1/* 2** 2001 September 15 3** 4** The author disclaims copyright to this source code. In place of 5** a legal notice, here is a blessing: 6** 7** May you do good and not evil. 8** May you find forgiveness for yourself and forgive others. 9** May you share freely, never taking more than you give. 10** 11************************************************************************* 12** This file contains code to implement the "sqlite" command line 13** utility for accessing SQLite databases. 14*/ 15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) 16/* This needs to come before any includes for MSVC compiler */ 17#define _CRT_SECURE_NO_WARNINGS 18#endif 19 20/* 21** Warning pragmas copied from msvc.h in the core. 22*/ 23#if defined(_MSC_VER) 24#pragma warning(disable : 4054) 25#pragma warning(disable : 4055) 26#pragma warning(disable : 4100) 27#pragma warning(disable : 4127) 28#pragma warning(disable : 4130) 29#pragma warning(disable : 4152) 30#pragma warning(disable : 4189) 31#pragma warning(disable : 4206) 32#pragma warning(disable : 4210) 33#pragma warning(disable : 4232) 34#pragma warning(disable : 4244) 35#pragma warning(disable : 4305) 36#pragma warning(disable : 4306) 37#pragma warning(disable : 4702) 38#pragma warning(disable : 4706) 39#endif /* defined(_MSC_VER) */ 40 41/* 42** No support for loadable extensions in VxWorks. 43*/ 44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION 45# define SQLITE_OMIT_LOAD_EXTENSION 1 46#endif 47 48/* 49** Enable large-file support for fopen() and friends on unix. 50*/ 51#ifndef SQLITE_DISABLE_LFS 52# define _LARGE_FILE 1 53# ifndef _FILE_OFFSET_BITS 54# define _FILE_OFFSET_BITS 64 55# endif 56# define _LARGEFILE_SOURCE 1 57#endif 58 59#include <stdlib.h> 60#include <string.h> 61#include <stdio.h> 62#include <assert.h> 63#include "sqlite3.h" 64typedef sqlite3_int64 i64; 65typedef sqlite3_uint64 u64; 66typedef unsigned char u8; 67#if SQLITE_USER_AUTHENTICATION 68# include "sqlite3userauth.h" 69#endif 70#include <ctype.h> 71#include <stdarg.h> 72 73#if !defined(_WIN32) && !defined(WIN32) 74# include <signal.h> 75# if !defined(__RTP__) && !defined(_WRS_KERNEL) 76# include <pwd.h> 77# endif 78#endif 79#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) 80# include <unistd.h> 81# include <dirent.h> 82# define GETPID getpid 83# if defined(__MINGW32__) 84# define DIRENT dirent 85# ifndef S_ISLNK 86# define S_ISLNK(mode) (0) 87# endif 88# endif 89#else 90# define GETPID (int)GetCurrentProcessId 91#endif 92#include <sys/types.h> 93#include <sys/stat.h> 94 95#if HAVE_READLINE 96# include <readline/readline.h> 97# include <readline/history.h> 98#endif 99 100#if HAVE_EDITLINE 101# include <editline/readline.h> 102#endif 103 104#if HAVE_EDITLINE || HAVE_READLINE 105 106# define shell_add_history(X) add_history(X) 107# define shell_read_history(X) read_history(X) 108# define shell_write_history(X) write_history(X) 109# define shell_stifle_history(X) stifle_history(X) 110# define shell_readline(X) readline(X) 111 112#elif HAVE_LINENOISE 113 114# include "linenoise.h" 115# define shell_add_history(X) linenoiseHistoryAdd(X) 116# define shell_read_history(X) linenoiseHistoryLoad(X) 117# define shell_write_history(X) linenoiseHistorySave(X) 118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) 119# define shell_readline(X) linenoise(X) 120 121#else 122 123# define shell_read_history(X) 124# define shell_write_history(X) 125# define shell_stifle_history(X) 126 127# define SHELL_USE_LOCAL_GETLINE 1 128#endif 129 130 131#if defined(_WIN32) || defined(WIN32) 132# include <io.h> 133# include <fcntl.h> 134# define isatty(h) _isatty(h) 135# ifndef access 136# define access(f,m) _access((f),(m)) 137# endif 138# ifndef unlink 139# define unlink _unlink 140# endif 141# ifndef strdup 142# define strdup _strdup 143# endif 144# undef popen 145# define popen _popen 146# undef pclose 147# define pclose _pclose 148#else 149 /* Make sure isatty() has a prototype. */ 150 extern int isatty(int); 151 152# if !defined(__RTP__) && !defined(_WRS_KERNEL) 153 /* popen and pclose are not C89 functions and so are 154 ** sometimes omitted from the <stdio.h> header */ 155 extern FILE *popen(const char*,const char*); 156 extern int pclose(FILE*); 157# else 158# define SQLITE_OMIT_POPEN 1 159# endif 160#endif 161 162#if defined(_WIN32_WCE) 163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() 164 * thus we always assume that we have a console. That can be 165 * overridden with the -batch command line option. 166 */ 167#define isatty(x) 1 168#endif 169 170/* ctype macros that work with signed characters */ 171#define IsSpace(X) isspace((unsigned char)X) 172#define IsDigit(X) isdigit((unsigned char)X) 173#define ToLower(X) (char)tolower((unsigned char)X) 174 175#if defined(_WIN32) || defined(WIN32) 176#include <windows.h> 177 178/* string conversion routines only needed on Win32 */ 179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); 180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); 181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); 182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); 183#endif 184 185/* On Windows, we normally run with output mode of TEXT so that \n characters 186** are automatically translated into \r\n. However, this behavior needs 187** to be disabled in some cases (ex: when generating CSV output and when 188** rendering quoted strings that contain \n characters). The following 189** routines take care of that. 190*/ 191#if defined(_WIN32) || defined(WIN32) 192static void setBinaryMode(FILE *file, int isOutput){ 193 if( isOutput ) fflush(file); 194 _setmode(_fileno(file), _O_BINARY); 195} 196static void setTextMode(FILE *file, int isOutput){ 197 if( isOutput ) fflush(file); 198 _setmode(_fileno(file), _O_TEXT); 199} 200#else 201# define setBinaryMode(X,Y) 202# define setTextMode(X,Y) 203#endif 204 205 206/* True if the timer is enabled */ 207static int enableTimer = 0; 208 209/* Return the current wall-clock time */ 210static sqlite3_int64 timeOfDay(void){ 211 static sqlite3_vfs *clockVfs = 0; 212 sqlite3_int64 t; 213 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); 214 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ 215 clockVfs->xCurrentTimeInt64(clockVfs, &t); 216 }else{ 217 double r; 218 clockVfs->xCurrentTime(clockVfs, &r); 219 t = (sqlite3_int64)(r*86400000.0); 220 } 221 return t; 222} 223 224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) 225#include <sys/time.h> 226#include <sys/resource.h> 227 228/* VxWorks does not support getrusage() as far as we can determine */ 229#if defined(_WRS_KERNEL) || defined(__RTP__) 230struct rusage { 231 struct timeval ru_utime; /* user CPU time used */ 232 struct timeval ru_stime; /* system CPU time used */ 233}; 234#define getrusage(A,B) memset(B,0,sizeof(*B)) 235#endif 236 237/* Saved resource information for the beginning of an operation */ 238static struct rusage sBegin; /* CPU time at start */ 239static sqlite3_int64 iBegin; /* Wall-clock time at start */ 240 241/* 242** Begin timing an operation 243*/ 244static void beginTimer(void){ 245 if( enableTimer ){ 246 getrusage(RUSAGE_SELF, &sBegin); 247 iBegin = timeOfDay(); 248 } 249} 250 251/* Return the difference of two time_structs in seconds */ 252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ 253 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 254 (double)(pEnd->tv_sec - pStart->tv_sec); 255} 256 257/* 258** Print the timing results. 259*/ 260static void endTimer(void){ 261 if( enableTimer ){ 262 sqlite3_int64 iEnd = timeOfDay(); 263 struct rusage sEnd; 264 getrusage(RUSAGE_SELF, &sEnd); 265 printf("Run Time: real %.3f user %f sys %f\n", 266 (iEnd - iBegin)*0.001, 267 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), 268 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); 269 } 270} 271 272#define BEGIN_TIMER beginTimer() 273#define END_TIMER endTimer() 274#define HAS_TIMER 1 275 276#elif (defined(_WIN32) || defined(WIN32)) 277 278/* Saved resource information for the beginning of an operation */ 279static HANDLE hProcess; 280static FILETIME ftKernelBegin; 281static FILETIME ftUserBegin; 282static sqlite3_int64 ftWallBegin; 283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, 284 LPFILETIME, LPFILETIME); 285static GETPROCTIMES getProcessTimesAddr = NULL; 286 287/* 288** Check to see if we have timer support. Return 1 if necessary 289** support found (or found previously). 290*/ 291static int hasTimer(void){ 292 if( getProcessTimesAddr ){ 293 return 1; 294 } else { 295 /* GetProcessTimes() isn't supported in WIN95 and some other Windows 296 ** versions. See if the version we are running on has it, and if it 297 ** does, save off a pointer to it and the current process handle. 298 */ 299 hProcess = GetCurrentProcess(); 300 if( hProcess ){ 301 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); 302 if( NULL != hinstLib ){ 303 getProcessTimesAddr = 304 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); 305 if( NULL != getProcessTimesAddr ){ 306 return 1; 307 } 308 FreeLibrary(hinstLib); 309 } 310 } 311 } 312 return 0; 313} 314 315/* 316** Begin timing an operation 317*/ 318static void beginTimer(void){ 319 if( enableTimer && getProcessTimesAddr ){ 320 FILETIME ftCreation, ftExit; 321 getProcessTimesAddr(hProcess,&ftCreation,&ftExit, 322 &ftKernelBegin,&ftUserBegin); 323 ftWallBegin = timeOfDay(); 324 } 325} 326 327/* Return the difference of two FILETIME structs in seconds */ 328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ 329 sqlite_int64 i64Start = *((sqlite_int64 *) pStart); 330 sqlite_int64 i64End = *((sqlite_int64 *) pEnd); 331 return (double) ((i64End - i64Start) / 10000000.0); 332} 333 334/* 335** Print the timing results. 336*/ 337static void endTimer(void){ 338 if( enableTimer && getProcessTimesAddr){ 339 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; 340 sqlite3_int64 ftWallEnd = timeOfDay(); 341 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); 342 printf("Run Time: real %.3f user %f sys %f\n", 343 (ftWallEnd - ftWallBegin)*0.001, 344 timeDiff(&ftUserBegin, &ftUserEnd), 345 timeDiff(&ftKernelBegin, &ftKernelEnd)); 346 } 347} 348 349#define BEGIN_TIMER beginTimer() 350#define END_TIMER endTimer() 351#define HAS_TIMER hasTimer() 352 353#else 354#define BEGIN_TIMER 355#define END_TIMER 356#define HAS_TIMER 0 357#endif 358 359/* 360** Used to prevent warnings about unused parameters 361*/ 362#define UNUSED_PARAMETER(x) (void)(x) 363 364/* 365** Number of elements in an array 366*/ 367#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) 368 369/* 370** If the following flag is set, then command execution stops 371** at an error if we are not interactive. 372*/ 373static int bail_on_error = 0; 374 375/* 376** Threat stdin as an interactive input if the following variable 377** is true. Otherwise, assume stdin is connected to a file or pipe. 378*/ 379static int stdin_is_interactive = 1; 380 381/* 382** On Windows systems we have to know if standard output is a console 383** in order to translate UTF-8 into MBCS. The following variable is 384** true if translation is required. 385*/ 386static int stdout_is_console = 1; 387 388/* 389** The following is the open SQLite database. We make a pointer 390** to this database a static variable so that it can be accessed 391** by the SIGINT handler to interrupt database processing. 392*/ 393static sqlite3 *globalDb = 0; 394 395/* 396** True if an interrupt (Control-C) has been received. 397*/ 398static volatile int seenInterrupt = 0; 399 400/* 401** This is the name of our program. It is set in main(), used 402** in a number of other places, mostly for error messages. 403*/ 404static char *Argv0; 405 406/* 407** Prompt strings. Initialized in main. Settable with 408** .prompt main continue 409*/ 410static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 411static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 412 413/* 414** Render output like fprintf(). Except, if the output is going to the 415** console and if this is running on a Windows machine, translate the 416** output from UTF-8 into MBCS. 417*/ 418#if defined(_WIN32) || defined(WIN32) 419void utf8_printf(FILE *out, const char *zFormat, ...){ 420 va_list ap; 421 va_start(ap, zFormat); 422 if( stdout_is_console && (out==stdout || out==stderr) ){ 423 char *z1 = sqlite3_vmprintf(zFormat, ap); 424 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 425 sqlite3_free(z1); 426 fputs(z2, out); 427 sqlite3_free(z2); 428 }else{ 429 vfprintf(out, zFormat, ap); 430 } 431 va_end(ap); 432} 433#elif !defined(utf8_printf) 434# define utf8_printf fprintf 435#endif 436 437/* 438** Render output like fprintf(). This should not be used on anything that 439** includes string formatting (e.g. "%s"). 440*/ 441#if !defined(raw_printf) 442# define raw_printf fprintf 443#endif 444 445/* Indicate out-of-memory and exit. */ 446static void shell_out_of_memory(void){ 447 raw_printf(stderr,"Error: out of memory\n"); 448 exit(1); 449} 450 451/* 452** Write I/O traces to the following stream. 453*/ 454#ifdef SQLITE_ENABLE_IOTRACE 455static FILE *iotrace = 0; 456#endif 457 458/* 459** This routine works like printf in that its first argument is a 460** format string and subsequent arguments are values to be substituted 461** in place of % fields. The result of formatting this string 462** is written to iotrace. 463*/ 464#ifdef SQLITE_ENABLE_IOTRACE 465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 466 va_list ap; 467 char *z; 468 if( iotrace==0 ) return; 469 va_start(ap, zFormat); 470 z = sqlite3_vmprintf(zFormat, ap); 471 va_end(ap); 472 utf8_printf(iotrace, "%s", z); 473 sqlite3_free(z); 474} 475#endif 476 477/* 478** Output string zUtf to stream pOut as w characters. If w is negative, 479** then right-justify the text. W is the width in UTF-8 characters, not 480** in bytes. This is different from the %*.*s specification in printf 481** since with %*.*s the width is measured in bytes, not characters. 482*/ 483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 484 int i; 485 int n; 486 int aw = w<0 ? -w : w; 487 char zBuf[1000]; 488 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3; 489 for(i=n=0; zUtf[i]; i++){ 490 if( (zUtf[i]&0xc0)!=0x80 ){ 491 n++; 492 if( n==aw ){ 493 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 494 break; 495 } 496 } 497 } 498 if( n>=aw ){ 499 utf8_printf(pOut, "%.*s", i, zUtf); 500 }else if( w<0 ){ 501 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 502 }else{ 503 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 504 } 505} 506 507 508/* 509** Determines if a string is a number of not. 510*/ 511static int isNumber(const char *z, int *realnum){ 512 if( *z=='-' || *z=='+' ) z++; 513 if( !IsDigit(*z) ){ 514 return 0; 515 } 516 z++; 517 if( realnum ) *realnum = 0; 518 while( IsDigit(*z) ){ z++; } 519 if( *z=='.' ){ 520 z++; 521 if( !IsDigit(*z) ) return 0; 522 while( IsDigit(*z) ){ z++; } 523 if( realnum ) *realnum = 1; 524 } 525 if( *z=='e' || *z=='E' ){ 526 z++; 527 if( *z=='+' || *z=='-' ) z++; 528 if( !IsDigit(*z) ) return 0; 529 while( IsDigit(*z) ){ z++; } 530 if( realnum ) *realnum = 1; 531 } 532 return *z==0; 533} 534 535/* 536** Compute a string length that is limited to what can be stored in 537** lower 30 bits of a 32-bit signed integer. 538*/ 539static int strlen30(const char *z){ 540 const char *z2 = z; 541 while( *z2 ){ z2++; } 542 return 0x3fffffff & (int)(z2 - z); 543} 544 545/* 546** Return the length of a string in characters. Multibyte UTF8 characters 547** count as a single character. 548*/ 549static int strlenChar(const char *z){ 550 int n = 0; 551 while( *z ){ 552 if( (0xc0&*(z++))!=0x80 ) n++; 553 } 554 return n; 555} 556 557/* 558** This routine reads a line of text from FILE in, stores 559** the text in memory obtained from malloc() and returns a pointer 560** to the text. NULL is returned at end of file, or if malloc() 561** fails. 562** 563** If zLine is not NULL then it is a malloced buffer returned from 564** a previous call to this routine that may be reused. 565*/ 566static char *local_getline(char *zLine, FILE *in){ 567 int nLine = zLine==0 ? 0 : 100; 568 int n = 0; 569 570 while( 1 ){ 571 if( n+100>nLine ){ 572 nLine = nLine*2 + 100; 573 zLine = realloc(zLine, nLine); 574 if( zLine==0 ) shell_out_of_memory(); 575 } 576 if( fgets(&zLine[n], nLine - n, in)==0 ){ 577 if( n==0 ){ 578 free(zLine); 579 return 0; 580 } 581 zLine[n] = 0; 582 break; 583 } 584 while( zLine[n] ) n++; 585 if( n>0 && zLine[n-1]=='\n' ){ 586 n--; 587 if( n>0 && zLine[n-1]=='\r' ) n--; 588 zLine[n] = 0; 589 break; 590 } 591 } 592#if defined(_WIN32) || defined(WIN32) 593 /* For interactive input on Windows systems, translate the 594 ** multi-byte characterset characters into UTF-8. */ 595 if( stdin_is_interactive && in==stdin ){ 596 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 597 if( zTrans ){ 598 int nTrans = strlen30(zTrans)+1; 599 if( nTrans>nLine ){ 600 zLine = realloc(zLine, nTrans); 601 if( zLine==0 ) shell_out_of_memory(); 602 } 603 memcpy(zLine, zTrans, nTrans); 604 sqlite3_free(zTrans); 605 } 606 } 607#endif /* defined(_WIN32) || defined(WIN32) */ 608 return zLine; 609} 610 611/* 612** Retrieve a single line of input text. 613** 614** If in==0 then read from standard input and prompt before each line. 615** If isContinuation is true, then a continuation prompt is appropriate. 616** If isContinuation is zero, then the main prompt should be used. 617** 618** If zPrior is not NULL then it is a buffer from a prior call to this 619** routine that can be reused. 620** 621** The result is stored in space obtained from malloc() and must either 622** be freed by the caller or else passed back into this routine via the 623** zPrior argument for reuse. 624*/ 625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 626 char *zPrompt; 627 char *zResult; 628 if( in!=0 ){ 629 zResult = local_getline(zPrior, in); 630 }else{ 631 zPrompt = isContinuation ? continuePrompt : mainPrompt; 632#if SHELL_USE_LOCAL_GETLINE 633 printf("%s", zPrompt); 634 fflush(stdout); 635 zResult = local_getline(zPrior, stdin); 636#else 637 free(zPrior); 638 zResult = shell_readline(zPrompt); 639 if( zResult && *zResult ) shell_add_history(zResult); 640#endif 641 } 642 return zResult; 643} 644 645 646/* 647** Return the value of a hexadecimal digit. Return -1 if the input 648** is not a hex digit. 649*/ 650static int hexDigitValue(char c){ 651 if( c>='0' && c<='9' ) return c - '0'; 652 if( c>='a' && c<='f' ) return c - 'a' + 10; 653 if( c>='A' && c<='F' ) return c - 'A' + 10; 654 return -1; 655} 656 657/* 658** Interpret zArg as an integer value, possibly with suffixes. 659*/ 660static sqlite3_int64 integerValue(const char *zArg){ 661 sqlite3_int64 v = 0; 662 static const struct { char *zSuffix; int iMult; } aMult[] = { 663 { "KiB", 1024 }, 664 { "MiB", 1024*1024 }, 665 { "GiB", 1024*1024*1024 }, 666 { "KB", 1000 }, 667 { "MB", 1000000 }, 668 { "GB", 1000000000 }, 669 { "K", 1000 }, 670 { "M", 1000000 }, 671 { "G", 1000000000 }, 672 }; 673 int i; 674 int isNeg = 0; 675 if( zArg[0]=='-' ){ 676 isNeg = 1; 677 zArg++; 678 }else if( zArg[0]=='+' ){ 679 zArg++; 680 } 681 if( zArg[0]=='0' && zArg[1]=='x' ){ 682 int x; 683 zArg += 2; 684 while( (x = hexDigitValue(zArg[0]))>=0 ){ 685 v = (v<<4) + x; 686 zArg++; 687 } 688 }else{ 689 while( IsDigit(zArg[0]) ){ 690 v = v*10 + zArg[0] - '0'; 691 zArg++; 692 } 693 } 694 for(i=0; i<ArraySize(aMult); i++){ 695 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 696 v *= aMult[i].iMult; 697 break; 698 } 699 } 700 return isNeg? -v : v; 701} 702 703/* 704** A variable length string to which one can append text. 705*/ 706typedef struct ShellText ShellText; 707struct ShellText { 708 char *z; 709 int n; 710 int nAlloc; 711}; 712 713/* 714** Initialize and destroy a ShellText object 715*/ 716static void initText(ShellText *p){ 717 memset(p, 0, sizeof(*p)); 718} 719static void freeText(ShellText *p){ 720 free(p->z); 721 initText(p); 722} 723 724/* zIn is either a pointer to a NULL-terminated string in memory obtained 725** from malloc(), or a NULL pointer. The string pointed to by zAppend is 726** added to zIn, and the result returned in memory obtained from malloc(). 727** zIn, if it was not NULL, is freed. 728** 729** If the third argument, quote, is not '\0', then it is used as a 730** quote character for zAppend. 731*/ 732static void appendText(ShellText *p, char const *zAppend, char quote){ 733 int len; 734 int i; 735 int nAppend = strlen30(zAppend); 736 737 len = nAppend+p->n+1; 738 if( quote ){ 739 len += 2; 740 for(i=0; i<nAppend; i++){ 741 if( zAppend[i]==quote ) len++; 742 } 743 } 744 745 if( p->n+len>=p->nAlloc ){ 746 p->nAlloc = p->nAlloc*2 + len + 20; 747 p->z = realloc(p->z, p->nAlloc); 748 if( p->z==0 ) shell_out_of_memory(); 749 } 750 751 if( quote ){ 752 char *zCsr = p->z+p->n; 753 *zCsr++ = quote; 754 for(i=0; i<nAppend; i++){ 755 *zCsr++ = zAppend[i]; 756 if( zAppend[i]==quote ) *zCsr++ = quote; 757 } 758 *zCsr++ = quote; 759 p->n = (int)(zCsr - p->z); 760 *zCsr = '\0'; 761 }else{ 762 memcpy(p->z+p->n, zAppend, nAppend); 763 p->n += nAppend; 764 p->z[p->n] = '\0'; 765 } 766} 767 768/* 769** Attempt to determine if identifier zName needs to be quoted, either 770** because it contains non-alphanumeric characters, or because it is an 771** SQLite keyword. Be conservative in this estimate: When in doubt assume 772** that quoting is required. 773** 774** Return '"' if quoting is required. Return 0 if no quoting is required. 775*/ 776static char quoteChar(const char *zName){ 777 int i; 778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 779 for(i=0; zName[i]; i++){ 780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 781 } 782 return sqlite3_keyword_check(zName, i) ? '"' : 0; 783} 784 785/* 786** Construct a fake object name and column list to describe the structure 787** of the view, virtual table, or table valued function zSchema.zName. 788*/ 789static char *shellFakeSchema( 790 sqlite3 *db, /* The database connection containing the vtab */ 791 const char *zSchema, /* Schema of the database holding the vtab */ 792 const char *zName /* The name of the virtual table */ 793){ 794 sqlite3_stmt *pStmt = 0; 795 char *zSql; 796 ShellText s; 797 char cQuote; 798 char *zDiv = "("; 799 int nRow = 0; 800 801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 802 zSchema ? zSchema : "main", zName); 803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 804 sqlite3_free(zSql); 805 initText(&s); 806 if( zSchema ){ 807 cQuote = quoteChar(zSchema); 808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 809 appendText(&s, zSchema, cQuote); 810 appendText(&s, ".", 0); 811 } 812 cQuote = quoteChar(zName); 813 appendText(&s, zName, cQuote); 814 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 816 nRow++; 817 appendText(&s, zDiv, 0); 818 zDiv = ","; 819 cQuote = quoteChar(zCol); 820 appendText(&s, zCol, cQuote); 821 } 822 appendText(&s, ")", 0); 823 sqlite3_finalize(pStmt); 824 if( nRow==0 ){ 825 freeText(&s); 826 s.z = 0; 827 } 828 return s.z; 829} 830 831/* 832** SQL function: shell_module_schema(X) 833** 834** Return a fake schema for the table-valued function or eponymous virtual 835** table X. 836*/ 837static void shellModuleSchema( 838 sqlite3_context *pCtx, 839 int nVal, 840 sqlite3_value **apVal 841){ 842 const char *zName = (const char*)sqlite3_value_text(apVal[0]); 843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); 844 UNUSED_PARAMETER(nVal); 845 if( zFake ){ 846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 847 -1, sqlite3_free); 848 free(zFake); 849 } 850} 851 852/* 853** SQL function: shell_add_schema(S,X) 854** 855** Add the schema name X to the CREATE statement in S and return the result. 856** Examples: 857** 858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 859** 860** Also works on 861** 862** CREATE INDEX 863** CREATE UNIQUE INDEX 864** CREATE VIEW 865** CREATE TRIGGER 866** CREATE VIRTUAL TABLE 867** 868** This UDF is used by the .schema command to insert the schema name of 869** attached databases into the middle of the sqlite_master.sql field. 870*/ 871static void shellAddSchemaName( 872 sqlite3_context *pCtx, 873 int nVal, 874 sqlite3_value **apVal 875){ 876 static const char *aPrefix[] = { 877 "TABLE", 878 "INDEX", 879 "UNIQUE INDEX", 880 "VIEW", 881 "TRIGGER", 882 "VIRTUAL TABLE" 883 }; 884 int i = 0; 885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 887 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 888 sqlite3 *db = sqlite3_context_db_handle(pCtx); 889 UNUSED_PARAMETER(nVal); 890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ 891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){ 892 int n = strlen30(aPrefix[i]); 893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 894 char *z = 0; 895 char *zFake = 0; 896 if( zSchema ){ 897 char cQuote = quoteChar(zSchema); 898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 900 }else{ 901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 902 } 903 } 904 if( zName 905 && aPrefix[i][0]=='V' 906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 907 ){ 908 if( z==0 ){ 909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 910 }else{ 911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 912 } 913 free(zFake); 914 } 915 if( z ){ 916 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 917 return; 918 } 919 } 920 } 921 } 922 sqlite3_result_value(pCtx, apVal[0]); 923} 924 925/* 926** The source code for several run-time loadable extensions is inserted 927** below by the ../tool/mkshellc.tcl script. Before processing that included 928** code, we need to override some macros to make the included program code 929** work here in the middle of this regular program. 930*/ 931#define SQLITE_EXTENSION_INIT1 932#define SQLITE_EXTENSION_INIT2(X) (void)(X) 933 934#if defined(_WIN32) && defined(_MSC_VER) 935INCLUDE test_windirent.h 936INCLUDE test_windirent.c 937#define dirent DIRENT 938#endif 939INCLUDE ../ext/misc/shathree.c 940INCLUDE ../ext/misc/fileio.c 941INCLUDE ../ext/misc/completion.c 942INCLUDE ../ext/misc/appendvfs.c 943INCLUDE ../ext/misc/memtrace.c 944#ifdef SQLITE_HAVE_ZLIB 945INCLUDE ../ext/misc/zipfile.c 946INCLUDE ../ext/misc/sqlar.c 947#endif 948INCLUDE ../ext/expert/sqlite3expert.h 949INCLUDE ../ext/expert/sqlite3expert.c 950 951#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 952INCLUDE ../ext/misc/dbdata.c 953#endif 954 955#if defined(SQLITE_ENABLE_SESSION) 956/* 957** State information for a single open session 958*/ 959typedef struct OpenSession OpenSession; 960struct OpenSession { 961 char *zName; /* Symbolic name for this session */ 962 int nFilter; /* Number of xFilter rejection GLOB patterns */ 963 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 964 sqlite3_session *p; /* The open session */ 965}; 966#endif 967 968/* 969** Shell output mode information from before ".explain on", 970** saved so that it can be restored by ".explain off" 971*/ 972typedef struct SavedModeInfo SavedModeInfo; 973struct SavedModeInfo { 974 int valid; /* Is there legit data in here? */ 975 int mode; /* Mode prior to ".explain on" */ 976 int showHeader; /* The ".header" setting prior to ".explain on" */ 977 int colWidth[100]; /* Column widths prior to ".explain on" */ 978}; 979 980typedef struct ExpertInfo ExpertInfo; 981struct ExpertInfo { 982 sqlite3expert *pExpert; 983 int bVerbose; 984}; 985 986/* A single line in the EQP output */ 987typedef struct EQPGraphRow EQPGraphRow; 988struct EQPGraphRow { 989 int iEqpId; /* ID for this row */ 990 int iParentId; /* ID of the parent row */ 991 EQPGraphRow *pNext; /* Next row in sequence */ 992 char zText[1]; /* Text to display for this row */ 993}; 994 995/* All EQP output is collected into an instance of the following */ 996typedef struct EQPGraph EQPGraph; 997struct EQPGraph { 998 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 999 EQPGraphRow *pLast; /* Last element of the pRow list */ 1000 char zPrefix[100]; /* Graph prefix */ 1001}; 1002 1003/* 1004** State information about the database connection is contained in an 1005** instance of the following structure. 1006*/ 1007typedef struct ShellState ShellState; 1008struct ShellState { 1009 sqlite3 *db; /* The database */ 1010 u8 autoExplain; /* Automatically turn on .explain mode */ 1011 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1012 u8 autoEQPtest; /* autoEQP is in test mode */ 1013 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1014 u8 statsOn; /* True to display memory stats before each finalize */ 1015 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1016 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1017 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1018 u8 nEqpLevel; /* Depth of the EQP output graph */ 1019 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1020 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1021 int outCount; /* Revert to stdout when reaching zero */ 1022 int cnt; /* Number of records displayed so far */ 1023 int lineno; /* Line number of last line read from in */ 1024 FILE *in; /* Read commands from this stream */ 1025 FILE *out; /* Write results here */ 1026 FILE *traceOut; /* Output for sqlite3_trace() */ 1027 int nErr; /* Number of errors seen */ 1028 int mode; /* An output mode setting */ 1029 int modePrior; /* Saved mode */ 1030 int cMode; /* temporary output mode for the current query */ 1031 int normalMode; /* Output mode before ".explain on" */ 1032 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1033 int showHeader; /* True to show column names in List or Column mode */ 1034 int nCheck; /* Number of ".check" commands run */ 1035 unsigned nProgress; /* Number of progress callbacks encountered */ 1036 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1037 unsigned flgProgress; /* Flags for the progress callback */ 1038 unsigned shellFlgs; /* Various flags */ 1039 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1040 char *zDestTable; /* Name of destination table when MODE_Insert */ 1041 char *zTempFile; /* Temporary file that might need deleting */ 1042 char zTestcase[30]; /* Name of current test case */ 1043 char colSeparator[20]; /* Column separator character for several modes */ 1044 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1045 char colSepPrior[20]; /* Saved column separator */ 1046 char rowSepPrior[20]; /* Saved row separator */ 1047 int colWidth[100]; /* Requested width of each column when in column mode*/ 1048 int actualWidth[100]; /* Actual width of each column */ 1049 char nullValue[20]; /* The text to print when a NULL comes back from 1050 ** the database */ 1051 char outfile[FILENAME_MAX]; /* Filename for *out */ 1052 const char *zDbFilename; /* name of the database file */ 1053 char *zFreeOnClose; /* Filename to free when closing */ 1054 const char *zVfs; /* Name of VFS to use */ 1055 sqlite3_stmt *pStmt; /* Current statement if any. */ 1056 FILE *pLog; /* Write log output here */ 1057 int *aiIndent; /* Array of indents used in MODE_Explain */ 1058 int nIndent; /* Size of array aiIndent[] */ 1059 int iIndent; /* Index of current op in aiIndent[] */ 1060 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1061#if defined(SQLITE_ENABLE_SESSION) 1062 int nSession; /* Number of active sessions */ 1063 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1064#endif 1065 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1066}; 1067 1068 1069/* Allowed values for ShellState.autoEQP 1070*/ 1071#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1072#define AUTOEQP_on 1 /* Automatic EQP is on */ 1073#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1074#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1075 1076/* Allowed values for ShellState.openMode 1077*/ 1078#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1079#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1080#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1081#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1082#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1083#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1084#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1085 1086/* Allowed values for ShellState.eTraceType 1087*/ 1088#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1089#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1090#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1091 1092/* Bits in the ShellState.flgProgress variable */ 1093#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1094#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1095 ** callback limit is reached, and for each 1096 ** top-level SQL statement */ 1097#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1098 1099/* 1100** These are the allowed shellFlgs values 1101*/ 1102#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1103#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1104#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1105#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1106#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1107#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1108#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1109 1110/* 1111** Macros for testing and setting shellFlgs 1112*/ 1113#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1114#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1115#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1116 1117/* 1118** These are the allowed modes. 1119*/ 1120#define MODE_Line 0 /* One column per line. Blank line between records */ 1121#define MODE_Column 1 /* One record per line in neat columns */ 1122#define MODE_List 2 /* One record per line with a separator */ 1123#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1124#define MODE_Html 4 /* Generate an XHTML table */ 1125#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1126#define MODE_Quote 6 /* Quote values as for SQL */ 1127#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1128#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1129#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1130#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1131#define MODE_Pretty 11 /* Pretty-print schemas */ 1132#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1133 1134static const char *modeDescr[] = { 1135 "line", 1136 "column", 1137 "list", 1138 "semi", 1139 "html", 1140 "insert", 1141 "quote", 1142 "tcl", 1143 "csv", 1144 "explain", 1145 "ascii", 1146 "prettyprint", 1147 "eqp" 1148}; 1149 1150/* 1151** These are the column/row/line separators used by the various 1152** import/export modes. 1153*/ 1154#define SEP_Column "|" 1155#define SEP_Row "\n" 1156#define SEP_Tab "\t" 1157#define SEP_Space " " 1158#define SEP_Comma "," 1159#define SEP_CrLf "\r\n" 1160#define SEP_Unit "\x1F" 1161#define SEP_Record "\x1E" 1162 1163/* 1164** A callback for the sqlite3_log() interface. 1165*/ 1166static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1167 ShellState *p = (ShellState*)pArg; 1168 if( p->pLog==0 ) return; 1169 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1170 fflush(p->pLog); 1171} 1172 1173/* 1174** SQL function: shell_putsnl(X) 1175** 1176** Write the text X to the screen (or whatever output is being directed) 1177** adding a newline at the end, and then return X. 1178*/ 1179static void shellPutsFunc( 1180 sqlite3_context *pCtx, 1181 int nVal, 1182 sqlite3_value **apVal 1183){ 1184 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1185 (void)nVal; 1186 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1187 sqlite3_result_value(pCtx, apVal[0]); 1188} 1189 1190/* 1191** SQL function: edit(VALUE) 1192** edit(VALUE,EDITOR) 1193** 1194** These steps: 1195** 1196** (1) Write VALUE into a temporary file. 1197** (2) Run program EDITOR on that temporary file. 1198** (3) Read the temporary file back and return its content as the result. 1199** (4) Delete the temporary file 1200** 1201** If the EDITOR argument is omitted, use the value in the VISUAL 1202** environment variable. If still there is no EDITOR, through an error. 1203** 1204** Also throw an error if the EDITOR program returns a non-zero exit code. 1205*/ 1206#ifndef SQLITE_NOHAVE_SYSTEM 1207static void editFunc( 1208 sqlite3_context *context, 1209 int argc, 1210 sqlite3_value **argv 1211){ 1212 const char *zEditor; 1213 char *zTempFile = 0; 1214 sqlite3 *db; 1215 char *zCmd = 0; 1216 int bBin; 1217 int rc; 1218 int hasCRNL = 0; 1219 FILE *f = 0; 1220 sqlite3_int64 sz; 1221 sqlite3_int64 x; 1222 unsigned char *p = 0; 1223 1224 if( argc==2 ){ 1225 zEditor = (const char*)sqlite3_value_text(argv[1]); 1226 }else{ 1227 zEditor = getenv("VISUAL"); 1228 } 1229 if( zEditor==0 ){ 1230 sqlite3_result_error(context, "no editor for edit()", -1); 1231 return; 1232 } 1233 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1234 sqlite3_result_error(context, "NULL input to edit()", -1); 1235 return; 1236 } 1237 db = sqlite3_context_db_handle(context); 1238 zTempFile = 0; 1239 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1240 if( zTempFile==0 ){ 1241 sqlite3_uint64 r = 0; 1242 sqlite3_randomness(sizeof(r), &r); 1243 zTempFile = sqlite3_mprintf("temp%llx", r); 1244 if( zTempFile==0 ){ 1245 sqlite3_result_error_nomem(context); 1246 return; 1247 } 1248 } 1249 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1250 /* When writing the file to be edited, do \n to \r\n conversions on systems 1251 ** that want \r\n line endings */ 1252 f = fopen(zTempFile, bBin ? "wb" : "w"); 1253 if( f==0 ){ 1254 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1255 goto edit_func_end; 1256 } 1257 sz = sqlite3_value_bytes(argv[0]); 1258 if( bBin ){ 1259 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); 1260 }else{ 1261 const char *z = (const char*)sqlite3_value_text(argv[0]); 1262 /* Remember whether or not the value originally contained \r\n */ 1263 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1264 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); 1265 } 1266 fclose(f); 1267 f = 0; 1268 if( x!=sz ){ 1269 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1270 goto edit_func_end; 1271 } 1272 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1273 if( zCmd==0 ){ 1274 sqlite3_result_error_nomem(context); 1275 goto edit_func_end; 1276 } 1277 rc = system(zCmd); 1278 sqlite3_free(zCmd); 1279 if( rc ){ 1280 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1281 goto edit_func_end; 1282 } 1283 f = fopen(zTempFile, "rb"); 1284 if( f==0 ){ 1285 sqlite3_result_error(context, 1286 "edit() cannot reopen temp file after edit", -1); 1287 goto edit_func_end; 1288 } 1289 fseek(f, 0, SEEK_END); 1290 sz = ftell(f); 1291 rewind(f); 1292 p = sqlite3_malloc64( sz+(bBin==0) ); 1293 if( p==0 ){ 1294 sqlite3_result_error_nomem(context); 1295 goto edit_func_end; 1296 } 1297 x = fread(p, 1, (size_t)sz, f); 1298 fclose(f); 1299 f = 0; 1300 if( x!=sz ){ 1301 sqlite3_result_error(context, "could not read back the whole file", -1); 1302 goto edit_func_end; 1303 } 1304 if( bBin ){ 1305 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1306 }else{ 1307 sqlite3_int64 i, j; 1308 if( hasCRNL ){ 1309 /* If the original contains \r\n then do no conversions back to \n */ 1310 j = sz; 1311 }else{ 1312 /* If the file did not originally contain \r\n then convert any new 1313 ** \r\n back into \n */ 1314 for(i=j=0; i<sz; i++){ 1315 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1316 p[j++] = p[i]; 1317 } 1318 sz = j; 1319 p[sz] = 0; 1320 } 1321 sqlite3_result_text64(context, (const char*)p, sz, 1322 sqlite3_free, SQLITE_UTF8); 1323 } 1324 p = 0; 1325 1326edit_func_end: 1327 if( f ) fclose(f); 1328 unlink(zTempFile); 1329 sqlite3_free(zTempFile); 1330 sqlite3_free(p); 1331} 1332#endif /* SQLITE_NOHAVE_SYSTEM */ 1333 1334/* 1335** Save or restore the current output mode 1336*/ 1337static void outputModePush(ShellState *p){ 1338 p->modePrior = p->mode; 1339 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1340 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1341} 1342static void outputModePop(ShellState *p){ 1343 p->mode = p->modePrior; 1344 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1345 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1346} 1347 1348/* 1349** Output the given string as a hex-encoded blob (eg. X'1234' ) 1350*/ 1351static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1352 int i; 1353 char *zBlob = (char *)pBlob; 1354 raw_printf(out,"X'"); 1355 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1356 raw_printf(out,"'"); 1357} 1358 1359/* 1360** Find a string that is not found anywhere in z[]. Return a pointer 1361** to that string. 1362** 1363** Try to use zA and zB first. If both of those are already found in z[] 1364** then make up some string and store it in the buffer zBuf. 1365*/ 1366static const char *unused_string( 1367 const char *z, /* Result must not appear anywhere in z */ 1368 const char *zA, const char *zB, /* Try these first */ 1369 char *zBuf /* Space to store a generated string */ 1370){ 1371 unsigned i = 0; 1372 if( strstr(z, zA)==0 ) return zA; 1373 if( strstr(z, zB)==0 ) return zB; 1374 do{ 1375 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1376 }while( strstr(z,zBuf)!=0 ); 1377 return zBuf; 1378} 1379 1380/* 1381** Output the given string as a quoted string using SQL quoting conventions. 1382** 1383** See also: output_quoted_escaped_string() 1384*/ 1385static void output_quoted_string(FILE *out, const char *z){ 1386 int i; 1387 char c; 1388 setBinaryMode(out, 1); 1389 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1390 if( c==0 ){ 1391 utf8_printf(out,"'%s'",z); 1392 }else{ 1393 raw_printf(out, "'"); 1394 while( *z ){ 1395 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1396 if( c=='\'' ) i++; 1397 if( i ){ 1398 utf8_printf(out, "%.*s", i, z); 1399 z += i; 1400 } 1401 if( c=='\'' ){ 1402 raw_printf(out, "'"); 1403 continue; 1404 } 1405 if( c==0 ){ 1406 break; 1407 } 1408 z++; 1409 } 1410 raw_printf(out, "'"); 1411 } 1412 setTextMode(out, 1); 1413} 1414 1415/* 1416** Output the given string as a quoted string using SQL quoting conventions. 1417** Additionallly , escape the "\n" and "\r" characters so that they do not 1418** get corrupted by end-of-line translation facilities in some operating 1419** systems. 1420** 1421** This is like output_quoted_string() but with the addition of the \r\n 1422** escape mechanism. 1423*/ 1424static void output_quoted_escaped_string(FILE *out, const char *z){ 1425 int i; 1426 char c; 1427 setBinaryMode(out, 1); 1428 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1429 if( c==0 ){ 1430 utf8_printf(out,"'%s'",z); 1431 }else{ 1432 const char *zNL = 0; 1433 const char *zCR = 0; 1434 int nNL = 0; 1435 int nCR = 0; 1436 char zBuf1[20], zBuf2[20]; 1437 for(i=0; z[i]; i++){ 1438 if( z[i]=='\n' ) nNL++; 1439 if( z[i]=='\r' ) nCR++; 1440 } 1441 if( nNL ){ 1442 raw_printf(out, "replace("); 1443 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1444 } 1445 if( nCR ){ 1446 raw_printf(out, "replace("); 1447 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1448 } 1449 raw_printf(out, "'"); 1450 while( *z ){ 1451 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1452 if( c=='\'' ) i++; 1453 if( i ){ 1454 utf8_printf(out, "%.*s", i, z); 1455 z += i; 1456 } 1457 if( c=='\'' ){ 1458 raw_printf(out, "'"); 1459 continue; 1460 } 1461 if( c==0 ){ 1462 break; 1463 } 1464 z++; 1465 if( c=='\n' ){ 1466 raw_printf(out, "%s", zNL); 1467 continue; 1468 } 1469 raw_printf(out, "%s", zCR); 1470 } 1471 raw_printf(out, "'"); 1472 if( nCR ){ 1473 raw_printf(out, ",'%s',char(13))", zCR); 1474 } 1475 if( nNL ){ 1476 raw_printf(out, ",'%s',char(10))", zNL); 1477 } 1478 } 1479 setTextMode(out, 1); 1480} 1481 1482/* 1483** Output the given string as a quoted according to C or TCL quoting rules. 1484*/ 1485static void output_c_string(FILE *out, const char *z){ 1486 unsigned int c; 1487 fputc('"', out); 1488 while( (c = *(z++))!=0 ){ 1489 if( c=='\\' ){ 1490 fputc(c, out); 1491 fputc(c, out); 1492 }else if( c=='"' ){ 1493 fputc('\\', out); 1494 fputc('"', out); 1495 }else if( c=='\t' ){ 1496 fputc('\\', out); 1497 fputc('t', out); 1498 }else if( c=='\n' ){ 1499 fputc('\\', out); 1500 fputc('n', out); 1501 }else if( c=='\r' ){ 1502 fputc('\\', out); 1503 fputc('r', out); 1504 }else if( !isprint(c&0xff) ){ 1505 raw_printf(out, "\\%03o", c&0xff); 1506 }else{ 1507 fputc(c, out); 1508 } 1509 } 1510 fputc('"', out); 1511} 1512 1513/* 1514** Output the given string with characters that are special to 1515** HTML escaped. 1516*/ 1517static void output_html_string(FILE *out, const char *z){ 1518 int i; 1519 if( z==0 ) z = ""; 1520 while( *z ){ 1521 for(i=0; z[i] 1522 && z[i]!='<' 1523 && z[i]!='&' 1524 && z[i]!='>' 1525 && z[i]!='\"' 1526 && z[i]!='\''; 1527 i++){} 1528 if( i>0 ){ 1529 utf8_printf(out,"%.*s",i,z); 1530 } 1531 if( z[i]=='<' ){ 1532 raw_printf(out,"<"); 1533 }else if( z[i]=='&' ){ 1534 raw_printf(out,"&"); 1535 }else if( z[i]=='>' ){ 1536 raw_printf(out,">"); 1537 }else if( z[i]=='\"' ){ 1538 raw_printf(out,"""); 1539 }else if( z[i]=='\'' ){ 1540 raw_printf(out,"'"); 1541 }else{ 1542 break; 1543 } 1544 z += i + 1; 1545 } 1546} 1547 1548/* 1549** If a field contains any character identified by a 1 in the following 1550** array, then the string must be quoted for CSV. 1551*/ 1552static const char needCsvQuote[] = { 1553 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1554 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1555 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1556 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1557 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1558 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1559 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1560 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1561 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1562 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1565 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1566 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1567 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1568 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1569}; 1570 1571/* 1572** Output a single term of CSV. Actually, p->colSeparator is used for 1573** the separator, which may or may not be a comma. p->nullValue is 1574** the null value. Strings are quoted if necessary. The separator 1575** is only issued if bSep is true. 1576*/ 1577static void output_csv(ShellState *p, const char *z, int bSep){ 1578 FILE *out = p->out; 1579 if( z==0 ){ 1580 utf8_printf(out,"%s",p->nullValue); 1581 }else{ 1582 int i; 1583 int nSep = strlen30(p->colSeparator); 1584 for(i=0; z[i]; i++){ 1585 if( needCsvQuote[((unsigned char*)z)[i]] 1586 || (z[i]==p->colSeparator[0] && 1587 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ 1588 i = 0; 1589 break; 1590 } 1591 } 1592 if( i==0 ){ 1593 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1594 utf8_printf(out, "%s", zQuoted); 1595 sqlite3_free(zQuoted); 1596 }else{ 1597 utf8_printf(out, "%s", z); 1598 } 1599 } 1600 if( bSep ){ 1601 utf8_printf(p->out, "%s", p->colSeparator); 1602 } 1603} 1604 1605/* 1606** This routine runs when the user presses Ctrl-C 1607*/ 1608static void interrupt_handler(int NotUsed){ 1609 UNUSED_PARAMETER(NotUsed); 1610 seenInterrupt++; 1611 if( seenInterrupt>2 ) exit(1); 1612 if( globalDb ) sqlite3_interrupt(globalDb); 1613} 1614 1615#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1616/* 1617** This routine runs for console events (e.g. Ctrl-C) on Win32 1618*/ 1619static BOOL WINAPI ConsoleCtrlHandler( 1620 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1621){ 1622 if( dwCtrlType==CTRL_C_EVENT ){ 1623 interrupt_handler(0); 1624 return TRUE; 1625 } 1626 return FALSE; 1627} 1628#endif 1629 1630#ifndef SQLITE_OMIT_AUTHORIZATION 1631/* 1632** When the ".auth ON" is set, the following authorizer callback is 1633** invoked. It always returns SQLITE_OK. 1634*/ 1635static int shellAuth( 1636 void *pClientData, 1637 int op, 1638 const char *zA1, 1639 const char *zA2, 1640 const char *zA3, 1641 const char *zA4 1642){ 1643 ShellState *p = (ShellState*)pClientData; 1644 static const char *azAction[] = { 0, 1645 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1646 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1647 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1648 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1649 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1650 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1651 "PRAGMA", "READ", "SELECT", 1652 "TRANSACTION", "UPDATE", "ATTACH", 1653 "DETACH", "ALTER_TABLE", "REINDEX", 1654 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1655 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1656 }; 1657 int i; 1658 const char *az[4]; 1659 az[0] = zA1; 1660 az[1] = zA2; 1661 az[2] = zA3; 1662 az[3] = zA4; 1663 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1664 for(i=0; i<4; i++){ 1665 raw_printf(p->out, " "); 1666 if( az[i] ){ 1667 output_c_string(p->out, az[i]); 1668 }else{ 1669 raw_printf(p->out, "NULL"); 1670 } 1671 } 1672 raw_printf(p->out, "\n"); 1673 return SQLITE_OK; 1674} 1675#endif 1676 1677/* 1678** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1679** 1680** This routine converts some CREATE TABLE statements for shadow tables 1681** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1682*/ 1683static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1684 if( z==0 ) return; 1685 if( zTail==0 ) return; 1686 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1687 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1688 }else{ 1689 utf8_printf(out, "%s%s", z, zTail); 1690 } 1691} 1692static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1693 char c = z[n]; 1694 z[n] = 0; 1695 printSchemaLine(out, z, zTail); 1696 z[n] = c; 1697} 1698 1699/* 1700** Return true if string z[] has nothing but whitespace and comments to the 1701** end of the first line. 1702*/ 1703static int wsToEol(const char *z){ 1704 int i; 1705 for(i=0; z[i]; i++){ 1706 if( z[i]=='\n' ) return 1; 1707 if( IsSpace(z[i]) ) continue; 1708 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1709 return 0; 1710 } 1711 return 1; 1712} 1713 1714/* 1715** Add a new entry to the EXPLAIN QUERY PLAN data 1716*/ 1717static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1718 EQPGraphRow *pNew; 1719 int nText = strlen30(zText); 1720 if( p->autoEQPtest ){ 1721 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1722 } 1723 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1724 if( pNew==0 ) shell_out_of_memory(); 1725 pNew->iEqpId = iEqpId; 1726 pNew->iParentId = p2; 1727 memcpy(pNew->zText, zText, nText+1); 1728 pNew->pNext = 0; 1729 if( p->sGraph.pLast ){ 1730 p->sGraph.pLast->pNext = pNew; 1731 }else{ 1732 p->sGraph.pRow = pNew; 1733 } 1734 p->sGraph.pLast = pNew; 1735} 1736 1737/* 1738** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1739** in p->sGraph. 1740*/ 1741static void eqp_reset(ShellState *p){ 1742 EQPGraphRow *pRow, *pNext; 1743 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1744 pNext = pRow->pNext; 1745 sqlite3_free(pRow); 1746 } 1747 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1748} 1749 1750/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1751** pOld, or return the first such line if pOld is NULL 1752*/ 1753static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1754 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1755 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1756 return pRow; 1757} 1758 1759/* Render a single level of the graph that has iEqpId as its parent. Called 1760** recursively to render sublevels. 1761*/ 1762static void eqp_render_level(ShellState *p, int iEqpId){ 1763 EQPGraphRow *pRow, *pNext; 1764 int n = strlen30(p->sGraph.zPrefix); 1765 char *z; 1766 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1767 pNext = eqp_next_row(p, iEqpId, pRow); 1768 z = pRow->zText; 1769 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z); 1770 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1771 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 1772 eqp_render_level(p, pRow->iEqpId); 1773 p->sGraph.zPrefix[n] = 0; 1774 } 1775 } 1776} 1777 1778/* 1779** Display and reset the EXPLAIN QUERY PLAN data 1780*/ 1781static void eqp_render(ShellState *p){ 1782 EQPGraphRow *pRow = p->sGraph.pRow; 1783 if( pRow ){ 1784 if( pRow->zText[0]=='-' ){ 1785 if( pRow->pNext==0 ){ 1786 eqp_reset(p); 1787 return; 1788 } 1789 utf8_printf(p->out, "%s\n", pRow->zText+3); 1790 p->sGraph.pRow = pRow->pNext; 1791 sqlite3_free(pRow); 1792 }else{ 1793 utf8_printf(p->out, "QUERY PLAN\n"); 1794 } 1795 p->sGraph.zPrefix[0] = 0; 1796 eqp_render_level(p, 0); 1797 eqp_reset(p); 1798 } 1799} 1800 1801#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1802/* 1803** Progress handler callback. 1804*/ 1805static int progress_handler(void *pClientData) { 1806 ShellState *p = (ShellState*)pClientData; 1807 p->nProgress++; 1808 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 1809 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 1810 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 1811 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 1812 return 1; 1813 } 1814 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 1815 raw_printf(p->out, "Progress %u\n", p->nProgress); 1816 } 1817 return 0; 1818} 1819#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 1820 1821/* 1822** This is the callback routine that the shell 1823** invokes for each row of a query result. 1824*/ 1825static int shell_callback( 1826 void *pArg, 1827 int nArg, /* Number of result columns */ 1828 char **azArg, /* Text of each result column */ 1829 char **azCol, /* Column names */ 1830 int *aiType /* Column types */ 1831){ 1832 int i; 1833 ShellState *p = (ShellState*)pArg; 1834 1835 if( azArg==0 ) return 0; 1836 switch( p->cMode ){ 1837 case MODE_Line: { 1838 int w = 5; 1839 if( azArg==0 ) break; 1840 for(i=0; i<nArg; i++){ 1841 int len = strlen30(azCol[i] ? azCol[i] : ""); 1842 if( len>w ) w = len; 1843 } 1844 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 1845 for(i=0; i<nArg; i++){ 1846 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 1847 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 1848 } 1849 break; 1850 } 1851 case MODE_Explain: 1852 case MODE_Column: { 1853 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13}; 1854 const int *colWidth; 1855 int showHdr; 1856 char *rowSep; 1857 if( p->cMode==MODE_Column ){ 1858 colWidth = p->colWidth; 1859 showHdr = p->showHeader; 1860 rowSep = p->rowSeparator; 1861 }else{ 1862 colWidth = aExplainWidths; 1863 showHdr = 1; 1864 rowSep = SEP_Row; 1865 } 1866 if( p->cnt++==0 ){ 1867 for(i=0; i<nArg; i++){ 1868 int w, n; 1869 if( i<ArraySize(p->colWidth) ){ 1870 w = colWidth[i]; 1871 }else{ 1872 w = 0; 1873 } 1874 if( w==0 ){ 1875 w = strlenChar(azCol[i] ? azCol[i] : ""); 1876 if( w<10 ) w = 10; 1877 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue); 1878 if( w<n ) w = n; 1879 } 1880 if( i<ArraySize(p->actualWidth) ){ 1881 p->actualWidth[i] = w; 1882 } 1883 if( showHdr ){ 1884 utf8_width_print(p->out, w, azCol[i]); 1885 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1886 } 1887 } 1888 if( showHdr ){ 1889 for(i=0; i<nArg; i++){ 1890 int w; 1891 if( i<ArraySize(p->actualWidth) ){ 1892 w = p->actualWidth[i]; 1893 if( w<0 ) w = -w; 1894 }else{ 1895 w = 10; 1896 } 1897 utf8_printf(p->out,"%-*.*s%s",w,w, 1898 "----------------------------------------------------------" 1899 "----------------------------------------------------------", 1900 i==nArg-1 ? rowSep : " "); 1901 } 1902 } 1903 } 1904 if( azArg==0 ) break; 1905 for(i=0; i<nArg; i++){ 1906 int w; 1907 if( i<ArraySize(p->actualWidth) ){ 1908 w = p->actualWidth[i]; 1909 }else{ 1910 w = 10; 1911 } 1912 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){ 1913 w = strlenChar(azArg[i]); 1914 } 1915 if( i==1 && p->aiIndent && p->pStmt ){ 1916 if( p->iIndent<p->nIndent ){ 1917 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 1918 } 1919 p->iIndent++; 1920 } 1921 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 1922 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1923 } 1924 break; 1925 } 1926 case MODE_Semi: { /* .schema and .fullschema output */ 1927 printSchemaLine(p->out, azArg[0], ";\n"); 1928 break; 1929 } 1930 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 1931 char *z; 1932 int j; 1933 int nParen = 0; 1934 char cEnd = 0; 1935 char c; 1936 int nLine = 0; 1937 assert( nArg==1 ); 1938 if( azArg[0]==0 ) break; 1939 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 1940 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 1941 ){ 1942 utf8_printf(p->out, "%s;\n", azArg[0]); 1943 break; 1944 } 1945 z = sqlite3_mprintf("%s", azArg[0]); 1946 j = 0; 1947 for(i=0; IsSpace(z[i]); i++){} 1948 for(; (c = z[i])!=0; i++){ 1949 if( IsSpace(c) ){ 1950 if( z[j-1]=='\r' ) z[j-1] = '\n'; 1951 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 1952 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 1953 j--; 1954 } 1955 z[j++] = c; 1956 } 1957 while( j>0 && IsSpace(z[j-1]) ){ j--; } 1958 z[j] = 0; 1959 if( strlen30(z)>=79 ){ 1960 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */ 1961 if( c==cEnd ){ 1962 cEnd = 0; 1963 }else if( c=='"' || c=='\'' || c=='`' ){ 1964 cEnd = c; 1965 }else if( c=='[' ){ 1966 cEnd = ']'; 1967 }else if( c=='-' && z[i+1]=='-' ){ 1968 cEnd = '\n'; 1969 }else if( c=='(' ){ 1970 nParen++; 1971 }else if( c==')' ){ 1972 nParen--; 1973 if( nLine>0 && nParen==0 && j>0 ){ 1974 printSchemaLineN(p->out, z, j, "\n"); 1975 j = 0; 1976 } 1977 } 1978 z[j++] = c; 1979 if( nParen==1 && cEnd==0 1980 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 1981 ){ 1982 if( c=='\n' ) j--; 1983 printSchemaLineN(p->out, z, j, "\n "); 1984 j = 0; 1985 nLine++; 1986 while( IsSpace(z[i+1]) ){ i++; } 1987 } 1988 } 1989 z[j] = 0; 1990 } 1991 printSchemaLine(p->out, z, ";\n"); 1992 sqlite3_free(z); 1993 break; 1994 } 1995 case MODE_List: { 1996 if( p->cnt++==0 && p->showHeader ){ 1997 for(i=0; i<nArg; i++){ 1998 utf8_printf(p->out,"%s%s",azCol[i], 1999 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2000 } 2001 } 2002 if( azArg==0 ) break; 2003 for(i=0; i<nArg; i++){ 2004 char *z = azArg[i]; 2005 if( z==0 ) z = p->nullValue; 2006 utf8_printf(p->out, "%s", z); 2007 if( i<nArg-1 ){ 2008 utf8_printf(p->out, "%s", p->colSeparator); 2009 }else{ 2010 utf8_printf(p->out, "%s", p->rowSeparator); 2011 } 2012 } 2013 break; 2014 } 2015 case MODE_Html: { 2016 if( p->cnt++==0 && p->showHeader ){ 2017 raw_printf(p->out,"<TR>"); 2018 for(i=0; i<nArg; i++){ 2019 raw_printf(p->out,"<TH>"); 2020 output_html_string(p->out, azCol[i]); 2021 raw_printf(p->out,"</TH>\n"); 2022 } 2023 raw_printf(p->out,"</TR>\n"); 2024 } 2025 if( azArg==0 ) break; 2026 raw_printf(p->out,"<TR>"); 2027 for(i=0; i<nArg; i++){ 2028 raw_printf(p->out,"<TD>"); 2029 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2030 raw_printf(p->out,"</TD>\n"); 2031 } 2032 raw_printf(p->out,"</TR>\n"); 2033 break; 2034 } 2035 case MODE_Tcl: { 2036 if( p->cnt++==0 && p->showHeader ){ 2037 for(i=0; i<nArg; i++){ 2038 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2039 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2040 } 2041 utf8_printf(p->out, "%s", p->rowSeparator); 2042 } 2043 if( azArg==0 ) break; 2044 for(i=0; i<nArg; i++){ 2045 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2046 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2047 } 2048 utf8_printf(p->out, "%s", p->rowSeparator); 2049 break; 2050 } 2051 case MODE_Csv: { 2052 setBinaryMode(p->out, 1); 2053 if( p->cnt++==0 && p->showHeader ){ 2054 for(i=0; i<nArg; i++){ 2055 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2056 } 2057 utf8_printf(p->out, "%s", p->rowSeparator); 2058 } 2059 if( nArg>0 ){ 2060 for(i=0; i<nArg; i++){ 2061 output_csv(p, azArg[i], i<nArg-1); 2062 } 2063 utf8_printf(p->out, "%s", p->rowSeparator); 2064 } 2065 setTextMode(p->out, 1); 2066 break; 2067 } 2068 case MODE_Insert: { 2069 if( azArg==0 ) break; 2070 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2071 if( p->showHeader ){ 2072 raw_printf(p->out,"("); 2073 for(i=0; i<nArg; i++){ 2074 if( i>0 ) raw_printf(p->out, ","); 2075 if( quoteChar(azCol[i]) ){ 2076 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2077 utf8_printf(p->out, "%s", z); 2078 sqlite3_free(z); 2079 }else{ 2080 raw_printf(p->out, "%s", azCol[i]); 2081 } 2082 } 2083 raw_printf(p->out,")"); 2084 } 2085 p->cnt++; 2086 for(i=0; i<nArg; i++){ 2087 raw_printf(p->out, i>0 ? "," : " VALUES("); 2088 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2089 utf8_printf(p->out,"NULL"); 2090 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2091 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2092 output_quoted_string(p->out, azArg[i]); 2093 }else{ 2094 output_quoted_escaped_string(p->out, azArg[i]); 2095 } 2096 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2097 utf8_printf(p->out,"%s", azArg[i]); 2098 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2099 char z[50]; 2100 double r = sqlite3_column_double(p->pStmt, i); 2101 sqlite3_uint64 ur; 2102 memcpy(&ur,&r,sizeof(r)); 2103 if( ur==0x7ff0000000000000LL ){ 2104 raw_printf(p->out, "1e999"); 2105 }else if( ur==0xfff0000000000000LL ){ 2106 raw_printf(p->out, "-1e999"); 2107 }else{ 2108 sqlite3_snprintf(50,z,"%!.20g", r); 2109 raw_printf(p->out, "%s", z); 2110 } 2111 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2112 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2113 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2114 output_hex_blob(p->out, pBlob, nBlob); 2115 }else if( isNumber(azArg[i], 0) ){ 2116 utf8_printf(p->out,"%s", azArg[i]); 2117 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2118 output_quoted_string(p->out, azArg[i]); 2119 }else{ 2120 output_quoted_escaped_string(p->out, azArg[i]); 2121 } 2122 } 2123 raw_printf(p->out,");\n"); 2124 break; 2125 } 2126 case MODE_Quote: { 2127 if( azArg==0 ) break; 2128 if( p->cnt==0 && p->showHeader ){ 2129 for(i=0; i<nArg; i++){ 2130 if( i>0 ) raw_printf(p->out, ","); 2131 output_quoted_string(p->out, azCol[i]); 2132 } 2133 raw_printf(p->out,"\n"); 2134 } 2135 p->cnt++; 2136 for(i=0; i<nArg; i++){ 2137 if( i>0 ) raw_printf(p->out, ","); 2138 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2139 utf8_printf(p->out,"NULL"); 2140 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2141 output_quoted_string(p->out, azArg[i]); 2142 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2143 utf8_printf(p->out,"%s", azArg[i]); 2144 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2145 char z[50]; 2146 double r = sqlite3_column_double(p->pStmt, i); 2147 sqlite3_snprintf(50,z,"%!.20g", r); 2148 raw_printf(p->out, "%s", z); 2149 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2150 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2151 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2152 output_hex_blob(p->out, pBlob, nBlob); 2153 }else if( isNumber(azArg[i], 0) ){ 2154 utf8_printf(p->out,"%s", azArg[i]); 2155 }else{ 2156 output_quoted_string(p->out, azArg[i]); 2157 } 2158 } 2159 raw_printf(p->out,"\n"); 2160 break; 2161 } 2162 case MODE_Ascii: { 2163 if( p->cnt++==0 && p->showHeader ){ 2164 for(i=0; i<nArg; i++){ 2165 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2166 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2167 } 2168 utf8_printf(p->out, "%s", p->rowSeparator); 2169 } 2170 if( azArg==0 ) break; 2171 for(i=0; i<nArg; i++){ 2172 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2173 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2174 } 2175 utf8_printf(p->out, "%s", p->rowSeparator); 2176 break; 2177 } 2178 case MODE_EQP: { 2179 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2180 break; 2181 } 2182 } 2183 return 0; 2184} 2185 2186/* 2187** This is the callback routine that the SQLite library 2188** invokes for each row of a query result. 2189*/ 2190static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2191 /* since we don't have type info, call the shell_callback with a NULL value */ 2192 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2193} 2194 2195/* 2196** This is the callback routine from sqlite3_exec() that appends all 2197** output onto the end of a ShellText object. 2198*/ 2199static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2200 ShellText *p = (ShellText*)pArg; 2201 int i; 2202 UNUSED_PARAMETER(az); 2203 if( azArg==0 ) return 0; 2204 if( p->n ) appendText(p, "|", 0); 2205 for(i=0; i<nArg; i++){ 2206 if( i ) appendText(p, ",", 0); 2207 if( azArg[i] ) appendText(p, azArg[i], 0); 2208 } 2209 return 0; 2210} 2211 2212/* 2213** Generate an appropriate SELFTEST table in the main database. 2214*/ 2215static void createSelftestTable(ShellState *p){ 2216 char *zErrMsg = 0; 2217 sqlite3_exec(p->db, 2218 "SAVEPOINT selftest_init;\n" 2219 "CREATE TABLE IF NOT EXISTS selftest(\n" 2220 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2221 " op TEXT,\n" /* Operator: memo run */ 2222 " cmd TEXT,\n" /* Command text */ 2223 " ans TEXT\n" /* Desired answer */ 2224 ");" 2225 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2226 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2227 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2228 " 'memo','Tests generated by --init');\n" 2229 "INSERT INTO [_shell$self]\n" 2230 " SELECT 'run',\n" 2231 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2232 "FROM sqlite_master ORDER BY 2'',224))',\n" 2233 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2234 "FROM sqlite_master ORDER BY 2',224));\n" 2235 "INSERT INTO [_shell$self]\n" 2236 " SELECT 'run'," 2237 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2238 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2239 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2240 " FROM (\n" 2241 " SELECT name FROM sqlite_master\n" 2242 " WHERE type='table'\n" 2243 " AND name<>'selftest'\n" 2244 " AND coalesce(rootpage,0)>0\n" 2245 " )\n" 2246 " ORDER BY name;\n" 2247 "INSERT INTO [_shell$self]\n" 2248 " VALUES('run','PRAGMA integrity_check','ok');\n" 2249 "INSERT INTO selftest(tno,op,cmd,ans)" 2250 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2251 "DROP TABLE [_shell$self];" 2252 ,0,0,&zErrMsg); 2253 if( zErrMsg ){ 2254 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2255 sqlite3_free(zErrMsg); 2256 } 2257 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2258} 2259 2260 2261/* 2262** Set the destination table field of the ShellState structure to 2263** the name of the table given. Escape any quote characters in the 2264** table name. 2265*/ 2266static void set_table_name(ShellState *p, const char *zName){ 2267 int i, n; 2268 char cQuote; 2269 char *z; 2270 2271 if( p->zDestTable ){ 2272 free(p->zDestTable); 2273 p->zDestTable = 0; 2274 } 2275 if( zName==0 ) return; 2276 cQuote = quoteChar(zName); 2277 n = strlen30(zName); 2278 if( cQuote ) n += n+2; 2279 z = p->zDestTable = malloc( n+1 ); 2280 if( z==0 ) shell_out_of_memory(); 2281 n = 0; 2282 if( cQuote ) z[n++] = cQuote; 2283 for(i=0; zName[i]; i++){ 2284 z[n++] = zName[i]; 2285 if( zName[i]==cQuote ) z[n++] = cQuote; 2286 } 2287 if( cQuote ) z[n++] = cQuote; 2288 z[n] = 0; 2289} 2290 2291 2292/* 2293** Execute a query statement that will generate SQL output. Print 2294** the result columns, comma-separated, on a line and then add a 2295** semicolon terminator to the end of that line. 2296** 2297** If the number of columns is 1 and that column contains text "--" 2298** then write the semicolon on a separate line. That way, if a 2299** "--" comment occurs at the end of the statement, the comment 2300** won't consume the semicolon terminator. 2301*/ 2302static int run_table_dump_query( 2303 ShellState *p, /* Query context */ 2304 const char *zSelect, /* SELECT statement to extract content */ 2305 const char *zFirstRow /* Print before first row, if not NULL */ 2306){ 2307 sqlite3_stmt *pSelect; 2308 int rc; 2309 int nResult; 2310 int i; 2311 const char *z; 2312 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2313 if( rc!=SQLITE_OK || !pSelect ){ 2314 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2315 sqlite3_errmsg(p->db)); 2316 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2317 return rc; 2318 } 2319 rc = sqlite3_step(pSelect); 2320 nResult = sqlite3_column_count(pSelect); 2321 while( rc==SQLITE_ROW ){ 2322 if( zFirstRow ){ 2323 utf8_printf(p->out, "%s", zFirstRow); 2324 zFirstRow = 0; 2325 } 2326 z = (const char*)sqlite3_column_text(pSelect, 0); 2327 utf8_printf(p->out, "%s", z); 2328 for(i=1; i<nResult; i++){ 2329 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2330 } 2331 if( z==0 ) z = ""; 2332 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2333 if( z[0] ){ 2334 raw_printf(p->out, "\n;\n"); 2335 }else{ 2336 raw_printf(p->out, ";\n"); 2337 } 2338 rc = sqlite3_step(pSelect); 2339 } 2340 rc = sqlite3_finalize(pSelect); 2341 if( rc!=SQLITE_OK ){ 2342 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2343 sqlite3_errmsg(p->db)); 2344 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2345 } 2346 return rc; 2347} 2348 2349/* 2350** Allocate space and save off current error string. 2351*/ 2352static char *save_err_msg( 2353 sqlite3 *db /* Database to query */ 2354){ 2355 int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); 2356 char *zErrMsg = sqlite3_malloc64(nErrMsg); 2357 if( zErrMsg ){ 2358 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); 2359 } 2360 return zErrMsg; 2361} 2362 2363#ifdef __linux__ 2364/* 2365** Attempt to display I/O stats on Linux using /proc/PID/io 2366*/ 2367static void displayLinuxIoStats(FILE *out){ 2368 FILE *in; 2369 char z[200]; 2370 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2371 in = fopen(z, "rb"); 2372 if( in==0 ) return; 2373 while( fgets(z, sizeof(z), in)!=0 ){ 2374 static const struct { 2375 const char *zPattern; 2376 const char *zDesc; 2377 } aTrans[] = { 2378 { "rchar: ", "Bytes received by read():" }, 2379 { "wchar: ", "Bytes sent to write():" }, 2380 { "syscr: ", "Read() system calls:" }, 2381 { "syscw: ", "Write() system calls:" }, 2382 { "read_bytes: ", "Bytes read from storage:" }, 2383 { "write_bytes: ", "Bytes written to storage:" }, 2384 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2385 }; 2386 int i; 2387 for(i=0; i<ArraySize(aTrans); i++){ 2388 int n = strlen30(aTrans[i].zPattern); 2389 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2390 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2391 break; 2392 } 2393 } 2394 } 2395 fclose(in); 2396} 2397#endif 2398 2399/* 2400** Display a single line of status using 64-bit values. 2401*/ 2402static void displayStatLine( 2403 ShellState *p, /* The shell context */ 2404 char *zLabel, /* Label for this one line */ 2405 char *zFormat, /* Format for the result */ 2406 int iStatusCtrl, /* Which status to display */ 2407 int bReset /* True to reset the stats */ 2408){ 2409 sqlite3_int64 iCur = -1; 2410 sqlite3_int64 iHiwtr = -1; 2411 int i, nPercent; 2412 char zLine[200]; 2413 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2414 for(i=0, nPercent=0; zFormat[i]; i++){ 2415 if( zFormat[i]=='%' ) nPercent++; 2416 } 2417 if( nPercent>1 ){ 2418 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2419 }else{ 2420 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2421 } 2422 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2423} 2424 2425/* 2426** Display memory stats. 2427*/ 2428static int display_stats( 2429 sqlite3 *db, /* Database to query */ 2430 ShellState *pArg, /* Pointer to ShellState */ 2431 int bReset /* True to reset the stats */ 2432){ 2433 int iCur; 2434 int iHiwtr; 2435 FILE *out; 2436 if( pArg==0 || pArg->out==0 ) return 0; 2437 out = pArg->out; 2438 2439 if( pArg->pStmt && (pArg->statsOn & 2) ){ 2440 int nCol, i, x; 2441 sqlite3_stmt *pStmt = pArg->pStmt; 2442 char z[100]; 2443 nCol = sqlite3_column_count(pStmt); 2444 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2445 for(i=0; i<nCol; i++){ 2446 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2447 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2448#ifndef SQLITE_OMIT_DECLTYPE 2449 sqlite3_snprintf(30, z+x, "declared type:"); 2450 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2451#endif 2452#ifdef SQLITE_ENABLE_COLUMN_METADATA 2453 sqlite3_snprintf(30, z+x, "database name:"); 2454 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2455 sqlite3_snprintf(30, z+x, "table name:"); 2456 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2457 sqlite3_snprintf(30, z+x, "origin name:"); 2458 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2459#endif 2460 } 2461 } 2462 2463 displayStatLine(pArg, "Memory Used:", 2464 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2465 displayStatLine(pArg, "Number of Outstanding Allocations:", 2466 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2467 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2468 displayStatLine(pArg, "Number of Pcache Pages Used:", 2469 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2470 } 2471 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2472 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2473 displayStatLine(pArg, "Largest Allocation:", 2474 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2475 displayStatLine(pArg, "Largest Pcache Allocation:", 2476 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2477#ifdef YYTRACKMAXSTACKDEPTH 2478 displayStatLine(pArg, "Deepest Parser Stack:", 2479 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2480#endif 2481 2482 if( db ){ 2483 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2484 iHiwtr = iCur = -1; 2485 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2486 &iCur, &iHiwtr, bReset); 2487 raw_printf(pArg->out, 2488 "Lookaside Slots Used: %d (max %d)\n", 2489 iCur, iHiwtr); 2490 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2491 &iCur, &iHiwtr, bReset); 2492 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2493 iHiwtr); 2494 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2495 &iCur, &iHiwtr, bReset); 2496 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2497 iHiwtr); 2498 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2499 &iCur, &iHiwtr, bReset); 2500 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2501 iHiwtr); 2502 } 2503 iHiwtr = iCur = -1; 2504 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2505 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2506 iCur); 2507 iHiwtr = iCur = -1; 2508 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2509 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2510 iHiwtr = iCur = -1; 2511 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2512 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2513 iHiwtr = iCur = -1; 2514 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2515 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2516 iHiwtr = iCur = -1; 2517 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2518 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2519 iHiwtr = iCur = -1; 2520 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2521 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2522 iCur); 2523 iHiwtr = iCur = -1; 2524 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2525 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2526 iCur); 2527 } 2528 2529 if( pArg->pStmt ){ 2530 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2531 bReset); 2532 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2533 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2534 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2535 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2536 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2537 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2538 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2539 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset); 2540 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2541 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2542 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2543 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2544 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2545 } 2546 2547#ifdef __linux__ 2548 displayLinuxIoStats(pArg->out); 2549#endif 2550 2551 /* Do not remove this machine readable comment: extra-stats-output-here */ 2552 2553 return 0; 2554} 2555 2556/* 2557** Display scan stats. 2558*/ 2559static void display_scanstats( 2560 sqlite3 *db, /* Database to query */ 2561 ShellState *pArg /* Pointer to ShellState */ 2562){ 2563#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2564 UNUSED_PARAMETER(db); 2565 UNUSED_PARAMETER(pArg); 2566#else 2567 int i, k, n, mx; 2568 raw_printf(pArg->out, "-------- scanstats --------\n"); 2569 mx = 0; 2570 for(k=0; k<=mx; k++){ 2571 double rEstLoop = 1.0; 2572 for(i=n=0; 1; i++){ 2573 sqlite3_stmt *p = pArg->pStmt; 2574 sqlite3_int64 nLoop, nVisit; 2575 double rEst; 2576 int iSid; 2577 const char *zExplain; 2578 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2579 break; 2580 } 2581 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2582 if( iSid>mx ) mx = iSid; 2583 if( iSid!=k ) continue; 2584 if( n==0 ){ 2585 rEstLoop = (double)nLoop; 2586 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2587 } 2588 n++; 2589 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2590 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2591 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2592 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2593 rEstLoop *= rEst; 2594 raw_printf(pArg->out, 2595 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2596 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2597 ); 2598 } 2599 } 2600 raw_printf(pArg->out, "---------------------------\n"); 2601#endif 2602} 2603 2604/* 2605** Parameter azArray points to a zero-terminated array of strings. zStr 2606** points to a single nul-terminated string. Return non-zero if zStr 2607** is equal, according to strcmp(), to any of the strings in the array. 2608** Otherwise, return zero. 2609*/ 2610static int str_in_array(const char *zStr, const char **azArray){ 2611 int i; 2612 for(i=0; azArray[i]; i++){ 2613 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2614 } 2615 return 0; 2616} 2617 2618/* 2619** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2620** and populate the ShellState.aiIndent[] array with the number of 2621** spaces each opcode should be indented before it is output. 2622** 2623** The indenting rules are: 2624** 2625** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2626** all opcodes that occur between the p2 jump destination and the opcode 2627** itself by 2 spaces. 2628** 2629** * For each "Goto", if the jump destination is earlier in the program 2630** and ends on one of: 2631** Yield SeekGt SeekLt RowSetRead Rewind 2632** or if the P1 parameter is one instead of zero, 2633** then indent all opcodes between the earlier instruction 2634** and "Goto" by 2 spaces. 2635*/ 2636static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2637 const char *zSql; /* The text of the SQL statement */ 2638 const char *z; /* Used to check if this is an EXPLAIN */ 2639 int *abYield = 0; /* True if op is an OP_Yield */ 2640 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2641 int iOp; /* Index of operation in p->aiIndent[] */ 2642 2643 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2644 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2645 "Rewind", 0 }; 2646 const char *azGoto[] = { "Goto", 0 }; 2647 2648 /* Try to figure out if this is really an EXPLAIN statement. If this 2649 ** cannot be verified, return early. */ 2650 if( sqlite3_column_count(pSql)!=8 ){ 2651 p->cMode = p->mode; 2652 return; 2653 } 2654 zSql = sqlite3_sql(pSql); 2655 if( zSql==0 ) return; 2656 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2657 if( sqlite3_strnicmp(z, "explain", 7) ){ 2658 p->cMode = p->mode; 2659 return; 2660 } 2661 2662 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2663 int i; 2664 int iAddr = sqlite3_column_int(pSql, 0); 2665 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2666 2667 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2668 ** p2 is an instruction address, set variable p2op to the index of that 2669 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2670 ** the current instruction is part of a sub-program generated by an 2671 ** SQL trigger or foreign key. */ 2672 int p2 = sqlite3_column_int(pSql, 3); 2673 int p2op = (p2 + (iOp-iAddr)); 2674 2675 /* Grow the p->aiIndent array as required */ 2676 if( iOp>=nAlloc ){ 2677 if( iOp==0 ){ 2678 /* Do further verfication that this is explain output. Abort if 2679 ** it is not */ 2680 static const char *explainCols[] = { 2681 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2682 int jj; 2683 for(jj=0; jj<ArraySize(explainCols); jj++){ 2684 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2685 p->cMode = p->mode; 2686 sqlite3_reset(pSql); 2687 return; 2688 } 2689 } 2690 } 2691 nAlloc += 100; 2692 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2693 if( p->aiIndent==0 ) shell_out_of_memory(); 2694 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2695 if( abYield==0 ) shell_out_of_memory(); 2696 } 2697 abYield[iOp] = str_in_array(zOp, azYield); 2698 p->aiIndent[iOp] = 0; 2699 p->nIndent = iOp+1; 2700 2701 if( str_in_array(zOp, azNext) ){ 2702 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2703 } 2704 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 2705 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 2706 ){ 2707 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2708 } 2709 } 2710 2711 p->iIndent = 0; 2712 sqlite3_free(abYield); 2713 sqlite3_reset(pSql); 2714} 2715 2716/* 2717** Free the array allocated by explain_data_prepare(). 2718*/ 2719static void explain_data_delete(ShellState *p){ 2720 sqlite3_free(p->aiIndent); 2721 p->aiIndent = 0; 2722 p->nIndent = 0; 2723 p->iIndent = 0; 2724} 2725 2726/* 2727** Disable and restore .wheretrace and .selecttrace settings. 2728*/ 2729#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2730extern int sqlite3SelectTrace; 2731static int savedSelectTrace; 2732#endif 2733#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2734extern int sqlite3WhereTrace; 2735static int savedWhereTrace; 2736#endif 2737static void disable_debug_trace_modes(void){ 2738#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2739 savedSelectTrace = sqlite3SelectTrace; 2740 sqlite3SelectTrace = 0; 2741#endif 2742#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2743 savedWhereTrace = sqlite3WhereTrace; 2744 sqlite3WhereTrace = 0; 2745#endif 2746} 2747static void restore_debug_trace_modes(void){ 2748#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2749 sqlite3SelectTrace = savedSelectTrace; 2750#endif 2751#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2752 sqlite3WhereTrace = savedWhereTrace; 2753#endif 2754} 2755 2756/* Create the TEMP table used to store parameter bindings */ 2757static void bind_table_init(ShellState *p){ 2758 int wrSchema = 0; 2759 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 2760 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 2761 sqlite3_exec(p->db, 2762 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 2763 " key TEXT PRIMARY KEY,\n" 2764 " value ANY\n" 2765 ") WITHOUT ROWID;", 2766 0, 0, 0); 2767 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 2768} 2769 2770/* 2771** Bind parameters on a prepared statement. 2772** 2773** Parameter bindings are taken from a TEMP table of the form: 2774** 2775** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 2776** WITHOUT ROWID; 2777** 2778** No bindings occur if this table does not exist. The special character '$' 2779** is included in the table name to help prevent collisions with actual tables. 2780** The table must be in the TEMP schema. 2781*/ 2782static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 2783 int nVar; 2784 int i; 2785 int rc; 2786 sqlite3_stmt *pQ = 0; 2787 2788 nVar = sqlite3_bind_parameter_count(pStmt); 2789 if( nVar==0 ) return; /* Nothing to do */ 2790 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 2791 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 2792 return; /* Parameter table does not exist */ 2793 } 2794 rc = sqlite3_prepare_v2(pArg->db, 2795 "SELECT value FROM temp.sqlite_parameters" 2796 " WHERE key=?1", -1, &pQ, 0); 2797 if( rc || pQ==0 ) return; 2798 for(i=1; i<=nVar; i++){ 2799 char zNum[30]; 2800 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 2801 if( zVar==0 ){ 2802 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 2803 zVar = zNum; 2804 } 2805 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 2806 if( sqlite3_step(pQ)==SQLITE_ROW ){ 2807 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 2808 }else{ 2809 sqlite3_bind_null(pStmt, i); 2810 } 2811 sqlite3_reset(pQ); 2812 } 2813 sqlite3_finalize(pQ); 2814} 2815 2816/* 2817** Run a prepared statement 2818*/ 2819static void exec_prepared_stmt( 2820 ShellState *pArg, /* Pointer to ShellState */ 2821 sqlite3_stmt *pStmt /* Statment to run */ 2822){ 2823 int rc; 2824 2825 /* perform the first step. this will tell us if we 2826 ** have a result set or not and how wide it is. 2827 */ 2828 rc = sqlite3_step(pStmt); 2829 /* if we have a result set... */ 2830 if( SQLITE_ROW == rc ){ 2831 /* allocate space for col name ptr, value ptr, and type */ 2832 int nCol = sqlite3_column_count(pStmt); 2833 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 2834 if( !pData ){ 2835 rc = SQLITE_NOMEM; 2836 }else{ 2837 char **azCols = (char **)pData; /* Names of result columns */ 2838 char **azVals = &azCols[nCol]; /* Results */ 2839 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 2840 int i, x; 2841 assert(sizeof(int) <= sizeof(char *)); 2842 /* save off ptrs to column names */ 2843 for(i=0; i<nCol; i++){ 2844 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 2845 } 2846 do{ 2847 /* extract the data and data types */ 2848 for(i=0; i<nCol; i++){ 2849 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 2850 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ 2851 azVals[i] = ""; 2852 }else{ 2853 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 2854 } 2855 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 2856 rc = SQLITE_NOMEM; 2857 break; /* from for */ 2858 } 2859 } /* end for */ 2860 2861 /* if data and types extracted successfully... */ 2862 if( SQLITE_ROW == rc ){ 2863 /* call the supplied callback with the result row data */ 2864 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 2865 rc = SQLITE_ABORT; 2866 }else{ 2867 rc = sqlite3_step(pStmt); 2868 } 2869 } 2870 } while( SQLITE_ROW == rc ); 2871 sqlite3_free(pData); 2872 } 2873 } 2874} 2875 2876#ifndef SQLITE_OMIT_VIRTUALTABLE 2877/* 2878** This function is called to process SQL if the previous shell command 2879** was ".expert". It passes the SQL in the second argument directly to 2880** the sqlite3expert object. 2881** 2882** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2883** code. In this case, (*pzErr) may be set to point to a buffer containing 2884** an English language error message. It is the responsibility of the 2885** caller to eventually free this buffer using sqlite3_free(). 2886*/ 2887static int expertHandleSQL( 2888 ShellState *pState, 2889 const char *zSql, 2890 char **pzErr 2891){ 2892 assert( pState->expert.pExpert ); 2893 assert( pzErr==0 || *pzErr==0 ); 2894 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 2895} 2896 2897/* 2898** This function is called either to silently clean up the object 2899** created by the ".expert" command (if bCancel==1), or to generate a 2900** report from it and then clean it up (if bCancel==0). 2901** 2902** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2903** code. In this case, (*pzErr) may be set to point to a buffer containing 2904** an English language error message. It is the responsibility of the 2905** caller to eventually free this buffer using sqlite3_free(). 2906*/ 2907static int expertFinish( 2908 ShellState *pState, 2909 int bCancel, 2910 char **pzErr 2911){ 2912 int rc = SQLITE_OK; 2913 sqlite3expert *p = pState->expert.pExpert; 2914 assert( p ); 2915 assert( bCancel || pzErr==0 || *pzErr==0 ); 2916 if( bCancel==0 ){ 2917 FILE *out = pState->out; 2918 int bVerbose = pState->expert.bVerbose; 2919 2920 rc = sqlite3_expert_analyze(p, pzErr); 2921 if( rc==SQLITE_OK ){ 2922 int nQuery = sqlite3_expert_count(p); 2923 int i; 2924 2925 if( bVerbose ){ 2926 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 2927 raw_printf(out, "-- Candidates -----------------------------\n"); 2928 raw_printf(out, "%s\n", zCand); 2929 } 2930 for(i=0; i<nQuery; i++){ 2931 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 2932 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 2933 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 2934 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 2935 if( bVerbose ){ 2936 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 2937 raw_printf(out, "%s\n\n", zSql); 2938 } 2939 raw_printf(out, "%s\n", zIdx); 2940 raw_printf(out, "%s\n", zEQP); 2941 } 2942 } 2943 } 2944 sqlite3_expert_destroy(p); 2945 pState->expert.pExpert = 0; 2946 return rc; 2947} 2948 2949/* 2950** Implementation of ".expert" dot command. 2951*/ 2952static int expertDotCommand( 2953 ShellState *pState, /* Current shell tool state */ 2954 char **azArg, /* Array of arguments passed to dot command */ 2955 int nArg /* Number of entries in azArg[] */ 2956){ 2957 int rc = SQLITE_OK; 2958 char *zErr = 0; 2959 int i; 2960 int iSample = 0; 2961 2962 assert( pState->expert.pExpert==0 ); 2963 memset(&pState->expert, 0, sizeof(ExpertInfo)); 2964 2965 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 2966 char *z = azArg[i]; 2967 int n; 2968 if( z[0]=='-' && z[1]=='-' ) z++; 2969 n = strlen30(z); 2970 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 2971 pState->expert.bVerbose = 1; 2972 } 2973 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 2974 if( i==(nArg-1) ){ 2975 raw_printf(stderr, "option requires an argument: %s\n", z); 2976 rc = SQLITE_ERROR; 2977 }else{ 2978 iSample = (int)integerValue(azArg[++i]); 2979 if( iSample<0 || iSample>100 ){ 2980 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 2981 rc = SQLITE_ERROR; 2982 } 2983 } 2984 } 2985 else{ 2986 raw_printf(stderr, "unknown option: %s\n", z); 2987 rc = SQLITE_ERROR; 2988 } 2989 } 2990 2991 if( rc==SQLITE_OK ){ 2992 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 2993 if( pState->expert.pExpert==0 ){ 2994 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); 2995 rc = SQLITE_ERROR; 2996 }else{ 2997 sqlite3_expert_config( 2998 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 2999 ); 3000 } 3001 } 3002 3003 return rc; 3004} 3005#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3006 3007/* 3008** Execute a statement or set of statements. Print 3009** any result rows/columns depending on the current mode 3010** set via the supplied callback. 3011** 3012** This is very similar to SQLite's built-in sqlite3_exec() 3013** function except it takes a slightly different callback 3014** and callback data argument. 3015*/ 3016static int shell_exec( 3017 ShellState *pArg, /* Pointer to ShellState */ 3018 const char *zSql, /* SQL to be evaluated */ 3019 char **pzErrMsg /* Error msg written here */ 3020){ 3021 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3022 int rc = SQLITE_OK; /* Return Code */ 3023 int rc2; 3024 const char *zLeftover; /* Tail of unprocessed SQL */ 3025 sqlite3 *db = pArg->db; 3026 3027 if( pzErrMsg ){ 3028 *pzErrMsg = NULL; 3029 } 3030 3031#ifndef SQLITE_OMIT_VIRTUALTABLE 3032 if( pArg->expert.pExpert ){ 3033 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3034 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3035 } 3036#endif 3037 3038 while( zSql[0] && (SQLITE_OK == rc) ){ 3039 static const char *zStmtSql; 3040 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3041 if( SQLITE_OK != rc ){ 3042 if( pzErrMsg ){ 3043 *pzErrMsg = save_err_msg(db); 3044 } 3045 }else{ 3046 if( !pStmt ){ 3047 /* this happens for a comment or white-space */ 3048 zSql = zLeftover; 3049 while( IsSpace(zSql[0]) ) zSql++; 3050 continue; 3051 } 3052 zStmtSql = sqlite3_sql(pStmt); 3053 if( zStmtSql==0 ) zStmtSql = ""; 3054 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3055 3056 /* save off the prepared statment handle and reset row count */ 3057 if( pArg ){ 3058 pArg->pStmt = pStmt; 3059 pArg->cnt = 0; 3060 } 3061 3062 /* echo the sql statement if echo on */ 3063 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3064 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3065 } 3066 3067 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3068 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3069 sqlite3_stmt *pExplain; 3070 char *zEQP; 3071 int triggerEQP = 0; 3072 disable_debug_trace_modes(); 3073 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3074 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3075 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3076 } 3077 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3078 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3079 if( rc==SQLITE_OK ){ 3080 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3081 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3082 int iEqpId = sqlite3_column_int(pExplain, 0); 3083 int iParentId = sqlite3_column_int(pExplain, 1); 3084 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3085 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3086 } 3087 eqp_render(pArg); 3088 } 3089 sqlite3_finalize(pExplain); 3090 sqlite3_free(zEQP); 3091 if( pArg->autoEQP>=AUTOEQP_full ){ 3092 /* Also do an EXPLAIN for ".eqp full" mode */ 3093 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3094 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3095 if( rc==SQLITE_OK ){ 3096 pArg->cMode = MODE_Explain; 3097 explain_data_prepare(pArg, pExplain); 3098 exec_prepared_stmt(pArg, pExplain); 3099 explain_data_delete(pArg); 3100 } 3101 sqlite3_finalize(pExplain); 3102 sqlite3_free(zEQP); 3103 } 3104 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3105 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3106 /* Reprepare pStmt before reactiving trace modes */ 3107 sqlite3_finalize(pStmt); 3108 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3109 if( pArg ) pArg->pStmt = pStmt; 3110 } 3111 restore_debug_trace_modes(); 3112 } 3113 3114 if( pArg ){ 3115 pArg->cMode = pArg->mode; 3116 if( pArg->autoExplain ){ 3117 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3118 pArg->cMode = MODE_Explain; 3119 } 3120 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3121 pArg->cMode = MODE_EQP; 3122 } 3123 } 3124 3125 /* If the shell is currently in ".explain" mode, gather the extra 3126 ** data required to add indents to the output.*/ 3127 if( pArg->cMode==MODE_Explain ){ 3128 explain_data_prepare(pArg, pStmt); 3129 } 3130 } 3131 3132 bind_prepared_stmt(pArg, pStmt); 3133 exec_prepared_stmt(pArg, pStmt); 3134 explain_data_delete(pArg); 3135 eqp_render(pArg); 3136 3137 /* print usage stats if stats on */ 3138 if( pArg && pArg->statsOn ){ 3139 display_stats(db, pArg, 0); 3140 } 3141 3142 /* print loop-counters if required */ 3143 if( pArg && pArg->scanstatsOn ){ 3144 display_scanstats(db, pArg); 3145 } 3146 3147 /* Finalize the statement just executed. If this fails, save a 3148 ** copy of the error message. Otherwise, set zSql to point to the 3149 ** next statement to execute. */ 3150 rc2 = sqlite3_finalize(pStmt); 3151 if( rc!=SQLITE_NOMEM ) rc = rc2; 3152 if( rc==SQLITE_OK ){ 3153 zSql = zLeftover; 3154 while( IsSpace(zSql[0]) ) zSql++; 3155 }else if( pzErrMsg ){ 3156 *pzErrMsg = save_err_msg(db); 3157 } 3158 3159 /* clear saved stmt handle */ 3160 if( pArg ){ 3161 pArg->pStmt = NULL; 3162 } 3163 } 3164 } /* end while */ 3165 3166 return rc; 3167} 3168 3169/* 3170** Release memory previously allocated by tableColumnList(). 3171*/ 3172static void freeColumnList(char **azCol){ 3173 int i; 3174 for(i=1; azCol[i]; i++){ 3175 sqlite3_free(azCol[i]); 3176 } 3177 /* azCol[0] is a static string */ 3178 sqlite3_free(azCol); 3179} 3180 3181/* 3182** Return a list of pointers to strings which are the names of all 3183** columns in table zTab. The memory to hold the names is dynamically 3184** allocated and must be released by the caller using a subsequent call 3185** to freeColumnList(). 3186** 3187** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3188** value that needs to be preserved, then azCol[0] is filled in with the 3189** name of the rowid column. 3190** 3191** The first regular column in the table is azCol[1]. The list is terminated 3192** by an entry with azCol[i]==0. 3193*/ 3194static char **tableColumnList(ShellState *p, const char *zTab){ 3195 char **azCol = 0; 3196 sqlite3_stmt *pStmt; 3197 char *zSql; 3198 int nCol = 0; 3199 int nAlloc = 0; 3200 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3201 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3202 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3203 int rc; 3204 3205 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3206 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3207 sqlite3_free(zSql); 3208 if( rc ) return 0; 3209 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3210 if( nCol>=nAlloc-2 ){ 3211 nAlloc = nAlloc*2 + nCol + 10; 3212 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3213 if( azCol==0 ) shell_out_of_memory(); 3214 } 3215 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3216 if( sqlite3_column_int(pStmt, 5) ){ 3217 nPK++; 3218 if( nPK==1 3219 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3220 "INTEGER")==0 3221 ){ 3222 isIPK = 1; 3223 }else{ 3224 isIPK = 0; 3225 } 3226 } 3227 } 3228 sqlite3_finalize(pStmt); 3229 if( azCol==0 ) return 0; 3230 azCol[0] = 0; 3231 azCol[nCol+1] = 0; 3232 3233 /* The decision of whether or not a rowid really needs to be preserved 3234 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3235 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3236 ** rowids on tables where the rowid is inaccessible because there are other 3237 ** columns in the table named "rowid", "_rowid_", and "oid". 3238 */ 3239 if( preserveRowid && isIPK ){ 3240 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3241 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3242 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3243 ** ROWID aliases. To distinguish these cases, check to see if 3244 ** there is a "pk" entry in "PRAGMA index_list". There will be 3245 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3246 */ 3247 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3248 " WHERE origin='pk'", zTab); 3249 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3250 sqlite3_free(zSql); 3251 if( rc ){ 3252 freeColumnList(azCol); 3253 return 0; 3254 } 3255 rc = sqlite3_step(pStmt); 3256 sqlite3_finalize(pStmt); 3257 preserveRowid = rc==SQLITE_ROW; 3258 } 3259 if( preserveRowid ){ 3260 /* Only preserve the rowid if we can find a name to use for the 3261 ** rowid */ 3262 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3263 int i, j; 3264 for(j=0; j<3; j++){ 3265 for(i=1; i<=nCol; i++){ 3266 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3267 } 3268 if( i>nCol ){ 3269 /* At this point, we know that azRowid[j] is not the name of any 3270 ** ordinary column in the table. Verify that azRowid[j] is a valid 3271 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3272 ** tables will fail this last check */ 3273 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3274 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3275 break; 3276 } 3277 } 3278 } 3279 return azCol; 3280} 3281 3282/* 3283** Toggle the reverse_unordered_selects setting. 3284*/ 3285static void toggleSelectOrder(sqlite3 *db){ 3286 sqlite3_stmt *pStmt = 0; 3287 int iSetting = 0; 3288 char zStmt[100]; 3289 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3290 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3291 iSetting = sqlite3_column_int(pStmt, 0); 3292 } 3293 sqlite3_finalize(pStmt); 3294 sqlite3_snprintf(sizeof(zStmt), zStmt, 3295 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3296 sqlite3_exec(db, zStmt, 0, 0, 0); 3297} 3298 3299/* 3300** This is a different callback routine used for dumping the database. 3301** Each row received by this callback consists of a table name, 3302** the table type ("index" or "table") and SQL to create the table. 3303** This routine should print text sufficient to recreate the table. 3304*/ 3305static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3306 int rc; 3307 const char *zTable; 3308 const char *zType; 3309 const char *zSql; 3310 ShellState *p = (ShellState *)pArg; 3311 3312 UNUSED_PARAMETER(azNotUsed); 3313 if( nArg!=3 || azArg==0 ) return 0; 3314 zTable = azArg[0]; 3315 zType = azArg[1]; 3316 zSql = azArg[2]; 3317 3318 if( strcmp(zTable, "sqlite_sequence")==0 ){ 3319 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3320 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ 3321 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 3322 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3323 return 0; 3324 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3325 char *zIns; 3326 if( !p->writableSchema ){ 3327 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3328 p->writableSchema = 1; 3329 } 3330 zIns = sqlite3_mprintf( 3331 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" 3332 "VALUES('table','%q','%q',0,'%q');", 3333 zTable, zTable, zSql); 3334 utf8_printf(p->out, "%s\n", zIns); 3335 sqlite3_free(zIns); 3336 return 0; 3337 }else{ 3338 printSchemaLine(p->out, zSql, ";\n"); 3339 } 3340 3341 if( strcmp(zType, "table")==0 ){ 3342 ShellText sSelect; 3343 ShellText sTable; 3344 char **azCol; 3345 int i; 3346 char *savedDestTable; 3347 int savedMode; 3348 3349 azCol = tableColumnList(p, zTable); 3350 if( azCol==0 ){ 3351 p->nErr++; 3352 return 0; 3353 } 3354 3355 /* Always quote the table name, even if it appears to be pure ascii, 3356 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3357 initText(&sTable); 3358 appendText(&sTable, zTable, quoteChar(zTable)); 3359 /* If preserving the rowid, add a column list after the table name. 3360 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3361 ** instead of the usual "INSERT INTO tab VALUES(...)". 3362 */ 3363 if( azCol[0] ){ 3364 appendText(&sTable, "(", 0); 3365 appendText(&sTable, azCol[0], 0); 3366 for(i=1; azCol[i]; i++){ 3367 appendText(&sTable, ",", 0); 3368 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3369 } 3370 appendText(&sTable, ")", 0); 3371 } 3372 3373 /* Build an appropriate SELECT statement */ 3374 initText(&sSelect); 3375 appendText(&sSelect, "SELECT ", 0); 3376 if( azCol[0] ){ 3377 appendText(&sSelect, azCol[0], 0); 3378 appendText(&sSelect, ",", 0); 3379 } 3380 for(i=1; azCol[i]; i++){ 3381 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3382 if( azCol[i+1] ){ 3383 appendText(&sSelect, ",", 0); 3384 } 3385 } 3386 freeColumnList(azCol); 3387 appendText(&sSelect, " FROM ", 0); 3388 appendText(&sSelect, zTable, quoteChar(zTable)); 3389 3390 savedDestTable = p->zDestTable; 3391 savedMode = p->mode; 3392 p->zDestTable = sTable.z; 3393 p->mode = p->cMode = MODE_Insert; 3394 rc = shell_exec(p, sSelect.z, 0); 3395 if( (rc&0xff)==SQLITE_CORRUPT ){ 3396 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3397 toggleSelectOrder(p->db); 3398 shell_exec(p, sSelect.z, 0); 3399 toggleSelectOrder(p->db); 3400 } 3401 p->zDestTable = savedDestTable; 3402 p->mode = savedMode; 3403 freeText(&sTable); 3404 freeText(&sSelect); 3405 if( rc ) p->nErr++; 3406 } 3407 return 0; 3408} 3409 3410/* 3411** Run zQuery. Use dump_callback() as the callback routine so that 3412** the contents of the query are output as SQL statements. 3413** 3414** If we get a SQLITE_CORRUPT error, rerun the query after appending 3415** "ORDER BY rowid DESC" to the end. 3416*/ 3417static int run_schema_dump_query( 3418 ShellState *p, 3419 const char *zQuery 3420){ 3421 int rc; 3422 char *zErr = 0; 3423 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3424 if( rc==SQLITE_CORRUPT ){ 3425 char *zQ2; 3426 int len = strlen30(zQuery); 3427 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3428 if( zErr ){ 3429 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3430 sqlite3_free(zErr); 3431 zErr = 0; 3432 } 3433 zQ2 = malloc( len+100 ); 3434 if( zQ2==0 ) return rc; 3435 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3436 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3437 if( rc ){ 3438 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3439 }else{ 3440 rc = SQLITE_CORRUPT; 3441 } 3442 sqlite3_free(zErr); 3443 free(zQ2); 3444 } 3445 return rc; 3446} 3447 3448/* 3449** Text of help messages. 3450** 3451** The help text for each individual command begins with a line that starts 3452** with ".". Subsequent lines are supplimental information. 3453** 3454** There must be two or more spaces between the end of the command and the 3455** start of the description of what that command does. 3456*/ 3457static const char *(azHelp[]) = { 3458#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 3459 ".archive ... Manage SQL archives", 3460 " Each command must have exactly one of the following options:", 3461 " -c, --create Create a new archive", 3462 " -u, --update Add files or update files with changed mtime", 3463 " -i, --insert Like -u but always add even if mtime unchanged", 3464 " -t, --list List contents of archive", 3465 " -x, --extract Extract files from archive", 3466 " Optional arguments:", 3467 " -v, --verbose Print each filename as it is processed", 3468 " -f FILE, --file FILE Operate on archive FILE (default is current db)", 3469 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS", 3470 " -C DIR, --directory DIR Change to directory DIR to read/extract files", 3471 " -n, --dryrun Show the SQL that would have occurred", 3472 " Examples:", 3473 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar", 3474 " .ar -tf archive.sar # List members of archive.sar", 3475 " .ar -xvf archive.sar # Verbosely extract files from archive.sar", 3476 " See also:", 3477 " http://sqlite.org/cli.html#sqlar_archive_support", 3478#endif 3479#ifndef SQLITE_OMIT_AUTHORIZATION 3480 ".auth ON|OFF Show authorizer callbacks", 3481#endif 3482 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 3483 " --append Use the appendvfs", 3484 " --async Write to FILE without a journal and without fsync()", 3485 ".bail on|off Stop after hitting an error. Default OFF", 3486 ".binary on|off Turn binary output on or off. Default OFF", 3487 ".cd DIRECTORY Change the working directory to DIRECTORY", 3488 ".changes on|off Show number of rows changed by SQL", 3489 ".check GLOB Fail if output since .testcase does not match", 3490 ".clone NEWDB Clone data into NEWDB from the existing database", 3491 ".databases List names and files of attached databases", 3492 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 3493 ".dbinfo ?DB? Show status information about the database", 3494 ".dump ?TABLE? ... Render all database content as SQL", 3495 " Options:", 3496 " --preserve-rowids Include ROWID values in the output", 3497 " --newlines Allow unescaped newline characters in output", 3498 " TABLE is a LIKE pattern for the tables to dump", 3499 ".echo on|off Turn command echo on or off", 3500 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 3501 " Other Modes:", 3502#ifdef SQLITE_DEBUG 3503 " test Show raw EXPLAIN QUERY PLAN output", 3504 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"", 3505#endif 3506 " trigger Like \"full\" but also show trigger bytecode", 3507 ".excel Display the output of next command in a spreadsheet", 3508 ".exit ?CODE? Exit this program with return-code CODE", 3509 ".expert EXPERIMENTAL. Suggest indexes for specified queries", 3510/* Because explain mode comes on automatically now, the ".explain" mode 3511** is removed from the help screen. It is still supported for legacy, however */ 3512/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/ 3513 ".filectrl CMD ... Run various sqlite3_file_control() operations", 3514 " Run \".filectrl\" with no arguments for details", 3515 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 3516 ".headers on|off Turn display of headers on or off", 3517 ".help ?-all? ?PATTERN? Show help text for PATTERN", 3518 ".import FILE TABLE Import data from FILE into TABLE", 3519#ifndef SQLITE_OMIT_TEST_CONTROL 3520 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 3521#endif 3522 ".indexes ?TABLE? Show names of indexes", 3523 " If TABLE is specified, only show indexes for", 3524 " tables matching TABLE using the LIKE operator.", 3525#ifdef SQLITE_ENABLE_IOTRACE 3526 ".iotrace FILE Enable I/O diagnostic logging to FILE", 3527#endif 3528 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 3529 ".lint OPTIONS Report potential schema issues.", 3530 " Options:", 3531 " fkey-indexes Find missing foreign key indexes", 3532#ifndef SQLITE_OMIT_LOAD_EXTENSION 3533 ".load FILE ?ENTRY? Load an extension library", 3534#endif 3535 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 3536 ".mode MODE ?TABLE? Set output mode", 3537 " MODE is one of:", 3538 " ascii Columns/rows delimited by 0x1F and 0x1E", 3539 " csv Comma-separated values", 3540 " column Left-aligned columns. (See .width)", 3541 " html HTML <table> code", 3542 " insert SQL insert statements for TABLE", 3543 " line One value per line", 3544 " list Values delimited by \"|\"", 3545 " quote Escape answers as for SQL", 3546 " tabs Tab-separated values", 3547 " tcl TCL list elements", 3548 ".nullvalue STRING Use STRING in place of NULL values", 3549 ".once (-e|-x|FILE) Output for the next SQL command only to FILE", 3550 " If FILE begins with '|' then open as a pipe", 3551 " Other options:", 3552 " -e Invoke system text editor", 3553 " -x Open in a spreadsheet", 3554 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 3555 " Options:", 3556 " --append Use appendvfs to append database to the end of FILE", 3557#ifdef SQLITE_ENABLE_DESERIALIZE 3558 " --deserialize Load into memory useing sqlite3_deserialize()", 3559 " --hexdb Load the output of \"dbtotxt\" as an in-memory database", 3560 " --maxsize N Maximum size for --hexdb or --deserialized database", 3561#endif 3562 " --new Initialize FILE to an empty database", 3563 " --readonly Open FILE readonly", 3564 " --zip FILE is a ZIP archive", 3565 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 3566 " If FILE begins with '|' then open it as a pipe.", 3567 ".parameter CMD ... Manage SQL parameter bindings", 3568 " clear Erase all bindings", 3569 " init Initialize the TEMP table that holds bindings", 3570 " list List the current parameter bindings", 3571 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 3572 " PARAMETER should start with '$', ':', '@', or '?'", 3573 " unset PARAMETER Remove PARAMETER from the binding table", 3574 ".print STRING... Print literal STRING", 3575#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 3576 ".progress N Invoke progress handler after every N opcodes", 3577 " --limit N Interrupt after N progress callbacks", 3578 " --once Do no more than one progress interrupt", 3579 " --quiet|-q No output except at interrupts", 3580 " --reset Reset the count for each input and interrupt", 3581#endif 3582 ".prompt MAIN CONTINUE Replace the standard prompts", 3583 ".quit Exit this program", 3584 ".read FILE Read input from FILE", 3585#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 3586 ".recover Recover as much data as possible from corrupt db.", 3587#endif 3588 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 3589 ".save FILE Write in-memory database into FILE", 3590 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 3591 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 3592 " Options:", 3593 " --indent Try to pretty-print the schema", 3594 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 3595 " Options:", 3596 " --init Create a new SELFTEST table", 3597 " -v Verbose output", 3598 ".separator COL ?ROW? Change the column and row separators", 3599#if defined(SQLITE_ENABLE_SESSION) 3600 ".session ?NAME? CMD ... Create or control sessions", 3601 " Subcommands:", 3602 " attach TABLE Attach TABLE", 3603 " changeset FILE Write a changeset into FILE", 3604 " close Close one session", 3605 " enable ?BOOLEAN? Set or query the enable bit", 3606 " filter GLOB... Reject tables matching GLOBs", 3607 " indirect ?BOOLEAN? Mark or query the indirect status", 3608 " isempty Query whether the session is empty", 3609 " list List currently open session names", 3610 " open DB NAME Open a new session on DB", 3611 " patchset FILE Write a patchset into FILE", 3612 " If ?NAME? is omitted, the first defined session is used.", 3613#endif 3614 ".sha3sum ... Compute a SHA3 hash of database content", 3615 " Options:", 3616 " --schema Also hash the sqlite_master table", 3617 " --sha3-224 Use the sha3-224 algorithm", 3618 " --sha3-256 Use the sha3-256 algorithm. This is the default.", 3619 " --sha3-384 Use the sha3-384 algorithm", 3620 " --sha3-512 Use the sha3-512 algorithm", 3621 " Any other argument is a LIKE pattern for tables to hash", 3622#ifndef SQLITE_NOHAVE_SYSTEM 3623 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 3624#endif 3625 ".show Show the current values for various settings", 3626 ".stats ?on|off? Show stats or turn stats on or off", 3627#ifndef SQLITE_NOHAVE_SYSTEM 3628 ".system CMD ARGS... Run CMD ARGS... in a system shell", 3629#endif 3630 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 3631 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 3632 ".testctrl CMD ... Run various sqlite3_test_control() operations", 3633 " Run \".testctrl\" with no arguments for details", 3634 ".timeout MS Try opening locked tables for MS milliseconds", 3635 ".timer on|off Turn SQL timer on or off", 3636#ifndef SQLITE_OMIT_TRACE 3637 ".trace ?OPTIONS? Output each SQL statement as it is run", 3638 " FILE Send output to FILE", 3639 " stdout Send output to stdout", 3640 " stderr Send output to stderr", 3641 " off Disable tracing", 3642 " --expanded Expand query parameters", 3643#ifdef SQLITE_ENABLE_NORMALIZE 3644 " --normalized Normal the SQL statements", 3645#endif 3646 " --plain Show SQL as it is input", 3647 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 3648 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 3649 " --row Trace each row (SQLITE_TRACE_ROW)", 3650 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 3651#endif /* SQLITE_OMIT_TRACE */ 3652#ifdef SQLITE_DEBUG 3653 ".unmodule NAME ... Unregister virtual table modules", 3654#endif 3655 ".vfsinfo ?AUX? Information about the top-level VFS", 3656 ".vfslist List all available VFSes", 3657 ".vfsname ?AUX? Print the name of the VFS stack", 3658 ".width NUM1 NUM2 ... Set column widths for \"column\" mode", 3659 " Negative values right-justify", 3660}; 3661 3662/* 3663** Output help text. 3664** 3665** zPattern describes the set of commands for which help text is provided. 3666** If zPattern is NULL, then show all commands, but only give a one-line 3667** description of each. 3668** 3669** Return the number of matches. 3670*/ 3671static int showHelp(FILE *out, const char *zPattern){ 3672 int i = 0; 3673 int j = 0; 3674 int n = 0; 3675 char *zPat; 3676 if( zPattern==0 3677 || zPattern[0]=='0' 3678 || strcmp(zPattern,"-a")==0 3679 || strcmp(zPattern,"-all")==0 3680 ){ 3681 /* Show all commands, but only one line per command */ 3682 if( zPattern==0 ) zPattern = ""; 3683 for(i=0; i<ArraySize(azHelp); i++){ 3684 if( azHelp[i][0]=='.' || zPattern[0] ){ 3685 utf8_printf(out, "%s\n", azHelp[i]); 3686 n++; 3687 } 3688 } 3689 }else{ 3690 /* Look for commands that for which zPattern is an exact prefix */ 3691 zPat = sqlite3_mprintf(".%s*", zPattern); 3692 for(i=0; i<ArraySize(azHelp); i++){ 3693 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 3694 utf8_printf(out, "%s\n", azHelp[i]); 3695 j = i+1; 3696 n++; 3697 } 3698 } 3699 sqlite3_free(zPat); 3700 if( n ){ 3701 if( n==1 ){ 3702 /* when zPattern is a prefix of exactly one command, then include the 3703 ** details of that command, which should begin at offset j */ 3704 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 3705 utf8_printf(out, "%s\n", azHelp[j]); 3706 j++; 3707 } 3708 } 3709 return n; 3710 } 3711 /* Look for commands that contain zPattern anywhere. Show the complete 3712 ** text of all commands that match. */ 3713 zPat = sqlite3_mprintf("%%%s%%", zPattern); 3714 for(i=0; i<ArraySize(azHelp); i++){ 3715 if( azHelp[i][0]=='.' ) j = i; 3716 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 3717 utf8_printf(out, "%s\n", azHelp[j]); 3718 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 3719 j++; 3720 utf8_printf(out, "%s\n", azHelp[j]); 3721 } 3722 i = j; 3723 n++; 3724 } 3725 } 3726 sqlite3_free(zPat); 3727 } 3728 return n; 3729} 3730 3731/* Forward reference */ 3732static int process_input(ShellState *p); 3733 3734/* 3735** Read the content of file zName into memory obtained from sqlite3_malloc64() 3736** and return a pointer to the buffer. The caller is responsible for freeing 3737** the memory. 3738** 3739** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 3740** read. 3741** 3742** For convenience, a nul-terminator byte is always appended to the data read 3743** from the file before the buffer is returned. This byte is not included in 3744** the final value of (*pnByte), if applicable. 3745** 3746** NULL is returned if any error is encountered. The final value of *pnByte 3747** is undefined in this case. 3748*/ 3749static char *readFile(const char *zName, int *pnByte){ 3750 FILE *in = fopen(zName, "rb"); 3751 long nIn; 3752 size_t nRead; 3753 char *pBuf; 3754 if( in==0 ) return 0; 3755 fseek(in, 0, SEEK_END); 3756 nIn = ftell(in); 3757 rewind(in); 3758 pBuf = sqlite3_malloc64( nIn+1 ); 3759 if( pBuf==0 ){ fclose(in); return 0; } 3760 nRead = fread(pBuf, nIn, 1, in); 3761 fclose(in); 3762 if( nRead!=1 ){ 3763 sqlite3_free(pBuf); 3764 return 0; 3765 } 3766 pBuf[nIn] = 0; 3767 if( pnByte ) *pnByte = nIn; 3768 return pBuf; 3769} 3770 3771#if defined(SQLITE_ENABLE_SESSION) 3772/* 3773** Close a single OpenSession object and release all of its associated 3774** resources. 3775*/ 3776static void session_close(OpenSession *pSession){ 3777 int i; 3778 sqlite3session_delete(pSession->p); 3779 sqlite3_free(pSession->zName); 3780 for(i=0; i<pSession->nFilter; i++){ 3781 sqlite3_free(pSession->azFilter[i]); 3782 } 3783 sqlite3_free(pSession->azFilter); 3784 memset(pSession, 0, sizeof(OpenSession)); 3785} 3786#endif 3787 3788/* 3789** Close all OpenSession objects and release all associated resources. 3790*/ 3791#if defined(SQLITE_ENABLE_SESSION) 3792static void session_close_all(ShellState *p){ 3793 int i; 3794 for(i=0; i<p->nSession; i++){ 3795 session_close(&p->aSession[i]); 3796 } 3797 p->nSession = 0; 3798} 3799#else 3800# define session_close_all(X) 3801#endif 3802 3803/* 3804** Implementation of the xFilter function for an open session. Omit 3805** any tables named by ".session filter" but let all other table through. 3806*/ 3807#if defined(SQLITE_ENABLE_SESSION) 3808static int session_filter(void *pCtx, const char *zTab){ 3809 OpenSession *pSession = (OpenSession*)pCtx; 3810 int i; 3811 for(i=0; i<pSession->nFilter; i++){ 3812 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 3813 } 3814 return 1; 3815} 3816#endif 3817 3818/* 3819** Try to deduce the type of file for zName based on its content. Return 3820** one of the SHELL_OPEN_* constants. 3821** 3822** If the file does not exist or is empty but its name looks like a ZIP 3823** archive and the dfltZip flag is true, then assume it is a ZIP archive. 3824** Otherwise, assume an ordinary database regardless of the filename if 3825** the type cannot be determined from content. 3826*/ 3827int deduceDatabaseType(const char *zName, int dfltZip){ 3828 FILE *f = fopen(zName, "rb"); 3829 size_t n; 3830 int rc = SHELL_OPEN_UNSPEC; 3831 char zBuf[100]; 3832 if( f==0 ){ 3833 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3834 return SHELL_OPEN_ZIPFILE; 3835 }else{ 3836 return SHELL_OPEN_NORMAL; 3837 } 3838 } 3839 n = fread(zBuf, 16, 1, f); 3840 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 3841 fclose(f); 3842 return SHELL_OPEN_NORMAL; 3843 } 3844 fseek(f, -25, SEEK_END); 3845 n = fread(zBuf, 25, 1, f); 3846 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 3847 rc = SHELL_OPEN_APPENDVFS; 3848 }else{ 3849 fseek(f, -22, SEEK_END); 3850 n = fread(zBuf, 22, 1, f); 3851 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 3852 && zBuf[3]==0x06 ){ 3853 rc = SHELL_OPEN_ZIPFILE; 3854 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3855 rc = SHELL_OPEN_ZIPFILE; 3856 } 3857 } 3858 fclose(f); 3859 return rc; 3860} 3861 3862#ifdef SQLITE_ENABLE_DESERIALIZE 3863/* 3864** Reconstruct an in-memory database using the output from the "dbtotxt" 3865** program. Read content from the file in p->zDbFilename. If p->zDbFilename 3866** is 0, then read from standard input. 3867*/ 3868static unsigned char *readHexDb(ShellState *p, int *pnData){ 3869 unsigned char *a = 0; 3870 int nLine; 3871 int n = 0; 3872 int pgsz = 0; 3873 int iOffset = 0; 3874 int j, k; 3875 int rc; 3876 FILE *in; 3877 unsigned int x[16]; 3878 char zLine[1000]; 3879 if( p->zDbFilename ){ 3880 in = fopen(p->zDbFilename, "r"); 3881 if( in==0 ){ 3882 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename); 3883 return 0; 3884 } 3885 nLine = 0; 3886 }else{ 3887 in = p->in; 3888 nLine = p->lineno; 3889 if( in==0 ) in = stdin; 3890 } 3891 *pnData = 0; 3892 nLine++; 3893 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 3894 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 3895 if( rc!=2 ) goto readHexDb_error; 3896 if( n<0 ) goto readHexDb_error; 3897 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 3898 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 3899 a = sqlite3_malloc( n ? n : 1 ); 3900 if( a==0 ){ 3901 utf8_printf(stderr, "Out of memory!\n"); 3902 goto readHexDb_error; 3903 } 3904 memset(a, 0, n); 3905 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 3906 utf8_printf(stderr, "invalid pagesize\n"); 3907 goto readHexDb_error; 3908 } 3909 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 3910 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 3911 if( rc==2 ){ 3912 iOffset = k; 3913 continue; 3914 } 3915 if( strncmp(zLine, "| end ", 6)==0 ){ 3916 break; 3917 } 3918 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 3919 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 3920 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 3921 if( rc==17 ){ 3922 k = iOffset+j; 3923 if( k+16<=n ){ 3924 int ii; 3925 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 3926 } 3927 } 3928 } 3929 *pnData = n; 3930 if( in!=p->in ){ 3931 fclose(in); 3932 }else{ 3933 p->lineno = nLine; 3934 } 3935 return a; 3936 3937readHexDb_error: 3938 if( in!=p->in ){ 3939 fclose(in); 3940 }else{ 3941 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 3942 nLine++; 3943 if(strncmp(zLine, "| end ", 6)==0 ) break; 3944 } 3945 p->lineno = nLine; 3946 } 3947 sqlite3_free(a); 3948 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 3949 return 0; 3950} 3951#endif /* SQLITE_ENABLE_DESERIALIZE */ 3952 3953/* 3954** Scalar function "shell_int32". The first argument to this function 3955** must be a blob. The second a non-negative integer. This function 3956** reads and returns a 32-bit big-endian integer from byte 3957** offset (4*<arg2>) of the blob. 3958*/ 3959static void shellInt32( 3960 sqlite3_context *context, 3961 int argc, 3962 sqlite3_value **argv 3963){ 3964 const unsigned char *pBlob; 3965 int nBlob; 3966 int iInt; 3967 3968 UNUSED_PARAMETER(argc); 3969 nBlob = sqlite3_value_bytes(argv[0]); 3970 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 3971 iInt = sqlite3_value_int(argv[1]); 3972 3973 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 3974 const unsigned char *a = &pBlob[iInt*4]; 3975 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 3976 + ((sqlite3_int64)a[1]<<16) 3977 + ((sqlite3_int64)a[2]<< 8) 3978 + ((sqlite3_int64)a[3]<< 0); 3979 sqlite3_result_int64(context, iVal); 3980 } 3981} 3982 3983/* 3984** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 3985** using "..." with internal double-quote characters doubled. 3986*/ 3987static void shellIdQuote( 3988 sqlite3_context *context, 3989 int argc, 3990 sqlite3_value **argv 3991){ 3992 const char *zName = (const char*)sqlite3_value_text(argv[0]); 3993 UNUSED_PARAMETER(argc); 3994 if( zName ){ 3995 char *z = sqlite3_mprintf("\"%w\"", zName); 3996 sqlite3_result_text(context, z, -1, sqlite3_free); 3997 } 3998} 3999 4000/* 4001** Scalar function "shell_escape_crnl" used by the .recover command. 4002** The argument passed to this function is the output of built-in 4003** function quote(). If the first character of the input is "'", 4004** indicating that the value passed to quote() was a text value, 4005** then this function searches the input for "\n" and "\r" characters 4006** and adds a wrapper similar to the following: 4007** 4008** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4009** 4010** Or, if the first character of the input is not "'", then a copy 4011** of the input is returned. 4012*/ 4013static void shellEscapeCrnl( 4014 sqlite3_context *context, 4015 int argc, 4016 sqlite3_value **argv 4017){ 4018 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4019 UNUSED_PARAMETER(argc); 4020 if( zText[0]=='\'' ){ 4021 int nText = sqlite3_value_bytes(argv[0]); 4022 int i; 4023 char zBuf1[20]; 4024 char zBuf2[20]; 4025 const char *zNL = 0; 4026 const char *zCR = 0; 4027 int nCR = 0; 4028 int nNL = 0; 4029 4030 for(i=0; zText[i]; i++){ 4031 if( zNL==0 && zText[i]=='\n' ){ 4032 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4033 nNL = (int)strlen(zNL); 4034 } 4035 if( zCR==0 && zText[i]=='\r' ){ 4036 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4037 nCR = (int)strlen(zCR); 4038 } 4039 } 4040 4041 if( zNL || zCR ){ 4042 int iOut = 0; 4043 i64 nMax = (nNL > nCR) ? nNL : nCR; 4044 i64 nAlloc = nMax * nText + (nMax+64)*2; 4045 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4046 if( zOut==0 ){ 4047 sqlite3_result_error_nomem(context); 4048 return; 4049 } 4050 4051 if( zNL && zCR ){ 4052 memcpy(&zOut[iOut], "replace(replace(", 16); 4053 iOut += 16; 4054 }else{ 4055 memcpy(&zOut[iOut], "replace(", 8); 4056 iOut += 8; 4057 } 4058 for(i=0; zText[i]; i++){ 4059 if( zText[i]=='\n' ){ 4060 memcpy(&zOut[iOut], zNL, nNL); 4061 iOut += nNL; 4062 }else if( zText[i]=='\r' ){ 4063 memcpy(&zOut[iOut], zCR, nCR); 4064 iOut += nCR; 4065 }else{ 4066 zOut[iOut] = zText[i]; 4067 iOut++; 4068 } 4069 } 4070 4071 if( zNL ){ 4072 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4073 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4074 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4075 } 4076 if( zCR ){ 4077 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4078 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4079 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4080 } 4081 4082 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4083 sqlite3_free(zOut); 4084 return; 4085 } 4086 } 4087 4088 sqlite3_result_value(context, argv[0]); 4089} 4090 4091/* Flags for open_db(). 4092** 4093** The default behavior of open_db() is to exit(1) if the database fails to 4094** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4095** but still returns without calling exit. 4096** 4097** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4098** ZIP archive if the file does not exist or is empty and its name matches 4099** the *.zip pattern. 4100*/ 4101#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4102#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4103 4104/* 4105** Make sure the database is open. If it is not, then open it. If 4106** the database fails to open, print an error message and exit. 4107*/ 4108static void open_db(ShellState *p, int openFlags){ 4109 if( p->db==0 ){ 4110 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4111 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){ 4112 p->openMode = SHELL_OPEN_NORMAL; 4113 }else{ 4114 p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 4115 (openFlags & OPEN_DB_ZIPFILE)!=0); 4116 } 4117 } 4118 switch( p->openMode ){ 4119 case SHELL_OPEN_APPENDVFS: { 4120 sqlite3_open_v2(p->zDbFilename, &p->db, 4121 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs"); 4122 break; 4123 } 4124 case SHELL_OPEN_HEXDB: 4125 case SHELL_OPEN_DESERIALIZE: { 4126 sqlite3_open(0, &p->db); 4127 break; 4128 } 4129 case SHELL_OPEN_ZIPFILE: { 4130 sqlite3_open(":memory:", &p->db); 4131 break; 4132 } 4133 case SHELL_OPEN_READONLY: { 4134 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0); 4135 break; 4136 } 4137 case SHELL_OPEN_UNSPEC: 4138 case SHELL_OPEN_NORMAL: { 4139 sqlite3_open(p->zDbFilename, &p->db); 4140 break; 4141 } 4142 } 4143 globalDb = p->db; 4144 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4145 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4146 p->zDbFilename, sqlite3_errmsg(p->db)); 4147 if( openFlags & OPEN_DB_KEEPALIVE ){ 4148 sqlite3_open(":memory:", &p->db); 4149 return; 4150 } 4151 exit(1); 4152 } 4153#ifndef SQLITE_OMIT_LOAD_EXTENSION 4154 sqlite3_enable_load_extension(p->db, 1); 4155#endif 4156 sqlite3_fileio_init(p->db, 0, 0); 4157 sqlite3_shathree_init(p->db, 0, 0); 4158 sqlite3_completion_init(p->db, 0, 0); 4159#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4160 sqlite3_dbdata_init(p->db, 0, 0); 4161#endif 4162#ifdef SQLITE_HAVE_ZLIB 4163 sqlite3_zipfile_init(p->db, 0, 0); 4164 sqlite3_sqlar_init(p->db, 0, 0); 4165#endif 4166 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4167 shellAddSchemaName, 0, 0); 4168 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4169 shellModuleSchema, 0, 0); 4170 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4171 shellPutsFunc, 0, 0); 4172 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4173 shellEscapeCrnl, 0, 0); 4174 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4175 shellInt32, 0, 0); 4176 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 4177 shellIdQuote, 0, 0); 4178#ifndef SQLITE_NOHAVE_SYSTEM 4179 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4180 editFunc, 0, 0); 4181 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4182 editFunc, 0, 0); 4183#endif 4184 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4185 char *zSql = sqlite3_mprintf( 4186 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); 4187 sqlite3_exec(p->db, zSql, 0, 0, 0); 4188 sqlite3_free(zSql); 4189 } 4190#ifdef SQLITE_ENABLE_DESERIALIZE 4191 else 4192 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4193 int rc; 4194 int nData = 0; 4195 unsigned char *aData; 4196 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4197 aData = (unsigned char*)readFile(p->zDbFilename, &nData); 4198 }else{ 4199 aData = readHexDb(p, &nData); 4200 if( aData==0 ){ 4201 return; 4202 } 4203 } 4204 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4205 SQLITE_DESERIALIZE_RESIZEABLE | 4206 SQLITE_DESERIALIZE_FREEONCLOSE); 4207 if( rc ){ 4208 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4209 } 4210 if( p->szMax>0 ){ 4211 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4212 } 4213 } 4214#endif 4215 } 4216} 4217 4218/* 4219** Attempt to close the databaes connection. Report errors. 4220*/ 4221void close_db(sqlite3 *db){ 4222 int rc = sqlite3_close(db); 4223 if( rc ){ 4224 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4225 rc, sqlite3_errmsg(db)); 4226 } 4227} 4228 4229#if HAVE_READLINE || HAVE_EDITLINE 4230/* 4231** Readline completion callbacks 4232*/ 4233static char *readline_completion_generator(const char *text, int state){ 4234 static sqlite3_stmt *pStmt = 0; 4235 char *zRet; 4236 if( state==0 ){ 4237 char *zSql; 4238 sqlite3_finalize(pStmt); 4239 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4240 " FROM completion(%Q) ORDER BY 1", text); 4241 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4242 sqlite3_free(zSql); 4243 } 4244 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4245 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); 4246 }else{ 4247 sqlite3_finalize(pStmt); 4248 pStmt = 0; 4249 zRet = 0; 4250 } 4251 return zRet; 4252} 4253static char **readline_completion(const char *zText, int iStart, int iEnd){ 4254 rl_attempted_completion_over = 1; 4255 return rl_completion_matches(zText, readline_completion_generator); 4256} 4257 4258#elif HAVE_LINENOISE 4259/* 4260** Linenoise completion callback 4261*/ 4262static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4263 int nLine = strlen30(zLine); 4264 int i, iStart; 4265 sqlite3_stmt *pStmt = 0; 4266 char *zSql; 4267 char zBuf[1000]; 4268 4269 if( nLine>sizeof(zBuf)-30 ) return; 4270 if( zLine[0]=='.' || zLine[0]=='#') return; 4271 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4272 if( i==nLine-1 ) return; 4273 iStart = i+1; 4274 memcpy(zBuf, zLine, iStart); 4275 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4276 " FROM completion(%Q,%Q) ORDER BY 1", 4277 &zLine[iStart], zLine); 4278 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4279 sqlite3_free(zSql); 4280 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4281 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4282 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4283 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4284 if( iStart+nCompletion < sizeof(zBuf)-1 ){ 4285 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4286 linenoiseAddCompletion(lc, zBuf); 4287 } 4288 } 4289 sqlite3_finalize(pStmt); 4290} 4291#endif 4292 4293/* 4294** Do C-language style dequoting. 4295** 4296** \a -> alarm 4297** \b -> backspace 4298** \t -> tab 4299** \n -> newline 4300** \v -> vertical tab 4301** \f -> form feed 4302** \r -> carriage return 4303** \s -> space 4304** \" -> " 4305** \' -> ' 4306** \\ -> backslash 4307** \NNN -> ascii character NNN in octal 4308*/ 4309static void resolve_backslashes(char *z){ 4310 int i, j; 4311 char c; 4312 while( *z && *z!='\\' ) z++; 4313 for(i=j=0; (c = z[i])!=0; i++, j++){ 4314 if( c=='\\' && z[i+1]!=0 ){ 4315 c = z[++i]; 4316 if( c=='a' ){ 4317 c = '\a'; 4318 }else if( c=='b' ){ 4319 c = '\b'; 4320 }else if( c=='t' ){ 4321 c = '\t'; 4322 }else if( c=='n' ){ 4323 c = '\n'; 4324 }else if( c=='v' ){ 4325 c = '\v'; 4326 }else if( c=='f' ){ 4327 c = '\f'; 4328 }else if( c=='r' ){ 4329 c = '\r'; 4330 }else if( c=='"' ){ 4331 c = '"'; 4332 }else if( c=='\'' ){ 4333 c = '\''; 4334 }else if( c=='\\' ){ 4335 c = '\\'; 4336 }else if( c>='0' && c<='7' ){ 4337 c -= '0'; 4338 if( z[i+1]>='0' && z[i+1]<='7' ){ 4339 i++; 4340 c = (c<<3) + z[i] - '0'; 4341 if( z[i+1]>='0' && z[i+1]<='7' ){ 4342 i++; 4343 c = (c<<3) + z[i] - '0'; 4344 } 4345 } 4346 } 4347 } 4348 z[j] = c; 4349 } 4350 if( j<i ) z[j] = 0; 4351} 4352 4353/* 4354** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4355** for TRUE and FALSE. Return the integer value if appropriate. 4356*/ 4357static int booleanValue(const char *zArg){ 4358 int i; 4359 if( zArg[0]=='0' && zArg[1]=='x' ){ 4360 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4361 }else{ 4362 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4363 } 4364 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4365 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4366 return 1; 4367 } 4368 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4369 return 0; 4370 } 4371 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4372 zArg); 4373 return 0; 4374} 4375 4376/* 4377** Set or clear a shell flag according to a boolean value. 4378*/ 4379static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4380 if( booleanValue(zArg) ){ 4381 ShellSetFlag(p, mFlag); 4382 }else{ 4383 ShellClearFlag(p, mFlag); 4384 } 4385} 4386 4387/* 4388** Close an output file, assuming it is not stderr or stdout 4389*/ 4390static void output_file_close(FILE *f){ 4391 if( f && f!=stdout && f!=stderr ) fclose(f); 4392} 4393 4394/* 4395** Try to open an output file. The names "stdout" and "stderr" are 4396** recognized and do the right thing. NULL is returned if the output 4397** filename is "off". 4398*/ 4399static FILE *output_file_open(const char *zFile, int bTextMode){ 4400 FILE *f; 4401 if( strcmp(zFile,"stdout")==0 ){ 4402 f = stdout; 4403 }else if( strcmp(zFile, "stderr")==0 ){ 4404 f = stderr; 4405 }else if( strcmp(zFile, "off")==0 ){ 4406 f = 0; 4407 }else{ 4408 f = fopen(zFile, bTextMode ? "w" : "wb"); 4409 if( f==0 ){ 4410 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 4411 } 4412 } 4413 return f; 4414} 4415 4416#ifndef SQLITE_OMIT_TRACE 4417/* 4418** A routine for handling output from sqlite3_trace(). 4419*/ 4420static int sql_trace_callback( 4421 unsigned mType, /* The trace type */ 4422 void *pArg, /* The ShellState pointer */ 4423 void *pP, /* Usually a pointer to sqlite_stmt */ 4424 void *pX /* Auxiliary output */ 4425){ 4426 ShellState *p = (ShellState*)pArg; 4427 sqlite3_stmt *pStmt; 4428 const char *zSql; 4429 int nSql; 4430 if( p->traceOut==0 ) return 0; 4431 if( mType==SQLITE_TRACE_CLOSE ){ 4432 utf8_printf(p->traceOut, "-- closing database connection\n"); 4433 return 0; 4434 } 4435 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 4436 zSql = (const char*)pX; 4437 }else{ 4438 pStmt = (sqlite3_stmt*)pP; 4439 switch( p->eTraceType ){ 4440 case SHELL_TRACE_EXPANDED: { 4441 zSql = sqlite3_expanded_sql(pStmt); 4442 break; 4443 } 4444#ifdef SQLITE_ENABLE_NORMALIZE 4445 case SHELL_TRACE_NORMALIZED: { 4446 zSql = sqlite3_normalized_sql(pStmt); 4447 break; 4448 } 4449#endif 4450 default: { 4451 zSql = sqlite3_sql(pStmt); 4452 break; 4453 } 4454 } 4455 } 4456 if( zSql==0 ) return 0; 4457 nSql = strlen30(zSql); 4458 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 4459 switch( mType ){ 4460 case SQLITE_TRACE_ROW: 4461 case SQLITE_TRACE_STMT: { 4462 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 4463 break; 4464 } 4465 case SQLITE_TRACE_PROFILE: { 4466 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 4467 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 4468 break; 4469 } 4470 } 4471 return 0; 4472} 4473#endif 4474 4475/* 4476** A no-op routine that runs with the ".breakpoint" doc-command. This is 4477** a useful spot to set a debugger breakpoint. 4478*/ 4479static void test_breakpoint(void){ 4480 static int nCall = 0; 4481 nCall++; 4482} 4483 4484/* 4485** An object used to read a CSV and other files for import. 4486*/ 4487typedef struct ImportCtx ImportCtx; 4488struct ImportCtx { 4489 const char *zFile; /* Name of the input file */ 4490 FILE *in; /* Read the CSV text from this input stream */ 4491 char *z; /* Accumulated text for a field */ 4492 int n; /* Number of bytes in z */ 4493 int nAlloc; /* Space allocated for z[] */ 4494 int nLine; /* Current line number */ 4495 int bNotFirst; /* True if one or more bytes already read */ 4496 int cTerm; /* Character that terminated the most recent field */ 4497 int cColSep; /* The column separator character. (Usually ",") */ 4498 int cRowSep; /* The row separator character. (Usually "\n") */ 4499}; 4500 4501/* Append a single byte to z[] */ 4502static void import_append_char(ImportCtx *p, int c){ 4503 if( p->n+1>=p->nAlloc ){ 4504 p->nAlloc += p->nAlloc + 100; 4505 p->z = sqlite3_realloc64(p->z, p->nAlloc); 4506 if( p->z==0 ) shell_out_of_memory(); 4507 } 4508 p->z[p->n++] = (char)c; 4509} 4510 4511/* Read a single field of CSV text. Compatible with rfc4180 and extended 4512** with the option of having a separator other than ",". 4513** 4514** + Input comes from p->in. 4515** + Store results in p->z of length p->n. Space to hold p->z comes 4516** from sqlite3_malloc64(). 4517** + Use p->cSep as the column separator. The default is ",". 4518** + Use p->rSep as the row separator. The default is "\n". 4519** + Keep track of the line number in p->nLine. 4520** + Store the character that terminates the field in p->cTerm. Store 4521** EOF on end-of-file. 4522** + Report syntax errors on stderr 4523*/ 4524static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 4525 int c; 4526 int cSep = p->cColSep; 4527 int rSep = p->cRowSep; 4528 p->n = 0; 4529 c = fgetc(p->in); 4530 if( c==EOF || seenInterrupt ){ 4531 p->cTerm = EOF; 4532 return 0; 4533 } 4534 if( c=='"' ){ 4535 int pc, ppc; 4536 int startLine = p->nLine; 4537 int cQuote = c; 4538 pc = ppc = 0; 4539 while( 1 ){ 4540 c = fgetc(p->in); 4541 if( c==rSep ) p->nLine++; 4542 if( c==cQuote ){ 4543 if( pc==cQuote ){ 4544 pc = 0; 4545 continue; 4546 } 4547 } 4548 if( (c==cSep && pc==cQuote) 4549 || (c==rSep && pc==cQuote) 4550 || (c==rSep && pc=='\r' && ppc==cQuote) 4551 || (c==EOF && pc==cQuote) 4552 ){ 4553 do{ p->n--; }while( p->z[p->n]!=cQuote ); 4554 p->cTerm = c; 4555 break; 4556 } 4557 if( pc==cQuote && c!='\r' ){ 4558 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 4559 p->zFile, p->nLine, cQuote); 4560 } 4561 if( c==EOF ){ 4562 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 4563 p->zFile, startLine, cQuote); 4564 p->cTerm = c; 4565 break; 4566 } 4567 import_append_char(p, c); 4568 ppc = pc; 4569 pc = c; 4570 } 4571 }else{ 4572 /* If this is the first field being parsed and it begins with the 4573 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 4574 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 4575 import_append_char(p, c); 4576 c = fgetc(p->in); 4577 if( (c&0xff)==0xbb ){ 4578 import_append_char(p, c); 4579 c = fgetc(p->in); 4580 if( (c&0xff)==0xbf ){ 4581 p->bNotFirst = 1; 4582 p->n = 0; 4583 return csv_read_one_field(p); 4584 } 4585 } 4586 } 4587 while( c!=EOF && c!=cSep && c!=rSep ){ 4588 import_append_char(p, c); 4589 c = fgetc(p->in); 4590 } 4591 if( c==rSep ){ 4592 p->nLine++; 4593 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 4594 } 4595 p->cTerm = c; 4596 } 4597 if( p->z ) p->z[p->n] = 0; 4598 p->bNotFirst = 1; 4599 return p->z; 4600} 4601 4602/* Read a single field of ASCII delimited text. 4603** 4604** + Input comes from p->in. 4605** + Store results in p->z of length p->n. Space to hold p->z comes 4606** from sqlite3_malloc64(). 4607** + Use p->cSep as the column separator. The default is "\x1F". 4608** + Use p->rSep as the row separator. The default is "\x1E". 4609** + Keep track of the row number in p->nLine. 4610** + Store the character that terminates the field in p->cTerm. Store 4611** EOF on end-of-file. 4612** + Report syntax errors on stderr 4613*/ 4614static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 4615 int c; 4616 int cSep = p->cColSep; 4617 int rSep = p->cRowSep; 4618 p->n = 0; 4619 c = fgetc(p->in); 4620 if( c==EOF || seenInterrupt ){ 4621 p->cTerm = EOF; 4622 return 0; 4623 } 4624 while( c!=EOF && c!=cSep && c!=rSep ){ 4625 import_append_char(p, c); 4626 c = fgetc(p->in); 4627 } 4628 if( c==rSep ){ 4629 p->nLine++; 4630 } 4631 p->cTerm = c; 4632 if( p->z ) p->z[p->n] = 0; 4633 return p->z; 4634} 4635 4636/* 4637** Try to transfer data for table zTable. If an error is seen while 4638** moving forward, try to go backwards. The backwards movement won't 4639** work for WITHOUT ROWID tables. 4640*/ 4641static void tryToCloneData( 4642 ShellState *p, 4643 sqlite3 *newDb, 4644 const char *zTable 4645){ 4646 sqlite3_stmt *pQuery = 0; 4647 sqlite3_stmt *pInsert = 0; 4648 char *zQuery = 0; 4649 char *zInsert = 0; 4650 int rc; 4651 int i, j, n; 4652 int nTable = strlen30(zTable); 4653 int k = 0; 4654 int cnt = 0; 4655 const int spinRate = 10000; 4656 4657 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 4658 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4659 if( rc ){ 4660 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4661 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4662 zQuery); 4663 goto end_data_xfer; 4664 } 4665 n = sqlite3_column_count(pQuery); 4666 zInsert = sqlite3_malloc64(200 + nTable + n*3); 4667 if( zInsert==0 ) shell_out_of_memory(); 4668 sqlite3_snprintf(200+nTable,zInsert, 4669 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 4670 i = strlen30(zInsert); 4671 for(j=1; j<n; j++){ 4672 memcpy(zInsert+i, ",?", 2); 4673 i += 2; 4674 } 4675 memcpy(zInsert+i, ");", 3); 4676 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 4677 if( rc ){ 4678 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4679 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 4680 zQuery); 4681 goto end_data_xfer; 4682 } 4683 for(k=0; k<2; k++){ 4684 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4685 for(i=0; i<n; i++){ 4686 switch( sqlite3_column_type(pQuery, i) ){ 4687 case SQLITE_NULL: { 4688 sqlite3_bind_null(pInsert, i+1); 4689 break; 4690 } 4691 case SQLITE_INTEGER: { 4692 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 4693 break; 4694 } 4695 case SQLITE_FLOAT: { 4696 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 4697 break; 4698 } 4699 case SQLITE_TEXT: { 4700 sqlite3_bind_text(pInsert, i+1, 4701 (const char*)sqlite3_column_text(pQuery,i), 4702 -1, SQLITE_STATIC); 4703 break; 4704 } 4705 case SQLITE_BLOB: { 4706 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 4707 sqlite3_column_bytes(pQuery,i), 4708 SQLITE_STATIC); 4709 break; 4710 } 4711 } 4712 } /* End for */ 4713 rc = sqlite3_step(pInsert); 4714 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 4715 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 4716 sqlite3_errmsg(newDb)); 4717 } 4718 sqlite3_reset(pInsert); 4719 cnt++; 4720 if( (cnt%spinRate)==0 ){ 4721 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 4722 fflush(stdout); 4723 } 4724 } /* End while */ 4725 if( rc==SQLITE_DONE ) break; 4726 sqlite3_finalize(pQuery); 4727 sqlite3_free(zQuery); 4728 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 4729 zTable); 4730 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4731 if( rc ){ 4732 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 4733 break; 4734 } 4735 } /* End for(k=0...) */ 4736 4737end_data_xfer: 4738 sqlite3_finalize(pQuery); 4739 sqlite3_finalize(pInsert); 4740 sqlite3_free(zQuery); 4741 sqlite3_free(zInsert); 4742} 4743 4744 4745/* 4746** Try to transfer all rows of the schema that match zWhere. For 4747** each row, invoke xForEach() on the object defined by that row. 4748** If an error is encountered while moving forward through the 4749** sqlite_master table, try again moving backwards. 4750*/ 4751static void tryToCloneSchema( 4752 ShellState *p, 4753 sqlite3 *newDb, 4754 const char *zWhere, 4755 void (*xForEach)(ShellState*,sqlite3*,const char*) 4756){ 4757 sqlite3_stmt *pQuery = 0; 4758 char *zQuery = 0; 4759 int rc; 4760 const unsigned char *zName; 4761 const unsigned char *zSql; 4762 char *zErrMsg = 0; 4763 4764 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4765 " WHERE %s", zWhere); 4766 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4767 if( rc ){ 4768 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4769 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4770 zQuery); 4771 goto end_schema_xfer; 4772 } 4773 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4774 zName = sqlite3_column_text(pQuery, 0); 4775 zSql = sqlite3_column_text(pQuery, 1); 4776 printf("%s... ", zName); fflush(stdout); 4777 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4778 if( zErrMsg ){ 4779 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4780 sqlite3_free(zErrMsg); 4781 zErrMsg = 0; 4782 } 4783 if( xForEach ){ 4784 xForEach(p, newDb, (const char*)zName); 4785 } 4786 printf("done\n"); 4787 } 4788 if( rc!=SQLITE_DONE ){ 4789 sqlite3_finalize(pQuery); 4790 sqlite3_free(zQuery); 4791 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4792 " WHERE %s ORDER BY rowid DESC", zWhere); 4793 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4794 if( rc ){ 4795 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4796 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4797 zQuery); 4798 goto end_schema_xfer; 4799 } 4800 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4801 zName = sqlite3_column_text(pQuery, 0); 4802 zSql = sqlite3_column_text(pQuery, 1); 4803 printf("%s... ", zName); fflush(stdout); 4804 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4805 if( zErrMsg ){ 4806 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4807 sqlite3_free(zErrMsg); 4808 zErrMsg = 0; 4809 } 4810 if( xForEach ){ 4811 xForEach(p, newDb, (const char*)zName); 4812 } 4813 printf("done\n"); 4814 } 4815 } 4816end_schema_xfer: 4817 sqlite3_finalize(pQuery); 4818 sqlite3_free(zQuery); 4819} 4820 4821/* 4822** Open a new database file named "zNewDb". Try to recover as much information 4823** as possible out of the main database (which might be corrupt) and write it 4824** into zNewDb. 4825*/ 4826static void tryToClone(ShellState *p, const char *zNewDb){ 4827 int rc; 4828 sqlite3 *newDb = 0; 4829 if( access(zNewDb,0)==0 ){ 4830 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 4831 return; 4832 } 4833 rc = sqlite3_open(zNewDb, &newDb); 4834 if( rc ){ 4835 utf8_printf(stderr, "Cannot create output database: %s\n", 4836 sqlite3_errmsg(newDb)); 4837 }else{ 4838 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 4839 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 4840 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 4841 tryToCloneSchema(p, newDb, "type!='table'", 0); 4842 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 4843 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 4844 } 4845 close_db(newDb); 4846} 4847 4848/* 4849** Change the output file back to stdout. 4850** 4851** If the p->doXdgOpen flag is set, that means the output was being 4852** redirected to a temporary file named by p->zTempFile. In that case, 4853** launch start/open/xdg-open on that temporary file. 4854*/ 4855static void output_reset(ShellState *p){ 4856 if( p->outfile[0]=='|' ){ 4857#ifndef SQLITE_OMIT_POPEN 4858 pclose(p->out); 4859#endif 4860 }else{ 4861 output_file_close(p->out); 4862#ifndef SQLITE_NOHAVE_SYSTEM 4863 if( p->doXdgOpen ){ 4864 const char *zXdgOpenCmd = 4865#if defined(_WIN32) 4866 "start"; 4867#elif defined(__APPLE__) 4868 "open"; 4869#else 4870 "xdg-open"; 4871#endif 4872 char *zCmd; 4873 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 4874 if( system(zCmd) ){ 4875 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 4876 } 4877 sqlite3_free(zCmd); 4878 outputModePop(p); 4879 p->doXdgOpen = 0; 4880 sqlite3_sleep(100); 4881 } 4882#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 4883 } 4884 p->outfile[0] = 0; 4885 p->out = stdout; 4886} 4887 4888/* 4889** Run an SQL command and return the single integer result. 4890*/ 4891static int db_int(ShellState *p, const char *zSql){ 4892 sqlite3_stmt *pStmt; 4893 int res = 0; 4894 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4895 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 4896 res = sqlite3_column_int(pStmt,0); 4897 } 4898 sqlite3_finalize(pStmt); 4899 return res; 4900} 4901 4902/* 4903** Convert a 2-byte or 4-byte big-endian integer into a native integer 4904*/ 4905static unsigned int get2byteInt(unsigned char *a){ 4906 return (a[0]<<8) + a[1]; 4907} 4908static unsigned int get4byteInt(unsigned char *a){ 4909 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 4910} 4911 4912/* 4913** Implementation of the ".info" command. 4914** 4915** Return 1 on error, 2 to exit, and 0 otherwise. 4916*/ 4917static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 4918 static const struct { const char *zName; int ofst; } aField[] = { 4919 { "file change counter:", 24 }, 4920 { "database page count:", 28 }, 4921 { "freelist page count:", 36 }, 4922 { "schema cookie:", 40 }, 4923 { "schema format:", 44 }, 4924 { "default cache size:", 48 }, 4925 { "autovacuum top root:", 52 }, 4926 { "incremental vacuum:", 64 }, 4927 { "text encoding:", 56 }, 4928 { "user version:", 60 }, 4929 { "application id:", 68 }, 4930 { "software version:", 96 }, 4931 }; 4932 static const struct { const char *zName; const char *zSql; } aQuery[] = { 4933 { "number of tables:", 4934 "SELECT count(*) FROM %s WHERE type='table'" }, 4935 { "number of indexes:", 4936 "SELECT count(*) FROM %s WHERE type='index'" }, 4937 { "number of triggers:", 4938 "SELECT count(*) FROM %s WHERE type='trigger'" }, 4939 { "number of views:", 4940 "SELECT count(*) FROM %s WHERE type='view'" }, 4941 { "schema size:", 4942 "SELECT total(length(sql)) FROM %s" }, 4943 }; 4944 int i, rc; 4945 unsigned iDataVersion; 4946 char *zSchemaTab; 4947 char *zDb = nArg>=2 ? azArg[1] : "main"; 4948 sqlite3_stmt *pStmt = 0; 4949 unsigned char aHdr[100]; 4950 open_db(p, 0); 4951 if( p->db==0 ) return 1; 4952 rc = sqlite3_prepare_v2(p->db, 4953 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 4954 -1, &pStmt, 0); 4955 if( rc ){ 4956 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){ 4957 utf8_printf(stderr, "the \".dbinfo\" command requires the " 4958 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n"); 4959 }else{ 4960 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 4961 } 4962 sqlite3_finalize(pStmt); 4963 return 1; 4964 } 4965 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 4966 if( sqlite3_step(pStmt)==SQLITE_ROW 4967 && sqlite3_column_bytes(pStmt,0)>100 4968 ){ 4969 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 4970 sqlite3_finalize(pStmt); 4971 }else{ 4972 raw_printf(stderr, "unable to read database header\n"); 4973 sqlite3_finalize(pStmt); 4974 return 1; 4975 } 4976 i = get2byteInt(aHdr+16); 4977 if( i==1 ) i = 65536; 4978 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 4979 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 4980 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 4981 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 4982 for(i=0; i<ArraySize(aField); i++){ 4983 int ofst = aField[i].ofst; 4984 unsigned int val = get4byteInt(aHdr + ofst); 4985 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 4986 switch( ofst ){ 4987 case 56: { 4988 if( val==1 ) raw_printf(p->out, " (utf8)"); 4989 if( val==2 ) raw_printf(p->out, " (utf16le)"); 4990 if( val==3 ) raw_printf(p->out, " (utf16be)"); 4991 } 4992 } 4993 raw_printf(p->out, "\n"); 4994 } 4995 if( zDb==0 ){ 4996 zSchemaTab = sqlite3_mprintf("main.sqlite_master"); 4997 }else if( strcmp(zDb,"temp")==0 ){ 4998 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); 4999 }else{ 5000 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); 5001 } 5002 for(i=0; i<ArraySize(aQuery); i++){ 5003 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 5004 int val = db_int(p, zSql); 5005 sqlite3_free(zSql); 5006 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 5007 } 5008 sqlite3_free(zSchemaTab); 5009 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 5010 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 5011 return 0; 5012} 5013 5014/* 5015** Print the current sqlite3_errmsg() value to stderr and return 1. 5016*/ 5017static int shellDatabaseError(sqlite3 *db){ 5018 const char *zErr = sqlite3_errmsg(db); 5019 utf8_printf(stderr, "Error: %s\n", zErr); 5020 return 1; 5021} 5022 5023/* 5024** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 5025** if they match and FALSE (0) if they do not match. 5026** 5027** Globbing rules: 5028** 5029** '*' Matches any sequence of zero or more characters. 5030** 5031** '?' Matches exactly one character. 5032** 5033** [...] Matches one character from the enclosed list of 5034** characters. 5035** 5036** [^...] Matches one character not in the enclosed list. 5037** 5038** '#' Matches any sequence of one or more digits with an 5039** optional + or - sign in front 5040** 5041** ' ' Any span of whitespace matches any other span of 5042** whitespace. 5043** 5044** Extra whitespace at the end of z[] is ignored. 5045*/ 5046static int testcase_glob(const char *zGlob, const char *z){ 5047 int c, c2; 5048 int invert; 5049 int seen; 5050 5051 while( (c = (*(zGlob++)))!=0 ){ 5052 if( IsSpace(c) ){ 5053 if( !IsSpace(*z) ) return 0; 5054 while( IsSpace(*zGlob) ) zGlob++; 5055 while( IsSpace(*z) ) z++; 5056 }else if( c=='*' ){ 5057 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5058 if( c=='?' && (*(z++))==0 ) return 0; 5059 } 5060 if( c==0 ){ 5061 return 1; 5062 }else if( c=='[' ){ 5063 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5064 z++; 5065 } 5066 return (*z)!=0; 5067 } 5068 while( (c2 = (*(z++)))!=0 ){ 5069 while( c2!=c ){ 5070 c2 = *(z++); 5071 if( c2==0 ) return 0; 5072 } 5073 if( testcase_glob(zGlob,z) ) return 1; 5074 } 5075 return 0; 5076 }else if( c=='?' ){ 5077 if( (*(z++))==0 ) return 0; 5078 }else if( c=='[' ){ 5079 int prior_c = 0; 5080 seen = 0; 5081 invert = 0; 5082 c = *(z++); 5083 if( c==0 ) return 0; 5084 c2 = *(zGlob++); 5085 if( c2=='^' ){ 5086 invert = 1; 5087 c2 = *(zGlob++); 5088 } 5089 if( c2==']' ){ 5090 if( c==']' ) seen = 1; 5091 c2 = *(zGlob++); 5092 } 5093 while( c2 && c2!=']' ){ 5094 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5095 c2 = *(zGlob++); 5096 if( c>=prior_c && c<=c2 ) seen = 1; 5097 prior_c = 0; 5098 }else{ 5099 if( c==c2 ){ 5100 seen = 1; 5101 } 5102 prior_c = c2; 5103 } 5104 c2 = *(zGlob++); 5105 } 5106 if( c2==0 || (seen ^ invert)==0 ) return 0; 5107 }else if( c=='#' ){ 5108 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5109 if( !IsDigit(z[0]) ) return 0; 5110 z++; 5111 while( IsDigit(z[0]) ){ z++; } 5112 }else{ 5113 if( c!=(*(z++)) ) return 0; 5114 } 5115 } 5116 while( IsSpace(*z) ){ z++; } 5117 return *z==0; 5118} 5119 5120 5121/* 5122** Compare the string as a command-line option with either one or two 5123** initial "-" characters. 5124*/ 5125static int optionMatch(const char *zStr, const char *zOpt){ 5126 if( zStr[0]!='-' ) return 0; 5127 zStr++; 5128 if( zStr[0]=='-' ) zStr++; 5129 return strcmp(zStr, zOpt)==0; 5130} 5131 5132/* 5133** Delete a file. 5134*/ 5135int shellDeleteFile(const char *zFilename){ 5136 int rc; 5137#ifdef _WIN32 5138 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5139 rc = _wunlink(z); 5140 sqlite3_free(z); 5141#else 5142 rc = unlink(zFilename); 5143#endif 5144 return rc; 5145} 5146 5147/* 5148** Try to delete the temporary file (if there is one) and free the 5149** memory used to hold the name of the temp file. 5150*/ 5151static void clearTempFile(ShellState *p){ 5152 if( p->zTempFile==0 ) return; 5153 if( p->doXdgOpen ) return; 5154 if( shellDeleteFile(p->zTempFile) ) return; 5155 sqlite3_free(p->zTempFile); 5156 p->zTempFile = 0; 5157} 5158 5159/* 5160** Create a new temp file name with the given suffix. 5161*/ 5162static void newTempFile(ShellState *p, const char *zSuffix){ 5163 clearTempFile(p); 5164 sqlite3_free(p->zTempFile); 5165 p->zTempFile = 0; 5166 if( p->db ){ 5167 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5168 } 5169 if( p->zTempFile==0 ){ 5170 sqlite3_uint64 r; 5171 sqlite3_randomness(sizeof(r), &r); 5172 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix); 5173 }else{ 5174 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5175 } 5176 if( p->zTempFile==0 ){ 5177 raw_printf(stderr, "out of memory\n"); 5178 exit(1); 5179 } 5180} 5181 5182 5183/* 5184** The implementation of SQL scalar function fkey_collate_clause(), used 5185** by the ".lint fkey-indexes" command. This scalar function is always 5186** called with four arguments - the parent table name, the parent column name, 5187** the child table name and the child column name. 5188** 5189** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5190** 5191** If either of the named tables or columns do not exist, this function 5192** returns an empty string. An empty string is also returned if both tables 5193** and columns exist but have the same default collation sequence. Or, 5194** if both exist but the default collation sequences are different, this 5195** function returns the string " COLLATE <parent-collation>", where 5196** <parent-collation> is the default collation sequence of the parent column. 5197*/ 5198static void shellFkeyCollateClause( 5199 sqlite3_context *pCtx, 5200 int nVal, 5201 sqlite3_value **apVal 5202){ 5203 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5204 const char *zParent; 5205 const char *zParentCol; 5206 const char *zParentSeq; 5207 const char *zChild; 5208 const char *zChildCol; 5209 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5210 int rc; 5211 5212 assert( nVal==4 ); 5213 zParent = (const char*)sqlite3_value_text(apVal[0]); 5214 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5215 zChild = (const char*)sqlite3_value_text(apVal[2]); 5216 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5217 5218 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5219 rc = sqlite3_table_column_metadata( 5220 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5221 ); 5222 if( rc==SQLITE_OK ){ 5223 rc = sqlite3_table_column_metadata( 5224 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5225 ); 5226 } 5227 5228 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5229 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5230 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5231 sqlite3_free(z); 5232 } 5233} 5234 5235 5236/* 5237** The implementation of dot-command ".lint fkey-indexes". 5238*/ 5239static int lintFkeyIndexes( 5240 ShellState *pState, /* Current shell tool state */ 5241 char **azArg, /* Array of arguments passed to dot command */ 5242 int nArg /* Number of entries in azArg[] */ 5243){ 5244 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5245 FILE *out = pState->out; /* Stream to write non-error output to */ 5246 int bVerbose = 0; /* If -verbose is present */ 5247 int bGroupByParent = 0; /* If -groupbyparent is present */ 5248 int i; /* To iterate through azArg[] */ 5249 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5250 int rc; /* Return code */ 5251 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5252 5253 /* 5254 ** This SELECT statement returns one row for each foreign key constraint 5255 ** in the schema of the main database. The column values are: 5256 ** 5257 ** 0. The text of an SQL statement similar to: 5258 ** 5259 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5260 ** 5261 ** This SELECT is similar to the one that the foreign keys implementation 5262 ** needs to run internally on child tables. If there is an index that can 5263 ** be used to optimize this query, then it can also be used by the FK 5264 ** implementation to optimize DELETE or UPDATE statements on the parent 5265 ** table. 5266 ** 5267 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5268 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5269 ** contains an index that can be used to optimize the query. 5270 ** 5271 ** 2. Human readable text that describes the child table and columns. e.g. 5272 ** 5273 ** "child_table(child_key1, child_key2)" 5274 ** 5275 ** 3. Human readable text that describes the parent table and columns. e.g. 5276 ** 5277 ** "parent_table(parent_key1, parent_key2)" 5278 ** 5279 ** 4. A full CREATE INDEX statement for an index that could be used to 5280 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5281 ** 5282 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5283 ** 5284 ** 5. The name of the parent table. 5285 ** 5286 ** These six values are used by the C logic below to generate the report. 5287 */ 5288 const char *zSql = 5289 "SELECT " 5290 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5291 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5292 " || fkey_collate_clause(" 5293 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5294 ", " 5295 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" 5296 " || group_concat('*=?', ' AND ') || ')'" 5297 ", " 5298 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5299 ", " 5300 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5301 ", " 5302 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5303 " || ' ON ' || quote(s.name) || '('" 5304 " || group_concat(quote(f.[from]) ||" 5305 " fkey_collate_clause(" 5306 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5307 " || ');'" 5308 ", " 5309 " f.[table] " 5310 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f " 5311 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5312 "GROUP BY s.name, f.id " 5313 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5314 ; 5315 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; 5316 5317 for(i=2; i<nArg; i++){ 5318 int n = strlen30(azArg[i]); 5319 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5320 bVerbose = 1; 5321 } 5322 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5323 bGroupByParent = 1; 5324 zIndent = " "; 5325 } 5326 else{ 5327 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5328 azArg[0], azArg[1] 5329 ); 5330 return SQLITE_ERROR; 5331 } 5332 } 5333 5334 /* Register the fkey_collate_clause() SQL function */ 5335 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5336 0, shellFkeyCollateClause, 0, 0 5337 ); 5338 5339 5340 if( rc==SQLITE_OK ){ 5341 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5342 } 5343 if( rc==SQLITE_OK ){ 5344 sqlite3_bind_int(pSql, 1, bGroupByParent); 5345 } 5346 5347 if( rc==SQLITE_OK ){ 5348 int rc2; 5349 char *zPrev = 0; 5350 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5351 int res = -1; 5352 sqlite3_stmt *pExplain = 0; 5353 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5354 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 5355 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 5356 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 5357 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 5358 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 5359 5360 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 5361 if( rc!=SQLITE_OK ) break; 5362 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 5363 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 5364 res = ( 5365 0==sqlite3_strglob(zGlob, zPlan) 5366 || 0==sqlite3_strglob(zGlobIPK, zPlan) 5367 ); 5368 } 5369 rc = sqlite3_finalize(pExplain); 5370 if( rc!=SQLITE_OK ) break; 5371 5372 if( res<0 ){ 5373 raw_printf(stderr, "Error: internal error"); 5374 break; 5375 }else{ 5376 if( bGroupByParent 5377 && (bVerbose || res==0) 5378 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 5379 ){ 5380 raw_printf(out, "-- Parent table %s\n", zParent); 5381 sqlite3_free(zPrev); 5382 zPrev = sqlite3_mprintf("%s", zParent); 5383 } 5384 5385 if( res==0 ){ 5386 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 5387 }else if( bVerbose ){ 5388 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 5389 zIndent, zFrom, zTarget 5390 ); 5391 } 5392 } 5393 } 5394 sqlite3_free(zPrev); 5395 5396 if( rc!=SQLITE_OK ){ 5397 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5398 } 5399 5400 rc2 = sqlite3_finalize(pSql); 5401 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 5402 rc = rc2; 5403 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5404 } 5405 }else{ 5406 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5407 } 5408 5409 return rc; 5410} 5411 5412/* 5413** Implementation of ".lint" dot command. 5414*/ 5415static int lintDotCommand( 5416 ShellState *pState, /* Current shell tool state */ 5417 char **azArg, /* Array of arguments passed to dot command */ 5418 int nArg /* Number of entries in azArg[] */ 5419){ 5420 int n; 5421 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 5422 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 5423 return lintFkeyIndexes(pState, azArg, nArg); 5424 5425 usage: 5426 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 5427 raw_printf(stderr, "Where sub-commands are:\n"); 5428 raw_printf(stderr, " fkey-indexes\n"); 5429 return SQLITE_ERROR; 5430} 5431 5432#if !defined SQLITE_OMIT_VIRTUALTABLE 5433static void shellPrepare( 5434 sqlite3 *db, 5435 int *pRc, 5436 const char *zSql, 5437 sqlite3_stmt **ppStmt 5438){ 5439 *ppStmt = 0; 5440 if( *pRc==SQLITE_OK ){ 5441 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 5442 if( rc!=SQLITE_OK ){ 5443 raw_printf(stderr, "sql error: %s (%d)\n", 5444 sqlite3_errmsg(db), sqlite3_errcode(db) 5445 ); 5446 *pRc = rc; 5447 } 5448 } 5449} 5450 5451/* 5452** Create a prepared statement using printf-style arguments for the SQL. 5453** 5454** This routine is could be marked "static". But it is not always used, 5455** depending on compile-time options. By omitting the "static", we avoid 5456** nuisance compiler warnings about "defined but not used". 5457*/ 5458void shellPreparePrintf( 5459 sqlite3 *db, 5460 int *pRc, 5461 sqlite3_stmt **ppStmt, 5462 const char *zFmt, 5463 ... 5464){ 5465 *ppStmt = 0; 5466 if( *pRc==SQLITE_OK ){ 5467 va_list ap; 5468 char *z; 5469 va_start(ap, zFmt); 5470 z = sqlite3_vmprintf(zFmt, ap); 5471 va_end(ap); 5472 if( z==0 ){ 5473 *pRc = SQLITE_NOMEM; 5474 }else{ 5475 shellPrepare(db, pRc, z, ppStmt); 5476 sqlite3_free(z); 5477 } 5478 } 5479} 5480 5481/* Finalize the prepared statement created using shellPreparePrintf(). 5482** 5483** This routine is could be marked "static". But it is not always used, 5484** depending on compile-time options. By omitting the "static", we avoid 5485** nuisance compiler warnings about "defined but not used". 5486*/ 5487void shellFinalize( 5488 int *pRc, 5489 sqlite3_stmt *pStmt 5490){ 5491 if( pStmt ){ 5492 sqlite3 *db = sqlite3_db_handle(pStmt); 5493 int rc = sqlite3_finalize(pStmt); 5494 if( *pRc==SQLITE_OK ){ 5495 if( rc!=SQLITE_OK ){ 5496 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5497 } 5498 *pRc = rc; 5499 } 5500 } 5501} 5502 5503/* Reset the prepared statement created using shellPreparePrintf(). 5504** 5505** This routine is could be marked "static". But it is not always used, 5506** depending on compile-time options. By omitting the "static", we avoid 5507** nuisance compiler warnings about "defined but not used". 5508*/ 5509void shellReset( 5510 int *pRc, 5511 sqlite3_stmt *pStmt 5512){ 5513 int rc = sqlite3_reset(pStmt); 5514 if( *pRc==SQLITE_OK ){ 5515 if( rc!=SQLITE_OK ){ 5516 sqlite3 *db = sqlite3_db_handle(pStmt); 5517 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5518 } 5519 *pRc = rc; 5520 } 5521} 5522#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 5523 5524#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 5525/********************************************************************************* 5526** The ".archive" or ".ar" command. 5527*/ 5528/* 5529** Structure representing a single ".ar" command. 5530*/ 5531typedef struct ArCommand ArCommand; 5532struct ArCommand { 5533 u8 eCmd; /* An AR_CMD_* value */ 5534 u8 bVerbose; /* True if --verbose */ 5535 u8 bZip; /* True if the archive is a ZIP */ 5536 u8 bDryRun; /* True if --dry-run */ 5537 u8 bAppend; /* True if --append */ 5538 u8 fromCmdLine; /* Run from -A instead of .archive */ 5539 int nArg; /* Number of command arguments */ 5540 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 5541 const char *zFile; /* --file argument, or NULL */ 5542 const char *zDir; /* --directory argument, or NULL */ 5543 char **azArg; /* Array of command arguments */ 5544 ShellState *p; /* Shell state */ 5545 sqlite3 *db; /* Database containing the archive */ 5546}; 5547 5548/* 5549** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 5550*/ 5551static int arUsage(FILE *f){ 5552 showHelp(f,"archive"); 5553 return SQLITE_ERROR; 5554} 5555 5556/* 5557** Print an error message for the .ar command to stderr and return 5558** SQLITE_ERROR. 5559*/ 5560static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 5561 va_list ap; 5562 char *z; 5563 va_start(ap, zFmt); 5564 z = sqlite3_vmprintf(zFmt, ap); 5565 va_end(ap); 5566 utf8_printf(stderr, "Error: %s\n", z); 5567 if( pAr->fromCmdLine ){ 5568 utf8_printf(stderr, "Use \"-A\" for more help\n"); 5569 }else{ 5570 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 5571 } 5572 sqlite3_free(z); 5573 return SQLITE_ERROR; 5574} 5575 5576/* 5577** Values for ArCommand.eCmd. 5578*/ 5579#define AR_CMD_CREATE 1 5580#define AR_CMD_UPDATE 2 5581#define AR_CMD_INSERT 3 5582#define AR_CMD_EXTRACT 4 5583#define AR_CMD_LIST 5 5584#define AR_CMD_HELP 6 5585 5586/* 5587** Other (non-command) switches. 5588*/ 5589#define AR_SWITCH_VERBOSE 7 5590#define AR_SWITCH_FILE 8 5591#define AR_SWITCH_DIRECTORY 9 5592#define AR_SWITCH_APPEND 10 5593#define AR_SWITCH_DRYRUN 11 5594 5595static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 5596 switch( eSwitch ){ 5597 case AR_CMD_CREATE: 5598 case AR_CMD_EXTRACT: 5599 case AR_CMD_LIST: 5600 case AR_CMD_UPDATE: 5601 case AR_CMD_INSERT: 5602 case AR_CMD_HELP: 5603 if( pAr->eCmd ){ 5604 return arErrorMsg(pAr, "multiple command options"); 5605 } 5606 pAr->eCmd = eSwitch; 5607 break; 5608 5609 case AR_SWITCH_DRYRUN: 5610 pAr->bDryRun = 1; 5611 break; 5612 case AR_SWITCH_VERBOSE: 5613 pAr->bVerbose = 1; 5614 break; 5615 case AR_SWITCH_APPEND: 5616 pAr->bAppend = 1; 5617 /* Fall thru into --file */ 5618 case AR_SWITCH_FILE: 5619 pAr->zFile = zArg; 5620 break; 5621 case AR_SWITCH_DIRECTORY: 5622 pAr->zDir = zArg; 5623 break; 5624 } 5625 5626 return SQLITE_OK; 5627} 5628 5629/* 5630** Parse the command line for an ".ar" command. The results are written into 5631** structure (*pAr). SQLITE_OK is returned if the command line is parsed 5632** successfully, otherwise an error message is written to stderr and 5633** SQLITE_ERROR returned. 5634*/ 5635static int arParseCommand( 5636 char **azArg, /* Array of arguments passed to dot command */ 5637 int nArg, /* Number of entries in azArg[] */ 5638 ArCommand *pAr /* Populate this object */ 5639){ 5640 struct ArSwitch { 5641 const char *zLong; 5642 char cShort; 5643 u8 eSwitch; 5644 u8 bArg; 5645 } aSwitch[] = { 5646 { "create", 'c', AR_CMD_CREATE, 0 }, 5647 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 5648 { "insert", 'i', AR_CMD_INSERT, 0 }, 5649 { "list", 't', AR_CMD_LIST, 0 }, 5650 { "update", 'u', AR_CMD_UPDATE, 0 }, 5651 { "help", 'h', AR_CMD_HELP, 0 }, 5652 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 5653 { "file", 'f', AR_SWITCH_FILE, 1 }, 5654 { "append", 'a', AR_SWITCH_APPEND, 1 }, 5655 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 5656 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 5657 }; 5658 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 5659 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 5660 5661 if( nArg<=1 ){ 5662 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 5663 return arUsage(stderr); 5664 }else{ 5665 char *z = azArg[1]; 5666 if( z[0]!='-' ){ 5667 /* Traditional style [tar] invocation */ 5668 int i; 5669 int iArg = 2; 5670 for(i=0; z[i]; i++){ 5671 const char *zArg = 0; 5672 struct ArSwitch *pOpt; 5673 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5674 if( z[i]==pOpt->cShort ) break; 5675 } 5676 if( pOpt==pEnd ){ 5677 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5678 } 5679 if( pOpt->bArg ){ 5680 if( iArg>=nArg ){ 5681 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5682 } 5683 zArg = azArg[iArg++]; 5684 } 5685 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5686 } 5687 pAr->nArg = nArg-iArg; 5688 if( pAr->nArg>0 ){ 5689 pAr->azArg = &azArg[iArg]; 5690 } 5691 }else{ 5692 /* Non-traditional invocation */ 5693 int iArg; 5694 for(iArg=1; iArg<nArg; iArg++){ 5695 int n; 5696 z = azArg[iArg]; 5697 if( z[0]!='-' ){ 5698 /* All remaining command line words are command arguments. */ 5699 pAr->azArg = &azArg[iArg]; 5700 pAr->nArg = nArg-iArg; 5701 break; 5702 } 5703 n = strlen30(z); 5704 5705 if( z[1]!='-' ){ 5706 int i; 5707 /* One or more short options */ 5708 for(i=1; i<n; i++){ 5709 const char *zArg = 0; 5710 struct ArSwitch *pOpt; 5711 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5712 if( z[i]==pOpt->cShort ) break; 5713 } 5714 if( pOpt==pEnd ){ 5715 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5716 } 5717 if( pOpt->bArg ){ 5718 if( i<(n-1) ){ 5719 zArg = &z[i+1]; 5720 i = n; 5721 }else{ 5722 if( iArg>=(nArg-1) ){ 5723 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5724 } 5725 zArg = azArg[++iArg]; 5726 } 5727 } 5728 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5729 } 5730 }else if( z[2]=='\0' ){ 5731 /* A -- option, indicating that all remaining command line words 5732 ** are command arguments. */ 5733 pAr->azArg = &azArg[iArg+1]; 5734 pAr->nArg = nArg-iArg-1; 5735 break; 5736 }else{ 5737 /* A long option */ 5738 const char *zArg = 0; /* Argument for option, if any */ 5739 struct ArSwitch *pMatch = 0; /* Matching option */ 5740 struct ArSwitch *pOpt; /* Iterator */ 5741 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5742 const char *zLong = pOpt->zLong; 5743 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 5744 if( pMatch ){ 5745 return arErrorMsg(pAr, "ambiguous option: %s",z); 5746 }else{ 5747 pMatch = pOpt; 5748 } 5749 } 5750 } 5751 5752 if( pMatch==0 ){ 5753 return arErrorMsg(pAr, "unrecognized option: %s", z); 5754 } 5755 if( pMatch->bArg ){ 5756 if( iArg>=(nArg-1) ){ 5757 return arErrorMsg(pAr, "option requires an argument: %s", z); 5758 } 5759 zArg = azArg[++iArg]; 5760 } 5761 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 5762 } 5763 } 5764 } 5765 } 5766 5767 return SQLITE_OK; 5768} 5769 5770/* 5771** This function assumes that all arguments within the ArCommand.azArg[] 5772** array refer to archive members, as for the --extract or --list commands. 5773** It checks that each of them are present. If any specified file is not 5774** present in the archive, an error is printed to stderr and an error 5775** code returned. Otherwise, if all specified arguments are present in 5776** the archive, SQLITE_OK is returned. 5777** 5778** This function strips any trailing '/' characters from each argument. 5779** This is consistent with the way the [tar] command seems to work on 5780** Linux. 5781*/ 5782static int arCheckEntries(ArCommand *pAr){ 5783 int rc = SQLITE_OK; 5784 if( pAr->nArg ){ 5785 int i, j; 5786 sqlite3_stmt *pTest = 0; 5787 5788 shellPreparePrintf(pAr->db, &rc, &pTest, 5789 "SELECT name FROM %s WHERE name=$name", 5790 pAr->zSrcTable 5791 ); 5792 j = sqlite3_bind_parameter_index(pTest, "$name"); 5793 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 5794 char *z = pAr->azArg[i]; 5795 int n = strlen30(z); 5796 int bOk = 0; 5797 while( n>0 && z[n-1]=='/' ) n--; 5798 z[n] = '\0'; 5799 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 5800 if( SQLITE_ROW==sqlite3_step(pTest) ){ 5801 bOk = 1; 5802 } 5803 shellReset(&rc, pTest); 5804 if( rc==SQLITE_OK && bOk==0 ){ 5805 utf8_printf(stderr, "not found in archive: %s\n", z); 5806 rc = SQLITE_ERROR; 5807 } 5808 } 5809 shellFinalize(&rc, pTest); 5810 } 5811 return rc; 5812} 5813 5814/* 5815** Format a WHERE clause that can be used against the "sqlar" table to 5816** identify all archive members that match the command arguments held 5817** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 5818** The caller is responsible for eventually calling sqlite3_free() on 5819** any non-NULL (*pzWhere) value. 5820*/ 5821static void arWhereClause( 5822 int *pRc, 5823 ArCommand *pAr, 5824 char **pzWhere /* OUT: New WHERE clause */ 5825){ 5826 char *zWhere = 0; 5827 if( *pRc==SQLITE_OK ){ 5828 if( pAr->nArg==0 ){ 5829 zWhere = sqlite3_mprintf("1"); 5830 }else{ 5831 int i; 5832 const char *zSep = ""; 5833 for(i=0; i<pAr->nArg; i++){ 5834 const char *z = pAr->azArg[i]; 5835 zWhere = sqlite3_mprintf( 5836 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 5837 zWhere, zSep, z, strlen30(z)+1, z 5838 ); 5839 if( zWhere==0 ){ 5840 *pRc = SQLITE_NOMEM; 5841 break; 5842 } 5843 zSep = " OR "; 5844 } 5845 } 5846 } 5847 *pzWhere = zWhere; 5848} 5849 5850/* 5851** Implementation of .ar "lisT" command. 5852*/ 5853static int arListCommand(ArCommand *pAr){ 5854 const char *zSql = "SELECT %s FROM %s WHERE %s"; 5855 const char *azCols[] = { 5856 "name", 5857 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 5858 }; 5859 5860 char *zWhere = 0; 5861 sqlite3_stmt *pSql = 0; 5862 int rc; 5863 5864 rc = arCheckEntries(pAr); 5865 arWhereClause(&rc, pAr, &zWhere); 5866 5867 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 5868 pAr->zSrcTable, zWhere); 5869 if( pAr->bDryRun ){ 5870 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5871 }else{ 5872 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5873 if( pAr->bVerbose ){ 5874 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 5875 sqlite3_column_text(pSql, 0), 5876 sqlite3_column_int(pSql, 1), 5877 sqlite3_column_text(pSql, 2), 5878 sqlite3_column_text(pSql, 3) 5879 ); 5880 }else{ 5881 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5882 } 5883 } 5884 } 5885 shellFinalize(&rc, pSql); 5886 sqlite3_free(zWhere); 5887 return rc; 5888} 5889 5890 5891/* 5892** Implementation of .ar "eXtract" command. 5893*/ 5894static int arExtractCommand(ArCommand *pAr){ 5895 const char *zSql1 = 5896 "SELECT " 5897 " ($dir || name)," 5898 " writefile(($dir || name), %s, mode, mtime) " 5899 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 5900 " AND name NOT GLOB '*..[/\\]*'"; 5901 5902 const char *azExtraArg[] = { 5903 "sqlar_uncompress(data, sz)", 5904 "data" 5905 }; 5906 5907 sqlite3_stmt *pSql = 0; 5908 int rc = SQLITE_OK; 5909 char *zDir = 0; 5910 char *zWhere = 0; 5911 int i, j; 5912 5913 /* If arguments are specified, check that they actually exist within 5914 ** the archive before proceeding. And formulate a WHERE clause to 5915 ** match them. */ 5916 rc = arCheckEntries(pAr); 5917 arWhereClause(&rc, pAr, &zWhere); 5918 5919 if( rc==SQLITE_OK ){ 5920 if( pAr->zDir ){ 5921 zDir = sqlite3_mprintf("%s/", pAr->zDir); 5922 }else{ 5923 zDir = sqlite3_mprintf(""); 5924 } 5925 if( zDir==0 ) rc = SQLITE_NOMEM; 5926 } 5927 5928 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 5929 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 5930 ); 5931 5932 if( rc==SQLITE_OK ){ 5933 j = sqlite3_bind_parameter_index(pSql, "$dir"); 5934 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 5935 5936 /* Run the SELECT statement twice. The first time, writefile() is called 5937 ** for all archive members that should be extracted. The second time, 5938 ** only for the directories. This is because the timestamps for 5939 ** extracted directories must be reset after they are populated (as 5940 ** populating them changes the timestamp). */ 5941 for(i=0; i<2; i++){ 5942 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 5943 sqlite3_bind_int(pSql, j, i); 5944 if( pAr->bDryRun ){ 5945 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5946 }else{ 5947 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5948 if( i==0 && pAr->bVerbose ){ 5949 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5950 } 5951 } 5952 } 5953 shellReset(&rc, pSql); 5954 } 5955 shellFinalize(&rc, pSql); 5956 } 5957 5958 sqlite3_free(zDir); 5959 sqlite3_free(zWhere); 5960 return rc; 5961} 5962 5963/* 5964** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 5965*/ 5966static int arExecSql(ArCommand *pAr, const char *zSql){ 5967 int rc; 5968 if( pAr->bDryRun ){ 5969 utf8_printf(pAr->p->out, "%s\n", zSql); 5970 rc = SQLITE_OK; 5971 }else{ 5972 char *zErr = 0; 5973 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 5974 if( zErr ){ 5975 utf8_printf(stdout, "ERROR: %s\n", zErr); 5976 sqlite3_free(zErr); 5977 } 5978 } 5979 return rc; 5980} 5981 5982 5983/* 5984** Implementation of .ar "create", "insert", and "update" commands. 5985** 5986** create -> Create a new SQL archive 5987** insert -> Insert or reinsert all files listed 5988** update -> Insert files that have changed or that were not 5989** previously in the archive 5990** 5991** Create the "sqlar" table in the database if it does not already exist. 5992** Then add each file in the azFile[] array to the archive. Directories 5993** are added recursively. If argument bVerbose is non-zero, a message is 5994** printed on stdout for each file archived. 5995** 5996** The create command is the same as update, except that it drops 5997** any existing "sqlar" table before beginning. The "insert" command 5998** always overwrites every file named on the command-line, where as 5999** "update" only overwrites if the size or mtime or mode has changed. 6000*/ 6001static int arCreateOrUpdateCommand( 6002 ArCommand *pAr, /* Command arguments and options */ 6003 int bUpdate, /* true for a --create. */ 6004 int bOnlyIfChanged /* Only update if file has changed */ 6005){ 6006 const char *zCreate = 6007 "CREATE TABLE IF NOT EXISTS sqlar(\n" 6008 " name TEXT PRIMARY KEY, -- name of the file\n" 6009 " mode INT, -- access permissions\n" 6010 " mtime INT, -- last modification time\n" 6011 " sz INT, -- original file size\n" 6012 " data BLOB -- compressed content\n" 6013 ")"; 6014 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 6015 const char *zInsertFmt[2] = { 6016 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 6017 " SELECT\n" 6018 " %s,\n" 6019 " mode,\n" 6020 " mtime,\n" 6021 " CASE substr(lsmode(mode),1,1)\n" 6022 " WHEN '-' THEN length(data)\n" 6023 " WHEN 'd' THEN 0\n" 6024 " ELSE -1 END,\n" 6025 " sqlar_compress(data)\n" 6026 " FROM fsdir(%Q,%Q) AS disk\n" 6027 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6028 , 6029 "REPLACE INTO %s(name,mode,mtime,data)\n" 6030 " SELECT\n" 6031 " %s,\n" 6032 " mode,\n" 6033 " mtime,\n" 6034 " data\n" 6035 " FROM fsdir(%Q,%Q) AS disk\n" 6036 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6037 }; 6038 int i; /* For iterating through azFile[] */ 6039 int rc; /* Return code */ 6040 const char *zTab = 0; /* SQL table into which to insert */ 6041 char *zSql; 6042 char zTemp[50]; 6043 char *zExists = 0; 6044 6045 arExecSql(pAr, "PRAGMA page_size=512"); 6046 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6047 if( rc!=SQLITE_OK ) return rc; 6048 zTemp[0] = 0; 6049 if( pAr->bZip ){ 6050 /* Initialize the zipfile virtual table, if necessary */ 6051 if( pAr->zFile ){ 6052 sqlite3_uint64 r; 6053 sqlite3_randomness(sizeof(r),&r); 6054 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6055 zTab = zTemp; 6056 zSql = sqlite3_mprintf( 6057 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6058 zTab, pAr->zFile 6059 ); 6060 rc = arExecSql(pAr, zSql); 6061 sqlite3_free(zSql); 6062 }else{ 6063 zTab = "zip"; 6064 } 6065 }else{ 6066 /* Initialize the table for an SQLAR */ 6067 zTab = "sqlar"; 6068 if( bUpdate==0 ){ 6069 rc = arExecSql(pAr, zDrop); 6070 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6071 } 6072 rc = arExecSql(pAr, zCreate); 6073 } 6074 if( bOnlyIfChanged ){ 6075 zExists = sqlite3_mprintf( 6076 " AND NOT EXISTS(" 6077 "SELECT 1 FROM %s AS mem" 6078 " WHERE mem.name=disk.name" 6079 " AND mem.mtime=disk.mtime" 6080 " AND mem.mode=disk.mode)", zTab); 6081 }else{ 6082 zExists = sqlite3_mprintf(""); 6083 } 6084 if( zExists==0 ) rc = SQLITE_NOMEM; 6085 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6086 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6087 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6088 pAr->azArg[i], pAr->zDir, zExists); 6089 rc = arExecSql(pAr, zSql2); 6090 sqlite3_free(zSql2); 6091 } 6092end_ar_transaction: 6093 if( rc!=SQLITE_OK ){ 6094 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6095 }else{ 6096 rc = arExecSql(pAr, "RELEASE ar;"); 6097 if( pAr->bZip && pAr->zFile ){ 6098 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6099 arExecSql(pAr, zSql); 6100 sqlite3_free(zSql); 6101 } 6102 } 6103 sqlite3_free(zExists); 6104 return rc; 6105} 6106 6107/* 6108** Implementation of ".ar" dot command. 6109*/ 6110static int arDotCommand( 6111 ShellState *pState, /* Current shell tool state */ 6112 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6113 char **azArg, /* Array of arguments passed to dot command */ 6114 int nArg /* Number of entries in azArg[] */ 6115){ 6116 ArCommand cmd; 6117 int rc; 6118 memset(&cmd, 0, sizeof(cmd)); 6119 cmd.fromCmdLine = fromCmdLine; 6120 rc = arParseCommand(azArg, nArg, &cmd); 6121 if( rc==SQLITE_OK ){ 6122 int eDbType = SHELL_OPEN_UNSPEC; 6123 cmd.p = pState; 6124 cmd.db = pState->db; 6125 if( cmd.zFile ){ 6126 eDbType = deduceDatabaseType(cmd.zFile, 1); 6127 }else{ 6128 eDbType = pState->openMode; 6129 } 6130 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6131 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6132 if( cmd.zFile==0 ){ 6133 cmd.zSrcTable = sqlite3_mprintf("zip"); 6134 }else{ 6135 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6136 } 6137 } 6138 cmd.bZip = 1; 6139 }else if( cmd.zFile ){ 6140 int flags; 6141 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6142 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6143 || cmd.eCmd==AR_CMD_UPDATE ){ 6144 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6145 }else{ 6146 flags = SQLITE_OPEN_READONLY; 6147 } 6148 cmd.db = 0; 6149 if( cmd.bDryRun ){ 6150 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6151 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6152 } 6153 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6154 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6155 if( rc!=SQLITE_OK ){ 6156 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6157 cmd.zFile, sqlite3_errmsg(cmd.db) 6158 ); 6159 goto end_ar_command; 6160 } 6161 sqlite3_fileio_init(cmd.db, 0, 0); 6162 sqlite3_sqlar_init(cmd.db, 0, 0); 6163 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6164 shellPutsFunc, 0, 0); 6165 6166 } 6167 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6168 if( cmd.eCmd!=AR_CMD_CREATE 6169 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6170 ){ 6171 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6172 rc = SQLITE_ERROR; 6173 goto end_ar_command; 6174 } 6175 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6176 } 6177 6178 switch( cmd.eCmd ){ 6179 case AR_CMD_CREATE: 6180 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6181 break; 6182 6183 case AR_CMD_EXTRACT: 6184 rc = arExtractCommand(&cmd); 6185 break; 6186 6187 case AR_CMD_LIST: 6188 rc = arListCommand(&cmd); 6189 break; 6190 6191 case AR_CMD_HELP: 6192 arUsage(pState->out); 6193 break; 6194 6195 case AR_CMD_INSERT: 6196 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6197 break; 6198 6199 default: 6200 assert( cmd.eCmd==AR_CMD_UPDATE ); 6201 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6202 break; 6203 } 6204 } 6205end_ar_command: 6206 if( cmd.db!=pState->db ){ 6207 close_db(cmd.db); 6208 } 6209 sqlite3_free(cmd.zSrcTable); 6210 6211 return rc; 6212} 6213/* End of the ".archive" or ".ar" command logic 6214**********************************************************************************/ 6215#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6216 6217#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6218/* 6219** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6220** Otherwise, the SQL statement or statements in zSql are executed using 6221** database connection db and the error code written to *pRc before 6222** this function returns. 6223*/ 6224static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6225 int rc = *pRc; 6226 if( rc==SQLITE_OK ){ 6227 char *zErr = 0; 6228 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6229 if( rc!=SQLITE_OK ){ 6230 raw_printf(stderr, "SQL error: %s\n", zErr); 6231 } 6232 *pRc = rc; 6233 } 6234} 6235 6236/* 6237** Like shellExec(), except that zFmt is a printf() style format string. 6238*/ 6239static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6240 char *z = 0; 6241 if( *pRc==SQLITE_OK ){ 6242 va_list ap; 6243 va_start(ap, zFmt); 6244 z = sqlite3_vmprintf(zFmt, ap); 6245 va_end(ap); 6246 if( z==0 ){ 6247 *pRc = SQLITE_NOMEM; 6248 }else{ 6249 shellExec(db, pRc, z); 6250 } 6251 sqlite3_free(z); 6252 } 6253} 6254 6255/* 6256** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6257** Otherwise, an attempt is made to allocate, zero and return a pointer 6258** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6259** to SQLITE_NOMEM and NULL returned. 6260*/ 6261static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6262 void *pRet = 0; 6263 if( *pRc==SQLITE_OK ){ 6264 pRet = sqlite3_malloc64(nByte); 6265 if( pRet==0 ){ 6266 *pRc = SQLITE_NOMEM; 6267 }else{ 6268 memset(pRet, 0, nByte); 6269 } 6270 } 6271 return pRet; 6272} 6273 6274/* 6275** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6276** Otherwise, zFmt is treated as a printf() style string. The result of 6277** formatting it along with any trailing arguments is written into a 6278** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6279** It is the responsibility of the caller to eventually free this buffer 6280** using a call to sqlite3_free(). 6281** 6282** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6283** pointer returned. 6284*/ 6285static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6286 char *z = 0; 6287 if( *pRc==SQLITE_OK ){ 6288 va_list ap; 6289 va_start(ap, zFmt); 6290 z = sqlite3_vmprintf(zFmt, ap); 6291 va_end(ap); 6292 if( z==0 ){ 6293 *pRc = SQLITE_NOMEM; 6294 } 6295 } 6296 return z; 6297} 6298 6299/* 6300** When running the ".recover" command, each output table, and the special 6301** orphaned row table if it is required, is represented by an instance 6302** of the following struct. 6303*/ 6304typedef struct RecoverTable RecoverTable; 6305struct RecoverTable { 6306 char *zQuoted; /* Quoted version of table name */ 6307 int nCol; /* Number of columns in table */ 6308 char **azlCol; /* Array of column lists */ 6309 int iPk; /* Index of IPK column */ 6310}; 6311 6312/* 6313** Free a RecoverTable object allocated by recoverFindTable() or 6314** recoverOrphanTable(). 6315*/ 6316static void recoverFreeTable(RecoverTable *pTab){ 6317 if( pTab ){ 6318 sqlite3_free(pTab->zQuoted); 6319 if( pTab->azlCol ){ 6320 int i; 6321 for(i=0; i<=pTab->nCol; i++){ 6322 sqlite3_free(pTab->azlCol[i]); 6323 } 6324 sqlite3_free(pTab->azlCol); 6325 } 6326 sqlite3_free(pTab); 6327 } 6328} 6329 6330/* 6331** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 6332** Otherwise, it allocates and returns a RecoverTable object based on the 6333** final four arguments passed to this function. It is the responsibility 6334** of the caller to eventually free the returned object using 6335** recoverFreeTable(). 6336*/ 6337static RecoverTable *recoverNewTable( 6338 int *pRc, /* IN/OUT: Error code */ 6339 const char *zName, /* Name of table */ 6340 const char *zSql, /* CREATE TABLE statement */ 6341 int bIntkey, 6342 int nCol 6343){ 6344 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 6345 int rc = *pRc; 6346 RecoverTable *pTab = 0; 6347 6348 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 6349 if( rc==SQLITE_OK ){ 6350 int nSqlCol = 0; 6351 int bSqlIntkey = 0; 6352 sqlite3_stmt *pStmt = 0; 6353 6354 rc = sqlite3_open("", &dbtmp); 6355 if( rc==SQLITE_OK ){ 6356 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, 6357 shellIdQuote, 0, 0); 6358 } 6359 if( rc==SQLITE_OK ){ 6360 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 6361 } 6362 if( rc==SQLITE_OK ){ 6363 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 6364 if( rc==SQLITE_ERROR ){ 6365 rc = SQLITE_OK; 6366 goto finished; 6367 } 6368 } 6369 shellPreparePrintf(dbtmp, &rc, &pStmt, 6370 "SELECT count(*) FROM pragma_table_info(%Q)", zName 6371 ); 6372 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6373 nSqlCol = sqlite3_column_int(pStmt, 0); 6374 } 6375 shellFinalize(&rc, pStmt); 6376 6377 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 6378 goto finished; 6379 } 6380 6381 shellPreparePrintf(dbtmp, &rc, &pStmt, 6382 "SELECT (" 6383 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 6384 ") FROM sqlite_master WHERE name = %Q", zName 6385 ); 6386 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6387 bSqlIntkey = sqlite3_column_int(pStmt, 0); 6388 } 6389 shellFinalize(&rc, pStmt); 6390 6391 if( bIntkey==bSqlIntkey ){ 6392 int i; 6393 const char *zPk = "_rowid_"; 6394 sqlite3_stmt *pPkFinder = 0; 6395 6396 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 6397 ** set zPk to the name of the PK column, and pTab->iPk to the index 6398 ** of the column, where columns are 0-numbered from left to right. 6399 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 6400 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 6401 pTab->iPk = -2; 6402 if( bIntkey ){ 6403 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 6404 "SELECT cid, name FROM pragma_table_info(%Q) " 6405 " WHERE pk=1 AND type='integer' COLLATE nocase" 6406 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 6407 , zName, zName 6408 ); 6409 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 6410 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 6411 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 6412 } 6413 } 6414 6415 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); 6416 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 6417 pTab->nCol = nSqlCol; 6418 6419 if( bIntkey ){ 6420 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); 6421 }else{ 6422 pTab->azlCol[0] = shellMPrintf(&rc, ""); 6423 } 6424 i = 1; 6425 shellPreparePrintf(dbtmp, &rc, &pStmt, 6426 "SELECT %Q || group_concat(shell_idquote(name), ', ') " 6427 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 6428 "FROM pragma_table_info(%Q)", 6429 bIntkey ? ", " : "", pTab->iPk, 6430 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 6431 zName 6432 ); 6433 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6434 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 6435 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 6436 i++; 6437 } 6438 shellFinalize(&rc, pStmt); 6439 6440 shellFinalize(&rc, pPkFinder); 6441 } 6442 } 6443 6444 finished: 6445 sqlite3_close(dbtmp); 6446 *pRc = rc; 6447 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 6448 recoverFreeTable(pTab); 6449 pTab = 0; 6450 } 6451 return pTab; 6452} 6453 6454/* 6455** This function is called to search the schema recovered from the 6456** sqlite_master table of the (possibly) corrupt database as part 6457** of a ".recover" command. Specifically, for a table with root page 6458** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 6459** table must be a WITHOUT ROWID table, or if non-zero, not one of 6460** those. 6461** 6462** If a table is found, a (RecoverTable*) object is returned. Or, if 6463** no such table is found, but bIntkey is false and iRoot is the 6464** root page of an index in the recovered schema, then (*pbNoop) is 6465** set to true and NULL returned. Or, if there is no such table or 6466** index, NULL is returned and (*pbNoop) set to 0, indicating that 6467** the caller should write data to the orphans table. 6468*/ 6469static RecoverTable *recoverFindTable( 6470 ShellState *pState, /* Shell state object */ 6471 int *pRc, /* IN/OUT: Error code */ 6472 int iRoot, /* Root page of table */ 6473 int bIntkey, /* True for an intkey table */ 6474 int nCol, /* Number of columns in table */ 6475 int *pbNoop /* OUT: True if iRoot is root of index */ 6476){ 6477 sqlite3_stmt *pStmt = 0; 6478 RecoverTable *pRet = 0; 6479 int bNoop = 0; 6480 const char *zSql = 0; 6481 const char *zName = 0; 6482 6483 /* Search the recovered schema for an object with root page iRoot. */ 6484 shellPreparePrintf(pState->db, pRc, &pStmt, 6485 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 6486 ); 6487 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6488 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 6489 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 6490 bNoop = 1; 6491 break; 6492 } 6493 if( sqlite3_stricmp(zType, "table")==0 ){ 6494 zName = (const char*)sqlite3_column_text(pStmt, 1); 6495 zSql = (const char*)sqlite3_column_text(pStmt, 2); 6496 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 6497 break; 6498 } 6499 } 6500 6501 shellFinalize(pRc, pStmt); 6502 *pbNoop = bNoop; 6503 return pRet; 6504} 6505 6506/* 6507** Return a RecoverTable object representing the orphans table. 6508*/ 6509static RecoverTable *recoverOrphanTable( 6510 ShellState *pState, /* Shell state object */ 6511 int *pRc, /* IN/OUT: Error code */ 6512 const char *zLostAndFound, /* Base name for orphans table */ 6513 int nCol /* Number of user data columns */ 6514){ 6515 RecoverTable *pTab = 0; 6516 if( nCol>=0 && *pRc==SQLITE_OK ){ 6517 int i; 6518 6519 /* This block determines the name of the orphan table. The prefered 6520 ** name is zLostAndFound. But if that clashes with another name 6521 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 6522 ** and so on until a non-clashing name is found. */ 6523 int iTab = 0; 6524 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 6525 sqlite3_stmt *pTest = 0; 6526 shellPrepare(pState->db, pRc, 6527 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 6528 ); 6529 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6530 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 6531 shellReset(pRc, pTest); 6532 sqlite3_free(zTab); 6533 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 6534 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6535 } 6536 shellFinalize(pRc, pTest); 6537 6538 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 6539 if( pTab ){ 6540 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); 6541 pTab->nCol = nCol; 6542 pTab->iPk = -2; 6543 if( nCol>0 ){ 6544 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 6545 if( pTab->azlCol ){ 6546 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 6547 for(i=nCol-1; i>=0; i--){ 6548 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 6549 } 6550 } 6551 } 6552 6553 if( *pRc!=SQLITE_OK ){ 6554 recoverFreeTable(pTab); 6555 pTab = 0; 6556 }else{ 6557 raw_printf(pState->out, 6558 "CREATE TABLE %s(rootpgno INTEGER, " 6559 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 6560 ); 6561 for(i=0; i<nCol; i++){ 6562 raw_printf(pState->out, ", c%d", i); 6563 } 6564 raw_printf(pState->out, ");\n"); 6565 } 6566 } 6567 sqlite3_free(zTab); 6568 } 6569 return pTab; 6570} 6571 6572/* 6573** This function is called to recover data from the database. A script 6574** to construct a new database containing all recovered data is output 6575** on stream pState->out. 6576*/ 6577static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 6578 int rc = SQLITE_OK; 6579 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 6580 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 6581 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 6582 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 6583 const char *zLostAndFound = "lost_and_found"; 6584 int i; 6585 int nOrphan = -1; 6586 RecoverTable *pOrphan = 0; 6587 6588 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 6589 for(i=1; i<nArg; i++){ 6590 char *z = azArg[i]; 6591 int n; 6592 if( z[0]=='-' && z[1]=='-' ) z++; 6593 n = strlen30(z); 6594 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 6595 bFreelist = 0; 6596 }else 6597 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 6598 i++; 6599 zRecoveryDb = azArg[i]; 6600 }else 6601 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 6602 i++; 6603 zLostAndFound = azArg[i]; 6604 } 6605 else{ 6606 raw_printf(stderr, "unexpected option: %s\n", azArg[i]); 6607 raw_printf(stderr, "options are:\n"); 6608 raw_printf(stderr, " --freelist-corrupt\n"); 6609 raw_printf(stderr, " --recovery-db DATABASE\n"); 6610 raw_printf(stderr, " --lost-and-found TABLE-NAME\n"); 6611 return 1; 6612 } 6613 } 6614 6615 shellExecPrintf(pState->db, &rc, 6616 /* Attach an in-memory database named 'recovery'. Create an indexed 6617 ** cache of the sqlite_dbptr virtual table. */ 6618 "PRAGMA writable_schema = on;" 6619 "ATTACH %Q AS recovery;" 6620 "DROP TABLE IF EXISTS recovery.dbptr;" 6621 "DROP TABLE IF EXISTS recovery.freelist;" 6622 "DROP TABLE IF EXISTS recovery.map;" 6623 "DROP TABLE IF EXISTS recovery.schema;" 6624 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 6625 ); 6626 6627 if( bFreelist ){ 6628 shellExec(pState->db, &rc, 6629 "WITH trunk(pgno) AS (" 6630 " SELECT shell_int32(" 6631 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 6632 " WHERE x>0" 6633 " UNION" 6634 " SELECT shell_int32(" 6635 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 6636 " FROM trunk WHERE x>0" 6637 ")," 6638 "freelist(data, n, freepgno) AS (" 6639 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 6640 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 6641 " UNION ALL" 6642 " SELECT data, n-1, shell_int32(data, 2+n) " 6643 " FROM freelist WHERE n>=0" 6644 ")" 6645 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 6646 ); 6647 } 6648 6649 /* If this is an auto-vacuum database, add all pointer-map pages to 6650 ** the freelist table. Do this regardless of whether or not 6651 ** --freelist-corrupt was specified. */ 6652 shellExec(pState->db, &rc, 6653 "WITH ptrmap(pgno) AS (" 6654 " SELECT 2 WHERE shell_int32(" 6655 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" 6656 " )" 6657 " UNION ALL " 6658 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " 6659 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" 6660 ")" 6661 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" 6662 ); 6663 6664 shellExec(pState->db, &rc, 6665 "CREATE TABLE recovery.dbptr(" 6666 " pgno, child, PRIMARY KEY(child, pgno)" 6667 ") WITHOUT ROWID;" 6668 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 6669 " SELECT * FROM sqlite_dbptr" 6670 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 6671 6672 /* Delete any pointer to page 1. This ensures that page 1 is considered 6673 ** a root page, regardless of how corrupt the db is. */ 6674 "DELETE FROM recovery.dbptr WHERE child = 1;" 6675 6676 /* Delete all pointers to any pages that have more than one pointer 6677 ** to them. Such pages will be treated as root pages when recovering 6678 ** data. */ 6679 "DELETE FROM recovery.dbptr WHERE child IN (" 6680 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 6681 ");" 6682 6683 /* Create the "map" table that will (eventually) contain instructions 6684 ** for dealing with each page in the db that contains one or more 6685 ** records. */ 6686 "CREATE TABLE recovery.map(" 6687 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 6688 ");" 6689 6690 /* Populate table [map]. If there are circular loops of pages in the 6691 ** database, the following adds all pages in such a loop to the map 6692 ** as individual root pages. This could be handled better. */ 6693 "WITH pages(i, maxlen) AS (" 6694 " SELECT page_count, (" 6695 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 6696 " ) FROM pragma_page_count WHERE page_count>0" 6697 " UNION ALL" 6698 " SELECT i-1, (" 6699 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 6700 " ) FROM pages WHERE i>=2" 6701 ")" 6702 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 6703 " SELECT i, maxlen, NULL, (" 6704 " WITH p(orig, pgno, parent) AS (" 6705 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 6706 " UNION " 6707 " SELECT i, p.parent, " 6708 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 6709 " )" 6710 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 6711 ") " 6712 "FROM pages WHERE maxlen > 0 AND i NOT IN freelist;" 6713 "UPDATE recovery.map AS o SET intkey = (" 6714 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 6715 ");" 6716 6717 /* Extract data from page 1 and any linked pages into table 6718 ** recovery.schema. With the same schema as an sqlite_master table. */ 6719 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 6720 "INSERT INTO recovery.schema SELECT " 6721 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 6722 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 6723 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 6724 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 6725 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 6726 "FROM sqlite_dbdata WHERE pgno IN (" 6727 " SELECT pgno FROM recovery.map WHERE root=1" 6728 ")" 6729 "GROUP BY pgno, cell;" 6730 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 6731 ); 6732 6733 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 6734 ** CREATE TABLE statements that extracted from the existing schema. */ 6735 if( rc==SQLITE_OK ){ 6736 sqlite3_stmt *pStmt = 0; 6737 /* ".recover" might output content in an order which causes immediate 6738 ** foreign key constraints to be violated. So disable foreign-key 6739 ** constraint enforcement to prevent problems when running the output 6740 ** script. */ 6741 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); 6742 raw_printf(pState->out, "BEGIN;\n"); 6743 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 6744 shellPrepare(pState->db, &rc, 6745 "SELECT sql FROM recovery.schema " 6746 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 6747 ); 6748 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6749 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 6750 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 6751 &zCreateTable[12] 6752 ); 6753 } 6754 shellFinalize(&rc, pStmt); 6755 } 6756 6757 /* Figure out if an orphan table will be required. And if so, how many 6758 ** user columns it should contain */ 6759 shellPrepare(pState->db, &rc, 6760 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 6761 , &pLoop 6762 ); 6763 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6764 nOrphan = sqlite3_column_int(pLoop, 0); 6765 } 6766 shellFinalize(&rc, pLoop); 6767 pLoop = 0; 6768 6769 shellPrepare(pState->db, &rc, 6770 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 6771 ); 6772 shellPrepare(pState->db, &rc, 6773 "SELECT max(field), group_concat(shell_escape_crnl(quote(value)), ', ')" 6774 ", min(field) " 6775 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 6776 "GROUP BY cell", &pCells 6777 ); 6778 6779 /* Loop through each root page. */ 6780 shellPrepare(pState->db, &rc, 6781 "SELECT root, intkey, max(maxlen) FROM recovery.map" 6782 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 6783 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 6784 ")", &pLoop 6785 ); 6786 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6787 int iRoot = sqlite3_column_int(pLoop, 0); 6788 int bIntkey = sqlite3_column_int(pLoop, 1); 6789 int nCol = sqlite3_column_int(pLoop, 2); 6790 int bNoop = 0; 6791 RecoverTable *pTab; 6792 6793 assert( bIntkey==0 || bIntkey==1 ); 6794 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 6795 if( bNoop || rc ) continue; 6796 if( pTab==0 ){ 6797 if( pOrphan==0 ){ 6798 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6799 } 6800 pTab = pOrphan; 6801 if( pTab==0 ) break; 6802 } 6803 6804 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ 6805 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 6806 } 6807 sqlite3_bind_int(pPages, 1, iRoot); 6808 sqlite3_bind_int(pCells, 2, pTab->iPk); 6809 6810 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 6811 int iPgno = sqlite3_column_int(pPages, 0); 6812 sqlite3_bind_int(pCells, 1, iPgno); 6813 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 6814 int nField = sqlite3_column_int(pCells, 0); 6815 int iMin = sqlite3_column_int(pCells, 2); 6816 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 6817 6818 RecoverTable *pTab2 = pTab; 6819 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ 6820 if( pOrphan==0 ){ 6821 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6822 } 6823 pTab2 = pOrphan; 6824 if( pTab2==0 ) break; 6825 } 6826 6827 nField = nField+1; 6828 if( pTab2==pOrphan ){ 6829 raw_printf(pState->out, 6830 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 6831 pTab2->zQuoted, iRoot, iPgno, nField, 6832 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] 6833 ); 6834 }else{ 6835 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 6836 pTab2->zQuoted, pTab2->azlCol[nField], zVal 6837 ); 6838 } 6839 } 6840 shellReset(&rc, pCells); 6841 } 6842 shellReset(&rc, pPages); 6843 if( pTab!=pOrphan ) recoverFreeTable(pTab); 6844 } 6845 shellFinalize(&rc, pLoop); 6846 shellFinalize(&rc, pPages); 6847 shellFinalize(&rc, pCells); 6848 recoverFreeTable(pOrphan); 6849 6850 /* The rest of the schema */ 6851 if( rc==SQLITE_OK ){ 6852 sqlite3_stmt *pStmt = 0; 6853 shellPrepare(pState->db, &rc, 6854 "SELECT sql, name FROM recovery.schema " 6855 "WHERE sql NOT LIKE 'create table%'", &pStmt 6856 ); 6857 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6858 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 6859 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 6860 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 6861 char *zPrint = shellMPrintf(&rc, 6862 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)", 6863 zName, zName, zSql 6864 ); 6865 raw_printf(pState->out, "%s;\n", zPrint); 6866 sqlite3_free(zPrint); 6867 }else{ 6868 raw_printf(pState->out, "%s;\n", zSql); 6869 } 6870 } 6871 shellFinalize(&rc, pStmt); 6872 } 6873 6874 if( rc==SQLITE_OK ){ 6875 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 6876 raw_printf(pState->out, "COMMIT;\n"); 6877 } 6878 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 6879 return rc; 6880} 6881#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 6882 6883 6884/* 6885** If an input line begins with "." then invoke this routine to 6886** process that line. 6887** 6888** Return 1 on error, 2 to exit, and 0 otherwise. 6889*/ 6890static int do_meta_command(char *zLine, ShellState *p){ 6891 int h = 1; 6892 int nArg = 0; 6893 int n, c; 6894 int rc = 0; 6895 char *azArg[50]; 6896 6897#ifndef SQLITE_OMIT_VIRTUALTABLE 6898 if( p->expert.pExpert ){ 6899 expertFinish(p, 1, 0); 6900 } 6901#endif 6902 6903 /* Parse the input line into tokens. 6904 */ 6905 while( zLine[h] && nArg<ArraySize(azArg) ){ 6906 while( IsSpace(zLine[h]) ){ h++; } 6907 if( zLine[h]==0 ) break; 6908 if( zLine[h]=='\'' || zLine[h]=='"' ){ 6909 int delim = zLine[h++]; 6910 azArg[nArg++] = &zLine[h]; 6911 while( zLine[h] && zLine[h]!=delim ){ 6912 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 6913 h++; 6914 } 6915 if( zLine[h]==delim ){ 6916 zLine[h++] = 0; 6917 } 6918 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 6919 }else{ 6920 azArg[nArg++] = &zLine[h]; 6921 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 6922 if( zLine[h] ) zLine[h++] = 0; 6923 resolve_backslashes(azArg[nArg-1]); 6924 } 6925 } 6926 6927 /* Process the input line. 6928 */ 6929 if( nArg==0 ) return 0; /* no tokens, no error */ 6930 n = strlen30(azArg[0]); 6931 c = azArg[0][0]; 6932 clearTempFile(p); 6933 6934#ifndef SQLITE_OMIT_AUTHORIZATION 6935 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 6936 if( nArg!=2 ){ 6937 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 6938 rc = 1; 6939 goto meta_command_exit; 6940 } 6941 open_db(p, 0); 6942 if( booleanValue(azArg[1]) ){ 6943 sqlite3_set_authorizer(p->db, shellAuth, p); 6944 }else{ 6945 sqlite3_set_authorizer(p->db, 0, 0); 6946 } 6947 }else 6948#endif 6949 6950#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6951 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 6952 open_db(p, 0); 6953 rc = arDotCommand(p, 0, azArg, nArg); 6954 }else 6955#endif 6956 6957 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 6958 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 6959 ){ 6960 const char *zDestFile = 0; 6961 const char *zDb = 0; 6962 sqlite3 *pDest; 6963 sqlite3_backup *pBackup; 6964 int j; 6965 int bAsync = 0; 6966 const char *zVfs = 0; 6967 for(j=1; j<nArg; j++){ 6968 const char *z = azArg[j]; 6969 if( z[0]=='-' ){ 6970 if( z[1]=='-' ) z++; 6971 if( strcmp(z, "-append")==0 ){ 6972 zVfs = "apndvfs"; 6973 }else 6974 if( strcmp(z, "-async")==0 ){ 6975 bAsync = 1; 6976 }else 6977 { 6978 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 6979 return 1; 6980 } 6981 }else if( zDestFile==0 ){ 6982 zDestFile = azArg[j]; 6983 }else if( zDb==0 ){ 6984 zDb = zDestFile; 6985 zDestFile = azArg[j]; 6986 }else{ 6987 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 6988 return 1; 6989 } 6990 } 6991 if( zDestFile==0 ){ 6992 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 6993 return 1; 6994 } 6995 if( zDb==0 ) zDb = "main"; 6996 rc = sqlite3_open_v2(zDestFile, &pDest, 6997 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 6998 if( rc!=SQLITE_OK ){ 6999 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 7000 close_db(pDest); 7001 return 1; 7002 } 7003 if( bAsync ){ 7004 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7005 0, 0, 0); 7006 } 7007 open_db(p, 0); 7008 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7009 if( pBackup==0 ){ 7010 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7011 close_db(pDest); 7012 return 1; 7013 } 7014 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7015 sqlite3_backup_finish(pBackup); 7016 if( rc==SQLITE_DONE ){ 7017 rc = 0; 7018 }else{ 7019 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7020 rc = 1; 7021 } 7022 close_db(pDest); 7023 }else 7024 7025 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 7026 if( nArg==2 ){ 7027 bail_on_error = booleanValue(azArg[1]); 7028 }else{ 7029 raw_printf(stderr, "Usage: .bail on|off\n"); 7030 rc = 1; 7031 } 7032 }else 7033 7034 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 7035 if( nArg==2 ){ 7036 if( booleanValue(azArg[1]) ){ 7037 setBinaryMode(p->out, 1); 7038 }else{ 7039 setTextMode(p->out, 1); 7040 } 7041 }else{ 7042 raw_printf(stderr, "Usage: .binary on|off\n"); 7043 rc = 1; 7044 } 7045 }else 7046 7047 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 7048 if( nArg==2 ){ 7049#if defined(_WIN32) || defined(WIN32) 7050 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7051 rc = !SetCurrentDirectoryW(z); 7052 sqlite3_free(z); 7053#else 7054 rc = chdir(azArg[1]); 7055#endif 7056 if( rc ){ 7057 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7058 rc = 1; 7059 } 7060 }else{ 7061 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7062 rc = 1; 7063 } 7064 }else 7065 7066 /* The undocumented ".breakpoint" command causes a call to the no-op 7067 ** routine named test_breakpoint(). 7068 */ 7069 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7070 test_breakpoint(); 7071 }else 7072 7073 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7074 if( nArg==2 ){ 7075 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7076 }else{ 7077 raw_printf(stderr, "Usage: .changes on|off\n"); 7078 rc = 1; 7079 } 7080 }else 7081 7082 /* Cancel output redirection, if it is currently set (by .testcase) 7083 ** Then read the content of the testcase-out.txt file and compare against 7084 ** azArg[1]. If there are differences, report an error and exit. 7085 */ 7086 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7087 char *zRes = 0; 7088 output_reset(p); 7089 if( nArg!=2 ){ 7090 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7091 rc = 2; 7092 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7093 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7094 rc = 2; 7095 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7096 utf8_printf(stderr, 7097 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7098 p->zTestcase, azArg[1], zRes); 7099 rc = 1; 7100 }else{ 7101 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7102 p->nCheck++; 7103 } 7104 sqlite3_free(zRes); 7105 }else 7106 7107 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7108 if( nArg==2 ){ 7109 tryToClone(p, azArg[1]); 7110 }else{ 7111 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7112 rc = 1; 7113 } 7114 }else 7115 7116 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7117 ShellState data; 7118 char *zErrMsg = 0; 7119 open_db(p, 0); 7120 memcpy(&data, p, sizeof(data)); 7121 data.showHeader = 0; 7122 data.cMode = data.mode = MODE_List; 7123 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); 7124 data.cnt = 0; 7125 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", 7126 callback, &data, &zErrMsg); 7127 if( zErrMsg ){ 7128 utf8_printf(stderr,"Error: %s\n", zErrMsg); 7129 sqlite3_free(zErrMsg); 7130 rc = 1; 7131 } 7132 }else 7133 7134 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7135 static const struct DbConfigChoices { 7136 const char *zName; 7137 int op; 7138 } aDbConfig[] = { 7139 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7140 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7141 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, 7142 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7143 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7144 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7145 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7146 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7147 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7148 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7149 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7150 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7151 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7152 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7153 }; 7154 int ii, v; 7155 open_db(p, 0); 7156 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7157 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7158 if( nArg>=3 ){ 7159 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7160 } 7161 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7162 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7163 if( nArg>1 ) break; 7164 } 7165 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7166 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7167 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7168 } 7169 }else 7170 7171 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7172 rc = shell_dbinfo_command(p, nArg, azArg); 7173 }else 7174 7175#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7176 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7177 open_db(p, 0); 7178 rc = recoverDatabaseCmd(p, nArg, azArg); 7179 }else 7180#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7181 7182 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7183 const char *zLike = 0; 7184 int i; 7185 int savedShowHeader = p->showHeader; 7186 int savedShellFlags = p->shellFlgs; 7187 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo); 7188 for(i=1; i<nArg; i++){ 7189 if( azArg[i][0]=='-' ){ 7190 const char *z = azArg[i]+1; 7191 if( z[0]=='-' ) z++; 7192 if( strcmp(z,"preserve-rowids")==0 ){ 7193#ifdef SQLITE_OMIT_VIRTUALTABLE 7194 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7195 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7196 rc = 1; 7197 goto meta_command_exit; 7198#else 7199 ShellSetFlag(p, SHFLG_PreserveRowid); 7200#endif 7201 }else 7202 if( strcmp(z,"newlines")==0 ){ 7203 ShellSetFlag(p, SHFLG_Newlines); 7204 }else 7205 { 7206 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 7207 rc = 1; 7208 goto meta_command_exit; 7209 } 7210 }else if( zLike ){ 7211 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? " 7212 "?--newlines? ?LIKE-PATTERN?\n"); 7213 rc = 1; 7214 goto meta_command_exit; 7215 }else{ 7216 zLike = azArg[i]; 7217 } 7218 } 7219 7220 open_db(p, 0); 7221 7222 /* When playing back a "dump", the content might appear in an order 7223 ** which causes immediate foreign key constraints to be violated. 7224 ** So disable foreign-key constraint enforcement to prevent problems. */ 7225 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 7226 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 7227 p->writableSchema = 0; 7228 p->showHeader = 0; 7229 /* Set writable_schema=ON since doing so forces SQLite to initialize 7230 ** as much of the schema as it can even if the sqlite_master table is 7231 ** corrupt. */ 7232 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 7233 p->nErr = 0; 7234 if( zLike==0 ){ 7235 run_schema_dump_query(p, 7236 "SELECT name, type, sql FROM sqlite_master " 7237 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" 7238 ); 7239 run_schema_dump_query(p, 7240 "SELECT name, type, sql FROM sqlite_master " 7241 "WHERE name=='sqlite_sequence'" 7242 ); 7243 run_table_dump_query(p, 7244 "SELECT sql FROM sqlite_master " 7245 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 7246 ); 7247 }else{ 7248 char *zSql; 7249 zSql = sqlite3_mprintf( 7250 "SELECT name, type, sql FROM sqlite_master " 7251 "WHERE tbl_name LIKE %Q AND type=='table'" 7252 " AND sql NOT NULL", zLike); 7253 run_schema_dump_query(p,zSql); 7254 sqlite3_free(zSql); 7255 zSql = sqlite3_mprintf( 7256 "SELECT sql FROM sqlite_master " 7257 "WHERE sql NOT NULL" 7258 " AND type IN ('index','trigger','view')" 7259 " AND tbl_name LIKE %Q", zLike); 7260 run_table_dump_query(p, zSql, 0); 7261 sqlite3_free(zSql); 7262 } 7263 if( p->writableSchema ){ 7264 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 7265 p->writableSchema = 0; 7266 } 7267 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 7268 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 7269 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 7270 p->showHeader = savedShowHeader; 7271 p->shellFlgs = savedShellFlags; 7272 }else 7273 7274 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 7275 if( nArg==2 ){ 7276 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 7277 }else{ 7278 raw_printf(stderr, "Usage: .echo on|off\n"); 7279 rc = 1; 7280 } 7281 }else 7282 7283 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 7284 if( nArg==2 ){ 7285 p->autoEQPtest = 0; 7286 if( p->autoEQPtrace ){ 7287 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 7288 p->autoEQPtrace = 0; 7289 } 7290 if( strcmp(azArg[1],"full")==0 ){ 7291 p->autoEQP = AUTOEQP_full; 7292 }else if( strcmp(azArg[1],"trigger")==0 ){ 7293 p->autoEQP = AUTOEQP_trigger; 7294#ifdef SQLITE_DEBUG 7295 }else if( strcmp(azArg[1],"test")==0 ){ 7296 p->autoEQP = AUTOEQP_on; 7297 p->autoEQPtest = 1; 7298 }else if( strcmp(azArg[1],"trace")==0 ){ 7299 p->autoEQP = AUTOEQP_full; 7300 p->autoEQPtrace = 1; 7301 open_db(p, 0); 7302 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0); 7303 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 7304#endif 7305 }else{ 7306 p->autoEQP = (u8)booleanValue(azArg[1]); 7307 } 7308 }else{ 7309 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 7310 rc = 1; 7311 } 7312 }else 7313 7314 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 7315 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 7316 rc = 2; 7317 }else 7318 7319 /* The ".explain" command is automatic now. It is largely pointless. It 7320 ** retained purely for backwards compatibility */ 7321 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 7322 int val = 1; 7323 if( nArg>=2 ){ 7324 if( strcmp(azArg[1],"auto")==0 ){ 7325 val = 99; 7326 }else{ 7327 val = booleanValue(azArg[1]); 7328 } 7329 } 7330 if( val==1 && p->mode!=MODE_Explain ){ 7331 p->normalMode = p->mode; 7332 p->mode = MODE_Explain; 7333 p->autoExplain = 0; 7334 }else if( val==0 ){ 7335 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7336 p->autoExplain = 0; 7337 }else if( val==99 ){ 7338 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7339 p->autoExplain = 1; 7340 } 7341 }else 7342 7343#ifndef SQLITE_OMIT_VIRTUALTABLE 7344 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 7345 open_db(p, 0); 7346 expertDotCommand(p, azArg, nArg); 7347 }else 7348#endif 7349 7350 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ 7351 static const struct { 7352 const char *zCtrlName; /* Name of a test-control option */ 7353 int ctrlCode; /* Integer code for that option */ 7354 const char *zUsage; /* Usage notes */ 7355 } aCtrl[] = { 7356 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 7357 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 7358 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 7359 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 7360 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 7361 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 7362 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 7363 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 7364 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 7365 }; 7366 int filectrl = -1; 7367 int iCtrl = -1; 7368 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 7369 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 7370 int n2, i; 7371 const char *zCmd = 0; 7372 7373 open_db(p, 0); 7374 zCmd = nArg>=2 ? azArg[1] : "help"; 7375 7376 /* The argument can optionally begin with "-" or "--" */ 7377 if( zCmd[0]=='-' && zCmd[1] ){ 7378 zCmd++; 7379 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 7380 } 7381 7382 /* --help lists all file-controls */ 7383 if( strcmp(zCmd,"help")==0 ){ 7384 utf8_printf(p->out, "Available file-controls:\n"); 7385 for(i=0; i<ArraySize(aCtrl); i++){ 7386 utf8_printf(p->out, " .filectrl %s %s\n", 7387 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 7388 } 7389 rc = 1; 7390 goto meta_command_exit; 7391 } 7392 7393 /* convert filectrl text option to value. allow any unique prefix 7394 ** of the option name, or a numerical value. */ 7395 n2 = strlen30(zCmd); 7396 for(i=0; i<ArraySize(aCtrl); i++){ 7397 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 7398 if( filectrl<0 ){ 7399 filectrl = aCtrl[i].ctrlCode; 7400 iCtrl = i; 7401 }else{ 7402 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 7403 "Use \".filectrl --help\" for help\n", zCmd); 7404 rc = 1; 7405 goto meta_command_exit; 7406 } 7407 } 7408 } 7409 if( filectrl<0 ){ 7410 utf8_printf(stderr,"Error: unknown file-control: %s\n" 7411 "Use \".filectrl --help\" for help\n", zCmd); 7412 }else{ 7413 switch(filectrl){ 7414 case SQLITE_FCNTL_SIZE_LIMIT: { 7415 if( nArg!=2 && nArg!=3 ) break; 7416 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 7417 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 7418 isOk = 1; 7419 break; 7420 } 7421 case SQLITE_FCNTL_LOCK_TIMEOUT: 7422 case SQLITE_FCNTL_CHUNK_SIZE: { 7423 int x; 7424 if( nArg!=3 ) break; 7425 x = (int)integerValue(azArg[2]); 7426 sqlite3_file_control(p->db, 0, filectrl, &x); 7427 isOk = 2; 7428 break; 7429 } 7430 case SQLITE_FCNTL_PERSIST_WAL: 7431 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 7432 int x; 7433 if( nArg!=2 && nArg!=3 ) break; 7434 x = nArg==3 ? booleanValue(azArg[2]) : -1; 7435 sqlite3_file_control(p->db, 0, filectrl, &x); 7436 iRes = x; 7437 isOk = 1; 7438 break; 7439 } 7440 case SQLITE_FCNTL_HAS_MOVED: { 7441 int x; 7442 if( nArg!=2 ) break; 7443 sqlite3_file_control(p->db, 0, filectrl, &x); 7444 iRes = x; 7445 isOk = 1; 7446 break; 7447 } 7448 case SQLITE_FCNTL_TEMPFILENAME: { 7449 char *z = 0; 7450 if( nArg!=2 ) break; 7451 sqlite3_file_control(p->db, 0, filectrl, &z); 7452 if( z ){ 7453 utf8_printf(p->out, "%s\n", z); 7454 sqlite3_free(z); 7455 } 7456 isOk = 2; 7457 break; 7458 } 7459 } 7460 } 7461 if( isOk==0 && iCtrl>=0 ){ 7462 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 7463 rc = 1; 7464 }else if( isOk==1 ){ 7465 char zBuf[100]; 7466 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 7467 raw_printf(p->out, "%s\n", zBuf); 7468 } 7469 }else 7470 7471 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 7472 ShellState data; 7473 char *zErrMsg = 0; 7474 int doStats = 0; 7475 memcpy(&data, p, sizeof(data)); 7476 data.showHeader = 0; 7477 data.cMode = data.mode = MODE_Semi; 7478 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 7479 data.cMode = data.mode = MODE_Pretty; 7480 nArg = 1; 7481 } 7482 if( nArg!=1 ){ 7483 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 7484 rc = 1; 7485 goto meta_command_exit; 7486 } 7487 open_db(p, 0); 7488 rc = sqlite3_exec(p->db, 7489 "SELECT sql FROM" 7490 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 7491 " FROM sqlite_master UNION ALL" 7492 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " 7493 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 7494 "ORDER BY rowid", 7495 callback, &data, &zErrMsg 7496 ); 7497 if( rc==SQLITE_OK ){ 7498 sqlite3_stmt *pStmt; 7499 rc = sqlite3_prepare_v2(p->db, 7500 "SELECT rowid FROM sqlite_master" 7501 " WHERE name GLOB 'sqlite_stat[134]'", 7502 -1, &pStmt, 0); 7503 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 7504 sqlite3_finalize(pStmt); 7505 } 7506 if( doStats==0 ){ 7507 raw_printf(p->out, "/* No STAT tables available */\n"); 7508 }else{ 7509 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7510 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", 7511 callback, &data, &zErrMsg); 7512 data.cMode = data.mode = MODE_Insert; 7513 data.zDestTable = "sqlite_stat1"; 7514 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg); 7515 data.zDestTable = "sqlite_stat4"; 7516 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg); 7517 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7518 } 7519 }else 7520 7521 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 7522 if( nArg==2 ){ 7523 p->showHeader = booleanValue(azArg[1]); 7524 }else{ 7525 raw_printf(stderr, "Usage: .headers on|off\n"); 7526 rc = 1; 7527 } 7528 }else 7529 7530 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 7531 if( nArg>=2 ){ 7532 n = showHelp(p->out, azArg[1]); 7533 if( n==0 ){ 7534 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 7535 } 7536 }else{ 7537 showHelp(p->out, 0); 7538 } 7539 }else 7540 7541 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 7542 char *zTable; /* Insert data into this table */ 7543 char *zFile; /* Name of file to extra content from */ 7544 sqlite3_stmt *pStmt = NULL; /* A statement */ 7545 int nCol; /* Number of columns in the table */ 7546 int nByte; /* Number of bytes in an SQL string */ 7547 int i, j; /* Loop counters */ 7548 int needCommit; /* True to COMMIT or ROLLBACK at end */ 7549 int nSep; /* Number of bytes in p->colSeparator[] */ 7550 char *zSql; /* An SQL statement */ 7551 ImportCtx sCtx; /* Reader context */ 7552 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 7553 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ 7554 7555 if( nArg!=3 ){ 7556 raw_printf(stderr, "Usage: .import FILE TABLE\n"); 7557 goto meta_command_exit; 7558 } 7559 zFile = azArg[1]; 7560 zTable = azArg[2]; 7561 seenInterrupt = 0; 7562 memset(&sCtx, 0, sizeof(sCtx)); 7563 open_db(p, 0); 7564 nSep = strlen30(p->colSeparator); 7565 if( nSep==0 ){ 7566 raw_printf(stderr, 7567 "Error: non-null column separator required for import\n"); 7568 return 1; 7569 } 7570 if( nSep>1 ){ 7571 raw_printf(stderr, "Error: multi-character column separators not allowed" 7572 " for import\n"); 7573 return 1; 7574 } 7575 nSep = strlen30(p->rowSeparator); 7576 if( nSep==0 ){ 7577 raw_printf(stderr, "Error: non-null row separator required for import\n"); 7578 return 1; 7579 } 7580 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){ 7581 /* When importing CSV (only), if the row separator is set to the 7582 ** default output row separator, change it to the default input 7583 ** row separator. This avoids having to maintain different input 7584 ** and output row separators. */ 7585 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7586 nSep = strlen30(p->rowSeparator); 7587 } 7588 if( nSep>1 ){ 7589 raw_printf(stderr, "Error: multi-character row separators not allowed" 7590 " for import\n"); 7591 return 1; 7592 } 7593 sCtx.zFile = zFile; 7594 sCtx.nLine = 1; 7595 if( sCtx.zFile[0]=='|' ){ 7596#ifdef SQLITE_OMIT_POPEN 7597 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 7598 return 1; 7599#else 7600 sCtx.in = popen(sCtx.zFile+1, "r"); 7601 sCtx.zFile = "<pipe>"; 7602 xCloser = pclose; 7603#endif 7604 }else{ 7605 sCtx.in = fopen(sCtx.zFile, "rb"); 7606 xCloser = fclose; 7607 } 7608 if( p->mode==MODE_Ascii ){ 7609 xRead = ascii_read_one_field; 7610 }else{ 7611 xRead = csv_read_one_field; 7612 } 7613 if( sCtx.in==0 ){ 7614 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 7615 return 1; 7616 } 7617 sCtx.cColSep = p->colSeparator[0]; 7618 sCtx.cRowSep = p->rowSeparator[0]; 7619 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); 7620 if( zSql==0 ){ 7621 xCloser(sCtx.in); 7622 shell_out_of_memory(); 7623 } 7624 nByte = strlen30(zSql); 7625 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7626 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 7627 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 7628 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); 7629 char cSep = '('; 7630 while( xRead(&sCtx) ){ 7631 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 7632 cSep = ','; 7633 if( sCtx.cTerm!=sCtx.cColSep ) break; 7634 } 7635 if( cSep=='(' ){ 7636 sqlite3_free(zCreate); 7637 sqlite3_free(sCtx.z); 7638 xCloser(sCtx.in); 7639 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 7640 return 1; 7641 } 7642 zCreate = sqlite3_mprintf("%z\n)", zCreate); 7643 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 7644 sqlite3_free(zCreate); 7645 if( rc ){ 7646 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, 7647 sqlite3_errmsg(p->db)); 7648 sqlite3_free(sCtx.z); 7649 xCloser(sCtx.in); 7650 return 1; 7651 } 7652 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7653 } 7654 sqlite3_free(zSql); 7655 if( rc ){ 7656 if (pStmt) sqlite3_finalize(pStmt); 7657 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 7658 xCloser(sCtx.in); 7659 return 1; 7660 } 7661 nCol = sqlite3_column_count(pStmt); 7662 sqlite3_finalize(pStmt); 7663 pStmt = 0; 7664 if( nCol==0 ) return 0; /* no columns, no error */ 7665 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 7666 if( zSql==0 ){ 7667 xCloser(sCtx.in); 7668 shell_out_of_memory(); 7669 } 7670 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); 7671 j = strlen30(zSql); 7672 for(i=1; i<nCol; i++){ 7673 zSql[j++] = ','; 7674 zSql[j++] = '?'; 7675 } 7676 zSql[j++] = ')'; 7677 zSql[j] = 0; 7678 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7679 sqlite3_free(zSql); 7680 if( rc ){ 7681 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7682 if (pStmt) sqlite3_finalize(pStmt); 7683 xCloser(sCtx.in); 7684 return 1; 7685 } 7686 needCommit = sqlite3_get_autocommit(p->db); 7687 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 7688 do{ 7689 int startLine = sCtx.nLine; 7690 for(i=0; i<nCol; i++){ 7691 char *z = xRead(&sCtx); 7692 /* 7693 ** Did we reach end-of-file before finding any columns? 7694 ** If so, stop instead of NULL filling the remaining columns. 7695 */ 7696 if( z==0 && i==0 ) break; 7697 /* 7698 ** Did we reach end-of-file OR end-of-line before finding any 7699 ** columns in ASCII mode? If so, stop instead of NULL filling 7700 ** the remaining columns. 7701 */ 7702 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 7703 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 7704 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 7705 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7706 "filling the rest with NULL\n", 7707 sCtx.zFile, startLine, nCol, i+1); 7708 i += 2; 7709 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 7710 } 7711 } 7712 if( sCtx.cTerm==sCtx.cColSep ){ 7713 do{ 7714 xRead(&sCtx); 7715 i++; 7716 }while( sCtx.cTerm==sCtx.cColSep ); 7717 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7718 "extras ignored\n", 7719 sCtx.zFile, startLine, nCol, i); 7720 } 7721 if( i>=nCol ){ 7722 sqlite3_step(pStmt); 7723 rc = sqlite3_reset(pStmt); 7724 if( rc!=SQLITE_OK ){ 7725 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 7726 startLine, sqlite3_errmsg(p->db)); 7727 } 7728 } 7729 }while( sCtx.cTerm!=EOF ); 7730 7731 xCloser(sCtx.in); 7732 sqlite3_free(sCtx.z); 7733 sqlite3_finalize(pStmt); 7734 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 7735 }else 7736 7737#ifndef SQLITE_UNTESTABLE 7738 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 7739 char *zSql; 7740 char *zCollist = 0; 7741 sqlite3_stmt *pStmt; 7742 int tnum = 0; 7743 int i; 7744 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 7745 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 7746 " .imposter off\n"); 7747 rc = 1; 7748 goto meta_command_exit; 7749 } 7750 open_db(p, 0); 7751 if( nArg==2 ){ 7752 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 7753 goto meta_command_exit; 7754 } 7755 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master" 7756 " WHERE name='%q' AND type='index'", azArg[1]); 7757 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7758 sqlite3_free(zSql); 7759 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 7760 tnum = sqlite3_column_int(pStmt, 0); 7761 } 7762 sqlite3_finalize(pStmt); 7763 if( tnum==0 ){ 7764 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 7765 rc = 1; 7766 goto meta_command_exit; 7767 } 7768 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 7769 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7770 sqlite3_free(zSql); 7771 i = 0; 7772 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7773 char zLabel[20]; 7774 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 7775 i++; 7776 if( zCol==0 ){ 7777 if( sqlite3_column_int(pStmt,1)==-1 ){ 7778 zCol = "_ROWID_"; 7779 }else{ 7780 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 7781 zCol = zLabel; 7782 } 7783 } 7784 if( zCollist==0 ){ 7785 zCollist = sqlite3_mprintf("\"%w\"", zCol); 7786 }else{ 7787 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 7788 } 7789 } 7790 sqlite3_finalize(pStmt); 7791 zSql = sqlite3_mprintf( 7792 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID", 7793 azArg[2], zCollist, zCollist); 7794 sqlite3_free(zCollist); 7795 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 7796 if( rc==SQLITE_OK ){ 7797 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 7798 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 7799 if( rc ){ 7800 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 7801 }else{ 7802 utf8_printf(stdout, "%s;\n", zSql); 7803 raw_printf(stdout, 7804 "WARNING: writing to an imposter table will corrupt the index!\n" 7805 ); 7806 } 7807 }else{ 7808 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 7809 rc = 1; 7810 } 7811 sqlite3_free(zSql); 7812 }else 7813#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 7814 7815#ifdef SQLITE_ENABLE_IOTRACE 7816 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 7817 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 7818 if( iotrace && iotrace!=stdout ) fclose(iotrace); 7819 iotrace = 0; 7820 if( nArg<2 ){ 7821 sqlite3IoTrace = 0; 7822 }else if( strcmp(azArg[1], "-")==0 ){ 7823 sqlite3IoTrace = iotracePrintf; 7824 iotrace = stdout; 7825 }else{ 7826 iotrace = fopen(azArg[1], "w"); 7827 if( iotrace==0 ){ 7828 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 7829 sqlite3IoTrace = 0; 7830 rc = 1; 7831 }else{ 7832 sqlite3IoTrace = iotracePrintf; 7833 } 7834 } 7835 }else 7836#endif 7837 7838 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 7839 static const struct { 7840 const char *zLimitName; /* Name of a limit */ 7841 int limitCode; /* Integer code for that limit */ 7842 } aLimit[] = { 7843 { "length", SQLITE_LIMIT_LENGTH }, 7844 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 7845 { "column", SQLITE_LIMIT_COLUMN }, 7846 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 7847 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 7848 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 7849 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 7850 { "attached", SQLITE_LIMIT_ATTACHED }, 7851 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 7852 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 7853 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 7854 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 7855 }; 7856 int i, n2; 7857 open_db(p, 0); 7858 if( nArg==1 ){ 7859 for(i=0; i<ArraySize(aLimit); i++){ 7860 printf("%20s %d\n", aLimit[i].zLimitName, 7861 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 7862 } 7863 }else if( nArg>3 ){ 7864 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 7865 rc = 1; 7866 goto meta_command_exit; 7867 }else{ 7868 int iLimit = -1; 7869 n2 = strlen30(azArg[1]); 7870 for(i=0; i<ArraySize(aLimit); i++){ 7871 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 7872 if( iLimit<0 ){ 7873 iLimit = i; 7874 }else{ 7875 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 7876 rc = 1; 7877 goto meta_command_exit; 7878 } 7879 } 7880 } 7881 if( iLimit<0 ){ 7882 utf8_printf(stderr, "unknown limit: \"%s\"\n" 7883 "enter \".limits\" with no arguments for a list.\n", 7884 azArg[1]); 7885 rc = 1; 7886 goto meta_command_exit; 7887 } 7888 if( nArg==3 ){ 7889 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 7890 (int)integerValue(azArg[2])); 7891 } 7892 printf("%20s %d\n", aLimit[iLimit].zLimitName, 7893 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 7894 } 7895 }else 7896 7897 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 7898 open_db(p, 0); 7899 lintDotCommand(p, azArg, nArg); 7900 }else 7901 7902#ifndef SQLITE_OMIT_LOAD_EXTENSION 7903 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 7904 const char *zFile, *zProc; 7905 char *zErrMsg = 0; 7906 if( nArg<2 ){ 7907 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 7908 rc = 1; 7909 goto meta_command_exit; 7910 } 7911 zFile = azArg[1]; 7912 zProc = nArg>=3 ? azArg[2] : 0; 7913 open_db(p, 0); 7914 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 7915 if( rc!=SQLITE_OK ){ 7916 utf8_printf(stderr, "Error: %s\n", zErrMsg); 7917 sqlite3_free(zErrMsg); 7918 rc = 1; 7919 } 7920 }else 7921#endif 7922 7923 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 7924 if( nArg!=2 ){ 7925 raw_printf(stderr, "Usage: .log FILENAME\n"); 7926 rc = 1; 7927 }else{ 7928 const char *zFile = azArg[1]; 7929 output_file_close(p->pLog); 7930 p->pLog = output_file_open(zFile, 0); 7931 } 7932 }else 7933 7934 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 7935 const char *zMode = nArg>=2 ? azArg[1] : ""; 7936 int n2 = strlen30(zMode); 7937 int c2 = zMode[0]; 7938 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 7939 p->mode = MODE_Line; 7940 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7941 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 7942 p->mode = MODE_Column; 7943 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7944 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 7945 p->mode = MODE_List; 7946 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 7947 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7948 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 7949 p->mode = MODE_Html; 7950 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 7951 p->mode = MODE_Tcl; 7952 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 7953 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7954 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 7955 p->mode = MODE_Csv; 7956 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 7957 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 7958 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 7959 p->mode = MODE_List; 7960 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 7961 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 7962 p->mode = MODE_Insert; 7963 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 7964 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 7965 p->mode = MODE_Quote; 7966 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 7967 p->mode = MODE_Ascii; 7968 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 7969 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 7970 }else if( nArg==1 ){ 7971 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 7972 }else{ 7973 raw_printf(stderr, "Error: mode should be one of: " 7974 "ascii column csv html insert line list quote tabs tcl\n"); 7975 rc = 1; 7976 } 7977 p->cMode = p->mode; 7978 }else 7979 7980 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 7981 if( nArg==2 ){ 7982 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 7983 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 7984 }else{ 7985 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 7986 rc = 1; 7987 } 7988 }else 7989 7990 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 7991 char *zNewFilename; /* Name of the database file to open */ 7992 int iName = 1; /* Index in azArg[] of the filename */ 7993 int newFlag = 0; /* True to delete file before opening */ 7994 /* Close the existing database */ 7995 session_close_all(p); 7996 close_db(p->db); 7997 p->db = 0; 7998 p->zDbFilename = 0; 7999 sqlite3_free(p->zFreeOnClose); 8000 p->zFreeOnClose = 0; 8001 p->openMode = SHELL_OPEN_UNSPEC; 8002 p->szMax = 0; 8003 /* Check for command-line arguments */ 8004 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){ 8005 const char *z = azArg[iName]; 8006 if( optionMatch(z,"new") ){ 8007 newFlag = 1; 8008#ifdef SQLITE_HAVE_ZLIB 8009 }else if( optionMatch(z, "zip") ){ 8010 p->openMode = SHELL_OPEN_ZIPFILE; 8011#endif 8012 }else if( optionMatch(z, "append") ){ 8013 p->openMode = SHELL_OPEN_APPENDVFS; 8014 }else if( optionMatch(z, "readonly") ){ 8015 p->openMode = SHELL_OPEN_READONLY; 8016#ifdef SQLITE_ENABLE_DESERIALIZE 8017 }else if( optionMatch(z, "deserialize") ){ 8018 p->openMode = SHELL_OPEN_DESERIALIZE; 8019 }else if( optionMatch(z, "hexdb") ){ 8020 p->openMode = SHELL_OPEN_HEXDB; 8021 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 8022 p->szMax = integerValue(azArg[++iName]); 8023#endif /* SQLITE_ENABLE_DESERIALIZE */ 8024 }else if( z[0]=='-' ){ 8025 utf8_printf(stderr, "unknown option: %s\n", z); 8026 rc = 1; 8027 goto meta_command_exit; 8028 } 8029 } 8030 /* If a filename is specified, try to open it first */ 8031 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; 8032 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ 8033 if( newFlag ) shellDeleteFile(zNewFilename); 8034 p->zDbFilename = zNewFilename; 8035 open_db(p, OPEN_DB_KEEPALIVE); 8036 if( p->db==0 ){ 8037 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 8038 sqlite3_free(zNewFilename); 8039 }else{ 8040 p->zFreeOnClose = zNewFilename; 8041 } 8042 } 8043 if( p->db==0 ){ 8044 /* As a fall-back open a TEMP database */ 8045 p->zDbFilename = 0; 8046 open_db(p, 0); 8047 } 8048 }else 8049 8050 if( (c=='o' 8051 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 8052 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 8053 ){ 8054 const char *zFile = nArg>=2 ? azArg[1] : "stdout"; 8055 int bTxtMode = 0; 8056 if( azArg[0][0]=='e' ){ 8057 /* Transform the ".excel" command into ".once -x" */ 8058 nArg = 2; 8059 azArg[0] = "once"; 8060 zFile = azArg[1] = "-x"; 8061 n = 4; 8062 } 8063 if( nArg>2 ){ 8064 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]); 8065 rc = 1; 8066 goto meta_command_exit; 8067 } 8068 if( n>1 && strncmp(azArg[0], "once", n)==0 ){ 8069 if( nArg<2 ){ 8070 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n"); 8071 rc = 1; 8072 goto meta_command_exit; 8073 } 8074 p->outCount = 2; 8075 }else{ 8076 p->outCount = 0; 8077 } 8078 output_reset(p); 8079 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++; 8080#ifndef SQLITE_NOHAVE_SYSTEM 8081 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){ 8082 p->doXdgOpen = 1; 8083 outputModePush(p); 8084 if( zFile[1]=='x' ){ 8085 newTempFile(p, "csv"); 8086 p->mode = MODE_Csv; 8087 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8088 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8089 }else{ 8090 newTempFile(p, "txt"); 8091 bTxtMode = 1; 8092 } 8093 zFile = p->zTempFile; 8094 } 8095#endif /* SQLITE_NOHAVE_SYSTEM */ 8096 if( zFile[0]=='|' ){ 8097#ifdef SQLITE_OMIT_POPEN 8098 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8099 rc = 1; 8100 p->out = stdout; 8101#else 8102 p->out = popen(zFile + 1, "w"); 8103 if( p->out==0 ){ 8104 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 8105 p->out = stdout; 8106 rc = 1; 8107 }else{ 8108 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 8109 } 8110#endif 8111 }else{ 8112 p->out = output_file_open(zFile, bTxtMode); 8113 if( p->out==0 ){ 8114 if( strcmp(zFile,"off")!=0 ){ 8115 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 8116 } 8117 p->out = stdout; 8118 rc = 1; 8119 } else { 8120 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 8121 } 8122 } 8123 }else 8124 8125 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 8126 open_db(p,0); 8127 if( nArg<=1 ) goto parameter_syntax_error; 8128 8129 /* .parameter clear 8130 ** Clear all bind parameters by dropping the TEMP table that holds them. 8131 */ 8132 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 8133 int wrSchema = 0; 8134 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 8135 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 8136 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 8137 0, 0, 0); 8138 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 8139 }else 8140 8141 /* .parameter list 8142 ** List all bind parameters. 8143 */ 8144 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 8145 sqlite3_stmt *pStmt = 0; 8146 int rx; 8147 int len = 0; 8148 rx = sqlite3_prepare_v2(p->db, 8149 "SELECT max(length(key)) " 8150 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 8151 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8152 len = sqlite3_column_int(pStmt, 0); 8153 if( len>40 ) len = 40; 8154 } 8155 sqlite3_finalize(pStmt); 8156 pStmt = 0; 8157 if( len ){ 8158 rx = sqlite3_prepare_v2(p->db, 8159 "SELECT key, quote(value) " 8160 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 8161 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8162 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 8163 sqlite3_column_text(pStmt,1)); 8164 } 8165 sqlite3_finalize(pStmt); 8166 } 8167 }else 8168 8169 /* .parameter init 8170 ** Make sure the TEMP table used to hold bind parameters exists. 8171 ** Create it if necessary. 8172 */ 8173 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 8174 bind_table_init(p); 8175 }else 8176 8177 /* .parameter set NAME VALUE 8178 ** Set or reset a bind parameter. NAME should be the full parameter 8179 ** name exactly as it appears in the query. (ex: $abc, @def). The 8180 ** VALUE can be in either SQL literal notation, or if not it will be 8181 ** understood to be a text string. 8182 */ 8183 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 8184 int rx; 8185 char *zSql; 8186 sqlite3_stmt *pStmt; 8187 const char *zKey = azArg[2]; 8188 const char *zValue = azArg[3]; 8189 bind_table_init(p); 8190 zSql = sqlite3_mprintf( 8191 "REPLACE INTO temp.sqlite_parameters(key,value)" 8192 "VALUES(%Q,%s);", zKey, zValue); 8193 if( zSql==0 ) shell_out_of_memory(); 8194 pStmt = 0; 8195 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8196 sqlite3_free(zSql); 8197 if( rx!=SQLITE_OK ){ 8198 sqlite3_finalize(pStmt); 8199 pStmt = 0; 8200 zSql = sqlite3_mprintf( 8201 "REPLACE INTO temp.sqlite_parameters(key,value)" 8202 "VALUES(%Q,%Q);", zKey, zValue); 8203 if( zSql==0 ) shell_out_of_memory(); 8204 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8205 sqlite3_free(zSql); 8206 if( rx!=SQLITE_OK ){ 8207 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 8208 sqlite3_finalize(pStmt); 8209 pStmt = 0; 8210 rc = 1; 8211 } 8212 } 8213 sqlite3_step(pStmt); 8214 sqlite3_finalize(pStmt); 8215 }else 8216 8217 /* .parameter unset NAME 8218 ** Remove the NAME binding from the parameter binding table, if it 8219 ** exists. 8220 */ 8221 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 8222 char *zSql = sqlite3_mprintf( 8223 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 8224 if( zSql==0 ) shell_out_of_memory(); 8225 sqlite3_exec(p->db, zSql, 0, 0, 0); 8226 sqlite3_free(zSql); 8227 }else 8228 /* If no command name matches, show a syntax error */ 8229 parameter_syntax_error: 8230 showHelp(p->out, "parameter"); 8231 }else 8232 8233 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 8234 int i; 8235 for(i=1; i<nArg; i++){ 8236 if( i>1 ) raw_printf(p->out, " "); 8237 utf8_printf(p->out, "%s", azArg[i]); 8238 } 8239 raw_printf(p->out, "\n"); 8240 }else 8241 8242#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 8243 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 8244 int i; 8245 int nn = 0; 8246 p->flgProgress = 0; 8247 p->mxProgress = 0; 8248 p->nProgress = 0; 8249 for(i=1; i<nArg; i++){ 8250 const char *z = azArg[i]; 8251 if( z[0]=='-' ){ 8252 z++; 8253 if( z[0]=='-' ) z++; 8254 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 8255 p->flgProgress |= SHELL_PROGRESS_QUIET; 8256 continue; 8257 } 8258 if( strcmp(z,"reset")==0 ){ 8259 p->flgProgress |= SHELL_PROGRESS_RESET; 8260 continue; 8261 } 8262 if( strcmp(z,"once")==0 ){ 8263 p->flgProgress |= SHELL_PROGRESS_ONCE; 8264 continue; 8265 } 8266 if( strcmp(z,"limit")==0 ){ 8267 if( i+1>=nArg ){ 8268 utf8_printf(stderr, "Error: missing argument on --limit\n"); 8269 rc = 1; 8270 goto meta_command_exit; 8271 }else{ 8272 p->mxProgress = (int)integerValue(azArg[++i]); 8273 } 8274 continue; 8275 } 8276 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 8277 rc = 1; 8278 goto meta_command_exit; 8279 }else{ 8280 nn = (int)integerValue(z); 8281 } 8282 } 8283 open_db(p, 0); 8284 sqlite3_progress_handler(p->db, nn, progress_handler, p); 8285 }else 8286#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 8287 8288 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 8289 if( nArg >= 2) { 8290 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 8291 } 8292 if( nArg >= 3) { 8293 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 8294 } 8295 }else 8296 8297 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 8298 rc = 2; 8299 }else 8300 8301 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 8302 FILE *inSaved = p->in; 8303 int savedLineno = p->lineno; 8304 if( nArg!=2 ){ 8305 raw_printf(stderr, "Usage: .read FILE\n"); 8306 rc = 1; 8307 goto meta_command_exit; 8308 } 8309 p->in = fopen(azArg[1], "rb"); 8310 if( p->in==0 ){ 8311 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 8312 rc = 1; 8313 }else{ 8314 rc = process_input(p); 8315 fclose(p->in); 8316 } 8317 p->in = inSaved; 8318 p->lineno = savedLineno; 8319 }else 8320 8321 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 8322 const char *zSrcFile; 8323 const char *zDb; 8324 sqlite3 *pSrc; 8325 sqlite3_backup *pBackup; 8326 int nTimeout = 0; 8327 8328 if( nArg==2 ){ 8329 zSrcFile = azArg[1]; 8330 zDb = "main"; 8331 }else if( nArg==3 ){ 8332 zSrcFile = azArg[2]; 8333 zDb = azArg[1]; 8334 }else{ 8335 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 8336 rc = 1; 8337 goto meta_command_exit; 8338 } 8339 rc = sqlite3_open(zSrcFile, &pSrc); 8340 if( rc!=SQLITE_OK ){ 8341 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 8342 close_db(pSrc); 8343 return 1; 8344 } 8345 open_db(p, 0); 8346 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 8347 if( pBackup==0 ){ 8348 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8349 close_db(pSrc); 8350 return 1; 8351 } 8352 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 8353 || rc==SQLITE_BUSY ){ 8354 if( rc==SQLITE_BUSY ){ 8355 if( nTimeout++ >= 3 ) break; 8356 sqlite3_sleep(100); 8357 } 8358 } 8359 sqlite3_backup_finish(pBackup); 8360 if( rc==SQLITE_DONE ){ 8361 rc = 0; 8362 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 8363 raw_printf(stderr, "Error: source database is busy\n"); 8364 rc = 1; 8365 }else{ 8366 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8367 rc = 1; 8368 } 8369 close_db(pSrc); 8370 }else 8371 8372 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 8373 if( nArg==2 ){ 8374 p->scanstatsOn = (u8)booleanValue(azArg[1]); 8375#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 8376 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 8377#endif 8378 }else{ 8379 raw_printf(stderr, "Usage: .scanstats on|off\n"); 8380 rc = 1; 8381 } 8382 }else 8383 8384 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 8385 ShellText sSelect; 8386 ShellState data; 8387 char *zErrMsg = 0; 8388 const char *zDiv = "("; 8389 const char *zName = 0; 8390 int iSchema = 0; 8391 int bDebug = 0; 8392 int ii; 8393 8394 open_db(p, 0); 8395 memcpy(&data, p, sizeof(data)); 8396 data.showHeader = 0; 8397 data.cMode = data.mode = MODE_Semi; 8398 initText(&sSelect); 8399 for(ii=1; ii<nArg; ii++){ 8400 if( optionMatch(azArg[ii],"indent") ){ 8401 data.cMode = data.mode = MODE_Pretty; 8402 }else if( optionMatch(azArg[ii],"debug") ){ 8403 bDebug = 1; 8404 }else if( zName==0 ){ 8405 zName = azArg[ii]; 8406 }else{ 8407 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); 8408 rc = 1; 8409 goto meta_command_exit; 8410 } 8411 } 8412 if( zName!=0 ){ 8413 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0; 8414 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){ 8415 char *new_argv[2], *new_colv[2]; 8416 new_argv[0] = sqlite3_mprintf( 8417 "CREATE TABLE %s (\n" 8418 " type text,\n" 8419 " name text,\n" 8420 " tbl_name text,\n" 8421 " rootpage integer,\n" 8422 " sql text\n" 8423 ")", isMaster ? "sqlite_master" : "sqlite_temp_master"); 8424 new_argv[1] = 0; 8425 new_colv[0] = "sql"; 8426 new_colv[1] = 0; 8427 callback(&data, 1, new_argv, new_colv); 8428 sqlite3_free(new_argv[0]); 8429 } 8430 } 8431 if( zDiv ){ 8432 sqlite3_stmt *pStmt = 0; 8433 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 8434 -1, &pStmt, 0); 8435 if( rc ){ 8436 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8437 sqlite3_finalize(pStmt); 8438 rc = 1; 8439 goto meta_command_exit; 8440 } 8441 appendText(&sSelect, "SELECT sql FROM", 0); 8442 iSchema = 0; 8443 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8444 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 8445 char zScNum[30]; 8446 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 8447 appendText(&sSelect, zDiv, 0); 8448 zDiv = " UNION ALL "; 8449 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 8450 if( sqlite3_stricmp(zDb, "main")!=0 ){ 8451 appendText(&sSelect, zDb, '\''); 8452 }else{ 8453 appendText(&sSelect, "NULL", 0); 8454 } 8455 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 8456 appendText(&sSelect, zScNum, 0); 8457 appendText(&sSelect, " AS snum, ", 0); 8458 appendText(&sSelect, zDb, '\''); 8459 appendText(&sSelect, " AS sname FROM ", 0); 8460 appendText(&sSelect, zDb, quoteChar(zDb)); 8461 appendText(&sSelect, ".sqlite_master", 0); 8462 } 8463 sqlite3_finalize(pStmt); 8464#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 8465 if( zName ){ 8466 appendText(&sSelect, 8467 " UNION ALL SELECT shell_module_schema(name)," 8468 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0); 8469 } 8470#endif 8471 appendText(&sSelect, ") WHERE ", 0); 8472 if( zName ){ 8473 char *zQarg = sqlite3_mprintf("%Q", zName); 8474 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 8475 strchr(zName, '[') != 0; 8476 if( strchr(zName, '.') ){ 8477 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 8478 }else{ 8479 appendText(&sSelect, "lower(tbl_name)", 0); 8480 } 8481 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 8482 appendText(&sSelect, zQarg, 0); 8483 if( !bGlob ){ 8484 appendText(&sSelect, " ESCAPE '\\' ", 0); 8485 } 8486 appendText(&sSelect, " AND ", 0); 8487 sqlite3_free(zQarg); 8488 } 8489 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" 8490 " ORDER BY snum, rowid", 0); 8491 if( bDebug ){ 8492 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 8493 }else{ 8494 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 8495 } 8496 freeText(&sSelect); 8497 } 8498 if( zErrMsg ){ 8499 utf8_printf(stderr,"Error: %s\n", zErrMsg); 8500 sqlite3_free(zErrMsg); 8501 rc = 1; 8502 }else if( rc != SQLITE_OK ){ 8503 raw_printf(stderr,"Error: querying schema information\n"); 8504 rc = 1; 8505 }else{ 8506 rc = 0; 8507 } 8508 }else 8509 8510#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 8511 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 8512 sqlite3SelectTrace = (int)integerValue(azArg[1]); 8513 }else 8514#endif 8515 8516#if defined(SQLITE_ENABLE_SESSION) 8517 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 8518 OpenSession *pSession = &p->aSession[0]; 8519 char **azCmd = &azArg[1]; 8520 int iSes = 0; 8521 int nCmd = nArg - 1; 8522 int i; 8523 if( nArg<=1 ) goto session_syntax_error; 8524 open_db(p, 0); 8525 if( nArg>=3 ){ 8526 for(iSes=0; iSes<p->nSession; iSes++){ 8527 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; 8528 } 8529 if( iSes<p->nSession ){ 8530 pSession = &p->aSession[iSes]; 8531 azCmd++; 8532 nCmd--; 8533 }else{ 8534 pSession = &p->aSession[0]; 8535 iSes = 0; 8536 } 8537 } 8538 8539 /* .session attach TABLE 8540 ** Invoke the sqlite3session_attach() interface to attach a particular 8541 ** table so that it is never filtered. 8542 */ 8543 if( strcmp(azCmd[0],"attach")==0 ){ 8544 if( nCmd!=2 ) goto session_syntax_error; 8545 if( pSession->p==0 ){ 8546 session_not_open: 8547 raw_printf(stderr, "ERROR: No sessions are open\n"); 8548 }else{ 8549 rc = sqlite3session_attach(pSession->p, azCmd[1]); 8550 if( rc ){ 8551 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 8552 rc = 0; 8553 } 8554 } 8555 }else 8556 8557 /* .session changeset FILE 8558 ** .session patchset FILE 8559 ** Write a changeset or patchset into a file. The file is overwritten. 8560 */ 8561 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 8562 FILE *out = 0; 8563 if( nCmd!=2 ) goto session_syntax_error; 8564 if( pSession->p==0 ) goto session_not_open; 8565 out = fopen(azCmd[1], "wb"); 8566 if( out==0 ){ 8567 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]); 8568 }else{ 8569 int szChng; 8570 void *pChng; 8571 if( azCmd[0][0]=='c' ){ 8572 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 8573 }else{ 8574 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 8575 } 8576 if( rc ){ 8577 printf("Error: error code %d\n", rc); 8578 rc = 0; 8579 } 8580 if( pChng 8581 && fwrite(pChng, szChng, 1, out)!=1 ){ 8582 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 8583 szChng); 8584 } 8585 sqlite3_free(pChng); 8586 fclose(out); 8587 } 8588 }else 8589 8590 /* .session close 8591 ** Close the identified session 8592 */ 8593 if( strcmp(azCmd[0], "close")==0 ){ 8594 if( nCmd!=1 ) goto session_syntax_error; 8595 if( p->nSession ){ 8596 session_close(pSession); 8597 p->aSession[iSes] = p->aSession[--p->nSession]; 8598 } 8599 }else 8600 8601 /* .session enable ?BOOLEAN? 8602 ** Query or set the enable flag 8603 */ 8604 if( strcmp(azCmd[0], "enable")==0 ){ 8605 int ii; 8606 if( nCmd>2 ) goto session_syntax_error; 8607 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8608 if( p->nSession ){ 8609 ii = sqlite3session_enable(pSession->p, ii); 8610 utf8_printf(p->out, "session %s enable flag = %d\n", 8611 pSession->zName, ii); 8612 } 8613 }else 8614 8615 /* .session filter GLOB .... 8616 ** Set a list of GLOB patterns of table names to be excluded. 8617 */ 8618 if( strcmp(azCmd[0], "filter")==0 ){ 8619 int ii, nByte; 8620 if( nCmd<2 ) goto session_syntax_error; 8621 if( p->nSession ){ 8622 for(ii=0; ii<pSession->nFilter; ii++){ 8623 sqlite3_free(pSession->azFilter[ii]); 8624 } 8625 sqlite3_free(pSession->azFilter); 8626 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 8627 pSession->azFilter = sqlite3_malloc( nByte ); 8628 if( pSession->azFilter==0 ){ 8629 raw_printf(stderr, "Error: out or memory\n"); 8630 exit(1); 8631 } 8632 for(ii=1; ii<nCmd; ii++){ 8633 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 8634 } 8635 pSession->nFilter = ii-1; 8636 } 8637 }else 8638 8639 /* .session indirect ?BOOLEAN? 8640 ** Query or set the indirect flag 8641 */ 8642 if( strcmp(azCmd[0], "indirect")==0 ){ 8643 int ii; 8644 if( nCmd>2 ) goto session_syntax_error; 8645 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8646 if( p->nSession ){ 8647 ii = sqlite3session_indirect(pSession->p, ii); 8648 utf8_printf(p->out, "session %s indirect flag = %d\n", 8649 pSession->zName, ii); 8650 } 8651 }else 8652 8653 /* .session isempty 8654 ** Determine if the session is empty 8655 */ 8656 if( strcmp(azCmd[0], "isempty")==0 ){ 8657 int ii; 8658 if( nCmd!=1 ) goto session_syntax_error; 8659 if( p->nSession ){ 8660 ii = sqlite3session_isempty(pSession->p); 8661 utf8_printf(p->out, "session %s isempty flag = %d\n", 8662 pSession->zName, ii); 8663 } 8664 }else 8665 8666 /* .session list 8667 ** List all currently open sessions 8668 */ 8669 if( strcmp(azCmd[0],"list")==0 ){ 8670 for(i=0; i<p->nSession; i++){ 8671 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); 8672 } 8673 }else 8674 8675 /* .session open DB NAME 8676 ** Open a new session called NAME on the attached database DB. 8677 ** DB is normally "main". 8678 */ 8679 if( strcmp(azCmd[0],"open")==0 ){ 8680 char *zName; 8681 if( nCmd!=3 ) goto session_syntax_error; 8682 zName = azCmd[2]; 8683 if( zName[0]==0 ) goto session_syntax_error; 8684 for(i=0; i<p->nSession; i++){ 8685 if( strcmp(p->aSession[i].zName,zName)==0 ){ 8686 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 8687 goto meta_command_exit; 8688 } 8689 } 8690 if( p->nSession>=ArraySize(p->aSession) ){ 8691 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); 8692 goto meta_command_exit; 8693 } 8694 pSession = &p->aSession[p->nSession]; 8695 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 8696 if( rc ){ 8697 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 8698 rc = 0; 8699 goto meta_command_exit; 8700 } 8701 pSession->nFilter = 0; 8702 sqlite3session_table_filter(pSession->p, session_filter, pSession); 8703 p->nSession++; 8704 pSession->zName = sqlite3_mprintf("%s", zName); 8705 }else 8706 /* If no command name matches, show a syntax error */ 8707 session_syntax_error: 8708 showHelp(p->out, "session"); 8709 }else 8710#endif 8711 8712#ifdef SQLITE_DEBUG 8713 /* Undocumented commands for internal testing. Subject to change 8714 ** without notice. */ 8715 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 8716 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 8717 int i, v; 8718 for(i=1; i<nArg; i++){ 8719 v = booleanValue(azArg[i]); 8720 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 8721 } 8722 } 8723 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 8724 int i; sqlite3_int64 v; 8725 for(i=1; i<nArg; i++){ 8726 char zBuf[200]; 8727 v = integerValue(azArg[i]); 8728 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 8729 utf8_printf(p->out, "%s", zBuf); 8730 } 8731 } 8732 }else 8733#endif 8734 8735 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 8736 int bIsInit = 0; /* True to initialize the SELFTEST table */ 8737 int bVerbose = 0; /* Verbose output */ 8738 int bSelftestExists; /* True if SELFTEST already exists */ 8739 int i, k; /* Loop counters */ 8740 int nTest = 0; /* Number of tests runs */ 8741 int nErr = 0; /* Number of errors seen */ 8742 ShellText str; /* Answer for a query */ 8743 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 8744 8745 open_db(p,0); 8746 for(i=1; i<nArg; i++){ 8747 const char *z = azArg[i]; 8748 if( z[0]=='-' && z[1]=='-' ) z++; 8749 if( strcmp(z,"-init")==0 ){ 8750 bIsInit = 1; 8751 }else 8752 if( strcmp(z,"-v")==0 ){ 8753 bVerbose++; 8754 }else 8755 { 8756 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8757 azArg[i], azArg[0]); 8758 raw_printf(stderr, "Should be one of: --init -v\n"); 8759 rc = 1; 8760 goto meta_command_exit; 8761 } 8762 } 8763 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 8764 != SQLITE_OK ){ 8765 bSelftestExists = 0; 8766 }else{ 8767 bSelftestExists = 1; 8768 } 8769 if( bIsInit ){ 8770 createSelftestTable(p); 8771 bSelftestExists = 1; 8772 } 8773 initText(&str); 8774 appendText(&str, "x", 0); 8775 for(k=bSelftestExists; k>=0; k--){ 8776 if( k==1 ){ 8777 rc = sqlite3_prepare_v2(p->db, 8778 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 8779 -1, &pStmt, 0); 8780 }else{ 8781 rc = sqlite3_prepare_v2(p->db, 8782 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 8783 " (1,'run','PRAGMA integrity_check','ok')", 8784 -1, &pStmt, 0); 8785 } 8786 if( rc ){ 8787 raw_printf(stderr, "Error querying the selftest table\n"); 8788 rc = 1; 8789 sqlite3_finalize(pStmt); 8790 goto meta_command_exit; 8791 } 8792 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 8793 int tno = sqlite3_column_int(pStmt, 0); 8794 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 8795 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 8796 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 8797 8798 k = 0; 8799 if( bVerbose>0 ){ 8800 char *zQuote = sqlite3_mprintf("%q", zSql); 8801 printf("%d: %s %s\n", tno, zOp, zSql); 8802 sqlite3_free(zQuote); 8803 } 8804 if( strcmp(zOp,"memo")==0 ){ 8805 utf8_printf(p->out, "%s\n", zSql); 8806 }else 8807 if( strcmp(zOp,"run")==0 ){ 8808 char *zErrMsg = 0; 8809 str.n = 0; 8810 str.z[0] = 0; 8811 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 8812 nTest++; 8813 if( bVerbose ){ 8814 utf8_printf(p->out, "Result: %s\n", str.z); 8815 } 8816 if( rc || zErrMsg ){ 8817 nErr++; 8818 rc = 1; 8819 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 8820 sqlite3_free(zErrMsg); 8821 }else if( strcmp(zAns,str.z)!=0 ){ 8822 nErr++; 8823 rc = 1; 8824 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 8825 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 8826 } 8827 }else 8828 { 8829 utf8_printf(stderr, 8830 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 8831 rc = 1; 8832 break; 8833 } 8834 } /* End loop over rows of content from SELFTEST */ 8835 sqlite3_finalize(pStmt); 8836 } /* End loop over k */ 8837 freeText(&str); 8838 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 8839 }else 8840 8841 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 8842 if( nArg<2 || nArg>3 ){ 8843 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 8844 rc = 1; 8845 } 8846 if( nArg>=2 ){ 8847 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 8848 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 8849 } 8850 if( nArg>=3 ){ 8851 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 8852 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 8853 } 8854 }else 8855 8856 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 8857 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 8858 int i; /* Loop counter */ 8859 int bSchema = 0; /* Also hash the schema */ 8860 int bSeparate = 0; /* Hash each table separately */ 8861 int iSize = 224; /* Hash algorithm to use */ 8862 int bDebug = 0; /* Only show the query that would have run */ 8863 sqlite3_stmt *pStmt; /* For querying tables names */ 8864 char *zSql; /* SQL to be run */ 8865 char *zSep; /* Separator */ 8866 ShellText sSql; /* Complete SQL for the query to run the hash */ 8867 ShellText sQuery; /* Set of queries used to read all content */ 8868 open_db(p, 0); 8869 for(i=1; i<nArg; i++){ 8870 const char *z = azArg[i]; 8871 if( z[0]=='-' ){ 8872 z++; 8873 if( z[0]=='-' ) z++; 8874 if( strcmp(z,"schema")==0 ){ 8875 bSchema = 1; 8876 }else 8877 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 8878 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 8879 ){ 8880 iSize = atoi(&z[5]); 8881 }else 8882 if( strcmp(z,"debug")==0 ){ 8883 bDebug = 1; 8884 }else 8885 { 8886 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8887 azArg[i], azArg[0]); 8888 raw_printf(stderr, "Should be one of: --schema" 8889 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n"); 8890 rc = 1; 8891 goto meta_command_exit; 8892 } 8893 }else if( zLike ){ 8894 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 8895 rc = 1; 8896 goto meta_command_exit; 8897 }else{ 8898 zLike = z; 8899 bSeparate = 1; 8900 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 8901 } 8902 } 8903 if( bSchema ){ 8904 zSql = "SELECT lower(name) FROM sqlite_master" 8905 " WHERE type='table' AND coalesce(rootpage,0)>1" 8906 " UNION ALL SELECT 'sqlite_master'" 8907 " ORDER BY 1 collate nocase"; 8908 }else{ 8909 zSql = "SELECT lower(name) FROM sqlite_master" 8910 " WHERE type='table' AND coalesce(rootpage,0)>1" 8911 " AND name NOT LIKE 'sqlite_%'" 8912 " ORDER BY 1 collate nocase"; 8913 } 8914 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8915 initText(&sQuery); 8916 initText(&sSql); 8917 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 8918 zSep = "VALUES("; 8919 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 8920 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 8921 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 8922 if( strncmp(zTab, "sqlite_",7)!=0 ){ 8923 appendText(&sQuery,"SELECT * FROM ", 0); 8924 appendText(&sQuery,zTab,'"'); 8925 appendText(&sQuery," NOT INDEXED;", 0); 8926 }else if( strcmp(zTab, "sqlite_master")==0 ){ 8927 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master" 8928 " ORDER BY name;", 0); 8929 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 8930 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 8931 " ORDER BY name;", 0); 8932 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 8933 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 8934 " ORDER BY tbl,idx;", 0); 8935 }else if( strcmp(zTab, "sqlite_stat4")==0 ){ 8936 appendText(&sQuery, "SELECT * FROM ", 0); 8937 appendText(&sQuery, zTab, 0); 8938 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 8939 } 8940 appendText(&sSql, zSep, 0); 8941 appendText(&sSql, sQuery.z, '\''); 8942 sQuery.n = 0; 8943 appendText(&sSql, ",", 0); 8944 appendText(&sSql, zTab, '\''); 8945 zSep = "),("; 8946 } 8947 sqlite3_finalize(pStmt); 8948 if( bSeparate ){ 8949 zSql = sqlite3_mprintf( 8950 "%s))" 8951 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 8952 " FROM [sha3sum$query]", 8953 sSql.z, iSize); 8954 }else{ 8955 zSql = sqlite3_mprintf( 8956 "%s))" 8957 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 8958 " FROM [sha3sum$query]", 8959 sSql.z, iSize); 8960 } 8961 freeText(&sQuery); 8962 freeText(&sSql); 8963 if( bDebug ){ 8964 utf8_printf(p->out, "%s\n", zSql); 8965 }else{ 8966 shell_exec(p, zSql, 0); 8967 } 8968 sqlite3_free(zSql); 8969 }else 8970 8971#ifndef SQLITE_NOHAVE_SYSTEM 8972 if( c=='s' 8973 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 8974 ){ 8975 char *zCmd; 8976 int i, x; 8977 if( nArg<2 ){ 8978 raw_printf(stderr, "Usage: .system COMMAND\n"); 8979 rc = 1; 8980 goto meta_command_exit; 8981 } 8982 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 8983 for(i=2; i<nArg; i++){ 8984 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 8985 zCmd, azArg[i]); 8986 } 8987 x = system(zCmd); 8988 sqlite3_free(zCmd); 8989 if( x ) raw_printf(stderr, "System command returns %d\n", x); 8990 }else 8991#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 8992 8993 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 8994 static const char *azBool[] = { "off", "on", "trigger", "full"}; 8995 int i; 8996 if( nArg!=1 ){ 8997 raw_printf(stderr, "Usage: .show\n"); 8998 rc = 1; 8999 goto meta_command_exit; 9000 } 9001 utf8_printf(p->out, "%12.12s: %s\n","echo", 9002 azBool[ShellHasFlag(p, SHFLG_Echo)]); 9003 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 9004 utf8_printf(p->out, "%12.12s: %s\n","explain", 9005 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 9006 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 9007 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 9008 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 9009 output_c_string(p->out, p->nullValue); 9010 raw_printf(p->out, "\n"); 9011 utf8_printf(p->out,"%12.12s: %s\n","output", 9012 strlen30(p->outfile) ? p->outfile : "stdout"); 9013 utf8_printf(p->out,"%12.12s: ", "colseparator"); 9014 output_c_string(p->out, p->colSeparator); 9015 raw_printf(p->out, "\n"); 9016 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 9017 output_c_string(p->out, p->rowSeparator); 9018 raw_printf(p->out, "\n"); 9019 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); 9020 utf8_printf(p->out, "%12.12s: ", "width"); 9021 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { 9022 raw_printf(p->out, "%d ", p->colWidth[i]); 9023 } 9024 raw_printf(p->out, "\n"); 9025 utf8_printf(p->out, "%12.12s: %s\n", "filename", 9026 p->zDbFilename ? p->zDbFilename : ""); 9027 }else 9028 9029 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 9030 if( nArg==2 ){ 9031 p->statsOn = (u8)booleanValue(azArg[1]); 9032 }else if( nArg==1 ){ 9033 display_stats(p->db, p, 0); 9034 }else{ 9035 raw_printf(stderr, "Usage: .stats ?on|off?\n"); 9036 rc = 1; 9037 } 9038 }else 9039 9040 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 9041 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 9042 || strncmp(azArg[0], "indexes", n)==0) ) 9043 ){ 9044 sqlite3_stmt *pStmt; 9045 char **azResult; 9046 int nRow, nAlloc; 9047 int ii; 9048 ShellText s; 9049 initText(&s); 9050 open_db(p, 0); 9051 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 9052 if( rc ){ 9053 sqlite3_finalize(pStmt); 9054 return shellDatabaseError(p->db); 9055 } 9056 9057 if( nArg>2 && c=='i' ){ 9058 /* It is an historical accident that the .indexes command shows an error 9059 ** when called with the wrong number of arguments whereas the .tables 9060 ** command does not. */ 9061 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 9062 rc = 1; 9063 sqlite3_finalize(pStmt); 9064 goto meta_command_exit; 9065 } 9066 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 9067 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 9068 if( zDbName==0 ) continue; 9069 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 9070 if( sqlite3_stricmp(zDbName, "main")==0 ){ 9071 appendText(&s, "SELECT name FROM ", 0); 9072 }else{ 9073 appendText(&s, "SELECT ", 0); 9074 appendText(&s, zDbName, '\''); 9075 appendText(&s, "||'.'||name FROM ", 0); 9076 } 9077 appendText(&s, zDbName, '"'); 9078 appendText(&s, ".sqlite_master ", 0); 9079 if( c=='t' ){ 9080 appendText(&s," WHERE type IN ('table','view')" 9081 " AND name NOT LIKE 'sqlite_%'" 9082 " AND name LIKE ?1", 0); 9083 }else{ 9084 appendText(&s," WHERE type='index'" 9085 " AND tbl_name LIKE ?1", 0); 9086 } 9087 } 9088 rc = sqlite3_finalize(pStmt); 9089 appendText(&s, " ORDER BY 1", 0); 9090 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 9091 freeText(&s); 9092 if( rc ) return shellDatabaseError(p->db); 9093 9094 /* Run the SQL statement prepared by the above block. Store the results 9095 ** as an array of nul-terminated strings in azResult[]. */ 9096 nRow = nAlloc = 0; 9097 azResult = 0; 9098 if( nArg>1 ){ 9099 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 9100 }else{ 9101 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 9102 } 9103 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9104 if( nRow>=nAlloc ){ 9105 char **azNew; 9106 int n2 = nAlloc*2 + 10; 9107 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 9108 if( azNew==0 ) shell_out_of_memory(); 9109 nAlloc = n2; 9110 azResult = azNew; 9111 } 9112 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 9113 if( 0==azResult[nRow] ) shell_out_of_memory(); 9114 nRow++; 9115 } 9116 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 9117 rc = shellDatabaseError(p->db); 9118 } 9119 9120 /* Pretty-print the contents of array azResult[] to the output */ 9121 if( rc==0 && nRow>0 ){ 9122 int len, maxlen = 0; 9123 int i, j; 9124 int nPrintCol, nPrintRow; 9125 for(i=0; i<nRow; i++){ 9126 len = strlen30(azResult[i]); 9127 if( len>maxlen ) maxlen = len; 9128 } 9129 nPrintCol = 80/(maxlen+2); 9130 if( nPrintCol<1 ) nPrintCol = 1; 9131 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 9132 for(i=0; i<nPrintRow; i++){ 9133 for(j=i; j<nRow; j+=nPrintRow){ 9134 char *zSp = j<nPrintRow ? "" : " "; 9135 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 9136 azResult[j] ? azResult[j]:""); 9137 } 9138 raw_printf(p->out, "\n"); 9139 } 9140 } 9141 9142 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 9143 sqlite3_free(azResult); 9144 }else 9145 9146 /* Begin redirecting output to the file "testcase-out.txt" */ 9147 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 9148 output_reset(p); 9149 p->out = output_file_open("testcase-out.txt", 0); 9150 if( p->out==0 ){ 9151 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 9152 } 9153 if( nArg>=2 ){ 9154 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 9155 }else{ 9156 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 9157 } 9158 }else 9159 9160#ifndef SQLITE_UNTESTABLE 9161 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 9162 static const struct { 9163 const char *zCtrlName; /* Name of a test-control option */ 9164 int ctrlCode; /* Integer code for that option */ 9165 const char *zUsage; /* Usage notes */ 9166 } aCtrl[] = { 9167 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, 9168 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, 9169 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ 9170 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ 9171 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, 9172 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" }, 9173 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */ 9174 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, 9175 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" }, 9176 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, 9177 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, 9178 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, 9179#ifdef YYCOVERAGE 9180 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, 9181#endif 9182 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, 9183 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, 9184 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, 9185 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" }, 9186 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" }, 9187 }; 9188 int testctrl = -1; 9189 int iCtrl = -1; 9190 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 9191 int isOk = 0; 9192 int i, n2; 9193 const char *zCmd = 0; 9194 9195 open_db(p, 0); 9196 zCmd = nArg>=2 ? azArg[1] : "help"; 9197 9198 /* The argument can optionally begin with "-" or "--" */ 9199 if( zCmd[0]=='-' && zCmd[1] ){ 9200 zCmd++; 9201 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 9202 } 9203 9204 /* --help lists all test-controls */ 9205 if( strcmp(zCmd,"help")==0 ){ 9206 utf8_printf(p->out, "Available test-controls:\n"); 9207 for(i=0; i<ArraySize(aCtrl); i++){ 9208 utf8_printf(p->out, " .testctrl %s %s\n", 9209 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 9210 } 9211 rc = 1; 9212 goto meta_command_exit; 9213 } 9214 9215 /* convert testctrl text option to value. allow any unique prefix 9216 ** of the option name, or a numerical value. */ 9217 n2 = strlen30(zCmd); 9218 for(i=0; i<ArraySize(aCtrl); i++){ 9219 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 9220 if( testctrl<0 ){ 9221 testctrl = aCtrl[i].ctrlCode; 9222 iCtrl = i; 9223 }else{ 9224 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 9225 "Use \".testctrl --help\" for help\n", zCmd); 9226 rc = 1; 9227 goto meta_command_exit; 9228 } 9229 } 9230 } 9231 if( testctrl<0 ){ 9232 utf8_printf(stderr,"Error: unknown test-control: %s\n" 9233 "Use \".testctrl --help\" for help\n", zCmd); 9234 }else{ 9235 switch(testctrl){ 9236 9237 /* sqlite3_test_control(int, db, int) */ 9238 case SQLITE_TESTCTRL_OPTIMIZATIONS: 9239 case SQLITE_TESTCTRL_RESERVE: 9240 if( nArg==3 ){ 9241 int opt = (int)strtol(azArg[2], 0, 0); 9242 rc2 = sqlite3_test_control(testctrl, p->db, opt); 9243 isOk = 3; 9244 } 9245 break; 9246 9247 /* sqlite3_test_control(int) */ 9248 case SQLITE_TESTCTRL_PRNG_SAVE: 9249 case SQLITE_TESTCTRL_PRNG_RESTORE: 9250 case SQLITE_TESTCTRL_PRNG_RESET: 9251 case SQLITE_TESTCTRL_BYTEORDER: 9252 if( nArg==2 ){ 9253 rc2 = sqlite3_test_control(testctrl); 9254 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 9255 } 9256 break; 9257 9258 /* sqlite3_test_control(int, uint) */ 9259 case SQLITE_TESTCTRL_PENDING_BYTE: 9260 if( nArg==3 ){ 9261 unsigned int opt = (unsigned int)integerValue(azArg[2]); 9262 rc2 = sqlite3_test_control(testctrl, opt); 9263 isOk = 3; 9264 } 9265 break; 9266 9267 /* sqlite3_test_control(int, int, sqlite3*) */ 9268 case SQLITE_TESTCTRL_PRNG_SEED: 9269 if( nArg==3 || nArg==4 ){ 9270 int ii = (int)integerValue(azArg[2]); 9271 sqlite3 *db; 9272 if( ii==0 && strcmp(azArg[2],"random")==0 ){ 9273 sqlite3_randomness(sizeof(ii),&ii); 9274 printf("-- random seed: %d\n", ii); 9275 } 9276 if( nArg==3 ){ 9277 db = 0; 9278 }else{ 9279 db = p->db; 9280 /* Make sure the schema has been loaded */ 9281 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 9282 } 9283 rc2 = sqlite3_test_control(testctrl, ii, db); 9284 isOk = 3; 9285 } 9286 break; 9287 9288 /* sqlite3_test_control(int, int) */ 9289 case SQLITE_TESTCTRL_ASSERT: 9290 case SQLITE_TESTCTRL_ALWAYS: 9291 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 9292 if( nArg==3 ){ 9293 int opt = booleanValue(azArg[2]); 9294 rc2 = sqlite3_test_control(testctrl, opt); 9295 isOk = 1; 9296 } 9297 break; 9298 9299 /* sqlite3_test_control(int, int) */ 9300 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 9301 case SQLITE_TESTCTRL_NEVER_CORRUPT: 9302 if( nArg==3 ){ 9303 int opt = booleanValue(azArg[2]); 9304 rc2 = sqlite3_test_control(testctrl, opt); 9305 isOk = 3; 9306 } 9307 break; 9308 9309 case SQLITE_TESTCTRL_IMPOSTER: 9310 if( nArg==5 ){ 9311 rc2 = sqlite3_test_control(testctrl, p->db, 9312 azArg[2], 9313 integerValue(azArg[3]), 9314 integerValue(azArg[4])); 9315 isOk = 3; 9316 } 9317 break; 9318 9319#ifdef YYCOVERAGE 9320 case SQLITE_TESTCTRL_PARSER_COVERAGE: 9321 if( nArg==2 ){ 9322 sqlite3_test_control(testctrl, p->out); 9323 isOk = 3; 9324 } 9325#endif 9326 } 9327 } 9328 if( isOk==0 && iCtrl>=0 ){ 9329 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage); 9330 rc = 1; 9331 }else if( isOk==1 ){ 9332 raw_printf(p->out, "%d\n", rc2); 9333 }else if( isOk==2 ){ 9334 raw_printf(p->out, "0x%08x\n", rc2); 9335 } 9336 }else 9337#endif /* !defined(SQLITE_UNTESTABLE) */ 9338 9339 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 9340 open_db(p, 0); 9341 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 9342 }else 9343 9344 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 9345 if( nArg==2 ){ 9346 enableTimer = booleanValue(azArg[1]); 9347 if( enableTimer && !HAS_TIMER ){ 9348 raw_printf(stderr, "Error: timer not available on this system.\n"); 9349 enableTimer = 0; 9350 } 9351 }else{ 9352 raw_printf(stderr, "Usage: .timer on|off\n"); 9353 rc = 1; 9354 } 9355 }else 9356 9357#ifndef SQLITE_OMIT_TRACE 9358 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 9359 int mType = 0; 9360 int jj; 9361 open_db(p, 0); 9362 for(jj=1; jj<nArg; jj++){ 9363 const char *z = azArg[jj]; 9364 if( z[0]=='-' ){ 9365 if( optionMatch(z, "expanded") ){ 9366 p->eTraceType = SHELL_TRACE_EXPANDED; 9367 } 9368#ifdef SQLITE_ENABLE_NORMALIZE 9369 else if( optionMatch(z, "normalized") ){ 9370 p->eTraceType = SHELL_TRACE_NORMALIZED; 9371 } 9372#endif 9373 else if( optionMatch(z, "plain") ){ 9374 p->eTraceType = SHELL_TRACE_PLAIN; 9375 } 9376 else if( optionMatch(z, "profile") ){ 9377 mType |= SQLITE_TRACE_PROFILE; 9378 } 9379 else if( optionMatch(z, "row") ){ 9380 mType |= SQLITE_TRACE_ROW; 9381 } 9382 else if( optionMatch(z, "stmt") ){ 9383 mType |= SQLITE_TRACE_STMT; 9384 } 9385 else if( optionMatch(z, "close") ){ 9386 mType |= SQLITE_TRACE_CLOSE; 9387 } 9388 else { 9389 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 9390 rc = 1; 9391 goto meta_command_exit; 9392 } 9393 }else{ 9394 output_file_close(p->traceOut); 9395 p->traceOut = output_file_open(azArg[1], 0); 9396 } 9397 } 9398 if( p->traceOut==0 ){ 9399 sqlite3_trace_v2(p->db, 0, 0, 0); 9400 }else{ 9401 if( mType==0 ) mType = SQLITE_TRACE_STMT; 9402 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 9403 } 9404 }else 9405#endif /* !defined(SQLITE_OMIT_TRACE) */ 9406 9407#ifdef SQLITE_DEBUG 9408 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){ 9409 int ii; 9410 if( nArg<2 ){ 9411 raw_printf(stderr, "Usage: .unmodule NAME ...\n"); 9412 rc = 1; 9413 goto meta_command_exit; 9414 } 9415 open_db(p, 0); 9416 for(ii=1; ii<nArg; ii++){ 9417 sqlite3_create_module(p->db, azArg[ii], 0, 0); 9418 } 9419 }else 9420#endif 9421 9422#if SQLITE_USER_AUTHENTICATION 9423 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 9424 if( nArg<2 ){ 9425 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 9426 rc = 1; 9427 goto meta_command_exit; 9428 } 9429 open_db(p, 0); 9430 if( strcmp(azArg[1],"login")==0 ){ 9431 if( nArg!=4 ){ 9432 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 9433 rc = 1; 9434 goto meta_command_exit; 9435 } 9436 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3])); 9437 if( rc ){ 9438 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 9439 rc = 1; 9440 } 9441 }else if( strcmp(azArg[1],"add")==0 ){ 9442 if( nArg!=5 ){ 9443 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 9444 rc = 1; 9445 goto meta_command_exit; 9446 } 9447 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9448 booleanValue(azArg[4])); 9449 if( rc ){ 9450 raw_printf(stderr, "User-Add failed: %d\n", rc); 9451 rc = 1; 9452 } 9453 }else if( strcmp(azArg[1],"edit")==0 ){ 9454 if( nArg!=5 ){ 9455 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 9456 rc = 1; 9457 goto meta_command_exit; 9458 } 9459 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9460 booleanValue(azArg[4])); 9461 if( rc ){ 9462 raw_printf(stderr, "User-Edit failed: %d\n", rc); 9463 rc = 1; 9464 } 9465 }else if( strcmp(azArg[1],"delete")==0 ){ 9466 if( nArg!=3 ){ 9467 raw_printf(stderr, "Usage: .user delete USER\n"); 9468 rc = 1; 9469 goto meta_command_exit; 9470 } 9471 rc = sqlite3_user_delete(p->db, azArg[2]); 9472 if( rc ){ 9473 raw_printf(stderr, "User-Delete failed: %d\n", rc); 9474 rc = 1; 9475 } 9476 }else{ 9477 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 9478 rc = 1; 9479 goto meta_command_exit; 9480 } 9481 }else 9482#endif /* SQLITE_USER_AUTHENTICATION */ 9483 9484 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 9485 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 9486 sqlite3_libversion(), sqlite3_sourceid()); 9487#if SQLITE_HAVE_ZLIB 9488 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 9489#endif 9490#define CTIMEOPT_VAL_(opt) #opt 9491#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 9492#if defined(__clang__) && defined(__clang_major__) 9493 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 9494 CTIMEOPT_VAL(__clang_minor__) "." 9495 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 9496#elif defined(_MSC_VER) 9497 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 9498#elif defined(__GNUC__) && defined(__VERSION__) 9499 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 9500#endif 9501 }else 9502 9503 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 9504 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9505 sqlite3_vfs *pVfs = 0; 9506 if( p->db ){ 9507 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 9508 if( pVfs ){ 9509 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 9510 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9511 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9512 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9513 } 9514 } 9515 }else 9516 9517 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 9518 sqlite3_vfs *pVfs; 9519 sqlite3_vfs *pCurrent = 0; 9520 if( p->db ){ 9521 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 9522 } 9523 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 9524 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 9525 pVfs==pCurrent ? " <--- CURRENT" : ""); 9526 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9527 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9528 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9529 if( pVfs->pNext ){ 9530 raw_printf(p->out, "-----------------------------------\n"); 9531 } 9532 } 9533 }else 9534 9535 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 9536 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9537 char *zVfsName = 0; 9538 if( p->db ){ 9539 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 9540 if( zVfsName ){ 9541 utf8_printf(p->out, "%s\n", zVfsName); 9542 sqlite3_free(zVfsName); 9543 } 9544 } 9545 }else 9546 9547#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 9548 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 9549 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; 9550 }else 9551#endif 9552 9553 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 9554 int j; 9555 assert( nArg<=ArraySize(azArg) ); 9556 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ 9557 p->colWidth[j-1] = (int)integerValue(azArg[j]); 9558 } 9559 }else 9560 9561 { 9562 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 9563 " \"%s\". Enter \".help\" for help\n", azArg[0]); 9564 rc = 1; 9565 } 9566 9567meta_command_exit: 9568 if( p->outCount ){ 9569 p->outCount--; 9570 if( p->outCount==0 ) output_reset(p); 9571 } 9572 return rc; 9573} 9574 9575/* 9576** Return TRUE if a semicolon occurs anywhere in the first N characters 9577** of string z[]. 9578*/ 9579static int line_contains_semicolon(const char *z, int N){ 9580 int i; 9581 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } 9582 return 0; 9583} 9584 9585/* 9586** Test to see if a line consists entirely of whitespace. 9587*/ 9588static int _all_whitespace(const char *z){ 9589 for(; *z; z++){ 9590 if( IsSpace(z[0]) ) continue; 9591 if( *z=='/' && z[1]=='*' ){ 9592 z += 2; 9593 while( *z && (*z!='*' || z[1]!='/') ){ z++; } 9594 if( *z==0 ) return 0; 9595 z++; 9596 continue; 9597 } 9598 if( *z=='-' && z[1]=='-' ){ 9599 z += 2; 9600 while( *z && *z!='\n' ){ z++; } 9601 if( *z==0 ) return 1; 9602 continue; 9603 } 9604 return 0; 9605 } 9606 return 1; 9607} 9608 9609/* 9610** Return TRUE if the line typed in is an SQL command terminator other 9611** than a semi-colon. The SQL Server style "go" command is understood 9612** as is the Oracle "/". 9613*/ 9614static int line_is_command_terminator(const char *zLine){ 9615 while( IsSpace(zLine[0]) ){ zLine++; }; 9616 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ 9617 return 1; /* Oracle */ 9618 } 9619 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' 9620 && _all_whitespace(&zLine[2]) ){ 9621 return 1; /* SQL Server */ 9622 } 9623 return 0; 9624} 9625 9626/* 9627** We need a default sqlite3_complete() implementation to use in case 9628** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 9629** any arbitrary text is a complete SQL statement. This is not very 9630** user-friendly, but it does seem to work. 9631*/ 9632#ifdef SQLITE_OMIT_COMPLETE 9633#define sqlite3_complete(x) 1 9634#endif 9635 9636/* 9637** Return true if zSql is a complete SQL statement. Return false if it 9638** ends in the middle of a string literal or C-style comment. 9639*/ 9640static int line_is_complete(char *zSql, int nSql){ 9641 int rc; 9642 if( zSql==0 ) return 1; 9643 zSql[nSql] = ';'; 9644 zSql[nSql+1] = 0; 9645 rc = sqlite3_complete(zSql); 9646 zSql[nSql] = 0; 9647 return rc; 9648} 9649 9650/* 9651** Run a single line of SQL. Return the number of errors. 9652*/ 9653static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 9654 int rc; 9655 char *zErrMsg = 0; 9656 9657 open_db(p, 0); 9658 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 9659 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 9660 BEGIN_TIMER; 9661 rc = shell_exec(p, zSql, &zErrMsg); 9662 END_TIMER; 9663 if( rc || zErrMsg ){ 9664 char zPrefix[100]; 9665 if( in!=0 || !stdin_is_interactive ){ 9666 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 9667 "Error: near line %d:", startline); 9668 }else{ 9669 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 9670 } 9671 if( zErrMsg!=0 ){ 9672 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 9673 sqlite3_free(zErrMsg); 9674 zErrMsg = 0; 9675 }else{ 9676 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 9677 } 9678 return 1; 9679 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 9680 raw_printf(p->out, "changes: %3d total_changes: %d\n", 9681 sqlite3_changes(p->db), sqlite3_total_changes(p->db)); 9682 } 9683 return 0; 9684} 9685 9686 9687/* 9688** Read input from *in and process it. If *in==0 then input 9689** is interactive - the user is typing it it. Otherwise, input 9690** is coming from a file or device. A prompt is issued and history 9691** is saved only if input is interactive. An interrupt signal will 9692** cause this routine to exit immediately, unless input is interactive. 9693** 9694** Return the number of errors. 9695*/ 9696static int process_input(ShellState *p){ 9697 char *zLine = 0; /* A single input line */ 9698 char *zSql = 0; /* Accumulated SQL text */ 9699 int nLine; /* Length of current line */ 9700 int nSql = 0; /* Bytes of zSql[] used */ 9701 int nAlloc = 0; /* Allocated zSql[] space */ 9702 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ 9703 int rc; /* Error code */ 9704 int errCnt = 0; /* Number of errors seen */ 9705 int startline = 0; /* Line number for start of current input */ 9706 9707 p->lineno = 0; 9708 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 9709 fflush(p->out); 9710 zLine = one_input_line(p->in, zLine, nSql>0); 9711 if( zLine==0 ){ 9712 /* End of input */ 9713 if( p->in==0 && stdin_is_interactive ) printf("\n"); 9714 break; 9715 } 9716 if( seenInterrupt ){ 9717 if( p->in!=0 ) break; 9718 seenInterrupt = 0; 9719 } 9720 p->lineno++; 9721 if( nSql==0 && _all_whitespace(zLine) ){ 9722 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9723 continue; 9724 } 9725 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 9726 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9727 if( zLine[0]=='.' ){ 9728 rc = do_meta_command(zLine, p); 9729 if( rc==2 ){ /* exit requested */ 9730 break; 9731 }else if( rc ){ 9732 errCnt++; 9733 } 9734 } 9735 continue; 9736 } 9737 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ 9738 memcpy(zLine,";",2); 9739 } 9740 nLine = strlen30(zLine); 9741 if( nSql+nLine+2>=nAlloc ){ 9742 nAlloc = nSql+nLine+100; 9743 zSql = realloc(zSql, nAlloc); 9744 if( zSql==0 ) shell_out_of_memory(); 9745 } 9746 nSqlPrior = nSql; 9747 if( nSql==0 ){ 9748 int i; 9749 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 9750 assert( nAlloc>0 && zSql!=0 ); 9751 memcpy(zSql, zLine+i, nLine+1-i); 9752 startline = p->lineno; 9753 nSql = nLine-i; 9754 }else{ 9755 zSql[nSql++] = '\n'; 9756 memcpy(zSql+nSql, zLine, nLine+1); 9757 nSql += nLine; 9758 } 9759 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) 9760 && sqlite3_complete(zSql) ){ 9761 errCnt += runOneSqlLine(p, zSql, p->in, startline); 9762 nSql = 0; 9763 if( p->outCount ){ 9764 output_reset(p); 9765 p->outCount = 0; 9766 }else{ 9767 clearTempFile(p); 9768 } 9769 }else if( nSql && _all_whitespace(zSql) ){ 9770 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 9771 nSql = 0; 9772 } 9773 } 9774 if( nSql && !_all_whitespace(zSql) ){ 9775 errCnt += runOneSqlLine(p, zSql, p->in, startline); 9776 } 9777 free(zSql); 9778 free(zLine); 9779 return errCnt>0; 9780} 9781 9782/* 9783** Return a pathname which is the user's home directory. A 9784** 0 return indicates an error of some kind. 9785*/ 9786static char *find_home_dir(int clearFlag){ 9787 static char *home_dir = NULL; 9788 if( clearFlag ){ 9789 free(home_dir); 9790 home_dir = 0; 9791 return 0; 9792 } 9793 if( home_dir ) return home_dir; 9794 9795#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 9796 && !defined(__RTP__) && !defined(_WRS_KERNEL) 9797 { 9798 struct passwd *pwent; 9799 uid_t uid = getuid(); 9800 if( (pwent=getpwuid(uid)) != NULL) { 9801 home_dir = pwent->pw_dir; 9802 } 9803 } 9804#endif 9805 9806#if defined(_WIN32_WCE) 9807 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 9808 */ 9809 home_dir = "/"; 9810#else 9811 9812#if defined(_WIN32) || defined(WIN32) 9813 if (!home_dir) { 9814 home_dir = getenv("USERPROFILE"); 9815 } 9816#endif 9817 9818 if (!home_dir) { 9819 home_dir = getenv("HOME"); 9820 } 9821 9822#if defined(_WIN32) || defined(WIN32) 9823 if (!home_dir) { 9824 char *zDrive, *zPath; 9825 int n; 9826 zDrive = getenv("HOMEDRIVE"); 9827 zPath = getenv("HOMEPATH"); 9828 if( zDrive && zPath ){ 9829 n = strlen30(zDrive) + strlen30(zPath) + 1; 9830 home_dir = malloc( n ); 9831 if( home_dir==0 ) return 0; 9832 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 9833 return home_dir; 9834 } 9835 home_dir = "c:\\"; 9836 } 9837#endif 9838 9839#endif /* !_WIN32_WCE */ 9840 9841 if( home_dir ){ 9842 int n = strlen30(home_dir) + 1; 9843 char *z = malloc( n ); 9844 if( z ) memcpy(z, home_dir, n); 9845 home_dir = z; 9846 } 9847 9848 return home_dir; 9849} 9850 9851/* 9852** Read input from the file given by sqliterc_override. Or if that 9853** parameter is NULL, take input from ~/.sqliterc 9854** 9855** Returns the number of errors. 9856*/ 9857static void process_sqliterc( 9858 ShellState *p, /* Configuration data */ 9859 const char *sqliterc_override /* Name of config file. NULL to use default */ 9860){ 9861 char *home_dir = NULL; 9862 const char *sqliterc = sqliterc_override; 9863 char *zBuf = 0; 9864 FILE *inSaved = p->in; 9865 int savedLineno = p->lineno; 9866 9867 if (sqliterc == NULL) { 9868 home_dir = find_home_dir(0); 9869 if( home_dir==0 ){ 9870 raw_printf(stderr, "-- warning: cannot find home directory;" 9871 " cannot read ~/.sqliterc\n"); 9872 return; 9873 } 9874 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 9875 sqliterc = zBuf; 9876 } 9877 p->in = fopen(sqliterc,"rb"); 9878 if( p->in ){ 9879 if( stdin_is_interactive ){ 9880 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 9881 } 9882 process_input(p); 9883 fclose(p->in); 9884 } 9885 p->in = inSaved; 9886 p->lineno = savedLineno; 9887 sqlite3_free(zBuf); 9888} 9889 9890/* 9891** Show available command line options 9892*/ 9893static const char zOptions[] = 9894#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 9895 " -A ARGS... run \".archive ARGS\" and exit\n" 9896#endif 9897 " -append append the database to the end of the file\n" 9898 " -ascii set output mode to 'ascii'\n" 9899 " -bail stop after hitting an error\n" 9900 " -batch force batch I/O\n" 9901 " -column set output mode to 'column'\n" 9902 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 9903 " -csv set output mode to 'csv'\n" 9904#if defined(SQLITE_ENABLE_DESERIALIZE) 9905 " -deserialize open the database using sqlite3_deserialize()\n" 9906#endif 9907 " -echo print commands before execution\n" 9908 " -init FILENAME read/process named file\n" 9909 " -[no]header turn headers on or off\n" 9910#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 9911 " -heap SIZE Size of heap for memsys3 or memsys5\n" 9912#endif 9913 " -help show this message\n" 9914 " -html set output mode to HTML\n" 9915 " -interactive force interactive I/O\n" 9916 " -line set output mode to 'line'\n" 9917 " -list set output mode to 'list'\n" 9918 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 9919#if defined(SQLITE_ENABLE_DESERIALIZE) 9920 " -maxsize N maximum size for a --deserialize database\n" 9921#endif 9922 " -memtrace trace all memory allocations and deallocations\n" 9923 " -mmap N default mmap size set to N\n" 9924#ifdef SQLITE_ENABLE_MULTIPLEX 9925 " -multiplex enable the multiplexor VFS\n" 9926#endif 9927 " -newline SEP set output row separator. Default: '\\n'\n" 9928 " -nullvalue TEXT set text string for NULL values. Default ''\n" 9929 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 9930 " -quote set output mode to 'quote'\n" 9931 " -readonly open the database read-only\n" 9932 " -separator SEP set output column separator. Default: '|'\n" 9933#ifdef SQLITE_ENABLE_SORTER_REFERENCES 9934 " -sorterref SIZE sorter references threshold size\n" 9935#endif 9936 " -stats print memory stats before each finalize\n" 9937 " -version show SQLite version\n" 9938 " -vfs NAME use NAME as the default VFS\n" 9939#ifdef SQLITE_ENABLE_VFSTRACE 9940 " -vfstrace enable tracing of all VFS calls\n" 9941#endif 9942#ifdef SQLITE_HAVE_ZLIB 9943 " -zip open the file as a ZIP Archive\n" 9944#endif 9945; 9946static void usage(int showDetail){ 9947 utf8_printf(stderr, 9948 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 9949 "FILENAME is the name of an SQLite database. A new database is created\n" 9950 "if the file does not previously exist.\n", Argv0); 9951 if( showDetail ){ 9952 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 9953 }else{ 9954 raw_printf(stderr, "Use the -help option for additional information\n"); 9955 } 9956 exit(1); 9957} 9958 9959/* 9960** Internal check: Verify that the SQLite is uninitialized. Print a 9961** error message if it is initialized. 9962*/ 9963static void verify_uninitialized(void){ 9964 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 9965 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 9966 " initialization.\n"); 9967 } 9968} 9969 9970/* 9971** Initialize the state information in data 9972*/ 9973static void main_init(ShellState *data) { 9974 memset(data, 0, sizeof(*data)); 9975 data->normalMode = data->cMode = data->mode = MODE_List; 9976 data->autoExplain = 1; 9977 memcpy(data->colSeparator,SEP_Column, 2); 9978 memcpy(data->rowSeparator,SEP_Row, 2); 9979 data->showHeader = 0; 9980 data->shellFlgs = SHFLG_Lookaside; 9981 verify_uninitialized(); 9982 sqlite3_config(SQLITE_CONFIG_URI, 1); 9983 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 9984 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 9985 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 9986 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 9987} 9988 9989/* 9990** Output text to the console in a font that attracts extra attention. 9991*/ 9992#ifdef _WIN32 9993static void printBold(const char *zText){ 9994 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 9995 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 9996 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 9997 SetConsoleTextAttribute(out, 9998 FOREGROUND_RED|FOREGROUND_INTENSITY 9999 ); 10000 printf("%s", zText); 10001 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 10002} 10003#else 10004static void printBold(const char *zText){ 10005 printf("\033[1m%s\033[0m", zText); 10006} 10007#endif 10008 10009/* 10010** Get the argument to an --option. Throw an error and die if no argument 10011** is available. 10012*/ 10013static char *cmdline_option_value(int argc, char **argv, int i){ 10014 if( i==argc ){ 10015 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 10016 argv[0], argv[argc-1]); 10017 exit(1); 10018 } 10019 return argv[i]; 10020} 10021 10022#ifndef SQLITE_SHELL_IS_UTF8 10023# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) 10024# define SQLITE_SHELL_IS_UTF8 (0) 10025# else 10026# define SQLITE_SHELL_IS_UTF8 (1) 10027# endif 10028#endif 10029 10030#if SQLITE_SHELL_IS_UTF8 10031int SQLITE_CDECL main(int argc, char **argv){ 10032#else 10033int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 10034 char **argv; 10035#endif 10036 char *zErrMsg = 0; 10037 ShellState data; 10038 const char *zInitFile = 0; 10039 int i; 10040 int rc = 0; 10041 int warnInmemoryDb = 0; 10042 int readStdin = 1; 10043 int nCmd = 0; 10044 char **azCmd = 0; 10045 const char *zVfs = 0; /* Value of -vfs command-line option */ 10046#if !SQLITE_SHELL_IS_UTF8 10047 char **argvToFree = 0; 10048 int argcToFree = 0; 10049#endif 10050 10051 setBinaryMode(stdin, 0); 10052 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 10053 stdin_is_interactive = isatty(0); 10054 stdout_is_console = isatty(1); 10055 10056#if !defined(_WIN32_WCE) 10057 if( getenv("SQLITE_DEBUG_BREAK") ){ 10058 if( isatty(0) && isatty(2) ){ 10059 fprintf(stderr, 10060 "attach debugger to process %d and press any key to continue.\n", 10061 GETPID()); 10062 fgetc(stdin); 10063 }else{ 10064#if defined(_WIN32) || defined(WIN32) 10065 DebugBreak(); 10066#elif defined(SIGTRAP) 10067 raise(SIGTRAP); 10068#endif 10069 } 10070 } 10071#endif 10072 10073#if USE_SYSTEM_SQLITE+0!=1 10074 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 10075 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 10076 sqlite3_sourceid(), SQLITE_SOURCE_ID); 10077 exit(1); 10078 } 10079#endif 10080 main_init(&data); 10081 10082 /* On Windows, we must translate command-line arguments into UTF-8. 10083 ** The SQLite memory allocator subsystem has to be enabled in order to 10084 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 10085 ** subsequent sqlite3_config() calls will work. So copy all results into 10086 ** memory that does not come from the SQLite memory allocator. 10087 */ 10088#if !SQLITE_SHELL_IS_UTF8 10089 sqlite3_initialize(); 10090 argvToFree = malloc(sizeof(argv[0])*argc*2); 10091 argcToFree = argc; 10092 argv = argvToFree + argc; 10093 if( argv==0 ) shell_out_of_memory(); 10094 for(i=0; i<argc; i++){ 10095 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 10096 int n; 10097 if( z==0 ) shell_out_of_memory(); 10098 n = (int)strlen(z); 10099 argv[i] = malloc( n+1 ); 10100 if( argv[i]==0 ) shell_out_of_memory(); 10101 memcpy(argv[i], z, n+1); 10102 argvToFree[i] = argv[i]; 10103 sqlite3_free(z); 10104 } 10105 sqlite3_shutdown(); 10106#endif 10107 10108 assert( argc>=1 && argv && argv[0] ); 10109 Argv0 = argv[0]; 10110 10111 /* Make sure we have a valid signal handler early, before anything 10112 ** else is done. 10113 */ 10114#ifdef SIGINT 10115 signal(SIGINT, interrupt_handler); 10116#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 10117 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 10118#endif 10119 10120#ifdef SQLITE_SHELL_DBNAME_PROC 10121 { 10122 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 10123 ** of a C-function that will provide the name of the database file. Use 10124 ** this compile-time option to embed this shell program in larger 10125 ** applications. */ 10126 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 10127 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); 10128 warnInmemoryDb = 0; 10129 } 10130#endif 10131 10132 /* Do an initial pass through the command-line argument to locate 10133 ** the name of the database file, the name of the initialization file, 10134 ** the size of the alternative malloc heap, 10135 ** and the first command to execute. 10136 */ 10137 verify_uninitialized(); 10138 for(i=1; i<argc; i++){ 10139 char *z; 10140 z = argv[i]; 10141 if( z[0]!='-' ){ 10142 if( data.zDbFilename==0 ){ 10143 data.zDbFilename = z; 10144 }else{ 10145 /* Excesss arguments are interpreted as SQL (or dot-commands) and 10146 ** mean that nothing is read from stdin */ 10147 readStdin = 0; 10148 nCmd++; 10149 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 10150 if( azCmd==0 ) shell_out_of_memory(); 10151 azCmd[nCmd-1] = z; 10152 } 10153 } 10154 if( z[1]=='-' ) z++; 10155 if( strcmp(z,"-separator")==0 10156 || strcmp(z,"-nullvalue")==0 10157 || strcmp(z,"-newline")==0 10158 || strcmp(z,"-cmd")==0 10159 ){ 10160 (void)cmdline_option_value(argc, argv, ++i); 10161 }else if( strcmp(z,"-init")==0 ){ 10162 zInitFile = cmdline_option_value(argc, argv, ++i); 10163 }else if( strcmp(z,"-batch")==0 ){ 10164 /* Need to check for batch mode here to so we can avoid printing 10165 ** informational messages (like from process_sqliterc) before 10166 ** we do the actual processing of arguments later in a second pass. 10167 */ 10168 stdin_is_interactive = 0; 10169 }else if( strcmp(z,"-heap")==0 ){ 10170#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 10171 const char *zSize; 10172 sqlite3_int64 szHeap; 10173 10174 zSize = cmdline_option_value(argc, argv, ++i); 10175 szHeap = integerValue(zSize); 10176 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 10177 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 10178#else 10179 (void)cmdline_option_value(argc, argv, ++i); 10180#endif 10181 }else if( strcmp(z,"-pagecache")==0 ){ 10182 int n, sz; 10183 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10184 if( sz>70000 ) sz = 70000; 10185 if( sz<0 ) sz = 0; 10186 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10187 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 10188 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 10189 data.shellFlgs |= SHFLG_Pagecache; 10190 }else if( strcmp(z,"-lookaside")==0 ){ 10191 int n, sz; 10192 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10193 if( sz<0 ) sz = 0; 10194 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10195 if( n<0 ) n = 0; 10196 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 10197 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 10198#ifdef SQLITE_ENABLE_VFSTRACE 10199 }else if( strcmp(z,"-vfstrace")==0 ){ 10200 extern int vfstrace_register( 10201 const char *zTraceName, 10202 const char *zOldVfsName, 10203 int (*xOut)(const char*,void*), 10204 void *pOutArg, 10205 int makeDefault 10206 ); 10207 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 10208#endif 10209#ifdef SQLITE_ENABLE_MULTIPLEX 10210 }else if( strcmp(z,"-multiplex")==0 ){ 10211 extern int sqlite3_multiple_initialize(const char*,int); 10212 sqlite3_multiplex_initialize(0, 1); 10213#endif 10214 }else if( strcmp(z,"-mmap")==0 ){ 10215 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 10216 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 10217#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10218 }else if( strcmp(z,"-sorterref")==0 ){ 10219 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 10220 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 10221#endif 10222 }else if( strcmp(z,"-vfs")==0 ){ 10223 zVfs = cmdline_option_value(argc, argv, ++i); 10224#ifdef SQLITE_HAVE_ZLIB 10225 }else if( strcmp(z,"-zip")==0 ){ 10226 data.openMode = SHELL_OPEN_ZIPFILE; 10227#endif 10228 }else if( strcmp(z,"-append")==0 ){ 10229 data.openMode = SHELL_OPEN_APPENDVFS; 10230#ifdef SQLITE_ENABLE_DESERIALIZE 10231 }else if( strcmp(z,"-deserialize")==0 ){ 10232 data.openMode = SHELL_OPEN_DESERIALIZE; 10233 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10234 data.szMax = integerValue(argv[++i]); 10235#endif 10236 }else if( strcmp(z,"-readonly")==0 ){ 10237 data.openMode = SHELL_OPEN_READONLY; 10238#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10239 }else if( strncmp(z, "-A",2)==0 ){ 10240 /* All remaining command-line arguments are passed to the ".archive" 10241 ** command, so ignore them */ 10242 break; 10243#endif 10244 }else if( strcmp(z, "-memtrace")==0 ){ 10245 sqlite3MemTraceActivate(stderr); 10246 } 10247 } 10248 verify_uninitialized(); 10249 10250 10251#ifdef SQLITE_SHELL_INIT_PROC 10252 { 10253 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 10254 ** of a C-function that will perform initialization actions on SQLite that 10255 ** occur just before or after sqlite3_initialize(). Use this compile-time 10256 ** option to embed this shell program in larger applications. */ 10257 extern void SQLITE_SHELL_INIT_PROC(void); 10258 SQLITE_SHELL_INIT_PROC(); 10259 } 10260#else 10261 /* All the sqlite3_config() calls have now been made. So it is safe 10262 ** to call sqlite3_initialize() and process any command line -vfs option. */ 10263 sqlite3_initialize(); 10264#endif 10265 10266 if( zVfs ){ 10267 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 10268 if( pVfs ){ 10269 sqlite3_vfs_register(pVfs, 1); 10270 }else{ 10271 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 10272 exit(1); 10273 } 10274 } 10275 10276 if( data.zDbFilename==0 ){ 10277#ifndef SQLITE_OMIT_MEMORYDB 10278 data.zDbFilename = ":memory:"; 10279 warnInmemoryDb = argc==1; 10280#else 10281 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 10282 return 1; 10283#endif 10284 } 10285 data.out = stdout; 10286 sqlite3_appendvfs_init(0,0,0); 10287 10288 /* Go ahead and open the database file if it already exists. If the 10289 ** file does not exist, delay opening it. This prevents empty database 10290 ** files from being created if a user mistypes the database name argument 10291 ** to the sqlite command-line tool. 10292 */ 10293 if( access(data.zDbFilename, 0)==0 ){ 10294 open_db(&data, 0); 10295 } 10296 10297 /* Process the initialization file if there is one. If no -init option 10298 ** is given on the command line, look for a file named ~/.sqliterc and 10299 ** try to process it. 10300 */ 10301 process_sqliterc(&data,zInitFile); 10302 10303 /* Make a second pass through the command-line argument and set 10304 ** options. This second pass is delayed until after the initialization 10305 ** file is processed so that the command-line arguments will override 10306 ** settings in the initialization file. 10307 */ 10308 for(i=1; i<argc; i++){ 10309 char *z = argv[i]; 10310 if( z[0]!='-' ) continue; 10311 if( z[1]=='-' ){ z++; } 10312 if( strcmp(z,"-init")==0 ){ 10313 i++; 10314 }else if( strcmp(z,"-html")==0 ){ 10315 data.mode = MODE_Html; 10316 }else if( strcmp(z,"-list")==0 ){ 10317 data.mode = MODE_List; 10318 }else if( strcmp(z,"-quote")==0 ){ 10319 data.mode = MODE_Quote; 10320 }else if( strcmp(z,"-line")==0 ){ 10321 data.mode = MODE_Line; 10322 }else if( strcmp(z,"-column")==0 ){ 10323 data.mode = MODE_Column; 10324 }else if( strcmp(z,"-csv")==0 ){ 10325 data.mode = MODE_Csv; 10326 memcpy(data.colSeparator,",",2); 10327#ifdef SQLITE_HAVE_ZLIB 10328 }else if( strcmp(z,"-zip")==0 ){ 10329 data.openMode = SHELL_OPEN_ZIPFILE; 10330#endif 10331 }else if( strcmp(z,"-append")==0 ){ 10332 data.openMode = SHELL_OPEN_APPENDVFS; 10333#ifdef SQLITE_ENABLE_DESERIALIZE 10334 }else if( strcmp(z,"-deserialize")==0 ){ 10335 data.openMode = SHELL_OPEN_DESERIALIZE; 10336 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10337 data.szMax = integerValue(argv[++i]); 10338#endif 10339 }else if( strcmp(z,"-readonly")==0 ){ 10340 data.openMode = SHELL_OPEN_READONLY; 10341 }else if( strcmp(z,"-ascii")==0 ){ 10342 data.mode = MODE_Ascii; 10343 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10344 SEP_Unit); 10345 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10346 SEP_Record); 10347 }else if( strcmp(z,"-separator")==0 ){ 10348 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10349 "%s",cmdline_option_value(argc,argv,++i)); 10350 }else if( strcmp(z,"-newline")==0 ){ 10351 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10352 "%s",cmdline_option_value(argc,argv,++i)); 10353 }else if( strcmp(z,"-nullvalue")==0 ){ 10354 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 10355 "%s",cmdline_option_value(argc,argv,++i)); 10356 }else if( strcmp(z,"-header")==0 ){ 10357 data.showHeader = 1; 10358 }else if( strcmp(z,"-noheader")==0 ){ 10359 data.showHeader = 0; 10360 }else if( strcmp(z,"-echo")==0 ){ 10361 ShellSetFlag(&data, SHFLG_Echo); 10362 }else if( strcmp(z,"-eqp")==0 ){ 10363 data.autoEQP = AUTOEQP_on; 10364 }else if( strcmp(z,"-eqpfull")==0 ){ 10365 data.autoEQP = AUTOEQP_full; 10366 }else if( strcmp(z,"-stats")==0 ){ 10367 data.statsOn = 1; 10368 }else if( strcmp(z,"-scanstats")==0 ){ 10369 data.scanstatsOn = 1; 10370 }else if( strcmp(z,"-backslash")==0 ){ 10371 /* Undocumented command-line option: -backslash 10372 ** Causes C-style backslash escapes to be evaluated in SQL statements 10373 ** prior to sending the SQL into SQLite. Useful for injecting 10374 ** crazy bytes in the middle of SQL statements for testing and debugging. 10375 */ 10376 ShellSetFlag(&data, SHFLG_Backslash); 10377 }else if( strcmp(z,"-bail")==0 ){ 10378 bail_on_error = 1; 10379 }else if( strcmp(z,"-version")==0 ){ 10380 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 10381 return 0; 10382 }else if( strcmp(z,"-interactive")==0 ){ 10383 stdin_is_interactive = 1; 10384 }else if( strcmp(z,"-batch")==0 ){ 10385 stdin_is_interactive = 0; 10386 }else if( strcmp(z,"-heap")==0 ){ 10387 i++; 10388 }else if( strcmp(z,"-pagecache")==0 ){ 10389 i+=2; 10390 }else if( strcmp(z,"-lookaside")==0 ){ 10391 i+=2; 10392 }else if( strcmp(z,"-mmap")==0 ){ 10393 i++; 10394 }else if( strcmp(z,"-memtrace")==0 ){ 10395 i++; 10396#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10397 }else if( strcmp(z,"-sorterref")==0 ){ 10398 i++; 10399#endif 10400 }else if( strcmp(z,"-vfs")==0 ){ 10401 i++; 10402#ifdef SQLITE_ENABLE_VFSTRACE 10403 }else if( strcmp(z,"-vfstrace")==0 ){ 10404 i++; 10405#endif 10406#ifdef SQLITE_ENABLE_MULTIPLEX 10407 }else if( strcmp(z,"-multiplex")==0 ){ 10408 i++; 10409#endif 10410 }else if( strcmp(z,"-help")==0 ){ 10411 usage(1); 10412 }else if( strcmp(z,"-cmd")==0 ){ 10413 /* Run commands that follow -cmd first and separately from commands 10414 ** that simply appear on the command-line. This seems goofy. It would 10415 ** be better if all commands ran in the order that they appear. But 10416 ** we retain the goofy behavior for historical compatibility. */ 10417 if( i==argc-1 ) break; 10418 z = cmdline_option_value(argc,argv,++i); 10419 if( z[0]=='.' ){ 10420 rc = do_meta_command(z, &data); 10421 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 10422 }else{ 10423 open_db(&data, 0); 10424 rc = shell_exec(&data, z, &zErrMsg); 10425 if( zErrMsg!=0 ){ 10426 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10427 if( bail_on_error ) return rc!=0 ? rc : 1; 10428 }else if( rc!=0 ){ 10429 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 10430 if( bail_on_error ) return rc; 10431 } 10432 } 10433#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10434 }else if( strncmp(z, "-A", 2)==0 ){ 10435 if( nCmd>0 ){ 10436 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 10437 " with \"%s\"\n", z); 10438 return 1; 10439 } 10440 open_db(&data, OPEN_DB_ZIPFILE); 10441 if( z[2] ){ 10442 argv[i] = &z[2]; 10443 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 10444 }else{ 10445 arDotCommand(&data, 1, argv+i, argc-i); 10446 } 10447 readStdin = 0; 10448 break; 10449#endif 10450 }else{ 10451 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 10452 raw_printf(stderr,"Use -help for a list of options.\n"); 10453 return 1; 10454 } 10455 data.cMode = data.mode; 10456 } 10457 10458 if( !readStdin ){ 10459 /* Run all arguments that do not begin with '-' as if they were separate 10460 ** command-line inputs, except for the argToSkip argument which contains 10461 ** the database filename. 10462 */ 10463 for(i=0; i<nCmd; i++){ 10464 if( azCmd[i][0]=='.' ){ 10465 rc = do_meta_command(azCmd[i], &data); 10466 if( rc ) return rc==2 ? 0 : rc; 10467 }else{ 10468 open_db(&data, 0); 10469 rc = shell_exec(&data, azCmd[i], &zErrMsg); 10470 if( zErrMsg!=0 ){ 10471 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10472 return rc!=0 ? rc : 1; 10473 }else if( rc!=0 ){ 10474 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 10475 return rc; 10476 } 10477 } 10478 } 10479 free(azCmd); 10480 }else{ 10481 /* Run commands received from standard input 10482 */ 10483 if( stdin_is_interactive ){ 10484 char *zHome; 10485 char *zHistory; 10486 int nHistory; 10487 printf( 10488 "SQLite version %s %.19s\n" /*extra-version-info*/ 10489 "Enter \".help\" for usage hints.\n", 10490 sqlite3_libversion(), sqlite3_sourceid() 10491 ); 10492 if( warnInmemoryDb ){ 10493 printf("Connected to a "); 10494 printBold("transient in-memory database"); 10495 printf(".\nUse \".open FILENAME\" to reopen on a " 10496 "persistent database.\n"); 10497 } 10498 zHistory = getenv("SQLITE_HISTORY"); 10499 if( zHistory ){ 10500 zHistory = strdup(zHistory); 10501 }else if( (zHome = find_home_dir(0))!=0 ){ 10502 nHistory = strlen30(zHome) + 20; 10503 if( (zHistory = malloc(nHistory))!=0 ){ 10504 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 10505 } 10506 } 10507 if( zHistory ){ shell_read_history(zHistory); } 10508#if HAVE_READLINE || HAVE_EDITLINE 10509 rl_attempted_completion_function = readline_completion; 10510#elif HAVE_LINENOISE 10511 linenoiseSetCompletionCallback(linenoise_completion); 10512#endif 10513 data.in = 0; 10514 rc = process_input(&data); 10515 if( zHistory ){ 10516 shell_stifle_history(2000); 10517 shell_write_history(zHistory); 10518 free(zHistory); 10519 } 10520 }else{ 10521 data.in = stdin; 10522 rc = process_input(&data); 10523 } 10524 } 10525 set_table_name(&data, 0); 10526 if( data.db ){ 10527 session_close_all(&data); 10528 close_db(data.db); 10529 } 10530 sqlite3_free(data.zFreeOnClose); 10531 find_home_dir(1); 10532 output_reset(&data); 10533 data.doXdgOpen = 0; 10534 clearTempFile(&data); 10535#if !SQLITE_SHELL_IS_UTF8 10536 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 10537 free(argvToFree); 10538#endif 10539 /* Clear the global data structure so that valgrind will detect memory 10540 ** leaks */ 10541 memset(&data, 0, sizeof(data)); 10542 return rc; 10543} 10544