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** Optionally #include a user-defined header, whereby compilation options 22** may be set prior to where they take effect, but after platform setup. 23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include 24** file. Note that this macro has a like effect on sqlite3.c compilation. 25*/ 26#ifdef SQLITE_CUSTOM_INCLUDE 27# define INC_STRINGIFY_(f) #f 28# define INC_STRINGIFY(f) INC_STRINGIFY_(f) 29# include INC_STRINGIFY(SQLITE_CUSTOM_INCLUDE) 30#endif 31 32/* 33** Determine if we are dealing with WinRT, which provides only a subset of 34** the full Win32 API. 35*/ 36#if !defined(SQLITE_OS_WINRT) 37# define SQLITE_OS_WINRT 0 38#endif 39 40/* 41** Warning pragmas copied from msvc.h in the core. 42*/ 43#if defined(_MSC_VER) 44#pragma warning(disable : 4054) 45#pragma warning(disable : 4055) 46#pragma warning(disable : 4100) 47#pragma warning(disable : 4127) 48#pragma warning(disable : 4130) 49#pragma warning(disable : 4152) 50#pragma warning(disable : 4189) 51#pragma warning(disable : 4206) 52#pragma warning(disable : 4210) 53#pragma warning(disable : 4232) 54#pragma warning(disable : 4244) 55#pragma warning(disable : 4305) 56#pragma warning(disable : 4306) 57#pragma warning(disable : 4702) 58#pragma warning(disable : 4706) 59#endif /* defined(_MSC_VER) */ 60 61/* 62** No support for loadable extensions in VxWorks. 63*/ 64#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION 65# define SQLITE_OMIT_LOAD_EXTENSION 1 66#endif 67 68/* 69** Enable large-file support for fopen() and friends on unix. 70*/ 71#ifndef SQLITE_DISABLE_LFS 72# define _LARGE_FILE 1 73# ifndef _FILE_OFFSET_BITS 74# define _FILE_OFFSET_BITS 64 75# endif 76# define _LARGEFILE_SOURCE 1 77#endif 78 79#include <stdlib.h> 80#include <string.h> 81#include <stdio.h> 82#include <assert.h> 83#include "sqlite3.h" 84typedef sqlite3_int64 i64; 85typedef sqlite3_uint64 u64; 86typedef unsigned char u8; 87#if SQLITE_USER_AUTHENTICATION 88# include "sqlite3userauth.h" 89#endif 90#include <ctype.h> 91#include <stdarg.h> 92 93#if !defined(_WIN32) && !defined(WIN32) 94# include <signal.h> 95# if !defined(__RTP__) && !defined(_WRS_KERNEL) 96# include <pwd.h> 97# endif 98#endif 99#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) 100# include <unistd.h> 101# include <dirent.h> 102# define GETPID getpid 103# if defined(__MINGW32__) 104# define DIRENT dirent 105# ifndef S_ISLNK 106# define S_ISLNK(mode) (0) 107# endif 108# endif 109#else 110# define GETPID (int)GetCurrentProcessId 111#endif 112#include <sys/types.h> 113#include <sys/stat.h> 114 115#if HAVE_READLINE 116# include <readline/readline.h> 117# include <readline/history.h> 118#endif 119 120#if HAVE_EDITLINE 121# include <editline/readline.h> 122#endif 123 124#if HAVE_EDITLINE || HAVE_READLINE 125 126# define shell_add_history(X) add_history(X) 127# define shell_read_history(X) read_history(X) 128# define shell_write_history(X) write_history(X) 129# define shell_stifle_history(X) stifle_history(X) 130# define shell_readline(X) readline(X) 131 132#elif HAVE_LINENOISE 133 134# include "linenoise.h" 135# define shell_add_history(X) linenoiseHistoryAdd(X) 136# define shell_read_history(X) linenoiseHistoryLoad(X) 137# define shell_write_history(X) linenoiseHistorySave(X) 138# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) 139# define shell_readline(X) linenoise(X) 140 141#else 142 143# define shell_read_history(X) 144# define shell_write_history(X) 145# define shell_stifle_history(X) 146 147# define SHELL_USE_LOCAL_GETLINE 1 148#endif 149 150 151#if defined(_WIN32) || defined(WIN32) 152# if SQLITE_OS_WINRT 153# define SQLITE_OMIT_POPEN 1 154# else 155# include <io.h> 156# include <fcntl.h> 157# define isatty(h) _isatty(h) 158# ifndef access 159# define access(f,m) _access((f),(m)) 160# endif 161# ifndef unlink 162# define unlink _unlink 163# endif 164# ifndef strdup 165# define strdup _strdup 166# endif 167# undef popen 168# define popen _popen 169# undef pclose 170# define pclose _pclose 171# endif 172#else 173 /* Make sure isatty() has a prototype. */ 174 extern int isatty(int); 175 176# if !defined(__RTP__) && !defined(_WRS_KERNEL) 177 /* popen and pclose are not C89 functions and so are 178 ** sometimes omitted from the <stdio.h> header */ 179 extern FILE *popen(const char*,const char*); 180 extern int pclose(FILE*); 181# else 182# define SQLITE_OMIT_POPEN 1 183# endif 184#endif 185 186#if defined(_WIN32_WCE) 187/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() 188 * thus we always assume that we have a console. That can be 189 * overridden with the -batch command line option. 190 */ 191#define isatty(x) 1 192#endif 193 194/* ctype macros that work with signed characters */ 195#define IsSpace(X) isspace((unsigned char)X) 196#define IsDigit(X) isdigit((unsigned char)X) 197#define ToLower(X) (char)tolower((unsigned char)X) 198 199#if defined(_WIN32) || defined(WIN32) 200#if SQLITE_OS_WINRT 201#include <intrin.h> 202#endif 203#include <windows.h> 204 205/* string conversion routines only needed on Win32 */ 206extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); 207extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); 208extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); 209extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); 210#endif 211 212/* On Windows, we normally run with output mode of TEXT so that \n characters 213** are automatically translated into \r\n. However, this behavior needs 214** to be disabled in some cases (ex: when generating CSV output and when 215** rendering quoted strings that contain \n characters). The following 216** routines take care of that. 217*/ 218#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT 219static void setBinaryMode(FILE *file, int isOutput){ 220 if( isOutput ) fflush(file); 221 _setmode(_fileno(file), _O_BINARY); 222} 223static void setTextMode(FILE *file, int isOutput){ 224 if( isOutput ) fflush(file); 225 _setmode(_fileno(file), _O_TEXT); 226} 227#else 228# define setBinaryMode(X,Y) 229# define setTextMode(X,Y) 230#endif 231 232 233/* True if the timer is enabled */ 234static int enableTimer = 0; 235 236/* Return the current wall-clock time */ 237static sqlite3_int64 timeOfDay(void){ 238 static sqlite3_vfs *clockVfs = 0; 239 sqlite3_int64 t; 240 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); 241 if( clockVfs==0 ) return 0; /* Never actually happens */ 242 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ 243 clockVfs->xCurrentTimeInt64(clockVfs, &t); 244 }else{ 245 double r; 246 clockVfs->xCurrentTime(clockVfs, &r); 247 t = (sqlite3_int64)(r*86400000.0); 248 } 249 return t; 250} 251 252#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) 253#include <sys/time.h> 254#include <sys/resource.h> 255 256/* VxWorks does not support getrusage() as far as we can determine */ 257#if defined(_WRS_KERNEL) || defined(__RTP__) 258struct rusage { 259 struct timeval ru_utime; /* user CPU time used */ 260 struct timeval ru_stime; /* system CPU time used */ 261}; 262#define getrusage(A,B) memset(B,0,sizeof(*B)) 263#endif 264 265/* Saved resource information for the beginning of an operation */ 266static struct rusage sBegin; /* CPU time at start */ 267static sqlite3_int64 iBegin; /* Wall-clock time at start */ 268 269/* 270** Begin timing an operation 271*/ 272static void beginTimer(void){ 273 if( enableTimer ){ 274 getrusage(RUSAGE_SELF, &sBegin); 275 iBegin = timeOfDay(); 276 } 277} 278 279/* Return the difference of two time_structs in seconds */ 280static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ 281 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 282 (double)(pEnd->tv_sec - pStart->tv_sec); 283} 284 285/* 286** Print the timing results. 287*/ 288static void endTimer(void){ 289 if( enableTimer ){ 290 sqlite3_int64 iEnd = timeOfDay(); 291 struct rusage sEnd; 292 getrusage(RUSAGE_SELF, &sEnd); 293 printf("Run Time: real %.3f user %f sys %f\n", 294 (iEnd - iBegin)*0.001, 295 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), 296 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); 297 } 298} 299 300#define BEGIN_TIMER beginTimer() 301#define END_TIMER endTimer() 302#define HAS_TIMER 1 303 304#elif (defined(_WIN32) || defined(WIN32)) 305 306/* Saved resource information for the beginning of an operation */ 307static HANDLE hProcess; 308static FILETIME ftKernelBegin; 309static FILETIME ftUserBegin; 310static sqlite3_int64 ftWallBegin; 311typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, 312 LPFILETIME, LPFILETIME); 313static GETPROCTIMES getProcessTimesAddr = NULL; 314 315/* 316** Check to see if we have timer support. Return 1 if necessary 317** support found (or found previously). 318*/ 319static int hasTimer(void){ 320 if( getProcessTimesAddr ){ 321 return 1; 322 } else { 323#if !SQLITE_OS_WINRT 324 /* GetProcessTimes() isn't supported in WIN95 and some other Windows 325 ** versions. See if the version we are running on has it, and if it 326 ** does, save off a pointer to it and the current process handle. 327 */ 328 hProcess = GetCurrentProcess(); 329 if( hProcess ){ 330 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); 331 if( NULL != hinstLib ){ 332 getProcessTimesAddr = 333 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); 334 if( NULL != getProcessTimesAddr ){ 335 return 1; 336 } 337 FreeLibrary(hinstLib); 338 } 339 } 340#endif 341 } 342 return 0; 343} 344 345/* 346** Begin timing an operation 347*/ 348static void beginTimer(void){ 349 if( enableTimer && getProcessTimesAddr ){ 350 FILETIME ftCreation, ftExit; 351 getProcessTimesAddr(hProcess,&ftCreation,&ftExit, 352 &ftKernelBegin,&ftUserBegin); 353 ftWallBegin = timeOfDay(); 354 } 355} 356 357/* Return the difference of two FILETIME structs in seconds */ 358static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ 359 sqlite_int64 i64Start = *((sqlite_int64 *) pStart); 360 sqlite_int64 i64End = *((sqlite_int64 *) pEnd); 361 return (double) ((i64End - i64Start) / 10000000.0); 362} 363 364/* 365** Print the timing results. 366*/ 367static void endTimer(void){ 368 if( enableTimer && getProcessTimesAddr){ 369 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; 370 sqlite3_int64 ftWallEnd = timeOfDay(); 371 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); 372 printf("Run Time: real %.3f user %f sys %f\n", 373 (ftWallEnd - ftWallBegin)*0.001, 374 timeDiff(&ftUserBegin, &ftUserEnd), 375 timeDiff(&ftKernelBegin, &ftKernelEnd)); 376 } 377} 378 379#define BEGIN_TIMER beginTimer() 380#define END_TIMER endTimer() 381#define HAS_TIMER hasTimer() 382 383#else 384#define BEGIN_TIMER 385#define END_TIMER 386#define HAS_TIMER 0 387#endif 388 389/* 390** Used to prevent warnings about unused parameters 391*/ 392#define UNUSED_PARAMETER(x) (void)(x) 393 394/* 395** Number of elements in an array 396*/ 397#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) 398 399/* 400** If the following flag is set, then command execution stops 401** at an error if we are not interactive. 402*/ 403static int bail_on_error = 0; 404 405/* 406** Threat stdin as an interactive input if the following variable 407** is true. Otherwise, assume stdin is connected to a file or pipe. 408*/ 409static int stdin_is_interactive = 1; 410 411/* 412** On Windows systems we have to know if standard output is a console 413** in order to translate UTF-8 into MBCS. The following variable is 414** true if translation is required. 415*/ 416static int stdout_is_console = 1; 417 418/* 419** The following is the open SQLite database. We make a pointer 420** to this database a static variable so that it can be accessed 421** by the SIGINT handler to interrupt database processing. 422*/ 423static sqlite3 *globalDb = 0; 424 425/* 426** True if an interrupt (Control-C) has been received. 427*/ 428static volatile int seenInterrupt = 0; 429 430/* 431** This is the name of our program. It is set in main(), used 432** in a number of other places, mostly for error messages. 433*/ 434static char *Argv0; 435 436/* 437** Prompt strings. Initialized in main. Settable with 438** .prompt main continue 439*/ 440static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 441static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 442 443/* 444** Render output like fprintf(). Except, if the output is going to the 445** console and if this is running on a Windows machine, translate the 446** output from UTF-8 into MBCS. 447*/ 448#if defined(_WIN32) || defined(WIN32) 449void utf8_printf(FILE *out, const char *zFormat, ...){ 450 va_list ap; 451 va_start(ap, zFormat); 452 if( stdout_is_console && (out==stdout || out==stderr) ){ 453 char *z1 = sqlite3_vmprintf(zFormat, ap); 454 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 455 sqlite3_free(z1); 456 fputs(z2, out); 457 sqlite3_free(z2); 458 }else{ 459 vfprintf(out, zFormat, ap); 460 } 461 va_end(ap); 462} 463#elif !defined(utf8_printf) 464# define utf8_printf fprintf 465#endif 466 467/* 468** Render output like fprintf(). This should not be used on anything that 469** includes string formatting (e.g. "%s"). 470*/ 471#if !defined(raw_printf) 472# define raw_printf fprintf 473#endif 474 475/* Indicate out-of-memory and exit. */ 476static void shell_out_of_memory(void){ 477 raw_printf(stderr,"Error: out of memory\n"); 478 exit(1); 479} 480 481/* Check a pointer to see if it is NULL. If it is NULL, exit with an 482** out-of-memory error. 483*/ 484static void shell_check_oom(void *p){ 485 if( p==0 ) shell_out_of_memory(); 486} 487 488/* 489** Write I/O traces to the following stream. 490*/ 491#ifdef SQLITE_ENABLE_IOTRACE 492static FILE *iotrace = 0; 493#endif 494 495/* 496** This routine works like printf in that its first argument is a 497** format string and subsequent arguments are values to be substituted 498** in place of % fields. The result of formatting this string 499** is written to iotrace. 500*/ 501#ifdef SQLITE_ENABLE_IOTRACE 502static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 503 va_list ap; 504 char *z; 505 if( iotrace==0 ) return; 506 va_start(ap, zFormat); 507 z = sqlite3_vmprintf(zFormat, ap); 508 va_end(ap); 509 utf8_printf(iotrace, "%s", z); 510 sqlite3_free(z); 511} 512#endif 513 514/* 515** Output string zUtf to stream pOut as w characters. If w is negative, 516** then right-justify the text. W is the width in UTF-8 characters, not 517** in bytes. This is different from the %*.*s specification in printf 518** since with %*.*s the width is measured in bytes, not characters. 519*/ 520static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 521 int i; 522 int n; 523 int aw = w<0 ? -w : w; 524 for(i=n=0; zUtf[i]; i++){ 525 if( (zUtf[i]&0xc0)!=0x80 ){ 526 n++; 527 if( n==aw ){ 528 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 529 break; 530 } 531 } 532 } 533 if( n>=aw ){ 534 utf8_printf(pOut, "%.*s", i, zUtf); 535 }else if( w<0 ){ 536 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 537 }else{ 538 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 539 } 540} 541 542 543/* 544** Determines if a string is a number of not. 545*/ 546static int isNumber(const char *z, int *realnum){ 547 if( *z=='-' || *z=='+' ) z++; 548 if( !IsDigit(*z) ){ 549 return 0; 550 } 551 z++; 552 if( realnum ) *realnum = 0; 553 while( IsDigit(*z) ){ z++; } 554 if( *z=='.' ){ 555 z++; 556 if( !IsDigit(*z) ) return 0; 557 while( IsDigit(*z) ){ z++; } 558 if( realnum ) *realnum = 1; 559 } 560 if( *z=='e' || *z=='E' ){ 561 z++; 562 if( *z=='+' || *z=='-' ) z++; 563 if( !IsDigit(*z) ) return 0; 564 while( IsDigit(*z) ){ z++; } 565 if( realnum ) *realnum = 1; 566 } 567 return *z==0; 568} 569 570/* 571** Compute a string length that is limited to what can be stored in 572** lower 30 bits of a 32-bit signed integer. 573*/ 574static int strlen30(const char *z){ 575 const char *z2 = z; 576 while( *z2 ){ z2++; } 577 return 0x3fffffff & (int)(z2 - z); 578} 579 580/* 581** Return the length of a string in characters. Multibyte UTF8 characters 582** count as a single character. 583*/ 584static int strlenChar(const char *z){ 585 int n = 0; 586 while( *z ){ 587 if( (0xc0&*(z++))!=0x80 ) n++; 588 } 589 return n; 590} 591 592/* 593** Return open FILE * if zFile exists, can be opened for read 594** and is an ordinary file or a character stream source. 595** Otherwise return 0. 596*/ 597static FILE * openChrSource(const char *zFile){ 598#ifdef _WIN32 599 struct _stat x = {0}; 600# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0) 601 /* On Windows, open first, then check the stream nature. This order 602 ** is necessary because _stat() and sibs, when checking a named pipe, 603 ** effectively break the pipe as its supplier sees it. */ 604 FILE *rv = fopen(zFile, "rb"); 605 if( rv==0 ) return 0; 606 if( _fstat(_fileno(rv), &x) != 0 607 || !STAT_CHR_SRC(x.st_mode)){ 608 fclose(rv); 609 rv = 0; 610 } 611 return rv; 612#else 613 struct stat x = {0}; 614 int rc = stat(zFile, &x); 615# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode)) 616 if( rc!=0 ) return 0; 617 if( STAT_CHR_SRC(x.st_mode) ){ 618 return fopen(zFile, "rb"); 619 }else{ 620 return 0; 621 } 622#endif 623#undef STAT_CHR_SRC 624} 625 626/* 627** This routine reads a line of text from FILE in, stores 628** the text in memory obtained from malloc() and returns a pointer 629** to the text. NULL is returned at end of file, or if malloc() 630** fails. 631** 632** If zLine is not NULL then it is a malloced buffer returned from 633** a previous call to this routine that may be reused. 634*/ 635static char *local_getline(char *zLine, FILE *in){ 636 int nLine = zLine==0 ? 0 : 100; 637 int n = 0; 638 639 while( 1 ){ 640 if( n+100>nLine ){ 641 nLine = nLine*2 + 100; 642 zLine = realloc(zLine, nLine); 643 shell_check_oom(zLine); 644 } 645 if( fgets(&zLine[n], nLine - n, in)==0 ){ 646 if( n==0 ){ 647 free(zLine); 648 return 0; 649 } 650 zLine[n] = 0; 651 break; 652 } 653 while( zLine[n] ) n++; 654 if( n>0 && zLine[n-1]=='\n' ){ 655 n--; 656 if( n>0 && zLine[n-1]=='\r' ) n--; 657 zLine[n] = 0; 658 break; 659 } 660 } 661#if defined(_WIN32) || defined(WIN32) 662 /* For interactive input on Windows systems, translate the 663 ** multi-byte characterset characters into UTF-8. */ 664 if( stdin_is_interactive && in==stdin ){ 665 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 666 if( zTrans ){ 667 int nTrans = strlen30(zTrans)+1; 668 if( nTrans>nLine ){ 669 zLine = realloc(zLine, nTrans); 670 shell_check_oom(zLine); 671 } 672 memcpy(zLine, zTrans, nTrans); 673 sqlite3_free(zTrans); 674 } 675 } 676#endif /* defined(_WIN32) || defined(WIN32) */ 677 return zLine; 678} 679 680/* 681** Retrieve a single line of input text. 682** 683** If in==0 then read from standard input and prompt before each line. 684** If isContinuation is true, then a continuation prompt is appropriate. 685** If isContinuation is zero, then the main prompt should be used. 686** 687** If zPrior is not NULL then it is a buffer from a prior call to this 688** routine that can be reused. 689** 690** The result is stored in space obtained from malloc() and must either 691** be freed by the caller or else passed back into this routine via the 692** zPrior argument for reuse. 693*/ 694static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 695 char *zPrompt; 696 char *zResult; 697 if( in!=0 ){ 698 zResult = local_getline(zPrior, in); 699 }else{ 700 zPrompt = isContinuation ? continuePrompt : mainPrompt; 701#if SHELL_USE_LOCAL_GETLINE 702 printf("%s", zPrompt); 703 fflush(stdout); 704 zResult = local_getline(zPrior, stdin); 705#else 706 free(zPrior); 707 zResult = shell_readline(zPrompt); 708 if( zResult && *zResult ) shell_add_history(zResult); 709#endif 710 } 711 return zResult; 712} 713 714 715/* 716** Return the value of a hexadecimal digit. Return -1 if the input 717** is not a hex digit. 718*/ 719static int hexDigitValue(char c){ 720 if( c>='0' && c<='9' ) return c - '0'; 721 if( c>='a' && c<='f' ) return c - 'a' + 10; 722 if( c>='A' && c<='F' ) return c - 'A' + 10; 723 return -1; 724} 725 726/* 727** Interpret zArg as an integer value, possibly with suffixes. 728*/ 729static sqlite3_int64 integerValue(const char *zArg){ 730 sqlite3_int64 v = 0; 731 static const struct { char *zSuffix; int iMult; } aMult[] = { 732 { "KiB", 1024 }, 733 { "MiB", 1024*1024 }, 734 { "GiB", 1024*1024*1024 }, 735 { "KB", 1000 }, 736 { "MB", 1000000 }, 737 { "GB", 1000000000 }, 738 { "K", 1000 }, 739 { "M", 1000000 }, 740 { "G", 1000000000 }, 741 }; 742 int i; 743 int isNeg = 0; 744 if( zArg[0]=='-' ){ 745 isNeg = 1; 746 zArg++; 747 }else if( zArg[0]=='+' ){ 748 zArg++; 749 } 750 if( zArg[0]=='0' && zArg[1]=='x' ){ 751 int x; 752 zArg += 2; 753 while( (x = hexDigitValue(zArg[0]))>=0 ){ 754 v = (v<<4) + x; 755 zArg++; 756 } 757 }else{ 758 while( IsDigit(zArg[0]) ){ 759 v = v*10 + zArg[0] - '0'; 760 zArg++; 761 } 762 } 763 for(i=0; i<ArraySize(aMult); i++){ 764 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 765 v *= aMult[i].iMult; 766 break; 767 } 768 } 769 return isNeg? -v : v; 770} 771 772/* 773** A variable length string to which one can append text. 774*/ 775typedef struct ShellText ShellText; 776struct ShellText { 777 char *z; 778 int n; 779 int nAlloc; 780}; 781 782/* 783** Initialize and destroy a ShellText object 784*/ 785static void initText(ShellText *p){ 786 memset(p, 0, sizeof(*p)); 787} 788static void freeText(ShellText *p){ 789 free(p->z); 790 initText(p); 791} 792 793/* zIn is either a pointer to a NULL-terminated string in memory obtained 794** from malloc(), or a NULL pointer. The string pointed to by zAppend is 795** added to zIn, and the result returned in memory obtained from malloc(). 796** zIn, if it was not NULL, is freed. 797** 798** If the third argument, quote, is not '\0', then it is used as a 799** quote character for zAppend. 800*/ 801static void appendText(ShellText *p, char const *zAppend, char quote){ 802 int len; 803 int i; 804 int nAppend = strlen30(zAppend); 805 806 len = nAppend+p->n+1; 807 if( quote ){ 808 len += 2; 809 for(i=0; i<nAppend; i++){ 810 if( zAppend[i]==quote ) len++; 811 } 812 } 813 814 if( p->z==0 || p->n+len>=p->nAlloc ){ 815 p->nAlloc = p->nAlloc*2 + len + 20; 816 p->z = realloc(p->z, p->nAlloc); 817 shell_check_oom(p->z); 818 } 819 820 if( quote ){ 821 char *zCsr = p->z+p->n; 822 *zCsr++ = quote; 823 for(i=0; i<nAppend; i++){ 824 *zCsr++ = zAppend[i]; 825 if( zAppend[i]==quote ) *zCsr++ = quote; 826 } 827 *zCsr++ = quote; 828 p->n = (int)(zCsr - p->z); 829 *zCsr = '\0'; 830 }else{ 831 memcpy(p->z+p->n, zAppend, nAppend); 832 p->n += nAppend; 833 p->z[p->n] = '\0'; 834 } 835} 836 837/* 838** Attempt to determine if identifier zName needs to be quoted, either 839** because it contains non-alphanumeric characters, or because it is an 840** SQLite keyword. Be conservative in this estimate: When in doubt assume 841** that quoting is required. 842** 843** Return '"' if quoting is required. Return 0 if no quoting is required. 844*/ 845static char quoteChar(const char *zName){ 846 int i; 847 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 848 for(i=0; zName[i]; i++){ 849 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 850 } 851 return sqlite3_keyword_check(zName, i) ? '"' : 0; 852} 853 854/* 855** Construct a fake object name and column list to describe the structure 856** of the view, virtual table, or table valued function zSchema.zName. 857*/ 858static char *shellFakeSchema( 859 sqlite3 *db, /* The database connection containing the vtab */ 860 const char *zSchema, /* Schema of the database holding the vtab */ 861 const char *zName /* The name of the virtual table */ 862){ 863 sqlite3_stmt *pStmt = 0; 864 char *zSql; 865 ShellText s; 866 char cQuote; 867 char *zDiv = "("; 868 int nRow = 0; 869 870 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 871 zSchema ? zSchema : "main", zName); 872 shell_check_oom(zSql); 873 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 874 sqlite3_free(zSql); 875 initText(&s); 876 if( zSchema ){ 877 cQuote = quoteChar(zSchema); 878 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 879 appendText(&s, zSchema, cQuote); 880 appendText(&s, ".", 0); 881 } 882 cQuote = quoteChar(zName); 883 appendText(&s, zName, cQuote); 884 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 885 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 886 nRow++; 887 appendText(&s, zDiv, 0); 888 zDiv = ","; 889 if( zCol==0 ) zCol = ""; 890 cQuote = quoteChar(zCol); 891 appendText(&s, zCol, cQuote); 892 } 893 appendText(&s, ")", 0); 894 sqlite3_finalize(pStmt); 895 if( nRow==0 ){ 896 freeText(&s); 897 s.z = 0; 898 } 899 return s.z; 900} 901 902/* 903** SQL function: shell_module_schema(X) 904** 905** Return a fake schema for the table-valued function or eponymous virtual 906** table X. 907*/ 908static void shellModuleSchema( 909 sqlite3_context *pCtx, 910 int nVal, 911 sqlite3_value **apVal 912){ 913 const char *zName; 914 char *zFake; 915 UNUSED_PARAMETER(nVal); 916 zName = (const char*)sqlite3_value_text(apVal[0]); 917 zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0; 918 if( zFake ){ 919 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 920 -1, sqlite3_free); 921 free(zFake); 922 } 923} 924 925/* 926** SQL function: shell_add_schema(S,X) 927** 928** Add the schema name X to the CREATE statement in S and return the result. 929** Examples: 930** 931** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 932** 933** Also works on 934** 935** CREATE INDEX 936** CREATE UNIQUE INDEX 937** CREATE VIEW 938** CREATE TRIGGER 939** CREATE VIRTUAL TABLE 940** 941** This UDF is used by the .schema command to insert the schema name of 942** attached databases into the middle of the sqlite_schema.sql field. 943*/ 944static void shellAddSchemaName( 945 sqlite3_context *pCtx, 946 int nVal, 947 sqlite3_value **apVal 948){ 949 static const char *aPrefix[] = { 950 "TABLE", 951 "INDEX", 952 "UNIQUE INDEX", 953 "VIEW", 954 "TRIGGER", 955 "VIRTUAL TABLE" 956 }; 957 int i = 0; 958 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 959 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 960 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 961 sqlite3 *db = sqlite3_context_db_handle(pCtx); 962 UNUSED_PARAMETER(nVal); 963 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ 964 for(i=0; i<ArraySize(aPrefix); i++){ 965 int n = strlen30(aPrefix[i]); 966 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 967 char *z = 0; 968 char *zFake = 0; 969 if( zSchema ){ 970 char cQuote = quoteChar(zSchema); 971 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 972 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 973 }else{ 974 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 975 } 976 } 977 if( zName 978 && aPrefix[i][0]=='V' 979 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 980 ){ 981 if( z==0 ){ 982 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 983 }else{ 984 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 985 } 986 free(zFake); 987 } 988 if( z ){ 989 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 990 return; 991 } 992 } 993 } 994 } 995 sqlite3_result_value(pCtx, apVal[0]); 996} 997 998/* 999** The source code for several run-time loadable extensions is inserted 1000** below by the ../tool/mkshellc.tcl script. Before processing that included 1001** code, we need to override some macros to make the included program code 1002** work here in the middle of this regular program. 1003*/ 1004#define SQLITE_EXTENSION_INIT1 1005#define SQLITE_EXTENSION_INIT2(X) (void)(X) 1006 1007#if defined(_WIN32) && defined(_MSC_VER) 1008INCLUDE test_windirent.h 1009INCLUDE test_windirent.c 1010#define dirent DIRENT 1011#endif 1012INCLUDE ../ext/misc/shathree.c 1013INCLUDE ../ext/misc/fileio.c 1014INCLUDE ../ext/misc/completion.c 1015INCLUDE ../ext/misc/appendvfs.c 1016INCLUDE ../ext/misc/memtrace.c 1017INCLUDE ../ext/misc/uint.c 1018INCLUDE ../ext/misc/decimal.c 1019INCLUDE ../ext/misc/ieee754.c 1020INCLUDE ../ext/misc/series.c 1021INCLUDE ../ext/misc/regexp.c 1022#ifdef SQLITE_HAVE_ZLIB 1023INCLUDE ../ext/misc/zipfile.c 1024INCLUDE ../ext/misc/sqlar.c 1025#endif 1026INCLUDE ../ext/expert/sqlite3expert.h 1027INCLUDE ../ext/expert/sqlite3expert.c 1028 1029#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 1030INCLUDE ../ext/misc/dbdata.c 1031#endif 1032 1033#if defined(SQLITE_ENABLE_SESSION) 1034/* 1035** State information for a single open session 1036*/ 1037typedef struct OpenSession OpenSession; 1038struct OpenSession { 1039 char *zName; /* Symbolic name for this session */ 1040 int nFilter; /* Number of xFilter rejection GLOB patterns */ 1041 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 1042 sqlite3_session *p; /* The open session */ 1043}; 1044#endif 1045 1046typedef struct ExpertInfo ExpertInfo; 1047struct ExpertInfo { 1048 sqlite3expert *pExpert; 1049 int bVerbose; 1050}; 1051 1052/* A single line in the EQP output */ 1053typedef struct EQPGraphRow EQPGraphRow; 1054struct EQPGraphRow { 1055 int iEqpId; /* ID for this row */ 1056 int iParentId; /* ID of the parent row */ 1057 EQPGraphRow *pNext; /* Next row in sequence */ 1058 char zText[1]; /* Text to display for this row */ 1059}; 1060 1061/* All EQP output is collected into an instance of the following */ 1062typedef struct EQPGraph EQPGraph; 1063struct EQPGraph { 1064 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 1065 EQPGraphRow *pLast; /* Last element of the pRow list */ 1066 char zPrefix[100]; /* Graph prefix */ 1067}; 1068 1069/* 1070** State information about the database connection is contained in an 1071** instance of the following structure. 1072*/ 1073typedef struct ShellState ShellState; 1074struct ShellState { 1075 sqlite3 *db; /* The database */ 1076 u8 autoExplain; /* Automatically turn on .explain mode */ 1077 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1078 u8 autoEQPtest; /* autoEQP is in test mode */ 1079 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1080 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1081 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1082 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1083 u8 nEqpLevel; /* Depth of the EQP output graph */ 1084 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1085 u8 bSafeMode; /* True to prohibit unsafe operations */ 1086 u8 bSafeModePersist; /* The long-term value of bSafeMode */ 1087 unsigned statsOn; /* True to display memory stats before each finalize */ 1088 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1089 int inputNesting; /* Track nesting level of .read and other redirects */ 1090 int outCount; /* Revert to stdout when reaching zero */ 1091 int cnt; /* Number of records displayed so far */ 1092 int lineno; /* Line number of last line read from in */ 1093 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ 1094 FILE *in; /* Read commands from this stream */ 1095 FILE *out; /* Write results here */ 1096 FILE *traceOut; /* Output for sqlite3_trace() */ 1097 int nErr; /* Number of errors seen */ 1098 int mode; /* An output mode setting */ 1099 int modePrior; /* Saved mode */ 1100 int cMode; /* temporary output mode for the current query */ 1101 int normalMode; /* Output mode before ".explain on" */ 1102 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1103 int showHeader; /* True to show column names in List or Column mode */ 1104 int nCheck; /* Number of ".check" commands run */ 1105 unsigned nProgress; /* Number of progress callbacks encountered */ 1106 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1107 unsigned flgProgress; /* Flags for the progress callback */ 1108 unsigned shellFlgs; /* Various flags */ 1109 unsigned priorShFlgs; /* Saved copy of flags */ 1110 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1111 char *zDestTable; /* Name of destination table when MODE_Insert */ 1112 char *zTempFile; /* Temporary file that might need deleting */ 1113 char zTestcase[30]; /* Name of current test case */ 1114 char colSeparator[20]; /* Column separator character for several modes */ 1115 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1116 char colSepPrior[20]; /* Saved column separator */ 1117 char rowSepPrior[20]; /* Saved row separator */ 1118 int *colWidth; /* Requested width of each column in columnar modes */ 1119 int *actualWidth; /* Actual width of each column */ 1120 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */ 1121 char nullValue[20]; /* The text to print when a NULL comes back from 1122 ** the database */ 1123 char outfile[FILENAME_MAX]; /* Filename for *out */ 1124 sqlite3_stmt *pStmt; /* Current statement if any. */ 1125 FILE *pLog; /* Write log output here */ 1126 struct AuxDb { /* Storage space for auxiliary database connections */ 1127 sqlite3 *db; /* Connection pointer */ 1128 const char *zDbFilename; /* Filename used to open the connection */ 1129 char *zFreeOnClose; /* Free this memory allocation on close */ 1130#if defined(SQLITE_ENABLE_SESSION) 1131 int nSession; /* Number of active sessions */ 1132 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1133#endif 1134 } aAuxDb[5], /* Array of all database connections */ 1135 *pAuxDb; /* Currently active database connection */ 1136 int *aiIndent; /* Array of indents used in MODE_Explain */ 1137 int nIndent; /* Size of array aiIndent[] */ 1138 int iIndent; /* Index of current op in aiIndent[] */ 1139 char *zNonce; /* Nonce for temporary safe-mode excapes */ 1140 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1141 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1142}; 1143 1144 1145/* Allowed values for ShellState.autoEQP 1146*/ 1147#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1148#define AUTOEQP_on 1 /* Automatic EQP is on */ 1149#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1150#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1151 1152/* Allowed values for ShellState.openMode 1153*/ 1154#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1155#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1156#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1157#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1158#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1159#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1160#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1161 1162/* Allowed values for ShellState.eTraceType 1163*/ 1164#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1165#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1166#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1167 1168/* Bits in the ShellState.flgProgress variable */ 1169#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1170#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1171 ** callback limit is reached, and for each 1172 ** top-level SQL statement */ 1173#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1174 1175/* 1176** These are the allowed shellFlgs values 1177*/ 1178#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1179#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1180#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1181#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1182#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1183#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1184#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1185#define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */ 1186#define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */ 1187#define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */ 1188 1189/* 1190** Macros for testing and setting shellFlgs 1191*/ 1192#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1193#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1194#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1195 1196/* 1197** These are the allowed modes. 1198*/ 1199#define MODE_Line 0 /* One column per line. Blank line between records */ 1200#define MODE_Column 1 /* One record per line in neat columns */ 1201#define MODE_List 2 /* One record per line with a separator */ 1202#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1203#define MODE_Html 4 /* Generate an XHTML table */ 1204#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1205#define MODE_Quote 6 /* Quote values as for SQL */ 1206#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1207#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1208#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1209#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1210#define MODE_Pretty 11 /* Pretty-print schemas */ 1211#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1212#define MODE_Json 13 /* Output JSON */ 1213#define MODE_Markdown 14 /* Markdown formatting */ 1214#define MODE_Table 15 /* MySQL-style table formatting */ 1215#define MODE_Box 16 /* Unicode box-drawing characters */ 1216#define MODE_Count 17 /* Output only a count of the rows of output */ 1217#define MODE_Off 18 /* No query output shown */ 1218 1219static const char *modeDescr[] = { 1220 "line", 1221 "column", 1222 "list", 1223 "semi", 1224 "html", 1225 "insert", 1226 "quote", 1227 "tcl", 1228 "csv", 1229 "explain", 1230 "ascii", 1231 "prettyprint", 1232 "eqp", 1233 "json", 1234 "markdown", 1235 "table", 1236 "box", 1237 "count", 1238 "off" 1239}; 1240 1241/* 1242** These are the column/row/line separators used by the various 1243** import/export modes. 1244*/ 1245#define SEP_Column "|" 1246#define SEP_Row "\n" 1247#define SEP_Tab "\t" 1248#define SEP_Space " " 1249#define SEP_Comma "," 1250#define SEP_CrLf "\r\n" 1251#define SEP_Unit "\x1F" 1252#define SEP_Record "\x1E" 1253 1254/* 1255** Limit input nesting via .read or any other input redirect. 1256** It's not too expensive, so a generous allowance can be made. 1257*/ 1258#define MAX_INPUT_NESTING 25 1259 1260/* 1261** A callback for the sqlite3_log() interface. 1262*/ 1263static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1264 ShellState *p = (ShellState*)pArg; 1265 if( p->pLog==0 ) return; 1266 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1267 fflush(p->pLog); 1268} 1269 1270/* 1271** SQL function: shell_putsnl(X) 1272** 1273** Write the text X to the screen (or whatever output is being directed) 1274** adding a newline at the end, and then return X. 1275*/ 1276static void shellPutsFunc( 1277 sqlite3_context *pCtx, 1278 int nVal, 1279 sqlite3_value **apVal 1280){ 1281 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1282 (void)nVal; 1283 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1284 sqlite3_result_value(pCtx, apVal[0]); 1285} 1286 1287/* 1288** If in safe mode, print an error message described by the arguments 1289** and exit immediately. 1290*/ 1291static void failIfSafeMode( 1292 ShellState *p, 1293 const char *zErrMsg, 1294 ... 1295){ 1296 if( p->bSafeMode ){ 1297 va_list ap; 1298 char *zMsg; 1299 va_start(ap, zErrMsg); 1300 zMsg = sqlite3_vmprintf(zErrMsg, ap); 1301 va_end(ap); 1302 raw_printf(stderr, "line %d: ", p->lineno); 1303 utf8_printf(stderr, "%s\n", zMsg); 1304 exit(1); 1305 } 1306} 1307 1308/* 1309** SQL function: edit(VALUE) 1310** edit(VALUE,EDITOR) 1311** 1312** These steps: 1313** 1314** (1) Write VALUE into a temporary file. 1315** (2) Run program EDITOR on that temporary file. 1316** (3) Read the temporary file back and return its content as the result. 1317** (4) Delete the temporary file 1318** 1319** If the EDITOR argument is omitted, use the value in the VISUAL 1320** environment variable. If still there is no EDITOR, through an error. 1321** 1322** Also throw an error if the EDITOR program returns a non-zero exit code. 1323*/ 1324#ifndef SQLITE_NOHAVE_SYSTEM 1325static void editFunc( 1326 sqlite3_context *context, 1327 int argc, 1328 sqlite3_value **argv 1329){ 1330 const char *zEditor; 1331 char *zTempFile = 0; 1332 sqlite3 *db; 1333 char *zCmd = 0; 1334 int bBin; 1335 int rc; 1336 int hasCRNL = 0; 1337 FILE *f = 0; 1338 sqlite3_int64 sz; 1339 sqlite3_int64 x; 1340 unsigned char *p = 0; 1341 1342 if( argc==2 ){ 1343 zEditor = (const char*)sqlite3_value_text(argv[1]); 1344 }else{ 1345 zEditor = getenv("VISUAL"); 1346 } 1347 if( zEditor==0 ){ 1348 sqlite3_result_error(context, "no editor for edit()", -1); 1349 return; 1350 } 1351 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1352 sqlite3_result_error(context, "NULL input to edit()", -1); 1353 return; 1354 } 1355 db = sqlite3_context_db_handle(context); 1356 zTempFile = 0; 1357 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1358 if( zTempFile==0 ){ 1359 sqlite3_uint64 r = 0; 1360 sqlite3_randomness(sizeof(r), &r); 1361 zTempFile = sqlite3_mprintf("temp%llx", r); 1362 if( zTempFile==0 ){ 1363 sqlite3_result_error_nomem(context); 1364 return; 1365 } 1366 } 1367 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1368 /* When writing the file to be edited, do \n to \r\n conversions on systems 1369 ** that want \r\n line endings */ 1370 f = fopen(zTempFile, bBin ? "wb" : "w"); 1371 if( f==0 ){ 1372 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1373 goto edit_func_end; 1374 } 1375 sz = sqlite3_value_bytes(argv[0]); 1376 if( bBin ){ 1377 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); 1378 }else{ 1379 const char *z = (const char*)sqlite3_value_text(argv[0]); 1380 /* Remember whether or not the value originally contained \r\n */ 1381 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1382 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); 1383 } 1384 fclose(f); 1385 f = 0; 1386 if( x!=sz ){ 1387 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1388 goto edit_func_end; 1389 } 1390 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1391 if( zCmd==0 ){ 1392 sqlite3_result_error_nomem(context); 1393 goto edit_func_end; 1394 } 1395 rc = system(zCmd); 1396 sqlite3_free(zCmd); 1397 if( rc ){ 1398 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1399 goto edit_func_end; 1400 } 1401 f = fopen(zTempFile, "rb"); 1402 if( f==0 ){ 1403 sqlite3_result_error(context, 1404 "edit() cannot reopen temp file after edit", -1); 1405 goto edit_func_end; 1406 } 1407 fseek(f, 0, SEEK_END); 1408 sz = ftell(f); 1409 rewind(f); 1410 p = sqlite3_malloc64( sz+1 ); 1411 if( p==0 ){ 1412 sqlite3_result_error_nomem(context); 1413 goto edit_func_end; 1414 } 1415 x = fread(p, 1, (size_t)sz, f); 1416 fclose(f); 1417 f = 0; 1418 if( x!=sz ){ 1419 sqlite3_result_error(context, "could not read back the whole file", -1); 1420 goto edit_func_end; 1421 } 1422 if( bBin ){ 1423 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1424 }else{ 1425 sqlite3_int64 i, j; 1426 if( hasCRNL ){ 1427 /* If the original contains \r\n then do no conversions back to \n */ 1428 }else{ 1429 /* If the file did not originally contain \r\n then convert any new 1430 ** \r\n back into \n */ 1431 for(i=j=0; i<sz; i++){ 1432 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1433 p[j++] = p[i]; 1434 } 1435 sz = j; 1436 p[sz] = 0; 1437 } 1438 sqlite3_result_text64(context, (const char*)p, sz, 1439 sqlite3_free, SQLITE_UTF8); 1440 } 1441 p = 0; 1442 1443edit_func_end: 1444 if( f ) fclose(f); 1445 unlink(zTempFile); 1446 sqlite3_free(zTempFile); 1447 sqlite3_free(p); 1448} 1449#endif /* SQLITE_NOHAVE_SYSTEM */ 1450 1451/* 1452** Save or restore the current output mode 1453*/ 1454static void outputModePush(ShellState *p){ 1455 p->modePrior = p->mode; 1456 p->priorShFlgs = p->shellFlgs; 1457 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1458 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1459} 1460static void outputModePop(ShellState *p){ 1461 p->mode = p->modePrior; 1462 p->shellFlgs = p->priorShFlgs; 1463 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1464 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1465} 1466 1467/* 1468** Output the given string as a hex-encoded blob (eg. X'1234' ) 1469*/ 1470static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1471 int i; 1472 char *zBlob = (char *)pBlob; 1473 raw_printf(out,"X'"); 1474 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1475 raw_printf(out,"'"); 1476} 1477 1478/* 1479** Find a string that is not found anywhere in z[]. Return a pointer 1480** to that string. 1481** 1482** Try to use zA and zB first. If both of those are already found in z[] 1483** then make up some string and store it in the buffer zBuf. 1484*/ 1485static const char *unused_string( 1486 const char *z, /* Result must not appear anywhere in z */ 1487 const char *zA, const char *zB, /* Try these first */ 1488 char *zBuf /* Space to store a generated string */ 1489){ 1490 unsigned i = 0; 1491 if( strstr(z, zA)==0 ) return zA; 1492 if( strstr(z, zB)==0 ) return zB; 1493 do{ 1494 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1495 }while( strstr(z,zBuf)!=0 ); 1496 return zBuf; 1497} 1498 1499/* 1500** Output the given string as a quoted string using SQL quoting conventions. 1501** 1502** See also: output_quoted_escaped_string() 1503*/ 1504static void output_quoted_string(FILE *out, const char *z){ 1505 int i; 1506 char c; 1507 setBinaryMode(out, 1); 1508 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1509 if( c==0 ){ 1510 utf8_printf(out,"'%s'",z); 1511 }else{ 1512 raw_printf(out, "'"); 1513 while( *z ){ 1514 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1515 if( c=='\'' ) i++; 1516 if( i ){ 1517 utf8_printf(out, "%.*s", i, z); 1518 z += i; 1519 } 1520 if( c=='\'' ){ 1521 raw_printf(out, "'"); 1522 continue; 1523 } 1524 if( c==0 ){ 1525 break; 1526 } 1527 z++; 1528 } 1529 raw_printf(out, "'"); 1530 } 1531 setTextMode(out, 1); 1532} 1533 1534/* 1535** Output the given string as a quoted string using SQL quoting conventions. 1536** Additionallly , escape the "\n" and "\r" characters so that they do not 1537** get corrupted by end-of-line translation facilities in some operating 1538** systems. 1539** 1540** This is like output_quoted_string() but with the addition of the \r\n 1541** escape mechanism. 1542*/ 1543static void output_quoted_escaped_string(FILE *out, const char *z){ 1544 int i; 1545 char c; 1546 setBinaryMode(out, 1); 1547 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1548 if( c==0 ){ 1549 utf8_printf(out,"'%s'",z); 1550 }else{ 1551 const char *zNL = 0; 1552 const char *zCR = 0; 1553 int nNL = 0; 1554 int nCR = 0; 1555 char zBuf1[20], zBuf2[20]; 1556 for(i=0; z[i]; i++){ 1557 if( z[i]=='\n' ) nNL++; 1558 if( z[i]=='\r' ) nCR++; 1559 } 1560 if( nNL ){ 1561 raw_printf(out, "replace("); 1562 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1563 } 1564 if( nCR ){ 1565 raw_printf(out, "replace("); 1566 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1567 } 1568 raw_printf(out, "'"); 1569 while( *z ){ 1570 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1571 if( c=='\'' ) i++; 1572 if( i ){ 1573 utf8_printf(out, "%.*s", i, z); 1574 z += i; 1575 } 1576 if( c=='\'' ){ 1577 raw_printf(out, "'"); 1578 continue; 1579 } 1580 if( c==0 ){ 1581 break; 1582 } 1583 z++; 1584 if( c=='\n' ){ 1585 raw_printf(out, "%s", zNL); 1586 continue; 1587 } 1588 raw_printf(out, "%s", zCR); 1589 } 1590 raw_printf(out, "'"); 1591 if( nCR ){ 1592 raw_printf(out, ",'%s',char(13))", zCR); 1593 } 1594 if( nNL ){ 1595 raw_printf(out, ",'%s',char(10))", zNL); 1596 } 1597 } 1598 setTextMode(out, 1); 1599} 1600 1601/* 1602** Output the given string as a quoted according to C or TCL quoting rules. 1603*/ 1604static void output_c_string(FILE *out, const char *z){ 1605 unsigned int c; 1606 fputc('"', out); 1607 while( (c = *(z++))!=0 ){ 1608 if( c=='\\' ){ 1609 fputc(c, out); 1610 fputc(c, out); 1611 }else if( c=='"' ){ 1612 fputc('\\', out); 1613 fputc('"', out); 1614 }else if( c=='\t' ){ 1615 fputc('\\', out); 1616 fputc('t', out); 1617 }else if( c=='\n' ){ 1618 fputc('\\', out); 1619 fputc('n', out); 1620 }else if( c=='\r' ){ 1621 fputc('\\', out); 1622 fputc('r', out); 1623 }else if( !isprint(c&0xff) ){ 1624 raw_printf(out, "\\%03o", c&0xff); 1625 }else{ 1626 fputc(c, out); 1627 } 1628 } 1629 fputc('"', out); 1630} 1631 1632/* 1633** Output the given string as a quoted according to JSON quoting rules. 1634*/ 1635static void output_json_string(FILE *out, const char *z, int n){ 1636 unsigned int c; 1637 if( n<0 ) n = (int)strlen(z); 1638 fputc('"', out); 1639 while( n-- ){ 1640 c = *(z++); 1641 if( c=='\\' || c=='"' ){ 1642 fputc('\\', out); 1643 fputc(c, out); 1644 }else if( c<=0x1f ){ 1645 fputc('\\', out); 1646 if( c=='\b' ){ 1647 fputc('b', out); 1648 }else if( c=='\f' ){ 1649 fputc('f', out); 1650 }else if( c=='\n' ){ 1651 fputc('n', out); 1652 }else if( c=='\r' ){ 1653 fputc('r', out); 1654 }else if( c=='\t' ){ 1655 fputc('t', out); 1656 }else{ 1657 raw_printf(out, "u%04x",c); 1658 } 1659 }else{ 1660 fputc(c, out); 1661 } 1662 } 1663 fputc('"', out); 1664} 1665 1666/* 1667** Output the given string with characters that are special to 1668** HTML escaped. 1669*/ 1670static void output_html_string(FILE *out, const char *z){ 1671 int i; 1672 if( z==0 ) z = ""; 1673 while( *z ){ 1674 for(i=0; z[i] 1675 && z[i]!='<' 1676 && z[i]!='&' 1677 && z[i]!='>' 1678 && z[i]!='\"' 1679 && z[i]!='\''; 1680 i++){} 1681 if( i>0 ){ 1682 utf8_printf(out,"%.*s",i,z); 1683 } 1684 if( z[i]=='<' ){ 1685 raw_printf(out,"<"); 1686 }else if( z[i]=='&' ){ 1687 raw_printf(out,"&"); 1688 }else if( z[i]=='>' ){ 1689 raw_printf(out,">"); 1690 }else if( z[i]=='\"' ){ 1691 raw_printf(out,"""); 1692 }else if( z[i]=='\'' ){ 1693 raw_printf(out,"'"); 1694 }else{ 1695 break; 1696 } 1697 z += i + 1; 1698 } 1699} 1700 1701/* 1702** If a field contains any character identified by a 1 in the following 1703** array, then the string must be quoted for CSV. 1704*/ 1705static const char needCsvQuote[] = { 1706 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1707 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1708 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1709 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1710 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1711 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1712 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1713 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1714 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1715 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1716 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1717 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1718 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1719 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1720 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1721 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1722}; 1723 1724/* 1725** Output a single term of CSV. Actually, p->colSeparator is used for 1726** the separator, which may or may not be a comma. p->nullValue is 1727** the null value. Strings are quoted if necessary. The separator 1728** is only issued if bSep is true. 1729*/ 1730static void output_csv(ShellState *p, const char *z, int bSep){ 1731 FILE *out = p->out; 1732 if( z==0 ){ 1733 utf8_printf(out,"%s",p->nullValue); 1734 }else{ 1735 unsigned i; 1736 for(i=0; z[i]; i++){ 1737 if( needCsvQuote[((unsigned char*)z)[i]] ){ 1738 i = 0; 1739 break; 1740 } 1741 } 1742 if( i==0 || strstr(z, p->colSeparator)!=0 ){ 1743 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1744 shell_check_oom(zQuoted); 1745 utf8_printf(out, "%s", zQuoted); 1746 sqlite3_free(zQuoted); 1747 }else{ 1748 utf8_printf(out, "%s", z); 1749 } 1750 } 1751 if( bSep ){ 1752 utf8_printf(p->out, "%s", p->colSeparator); 1753 } 1754} 1755 1756/* 1757** This routine runs when the user presses Ctrl-C 1758*/ 1759static void interrupt_handler(int NotUsed){ 1760 UNUSED_PARAMETER(NotUsed); 1761 seenInterrupt++; 1762 if( seenInterrupt>2 ) exit(1); 1763 if( globalDb ) sqlite3_interrupt(globalDb); 1764} 1765 1766#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1767/* 1768** This routine runs for console events (e.g. Ctrl-C) on Win32 1769*/ 1770static BOOL WINAPI ConsoleCtrlHandler( 1771 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1772){ 1773 if( dwCtrlType==CTRL_C_EVENT ){ 1774 interrupt_handler(0); 1775 return TRUE; 1776 } 1777 return FALSE; 1778} 1779#endif 1780 1781#ifndef SQLITE_OMIT_AUTHORIZATION 1782/* 1783** This authorizer runs in safe mode. 1784*/ 1785static int safeModeAuth( 1786 void *pClientData, 1787 int op, 1788 const char *zA1, 1789 const char *zA2, 1790 const char *zA3, 1791 const char *zA4 1792){ 1793 ShellState *p = (ShellState*)pClientData; 1794 static const char *azProhibitedFunctions[] = { 1795 "edit", 1796 "fts3_tokenizer", 1797 "load_extension", 1798 "readfile", 1799 "writefile", 1800 "zipfile", 1801 "zipfile_cds", 1802 }; 1803 UNUSED_PARAMETER(zA2); 1804 UNUSED_PARAMETER(zA3); 1805 UNUSED_PARAMETER(zA4); 1806 switch( op ){ 1807 case SQLITE_ATTACH: { 1808 failIfSafeMode(p, "cannot run ATTACH in safe mode"); 1809 break; 1810 } 1811 case SQLITE_FUNCTION: { 1812 int i; 1813 for(i=0; i<ArraySize(azProhibitedFunctions); i++){ 1814 if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){ 1815 failIfSafeMode(p, "cannot use the %s() function in safe mode", 1816 azProhibitedFunctions[i]); 1817 } 1818 } 1819 break; 1820 } 1821 } 1822 return SQLITE_OK; 1823} 1824 1825/* 1826** When the ".auth ON" is set, the following authorizer callback is 1827** invoked. It always returns SQLITE_OK. 1828*/ 1829static int shellAuth( 1830 void *pClientData, 1831 int op, 1832 const char *zA1, 1833 const char *zA2, 1834 const char *zA3, 1835 const char *zA4 1836){ 1837 ShellState *p = (ShellState*)pClientData; 1838 static const char *azAction[] = { 0, 1839 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1840 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1841 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1842 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1843 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1844 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1845 "PRAGMA", "READ", "SELECT", 1846 "TRANSACTION", "UPDATE", "ATTACH", 1847 "DETACH", "ALTER_TABLE", "REINDEX", 1848 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1849 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1850 }; 1851 int i; 1852 const char *az[4]; 1853 az[0] = zA1; 1854 az[1] = zA2; 1855 az[2] = zA3; 1856 az[3] = zA4; 1857 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1858 for(i=0; i<4; i++){ 1859 raw_printf(p->out, " "); 1860 if( az[i] ){ 1861 output_c_string(p->out, az[i]); 1862 }else{ 1863 raw_printf(p->out, "NULL"); 1864 } 1865 } 1866 raw_printf(p->out, "\n"); 1867 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); 1868 return SQLITE_OK; 1869} 1870#endif 1871 1872/* 1873** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1874** 1875** This routine converts some CREATE TABLE statements for shadow tables 1876** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1877*/ 1878static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1879 if( z==0 ) return; 1880 if( zTail==0 ) return; 1881 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1882 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1883 }else{ 1884 utf8_printf(out, "%s%s", z, zTail); 1885 } 1886} 1887static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1888 char c = z[n]; 1889 z[n] = 0; 1890 printSchemaLine(out, z, zTail); 1891 z[n] = c; 1892} 1893 1894/* 1895** Return true if string z[] has nothing but whitespace and comments to the 1896** end of the first line. 1897*/ 1898static int wsToEol(const char *z){ 1899 int i; 1900 for(i=0; z[i]; i++){ 1901 if( z[i]=='\n' ) return 1; 1902 if( IsSpace(z[i]) ) continue; 1903 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1904 return 0; 1905 } 1906 return 1; 1907} 1908 1909/* 1910** Add a new entry to the EXPLAIN QUERY PLAN data 1911*/ 1912static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1913 EQPGraphRow *pNew; 1914 int nText = strlen30(zText); 1915 if( p->autoEQPtest ){ 1916 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1917 } 1918 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1919 shell_check_oom(pNew); 1920 pNew->iEqpId = iEqpId; 1921 pNew->iParentId = p2; 1922 memcpy(pNew->zText, zText, nText+1); 1923 pNew->pNext = 0; 1924 if( p->sGraph.pLast ){ 1925 p->sGraph.pLast->pNext = pNew; 1926 }else{ 1927 p->sGraph.pRow = pNew; 1928 } 1929 p->sGraph.pLast = pNew; 1930} 1931 1932/* 1933** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1934** in p->sGraph. 1935*/ 1936static void eqp_reset(ShellState *p){ 1937 EQPGraphRow *pRow, *pNext; 1938 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1939 pNext = pRow->pNext; 1940 sqlite3_free(pRow); 1941 } 1942 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1943} 1944 1945/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1946** pOld, or return the first such line if pOld is NULL 1947*/ 1948static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1949 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1950 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1951 return pRow; 1952} 1953 1954/* Render a single level of the graph that has iEqpId as its parent. Called 1955** recursively to render sublevels. 1956*/ 1957static void eqp_render_level(ShellState *p, int iEqpId){ 1958 EQPGraphRow *pRow, *pNext; 1959 int n = strlen30(p->sGraph.zPrefix); 1960 char *z; 1961 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1962 pNext = eqp_next_row(p, iEqpId, pRow); 1963 z = pRow->zText; 1964 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, 1965 pNext ? "|--" : "`--", z); 1966 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1967 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 1968 eqp_render_level(p, pRow->iEqpId); 1969 p->sGraph.zPrefix[n] = 0; 1970 } 1971 } 1972} 1973 1974/* 1975** Display and reset the EXPLAIN QUERY PLAN data 1976*/ 1977static void eqp_render(ShellState *p){ 1978 EQPGraphRow *pRow = p->sGraph.pRow; 1979 if( pRow ){ 1980 if( pRow->zText[0]=='-' ){ 1981 if( pRow->pNext==0 ){ 1982 eqp_reset(p); 1983 return; 1984 } 1985 utf8_printf(p->out, "%s\n", pRow->zText+3); 1986 p->sGraph.pRow = pRow->pNext; 1987 sqlite3_free(pRow); 1988 }else{ 1989 utf8_printf(p->out, "QUERY PLAN\n"); 1990 } 1991 p->sGraph.zPrefix[0] = 0; 1992 eqp_render_level(p, 0); 1993 eqp_reset(p); 1994 } 1995} 1996 1997#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1998/* 1999** Progress handler callback. 2000*/ 2001static int progress_handler(void *pClientData) { 2002 ShellState *p = (ShellState*)pClientData; 2003 p->nProgress++; 2004 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 2005 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 2006 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 2007 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 2008 return 1; 2009 } 2010 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 2011 raw_printf(p->out, "Progress %u\n", p->nProgress); 2012 } 2013 return 0; 2014} 2015#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 2016 2017/* 2018** Print N dashes 2019*/ 2020static void print_dashes(FILE *out, int N){ 2021 const char zDash[] = "--------------------------------------------------"; 2022 const int nDash = sizeof(zDash) - 1; 2023 while( N>nDash ){ 2024 fputs(zDash, out); 2025 N -= nDash; 2026 } 2027 raw_printf(out, "%.*s", N, zDash); 2028} 2029 2030/* 2031** Print a markdown or table-style row separator using ascii-art 2032*/ 2033static void print_row_separator( 2034 ShellState *p, 2035 int nArg, 2036 const char *zSep 2037){ 2038 int i; 2039 if( nArg>0 ){ 2040 fputs(zSep, p->out); 2041 print_dashes(p->out, p->actualWidth[0]+2); 2042 for(i=1; i<nArg; i++){ 2043 fputs(zSep, p->out); 2044 print_dashes(p->out, p->actualWidth[i]+2); 2045 } 2046 fputs(zSep, p->out); 2047 } 2048 fputs("\n", p->out); 2049} 2050 2051/* 2052** This is the callback routine that the shell 2053** invokes for each row of a query result. 2054*/ 2055static int shell_callback( 2056 void *pArg, 2057 int nArg, /* Number of result columns */ 2058 char **azArg, /* Text of each result column */ 2059 char **azCol, /* Column names */ 2060 int *aiType /* Column types. Might be NULL */ 2061){ 2062 int i; 2063 ShellState *p = (ShellState*)pArg; 2064 2065 if( azArg==0 ) return 0; 2066 switch( p->cMode ){ 2067 case MODE_Count: 2068 case MODE_Off: { 2069 break; 2070 } 2071 case MODE_Line: { 2072 int w = 5; 2073 if( azArg==0 ) break; 2074 for(i=0; i<nArg; i++){ 2075 int len = strlen30(azCol[i] ? azCol[i] : ""); 2076 if( len>w ) w = len; 2077 } 2078 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 2079 for(i=0; i<nArg; i++){ 2080 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 2081 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 2082 } 2083 break; 2084 } 2085 case MODE_Explain: { 2086 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13}; 2087 if( nArg>ArraySize(aExplainWidth) ){ 2088 nArg = ArraySize(aExplainWidth); 2089 } 2090 if( p->cnt++==0 ){ 2091 for(i=0; i<nArg; i++){ 2092 int w = aExplainWidth[i]; 2093 utf8_width_print(p->out, w, azCol[i]); 2094 fputs(i==nArg-1 ? "\n" : " ", p->out); 2095 } 2096 for(i=0; i<nArg; i++){ 2097 int w = aExplainWidth[i]; 2098 print_dashes(p->out, w); 2099 fputs(i==nArg-1 ? "\n" : " ", p->out); 2100 } 2101 } 2102 if( azArg==0 ) break; 2103 for(i=0; i<nArg; i++){ 2104 int w = aExplainWidth[i]; 2105 if( i==nArg-1 ) w = 0; 2106 if( azArg[i] && strlenChar(azArg[i])>w ){ 2107 w = strlenChar(azArg[i]); 2108 } 2109 if( i==1 && p->aiIndent && p->pStmt ){ 2110 if( p->iIndent<p->nIndent ){ 2111 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 2112 } 2113 p->iIndent++; 2114 } 2115 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 2116 fputs(i==nArg-1 ? "\n" : " ", p->out); 2117 } 2118 break; 2119 } 2120 case MODE_Semi: { /* .schema and .fullschema output */ 2121 printSchemaLine(p->out, azArg[0], ";\n"); 2122 break; 2123 } 2124 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 2125 char *z; 2126 int j; 2127 int nParen = 0; 2128 char cEnd = 0; 2129 char c; 2130 int nLine = 0; 2131 assert( nArg==1 ); 2132 if( azArg[0]==0 ) break; 2133 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 2134 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 2135 ){ 2136 utf8_printf(p->out, "%s;\n", azArg[0]); 2137 break; 2138 } 2139 z = sqlite3_mprintf("%s", azArg[0]); 2140 shell_check_oom(z); 2141 j = 0; 2142 for(i=0; IsSpace(z[i]); i++){} 2143 for(; (c = z[i])!=0; i++){ 2144 if( IsSpace(c) ){ 2145 if( z[j-1]=='\r' ) z[j-1] = '\n'; 2146 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 2147 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 2148 j--; 2149 } 2150 z[j++] = c; 2151 } 2152 while( j>0 && IsSpace(z[j-1]) ){ j--; } 2153 z[j] = 0; 2154 if( strlen30(z)>=79 ){ 2155 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ 2156 if( c==cEnd ){ 2157 cEnd = 0; 2158 }else if( c=='"' || c=='\'' || c=='`' ){ 2159 cEnd = c; 2160 }else if( c=='[' ){ 2161 cEnd = ']'; 2162 }else if( c=='-' && z[i+1]=='-' ){ 2163 cEnd = '\n'; 2164 }else if( c=='(' ){ 2165 nParen++; 2166 }else if( c==')' ){ 2167 nParen--; 2168 if( nLine>0 && nParen==0 && j>0 ){ 2169 printSchemaLineN(p->out, z, j, "\n"); 2170 j = 0; 2171 } 2172 } 2173 z[j++] = c; 2174 if( nParen==1 && cEnd==0 2175 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 2176 ){ 2177 if( c=='\n' ) j--; 2178 printSchemaLineN(p->out, z, j, "\n "); 2179 j = 0; 2180 nLine++; 2181 while( IsSpace(z[i+1]) ){ i++; } 2182 } 2183 } 2184 z[j] = 0; 2185 } 2186 printSchemaLine(p->out, z, ";\n"); 2187 sqlite3_free(z); 2188 break; 2189 } 2190 case MODE_List: { 2191 if( p->cnt++==0 && p->showHeader ){ 2192 for(i=0; i<nArg; i++){ 2193 utf8_printf(p->out,"%s%s",azCol[i], 2194 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2195 } 2196 } 2197 if( azArg==0 ) break; 2198 for(i=0; i<nArg; i++){ 2199 char *z = azArg[i]; 2200 if( z==0 ) z = p->nullValue; 2201 utf8_printf(p->out, "%s", z); 2202 if( i<nArg-1 ){ 2203 utf8_printf(p->out, "%s", p->colSeparator); 2204 }else{ 2205 utf8_printf(p->out, "%s", p->rowSeparator); 2206 } 2207 } 2208 break; 2209 } 2210 case MODE_Html: { 2211 if( p->cnt++==0 && p->showHeader ){ 2212 raw_printf(p->out,"<TR>"); 2213 for(i=0; i<nArg; i++){ 2214 raw_printf(p->out,"<TH>"); 2215 output_html_string(p->out, azCol[i]); 2216 raw_printf(p->out,"</TH>\n"); 2217 } 2218 raw_printf(p->out,"</TR>\n"); 2219 } 2220 if( azArg==0 ) break; 2221 raw_printf(p->out,"<TR>"); 2222 for(i=0; i<nArg; i++){ 2223 raw_printf(p->out,"<TD>"); 2224 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2225 raw_printf(p->out,"</TD>\n"); 2226 } 2227 raw_printf(p->out,"</TR>\n"); 2228 break; 2229 } 2230 case MODE_Tcl: { 2231 if( p->cnt++==0 && p->showHeader ){ 2232 for(i=0; i<nArg; i++){ 2233 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2234 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2235 } 2236 utf8_printf(p->out, "%s", p->rowSeparator); 2237 } 2238 if( azArg==0 ) break; 2239 for(i=0; i<nArg; i++){ 2240 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2241 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2242 } 2243 utf8_printf(p->out, "%s", p->rowSeparator); 2244 break; 2245 } 2246 case MODE_Csv: { 2247 setBinaryMode(p->out, 1); 2248 if( p->cnt++==0 && p->showHeader ){ 2249 for(i=0; i<nArg; i++){ 2250 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2251 } 2252 utf8_printf(p->out, "%s", p->rowSeparator); 2253 } 2254 if( nArg>0 ){ 2255 for(i=0; i<nArg; i++){ 2256 output_csv(p, azArg[i], i<nArg-1); 2257 } 2258 utf8_printf(p->out, "%s", p->rowSeparator); 2259 } 2260 setTextMode(p->out, 1); 2261 break; 2262 } 2263 case MODE_Insert: { 2264 if( azArg==0 ) break; 2265 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2266 if( p->showHeader ){ 2267 raw_printf(p->out,"("); 2268 for(i=0; i<nArg; i++){ 2269 if( i>0 ) raw_printf(p->out, ","); 2270 if( quoteChar(azCol[i]) ){ 2271 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2272 shell_check_oom(z); 2273 utf8_printf(p->out, "%s", z); 2274 sqlite3_free(z); 2275 }else{ 2276 raw_printf(p->out, "%s", azCol[i]); 2277 } 2278 } 2279 raw_printf(p->out,")"); 2280 } 2281 p->cnt++; 2282 for(i=0; i<nArg; i++){ 2283 raw_printf(p->out, i>0 ? "," : " VALUES("); 2284 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2285 utf8_printf(p->out,"NULL"); 2286 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2287 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2288 output_quoted_string(p->out, azArg[i]); 2289 }else{ 2290 output_quoted_escaped_string(p->out, azArg[i]); 2291 } 2292 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2293 utf8_printf(p->out,"%s", azArg[i]); 2294 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2295 char z[50]; 2296 double r = sqlite3_column_double(p->pStmt, i); 2297 sqlite3_uint64 ur; 2298 memcpy(&ur,&r,sizeof(r)); 2299 if( ur==0x7ff0000000000000LL ){ 2300 raw_printf(p->out, "1e999"); 2301 }else if( ur==0xfff0000000000000LL ){ 2302 raw_printf(p->out, "-1e999"); 2303 }else{ 2304 sqlite3_snprintf(50,z,"%!.20g", r); 2305 raw_printf(p->out, "%s", z); 2306 } 2307 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2308 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2309 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2310 output_hex_blob(p->out, pBlob, nBlob); 2311 }else if( isNumber(azArg[i], 0) ){ 2312 utf8_printf(p->out,"%s", azArg[i]); 2313 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2314 output_quoted_string(p->out, azArg[i]); 2315 }else{ 2316 output_quoted_escaped_string(p->out, azArg[i]); 2317 } 2318 } 2319 raw_printf(p->out,");\n"); 2320 break; 2321 } 2322 case MODE_Json: { 2323 if( azArg==0 ) break; 2324 if( p->cnt==0 ){ 2325 fputs("[{", p->out); 2326 }else{ 2327 fputs(",\n{", p->out); 2328 } 2329 p->cnt++; 2330 for(i=0; i<nArg; i++){ 2331 output_json_string(p->out, azCol[i], -1); 2332 putc(':', p->out); 2333 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2334 fputs("null",p->out); 2335 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2336 char z[50]; 2337 double r = sqlite3_column_double(p->pStmt, i); 2338 sqlite3_uint64 ur; 2339 memcpy(&ur,&r,sizeof(r)); 2340 if( ur==0x7ff0000000000000LL ){ 2341 raw_printf(p->out, "1e999"); 2342 }else if( ur==0xfff0000000000000LL ){ 2343 raw_printf(p->out, "-1e999"); 2344 }else{ 2345 sqlite3_snprintf(50,z,"%!.20g", r); 2346 raw_printf(p->out, "%s", z); 2347 } 2348 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2349 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2350 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2351 output_json_string(p->out, pBlob, nBlob); 2352 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2353 output_json_string(p->out, azArg[i], -1); 2354 }else{ 2355 utf8_printf(p->out,"%s", azArg[i]); 2356 } 2357 if( i<nArg-1 ){ 2358 putc(',', p->out); 2359 } 2360 } 2361 putc('}', p->out); 2362 break; 2363 } 2364 case MODE_Quote: { 2365 if( azArg==0 ) break; 2366 if( p->cnt==0 && p->showHeader ){ 2367 for(i=0; i<nArg; i++){ 2368 if( i>0 ) fputs(p->colSeparator, p->out); 2369 output_quoted_string(p->out, azCol[i]); 2370 } 2371 fputs(p->rowSeparator, p->out); 2372 } 2373 p->cnt++; 2374 for(i=0; i<nArg; i++){ 2375 if( i>0 ) fputs(p->colSeparator, p->out); 2376 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2377 utf8_printf(p->out,"NULL"); 2378 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2379 output_quoted_string(p->out, azArg[i]); 2380 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2381 utf8_printf(p->out,"%s", azArg[i]); 2382 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2383 char z[50]; 2384 double r = sqlite3_column_double(p->pStmt, i); 2385 sqlite3_snprintf(50,z,"%!.20g", r); 2386 raw_printf(p->out, "%s", z); 2387 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2388 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2389 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2390 output_hex_blob(p->out, pBlob, nBlob); 2391 }else if( isNumber(azArg[i], 0) ){ 2392 utf8_printf(p->out,"%s", azArg[i]); 2393 }else{ 2394 output_quoted_string(p->out, azArg[i]); 2395 } 2396 } 2397 fputs(p->rowSeparator, p->out); 2398 break; 2399 } 2400 case MODE_Ascii: { 2401 if( p->cnt++==0 && p->showHeader ){ 2402 for(i=0; i<nArg; i++){ 2403 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2404 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2405 } 2406 utf8_printf(p->out, "%s", p->rowSeparator); 2407 } 2408 if( azArg==0 ) break; 2409 for(i=0; i<nArg; i++){ 2410 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2411 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2412 } 2413 utf8_printf(p->out, "%s", p->rowSeparator); 2414 break; 2415 } 2416 case MODE_EQP: { 2417 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2418 break; 2419 } 2420 } 2421 return 0; 2422} 2423 2424/* 2425** This is the callback routine that the SQLite library 2426** invokes for each row of a query result. 2427*/ 2428static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2429 /* since we don't have type info, call the shell_callback with a NULL value */ 2430 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2431} 2432 2433/* 2434** This is the callback routine from sqlite3_exec() that appends all 2435** output onto the end of a ShellText object. 2436*/ 2437static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2438 ShellText *p = (ShellText*)pArg; 2439 int i; 2440 UNUSED_PARAMETER(az); 2441 if( azArg==0 ) return 0; 2442 if( p->n ) appendText(p, "|", 0); 2443 for(i=0; i<nArg; i++){ 2444 if( i ) appendText(p, ",", 0); 2445 if( azArg[i] ) appendText(p, azArg[i], 0); 2446 } 2447 return 0; 2448} 2449 2450/* 2451** Generate an appropriate SELFTEST table in the main database. 2452*/ 2453static void createSelftestTable(ShellState *p){ 2454 char *zErrMsg = 0; 2455 sqlite3_exec(p->db, 2456 "SAVEPOINT selftest_init;\n" 2457 "CREATE TABLE IF NOT EXISTS selftest(\n" 2458 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2459 " op TEXT,\n" /* Operator: memo run */ 2460 " cmd TEXT,\n" /* Command text */ 2461 " ans TEXT\n" /* Desired answer */ 2462 ");" 2463 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2464 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2465 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2466 " 'memo','Tests generated by --init');\n" 2467 "INSERT INTO [_shell$self]\n" 2468 " SELECT 'run',\n" 2469 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2470 "FROM sqlite_schema ORDER BY 2'',224))',\n" 2471 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2472 "FROM sqlite_schema ORDER BY 2',224));\n" 2473 "INSERT INTO [_shell$self]\n" 2474 " SELECT 'run'," 2475 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2476 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2477 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2478 " FROM (\n" 2479 " SELECT name FROM sqlite_schema\n" 2480 " WHERE type='table'\n" 2481 " AND name<>'selftest'\n" 2482 " AND coalesce(rootpage,0)>0\n" 2483 " )\n" 2484 " ORDER BY name;\n" 2485 "INSERT INTO [_shell$self]\n" 2486 " VALUES('run','PRAGMA integrity_check','ok');\n" 2487 "INSERT INTO selftest(tno,op,cmd,ans)" 2488 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2489 "DROP TABLE [_shell$self];" 2490 ,0,0,&zErrMsg); 2491 if( zErrMsg ){ 2492 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2493 sqlite3_free(zErrMsg); 2494 } 2495 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2496} 2497 2498 2499/* 2500** Set the destination table field of the ShellState structure to 2501** the name of the table given. Escape any quote characters in the 2502** table name. 2503*/ 2504static void set_table_name(ShellState *p, const char *zName){ 2505 int i, n; 2506 char cQuote; 2507 char *z; 2508 2509 if( p->zDestTable ){ 2510 free(p->zDestTable); 2511 p->zDestTable = 0; 2512 } 2513 if( zName==0 ) return; 2514 cQuote = quoteChar(zName); 2515 n = strlen30(zName); 2516 if( cQuote ) n += n+2; 2517 z = p->zDestTable = malloc( n+1 ); 2518 shell_check_oom(z); 2519 n = 0; 2520 if( cQuote ) z[n++] = cQuote; 2521 for(i=0; zName[i]; i++){ 2522 z[n++] = zName[i]; 2523 if( zName[i]==cQuote ) z[n++] = cQuote; 2524 } 2525 if( cQuote ) z[n++] = cQuote; 2526 z[n] = 0; 2527} 2528 2529/* 2530** Maybe construct two lines of text that point out the position of a 2531** syntax error. Return a pointer to the text, in memory obtained from 2532** sqlite3_malloc(). Or, if the most recent error does not involve a 2533** specific token that we can point to, return an empty string. 2534** 2535** In all cases, the memory returned is obtained from sqlite3_malloc64() 2536** and should be released by the caller invoking sqlite3_free(). 2537*/ 2538static char *shell_error_context(const char *zSql, sqlite3 *db){ 2539 int iOffset; 2540 size_t len; 2541 char *zCode; 2542 char *zMsg; 2543 int i; 2544 if( db==0 2545 || zSql==0 2546 || (iOffset = sqlite3_error_offset(db))<0 2547 ){ 2548 return sqlite3_mprintf(""); 2549 } 2550 while( iOffset>50 ){ 2551 iOffset--; 2552 zSql++; 2553 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } 2554 } 2555 len = strlen(zSql); 2556 if( len>78 ){ 2557 len = 78; 2558 while( (zSql[len]&0xc0)==0x80 ) len--; 2559 } 2560 zCode = sqlite3_mprintf("%.*s", len, zSql); 2561 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; } 2562 if( iOffset<25 ){ 2563 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode, iOffset, ""); 2564 }else{ 2565 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode, iOffset-14, ""); 2566 } 2567 return zMsg; 2568} 2569 2570 2571/* 2572** Execute a query statement that will generate SQL output. Print 2573** the result columns, comma-separated, on a line and then add a 2574** semicolon terminator to the end of that line. 2575** 2576** If the number of columns is 1 and that column contains text "--" 2577** then write the semicolon on a separate line. That way, if a 2578** "--" comment occurs at the end of the statement, the comment 2579** won't consume the semicolon terminator. 2580*/ 2581static int run_table_dump_query( 2582 ShellState *p, /* Query context */ 2583 const char *zSelect /* SELECT statement to extract content */ 2584){ 2585 sqlite3_stmt *pSelect; 2586 int rc; 2587 int nResult; 2588 int i; 2589 const char *z; 2590 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2591 if( rc!=SQLITE_OK || !pSelect ){ 2592 char *zContext = shell_error_context(zSelect, p->db); 2593 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc, 2594 sqlite3_errmsg(p->db), zContext); 2595 sqlite3_free(zContext); 2596 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2597 return rc; 2598 } 2599 rc = sqlite3_step(pSelect); 2600 nResult = sqlite3_column_count(pSelect); 2601 while( rc==SQLITE_ROW ){ 2602 z = (const char*)sqlite3_column_text(pSelect, 0); 2603 utf8_printf(p->out, "%s", z); 2604 for(i=1; i<nResult; i++){ 2605 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2606 } 2607 if( z==0 ) z = ""; 2608 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2609 if( z[0] ){ 2610 raw_printf(p->out, "\n;\n"); 2611 }else{ 2612 raw_printf(p->out, ";\n"); 2613 } 2614 rc = sqlite3_step(pSelect); 2615 } 2616 rc = sqlite3_finalize(pSelect); 2617 if( rc!=SQLITE_OK ){ 2618 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2619 sqlite3_errmsg(p->db)); 2620 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2621 } 2622 return rc; 2623} 2624 2625/* 2626** Allocate space and save off string indicating current error. 2627*/ 2628static char *save_err_msg( 2629 sqlite3 *db, /* Database to query */ 2630 const char *zWhen, /* Qualifier (format) wrapper */ 2631 int rc, /* Error code returned from API */ 2632 const char *zSql /* SQL string, or NULL */ 2633){ 2634 char *zErr; 2635 char *zContext; 2636 if( zWhen==0 ) zWhen = "%s (%d)%s"; 2637 zContext = shell_error_context(zSql, db); 2638 zErr = sqlite3_mprintf(zWhen, sqlite3_errmsg(db), rc, zContext); 2639 shell_check_oom(zErr); 2640 sqlite3_free(zContext); 2641 return zErr; 2642} 2643 2644#ifdef __linux__ 2645/* 2646** Attempt to display I/O stats on Linux using /proc/PID/io 2647*/ 2648static void displayLinuxIoStats(FILE *out){ 2649 FILE *in; 2650 char z[200]; 2651 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2652 in = fopen(z, "rb"); 2653 if( in==0 ) return; 2654 while( fgets(z, sizeof(z), in)!=0 ){ 2655 static const struct { 2656 const char *zPattern; 2657 const char *zDesc; 2658 } aTrans[] = { 2659 { "rchar: ", "Bytes received by read():" }, 2660 { "wchar: ", "Bytes sent to write():" }, 2661 { "syscr: ", "Read() system calls:" }, 2662 { "syscw: ", "Write() system calls:" }, 2663 { "read_bytes: ", "Bytes read from storage:" }, 2664 { "write_bytes: ", "Bytes written to storage:" }, 2665 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2666 }; 2667 int i; 2668 for(i=0; i<ArraySize(aTrans); i++){ 2669 int n = strlen30(aTrans[i].zPattern); 2670 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2671 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2672 break; 2673 } 2674 } 2675 } 2676 fclose(in); 2677} 2678#endif 2679 2680/* 2681** Display a single line of status using 64-bit values. 2682*/ 2683static void displayStatLine( 2684 ShellState *p, /* The shell context */ 2685 char *zLabel, /* Label for this one line */ 2686 char *zFormat, /* Format for the result */ 2687 int iStatusCtrl, /* Which status to display */ 2688 int bReset /* True to reset the stats */ 2689){ 2690 sqlite3_int64 iCur = -1; 2691 sqlite3_int64 iHiwtr = -1; 2692 int i, nPercent; 2693 char zLine[200]; 2694 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2695 for(i=0, nPercent=0; zFormat[i]; i++){ 2696 if( zFormat[i]=='%' ) nPercent++; 2697 } 2698 if( nPercent>1 ){ 2699 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2700 }else{ 2701 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2702 } 2703 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2704} 2705 2706/* 2707** Display memory stats. 2708*/ 2709static int display_stats( 2710 sqlite3 *db, /* Database to query */ 2711 ShellState *pArg, /* Pointer to ShellState */ 2712 int bReset /* True to reset the stats */ 2713){ 2714 int iCur; 2715 int iHiwtr; 2716 FILE *out; 2717 if( pArg==0 || pArg->out==0 ) return 0; 2718 out = pArg->out; 2719 2720 if( pArg->pStmt && pArg->statsOn==2 ){ 2721 int nCol, i, x; 2722 sqlite3_stmt *pStmt = pArg->pStmt; 2723 char z[100]; 2724 nCol = sqlite3_column_count(pStmt); 2725 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2726 for(i=0; i<nCol; i++){ 2727 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2728 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2729#ifndef SQLITE_OMIT_DECLTYPE 2730 sqlite3_snprintf(30, z+x, "declared type:"); 2731 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2732#endif 2733#ifdef SQLITE_ENABLE_COLUMN_METADATA 2734 sqlite3_snprintf(30, z+x, "database name:"); 2735 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2736 sqlite3_snprintf(30, z+x, "table name:"); 2737 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2738 sqlite3_snprintf(30, z+x, "origin name:"); 2739 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2740#endif 2741 } 2742 } 2743 2744 if( pArg->statsOn==3 ){ 2745 if( pArg->pStmt ){ 2746 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2747 raw_printf(pArg->out, "VM-steps: %d\n", iCur); 2748 } 2749 return 0; 2750 } 2751 2752 displayStatLine(pArg, "Memory Used:", 2753 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2754 displayStatLine(pArg, "Number of Outstanding Allocations:", 2755 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2756 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2757 displayStatLine(pArg, "Number of Pcache Pages Used:", 2758 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2759 } 2760 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2761 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2762 displayStatLine(pArg, "Largest Allocation:", 2763 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2764 displayStatLine(pArg, "Largest Pcache Allocation:", 2765 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2766#ifdef YYTRACKMAXSTACKDEPTH 2767 displayStatLine(pArg, "Deepest Parser Stack:", 2768 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2769#endif 2770 2771 if( db ){ 2772 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2773 iHiwtr = iCur = -1; 2774 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2775 &iCur, &iHiwtr, bReset); 2776 raw_printf(pArg->out, 2777 "Lookaside Slots Used: %d (max %d)\n", 2778 iCur, iHiwtr); 2779 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2780 &iCur, &iHiwtr, bReset); 2781 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2782 iHiwtr); 2783 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2784 &iCur, &iHiwtr, bReset); 2785 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2786 iHiwtr); 2787 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2788 &iCur, &iHiwtr, bReset); 2789 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2790 iHiwtr); 2791 } 2792 iHiwtr = iCur = -1; 2793 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2794 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2795 iCur); 2796 iHiwtr = iCur = -1; 2797 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2798 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2799 iHiwtr = iCur = -1; 2800 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2801 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2802 iHiwtr = iCur = -1; 2803 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2804 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2805 iHiwtr = iCur = -1; 2806 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2807 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2808 iHiwtr = iCur = -1; 2809 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2810 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2811 iCur); 2812 iHiwtr = iCur = -1; 2813 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2814 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2815 iCur); 2816 } 2817 2818 if( pArg->pStmt ){ 2819 int iHit, iMiss; 2820 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2821 bReset); 2822 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2823 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2824 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2825 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2826 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2827 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset); 2828 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset); 2829 if( iHit || iMiss ){ 2830 raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n", 2831 iHit, iHit+iMiss); 2832 } 2833 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2834 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2835 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); 2836 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2837 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2838 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2839 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2840 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2841 } 2842 2843#ifdef __linux__ 2844 displayLinuxIoStats(pArg->out); 2845#endif 2846 2847 /* Do not remove this machine readable comment: extra-stats-output-here */ 2848 2849 return 0; 2850} 2851 2852/* 2853** Display scan stats. 2854*/ 2855static void display_scanstats( 2856 sqlite3 *db, /* Database to query */ 2857 ShellState *pArg /* Pointer to ShellState */ 2858){ 2859#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2860 UNUSED_PARAMETER(db); 2861 UNUSED_PARAMETER(pArg); 2862#else 2863 int i, k, n, mx; 2864 raw_printf(pArg->out, "-------- scanstats --------\n"); 2865 mx = 0; 2866 for(k=0; k<=mx; k++){ 2867 double rEstLoop = 1.0; 2868 for(i=n=0; 1; i++){ 2869 sqlite3_stmt *p = pArg->pStmt; 2870 sqlite3_int64 nLoop, nVisit; 2871 double rEst; 2872 int iSid; 2873 const char *zExplain; 2874 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2875 break; 2876 } 2877 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2878 if( iSid>mx ) mx = iSid; 2879 if( iSid!=k ) continue; 2880 if( n==0 ){ 2881 rEstLoop = (double)nLoop; 2882 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2883 } 2884 n++; 2885 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2886 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2887 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2888 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2889 rEstLoop *= rEst; 2890 raw_printf(pArg->out, 2891 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2892 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2893 ); 2894 } 2895 } 2896 raw_printf(pArg->out, "---------------------------\n"); 2897#endif 2898} 2899 2900/* 2901** Parameter azArray points to a zero-terminated array of strings. zStr 2902** points to a single nul-terminated string. Return non-zero if zStr 2903** is equal, according to strcmp(), to any of the strings in the array. 2904** Otherwise, return zero. 2905*/ 2906static int str_in_array(const char *zStr, const char **azArray){ 2907 int i; 2908 for(i=0; azArray[i]; i++){ 2909 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2910 } 2911 return 0; 2912} 2913 2914/* 2915** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2916** and populate the ShellState.aiIndent[] array with the number of 2917** spaces each opcode should be indented before it is output. 2918** 2919** The indenting rules are: 2920** 2921** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2922** all opcodes that occur between the p2 jump destination and the opcode 2923** itself by 2 spaces. 2924** 2925** * For each "Goto", if the jump destination is earlier in the program 2926** and ends on one of: 2927** Yield SeekGt SeekLt RowSetRead Rewind 2928** or if the P1 parameter is one instead of zero, 2929** then indent all opcodes between the earlier instruction 2930** and "Goto" by 2 spaces. 2931*/ 2932static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2933 const char *zSql; /* The text of the SQL statement */ 2934 const char *z; /* Used to check if this is an EXPLAIN */ 2935 int *abYield = 0; /* True if op is an OP_Yield */ 2936 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2937 int iOp; /* Index of operation in p->aiIndent[] */ 2938 2939 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2940 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2941 "Rewind", 0 }; 2942 const char *azGoto[] = { "Goto", 0 }; 2943 2944 /* Try to figure out if this is really an EXPLAIN statement. If this 2945 ** cannot be verified, return early. */ 2946 if( sqlite3_column_count(pSql)!=8 ){ 2947 p->cMode = p->mode; 2948 return; 2949 } 2950 zSql = sqlite3_sql(pSql); 2951 if( zSql==0 ) return; 2952 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2953 if( sqlite3_strnicmp(z, "explain", 7) ){ 2954 p->cMode = p->mode; 2955 return; 2956 } 2957 2958 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2959 int i; 2960 int iAddr = sqlite3_column_int(pSql, 0); 2961 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2962 2963 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2964 ** p2 is an instruction address, set variable p2op to the index of that 2965 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2966 ** the current instruction is part of a sub-program generated by an 2967 ** SQL trigger or foreign key. */ 2968 int p2 = sqlite3_column_int(pSql, 3); 2969 int p2op = (p2 + (iOp-iAddr)); 2970 2971 /* Grow the p->aiIndent array as required */ 2972 if( iOp>=nAlloc ){ 2973 if( iOp==0 ){ 2974 /* Do further verfication that this is explain output. Abort if 2975 ** it is not */ 2976 static const char *explainCols[] = { 2977 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2978 int jj; 2979 for(jj=0; jj<ArraySize(explainCols); jj++){ 2980 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2981 p->cMode = p->mode; 2982 sqlite3_reset(pSql); 2983 return; 2984 } 2985 } 2986 } 2987 nAlloc += 100; 2988 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2989 shell_check_oom(p->aiIndent); 2990 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2991 shell_check_oom(abYield); 2992 } 2993 abYield[iOp] = str_in_array(zOp, azYield); 2994 p->aiIndent[iOp] = 0; 2995 p->nIndent = iOp+1; 2996 2997 if( str_in_array(zOp, azNext) ){ 2998 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2999 } 3000 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 3001 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 3002 ){ 3003 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 3004 } 3005 } 3006 3007 p->iIndent = 0; 3008 sqlite3_free(abYield); 3009 sqlite3_reset(pSql); 3010} 3011 3012/* 3013** Free the array allocated by explain_data_prepare(). 3014*/ 3015static void explain_data_delete(ShellState *p){ 3016 sqlite3_free(p->aiIndent); 3017 p->aiIndent = 0; 3018 p->nIndent = 0; 3019 p->iIndent = 0; 3020} 3021 3022/* 3023** Disable and restore .wheretrace and .selecttrace settings. 3024*/ 3025static unsigned int savedSelectTrace; 3026static unsigned int savedWhereTrace; 3027static void disable_debug_trace_modes(void){ 3028 unsigned int zero = 0; 3029 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace); 3030 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero); 3031 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace); 3032 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero); 3033} 3034static void restore_debug_trace_modes(void){ 3035 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace); 3036 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace); 3037} 3038 3039/* Create the TEMP table used to store parameter bindings */ 3040static void bind_table_init(ShellState *p){ 3041 int wrSchema = 0; 3042 int defensiveMode = 0; 3043 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); 3044 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); 3045 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 3046 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 3047 sqlite3_exec(p->db, 3048 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 3049 " key TEXT PRIMARY KEY,\n" 3050 " value\n" 3051 ") WITHOUT ROWID;", 3052 0, 0, 0); 3053 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 3054 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); 3055} 3056 3057/* 3058** Bind parameters on a prepared statement. 3059** 3060** Parameter bindings are taken from a TEMP table of the form: 3061** 3062** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 3063** WITHOUT ROWID; 3064** 3065** No bindings occur if this table does not exist. The name of the table 3066** begins with "sqlite_" so that it will not collide with ordinary application 3067** tables. The table must be in the TEMP schema. 3068*/ 3069static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 3070 int nVar; 3071 int i; 3072 int rc; 3073 sqlite3_stmt *pQ = 0; 3074 3075 nVar = sqlite3_bind_parameter_count(pStmt); 3076 if( nVar==0 ) return; /* Nothing to do */ 3077 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 3078 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 3079 return; /* Parameter table does not exist */ 3080 } 3081 rc = sqlite3_prepare_v2(pArg->db, 3082 "SELECT value FROM temp.sqlite_parameters" 3083 " WHERE key=?1", -1, &pQ, 0); 3084 if( rc || pQ==0 ) return; 3085 for(i=1; i<=nVar; i++){ 3086 char zNum[30]; 3087 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 3088 if( zVar==0 ){ 3089 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 3090 zVar = zNum; 3091 } 3092 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 3093 if( sqlite3_step(pQ)==SQLITE_ROW ){ 3094 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 3095 }else{ 3096 sqlite3_bind_null(pStmt, i); 3097 } 3098 sqlite3_reset(pQ); 3099 } 3100 sqlite3_finalize(pQ); 3101} 3102 3103/* 3104** UTF8 box-drawing characters. Imagine box lines like this: 3105** 3106** 1 3107** | 3108** 4 --+-- 2 3109** | 3110** 3 3111** 3112** Each box characters has between 2 and 4 of the lines leading from 3113** the center. The characters are here identified by the numbers of 3114** their corresponding lines. 3115*/ 3116#define BOX_24 "\342\224\200" /* U+2500 --- */ 3117#define BOX_13 "\342\224\202" /* U+2502 | */ 3118#define BOX_23 "\342\224\214" /* U+250c ,- */ 3119#define BOX_34 "\342\224\220" /* U+2510 -, */ 3120#define BOX_12 "\342\224\224" /* U+2514 '- */ 3121#define BOX_14 "\342\224\230" /* U+2518 -' */ 3122#define BOX_123 "\342\224\234" /* U+251c |- */ 3123#define BOX_134 "\342\224\244" /* U+2524 -| */ 3124#define BOX_234 "\342\224\254" /* U+252c -,- */ 3125#define BOX_124 "\342\224\264" /* U+2534 -'- */ 3126#define BOX_1234 "\342\224\274" /* U+253c -|- */ 3127 3128/* Draw horizontal line N characters long using unicode box 3129** characters 3130*/ 3131static void print_box_line(FILE *out, int N){ 3132 const char zDash[] = 3133 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 3134 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24; 3135 const int nDash = sizeof(zDash) - 1; 3136 N *= 3; 3137 while( N>nDash ){ 3138 utf8_printf(out, zDash); 3139 N -= nDash; 3140 } 3141 utf8_printf(out, "%.*s", N, zDash); 3142} 3143 3144/* 3145** Draw a horizontal separator for a MODE_Box table. 3146*/ 3147static void print_box_row_separator( 3148 ShellState *p, 3149 int nArg, 3150 const char *zSep1, 3151 const char *zSep2, 3152 const char *zSep3 3153){ 3154 int i; 3155 if( nArg>0 ){ 3156 utf8_printf(p->out, "%s", zSep1); 3157 print_box_line(p->out, p->actualWidth[0]+2); 3158 for(i=1; i<nArg; i++){ 3159 utf8_printf(p->out, "%s", zSep2); 3160 print_box_line(p->out, p->actualWidth[i]+2); 3161 } 3162 utf8_printf(p->out, "%s", zSep3); 3163 } 3164 fputs("\n", p->out); 3165} 3166 3167 3168 3169/* 3170** Run a prepared statement and output the result in one of the 3171** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table, 3172** or MODE_Box. 3173** 3174** This is different from ordinary exec_prepared_stmt() in that 3175** it has to run the entire query and gather the results into memory 3176** first, in order to determine column widths, before providing 3177** any output. 3178*/ 3179static void exec_prepared_stmt_columnar( 3180 ShellState *p, /* Pointer to ShellState */ 3181 sqlite3_stmt *pStmt /* Statment to run */ 3182){ 3183 sqlite3_int64 nRow = 0; 3184 int nColumn = 0; 3185 char **azData = 0; 3186 sqlite3_int64 nAlloc = 0; 3187 const char *z; 3188 int rc; 3189 sqlite3_int64 i, nData; 3190 int j, nTotal, w, n; 3191 const char *colSep = 0; 3192 const char *rowSep = 0; 3193 3194 rc = sqlite3_step(pStmt); 3195 if( rc!=SQLITE_ROW ) return; 3196 nColumn = sqlite3_column_count(pStmt); 3197 nAlloc = nColumn*4; 3198 if( nAlloc<=0 ) nAlloc = 1; 3199 azData = sqlite3_malloc64( nAlloc*sizeof(char*) ); 3200 shell_check_oom(azData); 3201 for(i=0; i<nColumn; i++){ 3202 azData[i] = strdup(sqlite3_column_name(pStmt,i)); 3203 } 3204 do{ 3205 if( (nRow+2)*nColumn >= nAlloc ){ 3206 nAlloc *= 2; 3207 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*)); 3208 shell_check_oom(azData); 3209 } 3210 nRow++; 3211 for(i=0; i<nColumn; i++){ 3212 z = (const char*)sqlite3_column_text(pStmt,i); 3213 azData[nRow*nColumn + i] = z ? strdup(z) : 0; 3214 } 3215 }while( sqlite3_step(pStmt)==SQLITE_ROW ); 3216 if( nColumn>p->nWidth ){ 3217 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); 3218 shell_check_oom(p->colWidth); 3219 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; 3220 p->nWidth = nColumn; 3221 p->actualWidth = &p->colWidth[nColumn]; 3222 } 3223 memset(p->actualWidth, 0, nColumn*sizeof(int)); 3224 for(i=0; i<nColumn; i++){ 3225 w = p->colWidth[i]; 3226 if( w<0 ) w = -w; 3227 p->actualWidth[i] = w; 3228 } 3229 nTotal = nColumn*(nRow+1); 3230 for(i=0; i<nTotal; i++){ 3231 z = azData[i]; 3232 if( z==0 ) z = p->nullValue; 3233 n = strlenChar(z); 3234 j = i%nColumn; 3235 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; 3236 } 3237 if( seenInterrupt ) goto columnar_end; 3238 if( nColumn==0 ) goto columnar_end; 3239 switch( p->cMode ){ 3240 case MODE_Column: { 3241 colSep = " "; 3242 rowSep = "\n"; 3243 if( p->showHeader ){ 3244 for(i=0; i<nColumn; i++){ 3245 w = p->actualWidth[i]; 3246 if( p->colWidth[i]<0 ) w = -w; 3247 utf8_width_print(p->out, w, azData[i]); 3248 fputs(i==nColumn-1?"\n":" ", p->out); 3249 } 3250 for(i=0; i<nColumn; i++){ 3251 print_dashes(p->out, p->actualWidth[i]); 3252 fputs(i==nColumn-1?"\n":" ", p->out); 3253 } 3254 } 3255 break; 3256 } 3257 case MODE_Table: { 3258 colSep = " | "; 3259 rowSep = " |\n"; 3260 print_row_separator(p, nColumn, "+"); 3261 fputs("| ", p->out); 3262 for(i=0; i<nColumn; i++){ 3263 w = p->actualWidth[i]; 3264 n = strlenChar(azData[i]); 3265 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3266 fputs(i==nColumn-1?" |\n":" | ", p->out); 3267 } 3268 print_row_separator(p, nColumn, "+"); 3269 break; 3270 } 3271 case MODE_Markdown: { 3272 colSep = " | "; 3273 rowSep = " |\n"; 3274 fputs("| ", p->out); 3275 for(i=0; i<nColumn; i++){ 3276 w = p->actualWidth[i]; 3277 n = strlenChar(azData[i]); 3278 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3279 fputs(i==nColumn-1?" |\n":" | ", p->out); 3280 } 3281 print_row_separator(p, nColumn, "|"); 3282 break; 3283 } 3284 case MODE_Box: { 3285 colSep = " " BOX_13 " "; 3286 rowSep = " " BOX_13 "\n"; 3287 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34); 3288 utf8_printf(p->out, BOX_13 " "); 3289 for(i=0; i<nColumn; i++){ 3290 w = p->actualWidth[i]; 3291 n = strlenChar(azData[i]); 3292 utf8_printf(p->out, "%*s%s%*s%s", 3293 (w-n)/2, "", azData[i], (w-n+1)/2, "", 3294 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); 3295 } 3296 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); 3297 break; 3298 } 3299 } 3300 for(i=nColumn, j=0; i<nTotal; i++, j++){ 3301 if( j==0 && p->cMode!=MODE_Column ){ 3302 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| "); 3303 } 3304 z = azData[i]; 3305 if( z==0 ) z = p->nullValue; 3306 w = p->actualWidth[j]; 3307 if( p->colWidth[j]<0 ) w = -w; 3308 utf8_width_print(p->out, w, z); 3309 if( j==nColumn-1 ){ 3310 utf8_printf(p->out, "%s", rowSep); 3311 j = -1; 3312 if( seenInterrupt ) goto columnar_end; 3313 }else{ 3314 utf8_printf(p->out, "%s", colSep); 3315 } 3316 } 3317 if( p->cMode==MODE_Table ){ 3318 print_row_separator(p, nColumn, "+"); 3319 }else if( p->cMode==MODE_Box ){ 3320 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14); 3321 } 3322columnar_end: 3323 if( seenInterrupt ){ 3324 utf8_printf(p->out, "Interrupt\n"); 3325 } 3326 nData = (nRow+1)*nColumn; 3327 for(i=0; i<nData; i++) free(azData[i]); 3328 sqlite3_free(azData); 3329} 3330 3331/* 3332** Run a prepared statement 3333*/ 3334static void exec_prepared_stmt( 3335 ShellState *pArg, /* Pointer to ShellState */ 3336 sqlite3_stmt *pStmt /* Statment to run */ 3337){ 3338 int rc; 3339 sqlite3_uint64 nRow = 0; 3340 3341 if( pArg->cMode==MODE_Column 3342 || pArg->cMode==MODE_Table 3343 || pArg->cMode==MODE_Box 3344 || pArg->cMode==MODE_Markdown 3345 ){ 3346 exec_prepared_stmt_columnar(pArg, pStmt); 3347 return; 3348 } 3349 3350 /* perform the first step. this will tell us if we 3351 ** have a result set or not and how wide it is. 3352 */ 3353 rc = sqlite3_step(pStmt); 3354 /* if we have a result set... */ 3355 if( SQLITE_ROW == rc ){ 3356 /* allocate space for col name ptr, value ptr, and type */ 3357 int nCol = sqlite3_column_count(pStmt); 3358 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 3359 if( !pData ){ 3360 shell_out_of_memory(); 3361 }else{ 3362 char **azCols = (char **)pData; /* Names of result columns */ 3363 char **azVals = &azCols[nCol]; /* Results */ 3364 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 3365 int i, x; 3366 assert(sizeof(int) <= sizeof(char *)); 3367 /* save off ptrs to column names */ 3368 for(i=0; i<nCol; i++){ 3369 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 3370 } 3371 do{ 3372 nRow++; 3373 /* extract the data and data types */ 3374 for(i=0; i<nCol; i++){ 3375 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 3376 if( x==SQLITE_BLOB 3377 && pArg 3378 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote) 3379 ){ 3380 azVals[i] = ""; 3381 }else{ 3382 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 3383 } 3384 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 3385 rc = SQLITE_NOMEM; 3386 break; /* from for */ 3387 } 3388 } /* end for */ 3389 3390 /* if data and types extracted successfully... */ 3391 if( SQLITE_ROW == rc ){ 3392 /* call the supplied callback with the result row data */ 3393 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 3394 rc = SQLITE_ABORT; 3395 }else{ 3396 rc = sqlite3_step(pStmt); 3397 } 3398 } 3399 } while( SQLITE_ROW == rc ); 3400 sqlite3_free(pData); 3401 if( pArg->cMode==MODE_Json ){ 3402 fputs("]\n", pArg->out); 3403 }else if( pArg->cMode==MODE_Count ){ 3404 char zBuf[200]; 3405 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n", 3406 nRow, nRow!=1 ? "s" : ""); 3407 printf("%s", zBuf); 3408 } 3409 } 3410 } 3411} 3412 3413#ifndef SQLITE_OMIT_VIRTUALTABLE 3414/* 3415** This function is called to process SQL if the previous shell command 3416** was ".expert". It passes the SQL in the second argument directly to 3417** the sqlite3expert object. 3418** 3419** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3420** code. In this case, (*pzErr) may be set to point to a buffer containing 3421** an English language error message. It is the responsibility of the 3422** caller to eventually free this buffer using sqlite3_free(). 3423*/ 3424static int expertHandleSQL( 3425 ShellState *pState, 3426 const char *zSql, 3427 char **pzErr 3428){ 3429 assert( pState->expert.pExpert ); 3430 assert( pzErr==0 || *pzErr==0 ); 3431 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 3432} 3433 3434/* 3435** This function is called either to silently clean up the object 3436** created by the ".expert" command (if bCancel==1), or to generate a 3437** report from it and then clean it up (if bCancel==0). 3438** 3439** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3440** code. In this case, (*pzErr) may be set to point to a buffer containing 3441** an English language error message. It is the responsibility of the 3442** caller to eventually free this buffer using sqlite3_free(). 3443*/ 3444static int expertFinish( 3445 ShellState *pState, 3446 int bCancel, 3447 char **pzErr 3448){ 3449 int rc = SQLITE_OK; 3450 sqlite3expert *p = pState->expert.pExpert; 3451 assert( p ); 3452 assert( bCancel || pzErr==0 || *pzErr==0 ); 3453 if( bCancel==0 ){ 3454 FILE *out = pState->out; 3455 int bVerbose = pState->expert.bVerbose; 3456 3457 rc = sqlite3_expert_analyze(p, pzErr); 3458 if( rc==SQLITE_OK ){ 3459 int nQuery = sqlite3_expert_count(p); 3460 int i; 3461 3462 if( bVerbose ){ 3463 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 3464 raw_printf(out, "-- Candidates -----------------------------\n"); 3465 raw_printf(out, "%s\n", zCand); 3466 } 3467 for(i=0; i<nQuery; i++){ 3468 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 3469 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 3470 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 3471 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 3472 if( bVerbose ){ 3473 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 3474 raw_printf(out, "%s\n\n", zSql); 3475 } 3476 raw_printf(out, "%s\n", zIdx); 3477 raw_printf(out, "%s\n", zEQP); 3478 } 3479 } 3480 } 3481 sqlite3_expert_destroy(p); 3482 pState->expert.pExpert = 0; 3483 return rc; 3484} 3485 3486/* 3487** Implementation of ".expert" dot command. 3488*/ 3489static int expertDotCommand( 3490 ShellState *pState, /* Current shell tool state */ 3491 char **azArg, /* Array of arguments passed to dot command */ 3492 int nArg /* Number of entries in azArg[] */ 3493){ 3494 int rc = SQLITE_OK; 3495 char *zErr = 0; 3496 int i; 3497 int iSample = 0; 3498 3499 assert( pState->expert.pExpert==0 ); 3500 memset(&pState->expert, 0, sizeof(ExpertInfo)); 3501 3502 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 3503 char *z = azArg[i]; 3504 int n; 3505 if( z[0]=='-' && z[1]=='-' ) z++; 3506 n = strlen30(z); 3507 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 3508 pState->expert.bVerbose = 1; 3509 } 3510 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 3511 if( i==(nArg-1) ){ 3512 raw_printf(stderr, "option requires an argument: %s\n", z); 3513 rc = SQLITE_ERROR; 3514 }else{ 3515 iSample = (int)integerValue(azArg[++i]); 3516 if( iSample<0 || iSample>100 ){ 3517 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 3518 rc = SQLITE_ERROR; 3519 } 3520 } 3521 } 3522 else{ 3523 raw_printf(stderr, "unknown option: %s\n", z); 3524 rc = SQLITE_ERROR; 3525 } 3526 } 3527 3528 if( rc==SQLITE_OK ){ 3529 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 3530 if( pState->expert.pExpert==0 ){ 3531 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory"); 3532 rc = SQLITE_ERROR; 3533 }else{ 3534 sqlite3_expert_config( 3535 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 3536 ); 3537 } 3538 } 3539 sqlite3_free(zErr); 3540 3541 return rc; 3542} 3543#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3544 3545/* 3546** Execute a statement or set of statements. Print 3547** any result rows/columns depending on the current mode 3548** set via the supplied callback. 3549** 3550** This is very similar to SQLite's built-in sqlite3_exec() 3551** function except it takes a slightly different callback 3552** and callback data argument. 3553*/ 3554static int shell_exec( 3555 ShellState *pArg, /* Pointer to ShellState */ 3556 const char *zSql, /* SQL to be evaluated */ 3557 char **pzErrMsg /* Error msg written here */ 3558){ 3559 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3560 int rc = SQLITE_OK; /* Return Code */ 3561 int rc2; 3562 const char *zLeftover; /* Tail of unprocessed SQL */ 3563 sqlite3 *db = pArg->db; 3564 3565 if( pzErrMsg ){ 3566 *pzErrMsg = NULL; 3567 } 3568 3569#ifndef SQLITE_OMIT_VIRTUALTABLE 3570 if( pArg->expert.pExpert ){ 3571 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3572 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3573 } 3574#endif 3575 3576 while( zSql[0] && (SQLITE_OK == rc) ){ 3577 static const char *zStmtSql; 3578 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3579 if( SQLITE_OK != rc ){ 3580 if( pzErrMsg ){ 3581 *pzErrMsg = save_err_msg(db, "in prepare, %s (%d)%s", rc, zSql); 3582 } 3583 }else{ 3584 if( !pStmt ){ 3585 /* this happens for a comment or white-space */ 3586 zSql = zLeftover; 3587 while( IsSpace(zSql[0]) ) zSql++; 3588 continue; 3589 } 3590 zStmtSql = sqlite3_sql(pStmt); 3591 if( zStmtSql==0 ) zStmtSql = ""; 3592 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3593 3594 /* save off the prepared statment handle and reset row count */ 3595 if( pArg ){ 3596 pArg->pStmt = pStmt; 3597 pArg->cnt = 0; 3598 } 3599 3600 /* echo the sql statement if echo on */ 3601 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3602 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3603 } 3604 3605 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3606 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3607 sqlite3_stmt *pExplain; 3608 char *zEQP; 3609 int triggerEQP = 0; 3610 disable_debug_trace_modes(); 3611 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3612 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3613 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3614 } 3615 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3616 shell_check_oom(zEQP); 3617 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3618 if( rc==SQLITE_OK ){ 3619 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3620 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3621 int iEqpId = sqlite3_column_int(pExplain, 0); 3622 int iParentId = sqlite3_column_int(pExplain, 1); 3623 if( zEQPLine==0 ) zEQPLine = ""; 3624 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3625 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3626 } 3627 eqp_render(pArg); 3628 } 3629 sqlite3_finalize(pExplain); 3630 sqlite3_free(zEQP); 3631 if( pArg->autoEQP>=AUTOEQP_full ){ 3632 /* Also do an EXPLAIN for ".eqp full" mode */ 3633 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3634 shell_check_oom(zEQP); 3635 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3636 if( rc==SQLITE_OK ){ 3637 pArg->cMode = MODE_Explain; 3638 explain_data_prepare(pArg, pExplain); 3639 exec_prepared_stmt(pArg, pExplain); 3640 explain_data_delete(pArg); 3641 } 3642 sqlite3_finalize(pExplain); 3643 sqlite3_free(zEQP); 3644 } 3645 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3646 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3647 /* Reprepare pStmt before reactiving trace modes */ 3648 sqlite3_finalize(pStmt); 3649 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3650 if( pArg ) pArg->pStmt = pStmt; 3651 } 3652 restore_debug_trace_modes(); 3653 } 3654 3655 if( pArg ){ 3656 pArg->cMode = pArg->mode; 3657 if( pArg->autoExplain ){ 3658 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3659 pArg->cMode = MODE_Explain; 3660 } 3661 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3662 pArg->cMode = MODE_EQP; 3663 } 3664 } 3665 3666 /* If the shell is currently in ".explain" mode, gather the extra 3667 ** data required to add indents to the output.*/ 3668 if( pArg->cMode==MODE_Explain ){ 3669 explain_data_prepare(pArg, pStmt); 3670 } 3671 } 3672 3673 bind_prepared_stmt(pArg, pStmt); 3674 exec_prepared_stmt(pArg, pStmt); 3675 explain_data_delete(pArg); 3676 eqp_render(pArg); 3677 3678 /* print usage stats if stats on */ 3679 if( pArg && pArg->statsOn ){ 3680 display_stats(db, pArg, 0); 3681 } 3682 3683 /* print loop-counters if required */ 3684 if( pArg && pArg->scanstatsOn ){ 3685 display_scanstats(db, pArg); 3686 } 3687 3688 /* Finalize the statement just executed. If this fails, save a 3689 ** copy of the error message. Otherwise, set zSql to point to the 3690 ** next statement to execute. */ 3691 rc2 = sqlite3_finalize(pStmt); 3692 if( rc!=SQLITE_NOMEM ) rc = rc2; 3693 if( rc==SQLITE_OK ){ 3694 zSql = zLeftover; 3695 while( IsSpace(zSql[0]) ) zSql++; 3696 }else if( pzErrMsg ){ 3697 *pzErrMsg = save_err_msg(db, "stepping, %s (%d)", rc, 0); 3698 } 3699 3700 /* clear saved stmt handle */ 3701 if( pArg ){ 3702 pArg->pStmt = NULL; 3703 } 3704 } 3705 } /* end while */ 3706 3707 return rc; 3708} 3709 3710/* 3711** Release memory previously allocated by tableColumnList(). 3712*/ 3713static void freeColumnList(char **azCol){ 3714 int i; 3715 for(i=1; azCol[i]; i++){ 3716 sqlite3_free(azCol[i]); 3717 } 3718 /* azCol[0] is a static string */ 3719 sqlite3_free(azCol); 3720} 3721 3722/* 3723** Return a list of pointers to strings which are the names of all 3724** columns in table zTab. The memory to hold the names is dynamically 3725** allocated and must be released by the caller using a subsequent call 3726** to freeColumnList(). 3727** 3728** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3729** value that needs to be preserved, then azCol[0] is filled in with the 3730** name of the rowid column. 3731** 3732** The first regular column in the table is azCol[1]. The list is terminated 3733** by an entry with azCol[i]==0. 3734*/ 3735static char **tableColumnList(ShellState *p, const char *zTab){ 3736 char **azCol = 0; 3737 sqlite3_stmt *pStmt; 3738 char *zSql; 3739 int nCol = 0; 3740 int nAlloc = 0; 3741 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3742 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3743 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3744 int rc; 3745 3746 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3747 shell_check_oom(zSql); 3748 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3749 sqlite3_free(zSql); 3750 if( rc ) return 0; 3751 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3752 if( nCol>=nAlloc-2 ){ 3753 nAlloc = nAlloc*2 + nCol + 10; 3754 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3755 shell_check_oom(azCol); 3756 } 3757 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3758 shell_check_oom(azCol[nCol]); 3759 if( sqlite3_column_int(pStmt, 5) ){ 3760 nPK++; 3761 if( nPK==1 3762 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3763 "INTEGER")==0 3764 ){ 3765 isIPK = 1; 3766 }else{ 3767 isIPK = 0; 3768 } 3769 } 3770 } 3771 sqlite3_finalize(pStmt); 3772 if( azCol==0 ) return 0; 3773 azCol[0] = 0; 3774 azCol[nCol+1] = 0; 3775 3776 /* The decision of whether or not a rowid really needs to be preserved 3777 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3778 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3779 ** rowids on tables where the rowid is inaccessible because there are other 3780 ** columns in the table named "rowid", "_rowid_", and "oid". 3781 */ 3782 if( preserveRowid && isIPK ){ 3783 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3784 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3785 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3786 ** ROWID aliases. To distinguish these cases, check to see if 3787 ** there is a "pk" entry in "PRAGMA index_list". There will be 3788 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3789 */ 3790 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3791 " WHERE origin='pk'", zTab); 3792 shell_check_oom(zSql); 3793 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3794 sqlite3_free(zSql); 3795 if( rc ){ 3796 freeColumnList(azCol); 3797 return 0; 3798 } 3799 rc = sqlite3_step(pStmt); 3800 sqlite3_finalize(pStmt); 3801 preserveRowid = rc==SQLITE_ROW; 3802 } 3803 if( preserveRowid ){ 3804 /* Only preserve the rowid if we can find a name to use for the 3805 ** rowid */ 3806 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3807 int i, j; 3808 for(j=0; j<3; j++){ 3809 for(i=1; i<=nCol; i++){ 3810 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3811 } 3812 if( i>nCol ){ 3813 /* At this point, we know that azRowid[j] is not the name of any 3814 ** ordinary column in the table. Verify that azRowid[j] is a valid 3815 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3816 ** tables will fail this last check */ 3817 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3818 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3819 break; 3820 } 3821 } 3822 } 3823 return azCol; 3824} 3825 3826/* 3827** Toggle the reverse_unordered_selects setting. 3828*/ 3829static void toggleSelectOrder(sqlite3 *db){ 3830 sqlite3_stmt *pStmt = 0; 3831 int iSetting = 0; 3832 char zStmt[100]; 3833 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3834 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3835 iSetting = sqlite3_column_int(pStmt, 0); 3836 } 3837 sqlite3_finalize(pStmt); 3838 sqlite3_snprintf(sizeof(zStmt), zStmt, 3839 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3840 sqlite3_exec(db, zStmt, 0, 0, 0); 3841} 3842 3843/* 3844** This is a different callback routine used for dumping the database. 3845** Each row received by this callback consists of a table name, 3846** the table type ("index" or "table") and SQL to create the table. 3847** This routine should print text sufficient to recreate the table. 3848*/ 3849static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3850 int rc; 3851 const char *zTable; 3852 const char *zType; 3853 const char *zSql; 3854 ShellState *p = (ShellState *)pArg; 3855 int dataOnly; 3856 int noSys; 3857 3858 UNUSED_PARAMETER(azNotUsed); 3859 if( nArg!=3 || azArg==0 ) return 0; 3860 zTable = azArg[0]; 3861 zType = azArg[1]; 3862 zSql = azArg[2]; 3863 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; 3864 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; 3865 3866 if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){ 3867 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3868 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){ 3869 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 3870 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3871 return 0; 3872 }else if( dataOnly ){ 3873 /* no-op */ 3874 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3875 char *zIns; 3876 if( !p->writableSchema ){ 3877 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3878 p->writableSchema = 1; 3879 } 3880 zIns = sqlite3_mprintf( 3881 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" 3882 "VALUES('table','%q','%q',0,'%q');", 3883 zTable, zTable, zSql); 3884 shell_check_oom(zIns); 3885 utf8_printf(p->out, "%s\n", zIns); 3886 sqlite3_free(zIns); 3887 return 0; 3888 }else{ 3889 printSchemaLine(p->out, zSql, ";\n"); 3890 } 3891 3892 if( strcmp(zType, "table")==0 ){ 3893 ShellText sSelect; 3894 ShellText sTable; 3895 char **azCol; 3896 int i; 3897 char *savedDestTable; 3898 int savedMode; 3899 3900 azCol = tableColumnList(p, zTable); 3901 if( azCol==0 ){ 3902 p->nErr++; 3903 return 0; 3904 } 3905 3906 /* Always quote the table name, even if it appears to be pure ascii, 3907 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3908 initText(&sTable); 3909 appendText(&sTable, zTable, quoteChar(zTable)); 3910 /* If preserving the rowid, add a column list after the table name. 3911 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3912 ** instead of the usual "INSERT INTO tab VALUES(...)". 3913 */ 3914 if( azCol[0] ){ 3915 appendText(&sTable, "(", 0); 3916 appendText(&sTable, azCol[0], 0); 3917 for(i=1; azCol[i]; i++){ 3918 appendText(&sTable, ",", 0); 3919 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3920 } 3921 appendText(&sTable, ")", 0); 3922 } 3923 3924 /* Build an appropriate SELECT statement */ 3925 initText(&sSelect); 3926 appendText(&sSelect, "SELECT ", 0); 3927 if( azCol[0] ){ 3928 appendText(&sSelect, azCol[0], 0); 3929 appendText(&sSelect, ",", 0); 3930 } 3931 for(i=1; azCol[i]; i++){ 3932 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3933 if( azCol[i+1] ){ 3934 appendText(&sSelect, ",", 0); 3935 } 3936 } 3937 freeColumnList(azCol); 3938 appendText(&sSelect, " FROM ", 0); 3939 appendText(&sSelect, zTable, quoteChar(zTable)); 3940 3941 savedDestTable = p->zDestTable; 3942 savedMode = p->mode; 3943 p->zDestTable = sTable.z; 3944 p->mode = p->cMode = MODE_Insert; 3945 rc = shell_exec(p, sSelect.z, 0); 3946 if( (rc&0xff)==SQLITE_CORRUPT ){ 3947 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3948 toggleSelectOrder(p->db); 3949 shell_exec(p, sSelect.z, 0); 3950 toggleSelectOrder(p->db); 3951 } 3952 p->zDestTable = savedDestTable; 3953 p->mode = savedMode; 3954 freeText(&sTable); 3955 freeText(&sSelect); 3956 if( rc ) p->nErr++; 3957 } 3958 return 0; 3959} 3960 3961/* 3962** Run zQuery. Use dump_callback() as the callback routine so that 3963** the contents of the query are output as SQL statements. 3964** 3965** If we get a SQLITE_CORRUPT error, rerun the query after appending 3966** "ORDER BY rowid DESC" to the end. 3967*/ 3968static int run_schema_dump_query( 3969 ShellState *p, 3970 const char *zQuery 3971){ 3972 int rc; 3973 char *zErr = 0; 3974 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3975 if( rc==SQLITE_CORRUPT ){ 3976 char *zQ2; 3977 int len = strlen30(zQuery); 3978 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3979 if( zErr ){ 3980 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3981 sqlite3_free(zErr); 3982 zErr = 0; 3983 } 3984 zQ2 = malloc( len+100 ); 3985 if( zQ2==0 ) return rc; 3986 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3987 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3988 if( rc ){ 3989 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3990 }else{ 3991 rc = SQLITE_CORRUPT; 3992 } 3993 sqlite3_free(zErr); 3994 free(zQ2); 3995 } 3996 return rc; 3997} 3998 3999/* 4000** Text of help messages. 4001** 4002** The help text for each individual command begins with a line that starts 4003** with ".". Subsequent lines are supplimental information. 4004** 4005** There must be two or more spaces between the end of the command and the 4006** start of the description of what that command does. 4007*/ 4008static const char *(azHelp[]) = { 4009#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 4010 ".archive ... Manage SQL archives", 4011 " Each command must have exactly one of the following options:", 4012 " -c, --create Create a new archive", 4013 " -u, --update Add or update files with changed mtime", 4014 " -i, --insert Like -u but always add even if unchanged", 4015 " -r, --remove Remove files from archive", 4016 " -t, --list List contents of archive", 4017 " -x, --extract Extract files from archive", 4018 " Optional arguments:", 4019 " -v, --verbose Print each filename as it is processed", 4020 " -f FILE, --file FILE Use archive FILE (default is current db)", 4021 " -a FILE, --append FILE Open FILE using the apndvfs VFS", 4022 " -C DIR, --directory DIR Read/extract files from directory DIR", 4023 " -g, --glob Use glob matching for names in archive", 4024 " -n, --dryrun Show the SQL that would have occurred", 4025 " Examples:", 4026 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", 4027 " .ar -tf ARCHIVE # List members of ARCHIVE", 4028 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", 4029 " See also:", 4030 " http://sqlite.org/cli.html#sqlite_archive_support", 4031#endif 4032#ifndef SQLITE_OMIT_AUTHORIZATION 4033 ".auth ON|OFF Show authorizer callbacks", 4034#endif 4035 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 4036 " --append Use the appendvfs", 4037 " --async Write to FILE without journal and fsync()", 4038 ".bail on|off Stop after hitting an error. Default OFF", 4039 ".binary on|off Turn binary output on or off. Default OFF", 4040 ".cd DIRECTORY Change the working directory to DIRECTORY", 4041 ".changes on|off Show number of rows changed by SQL", 4042 ".check GLOB Fail if output since .testcase does not match", 4043 ".clone NEWDB Clone data into NEWDB from the existing database", 4044 ".connection [close] [#] Open or close an auxiliary database connection", 4045 ".databases List names and files of attached databases", 4046 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 4047 ".dbinfo ?DB? Show status information about the database", 4048 ".dump ?OBJECTS? Render database content as SQL", 4049 " Options:", 4050 " --data-only Output only INSERT statements", 4051 " --newlines Allow unescaped newline characters in output", 4052 " --nosys Omit system tables (ex: \"sqlite_stat1\")", 4053 " --preserve-rowids Include ROWID values in the output", 4054 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump", 4055 " Additional LIKE patterns can be given in subsequent arguments", 4056 ".echo on|off Turn command echo on or off", 4057 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 4058 " Other Modes:", 4059#ifdef SQLITE_DEBUG 4060 " test Show raw EXPLAIN QUERY PLAN output", 4061 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", 4062#endif 4063 " trigger Like \"full\" but also show trigger bytecode", 4064 ".excel Display the output of next command in spreadsheet", 4065 " --bom Put a UTF8 byte-order mark on intermediate file", 4066 ".exit ?CODE? Exit this program with return-code CODE", 4067 ".expert EXPERIMENTAL. Suggest indexes for queries", 4068 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", 4069 ".filectrl CMD ... Run various sqlite3_file_control() operations", 4070 " --schema SCHEMA Use SCHEMA instead of \"main\"", 4071 " --help Show CMD details", 4072 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 4073 ".headers on|off Turn display of headers on or off", 4074 ".help ?-all? ?PATTERN? Show help text for PATTERN", 4075 ".import FILE TABLE Import data from FILE into TABLE", 4076 " Options:", 4077 " --ascii Use \\037 and \\036 as column and row separators", 4078 " --csv Use , and \\n as column and row separators", 4079 " --skip N Skip the first N rows of input", 4080 " --schema S Target table to be S.TABLE", 4081 " -v \"Verbose\" - increase auxiliary output", 4082 " Notes:", 4083 " * If TABLE does not exist, it is created. The first row of input", 4084 " determines the column names.", 4085 " * If neither --csv or --ascii are used, the input mode is derived", 4086 " from the \".mode\" output mode", 4087 " * If FILE begins with \"|\" then it is a command that generates the", 4088 " input text.", 4089#ifndef SQLITE_OMIT_TEST_CONTROL 4090 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 4091#endif 4092 ".indexes ?TABLE? Show names of indexes", 4093 " If TABLE is specified, only show indexes for", 4094 " tables matching TABLE using the LIKE operator.", 4095#ifdef SQLITE_ENABLE_IOTRACE 4096 ".iotrace FILE Enable I/O diagnostic logging to FILE", 4097#endif 4098 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 4099 ".lint OPTIONS Report potential schema issues.", 4100 " Options:", 4101 " fkey-indexes Find missing foreign key indexes", 4102#ifndef SQLITE_OMIT_LOAD_EXTENSION 4103 ".load FILE ?ENTRY? Load an extension library", 4104#endif 4105 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 4106 ".mode MODE ?TABLE? Set output mode", 4107 " MODE is one of:", 4108 " ascii Columns/rows delimited by 0x1F and 0x1E", 4109 " box Tables using unicode box-drawing characters", 4110 " csv Comma-separated values", 4111 " column Output in columns. (See .width)", 4112 " html HTML <table> code", 4113 " insert SQL insert statements for TABLE", 4114 " json Results in a JSON array", 4115 " line One value per line", 4116 " list Values delimited by \"|\"", 4117 " markdown Markdown table format", 4118 " quote Escape answers as for SQL", 4119 " table ASCII-art table", 4120 " tabs Tab-separated values", 4121 " tcl TCL list elements", 4122 ".nonce STRING Disable safe mode for one command if the nonce matches", 4123 ".nullvalue STRING Use STRING in place of NULL values", 4124 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE", 4125 " If FILE begins with '|' then open as a pipe", 4126 " --bom Put a UTF8 byte-order mark at the beginning", 4127 " -e Send output to the system text editor", 4128 " -x Send output as CSV to a spreadsheet (same as \".excel\")", 4129 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 4130 " Options:", 4131 " --append Use appendvfs to append database to the end of FILE", 4132#ifndef SQLITE_OMIT_DESERIALIZE 4133 " --deserialize Load into memory using sqlite3_deserialize()", 4134 " --hexdb Load the output of \"dbtotxt\" as an in-memory db", 4135 " --maxsize N Maximum size for --hexdb or --deserialized database", 4136#endif 4137 " --new Initialize FILE to an empty database", 4138 " --nofollow Do not follow symbolic links", 4139 " --readonly Open FILE readonly", 4140 " --zip FILE is a ZIP archive", 4141 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 4142 " If FILE begins with '|' then open it as a pipe.", 4143 " Options:", 4144 " --bom Prefix output with a UTF8 byte-order mark", 4145 " -e Send output to the system text editor", 4146 " -x Send output as CSV to a spreadsheet", 4147 ".parameter CMD ... Manage SQL parameter bindings", 4148 " clear Erase all bindings", 4149 " init Initialize the TEMP table that holds bindings", 4150 " list List the current parameter bindings", 4151 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 4152 " PARAMETER should start with one of: $ : @ ?", 4153 " unset PARAMETER Remove PARAMETER from the binding table", 4154 ".print STRING... Print literal STRING", 4155#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 4156 ".progress N Invoke progress handler after every N opcodes", 4157 " --limit N Interrupt after N progress callbacks", 4158 " --once Do no more than one progress interrupt", 4159 " --quiet|-q No output except at interrupts", 4160 " --reset Reset the count for each input and interrupt", 4161#endif 4162 ".prompt MAIN CONTINUE Replace the standard prompts", 4163 ".quit Exit this program", 4164 ".read FILE Read input from FILE or command output", 4165 " If FILE begins with \"|\", it is a command that generates the input.", 4166#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4167 ".recover Recover as much data as possible from corrupt db.", 4168 " --freelist-corrupt Assume the freelist is corrupt", 4169 " --recovery-db NAME Store recovery metadata in database file NAME", 4170 " --lost-and-found TABLE Alternative name for the lost-and-found table", 4171 " --no-rowids Do not attempt to recover rowid values", 4172 " that are not also INTEGER PRIMARY KEYs", 4173#endif 4174 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 4175 ".save FILE Write in-memory database into FILE", 4176 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 4177 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 4178 " Options:", 4179 " --indent Try to pretty-print the schema", 4180 " --nosys Omit objects whose names start with \"sqlite_\"", 4181 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 4182 " Options:", 4183 " --init Create a new SELFTEST table", 4184 " -v Verbose output", 4185 ".separator COL ?ROW? Change the column and row separators", 4186#if defined(SQLITE_ENABLE_SESSION) 4187 ".session ?NAME? CMD ... Create or control sessions", 4188 " Subcommands:", 4189 " attach TABLE Attach TABLE", 4190 " changeset FILE Write a changeset into FILE", 4191 " close Close one session", 4192 " enable ?BOOLEAN? Set or query the enable bit", 4193 " filter GLOB... Reject tables matching GLOBs", 4194 " indirect ?BOOLEAN? Mark or query the indirect status", 4195 " isempty Query whether the session is empty", 4196 " list List currently open session names", 4197 " open DB NAME Open a new session on DB", 4198 " patchset FILE Write a patchset into FILE", 4199 " If ?NAME? is omitted, the first defined session is used.", 4200#endif 4201 ".sha3sum ... Compute a SHA3 hash of database content", 4202 " Options:", 4203 " --schema Also hash the sqlite_schema table", 4204 " --sha3-224 Use the sha3-224 algorithm", 4205 " --sha3-256 Use the sha3-256 algorithm (default)", 4206 " --sha3-384 Use the sha3-384 algorithm", 4207 " --sha3-512 Use the sha3-512 algorithm", 4208 " Any other argument is a LIKE pattern for tables to hash", 4209#ifndef SQLITE_NOHAVE_SYSTEM 4210 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 4211#endif 4212 ".show Show the current values for various settings", 4213 ".stats ?ARG? Show stats or turn stats on or off", 4214 " off Turn off automatic stat display", 4215 " on Turn on automatic stat display", 4216 " stmt Show statement stats", 4217 " vmstep Show the virtual machine step count only", 4218#ifndef SQLITE_NOHAVE_SYSTEM 4219 ".system CMD ARGS... Run CMD ARGS... in a system shell", 4220#endif 4221 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 4222 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 4223 ".testctrl CMD ... Run various sqlite3_test_control() operations", 4224 " Run \".testctrl\" with no arguments for details", 4225 ".timeout MS Try opening locked tables for MS milliseconds", 4226 ".timer on|off Turn SQL timer on or off", 4227#ifndef SQLITE_OMIT_TRACE 4228 ".trace ?OPTIONS? Output each SQL statement as it is run", 4229 " FILE Send output to FILE", 4230 " stdout Send output to stdout", 4231 " stderr Send output to stderr", 4232 " off Disable tracing", 4233 " --expanded Expand query parameters", 4234#ifdef SQLITE_ENABLE_NORMALIZE 4235 " --normalized Normal the SQL statements", 4236#endif 4237 " --plain Show SQL as it is input", 4238 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 4239 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 4240 " --row Trace each row (SQLITE_TRACE_ROW)", 4241 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 4242#endif /* SQLITE_OMIT_TRACE */ 4243#ifdef SQLITE_DEBUG 4244 ".unmodule NAME ... Unregister virtual table modules", 4245 " --allexcept Unregister everything except those named", 4246#endif 4247 ".vfsinfo ?AUX? Information about the top-level VFS", 4248 ".vfslist List all available VFSes", 4249 ".vfsname ?AUX? Print the name of the VFS stack", 4250 ".width NUM1 NUM2 ... Set minimum column widths for columnar output", 4251 " Negative values right-justify", 4252}; 4253 4254/* 4255** Output help text. 4256** 4257** zPattern describes the set of commands for which help text is provided. 4258** If zPattern is NULL, then show all commands, but only give a one-line 4259** description of each. 4260** 4261** Return the number of matches. 4262*/ 4263static int showHelp(FILE *out, const char *zPattern){ 4264 int i = 0; 4265 int j = 0; 4266 int n = 0; 4267 char *zPat; 4268 if( zPattern==0 4269 || zPattern[0]=='0' 4270 || strcmp(zPattern,"-a")==0 4271 || strcmp(zPattern,"-all")==0 4272 || strcmp(zPattern,"--all")==0 4273 ){ 4274 /* Show all commands, but only one line per command */ 4275 if( zPattern==0 ) zPattern = ""; 4276 for(i=0; i<ArraySize(azHelp); i++){ 4277 if( azHelp[i][0]=='.' || zPattern[0] ){ 4278 utf8_printf(out, "%s\n", azHelp[i]); 4279 n++; 4280 } 4281 } 4282 }else{ 4283 /* Look for commands that for which zPattern is an exact prefix */ 4284 zPat = sqlite3_mprintf(".%s*", zPattern); 4285 shell_check_oom(zPat); 4286 for(i=0; i<ArraySize(azHelp); i++){ 4287 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 4288 utf8_printf(out, "%s\n", azHelp[i]); 4289 j = i+1; 4290 n++; 4291 } 4292 } 4293 sqlite3_free(zPat); 4294 if( n ){ 4295 if( n==1 ){ 4296 /* when zPattern is a prefix of exactly one command, then include the 4297 ** details of that command, which should begin at offset j */ 4298 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 4299 utf8_printf(out, "%s\n", azHelp[j]); 4300 j++; 4301 } 4302 } 4303 return n; 4304 } 4305 /* Look for commands that contain zPattern anywhere. Show the complete 4306 ** text of all commands that match. */ 4307 zPat = sqlite3_mprintf("%%%s%%", zPattern); 4308 shell_check_oom(zPat); 4309 for(i=0; i<ArraySize(azHelp); i++){ 4310 if( azHelp[i][0]=='.' ) j = i; 4311 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 4312 utf8_printf(out, "%s\n", azHelp[j]); 4313 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 4314 j++; 4315 utf8_printf(out, "%s\n", azHelp[j]); 4316 } 4317 i = j; 4318 n++; 4319 } 4320 } 4321 sqlite3_free(zPat); 4322 } 4323 return n; 4324} 4325 4326/* Forward reference */ 4327static int process_input(ShellState *p); 4328 4329/* 4330** Read the content of file zName into memory obtained from sqlite3_malloc64() 4331** and return a pointer to the buffer. The caller is responsible for freeing 4332** the memory. 4333** 4334** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 4335** read. 4336** 4337** For convenience, a nul-terminator byte is always appended to the data read 4338** from the file before the buffer is returned. This byte is not included in 4339** the final value of (*pnByte), if applicable. 4340** 4341** NULL is returned if any error is encountered. The final value of *pnByte 4342** is undefined in this case. 4343*/ 4344static char *readFile(const char *zName, int *pnByte){ 4345 FILE *in = fopen(zName, "rb"); 4346 long nIn; 4347 size_t nRead; 4348 char *pBuf; 4349 if( in==0 ) return 0; 4350 fseek(in, 0, SEEK_END); 4351 nIn = ftell(in); 4352 rewind(in); 4353 pBuf = sqlite3_malloc64( nIn+1 ); 4354 if( pBuf==0 ){ fclose(in); return 0; } 4355 nRead = fread(pBuf, nIn, 1, in); 4356 fclose(in); 4357 if( nRead!=1 ){ 4358 sqlite3_free(pBuf); 4359 return 0; 4360 } 4361 pBuf[nIn] = 0; 4362 if( pnByte ) *pnByte = nIn; 4363 return pBuf; 4364} 4365 4366#if defined(SQLITE_ENABLE_SESSION) 4367/* 4368** Close a single OpenSession object and release all of its associated 4369** resources. 4370*/ 4371static void session_close(OpenSession *pSession){ 4372 int i; 4373 sqlite3session_delete(pSession->p); 4374 sqlite3_free(pSession->zName); 4375 for(i=0; i<pSession->nFilter; i++){ 4376 sqlite3_free(pSession->azFilter[i]); 4377 } 4378 sqlite3_free(pSession->azFilter); 4379 memset(pSession, 0, sizeof(OpenSession)); 4380} 4381#endif 4382 4383/* 4384** Close all OpenSession objects and release all associated resources. 4385*/ 4386#if defined(SQLITE_ENABLE_SESSION) 4387static void session_close_all(ShellState *p, int i){ 4388 int j; 4389 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; 4390 for(j=0; j<pAuxDb->nSession; j++){ 4391 session_close(&pAuxDb->aSession[j]); 4392 } 4393 pAuxDb->nSession = 0; 4394} 4395#else 4396# define session_close_all(X,Y) 4397#endif 4398 4399/* 4400** Implementation of the xFilter function for an open session. Omit 4401** any tables named by ".session filter" but let all other table through. 4402*/ 4403#if defined(SQLITE_ENABLE_SESSION) 4404static int session_filter(void *pCtx, const char *zTab){ 4405 OpenSession *pSession = (OpenSession*)pCtx; 4406 int i; 4407 for(i=0; i<pSession->nFilter; i++){ 4408 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 4409 } 4410 return 1; 4411} 4412#endif 4413 4414/* 4415** Try to deduce the type of file for zName based on its content. Return 4416** one of the SHELL_OPEN_* constants. 4417** 4418** If the file does not exist or is empty but its name looks like a ZIP 4419** archive and the dfltZip flag is true, then assume it is a ZIP archive. 4420** Otherwise, assume an ordinary database regardless of the filename if 4421** the type cannot be determined from content. 4422*/ 4423int deduceDatabaseType(const char *zName, int dfltZip){ 4424 FILE *f = fopen(zName, "rb"); 4425 size_t n; 4426 int rc = SHELL_OPEN_UNSPEC; 4427 char zBuf[100]; 4428 if( f==0 ){ 4429 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4430 return SHELL_OPEN_ZIPFILE; 4431 }else{ 4432 return SHELL_OPEN_NORMAL; 4433 } 4434 } 4435 n = fread(zBuf, 16, 1, f); 4436 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 4437 fclose(f); 4438 return SHELL_OPEN_NORMAL; 4439 } 4440 fseek(f, -25, SEEK_END); 4441 n = fread(zBuf, 25, 1, f); 4442 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 4443 rc = SHELL_OPEN_APPENDVFS; 4444 }else{ 4445 fseek(f, -22, SEEK_END); 4446 n = fread(zBuf, 22, 1, f); 4447 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 4448 && zBuf[3]==0x06 ){ 4449 rc = SHELL_OPEN_ZIPFILE; 4450 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4451 rc = SHELL_OPEN_ZIPFILE; 4452 } 4453 } 4454 fclose(f); 4455 return rc; 4456} 4457 4458#ifndef SQLITE_OMIT_DESERIALIZE 4459/* 4460** Reconstruct an in-memory database using the output from the "dbtotxt" 4461** program. Read content from the file in p->aAuxDb[].zDbFilename. 4462** If p->aAuxDb[].zDbFilename is 0, then read from standard input. 4463*/ 4464static unsigned char *readHexDb(ShellState *p, int *pnData){ 4465 unsigned char *a = 0; 4466 int nLine; 4467 int n = 0; 4468 int pgsz = 0; 4469 int iOffset = 0; 4470 int j, k; 4471 int rc; 4472 FILE *in; 4473 const char *zDbFilename = p->pAuxDb->zDbFilename; 4474 unsigned int x[16]; 4475 char zLine[1000]; 4476 if( zDbFilename ){ 4477 in = fopen(zDbFilename, "r"); 4478 if( in==0 ){ 4479 utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename); 4480 return 0; 4481 } 4482 nLine = 0; 4483 }else{ 4484 in = p->in; 4485 nLine = p->lineno; 4486 if( in==0 ) in = stdin; 4487 } 4488 *pnData = 0; 4489 nLine++; 4490 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 4491 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 4492 if( rc!=2 ) goto readHexDb_error; 4493 if( n<0 ) goto readHexDb_error; 4494 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 4495 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 4496 a = sqlite3_malloc( n ? n : 1 ); 4497 shell_check_oom(a); 4498 memset(a, 0, n); 4499 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 4500 utf8_printf(stderr, "invalid pagesize\n"); 4501 goto readHexDb_error; 4502 } 4503 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 4504 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 4505 if( rc==2 ){ 4506 iOffset = k; 4507 continue; 4508 } 4509 if( strncmp(zLine, "| end ", 6)==0 ){ 4510 break; 4511 } 4512 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 4513 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 4514 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 4515 if( rc==17 ){ 4516 k = iOffset+j; 4517 if( k+16<=n && k>=0 ){ 4518 int ii; 4519 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 4520 } 4521 } 4522 } 4523 *pnData = n; 4524 if( in!=p->in ){ 4525 fclose(in); 4526 }else{ 4527 p->lineno = nLine; 4528 } 4529 return a; 4530 4531readHexDb_error: 4532 if( in!=p->in ){ 4533 fclose(in); 4534 }else{ 4535 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 4536 nLine++; 4537 if(strncmp(zLine, "| end ", 6)==0 ) break; 4538 } 4539 p->lineno = nLine; 4540 } 4541 sqlite3_free(a); 4542 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 4543 return 0; 4544} 4545#endif /* SQLITE_OMIT_DESERIALIZE */ 4546 4547/* 4548** Scalar function "shell_int32". The first argument to this function 4549** must be a blob. The second a non-negative integer. This function 4550** reads and returns a 32-bit big-endian integer from byte 4551** offset (4*<arg2>) of the blob. 4552*/ 4553static void shellInt32( 4554 sqlite3_context *context, 4555 int argc, 4556 sqlite3_value **argv 4557){ 4558 const unsigned char *pBlob; 4559 int nBlob; 4560 int iInt; 4561 4562 UNUSED_PARAMETER(argc); 4563 nBlob = sqlite3_value_bytes(argv[0]); 4564 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 4565 iInt = sqlite3_value_int(argv[1]); 4566 4567 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 4568 const unsigned char *a = &pBlob[iInt*4]; 4569 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 4570 + ((sqlite3_int64)a[1]<<16) 4571 + ((sqlite3_int64)a[2]<< 8) 4572 + ((sqlite3_int64)a[3]<< 0); 4573 sqlite3_result_int64(context, iVal); 4574 } 4575} 4576 4577/* 4578** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 4579** using "..." with internal double-quote characters doubled. 4580*/ 4581static void shellIdQuote( 4582 sqlite3_context *context, 4583 int argc, 4584 sqlite3_value **argv 4585){ 4586 const char *zName = (const char*)sqlite3_value_text(argv[0]); 4587 UNUSED_PARAMETER(argc); 4588 if( zName ){ 4589 char *z = sqlite3_mprintf("\"%w\"", zName); 4590 sqlite3_result_text(context, z, -1, sqlite3_free); 4591 } 4592} 4593 4594/* 4595** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X. 4596*/ 4597static void shellUSleepFunc( 4598 sqlite3_context *context, 4599 int argcUnused, 4600 sqlite3_value **argv 4601){ 4602 int sleep = sqlite3_value_int(argv[0]); 4603 (void)argcUnused; 4604 sqlite3_sleep(sleep/1000); 4605 sqlite3_result_int(context, sleep); 4606} 4607 4608/* 4609** Scalar function "shell_escape_crnl" used by the .recover command. 4610** The argument passed to this function is the output of built-in 4611** function quote(). If the first character of the input is "'", 4612** indicating that the value passed to quote() was a text value, 4613** then this function searches the input for "\n" and "\r" characters 4614** and adds a wrapper similar to the following: 4615** 4616** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4617** 4618** Or, if the first character of the input is not "'", then a copy 4619** of the input is returned. 4620*/ 4621static void shellEscapeCrnl( 4622 sqlite3_context *context, 4623 int argc, 4624 sqlite3_value **argv 4625){ 4626 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4627 UNUSED_PARAMETER(argc); 4628 if( zText && zText[0]=='\'' ){ 4629 int nText = sqlite3_value_bytes(argv[0]); 4630 int i; 4631 char zBuf1[20]; 4632 char zBuf2[20]; 4633 const char *zNL = 0; 4634 const char *zCR = 0; 4635 int nCR = 0; 4636 int nNL = 0; 4637 4638 for(i=0; zText[i]; i++){ 4639 if( zNL==0 && zText[i]=='\n' ){ 4640 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4641 nNL = (int)strlen(zNL); 4642 } 4643 if( zCR==0 && zText[i]=='\r' ){ 4644 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4645 nCR = (int)strlen(zCR); 4646 } 4647 } 4648 4649 if( zNL || zCR ){ 4650 int iOut = 0; 4651 i64 nMax = (nNL > nCR) ? nNL : nCR; 4652 i64 nAlloc = nMax * nText + (nMax+64)*2; 4653 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4654 if( zOut==0 ){ 4655 sqlite3_result_error_nomem(context); 4656 return; 4657 } 4658 4659 if( zNL && zCR ){ 4660 memcpy(&zOut[iOut], "replace(replace(", 16); 4661 iOut += 16; 4662 }else{ 4663 memcpy(&zOut[iOut], "replace(", 8); 4664 iOut += 8; 4665 } 4666 for(i=0; zText[i]; i++){ 4667 if( zText[i]=='\n' ){ 4668 memcpy(&zOut[iOut], zNL, nNL); 4669 iOut += nNL; 4670 }else if( zText[i]=='\r' ){ 4671 memcpy(&zOut[iOut], zCR, nCR); 4672 iOut += nCR; 4673 }else{ 4674 zOut[iOut] = zText[i]; 4675 iOut++; 4676 } 4677 } 4678 4679 if( zNL ){ 4680 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4681 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4682 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4683 } 4684 if( zCR ){ 4685 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4686 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4687 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4688 } 4689 4690 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4691 sqlite3_free(zOut); 4692 return; 4693 } 4694 } 4695 4696 sqlite3_result_value(context, argv[0]); 4697} 4698 4699/* Flags for open_db(). 4700** 4701** The default behavior of open_db() is to exit(1) if the database fails to 4702** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4703** but still returns without calling exit. 4704** 4705** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4706** ZIP archive if the file does not exist or is empty and its name matches 4707** the *.zip pattern. 4708*/ 4709#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4710#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4711 4712/* 4713** Make sure the database is open. If it is not, then open it. If 4714** the database fails to open, print an error message and exit. 4715*/ 4716static void open_db(ShellState *p, int openFlags){ 4717 if( p->db==0 ){ 4718 const char *zDbFilename = p->pAuxDb->zDbFilename; 4719 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4720 if( zDbFilename==0 || zDbFilename[0]==0 ){ 4721 p->openMode = SHELL_OPEN_NORMAL; 4722 }else{ 4723 p->openMode = (u8)deduceDatabaseType(zDbFilename, 4724 (openFlags & OPEN_DB_ZIPFILE)!=0); 4725 } 4726 } 4727 switch( p->openMode ){ 4728 case SHELL_OPEN_APPENDVFS: { 4729 sqlite3_open_v2(zDbFilename, &p->db, 4730 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); 4731 break; 4732 } 4733 case SHELL_OPEN_HEXDB: 4734 case SHELL_OPEN_DESERIALIZE: { 4735 sqlite3_open(0, &p->db); 4736 break; 4737 } 4738 case SHELL_OPEN_ZIPFILE: { 4739 sqlite3_open(":memory:", &p->db); 4740 break; 4741 } 4742 case SHELL_OPEN_READONLY: { 4743 sqlite3_open_v2(zDbFilename, &p->db, 4744 SQLITE_OPEN_READONLY|p->openFlags, 0); 4745 break; 4746 } 4747 case SHELL_OPEN_UNSPEC: 4748 case SHELL_OPEN_NORMAL: { 4749 sqlite3_open_v2(zDbFilename, &p->db, 4750 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); 4751 break; 4752 } 4753 } 4754 globalDb = p->db; 4755 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4756 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4757 zDbFilename, sqlite3_errmsg(p->db)); 4758 if( openFlags & OPEN_DB_KEEPALIVE ){ 4759 sqlite3_open(":memory:", &p->db); 4760 return; 4761 } 4762 exit(1); 4763 } 4764#ifndef SQLITE_OMIT_LOAD_EXTENSION 4765 sqlite3_enable_load_extension(p->db, 1); 4766#endif 4767 sqlite3_fileio_init(p->db, 0, 0); 4768 sqlite3_shathree_init(p->db, 0, 0); 4769 sqlite3_completion_init(p->db, 0, 0); 4770 sqlite3_uint_init(p->db, 0, 0); 4771 sqlite3_decimal_init(p->db, 0, 0); 4772 sqlite3_regexp_init(p->db, 0, 0); 4773 sqlite3_ieee_init(p->db, 0, 0); 4774 sqlite3_series_init(p->db, 0, 0); 4775#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4776 sqlite3_dbdata_init(p->db, 0, 0); 4777#endif 4778#ifdef SQLITE_HAVE_ZLIB 4779 sqlite3_zipfile_init(p->db, 0, 0); 4780 sqlite3_sqlar_init(p->db, 0, 0); 4781#endif 4782 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4783 shellAddSchemaName, 0, 0); 4784 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4785 shellModuleSchema, 0, 0); 4786 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4787 shellPutsFunc, 0, 0); 4788 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4789 shellEscapeCrnl, 0, 0); 4790 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4791 shellInt32, 0, 0); 4792 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 4793 shellIdQuote, 0, 0); 4794 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, 4795 shellUSleepFunc, 0, 0); 4796#ifndef SQLITE_NOHAVE_SYSTEM 4797 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4798 editFunc, 0, 0); 4799 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4800 editFunc, 0, 0); 4801#endif 4802 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4803 char *zSql = sqlite3_mprintf( 4804 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename); 4805 shell_check_oom(zSql); 4806 sqlite3_exec(p->db, zSql, 0, 0, 0); 4807 sqlite3_free(zSql); 4808 } 4809#ifndef SQLITE_OMIT_DESERIALIZE 4810 else 4811 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4812 int rc; 4813 int nData = 0; 4814 unsigned char *aData; 4815 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4816 aData = (unsigned char*)readFile(zDbFilename, &nData); 4817 }else{ 4818 aData = readHexDb(p, &nData); 4819 if( aData==0 ){ 4820 return; 4821 } 4822 } 4823 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4824 SQLITE_DESERIALIZE_RESIZEABLE | 4825 SQLITE_DESERIALIZE_FREEONCLOSE); 4826 if( rc ){ 4827 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4828 } 4829 if( p->szMax>0 ){ 4830 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4831 } 4832 } 4833#endif 4834 } 4835 if( p->bSafeModePersist && p->db!=0 ){ 4836 sqlite3_set_authorizer(p->db, safeModeAuth, p); 4837 } 4838} 4839 4840/* 4841** Attempt to close the databaes connection. Report errors. 4842*/ 4843void close_db(sqlite3 *db){ 4844 int rc = sqlite3_close(db); 4845 if( rc ){ 4846 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4847 rc, sqlite3_errmsg(db)); 4848 } 4849} 4850 4851#if HAVE_READLINE || HAVE_EDITLINE 4852/* 4853** Readline completion callbacks 4854*/ 4855static char *readline_completion_generator(const char *text, int state){ 4856 static sqlite3_stmt *pStmt = 0; 4857 char *zRet; 4858 if( state==0 ){ 4859 char *zSql; 4860 sqlite3_finalize(pStmt); 4861 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4862 " FROM completion(%Q) ORDER BY 1", text); 4863 shell_check_oom(zSql); 4864 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4865 sqlite3_free(zSql); 4866 } 4867 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4868 const char *z = (const char*)sqlite3_column_text(pStmt,0); 4869 zRet = z ? strdup(z) : 0; 4870 }else{ 4871 sqlite3_finalize(pStmt); 4872 pStmt = 0; 4873 zRet = 0; 4874 } 4875 return zRet; 4876} 4877static char **readline_completion(const char *zText, int iStart, int iEnd){ 4878 rl_attempted_completion_over = 1; 4879 return rl_completion_matches(zText, readline_completion_generator); 4880} 4881 4882#elif HAVE_LINENOISE 4883/* 4884** Linenoise completion callback 4885*/ 4886static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4887 int nLine = strlen30(zLine); 4888 int i, iStart; 4889 sqlite3_stmt *pStmt = 0; 4890 char *zSql; 4891 char zBuf[1000]; 4892 4893 if( nLine>sizeof(zBuf)-30 ) return; 4894 if( zLine[0]=='.' || zLine[0]=='#') return; 4895 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4896 if( i==nLine-1 ) return; 4897 iStart = i+1; 4898 memcpy(zBuf, zLine, iStart); 4899 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4900 " FROM completion(%Q,%Q) ORDER BY 1", 4901 &zLine[iStart], zLine); 4902 shell_check_oom(zSql); 4903 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4904 sqlite3_free(zSql); 4905 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4906 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4907 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4908 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4909 if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){ 4910 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4911 linenoiseAddCompletion(lc, zBuf); 4912 } 4913 } 4914 sqlite3_finalize(pStmt); 4915} 4916#endif 4917 4918/* 4919** Do C-language style dequoting. 4920** 4921** \a -> alarm 4922** \b -> backspace 4923** \t -> tab 4924** \n -> newline 4925** \v -> vertical tab 4926** \f -> form feed 4927** \r -> carriage return 4928** \s -> space 4929** \" -> " 4930** \' -> ' 4931** \\ -> backslash 4932** \NNN -> ascii character NNN in octal 4933*/ 4934static void resolve_backslashes(char *z){ 4935 int i, j; 4936 char c; 4937 while( *z && *z!='\\' ) z++; 4938 for(i=j=0; (c = z[i])!=0; i++, j++){ 4939 if( c=='\\' && z[i+1]!=0 ){ 4940 c = z[++i]; 4941 if( c=='a' ){ 4942 c = '\a'; 4943 }else if( c=='b' ){ 4944 c = '\b'; 4945 }else if( c=='t' ){ 4946 c = '\t'; 4947 }else if( c=='n' ){ 4948 c = '\n'; 4949 }else if( c=='v' ){ 4950 c = '\v'; 4951 }else if( c=='f' ){ 4952 c = '\f'; 4953 }else if( c=='r' ){ 4954 c = '\r'; 4955 }else if( c=='"' ){ 4956 c = '"'; 4957 }else if( c=='\'' ){ 4958 c = '\''; 4959 }else if( c=='\\' ){ 4960 c = '\\'; 4961 }else if( c>='0' && c<='7' ){ 4962 c -= '0'; 4963 if( z[i+1]>='0' && z[i+1]<='7' ){ 4964 i++; 4965 c = (c<<3) + z[i] - '0'; 4966 if( z[i+1]>='0' && z[i+1]<='7' ){ 4967 i++; 4968 c = (c<<3) + z[i] - '0'; 4969 } 4970 } 4971 } 4972 } 4973 z[j] = c; 4974 } 4975 if( j<i ) z[j] = 0; 4976} 4977 4978/* 4979** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4980** for TRUE and FALSE. Return the integer value if appropriate. 4981*/ 4982static int booleanValue(const char *zArg){ 4983 int i; 4984 if( zArg[0]=='0' && zArg[1]=='x' ){ 4985 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4986 }else{ 4987 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4988 } 4989 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4990 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4991 return 1; 4992 } 4993 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4994 return 0; 4995 } 4996 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4997 zArg); 4998 return 0; 4999} 5000 5001/* 5002** Set or clear a shell flag according to a boolean value. 5003*/ 5004static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 5005 if( booleanValue(zArg) ){ 5006 ShellSetFlag(p, mFlag); 5007 }else{ 5008 ShellClearFlag(p, mFlag); 5009 } 5010} 5011 5012/* 5013** Close an output file, assuming it is not stderr or stdout 5014*/ 5015static void output_file_close(FILE *f){ 5016 if( f && f!=stdout && f!=stderr ) fclose(f); 5017} 5018 5019/* 5020** Try to open an output file. The names "stdout" and "stderr" are 5021** recognized and do the right thing. NULL is returned if the output 5022** filename is "off". 5023*/ 5024static FILE *output_file_open(const char *zFile, int bTextMode){ 5025 FILE *f; 5026 if( strcmp(zFile,"stdout")==0 ){ 5027 f = stdout; 5028 }else if( strcmp(zFile, "stderr")==0 ){ 5029 f = stderr; 5030 }else if( strcmp(zFile, "off")==0 ){ 5031 f = 0; 5032 }else{ 5033 f = fopen(zFile, bTextMode ? "w" : "wb"); 5034 if( f==0 ){ 5035 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 5036 } 5037 } 5038 return f; 5039} 5040 5041#ifndef SQLITE_OMIT_TRACE 5042/* 5043** A routine for handling output from sqlite3_trace(). 5044*/ 5045static int sql_trace_callback( 5046 unsigned mType, /* The trace type */ 5047 void *pArg, /* The ShellState pointer */ 5048 void *pP, /* Usually a pointer to sqlite_stmt */ 5049 void *pX /* Auxiliary output */ 5050){ 5051 ShellState *p = (ShellState*)pArg; 5052 sqlite3_stmt *pStmt; 5053 const char *zSql; 5054 int nSql; 5055 if( p->traceOut==0 ) return 0; 5056 if( mType==SQLITE_TRACE_CLOSE ){ 5057 utf8_printf(p->traceOut, "-- closing database connection\n"); 5058 return 0; 5059 } 5060 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 5061 zSql = (const char*)pX; 5062 }else{ 5063 pStmt = (sqlite3_stmt*)pP; 5064 switch( p->eTraceType ){ 5065 case SHELL_TRACE_EXPANDED: { 5066 zSql = sqlite3_expanded_sql(pStmt); 5067 break; 5068 } 5069#ifdef SQLITE_ENABLE_NORMALIZE 5070 case SHELL_TRACE_NORMALIZED: { 5071 zSql = sqlite3_normalized_sql(pStmt); 5072 break; 5073 } 5074#endif 5075 default: { 5076 zSql = sqlite3_sql(pStmt); 5077 break; 5078 } 5079 } 5080 } 5081 if( zSql==0 ) return 0; 5082 nSql = strlen30(zSql); 5083 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 5084 switch( mType ){ 5085 case SQLITE_TRACE_ROW: 5086 case SQLITE_TRACE_STMT: { 5087 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 5088 break; 5089 } 5090 case SQLITE_TRACE_PROFILE: { 5091 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 5092 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 5093 break; 5094 } 5095 } 5096 return 0; 5097} 5098#endif 5099 5100/* 5101** A no-op routine that runs with the ".breakpoint" doc-command. This is 5102** a useful spot to set a debugger breakpoint. 5103*/ 5104static void test_breakpoint(void){ 5105 static int nCall = 0; 5106 nCall++; 5107} 5108 5109/* 5110** An object used to read a CSV and other files for import. 5111*/ 5112typedef struct ImportCtx ImportCtx; 5113struct ImportCtx { 5114 const char *zFile; /* Name of the input file */ 5115 FILE *in; /* Read the CSV text from this input stream */ 5116 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */ 5117 char *z; /* Accumulated text for a field */ 5118 int n; /* Number of bytes in z */ 5119 int nAlloc; /* Space allocated for z[] */ 5120 int nLine; /* Current line number */ 5121 int nRow; /* Number of rows imported */ 5122 int nErr; /* Number of errors encountered */ 5123 int bNotFirst; /* True if one or more bytes already read */ 5124 int cTerm; /* Character that terminated the most recent field */ 5125 int cColSep; /* The column separator character. (Usually ",") */ 5126 int cRowSep; /* The row separator character. (Usually "\n") */ 5127}; 5128 5129/* Clean up resourced used by an ImportCtx */ 5130static void import_cleanup(ImportCtx *p){ 5131 if( p->in!=0 && p->xCloser!=0 ){ 5132 p->xCloser(p->in); 5133 p->in = 0; 5134 } 5135 sqlite3_free(p->z); 5136 p->z = 0; 5137} 5138 5139/* Append a single byte to z[] */ 5140static void import_append_char(ImportCtx *p, int c){ 5141 if( p->n+1>=p->nAlloc ){ 5142 p->nAlloc += p->nAlloc + 100; 5143 p->z = sqlite3_realloc64(p->z, p->nAlloc); 5144 shell_check_oom(p->z); 5145 } 5146 p->z[p->n++] = (char)c; 5147} 5148 5149/* Read a single field of CSV text. Compatible with rfc4180 and extended 5150** with the option of having a separator other than ",". 5151** 5152** + Input comes from p->in. 5153** + Store results in p->z of length p->n. Space to hold p->z comes 5154** from sqlite3_malloc64(). 5155** + Use p->cSep as the column separator. The default is ",". 5156** + Use p->rSep as the row separator. The default is "\n". 5157** + Keep track of the line number in p->nLine. 5158** + Store the character that terminates the field in p->cTerm. Store 5159** EOF on end-of-file. 5160** + Report syntax errors on stderr 5161*/ 5162static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 5163 int c; 5164 int cSep = p->cColSep; 5165 int rSep = p->cRowSep; 5166 p->n = 0; 5167 c = fgetc(p->in); 5168 if( c==EOF || seenInterrupt ){ 5169 p->cTerm = EOF; 5170 return 0; 5171 } 5172 if( c=='"' ){ 5173 int pc, ppc; 5174 int startLine = p->nLine; 5175 int cQuote = c; 5176 pc = ppc = 0; 5177 while( 1 ){ 5178 c = fgetc(p->in); 5179 if( c==rSep ) p->nLine++; 5180 if( c==cQuote ){ 5181 if( pc==cQuote ){ 5182 pc = 0; 5183 continue; 5184 } 5185 } 5186 if( (c==cSep && pc==cQuote) 5187 || (c==rSep && pc==cQuote) 5188 || (c==rSep && pc=='\r' && ppc==cQuote) 5189 || (c==EOF && pc==cQuote) 5190 ){ 5191 do{ p->n--; }while( p->z[p->n]!=cQuote ); 5192 p->cTerm = c; 5193 break; 5194 } 5195 if( pc==cQuote && c!='\r' ){ 5196 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 5197 p->zFile, p->nLine, cQuote); 5198 } 5199 if( c==EOF ){ 5200 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 5201 p->zFile, startLine, cQuote); 5202 p->cTerm = c; 5203 break; 5204 } 5205 import_append_char(p, c); 5206 ppc = pc; 5207 pc = c; 5208 } 5209 }else{ 5210 /* If this is the first field being parsed and it begins with the 5211 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 5212 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 5213 import_append_char(p, c); 5214 c = fgetc(p->in); 5215 if( (c&0xff)==0xbb ){ 5216 import_append_char(p, c); 5217 c = fgetc(p->in); 5218 if( (c&0xff)==0xbf ){ 5219 p->bNotFirst = 1; 5220 p->n = 0; 5221 return csv_read_one_field(p); 5222 } 5223 } 5224 } 5225 while( c!=EOF && c!=cSep && c!=rSep ){ 5226 import_append_char(p, c); 5227 c = fgetc(p->in); 5228 } 5229 if( c==rSep ){ 5230 p->nLine++; 5231 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 5232 } 5233 p->cTerm = c; 5234 } 5235 if( p->z ) p->z[p->n] = 0; 5236 p->bNotFirst = 1; 5237 return p->z; 5238} 5239 5240/* Read a single field of ASCII delimited text. 5241** 5242** + Input comes from p->in. 5243** + Store results in p->z of length p->n. Space to hold p->z comes 5244** from sqlite3_malloc64(). 5245** + Use p->cSep as the column separator. The default is "\x1F". 5246** + Use p->rSep as the row separator. The default is "\x1E". 5247** + Keep track of the row number in p->nLine. 5248** + Store the character that terminates the field in p->cTerm. Store 5249** EOF on end-of-file. 5250** + Report syntax errors on stderr 5251*/ 5252static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 5253 int c; 5254 int cSep = p->cColSep; 5255 int rSep = p->cRowSep; 5256 p->n = 0; 5257 c = fgetc(p->in); 5258 if( c==EOF || seenInterrupt ){ 5259 p->cTerm = EOF; 5260 return 0; 5261 } 5262 while( c!=EOF && c!=cSep && c!=rSep ){ 5263 import_append_char(p, c); 5264 c = fgetc(p->in); 5265 } 5266 if( c==rSep ){ 5267 p->nLine++; 5268 } 5269 p->cTerm = c; 5270 if( p->z ) p->z[p->n] = 0; 5271 return p->z; 5272} 5273 5274/* 5275** Try to transfer data for table zTable. If an error is seen while 5276** moving forward, try to go backwards. The backwards movement won't 5277** work for WITHOUT ROWID tables. 5278*/ 5279static void tryToCloneData( 5280 ShellState *p, 5281 sqlite3 *newDb, 5282 const char *zTable 5283){ 5284 sqlite3_stmt *pQuery = 0; 5285 sqlite3_stmt *pInsert = 0; 5286 char *zQuery = 0; 5287 char *zInsert = 0; 5288 int rc; 5289 int i, j, n; 5290 int nTable = strlen30(zTable); 5291 int k = 0; 5292 int cnt = 0; 5293 const int spinRate = 10000; 5294 5295 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 5296 shell_check_oom(zQuery); 5297 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5298 if( rc ){ 5299 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5300 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5301 zQuery); 5302 goto end_data_xfer; 5303 } 5304 n = sqlite3_column_count(pQuery); 5305 zInsert = sqlite3_malloc64(200 + nTable + n*3); 5306 shell_check_oom(zInsert); 5307 sqlite3_snprintf(200+nTable,zInsert, 5308 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 5309 i = strlen30(zInsert); 5310 for(j=1; j<n; j++){ 5311 memcpy(zInsert+i, ",?", 2); 5312 i += 2; 5313 } 5314 memcpy(zInsert+i, ");", 3); 5315 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 5316 if( rc ){ 5317 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5318 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 5319 zQuery); 5320 goto end_data_xfer; 5321 } 5322 for(k=0; k<2; k++){ 5323 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5324 for(i=0; i<n; i++){ 5325 switch( sqlite3_column_type(pQuery, i) ){ 5326 case SQLITE_NULL: { 5327 sqlite3_bind_null(pInsert, i+1); 5328 break; 5329 } 5330 case SQLITE_INTEGER: { 5331 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 5332 break; 5333 } 5334 case SQLITE_FLOAT: { 5335 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 5336 break; 5337 } 5338 case SQLITE_TEXT: { 5339 sqlite3_bind_text(pInsert, i+1, 5340 (const char*)sqlite3_column_text(pQuery,i), 5341 -1, SQLITE_STATIC); 5342 break; 5343 } 5344 case SQLITE_BLOB: { 5345 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 5346 sqlite3_column_bytes(pQuery,i), 5347 SQLITE_STATIC); 5348 break; 5349 } 5350 } 5351 } /* End for */ 5352 rc = sqlite3_step(pInsert); 5353 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 5354 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 5355 sqlite3_errmsg(newDb)); 5356 } 5357 sqlite3_reset(pInsert); 5358 cnt++; 5359 if( (cnt%spinRate)==0 ){ 5360 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 5361 fflush(stdout); 5362 } 5363 } /* End while */ 5364 if( rc==SQLITE_DONE ) break; 5365 sqlite3_finalize(pQuery); 5366 sqlite3_free(zQuery); 5367 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 5368 zTable); 5369 shell_check_oom(zQuery); 5370 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5371 if( rc ){ 5372 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 5373 break; 5374 } 5375 } /* End for(k=0...) */ 5376 5377end_data_xfer: 5378 sqlite3_finalize(pQuery); 5379 sqlite3_finalize(pInsert); 5380 sqlite3_free(zQuery); 5381 sqlite3_free(zInsert); 5382} 5383 5384 5385/* 5386** Try to transfer all rows of the schema that match zWhere. For 5387** each row, invoke xForEach() on the object defined by that row. 5388** If an error is encountered while moving forward through the 5389** sqlite_schema table, try again moving backwards. 5390*/ 5391static void tryToCloneSchema( 5392 ShellState *p, 5393 sqlite3 *newDb, 5394 const char *zWhere, 5395 void (*xForEach)(ShellState*,sqlite3*,const char*) 5396){ 5397 sqlite3_stmt *pQuery = 0; 5398 char *zQuery = 0; 5399 int rc; 5400 const unsigned char *zName; 5401 const unsigned char *zSql; 5402 char *zErrMsg = 0; 5403 5404 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5405 " WHERE %s", zWhere); 5406 shell_check_oom(zQuery); 5407 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5408 if( rc ){ 5409 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5410 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5411 zQuery); 5412 goto end_schema_xfer; 5413 } 5414 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5415 zName = sqlite3_column_text(pQuery, 0); 5416 zSql = sqlite3_column_text(pQuery, 1); 5417 if( zName==0 || zSql==0 ) continue; 5418 printf("%s... ", zName); fflush(stdout); 5419 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5420 if( zErrMsg ){ 5421 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5422 sqlite3_free(zErrMsg); 5423 zErrMsg = 0; 5424 } 5425 if( xForEach ){ 5426 xForEach(p, newDb, (const char*)zName); 5427 } 5428 printf("done\n"); 5429 } 5430 if( rc!=SQLITE_DONE ){ 5431 sqlite3_finalize(pQuery); 5432 sqlite3_free(zQuery); 5433 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5434 " WHERE %s ORDER BY rowid DESC", zWhere); 5435 shell_check_oom(zQuery); 5436 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5437 if( rc ){ 5438 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5439 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5440 zQuery); 5441 goto end_schema_xfer; 5442 } 5443 while( sqlite3_step(pQuery)==SQLITE_ROW ){ 5444 zName = sqlite3_column_text(pQuery, 0); 5445 zSql = sqlite3_column_text(pQuery, 1); 5446 if( zName==0 || zSql==0 ) continue; 5447 printf("%s... ", zName); fflush(stdout); 5448 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5449 if( zErrMsg ){ 5450 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5451 sqlite3_free(zErrMsg); 5452 zErrMsg = 0; 5453 } 5454 if( xForEach ){ 5455 xForEach(p, newDb, (const char*)zName); 5456 } 5457 printf("done\n"); 5458 } 5459 } 5460end_schema_xfer: 5461 sqlite3_finalize(pQuery); 5462 sqlite3_free(zQuery); 5463} 5464 5465/* 5466** Open a new database file named "zNewDb". Try to recover as much information 5467** as possible out of the main database (which might be corrupt) and write it 5468** into zNewDb. 5469*/ 5470static void tryToClone(ShellState *p, const char *zNewDb){ 5471 int rc; 5472 sqlite3 *newDb = 0; 5473 if( access(zNewDb,0)==0 ){ 5474 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 5475 return; 5476 } 5477 rc = sqlite3_open(zNewDb, &newDb); 5478 if( rc ){ 5479 utf8_printf(stderr, "Cannot create output database: %s\n", 5480 sqlite3_errmsg(newDb)); 5481 }else{ 5482 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 5483 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 5484 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 5485 tryToCloneSchema(p, newDb, "type!='table'", 0); 5486 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 5487 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 5488 } 5489 close_db(newDb); 5490} 5491 5492/* 5493** Change the output file back to stdout. 5494** 5495** If the p->doXdgOpen flag is set, that means the output was being 5496** redirected to a temporary file named by p->zTempFile. In that case, 5497** launch start/open/xdg-open on that temporary file. 5498*/ 5499static void output_reset(ShellState *p){ 5500 if( p->outfile[0]=='|' ){ 5501#ifndef SQLITE_OMIT_POPEN 5502 pclose(p->out); 5503#endif 5504 }else{ 5505 output_file_close(p->out); 5506#ifndef SQLITE_NOHAVE_SYSTEM 5507 if( p->doXdgOpen ){ 5508 const char *zXdgOpenCmd = 5509#if defined(_WIN32) 5510 "start"; 5511#elif defined(__APPLE__) 5512 "open"; 5513#else 5514 "xdg-open"; 5515#endif 5516 char *zCmd; 5517 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 5518 if( system(zCmd) ){ 5519 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 5520 }else{ 5521 /* Give the start/open/xdg-open command some time to get 5522 ** going before we continue, and potential delete the 5523 ** p->zTempFile data file out from under it */ 5524 sqlite3_sleep(2000); 5525 } 5526 sqlite3_free(zCmd); 5527 outputModePop(p); 5528 p->doXdgOpen = 0; 5529 } 5530#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 5531 } 5532 p->outfile[0] = 0; 5533 p->out = stdout; 5534} 5535 5536/* 5537** Run an SQL command and return the single integer result. 5538*/ 5539static int db_int(ShellState *p, const char *zSql){ 5540 sqlite3_stmt *pStmt; 5541 int res = 0; 5542 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 5543 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 5544 res = sqlite3_column_int(pStmt,0); 5545 } 5546 sqlite3_finalize(pStmt); 5547 return res; 5548} 5549 5550/* 5551** Convert a 2-byte or 4-byte big-endian integer into a native integer 5552*/ 5553static unsigned int get2byteInt(unsigned char *a){ 5554 return (a[0]<<8) + a[1]; 5555} 5556static unsigned int get4byteInt(unsigned char *a){ 5557 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 5558} 5559 5560/* 5561** Implementation of the ".dbinfo" command. 5562** 5563** Return 1 on error, 2 to exit, and 0 otherwise. 5564*/ 5565static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 5566 static const struct { const char *zName; int ofst; } aField[] = { 5567 { "file change counter:", 24 }, 5568 { "database page count:", 28 }, 5569 { "freelist page count:", 36 }, 5570 { "schema cookie:", 40 }, 5571 { "schema format:", 44 }, 5572 { "default cache size:", 48 }, 5573 { "autovacuum top root:", 52 }, 5574 { "incremental vacuum:", 64 }, 5575 { "text encoding:", 56 }, 5576 { "user version:", 60 }, 5577 { "application id:", 68 }, 5578 { "software version:", 96 }, 5579 }; 5580 static const struct { const char *zName; const char *zSql; } aQuery[] = { 5581 { "number of tables:", 5582 "SELECT count(*) FROM %s WHERE type='table'" }, 5583 { "number of indexes:", 5584 "SELECT count(*) FROM %s WHERE type='index'" }, 5585 { "number of triggers:", 5586 "SELECT count(*) FROM %s WHERE type='trigger'" }, 5587 { "number of views:", 5588 "SELECT count(*) FROM %s WHERE type='view'" }, 5589 { "schema size:", 5590 "SELECT total(length(sql)) FROM %s" }, 5591 }; 5592 int i, rc; 5593 unsigned iDataVersion; 5594 char *zSchemaTab; 5595 char *zDb = nArg>=2 ? azArg[1] : "main"; 5596 sqlite3_stmt *pStmt = 0; 5597 unsigned char aHdr[100]; 5598 open_db(p, 0); 5599 if( p->db==0 ) return 1; 5600 rc = sqlite3_prepare_v2(p->db, 5601 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 5602 -1, &pStmt, 0); 5603 if( rc ){ 5604 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 5605 sqlite3_finalize(pStmt); 5606 return 1; 5607 } 5608 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 5609 if( sqlite3_step(pStmt)==SQLITE_ROW 5610 && sqlite3_column_bytes(pStmt,0)>100 5611 ){ 5612 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 5613 sqlite3_finalize(pStmt); 5614 }else{ 5615 raw_printf(stderr, "unable to read database header\n"); 5616 sqlite3_finalize(pStmt); 5617 return 1; 5618 } 5619 i = get2byteInt(aHdr+16); 5620 if( i==1 ) i = 65536; 5621 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 5622 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 5623 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 5624 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 5625 for(i=0; i<ArraySize(aField); i++){ 5626 int ofst = aField[i].ofst; 5627 unsigned int val = get4byteInt(aHdr + ofst); 5628 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 5629 switch( ofst ){ 5630 case 56: { 5631 if( val==1 ) raw_printf(p->out, " (utf8)"); 5632 if( val==2 ) raw_printf(p->out, " (utf16le)"); 5633 if( val==3 ) raw_printf(p->out, " (utf16be)"); 5634 } 5635 } 5636 raw_printf(p->out, "\n"); 5637 } 5638 if( zDb==0 ){ 5639 zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); 5640 }else if( strcmp(zDb,"temp")==0 ){ 5641 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); 5642 }else{ 5643 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); 5644 } 5645 for(i=0; i<ArraySize(aQuery); i++){ 5646 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 5647 int val = db_int(p, zSql); 5648 sqlite3_free(zSql); 5649 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 5650 } 5651 sqlite3_free(zSchemaTab); 5652 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 5653 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 5654 return 0; 5655} 5656 5657/* 5658** Print the current sqlite3_errmsg() value to stderr and return 1. 5659*/ 5660static int shellDatabaseError(sqlite3 *db){ 5661 const char *zErr = sqlite3_errmsg(db); 5662 utf8_printf(stderr, "Error: %s\n", zErr); 5663 return 1; 5664} 5665 5666/* 5667** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 5668** if they match and FALSE (0) if they do not match. 5669** 5670** Globbing rules: 5671** 5672** '*' Matches any sequence of zero or more characters. 5673** 5674** '?' Matches exactly one character. 5675** 5676** [...] Matches one character from the enclosed list of 5677** characters. 5678** 5679** [^...] Matches one character not in the enclosed list. 5680** 5681** '#' Matches any sequence of one or more digits with an 5682** optional + or - sign in front 5683** 5684** ' ' Any span of whitespace matches any other span of 5685** whitespace. 5686** 5687** Extra whitespace at the end of z[] is ignored. 5688*/ 5689static int testcase_glob(const char *zGlob, const char *z){ 5690 int c, c2; 5691 int invert; 5692 int seen; 5693 5694 while( (c = (*(zGlob++)))!=0 ){ 5695 if( IsSpace(c) ){ 5696 if( !IsSpace(*z) ) return 0; 5697 while( IsSpace(*zGlob) ) zGlob++; 5698 while( IsSpace(*z) ) z++; 5699 }else if( c=='*' ){ 5700 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5701 if( c=='?' && (*(z++))==0 ) return 0; 5702 } 5703 if( c==0 ){ 5704 return 1; 5705 }else if( c=='[' ){ 5706 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5707 z++; 5708 } 5709 return (*z)!=0; 5710 } 5711 while( (c2 = (*(z++)))!=0 ){ 5712 while( c2!=c ){ 5713 c2 = *(z++); 5714 if( c2==0 ) return 0; 5715 } 5716 if( testcase_glob(zGlob,z) ) return 1; 5717 } 5718 return 0; 5719 }else if( c=='?' ){ 5720 if( (*(z++))==0 ) return 0; 5721 }else if( c=='[' ){ 5722 int prior_c = 0; 5723 seen = 0; 5724 invert = 0; 5725 c = *(z++); 5726 if( c==0 ) return 0; 5727 c2 = *(zGlob++); 5728 if( c2=='^' ){ 5729 invert = 1; 5730 c2 = *(zGlob++); 5731 } 5732 if( c2==']' ){ 5733 if( c==']' ) seen = 1; 5734 c2 = *(zGlob++); 5735 } 5736 while( c2 && c2!=']' ){ 5737 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5738 c2 = *(zGlob++); 5739 if( c>=prior_c && c<=c2 ) seen = 1; 5740 prior_c = 0; 5741 }else{ 5742 if( c==c2 ){ 5743 seen = 1; 5744 } 5745 prior_c = c2; 5746 } 5747 c2 = *(zGlob++); 5748 } 5749 if( c2==0 || (seen ^ invert)==0 ) return 0; 5750 }else if( c=='#' ){ 5751 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5752 if( !IsDigit(z[0]) ) return 0; 5753 z++; 5754 while( IsDigit(z[0]) ){ z++; } 5755 }else{ 5756 if( c!=(*(z++)) ) return 0; 5757 } 5758 } 5759 while( IsSpace(*z) ){ z++; } 5760 return *z==0; 5761} 5762 5763 5764/* 5765** Compare the string as a command-line option with either one or two 5766** initial "-" characters. 5767*/ 5768static int optionMatch(const char *zStr, const char *zOpt){ 5769 if( zStr[0]!='-' ) return 0; 5770 zStr++; 5771 if( zStr[0]=='-' ) zStr++; 5772 return strcmp(zStr, zOpt)==0; 5773} 5774 5775/* 5776** Delete a file. 5777*/ 5778int shellDeleteFile(const char *zFilename){ 5779 int rc; 5780#ifdef _WIN32 5781 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5782 rc = _wunlink(z); 5783 sqlite3_free(z); 5784#else 5785 rc = unlink(zFilename); 5786#endif 5787 return rc; 5788} 5789 5790/* 5791** Try to delete the temporary file (if there is one) and free the 5792** memory used to hold the name of the temp file. 5793*/ 5794static void clearTempFile(ShellState *p){ 5795 if( p->zTempFile==0 ) return; 5796 if( p->doXdgOpen ) return; 5797 if( shellDeleteFile(p->zTempFile) ) return; 5798 sqlite3_free(p->zTempFile); 5799 p->zTempFile = 0; 5800} 5801 5802/* 5803** Create a new temp file name with the given suffix. 5804*/ 5805static void newTempFile(ShellState *p, const char *zSuffix){ 5806 clearTempFile(p); 5807 sqlite3_free(p->zTempFile); 5808 p->zTempFile = 0; 5809 if( p->db ){ 5810 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5811 } 5812 if( p->zTempFile==0 ){ 5813 /* If p->db is an in-memory database then the TEMPFILENAME file-control 5814 ** will not work and we will need to fallback to guessing */ 5815 char *zTemp; 5816 sqlite3_uint64 r; 5817 sqlite3_randomness(sizeof(r), &r); 5818 zTemp = getenv("TEMP"); 5819 if( zTemp==0 ) zTemp = getenv("TMP"); 5820 if( zTemp==0 ){ 5821#ifdef _WIN32 5822 zTemp = "\\tmp"; 5823#else 5824 zTemp = "/tmp"; 5825#endif 5826 } 5827 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); 5828 }else{ 5829 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5830 } 5831 shell_check_oom(p->zTempFile); 5832} 5833 5834 5835/* 5836** The implementation of SQL scalar function fkey_collate_clause(), used 5837** by the ".lint fkey-indexes" command. This scalar function is always 5838** called with four arguments - the parent table name, the parent column name, 5839** the child table name and the child column name. 5840** 5841** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5842** 5843** If either of the named tables or columns do not exist, this function 5844** returns an empty string. An empty string is also returned if both tables 5845** and columns exist but have the same default collation sequence. Or, 5846** if both exist but the default collation sequences are different, this 5847** function returns the string " COLLATE <parent-collation>", where 5848** <parent-collation> is the default collation sequence of the parent column. 5849*/ 5850static void shellFkeyCollateClause( 5851 sqlite3_context *pCtx, 5852 int nVal, 5853 sqlite3_value **apVal 5854){ 5855 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5856 const char *zParent; 5857 const char *zParentCol; 5858 const char *zParentSeq; 5859 const char *zChild; 5860 const char *zChildCol; 5861 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5862 int rc; 5863 5864 assert( nVal==4 ); 5865 zParent = (const char*)sqlite3_value_text(apVal[0]); 5866 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5867 zChild = (const char*)sqlite3_value_text(apVal[2]); 5868 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5869 5870 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5871 rc = sqlite3_table_column_metadata( 5872 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5873 ); 5874 if( rc==SQLITE_OK ){ 5875 rc = sqlite3_table_column_metadata( 5876 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5877 ); 5878 } 5879 5880 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5881 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5882 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5883 sqlite3_free(z); 5884 } 5885} 5886 5887 5888/* 5889** The implementation of dot-command ".lint fkey-indexes". 5890*/ 5891static int lintFkeyIndexes( 5892 ShellState *pState, /* Current shell tool state */ 5893 char **azArg, /* Array of arguments passed to dot command */ 5894 int nArg /* Number of entries in azArg[] */ 5895){ 5896 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5897 FILE *out = pState->out; /* Stream to write non-error output to */ 5898 int bVerbose = 0; /* If -verbose is present */ 5899 int bGroupByParent = 0; /* If -groupbyparent is present */ 5900 int i; /* To iterate through azArg[] */ 5901 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5902 int rc; /* Return code */ 5903 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5904 5905 /* 5906 ** This SELECT statement returns one row for each foreign key constraint 5907 ** in the schema of the main database. The column values are: 5908 ** 5909 ** 0. The text of an SQL statement similar to: 5910 ** 5911 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5912 ** 5913 ** This SELECT is similar to the one that the foreign keys implementation 5914 ** needs to run internally on child tables. If there is an index that can 5915 ** be used to optimize this query, then it can also be used by the FK 5916 ** implementation to optimize DELETE or UPDATE statements on the parent 5917 ** table. 5918 ** 5919 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5920 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5921 ** contains an index that can be used to optimize the query. 5922 ** 5923 ** 2. Human readable text that describes the child table and columns. e.g. 5924 ** 5925 ** "child_table(child_key1, child_key2)" 5926 ** 5927 ** 3. Human readable text that describes the parent table and columns. e.g. 5928 ** 5929 ** "parent_table(parent_key1, parent_key2)" 5930 ** 5931 ** 4. A full CREATE INDEX statement for an index that could be used to 5932 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5933 ** 5934 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5935 ** 5936 ** 5. The name of the parent table. 5937 ** 5938 ** These six values are used by the C logic below to generate the report. 5939 */ 5940 const char *zSql = 5941 "SELECT " 5942 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5943 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5944 " || fkey_collate_clause(" 5945 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5946 ", " 5947 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('" 5948 " || group_concat('*=?', ' AND ') || ')'" 5949 ", " 5950 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5951 ", " 5952 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5953 ", " 5954 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5955 " || ' ON ' || quote(s.name) || '('" 5956 " || group_concat(quote(f.[from]) ||" 5957 " fkey_collate_clause(" 5958 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5959 " || ');'" 5960 ", " 5961 " f.[table] " 5962 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " 5963 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5964 "GROUP BY s.name, f.id " 5965 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5966 ; 5967 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)"; 5968 5969 for(i=2; i<nArg; i++){ 5970 int n = strlen30(azArg[i]); 5971 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5972 bVerbose = 1; 5973 } 5974 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5975 bGroupByParent = 1; 5976 zIndent = " "; 5977 } 5978 else{ 5979 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5980 azArg[0], azArg[1] 5981 ); 5982 return SQLITE_ERROR; 5983 } 5984 } 5985 5986 /* Register the fkey_collate_clause() SQL function */ 5987 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5988 0, shellFkeyCollateClause, 0, 0 5989 ); 5990 5991 5992 if( rc==SQLITE_OK ){ 5993 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5994 } 5995 if( rc==SQLITE_OK ){ 5996 sqlite3_bind_int(pSql, 1, bGroupByParent); 5997 } 5998 5999 if( rc==SQLITE_OK ){ 6000 int rc2; 6001 char *zPrev = 0; 6002 while( SQLITE_ROW==sqlite3_step(pSql) ){ 6003 int res = -1; 6004 sqlite3_stmt *pExplain = 0; 6005 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 6006 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 6007 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 6008 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 6009 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 6010 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 6011 6012 if( zEQP==0 ) continue; 6013 if( zGlob==0 ) continue; 6014 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 6015 if( rc!=SQLITE_OK ) break; 6016 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 6017 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 6018 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan) 6019 || 0==sqlite3_strglob(zGlobIPK, zPlan)); 6020 } 6021 rc = sqlite3_finalize(pExplain); 6022 if( rc!=SQLITE_OK ) break; 6023 6024 if( res<0 ){ 6025 raw_printf(stderr, "Error: internal error"); 6026 break; 6027 }else{ 6028 if( bGroupByParent 6029 && (bVerbose || res==0) 6030 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 6031 ){ 6032 raw_printf(out, "-- Parent table %s\n", zParent); 6033 sqlite3_free(zPrev); 6034 zPrev = sqlite3_mprintf("%s", zParent); 6035 } 6036 6037 if( res==0 ){ 6038 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 6039 }else if( bVerbose ){ 6040 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 6041 zIndent, zFrom, zTarget 6042 ); 6043 } 6044 } 6045 } 6046 sqlite3_free(zPrev); 6047 6048 if( rc!=SQLITE_OK ){ 6049 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6050 } 6051 6052 rc2 = sqlite3_finalize(pSql); 6053 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 6054 rc = rc2; 6055 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6056 } 6057 }else{ 6058 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6059 } 6060 6061 return rc; 6062} 6063 6064/* 6065** Implementation of ".lint" dot command. 6066*/ 6067static int lintDotCommand( 6068 ShellState *pState, /* Current shell tool state */ 6069 char **azArg, /* Array of arguments passed to dot command */ 6070 int nArg /* Number of entries in azArg[] */ 6071){ 6072 int n; 6073 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 6074 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 6075 return lintFkeyIndexes(pState, azArg, nArg); 6076 6077 usage: 6078 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 6079 raw_printf(stderr, "Where sub-commands are:\n"); 6080 raw_printf(stderr, " fkey-indexes\n"); 6081 return SQLITE_ERROR; 6082} 6083 6084#if !defined SQLITE_OMIT_VIRTUALTABLE 6085static void shellPrepare( 6086 sqlite3 *db, 6087 int *pRc, 6088 const char *zSql, 6089 sqlite3_stmt **ppStmt 6090){ 6091 *ppStmt = 0; 6092 if( *pRc==SQLITE_OK ){ 6093 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 6094 if( rc!=SQLITE_OK ){ 6095 raw_printf(stderr, "sql error: %s (%d)\n", 6096 sqlite3_errmsg(db), sqlite3_errcode(db) 6097 ); 6098 *pRc = rc; 6099 } 6100 } 6101} 6102 6103/* 6104** Create a prepared statement using printf-style arguments for the SQL. 6105** 6106** This routine is could be marked "static". But it is not always used, 6107** depending on compile-time options. By omitting the "static", we avoid 6108** nuisance compiler warnings about "defined but not used". 6109*/ 6110void shellPreparePrintf( 6111 sqlite3 *db, 6112 int *pRc, 6113 sqlite3_stmt **ppStmt, 6114 const char *zFmt, 6115 ... 6116){ 6117 *ppStmt = 0; 6118 if( *pRc==SQLITE_OK ){ 6119 va_list ap; 6120 char *z; 6121 va_start(ap, zFmt); 6122 z = sqlite3_vmprintf(zFmt, ap); 6123 va_end(ap); 6124 if( z==0 ){ 6125 *pRc = SQLITE_NOMEM; 6126 }else{ 6127 shellPrepare(db, pRc, z, ppStmt); 6128 sqlite3_free(z); 6129 } 6130 } 6131} 6132 6133/* Finalize the prepared statement created using shellPreparePrintf(). 6134** 6135** This routine is could be marked "static". But it is not always used, 6136** depending on compile-time options. By omitting the "static", we avoid 6137** nuisance compiler warnings about "defined but not used". 6138*/ 6139void shellFinalize( 6140 int *pRc, 6141 sqlite3_stmt *pStmt 6142){ 6143 if( pStmt ){ 6144 sqlite3 *db = sqlite3_db_handle(pStmt); 6145 int rc = sqlite3_finalize(pStmt); 6146 if( *pRc==SQLITE_OK ){ 6147 if( rc!=SQLITE_OK ){ 6148 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6149 } 6150 *pRc = rc; 6151 } 6152 } 6153} 6154 6155/* Reset the prepared statement created using shellPreparePrintf(). 6156** 6157** This routine is could be marked "static". But it is not always used, 6158** depending on compile-time options. By omitting the "static", we avoid 6159** nuisance compiler warnings about "defined but not used". 6160*/ 6161void shellReset( 6162 int *pRc, 6163 sqlite3_stmt *pStmt 6164){ 6165 int rc = sqlite3_reset(pStmt); 6166 if( *pRc==SQLITE_OK ){ 6167 if( rc!=SQLITE_OK ){ 6168 sqlite3 *db = sqlite3_db_handle(pStmt); 6169 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6170 } 6171 *pRc = rc; 6172 } 6173} 6174#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 6175 6176#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6177/****************************************************************************** 6178** The ".archive" or ".ar" command. 6179*/ 6180/* 6181** Structure representing a single ".ar" command. 6182*/ 6183typedef struct ArCommand ArCommand; 6184struct ArCommand { 6185 u8 eCmd; /* An AR_CMD_* value */ 6186 u8 bVerbose; /* True if --verbose */ 6187 u8 bZip; /* True if the archive is a ZIP */ 6188 u8 bDryRun; /* True if --dry-run */ 6189 u8 bAppend; /* True if --append */ 6190 u8 bGlob; /* True if --glob */ 6191 u8 fromCmdLine; /* Run from -A instead of .archive */ 6192 int nArg; /* Number of command arguments */ 6193 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 6194 const char *zFile; /* --file argument, or NULL */ 6195 const char *zDir; /* --directory argument, or NULL */ 6196 char **azArg; /* Array of command arguments */ 6197 ShellState *p; /* Shell state */ 6198 sqlite3 *db; /* Database containing the archive */ 6199}; 6200 6201/* 6202** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 6203*/ 6204static int arUsage(FILE *f){ 6205 showHelp(f,"archive"); 6206 return SQLITE_ERROR; 6207} 6208 6209/* 6210** Print an error message for the .ar command to stderr and return 6211** SQLITE_ERROR. 6212*/ 6213static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 6214 va_list ap; 6215 char *z; 6216 va_start(ap, zFmt); 6217 z = sqlite3_vmprintf(zFmt, ap); 6218 va_end(ap); 6219 utf8_printf(stderr, "Error: %s\n", z); 6220 if( pAr->fromCmdLine ){ 6221 utf8_printf(stderr, "Use \"-A\" for more help\n"); 6222 }else{ 6223 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 6224 } 6225 sqlite3_free(z); 6226 return SQLITE_ERROR; 6227} 6228 6229/* 6230** Values for ArCommand.eCmd. 6231*/ 6232#define AR_CMD_CREATE 1 6233#define AR_CMD_UPDATE 2 6234#define AR_CMD_INSERT 3 6235#define AR_CMD_EXTRACT 4 6236#define AR_CMD_LIST 5 6237#define AR_CMD_HELP 6 6238#define AR_CMD_REMOVE 7 6239 6240/* 6241** Other (non-command) switches. 6242*/ 6243#define AR_SWITCH_VERBOSE 8 6244#define AR_SWITCH_FILE 9 6245#define AR_SWITCH_DIRECTORY 10 6246#define AR_SWITCH_APPEND 11 6247#define AR_SWITCH_DRYRUN 12 6248#define AR_SWITCH_GLOB 13 6249 6250static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 6251 switch( eSwitch ){ 6252 case AR_CMD_CREATE: 6253 case AR_CMD_EXTRACT: 6254 case AR_CMD_LIST: 6255 case AR_CMD_REMOVE: 6256 case AR_CMD_UPDATE: 6257 case AR_CMD_INSERT: 6258 case AR_CMD_HELP: 6259 if( pAr->eCmd ){ 6260 return arErrorMsg(pAr, "multiple command options"); 6261 } 6262 pAr->eCmd = eSwitch; 6263 break; 6264 6265 case AR_SWITCH_DRYRUN: 6266 pAr->bDryRun = 1; 6267 break; 6268 case AR_SWITCH_GLOB: 6269 pAr->bGlob = 1; 6270 break; 6271 case AR_SWITCH_VERBOSE: 6272 pAr->bVerbose = 1; 6273 break; 6274 case AR_SWITCH_APPEND: 6275 pAr->bAppend = 1; 6276 /* Fall thru into --file */ 6277 case AR_SWITCH_FILE: 6278 pAr->zFile = zArg; 6279 break; 6280 case AR_SWITCH_DIRECTORY: 6281 pAr->zDir = zArg; 6282 break; 6283 } 6284 6285 return SQLITE_OK; 6286} 6287 6288/* 6289** Parse the command line for an ".ar" command. The results are written into 6290** structure (*pAr). SQLITE_OK is returned if the command line is parsed 6291** successfully, otherwise an error message is written to stderr and 6292** SQLITE_ERROR returned. 6293*/ 6294static int arParseCommand( 6295 char **azArg, /* Array of arguments passed to dot command */ 6296 int nArg, /* Number of entries in azArg[] */ 6297 ArCommand *pAr /* Populate this object */ 6298){ 6299 struct ArSwitch { 6300 const char *zLong; 6301 char cShort; 6302 u8 eSwitch; 6303 u8 bArg; 6304 } aSwitch[] = { 6305 { "create", 'c', AR_CMD_CREATE, 0 }, 6306 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 6307 { "insert", 'i', AR_CMD_INSERT, 0 }, 6308 { "list", 't', AR_CMD_LIST, 0 }, 6309 { "remove", 'r', AR_CMD_REMOVE, 0 }, 6310 { "update", 'u', AR_CMD_UPDATE, 0 }, 6311 { "help", 'h', AR_CMD_HELP, 0 }, 6312 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 6313 { "file", 'f', AR_SWITCH_FILE, 1 }, 6314 { "append", 'a', AR_SWITCH_APPEND, 1 }, 6315 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 6316 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 6317 { "glob", 'g', AR_SWITCH_GLOB, 0 }, 6318 }; 6319 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 6320 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 6321 6322 if( nArg<=1 ){ 6323 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 6324 return arUsage(stderr); 6325 }else{ 6326 char *z = azArg[1]; 6327 if( z[0]!='-' ){ 6328 /* Traditional style [tar] invocation */ 6329 int i; 6330 int iArg = 2; 6331 for(i=0; z[i]; i++){ 6332 const char *zArg = 0; 6333 struct ArSwitch *pOpt; 6334 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6335 if( z[i]==pOpt->cShort ) break; 6336 } 6337 if( pOpt==pEnd ){ 6338 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6339 } 6340 if( pOpt->bArg ){ 6341 if( iArg>=nArg ){ 6342 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 6343 } 6344 zArg = azArg[iArg++]; 6345 } 6346 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6347 } 6348 pAr->nArg = nArg-iArg; 6349 if( pAr->nArg>0 ){ 6350 pAr->azArg = &azArg[iArg]; 6351 } 6352 }else{ 6353 /* Non-traditional invocation */ 6354 int iArg; 6355 for(iArg=1; iArg<nArg; iArg++){ 6356 int n; 6357 z = azArg[iArg]; 6358 if( z[0]!='-' ){ 6359 /* All remaining command line words are command arguments. */ 6360 pAr->azArg = &azArg[iArg]; 6361 pAr->nArg = nArg-iArg; 6362 break; 6363 } 6364 n = strlen30(z); 6365 6366 if( z[1]!='-' ){ 6367 int i; 6368 /* One or more short options */ 6369 for(i=1; i<n; i++){ 6370 const char *zArg = 0; 6371 struct ArSwitch *pOpt; 6372 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6373 if( z[i]==pOpt->cShort ) break; 6374 } 6375 if( pOpt==pEnd ){ 6376 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6377 } 6378 if( pOpt->bArg ){ 6379 if( i<(n-1) ){ 6380 zArg = &z[i+1]; 6381 i = n; 6382 }else{ 6383 if( iArg>=(nArg-1) ){ 6384 return arErrorMsg(pAr, "option requires an argument: %c", 6385 z[i]); 6386 } 6387 zArg = azArg[++iArg]; 6388 } 6389 } 6390 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6391 } 6392 }else if( z[2]=='\0' ){ 6393 /* A -- option, indicating that all remaining command line words 6394 ** are command arguments. */ 6395 pAr->azArg = &azArg[iArg+1]; 6396 pAr->nArg = nArg-iArg-1; 6397 break; 6398 }else{ 6399 /* A long option */ 6400 const char *zArg = 0; /* Argument for option, if any */ 6401 struct ArSwitch *pMatch = 0; /* Matching option */ 6402 struct ArSwitch *pOpt; /* Iterator */ 6403 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6404 const char *zLong = pOpt->zLong; 6405 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 6406 if( pMatch ){ 6407 return arErrorMsg(pAr, "ambiguous option: %s",z); 6408 }else{ 6409 pMatch = pOpt; 6410 } 6411 } 6412 } 6413 6414 if( pMatch==0 ){ 6415 return arErrorMsg(pAr, "unrecognized option: %s", z); 6416 } 6417 if( pMatch->bArg ){ 6418 if( iArg>=(nArg-1) ){ 6419 return arErrorMsg(pAr, "option requires an argument: %s", z); 6420 } 6421 zArg = azArg[++iArg]; 6422 } 6423 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 6424 } 6425 } 6426 } 6427 } 6428 6429 return SQLITE_OK; 6430} 6431 6432/* 6433** This function assumes that all arguments within the ArCommand.azArg[] 6434** array refer to archive members, as for the --extract, --list or --remove 6435** commands. It checks that each of them are "present". If any specified 6436** file is not present in the archive, an error is printed to stderr and an 6437** error code returned. Otherwise, if all specified arguments are present 6438** in the archive, SQLITE_OK is returned. Here, "present" means either an 6439** exact equality when pAr->bGlob is false or a "name GLOB pattern" match 6440** when pAr->bGlob is true. 6441** 6442** This function strips any trailing '/' characters from each argument. 6443** This is consistent with the way the [tar] command seems to work on 6444** Linux. 6445*/ 6446static int arCheckEntries(ArCommand *pAr){ 6447 int rc = SQLITE_OK; 6448 if( pAr->nArg ){ 6449 int i, j; 6450 sqlite3_stmt *pTest = 0; 6451 const char *zSel = (pAr->bGlob) 6452 ? "SELECT name FROM %s WHERE glob($name,name)" 6453 : "SELECT name FROM %s WHERE name=$name"; 6454 6455 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); 6456 j = sqlite3_bind_parameter_index(pTest, "$name"); 6457 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6458 char *z = pAr->azArg[i]; 6459 int n = strlen30(z); 6460 int bOk = 0; 6461 while( n>0 && z[n-1]=='/' ) n--; 6462 z[n] = '\0'; 6463 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 6464 if( SQLITE_ROW==sqlite3_step(pTest) ){ 6465 bOk = 1; 6466 } 6467 shellReset(&rc, pTest); 6468 if( rc==SQLITE_OK && bOk==0 ){ 6469 utf8_printf(stderr, "not found in archive: %s\n", z); 6470 rc = SQLITE_ERROR; 6471 } 6472 } 6473 shellFinalize(&rc, pTest); 6474 } 6475 return rc; 6476} 6477 6478/* 6479** Format a WHERE clause that can be used against the "sqlar" table to 6480** identify all archive members that match the command arguments held 6481** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 6482** The caller is responsible for eventually calling sqlite3_free() on 6483** any non-NULL (*pzWhere) value. Here, "match" means strict equality 6484** when pAr->bGlob is false and GLOB match when pAr->bGlob is true. 6485*/ 6486static void arWhereClause( 6487 int *pRc, 6488 ArCommand *pAr, 6489 char **pzWhere /* OUT: New WHERE clause */ 6490){ 6491 char *zWhere = 0; 6492 const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; 6493 if( *pRc==SQLITE_OK ){ 6494 if( pAr->nArg==0 ){ 6495 zWhere = sqlite3_mprintf("1"); 6496 }else{ 6497 int i; 6498 const char *zSep = ""; 6499 for(i=0; i<pAr->nArg; i++){ 6500 const char *z = pAr->azArg[i]; 6501 zWhere = sqlite3_mprintf( 6502 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'", 6503 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z 6504 ); 6505 if( zWhere==0 ){ 6506 *pRc = SQLITE_NOMEM; 6507 break; 6508 } 6509 zSep = " OR "; 6510 } 6511 } 6512 } 6513 *pzWhere = zWhere; 6514} 6515 6516/* 6517** Implementation of .ar "lisT" command. 6518*/ 6519static int arListCommand(ArCommand *pAr){ 6520 const char *zSql = "SELECT %s FROM %s WHERE %s"; 6521 const char *azCols[] = { 6522 "name", 6523 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 6524 }; 6525 6526 char *zWhere = 0; 6527 sqlite3_stmt *pSql = 0; 6528 int rc; 6529 6530 rc = arCheckEntries(pAr); 6531 arWhereClause(&rc, pAr, &zWhere); 6532 6533 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 6534 pAr->zSrcTable, zWhere); 6535 if( pAr->bDryRun ){ 6536 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6537 }else{ 6538 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6539 if( pAr->bVerbose ){ 6540 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 6541 sqlite3_column_text(pSql, 0), 6542 sqlite3_column_int(pSql, 1), 6543 sqlite3_column_text(pSql, 2), 6544 sqlite3_column_text(pSql, 3) 6545 ); 6546 }else{ 6547 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6548 } 6549 } 6550 } 6551 shellFinalize(&rc, pSql); 6552 sqlite3_free(zWhere); 6553 return rc; 6554} 6555 6556 6557/* 6558** Implementation of .ar "Remove" command. 6559*/ 6560static int arRemoveCommand(ArCommand *pAr){ 6561 int rc = 0; 6562 char *zSql = 0; 6563 char *zWhere = 0; 6564 6565 if( pAr->nArg ){ 6566 /* Verify that args actually exist within the archive before proceeding. 6567 ** And formulate a WHERE clause to match them. */ 6568 rc = arCheckEntries(pAr); 6569 arWhereClause(&rc, pAr, &zWhere); 6570 } 6571 if( rc==SQLITE_OK ){ 6572 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;", 6573 pAr->zSrcTable, zWhere); 6574 if( pAr->bDryRun ){ 6575 utf8_printf(pAr->p->out, "%s\n", zSql); 6576 }else{ 6577 char *zErr = 0; 6578 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); 6579 if( rc==SQLITE_OK ){ 6580 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6581 if( rc!=SQLITE_OK ){ 6582 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6583 }else{ 6584 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); 6585 } 6586 } 6587 if( zErr ){ 6588 utf8_printf(stdout, "ERROR: %s\n", zErr); 6589 sqlite3_free(zErr); 6590 } 6591 } 6592 } 6593 sqlite3_free(zWhere); 6594 sqlite3_free(zSql); 6595 return rc; 6596} 6597 6598/* 6599** Implementation of .ar "eXtract" command. 6600*/ 6601static int arExtractCommand(ArCommand *pAr){ 6602 const char *zSql1 = 6603 "SELECT " 6604 " ($dir || name)," 6605 " writefile(($dir || name), %s, mode, mtime) " 6606 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 6607 " AND name NOT GLOB '*..[/\\]*'"; 6608 6609 const char *azExtraArg[] = { 6610 "sqlar_uncompress(data, sz)", 6611 "data" 6612 }; 6613 6614 sqlite3_stmt *pSql = 0; 6615 int rc = SQLITE_OK; 6616 char *zDir = 0; 6617 char *zWhere = 0; 6618 int i, j; 6619 6620 /* If arguments are specified, check that they actually exist within 6621 ** the archive before proceeding. And formulate a WHERE clause to 6622 ** match them. */ 6623 rc = arCheckEntries(pAr); 6624 arWhereClause(&rc, pAr, &zWhere); 6625 6626 if( rc==SQLITE_OK ){ 6627 if( pAr->zDir ){ 6628 zDir = sqlite3_mprintf("%s/", pAr->zDir); 6629 }else{ 6630 zDir = sqlite3_mprintf(""); 6631 } 6632 if( zDir==0 ) rc = SQLITE_NOMEM; 6633 } 6634 6635 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 6636 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 6637 ); 6638 6639 if( rc==SQLITE_OK ){ 6640 j = sqlite3_bind_parameter_index(pSql, "$dir"); 6641 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 6642 6643 /* Run the SELECT statement twice. The first time, writefile() is called 6644 ** for all archive members that should be extracted. The second time, 6645 ** only for the directories. This is because the timestamps for 6646 ** extracted directories must be reset after they are populated (as 6647 ** populating them changes the timestamp). */ 6648 for(i=0; i<2; i++){ 6649 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 6650 sqlite3_bind_int(pSql, j, i); 6651 if( pAr->bDryRun ){ 6652 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6653 }else{ 6654 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6655 if( i==0 && pAr->bVerbose ){ 6656 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6657 } 6658 } 6659 } 6660 shellReset(&rc, pSql); 6661 } 6662 shellFinalize(&rc, pSql); 6663 } 6664 6665 sqlite3_free(zDir); 6666 sqlite3_free(zWhere); 6667 return rc; 6668} 6669 6670/* 6671** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 6672*/ 6673static int arExecSql(ArCommand *pAr, const char *zSql){ 6674 int rc; 6675 if( pAr->bDryRun ){ 6676 utf8_printf(pAr->p->out, "%s\n", zSql); 6677 rc = SQLITE_OK; 6678 }else{ 6679 char *zErr = 0; 6680 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6681 if( zErr ){ 6682 utf8_printf(stdout, "ERROR: %s\n", zErr); 6683 sqlite3_free(zErr); 6684 } 6685 } 6686 return rc; 6687} 6688 6689 6690/* 6691** Implementation of .ar "create", "insert", and "update" commands. 6692** 6693** create -> Create a new SQL archive 6694** insert -> Insert or reinsert all files listed 6695** update -> Insert files that have changed or that were not 6696** previously in the archive 6697** 6698** Create the "sqlar" table in the database if it does not already exist. 6699** Then add each file in the azFile[] array to the archive. Directories 6700** are added recursively. If argument bVerbose is non-zero, a message is 6701** printed on stdout for each file archived. 6702** 6703** The create command is the same as update, except that it drops 6704** any existing "sqlar" table before beginning. The "insert" command 6705** always overwrites every file named on the command-line, where as 6706** "update" only overwrites if the size or mtime or mode has changed. 6707*/ 6708static int arCreateOrUpdateCommand( 6709 ArCommand *pAr, /* Command arguments and options */ 6710 int bUpdate, /* true for a --create. */ 6711 int bOnlyIfChanged /* Only update if file has changed */ 6712){ 6713 const char *zCreate = 6714 "CREATE TABLE IF NOT EXISTS sqlar(\n" 6715 " name TEXT PRIMARY KEY, -- name of the file\n" 6716 " mode INT, -- access permissions\n" 6717 " mtime INT, -- last modification time\n" 6718 " sz INT, -- original file size\n" 6719 " data BLOB -- compressed content\n" 6720 ")"; 6721 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 6722 const char *zInsertFmt[2] = { 6723 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 6724 " SELECT\n" 6725 " %s,\n" 6726 " mode,\n" 6727 " mtime,\n" 6728 " CASE substr(lsmode(mode),1,1)\n" 6729 " WHEN '-' THEN length(data)\n" 6730 " WHEN 'd' THEN 0\n" 6731 " ELSE -1 END,\n" 6732 " sqlar_compress(data)\n" 6733 " FROM fsdir(%Q,%Q) AS disk\n" 6734 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6735 , 6736 "REPLACE INTO %s(name,mode,mtime,data)\n" 6737 " SELECT\n" 6738 " %s,\n" 6739 " mode,\n" 6740 " mtime,\n" 6741 " data\n" 6742 " FROM fsdir(%Q,%Q) AS disk\n" 6743 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6744 }; 6745 int i; /* For iterating through azFile[] */ 6746 int rc; /* Return code */ 6747 const char *zTab = 0; /* SQL table into which to insert */ 6748 char *zSql; 6749 char zTemp[50]; 6750 char *zExists = 0; 6751 6752 arExecSql(pAr, "PRAGMA page_size=512"); 6753 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6754 if( rc!=SQLITE_OK ) return rc; 6755 zTemp[0] = 0; 6756 if( pAr->bZip ){ 6757 /* Initialize the zipfile virtual table, if necessary */ 6758 if( pAr->zFile ){ 6759 sqlite3_uint64 r; 6760 sqlite3_randomness(sizeof(r),&r); 6761 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6762 zTab = zTemp; 6763 zSql = sqlite3_mprintf( 6764 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6765 zTab, pAr->zFile 6766 ); 6767 rc = arExecSql(pAr, zSql); 6768 sqlite3_free(zSql); 6769 }else{ 6770 zTab = "zip"; 6771 } 6772 }else{ 6773 /* Initialize the table for an SQLAR */ 6774 zTab = "sqlar"; 6775 if( bUpdate==0 ){ 6776 rc = arExecSql(pAr, zDrop); 6777 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6778 } 6779 rc = arExecSql(pAr, zCreate); 6780 } 6781 if( bOnlyIfChanged ){ 6782 zExists = sqlite3_mprintf( 6783 " AND NOT EXISTS(" 6784 "SELECT 1 FROM %s AS mem" 6785 " WHERE mem.name=disk.name" 6786 " AND mem.mtime=disk.mtime" 6787 " AND mem.mode=disk.mode)", zTab); 6788 }else{ 6789 zExists = sqlite3_mprintf(""); 6790 } 6791 if( zExists==0 ) rc = SQLITE_NOMEM; 6792 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6793 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6794 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6795 pAr->azArg[i], pAr->zDir, zExists); 6796 rc = arExecSql(pAr, zSql2); 6797 sqlite3_free(zSql2); 6798 } 6799end_ar_transaction: 6800 if( rc!=SQLITE_OK ){ 6801 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6802 }else{ 6803 rc = arExecSql(pAr, "RELEASE ar;"); 6804 if( pAr->bZip && pAr->zFile ){ 6805 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6806 arExecSql(pAr, zSql); 6807 sqlite3_free(zSql); 6808 } 6809 } 6810 sqlite3_free(zExists); 6811 return rc; 6812} 6813 6814/* 6815** Implementation of ".ar" dot command. 6816*/ 6817static int arDotCommand( 6818 ShellState *pState, /* Current shell tool state */ 6819 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6820 char **azArg, /* Array of arguments passed to dot command */ 6821 int nArg /* Number of entries in azArg[] */ 6822){ 6823 ArCommand cmd; 6824 int rc; 6825 memset(&cmd, 0, sizeof(cmd)); 6826 cmd.fromCmdLine = fromCmdLine; 6827 rc = arParseCommand(azArg, nArg, &cmd); 6828 if( rc==SQLITE_OK ){ 6829 int eDbType = SHELL_OPEN_UNSPEC; 6830 cmd.p = pState; 6831 cmd.db = pState->db; 6832 if( cmd.zFile ){ 6833 eDbType = deduceDatabaseType(cmd.zFile, 1); 6834 }else{ 6835 eDbType = pState->openMode; 6836 } 6837 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6838 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6839 if( cmd.zFile==0 ){ 6840 cmd.zSrcTable = sqlite3_mprintf("zip"); 6841 }else{ 6842 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6843 } 6844 } 6845 cmd.bZip = 1; 6846 }else if( cmd.zFile ){ 6847 int flags; 6848 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6849 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6850 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){ 6851 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6852 }else{ 6853 flags = SQLITE_OPEN_READONLY; 6854 } 6855 cmd.db = 0; 6856 if( cmd.bDryRun ){ 6857 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6858 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6859 } 6860 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6861 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6862 if( rc!=SQLITE_OK ){ 6863 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6864 cmd.zFile, sqlite3_errmsg(cmd.db) 6865 ); 6866 goto end_ar_command; 6867 } 6868 sqlite3_fileio_init(cmd.db, 0, 0); 6869 sqlite3_sqlar_init(cmd.db, 0, 0); 6870 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6871 shellPutsFunc, 0, 0); 6872 6873 } 6874 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6875 if( cmd.eCmd!=AR_CMD_CREATE 6876 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6877 ){ 6878 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6879 rc = SQLITE_ERROR; 6880 goto end_ar_command; 6881 } 6882 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6883 } 6884 6885 switch( cmd.eCmd ){ 6886 case AR_CMD_CREATE: 6887 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6888 break; 6889 6890 case AR_CMD_EXTRACT: 6891 rc = arExtractCommand(&cmd); 6892 break; 6893 6894 case AR_CMD_LIST: 6895 rc = arListCommand(&cmd); 6896 break; 6897 6898 case AR_CMD_HELP: 6899 arUsage(pState->out); 6900 break; 6901 6902 case AR_CMD_INSERT: 6903 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6904 break; 6905 6906 case AR_CMD_REMOVE: 6907 rc = arRemoveCommand(&cmd); 6908 break; 6909 6910 default: 6911 assert( cmd.eCmd==AR_CMD_UPDATE ); 6912 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6913 break; 6914 } 6915 } 6916end_ar_command: 6917 if( cmd.db!=pState->db ){ 6918 close_db(cmd.db); 6919 } 6920 sqlite3_free(cmd.zSrcTable); 6921 6922 return rc; 6923} 6924/* End of the ".archive" or ".ar" command logic 6925*******************************************************************************/ 6926#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6927 6928#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6929/* 6930** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6931** Otherwise, the SQL statement or statements in zSql are executed using 6932** database connection db and the error code written to *pRc before 6933** this function returns. 6934*/ 6935static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6936 int rc = *pRc; 6937 if( rc==SQLITE_OK ){ 6938 char *zErr = 0; 6939 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6940 if( rc!=SQLITE_OK ){ 6941 raw_printf(stderr, "SQL error: %s\n", zErr); 6942 } 6943 sqlite3_free(zErr); 6944 *pRc = rc; 6945 } 6946} 6947 6948/* 6949** Like shellExec(), except that zFmt is a printf() style format string. 6950*/ 6951static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6952 char *z = 0; 6953 if( *pRc==SQLITE_OK ){ 6954 va_list ap; 6955 va_start(ap, zFmt); 6956 z = sqlite3_vmprintf(zFmt, ap); 6957 va_end(ap); 6958 if( z==0 ){ 6959 *pRc = SQLITE_NOMEM; 6960 }else{ 6961 shellExec(db, pRc, z); 6962 } 6963 sqlite3_free(z); 6964 } 6965} 6966 6967/* 6968** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6969** Otherwise, an attempt is made to allocate, zero and return a pointer 6970** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6971** to SQLITE_NOMEM and NULL returned. 6972*/ 6973static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6974 void *pRet = 0; 6975 if( *pRc==SQLITE_OK ){ 6976 pRet = sqlite3_malloc64(nByte); 6977 if( pRet==0 ){ 6978 *pRc = SQLITE_NOMEM; 6979 }else{ 6980 memset(pRet, 0, nByte); 6981 } 6982 } 6983 return pRet; 6984} 6985 6986/* 6987** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6988** Otherwise, zFmt is treated as a printf() style string. The result of 6989** formatting it along with any trailing arguments is written into a 6990** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6991** It is the responsibility of the caller to eventually free this buffer 6992** using a call to sqlite3_free(). 6993** 6994** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6995** pointer returned. 6996*/ 6997static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6998 char *z = 0; 6999 if( *pRc==SQLITE_OK ){ 7000 va_list ap; 7001 va_start(ap, zFmt); 7002 z = sqlite3_vmprintf(zFmt, ap); 7003 va_end(ap); 7004 if( z==0 ){ 7005 *pRc = SQLITE_NOMEM; 7006 } 7007 } 7008 return z; 7009} 7010 7011/* 7012** When running the ".recover" command, each output table, and the special 7013** orphaned row table if it is required, is represented by an instance 7014** of the following struct. 7015*/ 7016typedef struct RecoverTable RecoverTable; 7017struct RecoverTable { 7018 char *zQuoted; /* Quoted version of table name */ 7019 int nCol; /* Number of columns in table */ 7020 char **azlCol; /* Array of column lists */ 7021 int iPk; /* Index of IPK column */ 7022}; 7023 7024/* 7025** Free a RecoverTable object allocated by recoverFindTable() or 7026** recoverOrphanTable(). 7027*/ 7028static void recoverFreeTable(RecoverTable *pTab){ 7029 if( pTab ){ 7030 sqlite3_free(pTab->zQuoted); 7031 if( pTab->azlCol ){ 7032 int i; 7033 for(i=0; i<=pTab->nCol; i++){ 7034 sqlite3_free(pTab->azlCol[i]); 7035 } 7036 sqlite3_free(pTab->azlCol); 7037 } 7038 sqlite3_free(pTab); 7039 } 7040} 7041 7042/* 7043** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 7044** Otherwise, it allocates and returns a RecoverTable object based on the 7045** final four arguments passed to this function. It is the responsibility 7046** of the caller to eventually free the returned object using 7047** recoverFreeTable(). 7048*/ 7049static RecoverTable *recoverNewTable( 7050 int *pRc, /* IN/OUT: Error code */ 7051 const char *zName, /* Name of table */ 7052 const char *zSql, /* CREATE TABLE statement */ 7053 int bIntkey, 7054 int nCol 7055){ 7056 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 7057 int rc = *pRc; 7058 RecoverTable *pTab = 0; 7059 7060 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 7061 if( rc==SQLITE_OK ){ 7062 int nSqlCol = 0; 7063 int bSqlIntkey = 0; 7064 sqlite3_stmt *pStmt = 0; 7065 7066 rc = sqlite3_open("", &dbtmp); 7067 if( rc==SQLITE_OK ){ 7068 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, 7069 shellIdQuote, 0, 0); 7070 } 7071 if( rc==SQLITE_OK ){ 7072 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 7073 } 7074 if( rc==SQLITE_OK ){ 7075 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 7076 if( rc==SQLITE_ERROR ){ 7077 rc = SQLITE_OK; 7078 goto finished; 7079 } 7080 } 7081 shellPreparePrintf(dbtmp, &rc, &pStmt, 7082 "SELECT count(*) FROM pragma_table_info(%Q)", zName 7083 ); 7084 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7085 nSqlCol = sqlite3_column_int(pStmt, 0); 7086 } 7087 shellFinalize(&rc, pStmt); 7088 7089 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 7090 goto finished; 7091 } 7092 7093 shellPreparePrintf(dbtmp, &rc, &pStmt, 7094 "SELECT (" 7095 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 7096 ") FROM sqlite_schema WHERE name = %Q", zName 7097 ); 7098 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7099 bSqlIntkey = sqlite3_column_int(pStmt, 0); 7100 } 7101 shellFinalize(&rc, pStmt); 7102 7103 if( bIntkey==bSqlIntkey ){ 7104 int i; 7105 const char *zPk = "_rowid_"; 7106 sqlite3_stmt *pPkFinder = 0; 7107 7108 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 7109 ** set zPk to the name of the PK column, and pTab->iPk to the index 7110 ** of the column, where columns are 0-numbered from left to right. 7111 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 7112 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 7113 pTab->iPk = -2; 7114 if( bIntkey ){ 7115 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 7116 "SELECT cid, name FROM pragma_table_info(%Q) " 7117 " WHERE pk=1 AND type='integer' COLLATE nocase" 7118 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 7119 , zName, zName 7120 ); 7121 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 7122 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 7123 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 7124 if( zPk==0 ){ zPk = "_"; /* Defensive. Should never happen */ } 7125 } 7126 } 7127 7128 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); 7129 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 7130 pTab->nCol = nSqlCol; 7131 7132 if( bIntkey ){ 7133 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); 7134 }else{ 7135 pTab->azlCol[0] = shellMPrintf(&rc, ""); 7136 } 7137 i = 1; 7138 shellPreparePrintf(dbtmp, &rc, &pStmt, 7139 "SELECT %Q || group_concat(shell_idquote(name), ', ') " 7140 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 7141 "FROM pragma_table_info(%Q)", 7142 bIntkey ? ", " : "", pTab->iPk, 7143 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 7144 zName 7145 ); 7146 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7147 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 7148 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 7149 i++; 7150 } 7151 shellFinalize(&rc, pStmt); 7152 7153 shellFinalize(&rc, pPkFinder); 7154 } 7155 } 7156 7157 finished: 7158 sqlite3_close(dbtmp); 7159 *pRc = rc; 7160 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 7161 recoverFreeTable(pTab); 7162 pTab = 0; 7163 } 7164 return pTab; 7165} 7166 7167/* 7168** This function is called to search the schema recovered from the 7169** sqlite_schema table of the (possibly) corrupt database as part 7170** of a ".recover" command. Specifically, for a table with root page 7171** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 7172** table must be a WITHOUT ROWID table, or if non-zero, not one of 7173** those. 7174** 7175** If a table is found, a (RecoverTable*) object is returned. Or, if 7176** no such table is found, but bIntkey is false and iRoot is the 7177** root page of an index in the recovered schema, then (*pbNoop) is 7178** set to true and NULL returned. Or, if there is no such table or 7179** index, NULL is returned and (*pbNoop) set to 0, indicating that 7180** the caller should write data to the orphans table. 7181*/ 7182static RecoverTable *recoverFindTable( 7183 ShellState *pState, /* Shell state object */ 7184 int *pRc, /* IN/OUT: Error code */ 7185 int iRoot, /* Root page of table */ 7186 int bIntkey, /* True for an intkey table */ 7187 int nCol, /* Number of columns in table */ 7188 int *pbNoop /* OUT: True if iRoot is root of index */ 7189){ 7190 sqlite3_stmt *pStmt = 0; 7191 RecoverTable *pRet = 0; 7192 int bNoop = 0; 7193 const char *zSql = 0; 7194 const char *zName = 0; 7195 7196 /* Search the recovered schema for an object with root page iRoot. */ 7197 shellPreparePrintf(pState->db, pRc, &pStmt, 7198 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 7199 ); 7200 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7201 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 7202 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 7203 bNoop = 1; 7204 break; 7205 } 7206 if( sqlite3_stricmp(zType, "table")==0 ){ 7207 zName = (const char*)sqlite3_column_text(pStmt, 1); 7208 zSql = (const char*)sqlite3_column_text(pStmt, 2); 7209 if( zName!=0 && zSql!=0 ){ 7210 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 7211 break; 7212 } 7213 } 7214 } 7215 7216 shellFinalize(pRc, pStmt); 7217 *pbNoop = bNoop; 7218 return pRet; 7219} 7220 7221/* 7222** Return a RecoverTable object representing the orphans table. 7223*/ 7224static RecoverTable *recoverOrphanTable( 7225 ShellState *pState, /* Shell state object */ 7226 int *pRc, /* IN/OUT: Error code */ 7227 const char *zLostAndFound, /* Base name for orphans table */ 7228 int nCol /* Number of user data columns */ 7229){ 7230 RecoverTable *pTab = 0; 7231 if( nCol>=0 && *pRc==SQLITE_OK ){ 7232 int i; 7233 7234 /* This block determines the name of the orphan table. The prefered 7235 ** name is zLostAndFound. But if that clashes with another name 7236 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 7237 ** and so on until a non-clashing name is found. */ 7238 int iTab = 0; 7239 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 7240 sqlite3_stmt *pTest = 0; 7241 shellPrepare(pState->db, pRc, 7242 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 7243 ); 7244 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 7245 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 7246 shellReset(pRc, pTest); 7247 sqlite3_free(zTab); 7248 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 7249 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 7250 } 7251 shellFinalize(pRc, pTest); 7252 7253 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 7254 if( pTab ){ 7255 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); 7256 pTab->nCol = nCol; 7257 pTab->iPk = -2; 7258 if( nCol>0 ){ 7259 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 7260 if( pTab->azlCol ){ 7261 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 7262 for(i=nCol-1; i>=0; i--){ 7263 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 7264 } 7265 } 7266 } 7267 7268 if( *pRc!=SQLITE_OK ){ 7269 recoverFreeTable(pTab); 7270 pTab = 0; 7271 }else{ 7272 raw_printf(pState->out, 7273 "CREATE TABLE %s(rootpgno INTEGER, " 7274 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 7275 ); 7276 for(i=0; i<nCol; i++){ 7277 raw_printf(pState->out, ", c%d", i); 7278 } 7279 raw_printf(pState->out, ");\n"); 7280 } 7281 } 7282 sqlite3_free(zTab); 7283 } 7284 return pTab; 7285} 7286 7287/* 7288** This function is called to recover data from the database. A script 7289** to construct a new database containing all recovered data is output 7290** on stream pState->out. 7291*/ 7292static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 7293 int rc = SQLITE_OK; 7294 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 7295 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 7296 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 7297 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 7298 const char *zLostAndFound = "lost_and_found"; 7299 int i; 7300 int nOrphan = -1; 7301 RecoverTable *pOrphan = 0; 7302 7303 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 7304 int bRowids = 1; /* 0 if --no-rowids */ 7305 for(i=1; i<nArg; i++){ 7306 char *z = azArg[i]; 7307 int n; 7308 if( z[0]=='-' && z[1]=='-' ) z++; 7309 n = strlen30(z); 7310 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 7311 bFreelist = 0; 7312 }else 7313 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 7314 i++; 7315 zRecoveryDb = azArg[i]; 7316 }else 7317 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 7318 i++; 7319 zLostAndFound = azArg[i]; 7320 }else 7321 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ 7322 bRowids = 0; 7323 } 7324 else{ 7325 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 7326 showHelp(pState->out, azArg[0]); 7327 return 1; 7328 } 7329 } 7330 7331 shellExecPrintf(pState->db, &rc, 7332 /* Attach an in-memory database named 'recovery'. Create an indexed 7333 ** cache of the sqlite_dbptr virtual table. */ 7334 "PRAGMA writable_schema = on;" 7335 "ATTACH %Q AS recovery;" 7336 "DROP TABLE IF EXISTS recovery.dbptr;" 7337 "DROP TABLE IF EXISTS recovery.freelist;" 7338 "DROP TABLE IF EXISTS recovery.map;" 7339 "DROP TABLE IF EXISTS recovery.schema;" 7340 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 7341 ); 7342 7343 if( bFreelist ){ 7344 shellExec(pState->db, &rc, 7345 "WITH trunk(pgno) AS (" 7346 " SELECT shell_int32(" 7347 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 7348 " WHERE x>0" 7349 " UNION" 7350 " SELECT shell_int32(" 7351 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 7352 " FROM trunk WHERE x>0" 7353 ")," 7354 "freelist(data, n, freepgno) AS (" 7355 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 7356 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 7357 " UNION ALL" 7358 " SELECT data, n-1, shell_int32(data, 2+n) " 7359 " FROM freelist WHERE n>=0" 7360 ")" 7361 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 7362 ); 7363 } 7364 7365 /* If this is an auto-vacuum database, add all pointer-map pages to 7366 ** the freelist table. Do this regardless of whether or not 7367 ** --freelist-corrupt was specified. */ 7368 shellExec(pState->db, &rc, 7369 "WITH ptrmap(pgno) AS (" 7370 " SELECT 2 WHERE shell_int32(" 7371 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" 7372 " )" 7373 " UNION ALL " 7374 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " 7375 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" 7376 ")" 7377 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" 7378 ); 7379 7380 shellExec(pState->db, &rc, 7381 "CREATE TABLE recovery.dbptr(" 7382 " pgno, child, PRIMARY KEY(child, pgno)" 7383 ") WITHOUT ROWID;" 7384 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 7385 " SELECT * FROM sqlite_dbptr" 7386 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 7387 7388 /* Delete any pointer to page 1. This ensures that page 1 is considered 7389 ** a root page, regardless of how corrupt the db is. */ 7390 "DELETE FROM recovery.dbptr WHERE child = 1;" 7391 7392 /* Delete all pointers to any pages that have more than one pointer 7393 ** to them. Such pages will be treated as root pages when recovering 7394 ** data. */ 7395 "DELETE FROM recovery.dbptr WHERE child IN (" 7396 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 7397 ");" 7398 7399 /* Create the "map" table that will (eventually) contain instructions 7400 ** for dealing with each page in the db that contains one or more 7401 ** records. */ 7402 "CREATE TABLE recovery.map(" 7403 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 7404 ");" 7405 7406 /* Populate table [map]. If there are circular loops of pages in the 7407 ** database, the following adds all pages in such a loop to the map 7408 ** as individual root pages. This could be handled better. */ 7409 "WITH pages(i, maxlen) AS (" 7410 " SELECT page_count, (" 7411 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 7412 " ) FROM pragma_page_count WHERE page_count>0" 7413 " UNION ALL" 7414 " SELECT i-1, (" 7415 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 7416 " ) FROM pages WHERE i>=2" 7417 ")" 7418 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 7419 " SELECT i, maxlen, NULL, (" 7420 " WITH p(orig, pgno, parent) AS (" 7421 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 7422 " UNION " 7423 " SELECT i, p.parent, " 7424 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 7425 " )" 7426 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 7427 ") " 7428 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;" 7429 "UPDATE recovery.map AS o SET intkey = (" 7430 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 7431 ");" 7432 7433 /* Extract data from page 1 and any linked pages into table 7434 ** recovery.schema. With the same schema as an sqlite_schema table. */ 7435 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 7436 "INSERT INTO recovery.schema SELECT " 7437 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 7438 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 7439 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 7440 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 7441 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 7442 "FROM sqlite_dbdata WHERE pgno IN (" 7443 " SELECT pgno FROM recovery.map WHERE root=1" 7444 ")" 7445 "GROUP BY pgno, cell;" 7446 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 7447 ); 7448 7449 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 7450 ** CREATE TABLE statements that extracted from the existing schema. */ 7451 if( rc==SQLITE_OK ){ 7452 sqlite3_stmt *pStmt = 0; 7453 /* ".recover" might output content in an order which causes immediate 7454 ** foreign key constraints to be violated. So disable foreign-key 7455 ** constraint enforcement to prevent problems when running the output 7456 ** script. */ 7457 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); 7458 raw_printf(pState->out, "BEGIN;\n"); 7459 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 7460 shellPrepare(pState->db, &rc, 7461 "SELECT sql FROM recovery.schema " 7462 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 7463 ); 7464 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7465 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 7466 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 7467 &zCreateTable[12] 7468 ); 7469 } 7470 shellFinalize(&rc, pStmt); 7471 } 7472 7473 /* Figure out if an orphan table will be required. And if so, how many 7474 ** user columns it should contain */ 7475 shellPrepare(pState->db, &rc, 7476 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 7477 , &pLoop 7478 ); 7479 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 7480 nOrphan = sqlite3_column_int(pLoop, 0); 7481 } 7482 shellFinalize(&rc, pLoop); 7483 pLoop = 0; 7484 7485 shellPrepare(pState->db, &rc, 7486 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 7487 ); 7488 7489 shellPrepare(pState->db, &rc, 7490 "SELECT max(field), group_concat(shell_escape_crnl(quote" 7491 "(case when (? AND field<0) then NULL else value end)" 7492 "), ', ')" 7493 ", min(field) " 7494 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 7495 "GROUP BY cell", &pCells 7496 ); 7497 7498 /* Loop through each root page. */ 7499 shellPrepare(pState->db, &rc, 7500 "SELECT root, intkey, max(maxlen) FROM recovery.map" 7501 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 7502 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 7503 ")", &pLoop 7504 ); 7505 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 7506 int iRoot = sqlite3_column_int(pLoop, 0); 7507 int bIntkey = sqlite3_column_int(pLoop, 1); 7508 int nCol = sqlite3_column_int(pLoop, 2); 7509 int bNoop = 0; 7510 RecoverTable *pTab; 7511 7512 assert( bIntkey==0 || bIntkey==1 ); 7513 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 7514 if( bNoop || rc ) continue; 7515 if( pTab==0 ){ 7516 if( pOrphan==0 ){ 7517 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 7518 } 7519 pTab = pOrphan; 7520 if( pTab==0 ) break; 7521 } 7522 7523 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ 7524 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 7525 } 7526 sqlite3_bind_int(pPages, 1, iRoot); 7527 if( bRowids==0 && pTab->iPk<0 ){ 7528 sqlite3_bind_int(pCells, 1, 1); 7529 }else{ 7530 sqlite3_bind_int(pCells, 1, 0); 7531 } 7532 sqlite3_bind_int(pCells, 3, pTab->iPk); 7533 7534 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 7535 int iPgno = sqlite3_column_int(pPages, 0); 7536 sqlite3_bind_int(pCells, 2, iPgno); 7537 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 7538 int nField = sqlite3_column_int(pCells, 0); 7539 int iMin = sqlite3_column_int(pCells, 2); 7540 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 7541 7542 RecoverTable *pTab2 = pTab; 7543 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ 7544 if( pOrphan==0 ){ 7545 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 7546 } 7547 pTab2 = pOrphan; 7548 if( pTab2==0 ) break; 7549 } 7550 7551 nField = nField+1; 7552 if( pTab2==pOrphan ){ 7553 raw_printf(pState->out, 7554 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 7555 pTab2->zQuoted, iRoot, iPgno, nField, 7556 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] 7557 ); 7558 }else{ 7559 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 7560 pTab2->zQuoted, pTab2->azlCol[nField], zVal 7561 ); 7562 } 7563 } 7564 shellReset(&rc, pCells); 7565 } 7566 shellReset(&rc, pPages); 7567 if( pTab!=pOrphan ) recoverFreeTable(pTab); 7568 } 7569 shellFinalize(&rc, pLoop); 7570 shellFinalize(&rc, pPages); 7571 shellFinalize(&rc, pCells); 7572 recoverFreeTable(pOrphan); 7573 7574 /* The rest of the schema */ 7575 if( rc==SQLITE_OK ){ 7576 sqlite3_stmt *pStmt = 0; 7577 shellPrepare(pState->db, &rc, 7578 "SELECT sql, name FROM recovery.schema " 7579 "WHERE sql NOT LIKE 'create table%'", &pStmt 7580 ); 7581 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7582 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 7583 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 7584 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 7585 char *zPrint = shellMPrintf(&rc, 7586 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", 7587 zName, zName, zSql 7588 ); 7589 raw_printf(pState->out, "%s;\n", zPrint); 7590 sqlite3_free(zPrint); 7591 }else{ 7592 raw_printf(pState->out, "%s;\n", zSql); 7593 } 7594 } 7595 shellFinalize(&rc, pStmt); 7596 } 7597 7598 if( rc==SQLITE_OK ){ 7599 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 7600 raw_printf(pState->out, "COMMIT;\n"); 7601 } 7602 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 7603 return rc; 7604} 7605#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7606 7607/* 7608** If an input line begins with "." then invoke this routine to 7609** process that line. 7610** 7611** Return 1 on error, 2 to exit, and 0 otherwise. 7612*/ 7613static int do_meta_command(char *zLine, ShellState *p){ 7614 int h = 1; 7615 int nArg = 0; 7616 int n, c; 7617 int rc = 0; 7618 char *azArg[52]; 7619 7620#ifndef SQLITE_OMIT_VIRTUALTABLE 7621 if( p->expert.pExpert ){ 7622 expertFinish(p, 1, 0); 7623 } 7624#endif 7625 7626 /* Parse the input line into tokens. 7627 */ 7628 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ 7629 while( IsSpace(zLine[h]) ){ h++; } 7630 if( zLine[h]==0 ) break; 7631 if( zLine[h]=='\'' || zLine[h]=='"' ){ 7632 int delim = zLine[h++]; 7633 azArg[nArg++] = &zLine[h]; 7634 while( zLine[h] && zLine[h]!=delim ){ 7635 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 7636 h++; 7637 } 7638 if( zLine[h]==delim ){ 7639 zLine[h++] = 0; 7640 } 7641 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 7642 }else{ 7643 azArg[nArg++] = &zLine[h]; 7644 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 7645 if( zLine[h] ) zLine[h++] = 0; 7646 resolve_backslashes(azArg[nArg-1]); 7647 } 7648 } 7649 azArg[nArg] = 0; 7650 7651 /* Process the input line. 7652 */ 7653 if( nArg==0 ) return 0; /* no tokens, no error */ 7654 n = strlen30(azArg[0]); 7655 c = azArg[0][0]; 7656 clearTempFile(p); 7657 7658#ifndef SQLITE_OMIT_AUTHORIZATION 7659 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 7660 if( nArg!=2 ){ 7661 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 7662 rc = 1; 7663 goto meta_command_exit; 7664 } 7665 open_db(p, 0); 7666 if( booleanValue(azArg[1]) ){ 7667 sqlite3_set_authorizer(p->db, shellAuth, p); 7668 }else if( p->bSafeModePersist ){ 7669 sqlite3_set_authorizer(p->db, safeModeAuth, p); 7670 }else{ 7671 sqlite3_set_authorizer(p->db, 0, 0); 7672 } 7673 }else 7674#endif 7675 7676#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 7677 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 7678 open_db(p, 0); 7679 failIfSafeMode(p, "cannot run .archive in safe mode"); 7680 rc = arDotCommand(p, 0, azArg, nArg); 7681 }else 7682#endif 7683 7684 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 7685 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 7686 ){ 7687 const char *zDestFile = 0; 7688 const char *zDb = 0; 7689 sqlite3 *pDest; 7690 sqlite3_backup *pBackup; 7691 int j; 7692 int bAsync = 0; 7693 const char *zVfs = 0; 7694 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 7695 for(j=1; j<nArg; j++){ 7696 const char *z = azArg[j]; 7697 if( z[0]=='-' ){ 7698 if( z[1]=='-' ) z++; 7699 if( strcmp(z, "-append")==0 ){ 7700 zVfs = "apndvfs"; 7701 }else 7702 if( strcmp(z, "-async")==0 ){ 7703 bAsync = 1; 7704 }else 7705 { 7706 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 7707 return 1; 7708 } 7709 }else if( zDestFile==0 ){ 7710 zDestFile = azArg[j]; 7711 }else if( zDb==0 ){ 7712 zDb = zDestFile; 7713 zDestFile = azArg[j]; 7714 }else{ 7715 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 7716 return 1; 7717 } 7718 } 7719 if( zDestFile==0 ){ 7720 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 7721 return 1; 7722 } 7723 if( zDb==0 ) zDb = "main"; 7724 rc = sqlite3_open_v2(zDestFile, &pDest, 7725 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 7726 if( rc!=SQLITE_OK ){ 7727 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 7728 close_db(pDest); 7729 return 1; 7730 } 7731 if( bAsync ){ 7732 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7733 0, 0, 0); 7734 } 7735 open_db(p, 0); 7736 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7737 if( pBackup==0 ){ 7738 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7739 close_db(pDest); 7740 return 1; 7741 } 7742 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7743 sqlite3_backup_finish(pBackup); 7744 if( rc==SQLITE_DONE ){ 7745 rc = 0; 7746 }else{ 7747 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7748 rc = 1; 7749 } 7750 close_db(pDest); 7751 }else 7752 7753 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 7754 if( nArg==2 ){ 7755 bail_on_error = booleanValue(azArg[1]); 7756 }else{ 7757 raw_printf(stderr, "Usage: .bail on|off\n"); 7758 rc = 1; 7759 } 7760 }else 7761 7762 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 7763 if( nArg==2 ){ 7764 if( booleanValue(azArg[1]) ){ 7765 setBinaryMode(p->out, 1); 7766 }else{ 7767 setTextMode(p->out, 1); 7768 } 7769 }else{ 7770 raw_printf(stderr, "Usage: .binary on|off\n"); 7771 rc = 1; 7772 } 7773 }else 7774 7775 /* The undocumented ".breakpoint" command causes a call to the no-op 7776 ** routine named test_breakpoint(). 7777 */ 7778 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7779 test_breakpoint(); 7780 }else 7781 7782 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 7783 failIfSafeMode(p, "cannot run .cd in safe mode"); 7784 if( nArg==2 ){ 7785#if defined(_WIN32) || defined(WIN32) 7786 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7787 rc = !SetCurrentDirectoryW(z); 7788 sqlite3_free(z); 7789#else 7790 rc = chdir(azArg[1]); 7791#endif 7792 if( rc ){ 7793 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7794 rc = 1; 7795 } 7796 }else{ 7797 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7798 rc = 1; 7799 } 7800 }else 7801 7802 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7803 if( nArg==2 ){ 7804 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7805 }else{ 7806 raw_printf(stderr, "Usage: .changes on|off\n"); 7807 rc = 1; 7808 } 7809 }else 7810 7811 /* Cancel output redirection, if it is currently set (by .testcase) 7812 ** Then read the content of the testcase-out.txt file and compare against 7813 ** azArg[1]. If there are differences, report an error and exit. 7814 */ 7815 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7816 char *zRes = 0; 7817 output_reset(p); 7818 if( nArg!=2 ){ 7819 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7820 rc = 2; 7821 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7822 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7823 rc = 2; 7824 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7825 utf8_printf(stderr, 7826 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7827 p->zTestcase, azArg[1], zRes); 7828 rc = 1; 7829 }else{ 7830 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7831 p->nCheck++; 7832 } 7833 sqlite3_free(zRes); 7834 }else 7835 7836 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7837 failIfSafeMode(p, "cannot run .clone in safe mode"); 7838 if( nArg==2 ){ 7839 tryToClone(p, azArg[1]); 7840 }else{ 7841 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7842 rc = 1; 7843 } 7844 }else 7845 7846 if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){ 7847 if( nArg==1 ){ 7848 /* List available connections */ 7849 int i; 7850 for(i=0; i<ArraySize(p->aAuxDb); i++){ 7851 const char *zFile = p->aAuxDb[i].zDbFilename; 7852 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ 7853 zFile = "(not open)"; 7854 }else if( zFile==0 ){ 7855 zFile = "(memory)"; 7856 }else if( zFile[0]==0 ){ 7857 zFile = "(temporary-file)"; 7858 } 7859 if( p->pAuxDb == &p->aAuxDb[i] ){ 7860 utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile); 7861 }else if( p->aAuxDb[i].db!=0 ){ 7862 utf8_printf(stdout, " %d: %s\n", i, zFile); 7863 } 7864 } 7865 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){ 7866 int i = azArg[1][0] - '0'; 7867 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ 7868 p->pAuxDb->db = p->db; 7869 p->pAuxDb = &p->aAuxDb[i]; 7870 globalDb = p->db = p->pAuxDb->db; 7871 p->pAuxDb->db = 0; 7872 } 7873 }else if( nArg==3 && strcmp(azArg[1], "close")==0 7874 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){ 7875 int i = azArg[2][0] - '0'; 7876 if( i<0 || i>=ArraySize(p->aAuxDb) ){ 7877 /* No-op */ 7878 }else if( p->pAuxDb == &p->aAuxDb[i] ){ 7879 raw_printf(stderr, "cannot close the active database connection\n"); 7880 rc = 1; 7881 }else if( p->aAuxDb[i].db ){ 7882 session_close_all(p, i); 7883 close_db(p->aAuxDb[i].db); 7884 p->aAuxDb[i].db = 0; 7885 } 7886 }else{ 7887 raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n"); 7888 rc = 1; 7889 } 7890 }else 7891 7892 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7893 char **azName = 0; 7894 int nName = 0; 7895 sqlite3_stmt *pStmt; 7896 int i; 7897 open_db(p, 0); 7898 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 7899 if( rc ){ 7900 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7901 rc = 1; 7902 }else{ 7903 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7904 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1); 7905 const char *zFile = (const char*)sqlite3_column_text(pStmt,2); 7906 if( zSchema==0 || zFile==0 ) continue; 7907 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*)); 7908 shell_check_oom(azName); 7909 azName[nName*2] = strdup(zSchema); 7910 azName[nName*2+1] = strdup(zFile); 7911 nName++; 7912 } 7913 } 7914 sqlite3_finalize(pStmt); 7915 for(i=0; i<nName; i++){ 7916 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); 7917 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); 7918 const char *z = azName[i*2+1]; 7919 utf8_printf(p->out, "%s: %s %s%s\n", 7920 azName[i*2], 7921 z && z[0] ? z : "\"\"", 7922 bRdonly ? "r/o" : "r/w", 7923 eTxn==SQLITE_TXN_NONE ? "" : 7924 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); 7925 free(azName[i*2]); 7926 free(azName[i*2+1]); 7927 } 7928 sqlite3_free(azName); 7929 }else 7930 7931 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7932 static const struct DbConfigChoices { 7933 const char *zName; 7934 int op; 7935 } aDbConfig[] = { 7936 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7937 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7938 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7939 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7940 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7941 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7942 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, 7943 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7944 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7945 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, 7946 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7947 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7948 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7949 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7950 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, 7951 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7952 }; 7953 int ii, v; 7954 open_db(p, 0); 7955 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7956 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7957 if( nArg>=3 ){ 7958 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7959 } 7960 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7961 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7962 if( nArg>1 ) break; 7963 } 7964 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7965 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7966 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7967 } 7968 }else 7969 7970 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7971 rc = shell_dbinfo_command(p, nArg, azArg); 7972 }else 7973 7974#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7975 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7976 open_db(p, 0); 7977 rc = recoverDatabaseCmd(p, nArg, azArg); 7978 }else 7979#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7980 7981 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7982 char *zLike = 0; 7983 char *zSql; 7984 int i; 7985 int savedShowHeader = p->showHeader; 7986 int savedShellFlags = p->shellFlgs; 7987 ShellClearFlag(p, 7988 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo 7989 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys); 7990 for(i=1; i<nArg; i++){ 7991 if( azArg[i][0]=='-' ){ 7992 const char *z = azArg[i]+1; 7993 if( z[0]=='-' ) z++; 7994 if( strcmp(z,"preserve-rowids")==0 ){ 7995#ifdef SQLITE_OMIT_VIRTUALTABLE 7996 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7997 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7998 rc = 1; 7999 sqlite3_free(zLike); 8000 goto meta_command_exit; 8001#else 8002 ShellSetFlag(p, SHFLG_PreserveRowid); 8003#endif 8004 }else 8005 if( strcmp(z,"newlines")==0 ){ 8006 ShellSetFlag(p, SHFLG_Newlines); 8007 }else 8008 if( strcmp(z,"data-only")==0 ){ 8009 ShellSetFlag(p, SHFLG_DumpDataOnly); 8010 }else 8011 if( strcmp(z,"nosys")==0 ){ 8012 ShellSetFlag(p, SHFLG_DumpNoSys); 8013 }else 8014 { 8015 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 8016 rc = 1; 8017 sqlite3_free(zLike); 8018 goto meta_command_exit; 8019 } 8020 }else{ 8021 /* azArg[i] contains a LIKE pattern. This ".dump" request should 8022 ** only dump data for tables for which either the table name matches 8023 ** the LIKE pattern, or the table appears to be a shadow table of 8024 ** a virtual table for which the name matches the LIKE pattern. 8025 */ 8026 char *zExpr = sqlite3_mprintf( 8027 "name LIKE %Q ESCAPE '\\' OR EXISTS (" 8028 " SELECT 1 FROM sqlite_schema WHERE " 8029 " name LIKE %Q ESCAPE '\\' AND" 8030 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND" 8031 " substr(o.name, 1, length(name)+1) == (name||'_')" 8032 ")", azArg[i], azArg[i] 8033 ); 8034 8035 if( zLike ){ 8036 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr); 8037 }else{ 8038 zLike = zExpr; 8039 } 8040 } 8041 } 8042 8043 open_db(p, 0); 8044 8045 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8046 /* When playing back a "dump", the content might appear in an order 8047 ** which causes immediate foreign key constraints to be violated. 8048 ** So disable foreign-key constraint enforcement to prevent problems. */ 8049 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 8050 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 8051 } 8052 p->writableSchema = 0; 8053 p->showHeader = 0; 8054 /* Set writable_schema=ON since doing so forces SQLite to initialize 8055 ** as much of the schema as it can even if the sqlite_schema table is 8056 ** corrupt. */ 8057 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 8058 p->nErr = 0; 8059 if( zLike==0 ) zLike = sqlite3_mprintf("true"); 8060 zSql = sqlite3_mprintf( 8061 "SELECT name, type, sql FROM sqlite_schema AS o " 8062 "WHERE (%s) AND type=='table'" 8063 " AND sql NOT NULL" 8064 " ORDER BY tbl_name='sqlite_sequence', rowid", 8065 zLike 8066 ); 8067 run_schema_dump_query(p,zSql); 8068 sqlite3_free(zSql); 8069 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8070 zSql = sqlite3_mprintf( 8071 "SELECT sql FROM sqlite_schema AS o " 8072 "WHERE (%s) AND sql NOT NULL" 8073 " AND type IN ('index','trigger','view')", 8074 zLike 8075 ); 8076 run_table_dump_query(p, zSql); 8077 sqlite3_free(zSql); 8078 } 8079 sqlite3_free(zLike); 8080 if( p->writableSchema ){ 8081 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 8082 p->writableSchema = 0; 8083 } 8084 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 8085 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 8086 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8087 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 8088 } 8089 p->showHeader = savedShowHeader; 8090 p->shellFlgs = savedShellFlags; 8091 }else 8092 8093 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 8094 if( nArg==2 ){ 8095 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 8096 }else{ 8097 raw_printf(stderr, "Usage: .echo on|off\n"); 8098 rc = 1; 8099 } 8100 }else 8101 8102 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 8103 if( nArg==2 ){ 8104 p->autoEQPtest = 0; 8105 if( p->autoEQPtrace ){ 8106 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 8107 p->autoEQPtrace = 0; 8108 } 8109 if( strcmp(azArg[1],"full")==0 ){ 8110 p->autoEQP = AUTOEQP_full; 8111 }else if( strcmp(azArg[1],"trigger")==0 ){ 8112 p->autoEQP = AUTOEQP_trigger; 8113#ifdef SQLITE_DEBUG 8114 }else if( strcmp(azArg[1],"test")==0 ){ 8115 p->autoEQP = AUTOEQP_on; 8116 p->autoEQPtest = 1; 8117 }else if( strcmp(azArg[1],"trace")==0 ){ 8118 p->autoEQP = AUTOEQP_full; 8119 p->autoEQPtrace = 1; 8120 open_db(p, 0); 8121 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); 8122 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 8123#endif 8124 }else{ 8125 p->autoEQP = (u8)booleanValue(azArg[1]); 8126 } 8127 }else{ 8128 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 8129 rc = 1; 8130 } 8131 }else 8132 8133 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 8134 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 8135 rc = 2; 8136 }else 8137 8138 /* The ".explain" command is automatic now. It is largely pointless. It 8139 ** retained purely for backwards compatibility */ 8140 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 8141 int val = 1; 8142 if( nArg>=2 ){ 8143 if( strcmp(azArg[1],"auto")==0 ){ 8144 val = 99; 8145 }else{ 8146 val = booleanValue(azArg[1]); 8147 } 8148 } 8149 if( val==1 && p->mode!=MODE_Explain ){ 8150 p->normalMode = p->mode; 8151 p->mode = MODE_Explain; 8152 p->autoExplain = 0; 8153 }else if( val==0 ){ 8154 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8155 p->autoExplain = 0; 8156 }else if( val==99 ){ 8157 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8158 p->autoExplain = 1; 8159 } 8160 }else 8161 8162#ifndef SQLITE_OMIT_VIRTUALTABLE 8163 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 8164 if( p->bSafeMode ){ 8165 raw_printf(stderr, 8166 "Cannot run experimental commands such as \"%s\" in safe mode\n", 8167 azArg[0]); 8168 rc = 1; 8169 }else{ 8170 open_db(p, 0); 8171 expertDotCommand(p, azArg, nArg); 8172 } 8173 }else 8174#endif 8175 8176 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ 8177 static const struct { 8178 const char *zCtrlName; /* Name of a test-control option */ 8179 int ctrlCode; /* Integer code for that option */ 8180 const char *zUsage; /* Usage notes */ 8181 } aCtrl[] = { 8182 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 8183 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" }, 8184 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 8185 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 8186 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 8187 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 8188 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 8189 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, 8190 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 8191 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 8192 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 8193 }; 8194 int filectrl = -1; 8195 int iCtrl = -1; 8196 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 8197 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 8198 int n2, i; 8199 const char *zCmd = 0; 8200 const char *zSchema = 0; 8201 8202 open_db(p, 0); 8203 zCmd = nArg>=2 ? azArg[1] : "help"; 8204 8205 if( zCmd[0]=='-' 8206 && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0) 8207 && nArg>=4 8208 ){ 8209 zSchema = azArg[2]; 8210 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; 8211 nArg -= 2; 8212 zCmd = azArg[1]; 8213 } 8214 8215 /* The argument can optionally begin with "-" or "--" */ 8216 if( zCmd[0]=='-' && zCmd[1] ){ 8217 zCmd++; 8218 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 8219 } 8220 8221 /* --help lists all file-controls */ 8222 if( strcmp(zCmd,"help")==0 ){ 8223 utf8_printf(p->out, "Available file-controls:\n"); 8224 for(i=0; i<ArraySize(aCtrl); i++){ 8225 utf8_printf(p->out, " .filectrl %s %s\n", 8226 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 8227 } 8228 rc = 1; 8229 goto meta_command_exit; 8230 } 8231 8232 /* convert filectrl text option to value. allow any unique prefix 8233 ** of the option name, or a numerical value. */ 8234 n2 = strlen30(zCmd); 8235 for(i=0; i<ArraySize(aCtrl); i++){ 8236 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 8237 if( filectrl<0 ){ 8238 filectrl = aCtrl[i].ctrlCode; 8239 iCtrl = i; 8240 }else{ 8241 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 8242 "Use \".filectrl --help\" for help\n", zCmd); 8243 rc = 1; 8244 goto meta_command_exit; 8245 } 8246 } 8247 } 8248 if( filectrl<0 ){ 8249 utf8_printf(stderr,"Error: unknown file-control: %s\n" 8250 "Use \".filectrl --help\" for help\n", zCmd); 8251 }else{ 8252 switch(filectrl){ 8253 case SQLITE_FCNTL_SIZE_LIMIT: { 8254 if( nArg!=2 && nArg!=3 ) break; 8255 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 8256 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 8257 isOk = 1; 8258 break; 8259 } 8260 case SQLITE_FCNTL_LOCK_TIMEOUT: 8261 case SQLITE_FCNTL_CHUNK_SIZE: { 8262 int x; 8263 if( nArg!=3 ) break; 8264 x = (int)integerValue(azArg[2]); 8265 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8266 isOk = 2; 8267 break; 8268 } 8269 case SQLITE_FCNTL_PERSIST_WAL: 8270 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 8271 int x; 8272 if( nArg!=2 && nArg!=3 ) break; 8273 x = nArg==3 ? booleanValue(azArg[2]) : -1; 8274 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8275 iRes = x; 8276 isOk = 1; 8277 break; 8278 } 8279 case SQLITE_FCNTL_DATA_VERSION: 8280 case SQLITE_FCNTL_HAS_MOVED: { 8281 int x; 8282 if( nArg!=2 ) break; 8283 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8284 iRes = x; 8285 isOk = 1; 8286 break; 8287 } 8288 case SQLITE_FCNTL_TEMPFILENAME: { 8289 char *z = 0; 8290 if( nArg!=2 ) break; 8291 sqlite3_file_control(p->db, zSchema, filectrl, &z); 8292 if( z ){ 8293 utf8_printf(p->out, "%s\n", z); 8294 sqlite3_free(z); 8295 } 8296 isOk = 2; 8297 break; 8298 } 8299 case SQLITE_FCNTL_RESERVE_BYTES: { 8300 int x; 8301 if( nArg>=3 ){ 8302 x = atoi(azArg[2]); 8303 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8304 } 8305 x = -1; 8306 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8307 utf8_printf(p->out,"%d\n", x); 8308 isOk = 2; 8309 break; 8310 } 8311 } 8312 } 8313 if( isOk==0 && iCtrl>=0 ){ 8314 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 8315 rc = 1; 8316 }else if( isOk==1 ){ 8317 char zBuf[100]; 8318 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 8319 raw_printf(p->out, "%s\n", zBuf); 8320 } 8321 }else 8322 8323 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 8324 ShellState data; 8325 int doStats = 0; 8326 memcpy(&data, p, sizeof(data)); 8327 data.showHeader = 0; 8328 data.cMode = data.mode = MODE_Semi; 8329 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 8330 data.cMode = data.mode = MODE_Pretty; 8331 nArg = 1; 8332 } 8333 if( nArg!=1 ){ 8334 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 8335 rc = 1; 8336 goto meta_command_exit; 8337 } 8338 open_db(p, 0); 8339 rc = sqlite3_exec(p->db, 8340 "SELECT sql FROM" 8341 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 8342 " FROM sqlite_schema UNION ALL" 8343 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " 8344 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 8345 "ORDER BY x", 8346 callback, &data, 0 8347 ); 8348 if( rc==SQLITE_OK ){ 8349 sqlite3_stmt *pStmt; 8350 rc = sqlite3_prepare_v2(p->db, 8351 "SELECT rowid FROM sqlite_schema" 8352 " WHERE name GLOB 'sqlite_stat[134]'", 8353 -1, &pStmt, 0); 8354 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 8355 sqlite3_finalize(pStmt); 8356 } 8357 if( doStats==0 ){ 8358 raw_printf(p->out, "/* No STAT tables available */\n"); 8359 }else{ 8360 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8361 data.cMode = data.mode = MODE_Insert; 8362 data.zDestTable = "sqlite_stat1"; 8363 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0); 8364 data.zDestTable = "sqlite_stat4"; 8365 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0); 8366 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8367 } 8368 }else 8369 8370 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 8371 if( nArg==2 ){ 8372 p->showHeader = booleanValue(azArg[1]); 8373 p->shellFlgs |= SHFLG_HeaderSet; 8374 }else{ 8375 raw_printf(stderr, "Usage: .headers on|off\n"); 8376 rc = 1; 8377 } 8378 }else 8379 8380 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 8381 if( nArg>=2 ){ 8382 n = showHelp(p->out, azArg[1]); 8383 if( n==0 ){ 8384 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 8385 } 8386 }else{ 8387 showHelp(p->out, 0); 8388 } 8389 }else 8390 8391 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 8392 char *zTable = 0; /* Insert data into this table */ 8393 char *zSchema = "main"; /* within this schema */ 8394 char *zFile = 0; /* Name of file to extra content from */ 8395 sqlite3_stmt *pStmt = NULL; /* A statement */ 8396 int nCol; /* Number of columns in the table */ 8397 int nByte; /* Number of bytes in an SQL string */ 8398 int i, j; /* Loop counters */ 8399 int needCommit; /* True to COMMIT or ROLLBACK at end */ 8400 int nSep; /* Number of bytes in p->colSeparator[] */ 8401 char *zSql; /* An SQL statement */ 8402 ImportCtx sCtx; /* Reader context */ 8403 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 8404 int eVerbose = 0; /* Larger for more console output */ 8405 int nSkip = 0; /* Initial lines to skip */ 8406 int useOutputMode = 1; /* Use output mode to determine separators */ 8407 8408 failIfSafeMode(p, "cannot run .import in safe mode"); 8409 memset(&sCtx, 0, sizeof(sCtx)); 8410 sCtx.z = sqlite3_malloc64(120); 8411 if( sCtx.z==0 ){ 8412 import_cleanup(&sCtx); 8413 shell_out_of_memory(); 8414 } 8415 if( p->mode==MODE_Ascii ){ 8416 xRead = ascii_read_one_field; 8417 }else{ 8418 xRead = csv_read_one_field; 8419 } 8420 for(i=1; i<nArg; i++){ 8421 char *z = azArg[i]; 8422 if( z[0]=='-' && z[1]=='-' ) z++; 8423 if( z[0]!='-' ){ 8424 if( zFile==0 ){ 8425 zFile = z; 8426 }else if( zTable==0 ){ 8427 zTable = z; 8428 }else{ 8429 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z); 8430 showHelp(p->out, "import"); 8431 rc = 1; 8432 goto meta_command_exit; 8433 } 8434 }else if( strcmp(z,"-v")==0 ){ 8435 eVerbose++; 8436 }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){ 8437 zSchema = azArg[++i]; 8438 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){ 8439 nSkip = integerValue(azArg[++i]); 8440 }else if( strcmp(z,"-ascii")==0 ){ 8441 sCtx.cColSep = SEP_Unit[0]; 8442 sCtx.cRowSep = SEP_Record[0]; 8443 xRead = ascii_read_one_field; 8444 useOutputMode = 0; 8445 }else if( strcmp(z,"-csv")==0 ){ 8446 sCtx.cColSep = ','; 8447 sCtx.cRowSep = '\n'; 8448 xRead = csv_read_one_field; 8449 useOutputMode = 0; 8450 }else{ 8451 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z); 8452 showHelp(p->out, "import"); 8453 rc = 1; 8454 goto meta_command_exit; 8455 } 8456 } 8457 if( zTable==0 ){ 8458 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n", 8459 zFile==0 ? "FILE" : "TABLE"); 8460 showHelp(p->out, "import"); 8461 rc = 1; 8462 goto meta_command_exit; 8463 } 8464 seenInterrupt = 0; 8465 open_db(p, 0); 8466 if( useOutputMode ){ 8467 /* If neither the --csv or --ascii options are specified, then set 8468 ** the column and row separator characters from the output mode. */ 8469 nSep = strlen30(p->colSeparator); 8470 if( nSep==0 ){ 8471 raw_printf(stderr, 8472 "Error: non-null column separator required for import\n"); 8473 rc = 1; 8474 goto meta_command_exit; 8475 } 8476 if( nSep>1 ){ 8477 raw_printf(stderr, 8478 "Error: multi-character column separators not allowed" 8479 " for import\n"); 8480 rc = 1; 8481 goto meta_command_exit; 8482 } 8483 nSep = strlen30(p->rowSeparator); 8484 if( nSep==0 ){ 8485 raw_printf(stderr, 8486 "Error: non-null row separator required for import\n"); 8487 rc = 1; 8488 goto meta_command_exit; 8489 } 8490 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){ 8491 /* When importing CSV (only), if the row separator is set to the 8492 ** default output row separator, change it to the default input 8493 ** row separator. This avoids having to maintain different input 8494 ** and output row separators. */ 8495 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8496 nSep = strlen30(p->rowSeparator); 8497 } 8498 if( nSep>1 ){ 8499 raw_printf(stderr, "Error: multi-character row separators not allowed" 8500 " for import\n"); 8501 rc = 1; 8502 goto meta_command_exit; 8503 } 8504 sCtx.cColSep = p->colSeparator[0]; 8505 sCtx.cRowSep = p->rowSeparator[0]; 8506 } 8507 sCtx.zFile = zFile; 8508 sCtx.nLine = 1; 8509 if( sCtx.zFile[0]=='|' ){ 8510#ifdef SQLITE_OMIT_POPEN 8511 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8512 rc = 1; 8513 goto meta_command_exit; 8514#else 8515 sCtx.in = popen(sCtx.zFile+1, "r"); 8516 sCtx.zFile = "<pipe>"; 8517 sCtx.xCloser = pclose; 8518#endif 8519 }else{ 8520 sCtx.in = fopen(sCtx.zFile, "rb"); 8521 sCtx.xCloser = fclose; 8522 } 8523 if( sCtx.in==0 ){ 8524 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 8525 rc = 1; 8526 import_cleanup(&sCtx); 8527 goto meta_command_exit; 8528 } 8529 /* Below, resources must be freed before exit. */ 8530 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ 8531 char zSep[2]; 8532 zSep[1] = 0; 8533 zSep[0] = sCtx.cColSep; 8534 utf8_printf(p->out, "Column separator "); 8535 output_c_string(p->out, zSep); 8536 utf8_printf(p->out, ", row separator "); 8537 zSep[0] = sCtx.cRowSep; 8538 output_c_string(p->out, zSep); 8539 utf8_printf(p->out, "\n"); 8540 } 8541 while( (nSkip--)>0 ){ 8542 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} 8543 } 8544 zSql = sqlite3_mprintf("SELECT * FROM \"%w\".\"%w\"", zSchema, zTable); 8545 if( zSql==0 ){ 8546 import_cleanup(&sCtx); 8547 shell_out_of_memory(); 8548 } 8549 nByte = strlen30(zSql); 8550 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8551 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 8552 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 8553 char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"", 8554 zSchema, zTable); 8555 char cSep = '('; 8556 while( xRead(&sCtx) ){ 8557 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 8558 cSep = ','; 8559 if( sCtx.cTerm!=sCtx.cColSep ) break; 8560 } 8561 if( cSep=='(' ){ 8562 sqlite3_free(zCreate); 8563 import_cleanup(&sCtx); 8564 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 8565 rc = 1; 8566 goto meta_command_exit; 8567 } 8568 zCreate = sqlite3_mprintf("%z\n)", zCreate); 8569 if( eVerbose>=1 ){ 8570 utf8_printf(p->out, "%s\n", zCreate); 8571 } 8572 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 8573 if( rc ){ 8574 utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); 8575 sqlite3_free(zCreate); 8576 import_cleanup(&sCtx); 8577 rc = 1; 8578 goto meta_command_exit; 8579 } 8580 sqlite3_free(zCreate); 8581 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8582 } 8583 sqlite3_free(zSql); 8584 if( rc ){ 8585 if (pStmt) sqlite3_finalize(pStmt); 8586 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 8587 import_cleanup(&sCtx); 8588 rc = 1; 8589 goto meta_command_exit; 8590 } 8591 nCol = sqlite3_column_count(pStmt); 8592 sqlite3_finalize(pStmt); 8593 pStmt = 0; 8594 if( nCol==0 ) return 0; /* no columns, no error */ 8595 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 8596 if( zSql==0 ){ 8597 import_cleanup(&sCtx); 8598 shell_out_of_memory(); 8599 } 8600 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?", 8601 zSchema, zTable); 8602 j = strlen30(zSql); 8603 for(i=1; i<nCol; i++){ 8604 zSql[j++] = ','; 8605 zSql[j++] = '?'; 8606 } 8607 zSql[j++] = ')'; 8608 zSql[j] = 0; 8609 if( eVerbose>=2 ){ 8610 utf8_printf(p->out, "Insert using: %s\n", zSql); 8611 } 8612 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8613 sqlite3_free(zSql); 8614 if( rc ){ 8615 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8616 if (pStmt) sqlite3_finalize(pStmt); 8617 import_cleanup(&sCtx); 8618 rc = 1; 8619 goto meta_command_exit; 8620 } 8621 needCommit = sqlite3_get_autocommit(p->db); 8622 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 8623 do{ 8624 int startLine = sCtx.nLine; 8625 for(i=0; i<nCol; i++){ 8626 char *z = xRead(&sCtx); 8627 /* 8628 ** Did we reach end-of-file before finding any columns? 8629 ** If so, stop instead of NULL filling the remaining columns. 8630 */ 8631 if( z==0 && i==0 ) break; 8632 /* 8633 ** Did we reach end-of-file OR end-of-line before finding any 8634 ** columns in ASCII mode? If so, stop instead of NULL filling 8635 ** the remaining columns. 8636 */ 8637 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 8638 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 8639 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 8640 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8641 "filling the rest with NULL\n", 8642 sCtx.zFile, startLine, nCol, i+1); 8643 i += 2; 8644 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 8645 } 8646 } 8647 if( sCtx.cTerm==sCtx.cColSep ){ 8648 do{ 8649 xRead(&sCtx); 8650 i++; 8651 }while( sCtx.cTerm==sCtx.cColSep ); 8652 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8653 "extras ignored\n", 8654 sCtx.zFile, startLine, nCol, i); 8655 } 8656 if( i>=nCol ){ 8657 sqlite3_step(pStmt); 8658 rc = sqlite3_reset(pStmt); 8659 if( rc!=SQLITE_OK ){ 8660 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 8661 startLine, sqlite3_errmsg(p->db)); 8662 sCtx.nErr++; 8663 }else{ 8664 sCtx.nRow++; 8665 } 8666 } 8667 }while( sCtx.cTerm!=EOF ); 8668 8669 import_cleanup(&sCtx); 8670 sqlite3_finalize(pStmt); 8671 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 8672 if( eVerbose>0 ){ 8673 utf8_printf(p->out, 8674 "Added %d rows with %d errors using %d lines of input\n", 8675 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); 8676 } 8677 }else 8678 8679#ifndef SQLITE_UNTESTABLE 8680 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 8681 char *zSql; 8682 char *zCollist = 0; 8683 sqlite3_stmt *pStmt; 8684 int tnum = 0; 8685 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ 8686 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ 8687 int i; 8688 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 8689 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 8690 " .imposter off\n"); 8691 /* Also allowed, but not documented: 8692 ** 8693 ** .imposter TABLE IMPOSTER 8694 ** 8695 ** where TABLE is a WITHOUT ROWID table. In that case, the 8696 ** imposter is another WITHOUT ROWID table with the columns in 8697 ** storage order. */ 8698 rc = 1; 8699 goto meta_command_exit; 8700 } 8701 open_db(p, 0); 8702 if( nArg==2 ){ 8703 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 8704 goto meta_command_exit; 8705 } 8706 zSql = sqlite3_mprintf( 8707 "SELECT rootpage, 0 FROM sqlite_schema" 8708 " WHERE name='%q' AND type='index'" 8709 "UNION ALL " 8710 "SELECT rootpage, 1 FROM sqlite_schema" 8711 " WHERE name='%q' AND type='table'" 8712 " AND sql LIKE '%%without%%rowid%%'", 8713 azArg[1], azArg[1] 8714 ); 8715 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8716 sqlite3_free(zSql); 8717 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 8718 tnum = sqlite3_column_int(pStmt, 0); 8719 isWO = sqlite3_column_int(pStmt, 1); 8720 } 8721 sqlite3_finalize(pStmt); 8722 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 8723 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8724 sqlite3_free(zSql); 8725 i = 0; 8726 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8727 char zLabel[20]; 8728 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 8729 i++; 8730 if( zCol==0 ){ 8731 if( sqlite3_column_int(pStmt,1)==-1 ){ 8732 zCol = "_ROWID_"; 8733 }else{ 8734 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 8735 zCol = zLabel; 8736 } 8737 } 8738 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ 8739 lenPK = (int)strlen(zCollist); 8740 } 8741 if( zCollist==0 ){ 8742 zCollist = sqlite3_mprintf("\"%w\"", zCol); 8743 }else{ 8744 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 8745 } 8746 } 8747 sqlite3_finalize(pStmt); 8748 if( i==0 || tnum==0 ){ 8749 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 8750 rc = 1; 8751 sqlite3_free(zCollist); 8752 goto meta_command_exit; 8753 } 8754 if( lenPK==0 ) lenPK = 100000; 8755 zSql = sqlite3_mprintf( 8756 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", 8757 azArg[2], zCollist, lenPK, zCollist); 8758 sqlite3_free(zCollist); 8759 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 8760 if( rc==SQLITE_OK ){ 8761 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 8762 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 8763 if( rc ){ 8764 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 8765 }else{ 8766 utf8_printf(stdout, "%s;\n", zSql); 8767 raw_printf(stdout, 8768 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n", 8769 azArg[1], isWO ? "table" : "index" 8770 ); 8771 } 8772 }else{ 8773 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 8774 rc = 1; 8775 } 8776 sqlite3_free(zSql); 8777 }else 8778#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 8779 8780#ifdef SQLITE_ENABLE_IOTRACE 8781 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 8782 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 8783 if( iotrace && iotrace!=stdout ) fclose(iotrace); 8784 iotrace = 0; 8785 if( nArg<2 ){ 8786 sqlite3IoTrace = 0; 8787 }else if( strcmp(azArg[1], "-")==0 ){ 8788 sqlite3IoTrace = iotracePrintf; 8789 iotrace = stdout; 8790 }else{ 8791 iotrace = fopen(azArg[1], "w"); 8792 if( iotrace==0 ){ 8793 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 8794 sqlite3IoTrace = 0; 8795 rc = 1; 8796 }else{ 8797 sqlite3IoTrace = iotracePrintf; 8798 } 8799 } 8800 }else 8801#endif 8802 8803 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 8804 static const struct { 8805 const char *zLimitName; /* Name of a limit */ 8806 int limitCode; /* Integer code for that limit */ 8807 } aLimit[] = { 8808 { "length", SQLITE_LIMIT_LENGTH }, 8809 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 8810 { "column", SQLITE_LIMIT_COLUMN }, 8811 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 8812 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 8813 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 8814 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 8815 { "attached", SQLITE_LIMIT_ATTACHED }, 8816 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 8817 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 8818 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 8819 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 8820 }; 8821 int i, n2; 8822 open_db(p, 0); 8823 if( nArg==1 ){ 8824 for(i=0; i<ArraySize(aLimit); i++){ 8825 printf("%20s %d\n", aLimit[i].zLimitName, 8826 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 8827 } 8828 }else if( nArg>3 ){ 8829 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 8830 rc = 1; 8831 goto meta_command_exit; 8832 }else{ 8833 int iLimit = -1; 8834 n2 = strlen30(azArg[1]); 8835 for(i=0; i<ArraySize(aLimit); i++){ 8836 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 8837 if( iLimit<0 ){ 8838 iLimit = i; 8839 }else{ 8840 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 8841 rc = 1; 8842 goto meta_command_exit; 8843 } 8844 } 8845 } 8846 if( iLimit<0 ){ 8847 utf8_printf(stderr, "unknown limit: \"%s\"\n" 8848 "enter \".limits\" with no arguments for a list.\n", 8849 azArg[1]); 8850 rc = 1; 8851 goto meta_command_exit; 8852 } 8853 if( nArg==3 ){ 8854 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 8855 (int)integerValue(azArg[2])); 8856 } 8857 printf("%20s %d\n", aLimit[iLimit].zLimitName, 8858 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 8859 } 8860 }else 8861 8862 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 8863 open_db(p, 0); 8864 lintDotCommand(p, azArg, nArg); 8865 }else 8866 8867#ifndef SQLITE_OMIT_LOAD_EXTENSION 8868 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 8869 const char *zFile, *zProc; 8870 char *zErrMsg = 0; 8871 failIfSafeMode(p, "cannot run .load in safe mode"); 8872 if( nArg<2 ){ 8873 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 8874 rc = 1; 8875 goto meta_command_exit; 8876 } 8877 zFile = azArg[1]; 8878 zProc = nArg>=3 ? azArg[2] : 0; 8879 open_db(p, 0); 8880 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 8881 if( rc!=SQLITE_OK ){ 8882 utf8_printf(stderr, "Error: %s\n", zErrMsg); 8883 sqlite3_free(zErrMsg); 8884 rc = 1; 8885 } 8886 }else 8887#endif 8888 8889 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 8890 failIfSafeMode(p, "cannot run .log in safe mode"); 8891 if( nArg!=2 ){ 8892 raw_printf(stderr, "Usage: .log FILENAME\n"); 8893 rc = 1; 8894 }else{ 8895 const char *zFile = azArg[1]; 8896 output_file_close(p->pLog); 8897 p->pLog = output_file_open(zFile, 0); 8898 } 8899 }else 8900 8901 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 8902 const char *zMode = nArg>=2 ? azArg[1] : ""; 8903 int n2 = strlen30(zMode); 8904 int c2 = zMode[0]; 8905 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 8906 p->mode = MODE_Line; 8907 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8908 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 8909 p->mode = MODE_Column; 8910 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ 8911 p->showHeader = 1; 8912 } 8913 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8914 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 8915 p->mode = MODE_List; 8916 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 8917 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8918 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 8919 p->mode = MODE_Html; 8920 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 8921 p->mode = MODE_Tcl; 8922 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 8923 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8924 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 8925 p->mode = MODE_Csv; 8926 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8927 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8928 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 8929 p->mode = MODE_List; 8930 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 8931 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 8932 p->mode = MODE_Insert; 8933 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 8934 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 8935 p->mode = MODE_Quote; 8936 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8937 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8938 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 8939 p->mode = MODE_Ascii; 8940 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 8941 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 8942 }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){ 8943 p->mode = MODE_Markdown; 8944 }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){ 8945 p->mode = MODE_Table; 8946 }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){ 8947 p->mode = MODE_Box; 8948 }else if( c2=='c' && strncmp(azArg[1],"count",n2)==0 ){ 8949 p->mode = MODE_Count; 8950 }else if( c2=='o' && strncmp(azArg[1],"off",n2)==0 ){ 8951 p->mode = MODE_Off; 8952 }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){ 8953 p->mode = MODE_Json; 8954 }else if( nArg==1 ){ 8955 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 8956 }else{ 8957 raw_printf(stderr, "Error: mode should be one of: " 8958 "ascii box column csv html insert json line list markdown " 8959 "quote table tabs tcl\n"); 8960 rc = 1; 8961 } 8962 p->cMode = p->mode; 8963 }else 8964 8965 if( c=='n' && strcmp(azArg[0], "nonce")==0 ){ 8966 if( nArg!=2 ){ 8967 raw_printf(stderr, "Usage: .nonce NONCE\n"); 8968 rc = 1; 8969 }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){ 8970 raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", 8971 p->lineno, azArg[1]); 8972 exit(1); 8973 }else{ 8974 p->bSafeMode = 0; 8975 return 0; /* Return immediately to bypass the safe mode reset 8976 ** at the end of this procedure */ 8977 } 8978 }else 8979 8980 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 8981 if( nArg==2 ){ 8982 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 8983 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 8984 }else{ 8985 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 8986 rc = 1; 8987 } 8988 }else 8989 8990 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 8991 const char *zFN = 0; /* Pointer to constant filename */ 8992 char *zNewFilename = 0; /* Name of the database file to open */ 8993 int iName = 1; /* Index in azArg[] of the filename */ 8994 int newFlag = 0; /* True to delete file before opening */ 8995 int openMode = SHELL_OPEN_UNSPEC; 8996 8997 /* Check for command-line arguments */ 8998 for(iName=1; iName<nArg; iName++){ 8999 const char *z = azArg[iName]; 9000 if( optionMatch(z,"new") ){ 9001 newFlag = 1; 9002#ifdef SQLITE_HAVE_ZLIB 9003 }else if( optionMatch(z, "zip") ){ 9004 openMode = SHELL_OPEN_ZIPFILE; 9005#endif 9006 }else if( optionMatch(z, "append") ){ 9007 openMode = SHELL_OPEN_APPENDVFS; 9008 }else if( optionMatch(z, "readonly") ){ 9009 openMode = SHELL_OPEN_READONLY; 9010 }else if( optionMatch(z, "nofollow") ){ 9011 p->openFlags |= SQLITE_OPEN_NOFOLLOW; 9012#ifndef SQLITE_OMIT_DESERIALIZE 9013 }else if( optionMatch(z, "deserialize") ){ 9014 openMode = SHELL_OPEN_DESERIALIZE; 9015 }else if( optionMatch(z, "hexdb") ){ 9016 openMode = SHELL_OPEN_HEXDB; 9017 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 9018 p->szMax = integerValue(azArg[++iName]); 9019#endif /* SQLITE_OMIT_DESERIALIZE */ 9020 }else if( z[0]=='-' ){ 9021 utf8_printf(stderr, "unknown option: %s\n", z); 9022 rc = 1; 9023 goto meta_command_exit; 9024 }else if( zFN ){ 9025 utf8_printf(stderr, "extra argument: \"%s\"\n", z); 9026 rc = 1; 9027 goto meta_command_exit; 9028 }else{ 9029 zFN = z; 9030 } 9031 } 9032 9033 /* Close the existing database */ 9034 session_close_all(p, -1); 9035 close_db(p->db); 9036 p->db = 0; 9037 p->pAuxDb->zDbFilename = 0; 9038 sqlite3_free(p->pAuxDb->zFreeOnClose); 9039 p->pAuxDb->zFreeOnClose = 0; 9040 p->openMode = openMode; 9041 p->openFlags = 0; 9042 p->szMax = 0; 9043 9044 /* If a filename is specified, try to open it first */ 9045 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ 9046 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); 9047 if( p->bSafeMode 9048 && p->openMode!=SHELL_OPEN_HEXDB 9049 && zFN 9050 && strcmp(zFN,":memory:")!=0 9051 ){ 9052 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); 9053 } 9054 if( zFN ){ 9055 zNewFilename = sqlite3_mprintf("%s", zFN); 9056 shell_check_oom(zNewFilename); 9057 }else{ 9058 zNewFilename = 0; 9059 } 9060 p->pAuxDb->zDbFilename = zNewFilename; 9061 open_db(p, OPEN_DB_KEEPALIVE); 9062 if( p->db==0 ){ 9063 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 9064 sqlite3_free(zNewFilename); 9065 }else{ 9066 p->pAuxDb->zFreeOnClose = zNewFilename; 9067 } 9068 } 9069 if( p->db==0 ){ 9070 /* As a fall-back open a TEMP database */ 9071 p->pAuxDb->zDbFilename = 0; 9072 open_db(p, 0); 9073 } 9074 }else 9075 9076 if( (c=='o' 9077 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 9078 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 9079 ){ 9080 char *zFile = 0; 9081 int bTxtMode = 0; 9082 int i; 9083 int eMode = 0; 9084 int bBOM = 0; 9085 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */ 9086 9087 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 9088 if( c=='e' ){ 9089 eMode = 'x'; 9090 bOnce = 2; 9091 }else if( strncmp(azArg[0],"once",n)==0 ){ 9092 bOnce = 1; 9093 } 9094 for(i=1; i<nArg; i++){ 9095 char *z = azArg[i]; 9096 if( z[0]=='-' ){ 9097 if( z[1]=='-' ) z++; 9098 if( strcmp(z,"-bom")==0 ){ 9099 bBOM = 1; 9100 }else if( c!='e' && strcmp(z,"-x")==0 ){ 9101 eMode = 'x'; /* spreadsheet */ 9102 }else if( c!='e' && strcmp(z,"-e")==0 ){ 9103 eMode = 'e'; /* text editor */ 9104 }else{ 9105 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", 9106 azArg[i]); 9107 showHelp(p->out, azArg[0]); 9108 rc = 1; 9109 goto meta_command_exit; 9110 } 9111 }else if( zFile==0 && eMode!='e' && eMode!='x' ){ 9112 zFile = sqlite3_mprintf("%s", z); 9113 if( zFile && zFile[0]=='|' ){ 9114 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]); 9115 break; 9116 } 9117 }else{ 9118 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n", 9119 azArg[i]); 9120 showHelp(p->out, azArg[0]); 9121 rc = 1; 9122 sqlite3_free(zFile); 9123 goto meta_command_exit; 9124 } 9125 } 9126 if( zFile==0 ){ 9127 zFile = sqlite3_mprintf("stdout"); 9128 } 9129 if( bOnce ){ 9130 p->outCount = 2; 9131 }else{ 9132 p->outCount = 0; 9133 } 9134 output_reset(p); 9135#ifndef SQLITE_NOHAVE_SYSTEM 9136 if( eMode=='e' || eMode=='x' ){ 9137 p->doXdgOpen = 1; 9138 outputModePush(p); 9139 if( eMode=='x' ){ 9140 /* spreadsheet mode. Output as CSV. */ 9141 newTempFile(p, "csv"); 9142 ShellClearFlag(p, SHFLG_Echo); 9143 p->mode = MODE_Csv; 9144 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 9145 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 9146 }else{ 9147 /* text editor mode */ 9148 newTempFile(p, "txt"); 9149 bTxtMode = 1; 9150 } 9151 sqlite3_free(zFile); 9152 zFile = sqlite3_mprintf("%s", p->zTempFile); 9153 } 9154#endif /* SQLITE_NOHAVE_SYSTEM */ 9155 shell_check_oom(zFile); 9156 if( zFile[0]=='|' ){ 9157#ifdef SQLITE_OMIT_POPEN 9158 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9159 rc = 1; 9160 p->out = stdout; 9161#else 9162 p->out = popen(zFile + 1, "w"); 9163 if( p->out==0 ){ 9164 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 9165 p->out = stdout; 9166 rc = 1; 9167 }else{ 9168 if( bBOM ) fprintf(p->out,"\357\273\277"); 9169 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9170 } 9171#endif 9172 }else{ 9173 p->out = output_file_open(zFile, bTxtMode); 9174 if( p->out==0 ){ 9175 if( strcmp(zFile,"off")!=0 ){ 9176 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 9177 } 9178 p->out = stdout; 9179 rc = 1; 9180 } else { 9181 if( bBOM ) fprintf(p->out,"\357\273\277"); 9182 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9183 } 9184 } 9185 sqlite3_free(zFile); 9186 }else 9187 9188 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 9189 open_db(p,0); 9190 if( nArg<=1 ) goto parameter_syntax_error; 9191 9192 /* .parameter clear 9193 ** Clear all bind parameters by dropping the TEMP table that holds them. 9194 */ 9195 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 9196 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 9197 0, 0, 0); 9198 }else 9199 9200 /* .parameter list 9201 ** List all bind parameters. 9202 */ 9203 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 9204 sqlite3_stmt *pStmt = 0; 9205 int rx; 9206 int len = 0; 9207 rx = sqlite3_prepare_v2(p->db, 9208 "SELECT max(length(key)) " 9209 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9210 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9211 len = sqlite3_column_int(pStmt, 0); 9212 if( len>40 ) len = 40; 9213 } 9214 sqlite3_finalize(pStmt); 9215 pStmt = 0; 9216 if( len ){ 9217 rx = sqlite3_prepare_v2(p->db, 9218 "SELECT key, quote(value) " 9219 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9220 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9221 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 9222 sqlite3_column_text(pStmt,1)); 9223 } 9224 sqlite3_finalize(pStmt); 9225 } 9226 }else 9227 9228 /* .parameter init 9229 ** Make sure the TEMP table used to hold bind parameters exists. 9230 ** Create it if necessary. 9231 */ 9232 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 9233 bind_table_init(p); 9234 }else 9235 9236 /* .parameter set NAME VALUE 9237 ** Set or reset a bind parameter. NAME should be the full parameter 9238 ** name exactly as it appears in the query. (ex: $abc, @def). The 9239 ** VALUE can be in either SQL literal notation, or if not it will be 9240 ** understood to be a text string. 9241 */ 9242 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 9243 int rx; 9244 char *zSql; 9245 sqlite3_stmt *pStmt; 9246 const char *zKey = azArg[2]; 9247 const char *zValue = azArg[3]; 9248 bind_table_init(p); 9249 zSql = sqlite3_mprintf( 9250 "REPLACE INTO temp.sqlite_parameters(key,value)" 9251 "VALUES(%Q,%s);", zKey, zValue); 9252 shell_check_oom(zSql); 9253 pStmt = 0; 9254 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9255 sqlite3_free(zSql); 9256 if( rx!=SQLITE_OK ){ 9257 sqlite3_finalize(pStmt); 9258 pStmt = 0; 9259 zSql = sqlite3_mprintf( 9260 "REPLACE INTO temp.sqlite_parameters(key,value)" 9261 "VALUES(%Q,%Q);", zKey, zValue); 9262 shell_check_oom(zSql); 9263 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9264 sqlite3_free(zSql); 9265 if( rx!=SQLITE_OK ){ 9266 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 9267 sqlite3_finalize(pStmt); 9268 pStmt = 0; 9269 rc = 1; 9270 } 9271 } 9272 sqlite3_step(pStmt); 9273 sqlite3_finalize(pStmt); 9274 }else 9275 9276 /* .parameter unset NAME 9277 ** Remove the NAME binding from the parameter binding table, if it 9278 ** exists. 9279 */ 9280 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 9281 char *zSql = sqlite3_mprintf( 9282 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 9283 shell_check_oom(zSql); 9284 sqlite3_exec(p->db, zSql, 0, 0, 0); 9285 sqlite3_free(zSql); 9286 }else 9287 /* If no command name matches, show a syntax error */ 9288 parameter_syntax_error: 9289 showHelp(p->out, "parameter"); 9290 }else 9291 9292 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 9293 int i; 9294 for(i=1; i<nArg; i++){ 9295 if( i>1 ) raw_printf(p->out, " "); 9296 utf8_printf(p->out, "%s", azArg[i]); 9297 } 9298 raw_printf(p->out, "\n"); 9299 }else 9300 9301#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 9302 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 9303 int i; 9304 int nn = 0; 9305 p->flgProgress = 0; 9306 p->mxProgress = 0; 9307 p->nProgress = 0; 9308 for(i=1; i<nArg; i++){ 9309 const char *z = azArg[i]; 9310 if( z[0]=='-' ){ 9311 z++; 9312 if( z[0]=='-' ) z++; 9313 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 9314 p->flgProgress |= SHELL_PROGRESS_QUIET; 9315 continue; 9316 } 9317 if( strcmp(z,"reset")==0 ){ 9318 p->flgProgress |= SHELL_PROGRESS_RESET; 9319 continue; 9320 } 9321 if( strcmp(z,"once")==0 ){ 9322 p->flgProgress |= SHELL_PROGRESS_ONCE; 9323 continue; 9324 } 9325 if( strcmp(z,"limit")==0 ){ 9326 if( i+1>=nArg ){ 9327 utf8_printf(stderr, "Error: missing argument on --limit\n"); 9328 rc = 1; 9329 goto meta_command_exit; 9330 }else{ 9331 p->mxProgress = (int)integerValue(azArg[++i]); 9332 } 9333 continue; 9334 } 9335 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 9336 rc = 1; 9337 goto meta_command_exit; 9338 }else{ 9339 nn = (int)integerValue(z); 9340 } 9341 } 9342 open_db(p, 0); 9343 sqlite3_progress_handler(p->db, nn, progress_handler, p); 9344 }else 9345#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 9346 9347 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 9348 if( nArg >= 2) { 9349 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 9350 } 9351 if( nArg >= 3) { 9352 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 9353 } 9354 }else 9355 9356 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 9357 rc = 2; 9358 }else 9359 9360 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 9361 FILE *inSaved = p->in; 9362 int savedLineno = p->lineno; 9363 failIfSafeMode(p, "cannot run .read in safe mode"); 9364 if( nArg!=2 ){ 9365 raw_printf(stderr, "Usage: .read FILE\n"); 9366 rc = 1; 9367 goto meta_command_exit; 9368 } 9369 if( azArg[1][0]=='|' ){ 9370#ifdef SQLITE_OMIT_POPEN 9371 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9372 rc = 1; 9373 p->out = stdout; 9374#else 9375 p->in = popen(azArg[1]+1, "r"); 9376 if( p->in==0 ){ 9377 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 9378 rc = 1; 9379 }else{ 9380 rc = process_input(p); 9381 pclose(p->in); 9382 } 9383#endif 9384 }else if( (p->in = openChrSource(azArg[1]))==0 ){ 9385 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 9386 rc = 1; 9387 }else{ 9388 rc = process_input(p); 9389 fclose(p->in); 9390 } 9391 p->in = inSaved; 9392 p->lineno = savedLineno; 9393 }else 9394 9395 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 9396 const char *zSrcFile; 9397 const char *zDb; 9398 sqlite3 *pSrc; 9399 sqlite3_backup *pBackup; 9400 int nTimeout = 0; 9401 9402 failIfSafeMode(p, "cannot run .restore in safe mode"); 9403 if( nArg==2 ){ 9404 zSrcFile = azArg[1]; 9405 zDb = "main"; 9406 }else if( nArg==3 ){ 9407 zSrcFile = azArg[2]; 9408 zDb = azArg[1]; 9409 }else{ 9410 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 9411 rc = 1; 9412 goto meta_command_exit; 9413 } 9414 rc = sqlite3_open(zSrcFile, &pSrc); 9415 if( rc!=SQLITE_OK ){ 9416 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 9417 close_db(pSrc); 9418 return 1; 9419 } 9420 open_db(p, 0); 9421 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 9422 if( pBackup==0 ){ 9423 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9424 close_db(pSrc); 9425 return 1; 9426 } 9427 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 9428 || rc==SQLITE_BUSY ){ 9429 if( rc==SQLITE_BUSY ){ 9430 if( nTimeout++ >= 3 ) break; 9431 sqlite3_sleep(100); 9432 } 9433 } 9434 sqlite3_backup_finish(pBackup); 9435 if( rc==SQLITE_DONE ){ 9436 rc = 0; 9437 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 9438 raw_printf(stderr, "Error: source database is busy\n"); 9439 rc = 1; 9440 }else{ 9441 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9442 rc = 1; 9443 } 9444 close_db(pSrc); 9445 }else 9446 9447 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 9448 if( nArg==2 ){ 9449 p->scanstatsOn = (u8)booleanValue(azArg[1]); 9450#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 9451 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 9452#endif 9453 }else{ 9454 raw_printf(stderr, "Usage: .scanstats on|off\n"); 9455 rc = 1; 9456 } 9457 }else 9458 9459 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 9460 ShellText sSelect; 9461 ShellState data; 9462 char *zErrMsg = 0; 9463 const char *zDiv = "("; 9464 const char *zName = 0; 9465 int iSchema = 0; 9466 int bDebug = 0; 9467 int bNoSystemTabs = 0; 9468 int ii; 9469 9470 open_db(p, 0); 9471 memcpy(&data, p, sizeof(data)); 9472 data.showHeader = 0; 9473 data.cMode = data.mode = MODE_Semi; 9474 initText(&sSelect); 9475 for(ii=1; ii<nArg; ii++){ 9476 if( optionMatch(azArg[ii],"indent") ){ 9477 data.cMode = data.mode = MODE_Pretty; 9478 }else if( optionMatch(azArg[ii],"debug") ){ 9479 bDebug = 1; 9480 }else if( optionMatch(azArg[ii],"nosys") ){ 9481 bNoSystemTabs = 1; 9482 }else if( azArg[ii][0]=='-' ){ 9483 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]); 9484 rc = 1; 9485 goto meta_command_exit; 9486 }else if( zName==0 ){ 9487 zName = azArg[ii]; 9488 }else{ 9489 raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); 9490 rc = 1; 9491 goto meta_command_exit; 9492 } 9493 } 9494 if( zName!=0 ){ 9495 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0 9496 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0 9497 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 9498 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0; 9499 if( isSchema ){ 9500 char *new_argv[2], *new_colv[2]; 9501 new_argv[0] = sqlite3_mprintf( 9502 "CREATE TABLE %s (\n" 9503 " type text,\n" 9504 " name text,\n" 9505 " tbl_name text,\n" 9506 " rootpage integer,\n" 9507 " sql text\n" 9508 ")", zName); 9509 shell_check_oom(new_argv[0]); 9510 new_argv[1] = 0; 9511 new_colv[0] = "sql"; 9512 new_colv[1] = 0; 9513 callback(&data, 1, new_argv, new_colv); 9514 sqlite3_free(new_argv[0]); 9515 } 9516 } 9517 if( zDiv ){ 9518 sqlite3_stmt *pStmt = 0; 9519 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 9520 -1, &pStmt, 0); 9521 if( rc ){ 9522 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9523 sqlite3_finalize(pStmt); 9524 rc = 1; 9525 goto meta_command_exit; 9526 } 9527 appendText(&sSelect, "SELECT sql FROM", 0); 9528 iSchema = 0; 9529 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9530 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 9531 char zScNum[30]; 9532 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 9533 appendText(&sSelect, zDiv, 0); 9534 zDiv = " UNION ALL "; 9535 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 9536 if( sqlite3_stricmp(zDb, "main")!=0 ){ 9537 appendText(&sSelect, zDb, '\''); 9538 }else{ 9539 appendText(&sSelect, "NULL", 0); 9540 } 9541 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 9542 appendText(&sSelect, zScNum, 0); 9543 appendText(&sSelect, " AS snum, ", 0); 9544 appendText(&sSelect, zDb, '\''); 9545 appendText(&sSelect, " AS sname FROM ", 0); 9546 appendText(&sSelect, zDb, quoteChar(zDb)); 9547 appendText(&sSelect, ".sqlite_schema", 0); 9548 } 9549 sqlite3_finalize(pStmt); 9550#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 9551 if( zName ){ 9552 appendText(&sSelect, 9553 " UNION ALL SELECT shell_module_schema(name)," 9554 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 9555 0); 9556 } 9557#endif 9558 appendText(&sSelect, ") WHERE ", 0); 9559 if( zName ){ 9560 char *zQarg = sqlite3_mprintf("%Q", zName); 9561 int bGlob; 9562 shell_check_oom(zQarg); 9563 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 9564 strchr(zName, '[') != 0; 9565 if( strchr(zName, '.') ){ 9566 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 9567 }else{ 9568 appendText(&sSelect, "lower(tbl_name)", 0); 9569 } 9570 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 9571 appendText(&sSelect, zQarg, 0); 9572 if( !bGlob ){ 9573 appendText(&sSelect, " ESCAPE '\\' ", 0); 9574 } 9575 appendText(&sSelect, " AND ", 0); 9576 sqlite3_free(zQarg); 9577 } 9578 if( bNoSystemTabs ){ 9579 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0); 9580 } 9581 appendText(&sSelect, "sql IS NOT NULL" 9582 " ORDER BY snum, rowid", 0); 9583 if( bDebug ){ 9584 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 9585 }else{ 9586 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 9587 } 9588 freeText(&sSelect); 9589 } 9590 if( zErrMsg ){ 9591 utf8_printf(stderr,"Error: %s\n", zErrMsg); 9592 sqlite3_free(zErrMsg); 9593 rc = 1; 9594 }else if( rc != SQLITE_OK ){ 9595 raw_printf(stderr,"Error: querying schema information\n"); 9596 rc = 1; 9597 }else{ 9598 rc = 0; 9599 } 9600 }else 9601 9602 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 9603 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 9604 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x); 9605 }else 9606 9607#if defined(SQLITE_ENABLE_SESSION) 9608 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 9609 struct AuxDb *pAuxDb = p->pAuxDb; 9610 OpenSession *pSession = &pAuxDb->aSession[0]; 9611 char **azCmd = &azArg[1]; 9612 int iSes = 0; 9613 int nCmd = nArg - 1; 9614 int i; 9615 if( nArg<=1 ) goto session_syntax_error; 9616 open_db(p, 0); 9617 if( nArg>=3 ){ 9618 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ 9619 if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; 9620 } 9621 if( iSes<pAuxDb->nSession ){ 9622 pSession = &pAuxDb->aSession[iSes]; 9623 azCmd++; 9624 nCmd--; 9625 }else{ 9626 pSession = &pAuxDb->aSession[0]; 9627 iSes = 0; 9628 } 9629 } 9630 9631 /* .session attach TABLE 9632 ** Invoke the sqlite3session_attach() interface to attach a particular 9633 ** table so that it is never filtered. 9634 */ 9635 if( strcmp(azCmd[0],"attach")==0 ){ 9636 if( nCmd!=2 ) goto session_syntax_error; 9637 if( pSession->p==0 ){ 9638 session_not_open: 9639 raw_printf(stderr, "ERROR: No sessions are open\n"); 9640 }else{ 9641 rc = sqlite3session_attach(pSession->p, azCmd[1]); 9642 if( rc ){ 9643 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 9644 rc = 0; 9645 } 9646 } 9647 }else 9648 9649 /* .session changeset FILE 9650 ** .session patchset FILE 9651 ** Write a changeset or patchset into a file. The file is overwritten. 9652 */ 9653 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 9654 FILE *out = 0; 9655 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]); 9656 if( nCmd!=2 ) goto session_syntax_error; 9657 if( pSession->p==0 ) goto session_not_open; 9658 out = fopen(azCmd[1], "wb"); 9659 if( out==0 ){ 9660 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", 9661 azCmd[1]); 9662 }else{ 9663 int szChng; 9664 void *pChng; 9665 if( azCmd[0][0]=='c' ){ 9666 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 9667 }else{ 9668 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 9669 } 9670 if( rc ){ 9671 printf("Error: error code %d\n", rc); 9672 rc = 0; 9673 } 9674 if( pChng 9675 && fwrite(pChng, szChng, 1, out)!=1 ){ 9676 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 9677 szChng); 9678 } 9679 sqlite3_free(pChng); 9680 fclose(out); 9681 } 9682 }else 9683 9684 /* .session close 9685 ** Close the identified session 9686 */ 9687 if( strcmp(azCmd[0], "close")==0 ){ 9688 if( nCmd!=1 ) goto session_syntax_error; 9689 if( pAuxDb->nSession ){ 9690 session_close(pSession); 9691 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; 9692 } 9693 }else 9694 9695 /* .session enable ?BOOLEAN? 9696 ** Query or set the enable flag 9697 */ 9698 if( strcmp(azCmd[0], "enable")==0 ){ 9699 int ii; 9700 if( nCmd>2 ) goto session_syntax_error; 9701 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9702 if( pAuxDb->nSession ){ 9703 ii = sqlite3session_enable(pSession->p, ii); 9704 utf8_printf(p->out, "session %s enable flag = %d\n", 9705 pSession->zName, ii); 9706 } 9707 }else 9708 9709 /* .session filter GLOB .... 9710 ** Set a list of GLOB patterns of table names to be excluded. 9711 */ 9712 if( strcmp(azCmd[0], "filter")==0 ){ 9713 int ii, nByte; 9714 if( nCmd<2 ) goto session_syntax_error; 9715 if( pAuxDb->nSession ){ 9716 for(ii=0; ii<pSession->nFilter; ii++){ 9717 sqlite3_free(pSession->azFilter[ii]); 9718 } 9719 sqlite3_free(pSession->azFilter); 9720 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 9721 pSession->azFilter = sqlite3_malloc( nByte ); 9722 if( pSession->azFilter==0 ){ 9723 raw_printf(stderr, "Error: out or memory\n"); 9724 exit(1); 9725 } 9726 for(ii=1; ii<nCmd; ii++){ 9727 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 9728 shell_check_oom(x); 9729 } 9730 pSession->nFilter = ii-1; 9731 } 9732 }else 9733 9734 /* .session indirect ?BOOLEAN? 9735 ** Query or set the indirect flag 9736 */ 9737 if( strcmp(azCmd[0], "indirect")==0 ){ 9738 int ii; 9739 if( nCmd>2 ) goto session_syntax_error; 9740 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9741 if( pAuxDb->nSession ){ 9742 ii = sqlite3session_indirect(pSession->p, ii); 9743 utf8_printf(p->out, "session %s indirect flag = %d\n", 9744 pSession->zName, ii); 9745 } 9746 }else 9747 9748 /* .session isempty 9749 ** Determine if the session is empty 9750 */ 9751 if( strcmp(azCmd[0], "isempty")==0 ){ 9752 int ii; 9753 if( nCmd!=1 ) goto session_syntax_error; 9754 if( pAuxDb->nSession ){ 9755 ii = sqlite3session_isempty(pSession->p); 9756 utf8_printf(p->out, "session %s isempty flag = %d\n", 9757 pSession->zName, ii); 9758 } 9759 }else 9760 9761 /* .session list 9762 ** List all currently open sessions 9763 */ 9764 if( strcmp(azCmd[0],"list")==0 ){ 9765 for(i=0; i<pAuxDb->nSession; i++){ 9766 utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); 9767 } 9768 }else 9769 9770 /* .session open DB NAME 9771 ** Open a new session called NAME on the attached database DB. 9772 ** DB is normally "main". 9773 */ 9774 if( strcmp(azCmd[0],"open")==0 ){ 9775 char *zName; 9776 if( nCmd!=3 ) goto session_syntax_error; 9777 zName = azCmd[2]; 9778 if( zName[0]==0 ) goto session_syntax_error; 9779 for(i=0; i<pAuxDb->nSession; i++){ 9780 if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ 9781 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 9782 goto meta_command_exit; 9783 } 9784 } 9785 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ 9786 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); 9787 goto meta_command_exit; 9788 } 9789 pSession = &pAuxDb->aSession[pAuxDb->nSession]; 9790 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 9791 if( rc ){ 9792 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 9793 rc = 0; 9794 goto meta_command_exit; 9795 } 9796 pSession->nFilter = 0; 9797 sqlite3session_table_filter(pSession->p, session_filter, pSession); 9798 pAuxDb->nSession++; 9799 pSession->zName = sqlite3_mprintf("%s", zName); 9800 shell_check_oom(pSession->zName); 9801 }else 9802 /* If no command name matches, show a syntax error */ 9803 session_syntax_error: 9804 showHelp(p->out, "session"); 9805 }else 9806#endif 9807 9808#ifdef SQLITE_DEBUG 9809 /* Undocumented commands for internal testing. Subject to change 9810 ** without notice. */ 9811 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 9812 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 9813 int i, v; 9814 for(i=1; i<nArg; i++){ 9815 v = booleanValue(azArg[i]); 9816 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 9817 } 9818 } 9819 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 9820 int i; sqlite3_int64 v; 9821 for(i=1; i<nArg; i++){ 9822 char zBuf[200]; 9823 v = integerValue(azArg[i]); 9824 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 9825 utf8_printf(p->out, "%s", zBuf); 9826 } 9827 } 9828 }else 9829#endif 9830 9831 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 9832 int bIsInit = 0; /* True to initialize the SELFTEST table */ 9833 int bVerbose = 0; /* Verbose output */ 9834 int bSelftestExists; /* True if SELFTEST already exists */ 9835 int i, k; /* Loop counters */ 9836 int nTest = 0; /* Number of tests runs */ 9837 int nErr = 0; /* Number of errors seen */ 9838 ShellText str; /* Answer for a query */ 9839 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 9840 9841 open_db(p,0); 9842 for(i=1; i<nArg; i++){ 9843 const char *z = azArg[i]; 9844 if( z[0]=='-' && z[1]=='-' ) z++; 9845 if( strcmp(z,"-init")==0 ){ 9846 bIsInit = 1; 9847 }else 9848 if( strcmp(z,"-v")==0 ){ 9849 bVerbose++; 9850 }else 9851 { 9852 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9853 azArg[i], azArg[0]); 9854 raw_printf(stderr, "Should be one of: --init -v\n"); 9855 rc = 1; 9856 goto meta_command_exit; 9857 } 9858 } 9859 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 9860 != SQLITE_OK ){ 9861 bSelftestExists = 0; 9862 }else{ 9863 bSelftestExists = 1; 9864 } 9865 if( bIsInit ){ 9866 createSelftestTable(p); 9867 bSelftestExists = 1; 9868 } 9869 initText(&str); 9870 appendText(&str, "x", 0); 9871 for(k=bSelftestExists; k>=0; k--){ 9872 if( k==1 ){ 9873 rc = sqlite3_prepare_v2(p->db, 9874 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 9875 -1, &pStmt, 0); 9876 }else{ 9877 rc = sqlite3_prepare_v2(p->db, 9878 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 9879 " (1,'run','PRAGMA integrity_check','ok')", 9880 -1, &pStmt, 0); 9881 } 9882 if( rc ){ 9883 raw_printf(stderr, "Error querying the selftest table\n"); 9884 rc = 1; 9885 sqlite3_finalize(pStmt); 9886 goto meta_command_exit; 9887 } 9888 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 9889 int tno = sqlite3_column_int(pStmt, 0); 9890 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 9891 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 9892 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 9893 9894 if( zOp==0 ) continue; 9895 if( zSql==0 ) continue; 9896 if( zAns==0 ) continue; 9897 k = 0; 9898 if( bVerbose>0 ){ 9899 printf("%d: %s %s\n", tno, zOp, zSql); 9900 } 9901 if( strcmp(zOp,"memo")==0 ){ 9902 utf8_printf(p->out, "%s\n", zSql); 9903 }else 9904 if( strcmp(zOp,"run")==0 ){ 9905 char *zErrMsg = 0; 9906 str.n = 0; 9907 str.z[0] = 0; 9908 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 9909 nTest++; 9910 if( bVerbose ){ 9911 utf8_printf(p->out, "Result: %s\n", str.z); 9912 } 9913 if( rc || zErrMsg ){ 9914 nErr++; 9915 rc = 1; 9916 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 9917 sqlite3_free(zErrMsg); 9918 }else if( strcmp(zAns,str.z)!=0 ){ 9919 nErr++; 9920 rc = 1; 9921 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 9922 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 9923 } 9924 }else 9925 { 9926 utf8_printf(stderr, 9927 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 9928 rc = 1; 9929 break; 9930 } 9931 } /* End loop over rows of content from SELFTEST */ 9932 sqlite3_finalize(pStmt); 9933 } /* End loop over k */ 9934 freeText(&str); 9935 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 9936 }else 9937 9938 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 9939 if( nArg<2 || nArg>3 ){ 9940 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 9941 rc = 1; 9942 } 9943 if( nArg>=2 ){ 9944 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 9945 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 9946 } 9947 if( nArg>=3 ){ 9948 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 9949 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 9950 } 9951 }else 9952 9953 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 9954 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 9955 int i; /* Loop counter */ 9956 int bSchema = 0; /* Also hash the schema */ 9957 int bSeparate = 0; /* Hash each table separately */ 9958 int iSize = 224; /* Hash algorithm to use */ 9959 int bDebug = 0; /* Only show the query that would have run */ 9960 sqlite3_stmt *pStmt; /* For querying tables names */ 9961 char *zSql; /* SQL to be run */ 9962 char *zSep; /* Separator */ 9963 ShellText sSql; /* Complete SQL for the query to run the hash */ 9964 ShellText sQuery; /* Set of queries used to read all content */ 9965 open_db(p, 0); 9966 for(i=1; i<nArg; i++){ 9967 const char *z = azArg[i]; 9968 if( z[0]=='-' ){ 9969 z++; 9970 if( z[0]=='-' ) z++; 9971 if( strcmp(z,"schema")==0 ){ 9972 bSchema = 1; 9973 }else 9974 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 9975 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 9976 ){ 9977 iSize = atoi(&z[5]); 9978 }else 9979 if( strcmp(z,"debug")==0 ){ 9980 bDebug = 1; 9981 }else 9982 { 9983 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9984 azArg[i], azArg[0]); 9985 showHelp(p->out, azArg[0]); 9986 rc = 1; 9987 goto meta_command_exit; 9988 } 9989 }else if( zLike ){ 9990 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 9991 rc = 1; 9992 goto meta_command_exit; 9993 }else{ 9994 zLike = z; 9995 bSeparate = 1; 9996 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 9997 } 9998 } 9999 if( bSchema ){ 10000 zSql = "SELECT lower(name) FROM sqlite_schema" 10001 " WHERE type='table' AND coalesce(rootpage,0)>1" 10002 " UNION ALL SELECT 'sqlite_schema'" 10003 " ORDER BY 1 collate nocase"; 10004 }else{ 10005 zSql = "SELECT lower(name) FROM sqlite_schema" 10006 " WHERE type='table' AND coalesce(rootpage,0)>1" 10007 " AND name NOT LIKE 'sqlite_%'" 10008 " ORDER BY 1 collate nocase"; 10009 } 10010 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 10011 initText(&sQuery); 10012 initText(&sSql); 10013 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 10014 zSep = "VALUES("; 10015 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 10016 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 10017 if( zTab==0 ) continue; 10018 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 10019 if( strncmp(zTab, "sqlite_",7)!=0 ){ 10020 appendText(&sQuery,"SELECT * FROM ", 0); 10021 appendText(&sQuery,zTab,'"'); 10022 appendText(&sQuery," NOT INDEXED;", 0); 10023 }else if( strcmp(zTab, "sqlite_schema")==0 ){ 10024 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" 10025 " ORDER BY name;", 0); 10026 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 10027 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 10028 " ORDER BY name;", 0); 10029 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 10030 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 10031 " ORDER BY tbl,idx;", 0); 10032 }else if( strcmp(zTab, "sqlite_stat4")==0 ){ 10033 appendText(&sQuery, "SELECT * FROM ", 0); 10034 appendText(&sQuery, zTab, 0); 10035 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 10036 } 10037 appendText(&sSql, zSep, 0); 10038 appendText(&sSql, sQuery.z, '\''); 10039 sQuery.n = 0; 10040 appendText(&sSql, ",", 0); 10041 appendText(&sSql, zTab, '\''); 10042 zSep = "),("; 10043 } 10044 sqlite3_finalize(pStmt); 10045 if( bSeparate ){ 10046 zSql = sqlite3_mprintf( 10047 "%s))" 10048 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 10049 " FROM [sha3sum$query]", 10050 sSql.z, iSize); 10051 }else{ 10052 zSql = sqlite3_mprintf( 10053 "%s))" 10054 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 10055 " FROM [sha3sum$query]", 10056 sSql.z, iSize); 10057 } 10058 shell_check_oom(zSql); 10059 freeText(&sQuery); 10060 freeText(&sSql); 10061 if( bDebug ){ 10062 utf8_printf(p->out, "%s\n", zSql); 10063 }else{ 10064 shell_exec(p, zSql, 0); 10065 } 10066 sqlite3_free(zSql); 10067 }else 10068 10069#ifndef SQLITE_NOHAVE_SYSTEM 10070 if( c=='s' 10071 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 10072 ){ 10073 char *zCmd; 10074 int i, x; 10075 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 10076 if( nArg<2 ){ 10077 raw_printf(stderr, "Usage: .system COMMAND\n"); 10078 rc = 1; 10079 goto meta_command_exit; 10080 } 10081 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 10082 for(i=2; i<nArg && zCmd!=0; i++){ 10083 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 10084 zCmd, azArg[i]); 10085 } 10086 x = zCmd!=0 ? system(zCmd) : 1; 10087 sqlite3_free(zCmd); 10088 if( x ) raw_printf(stderr, "System command returns %d\n", x); 10089 }else 10090#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 10091 10092 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 10093 static const char *azBool[] = { "off", "on", "trigger", "full"}; 10094 const char *zOut; 10095 int i; 10096 if( nArg!=1 ){ 10097 raw_printf(stderr, "Usage: .show\n"); 10098 rc = 1; 10099 goto meta_command_exit; 10100 } 10101 utf8_printf(p->out, "%12.12s: %s\n","echo", 10102 azBool[ShellHasFlag(p, SHFLG_Echo)]); 10103 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 10104 utf8_printf(p->out, "%12.12s: %s\n","explain", 10105 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 10106 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 10107 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 10108 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 10109 output_c_string(p->out, p->nullValue); 10110 raw_printf(p->out, "\n"); 10111 utf8_printf(p->out,"%12.12s: %s\n","output", 10112 strlen30(p->outfile) ? p->outfile : "stdout"); 10113 utf8_printf(p->out,"%12.12s: ", "colseparator"); 10114 output_c_string(p->out, p->colSeparator); 10115 raw_printf(p->out, "\n"); 10116 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 10117 output_c_string(p->out, p->rowSeparator); 10118 raw_printf(p->out, "\n"); 10119 switch( p->statsOn ){ 10120 case 0: zOut = "off"; break; 10121 default: zOut = "on"; break; 10122 case 2: zOut = "stmt"; break; 10123 case 3: zOut = "vmstep"; break; 10124 } 10125 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut); 10126 utf8_printf(p->out, "%12.12s: ", "width"); 10127 for (i=0;i<p->nWidth;i++) { 10128 raw_printf(p->out, "%d ", p->colWidth[i]); 10129 } 10130 raw_printf(p->out, "\n"); 10131 utf8_printf(p->out, "%12.12s: %s\n", "filename", 10132 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); 10133 }else 10134 10135 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 10136 if( nArg==2 ){ 10137 if( strcmp(azArg[1],"stmt")==0 ){ 10138 p->statsOn = 2; 10139 }else if( strcmp(azArg[1],"vmstep")==0 ){ 10140 p->statsOn = 3; 10141 }else{ 10142 p->statsOn = (u8)booleanValue(azArg[1]); 10143 } 10144 }else if( nArg==1 ){ 10145 display_stats(p->db, p, 0); 10146 }else{ 10147 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n"); 10148 rc = 1; 10149 } 10150 }else 10151 10152 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 10153 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 10154 || strncmp(azArg[0], "indexes", n)==0) ) 10155 ){ 10156 sqlite3_stmt *pStmt; 10157 char **azResult; 10158 int nRow, nAlloc; 10159 int ii; 10160 ShellText s; 10161 initText(&s); 10162 open_db(p, 0); 10163 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 10164 if( rc ){ 10165 sqlite3_finalize(pStmt); 10166 return shellDatabaseError(p->db); 10167 } 10168 10169 if( nArg>2 && c=='i' ){ 10170 /* It is an historical accident that the .indexes command shows an error 10171 ** when called with the wrong number of arguments whereas the .tables 10172 ** command does not. */ 10173 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 10174 rc = 1; 10175 sqlite3_finalize(pStmt); 10176 goto meta_command_exit; 10177 } 10178 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 10179 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 10180 if( zDbName==0 ) continue; 10181 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 10182 if( sqlite3_stricmp(zDbName, "main")==0 ){ 10183 appendText(&s, "SELECT name FROM ", 0); 10184 }else{ 10185 appendText(&s, "SELECT ", 0); 10186 appendText(&s, zDbName, '\''); 10187 appendText(&s, "||'.'||name FROM ", 0); 10188 } 10189 appendText(&s, zDbName, '"'); 10190 appendText(&s, ".sqlite_schema ", 0); 10191 if( c=='t' ){ 10192 appendText(&s," WHERE type IN ('table','view')" 10193 " AND name NOT LIKE 'sqlite_%'" 10194 " AND name LIKE ?1", 0); 10195 }else{ 10196 appendText(&s," WHERE type='index'" 10197 " AND tbl_name LIKE ?1", 0); 10198 } 10199 } 10200 rc = sqlite3_finalize(pStmt); 10201 if( rc==SQLITE_OK ){ 10202 appendText(&s, " ORDER BY 1", 0); 10203 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 10204 } 10205 freeText(&s); 10206 if( rc ) return shellDatabaseError(p->db); 10207 10208 /* Run the SQL statement prepared by the above block. Store the results 10209 ** as an array of nul-terminated strings in azResult[]. */ 10210 nRow = nAlloc = 0; 10211 azResult = 0; 10212 if( nArg>1 ){ 10213 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 10214 }else{ 10215 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 10216 } 10217 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 10218 if( nRow>=nAlloc ){ 10219 char **azNew; 10220 int n2 = nAlloc*2 + 10; 10221 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 10222 shell_check_oom(azNew); 10223 nAlloc = n2; 10224 azResult = azNew; 10225 } 10226 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 10227 shell_check_oom(azResult[nRow]); 10228 nRow++; 10229 } 10230 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 10231 rc = shellDatabaseError(p->db); 10232 } 10233 10234 /* Pretty-print the contents of array azResult[] to the output */ 10235 if( rc==0 && nRow>0 ){ 10236 int len, maxlen = 0; 10237 int i, j; 10238 int nPrintCol, nPrintRow; 10239 for(i=0; i<nRow; i++){ 10240 len = strlen30(azResult[i]); 10241 if( len>maxlen ) maxlen = len; 10242 } 10243 nPrintCol = 80/(maxlen+2); 10244 if( nPrintCol<1 ) nPrintCol = 1; 10245 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 10246 for(i=0; i<nPrintRow; i++){ 10247 for(j=i; j<nRow; j+=nPrintRow){ 10248 char *zSp = j<nPrintRow ? "" : " "; 10249 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 10250 azResult[j] ? azResult[j]:""); 10251 } 10252 raw_printf(p->out, "\n"); 10253 } 10254 } 10255 10256 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 10257 sqlite3_free(azResult); 10258 }else 10259 10260 /* Begin redirecting output to the file "testcase-out.txt" */ 10261 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 10262 output_reset(p); 10263 p->out = output_file_open("testcase-out.txt", 0); 10264 if( p->out==0 ){ 10265 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 10266 } 10267 if( nArg>=2 ){ 10268 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 10269 }else{ 10270 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 10271 } 10272 }else 10273 10274#ifndef SQLITE_UNTESTABLE 10275 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 10276 static const struct { 10277 const char *zCtrlName; /* Name of a test-control option */ 10278 int ctrlCode; /* Integer code for that option */ 10279 int unSafe; /* Not valid for --safe mode */ 10280 const char *zUsage; /* Usage notes */ 10281 } aCtrl[] = { 10282 { "always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" }, 10283 { "assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" }, 10284 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/ 10285 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/ 10286 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" }, 10287 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" }, 10288 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/ 10289 { "imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"}, 10290 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" }, 10291 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" }, 10292 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" }, 10293 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" }, 10294#ifdef YYCOVERAGE 10295 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" }, 10296#endif 10297 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " }, 10298 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" }, 10299 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" }, 10300 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" }, 10301 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" }, 10302 { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" }, 10303 { "tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" }, 10304 }; 10305 int testctrl = -1; 10306 int iCtrl = -1; 10307 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 10308 int isOk = 0; 10309 int i, n2; 10310 const char *zCmd = 0; 10311 10312 open_db(p, 0); 10313 zCmd = nArg>=2 ? azArg[1] : "help"; 10314 10315 /* The argument can optionally begin with "-" or "--" */ 10316 if( zCmd[0]=='-' && zCmd[1] ){ 10317 zCmd++; 10318 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 10319 } 10320 10321 /* --help lists all test-controls */ 10322 if( strcmp(zCmd,"help")==0 ){ 10323 utf8_printf(p->out, "Available test-controls:\n"); 10324 for(i=0; i<ArraySize(aCtrl); i++){ 10325 utf8_printf(p->out, " .testctrl %s %s\n", 10326 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 10327 } 10328 rc = 1; 10329 goto meta_command_exit; 10330 } 10331 10332 /* convert testctrl text option to value. allow any unique prefix 10333 ** of the option name, or a numerical value. */ 10334 n2 = strlen30(zCmd); 10335 for(i=0; i<ArraySize(aCtrl); i++){ 10336 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 10337 if( testctrl<0 ){ 10338 testctrl = aCtrl[i].ctrlCode; 10339 iCtrl = i; 10340 }else{ 10341 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 10342 "Use \".testctrl --help\" for help\n", zCmd); 10343 rc = 1; 10344 goto meta_command_exit; 10345 } 10346 } 10347 } 10348 if( testctrl<0 ){ 10349 utf8_printf(stderr,"Error: unknown test-control: %s\n" 10350 "Use \".testctrl --help\" for help\n", zCmd); 10351 }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){ 10352 utf8_printf(stderr, 10353 "line %d: \".testctrl %s\" may not be used in safe mode\n", 10354 p->lineno, aCtrl[iCtrl].zCtrlName); 10355 exit(1); 10356 }else{ 10357 switch(testctrl){ 10358 10359 /* sqlite3_test_control(int, db, int) */ 10360 case SQLITE_TESTCTRL_OPTIMIZATIONS: 10361 if( nArg==3 ){ 10362 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0); 10363 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10364 isOk = 3; 10365 } 10366 break; 10367 10368 /* sqlite3_test_control(int) */ 10369 case SQLITE_TESTCTRL_PRNG_SAVE: 10370 case SQLITE_TESTCTRL_PRNG_RESTORE: 10371 case SQLITE_TESTCTRL_BYTEORDER: 10372 if( nArg==2 ){ 10373 rc2 = sqlite3_test_control(testctrl); 10374 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 10375 } 10376 break; 10377 10378 /* sqlite3_test_control(int, uint) */ 10379 case SQLITE_TESTCTRL_PENDING_BYTE: 10380 if( nArg==3 ){ 10381 unsigned int opt = (unsigned int)integerValue(azArg[2]); 10382 rc2 = sqlite3_test_control(testctrl, opt); 10383 isOk = 3; 10384 } 10385 break; 10386 10387 /* sqlite3_test_control(int, int, sqlite3*) */ 10388 case SQLITE_TESTCTRL_PRNG_SEED: 10389 if( nArg==3 || nArg==4 ){ 10390 int ii = (int)integerValue(azArg[2]); 10391 sqlite3 *db; 10392 if( ii==0 && strcmp(azArg[2],"random")==0 ){ 10393 sqlite3_randomness(sizeof(ii),&ii); 10394 printf("-- random seed: %d\n", ii); 10395 } 10396 if( nArg==3 ){ 10397 db = 0; 10398 }else{ 10399 db = p->db; 10400 /* Make sure the schema has been loaded */ 10401 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 10402 } 10403 rc2 = sqlite3_test_control(testctrl, ii, db); 10404 isOk = 3; 10405 } 10406 break; 10407 10408 /* sqlite3_test_control(int, int) */ 10409 case SQLITE_TESTCTRL_ASSERT: 10410 case SQLITE_TESTCTRL_ALWAYS: 10411 if( nArg==3 ){ 10412 int opt = booleanValue(azArg[2]); 10413 rc2 = sqlite3_test_control(testctrl, opt); 10414 isOk = 1; 10415 } 10416 break; 10417 10418 /* sqlite3_test_control(int, int) */ 10419 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 10420 case SQLITE_TESTCTRL_NEVER_CORRUPT: 10421 if( nArg==3 ){ 10422 int opt = booleanValue(azArg[2]); 10423 rc2 = sqlite3_test_control(testctrl, opt); 10424 isOk = 3; 10425 } 10426 break; 10427 10428 /* sqlite3_test_control(sqlite3*) */ 10429 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 10430 rc2 = sqlite3_test_control(testctrl, p->db); 10431 isOk = 3; 10432 break; 10433 10434 case SQLITE_TESTCTRL_IMPOSTER: 10435 if( nArg==5 ){ 10436 rc2 = sqlite3_test_control(testctrl, p->db, 10437 azArg[2], 10438 integerValue(azArg[3]), 10439 integerValue(azArg[4])); 10440 isOk = 3; 10441 } 10442 break; 10443 10444 case SQLITE_TESTCTRL_SEEK_COUNT: { 10445 u64 x = 0; 10446 rc2 = sqlite3_test_control(testctrl, p->db, &x); 10447 utf8_printf(p->out, "%llu\n", x); 10448 isOk = 3; 10449 break; 10450 } 10451 10452#ifdef YYCOVERAGE 10453 case SQLITE_TESTCTRL_PARSER_COVERAGE: { 10454 if( nArg==2 ){ 10455 sqlite3_test_control(testctrl, p->out); 10456 isOk = 3; 10457 } 10458 break; 10459 } 10460#endif 10461#ifdef SQLITE_DEBUG 10462 case SQLITE_TESTCTRL_TUNE: { 10463 if( nArg==4 ){ 10464 int id = (int)integerValue(azArg[2]); 10465 int val = (int)integerValue(azArg[3]); 10466 sqlite3_test_control(testctrl, id, &val); 10467 isOk = 3; 10468 }else if( nArg==3 ){ 10469 int id = (int)integerValue(azArg[2]); 10470 sqlite3_test_control(testctrl, -id, &rc2); 10471 isOk = 1; 10472 }else if( nArg==2 ){ 10473 int id = 1; 10474 while(1){ 10475 int val = 0; 10476 rc2 = sqlite3_test_control(testctrl, -id, &val); 10477 if( rc2!=SQLITE_OK ) break; 10478 if( id>1 ) utf8_printf(p->out, " "); 10479 utf8_printf(p->out, "%d: %d", id, val); 10480 id++; 10481 } 10482 if( id>1 ) utf8_printf(p->out, "\n"); 10483 isOk = 3; 10484 } 10485 break; 10486 } 10487#endif 10488 case SQLITE_TESTCTRL_SORTER_MMAP: 10489 if( nArg==3 ){ 10490 int opt = (unsigned int)integerValue(azArg[2]); 10491 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10492 isOk = 3; 10493 } 10494 break; 10495 } 10496 } 10497 if( isOk==0 && iCtrl>=0 ){ 10498 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 10499 rc = 1; 10500 }else if( isOk==1 ){ 10501 raw_printf(p->out, "%d\n", rc2); 10502 }else if( isOk==2 ){ 10503 raw_printf(p->out, "0x%08x\n", rc2); 10504 } 10505 }else 10506#endif /* !defined(SQLITE_UNTESTABLE) */ 10507 10508 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 10509 open_db(p, 0); 10510 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 10511 }else 10512 10513 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 10514 if( nArg==2 ){ 10515 enableTimer = booleanValue(azArg[1]); 10516 if( enableTimer && !HAS_TIMER ){ 10517 raw_printf(stderr, "Error: timer not available on this system.\n"); 10518 enableTimer = 0; 10519 } 10520 }else{ 10521 raw_printf(stderr, "Usage: .timer on|off\n"); 10522 rc = 1; 10523 } 10524 }else 10525 10526#ifndef SQLITE_OMIT_TRACE 10527 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 10528 int mType = 0; 10529 int jj; 10530 open_db(p, 0); 10531 for(jj=1; jj<nArg; jj++){ 10532 const char *z = azArg[jj]; 10533 if( z[0]=='-' ){ 10534 if( optionMatch(z, "expanded") ){ 10535 p->eTraceType = SHELL_TRACE_EXPANDED; 10536 } 10537#ifdef SQLITE_ENABLE_NORMALIZE 10538 else if( optionMatch(z, "normalized") ){ 10539 p->eTraceType = SHELL_TRACE_NORMALIZED; 10540 } 10541#endif 10542 else if( optionMatch(z, "plain") ){ 10543 p->eTraceType = SHELL_TRACE_PLAIN; 10544 } 10545 else if( optionMatch(z, "profile") ){ 10546 mType |= SQLITE_TRACE_PROFILE; 10547 } 10548 else if( optionMatch(z, "row") ){ 10549 mType |= SQLITE_TRACE_ROW; 10550 } 10551 else if( optionMatch(z, "stmt") ){ 10552 mType |= SQLITE_TRACE_STMT; 10553 } 10554 else if( optionMatch(z, "close") ){ 10555 mType |= SQLITE_TRACE_CLOSE; 10556 } 10557 else { 10558 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 10559 rc = 1; 10560 goto meta_command_exit; 10561 } 10562 }else{ 10563 output_file_close(p->traceOut); 10564 p->traceOut = output_file_open(azArg[1], 0); 10565 } 10566 } 10567 if( p->traceOut==0 ){ 10568 sqlite3_trace_v2(p->db, 0, 0, 0); 10569 }else{ 10570 if( mType==0 ) mType = SQLITE_TRACE_STMT; 10571 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 10572 } 10573 }else 10574#endif /* !defined(SQLITE_OMIT_TRACE) */ 10575 10576#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) 10577 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){ 10578 int ii; 10579 int lenOpt; 10580 char *zOpt; 10581 if( nArg<2 ){ 10582 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n"); 10583 rc = 1; 10584 goto meta_command_exit; 10585 } 10586 open_db(p, 0); 10587 zOpt = azArg[1]; 10588 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; 10589 lenOpt = (int)strlen(zOpt); 10590 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){ 10591 assert( azArg[nArg]==0 ); 10592 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); 10593 }else{ 10594 for(ii=1; ii<nArg; ii++){ 10595 sqlite3_create_module(p->db, azArg[ii], 0, 0); 10596 } 10597 } 10598 }else 10599#endif 10600 10601#if SQLITE_USER_AUTHENTICATION 10602 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 10603 if( nArg<2 ){ 10604 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 10605 rc = 1; 10606 goto meta_command_exit; 10607 } 10608 open_db(p, 0); 10609 if( strcmp(azArg[1],"login")==0 ){ 10610 if( nArg!=4 ){ 10611 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 10612 rc = 1; 10613 goto meta_command_exit; 10614 } 10615 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], 10616 strlen30(azArg[3])); 10617 if( rc ){ 10618 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 10619 rc = 1; 10620 } 10621 }else if( strcmp(azArg[1],"add")==0 ){ 10622 if( nArg!=5 ){ 10623 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 10624 rc = 1; 10625 goto meta_command_exit; 10626 } 10627 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10628 booleanValue(azArg[4])); 10629 if( rc ){ 10630 raw_printf(stderr, "User-Add failed: %d\n", rc); 10631 rc = 1; 10632 } 10633 }else if( strcmp(azArg[1],"edit")==0 ){ 10634 if( nArg!=5 ){ 10635 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 10636 rc = 1; 10637 goto meta_command_exit; 10638 } 10639 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10640 booleanValue(azArg[4])); 10641 if( rc ){ 10642 raw_printf(stderr, "User-Edit failed: %d\n", rc); 10643 rc = 1; 10644 } 10645 }else if( strcmp(azArg[1],"delete")==0 ){ 10646 if( nArg!=3 ){ 10647 raw_printf(stderr, "Usage: .user delete USER\n"); 10648 rc = 1; 10649 goto meta_command_exit; 10650 } 10651 rc = sqlite3_user_delete(p->db, azArg[2]); 10652 if( rc ){ 10653 raw_printf(stderr, "User-Delete failed: %d\n", rc); 10654 rc = 1; 10655 } 10656 }else{ 10657 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 10658 rc = 1; 10659 goto meta_command_exit; 10660 } 10661 }else 10662#endif /* SQLITE_USER_AUTHENTICATION */ 10663 10664 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 10665 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 10666 sqlite3_libversion(), sqlite3_sourceid()); 10667#if SQLITE_HAVE_ZLIB 10668 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 10669#endif 10670#define CTIMEOPT_VAL_(opt) #opt 10671#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 10672#if defined(__clang__) && defined(__clang_major__) 10673 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 10674 CTIMEOPT_VAL(__clang_minor__) "." 10675 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 10676#elif defined(_MSC_VER) 10677 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 10678#elif defined(__GNUC__) && defined(__VERSION__) 10679 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 10680#endif 10681 }else 10682 10683 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 10684 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10685 sqlite3_vfs *pVfs = 0; 10686 if( p->db ){ 10687 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 10688 if( pVfs ){ 10689 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 10690 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10691 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10692 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10693 } 10694 } 10695 }else 10696 10697 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 10698 sqlite3_vfs *pVfs; 10699 sqlite3_vfs *pCurrent = 0; 10700 if( p->db ){ 10701 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 10702 } 10703 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 10704 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 10705 pVfs==pCurrent ? " <--- CURRENT" : ""); 10706 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10707 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10708 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10709 if( pVfs->pNext ){ 10710 raw_printf(p->out, "-----------------------------------\n"); 10711 } 10712 } 10713 }else 10714 10715 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 10716 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10717 char *zVfsName = 0; 10718 if( p->db ){ 10719 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 10720 if( zVfsName ){ 10721 utf8_printf(p->out, "%s\n", zVfsName); 10722 sqlite3_free(zVfsName); 10723 } 10724 } 10725 }else 10726 10727 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 10728 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 10729 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x); 10730 }else 10731 10732 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 10733 int j; 10734 assert( nArg<=ArraySize(azArg) ); 10735 p->nWidth = nArg-1; 10736 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); 10737 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); 10738 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; 10739 for(j=1; j<nArg; j++){ 10740 p->colWidth[j-1] = (int)integerValue(azArg[j]); 10741 } 10742 }else 10743 10744 { 10745 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 10746 " \"%s\". Enter \".help\" for help\n", azArg[0]); 10747 rc = 1; 10748 } 10749 10750meta_command_exit: 10751 if( p->outCount ){ 10752 p->outCount--; 10753 if( p->outCount==0 ) output_reset(p); 10754 } 10755 p->bSafeMode = p->bSafeModePersist; 10756 return rc; 10757} 10758 10759/* Line scan result and intermediate states (supporting scan resumption) 10760*/ 10761#ifndef CHAR_BIT 10762# define CHAR_BIT 8 10763#endif 10764typedef enum { 10765 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT, 10766 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT, 10767 QSS_Start = 0 10768} QuickScanState; 10769#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask)) 10770#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start) 10771#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start) 10772#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark) 10773#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi) 10774 10775/* 10776** Scan line for classification to guide shell's handling. 10777** The scan is resumable for subsequent lines when prior 10778** return values are passed as the 2nd argument. 10779*/ 10780static QuickScanState quickscan(char *zLine, QuickScanState qss){ 10781 char cin; 10782 char cWait = (char)qss; /* intentional narrowing loss */ 10783 if( cWait==0 ){ 10784 PlainScan: 10785 assert( cWait==0 ); 10786 while( (cin = *zLine++)!=0 ){ 10787 if( IsSpace(cin) ) 10788 continue; 10789 switch (cin){ 10790 case '-': 10791 if( *zLine!='-' ) 10792 break; 10793 while((cin = *++zLine)!=0 ) 10794 if( cin=='\n') 10795 goto PlainScan; 10796 return qss; 10797 case ';': 10798 qss |= QSS_EndingSemi; 10799 continue; 10800 case '/': 10801 if( *zLine=='*' ){ 10802 ++zLine; 10803 cWait = '*'; 10804 qss = QSS_SETV(qss, cWait); 10805 goto TermScan; 10806 } 10807 break; 10808 case '[': 10809 cin = ']'; 10810 /* fall thru */ 10811 case '`': case '\'': case '"': 10812 cWait = cin; 10813 qss = QSS_HasDark | cWait; 10814 goto TermScan; 10815 default: 10816 break; 10817 } 10818 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark; 10819 } 10820 }else{ 10821 TermScan: 10822 while( (cin = *zLine++)!=0 ){ 10823 if( cin==cWait ){ 10824 switch( cWait ){ 10825 case '*': 10826 if( *zLine != '/' ) 10827 continue; 10828 ++zLine; 10829 cWait = 0; 10830 qss = QSS_SETV(qss, 0); 10831 goto PlainScan; 10832 case '`': case '\'': case '"': 10833 if(*zLine==cWait){ 10834 ++zLine; 10835 continue; 10836 } 10837 /* fall thru */ 10838 case ']': 10839 cWait = 0; 10840 qss = QSS_SETV(qss, 0); 10841 goto PlainScan; 10842 default: assert(0); 10843 } 10844 } 10845 } 10846 } 10847 return qss; 10848} 10849 10850/* 10851** Return TRUE if the line typed in is an SQL command terminator other 10852** than a semi-colon. The SQL Server style "go" command is understood 10853** as is the Oracle "/". 10854*/ 10855static int line_is_command_terminator(char *zLine){ 10856 while( IsSpace(zLine[0]) ){ zLine++; }; 10857 if( zLine[0]=='/' ) 10858 zLine += 1; /* Oracle */ 10859 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' ) 10860 zLine += 2; /* SQL Server */ 10861 else 10862 return 0; 10863 return quickscan(zLine,QSS_Start)==QSS_Start; 10864} 10865 10866/* 10867** We need a default sqlite3_complete() implementation to use in case 10868** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 10869** any arbitrary text is a complete SQL statement. This is not very 10870** user-friendly, but it does seem to work. 10871*/ 10872#ifdef SQLITE_OMIT_COMPLETE 10873#define sqlite3_complete(x) 1 10874#endif 10875 10876/* 10877** Return true if zSql is a complete SQL statement. Return false if it 10878** ends in the middle of a string literal or C-style comment. 10879*/ 10880static int line_is_complete(char *zSql, int nSql){ 10881 int rc; 10882 if( zSql==0 ) return 1; 10883 zSql[nSql] = ';'; 10884 zSql[nSql+1] = 0; 10885 rc = sqlite3_complete(zSql); 10886 zSql[nSql] = 0; 10887 return rc; 10888} 10889 10890/* 10891** Run a single line of SQL. Return the number of errors. 10892*/ 10893static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 10894 int rc; 10895 char *zErrMsg = 0; 10896 10897 open_db(p, 0); 10898 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 10899 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 10900 BEGIN_TIMER; 10901 rc = shell_exec(p, zSql, &zErrMsg); 10902 END_TIMER; 10903 if( rc || zErrMsg ){ 10904 char zPrefix[100]; 10905 if( in!=0 || !stdin_is_interactive ){ 10906 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 10907 "Error: near line %d:", startline); 10908 }else{ 10909 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 10910 } 10911 if( zErrMsg!=0 ){ 10912 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 10913 sqlite3_free(zErrMsg); 10914 zErrMsg = 0; 10915 }else{ 10916 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 10917 } 10918 return 1; 10919 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 10920 char zLineBuf[2000]; 10921 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf, 10922 "changes: %lld total_changes: %lld", 10923 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); 10924 raw_printf(p->out, "%s\n", zLineBuf); 10925 } 10926 return 0; 10927} 10928 10929 10930/* 10931** Read input from *in and process it. If *in==0 then input 10932** is interactive - the user is typing it it. Otherwise, input 10933** is coming from a file or device. A prompt is issued and history 10934** is saved only if input is interactive. An interrupt signal will 10935** cause this routine to exit immediately, unless input is interactive. 10936** 10937** Return the number of errors. 10938*/ 10939static int process_input(ShellState *p){ 10940 char *zLine = 0; /* A single input line */ 10941 char *zSql = 0; /* Accumulated SQL text */ 10942 int nLine; /* Length of current line */ 10943 int nSql = 0; /* Bytes of zSql[] used */ 10944 int nAlloc = 0; /* Allocated zSql[] space */ 10945 int rc; /* Error code */ 10946 int errCnt = 0; /* Number of errors seen */ 10947 int startline = 0; /* Line number for start of current input */ 10948 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */ 10949 10950 if( p->inputNesting==MAX_INPUT_NESTING ){ 10951 /* This will be more informative in a later version. */ 10952 utf8_printf(stderr,"Input nesting limit (%d) reached at line %d." 10953 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno); 10954 return 1; 10955 } 10956 ++p->inputNesting; 10957 p->lineno = 0; 10958 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 10959 fflush(p->out); 10960 zLine = one_input_line(p->in, zLine, nSql>0); 10961 if( zLine==0 ){ 10962 /* End of input */ 10963 if( p->in==0 && stdin_is_interactive ) printf("\n"); 10964 break; 10965 } 10966 if( seenInterrupt ){ 10967 if( p->in!=0 ) break; 10968 seenInterrupt = 0; 10969 } 10970 p->lineno++; 10971 if( QSS_INPLAIN(qss) 10972 && line_is_command_terminator(zLine) 10973 && line_is_complete(zSql, nSql) ){ 10974 memcpy(zLine,";",2); 10975 } 10976 qss = quickscan(zLine, qss); 10977 if( QSS_PLAINWHITE(qss) && nSql==0 ){ 10978 if( ShellHasFlag(p, SHFLG_Echo) ) 10979 printf("%s\n", zLine); 10980 /* Just swallow single-line whitespace */ 10981 qss = QSS_Start; 10982 continue; 10983 } 10984 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 10985 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 10986 if( zLine[0]=='.' ){ 10987 rc = do_meta_command(zLine, p); 10988 if( rc==2 ){ /* exit requested */ 10989 break; 10990 }else if( rc ){ 10991 errCnt++; 10992 } 10993 } 10994 qss = QSS_Start; 10995 continue; 10996 } 10997 /* No single-line dispositions remain; accumulate line(s). */ 10998 nLine = strlen30(zLine); 10999 if( nSql+nLine+2>=nAlloc ){ 11000 /* Grow buffer by half-again increments when big. */ 11001 nAlloc = nSql+(nSql>>1)+nLine+100; 11002 zSql = realloc(zSql, nAlloc); 11003 shell_check_oom(zSql); 11004 } 11005 if( nSql==0 ){ 11006 int i; 11007 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 11008 assert( nAlloc>0 && zSql!=0 ); 11009 memcpy(zSql, zLine+i, nLine+1-i); 11010 startline = p->lineno; 11011 nSql = nLine-i; 11012 }else{ 11013 zSql[nSql++] = '\n'; 11014 memcpy(zSql+nSql, zLine, nLine+1); 11015 nSql += nLine; 11016 } 11017 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){ 11018 errCnt += runOneSqlLine(p, zSql, p->in, startline); 11019 nSql = 0; 11020 if( p->outCount ){ 11021 output_reset(p); 11022 p->outCount = 0; 11023 }else{ 11024 clearTempFile(p); 11025 } 11026 p->bSafeMode = p->bSafeModePersist; 11027 qss = QSS_Start; 11028 }else if( nSql && QSS_PLAINWHITE(qss) ){ 11029 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 11030 nSql = 0; 11031 qss = QSS_Start; 11032 } 11033 } 11034 if( nSql && QSS_PLAINDARK(qss) ){ 11035 errCnt += runOneSqlLine(p, zSql, p->in, startline); 11036 } 11037 free(zSql); 11038 free(zLine); 11039 --p->inputNesting; 11040 return errCnt>0; 11041} 11042 11043/* 11044** Return a pathname which is the user's home directory. A 11045** 0 return indicates an error of some kind. 11046*/ 11047static char *find_home_dir(int clearFlag){ 11048 static char *home_dir = NULL; 11049 if( clearFlag ){ 11050 free(home_dir); 11051 home_dir = 0; 11052 return 0; 11053 } 11054 if( home_dir ) return home_dir; 11055 11056#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 11057 && !defined(__RTP__) && !defined(_WRS_KERNEL) 11058 { 11059 struct passwd *pwent; 11060 uid_t uid = getuid(); 11061 if( (pwent=getpwuid(uid)) != NULL) { 11062 home_dir = pwent->pw_dir; 11063 } 11064 } 11065#endif 11066 11067#if defined(_WIN32_WCE) 11068 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 11069 */ 11070 home_dir = "/"; 11071#else 11072 11073#if defined(_WIN32) || defined(WIN32) 11074 if (!home_dir) { 11075 home_dir = getenv("USERPROFILE"); 11076 } 11077#endif 11078 11079 if (!home_dir) { 11080 home_dir = getenv("HOME"); 11081 } 11082 11083#if defined(_WIN32) || defined(WIN32) 11084 if (!home_dir) { 11085 char *zDrive, *zPath; 11086 int n; 11087 zDrive = getenv("HOMEDRIVE"); 11088 zPath = getenv("HOMEPATH"); 11089 if( zDrive && zPath ){ 11090 n = strlen30(zDrive) + strlen30(zPath) + 1; 11091 home_dir = malloc( n ); 11092 if( home_dir==0 ) return 0; 11093 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 11094 return home_dir; 11095 } 11096 home_dir = "c:\\"; 11097 } 11098#endif 11099 11100#endif /* !_WIN32_WCE */ 11101 11102 if( home_dir ){ 11103 int n = strlen30(home_dir) + 1; 11104 char *z = malloc( n ); 11105 if( z ) memcpy(z, home_dir, n); 11106 home_dir = z; 11107 } 11108 11109 return home_dir; 11110} 11111 11112/* 11113** Read input from the file given by sqliterc_override. Or if that 11114** parameter is NULL, take input from ~/.sqliterc 11115** 11116** Returns the number of errors. 11117*/ 11118static void process_sqliterc( 11119 ShellState *p, /* Configuration data */ 11120 const char *sqliterc_override /* Name of config file. NULL to use default */ 11121){ 11122 char *home_dir = NULL; 11123 const char *sqliterc = sqliterc_override; 11124 char *zBuf = 0; 11125 FILE *inSaved = p->in; 11126 int savedLineno = p->lineno; 11127 11128 if (sqliterc == NULL) { 11129 home_dir = find_home_dir(0); 11130 if( home_dir==0 ){ 11131 raw_printf(stderr, "-- warning: cannot find home directory;" 11132 " cannot read ~/.sqliterc\n"); 11133 return; 11134 } 11135 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 11136 shell_check_oom(zBuf); 11137 sqliterc = zBuf; 11138 } 11139 p->in = fopen(sqliterc,"rb"); 11140 if( p->in ){ 11141 if( stdin_is_interactive ){ 11142 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 11143 } 11144 if( process_input(p) && bail_on_error ) exit(1); 11145 fclose(p->in); 11146 }else if( sqliterc_override!=0 ){ 11147 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc); 11148 if( bail_on_error ) exit(1); 11149 } 11150 p->in = inSaved; 11151 p->lineno = savedLineno; 11152 sqlite3_free(zBuf); 11153} 11154 11155/* 11156** Show available command line options 11157*/ 11158static const char zOptions[] = 11159#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 11160 " -A ARGS... run \".archive ARGS\" and exit\n" 11161#endif 11162 " -append append the database to the end of the file\n" 11163 " -ascii set output mode to 'ascii'\n" 11164 " -bail stop after hitting an error\n" 11165 " -batch force batch I/O\n" 11166 " -box set output mode to 'box'\n" 11167 " -column set output mode to 'column'\n" 11168 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 11169 " -csv set output mode to 'csv'\n" 11170#if !defined(SQLITE_OMIT_DESERIALIZE) 11171 " -deserialize open the database using sqlite3_deserialize()\n" 11172#endif 11173 " -echo print commands before execution\n" 11174 " -init FILENAME read/process named file\n" 11175 " -[no]header turn headers on or off\n" 11176#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11177 " -heap SIZE Size of heap for memsys3 or memsys5\n" 11178#endif 11179 " -help show this message\n" 11180 " -html set output mode to HTML\n" 11181 " -interactive force interactive I/O\n" 11182 " -json set output mode to 'json'\n" 11183 " -line set output mode to 'line'\n" 11184 " -list set output mode to 'list'\n" 11185 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 11186 " -markdown set output mode to 'markdown'\n" 11187#if !defined(SQLITE_OMIT_DESERIALIZE) 11188 " -maxsize N maximum size for a --deserialize database\n" 11189#endif 11190 " -memtrace trace all memory allocations and deallocations\n" 11191 " -mmap N default mmap size set to N\n" 11192#ifdef SQLITE_ENABLE_MULTIPLEX 11193 " -multiplex enable the multiplexor VFS\n" 11194#endif 11195 " -newline SEP set output row separator. Default: '\\n'\n" 11196 " -nofollow refuse to open symbolic links to database files\n" 11197 " -nonce STRING set the safe-mode escape nonce\n" 11198 " -nullvalue TEXT set text string for NULL values. Default ''\n" 11199 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 11200 " -quote set output mode to 'quote'\n" 11201 " -readonly open the database read-only\n" 11202 " -safe enable safe-mode\n" 11203 " -separator SEP set output column separator. Default: '|'\n" 11204#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11205 " -sorterref SIZE sorter references threshold size\n" 11206#endif 11207 " -stats print memory stats before each finalize\n" 11208 " -table set output mode to 'table'\n" 11209 " -tabs set output mode to 'tabs'\n" 11210 " -version show SQLite version\n" 11211 " -vfs NAME use NAME as the default VFS\n" 11212#ifdef SQLITE_ENABLE_VFSTRACE 11213 " -vfstrace enable tracing of all VFS calls\n" 11214#endif 11215#ifdef SQLITE_HAVE_ZLIB 11216 " -zip open the file as a ZIP Archive\n" 11217#endif 11218; 11219static void usage(int showDetail){ 11220 utf8_printf(stderr, 11221 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 11222 "FILENAME is the name of an SQLite database. A new database is created\n" 11223 "if the file does not previously exist.\n", Argv0); 11224 if( showDetail ){ 11225 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 11226 }else{ 11227 raw_printf(stderr, "Use the -help option for additional information\n"); 11228 } 11229 exit(1); 11230} 11231 11232/* 11233** Internal check: Verify that the SQLite is uninitialized. Print a 11234** error message if it is initialized. 11235*/ 11236static void verify_uninitialized(void){ 11237 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 11238 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 11239 " initialization.\n"); 11240 } 11241} 11242 11243/* 11244** Initialize the state information in data 11245*/ 11246static void main_init(ShellState *data) { 11247 memset(data, 0, sizeof(*data)); 11248 data->normalMode = data->cMode = data->mode = MODE_List; 11249 data->autoExplain = 1; 11250 data->pAuxDb = &data->aAuxDb[0]; 11251 memcpy(data->colSeparator,SEP_Column, 2); 11252 memcpy(data->rowSeparator,SEP_Row, 2); 11253 data->showHeader = 0; 11254 data->shellFlgs = SHFLG_Lookaside; 11255 verify_uninitialized(); 11256 sqlite3_config(SQLITE_CONFIG_URI, 1); 11257 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 11258 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 11259 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 11260 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 11261} 11262 11263/* 11264** Output text to the console in a font that attracts extra attention. 11265*/ 11266#ifdef _WIN32 11267static void printBold(const char *zText){ 11268#if !SQLITE_OS_WINRT 11269 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 11270 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 11271 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 11272 SetConsoleTextAttribute(out, 11273 FOREGROUND_RED|FOREGROUND_INTENSITY 11274 ); 11275#endif 11276 printf("%s", zText); 11277#if !SQLITE_OS_WINRT 11278 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 11279#endif 11280} 11281#else 11282static void printBold(const char *zText){ 11283 printf("\033[1m%s\033[0m", zText); 11284} 11285#endif 11286 11287/* 11288** Get the argument to an --option. Throw an error and die if no argument 11289** is available. 11290*/ 11291static char *cmdline_option_value(int argc, char **argv, int i){ 11292 if( i==argc ){ 11293 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 11294 argv[0], argv[argc-1]); 11295 exit(1); 11296 } 11297 return argv[i]; 11298} 11299 11300#ifndef SQLITE_SHELL_IS_UTF8 11301# if (defined(_WIN32) || defined(WIN32)) \ 11302 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__))) 11303# define SQLITE_SHELL_IS_UTF8 (0) 11304# else 11305# define SQLITE_SHELL_IS_UTF8 (1) 11306# endif 11307#endif 11308 11309#if SQLITE_SHELL_IS_UTF8 11310int SQLITE_CDECL main(int argc, char **argv){ 11311#else 11312int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 11313 char **argv; 11314#endif 11315 char *zErrMsg = 0; 11316 ShellState data; 11317 const char *zInitFile = 0; 11318 int i; 11319 int rc = 0; 11320 int warnInmemoryDb = 0; 11321 int readStdin = 1; 11322 int nCmd = 0; 11323 char **azCmd = 0; 11324 const char *zVfs = 0; /* Value of -vfs command-line option */ 11325#if !SQLITE_SHELL_IS_UTF8 11326 char **argvToFree = 0; 11327 int argcToFree = 0; 11328#endif 11329 11330 setBinaryMode(stdin, 0); 11331 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 11332 stdin_is_interactive = isatty(0); 11333 stdout_is_console = isatty(1); 11334 11335#if !defined(_WIN32_WCE) 11336 if( getenv("SQLITE_DEBUG_BREAK") ){ 11337 if( isatty(0) && isatty(2) ){ 11338 fprintf(stderr, 11339 "attach debugger to process %d and press any key to continue.\n", 11340 GETPID()); 11341 fgetc(stdin); 11342 }else{ 11343#if defined(_WIN32) || defined(WIN32) 11344#if SQLITE_OS_WINRT 11345 __debugbreak(); 11346#else 11347 DebugBreak(); 11348#endif 11349#elif defined(SIGTRAP) 11350 raise(SIGTRAP); 11351#endif 11352 } 11353 } 11354#endif 11355 11356#if USE_SYSTEM_SQLITE+0!=1 11357 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 11358 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 11359 sqlite3_sourceid(), SQLITE_SOURCE_ID); 11360 exit(1); 11361 } 11362#endif 11363 main_init(&data); 11364 11365 /* On Windows, we must translate command-line arguments into UTF-8. 11366 ** The SQLite memory allocator subsystem has to be enabled in order to 11367 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 11368 ** subsequent sqlite3_config() calls will work. So copy all results into 11369 ** memory that does not come from the SQLite memory allocator. 11370 */ 11371#if !SQLITE_SHELL_IS_UTF8 11372 sqlite3_initialize(); 11373 argvToFree = malloc(sizeof(argv[0])*argc*2); 11374 shell_check_oom(argvToFree); 11375 argcToFree = argc; 11376 argv = argvToFree + argc; 11377 for(i=0; i<argc; i++){ 11378 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 11379 int n; 11380 shell_check_oom(z); 11381 n = (int)strlen(z); 11382 argv[i] = malloc( n+1 ); 11383 shell_check_oom(argv[i]); 11384 memcpy(argv[i], z, n+1); 11385 argvToFree[i] = argv[i]; 11386 sqlite3_free(z); 11387 } 11388 sqlite3_shutdown(); 11389#endif 11390 11391 assert( argc>=1 && argv && argv[0] ); 11392 Argv0 = argv[0]; 11393 11394 /* Make sure we have a valid signal handler early, before anything 11395 ** else is done. 11396 */ 11397#ifdef SIGINT 11398 signal(SIGINT, interrupt_handler); 11399#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 11400 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 11401#endif 11402 11403#ifdef SQLITE_SHELL_DBNAME_PROC 11404 { 11405 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 11406 ** of a C-function that will provide the name of the database file. Use 11407 ** this compile-time option to embed this shell program in larger 11408 ** applications. */ 11409 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 11410 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename); 11411 warnInmemoryDb = 0; 11412 } 11413#endif 11414 11415 /* Do an initial pass through the command-line argument to locate 11416 ** the name of the database file, the name of the initialization file, 11417 ** the size of the alternative malloc heap, 11418 ** and the first command to execute. 11419 */ 11420 verify_uninitialized(); 11421 for(i=1; i<argc; i++){ 11422 char *z; 11423 z = argv[i]; 11424 if( z[0]!='-' ){ 11425 if( data.aAuxDb->zDbFilename==0 ){ 11426 data.aAuxDb->zDbFilename = z; 11427 }else{ 11428 /* Excesss arguments are interpreted as SQL (or dot-commands) and 11429 ** mean that nothing is read from stdin */ 11430 readStdin = 0; 11431 nCmd++; 11432 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 11433 shell_check_oom(azCmd); 11434 azCmd[nCmd-1] = z; 11435 } 11436 } 11437 if( z[1]=='-' ) z++; 11438 if( strcmp(z,"-separator")==0 11439 || strcmp(z,"-nullvalue")==0 11440 || strcmp(z,"-newline")==0 11441 || strcmp(z,"-cmd")==0 11442 ){ 11443 (void)cmdline_option_value(argc, argv, ++i); 11444 }else if( strcmp(z,"-init")==0 ){ 11445 zInitFile = cmdline_option_value(argc, argv, ++i); 11446 }else if( strcmp(z,"-batch")==0 ){ 11447 /* Need to check for batch mode here to so we can avoid printing 11448 ** informational messages (like from process_sqliterc) before 11449 ** we do the actual processing of arguments later in a second pass. 11450 */ 11451 stdin_is_interactive = 0; 11452 }else if( strcmp(z,"-heap")==0 ){ 11453#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11454 const char *zSize; 11455 sqlite3_int64 szHeap; 11456 11457 zSize = cmdline_option_value(argc, argv, ++i); 11458 szHeap = integerValue(zSize); 11459 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 11460 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 11461#else 11462 (void)cmdline_option_value(argc, argv, ++i); 11463#endif 11464 }else if( strcmp(z,"-pagecache")==0 ){ 11465 sqlite3_int64 n, sz; 11466 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11467 if( sz>70000 ) sz = 70000; 11468 if( sz<0 ) sz = 0; 11469 n = integerValue(cmdline_option_value(argc,argv,++i)); 11470 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){ 11471 n = 0xffffffffffffLL/sz; 11472 } 11473 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 11474 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 11475 data.shellFlgs |= SHFLG_Pagecache; 11476 }else if( strcmp(z,"-lookaside")==0 ){ 11477 int n, sz; 11478 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11479 if( sz<0 ) sz = 0; 11480 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11481 if( n<0 ) n = 0; 11482 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 11483 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 11484 }else if( strcmp(z,"-threadsafe")==0 ){ 11485 int n; 11486 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11487 switch( n ){ 11488 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break; 11489 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break; 11490 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break; 11491 } 11492#ifdef SQLITE_ENABLE_VFSTRACE 11493 }else if( strcmp(z,"-vfstrace")==0 ){ 11494 extern int vfstrace_register( 11495 const char *zTraceName, 11496 const char *zOldVfsName, 11497 int (*xOut)(const char*,void*), 11498 void *pOutArg, 11499 int makeDefault 11500 ); 11501 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 11502#endif 11503#ifdef SQLITE_ENABLE_MULTIPLEX 11504 }else if( strcmp(z,"-multiplex")==0 ){ 11505 extern int sqlite3_multiple_initialize(const char*,int); 11506 sqlite3_multiplex_initialize(0, 1); 11507#endif 11508 }else if( strcmp(z,"-mmap")==0 ){ 11509 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11510 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 11511#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11512 }else if( strcmp(z,"-sorterref")==0 ){ 11513 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11514 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 11515#endif 11516 }else if( strcmp(z,"-vfs")==0 ){ 11517 zVfs = cmdline_option_value(argc, argv, ++i); 11518#ifdef SQLITE_HAVE_ZLIB 11519 }else if( strcmp(z,"-zip")==0 ){ 11520 data.openMode = SHELL_OPEN_ZIPFILE; 11521#endif 11522 }else if( strcmp(z,"-append")==0 ){ 11523 data.openMode = SHELL_OPEN_APPENDVFS; 11524#ifndef SQLITE_OMIT_DESERIALIZE 11525 }else if( strcmp(z,"-deserialize")==0 ){ 11526 data.openMode = SHELL_OPEN_DESERIALIZE; 11527 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 11528 data.szMax = integerValue(argv[++i]); 11529#endif 11530 }else if( strcmp(z,"-readonly")==0 ){ 11531 data.openMode = SHELL_OPEN_READONLY; 11532 }else if( strcmp(z,"-nofollow")==0 ){ 11533 data.openFlags = SQLITE_OPEN_NOFOLLOW; 11534#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11535 }else if( strncmp(z, "-A",2)==0 ){ 11536 /* All remaining command-line arguments are passed to the ".archive" 11537 ** command, so ignore them */ 11538 break; 11539#endif 11540 }else if( strcmp(z, "-memtrace")==0 ){ 11541 sqlite3MemTraceActivate(stderr); 11542 }else if( strcmp(z,"-bail")==0 ){ 11543 bail_on_error = 1; 11544 }else if( strcmp(z,"-nonce")==0 ){ 11545 free(data.zNonce); 11546 data.zNonce = strdup(argv[++i]); 11547 }else if( strcmp(z,"-safe")==0 ){ 11548 /* no-op - catch this on the second pass */ 11549 } 11550 } 11551 verify_uninitialized(); 11552 11553 11554#ifdef SQLITE_SHELL_INIT_PROC 11555 { 11556 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 11557 ** of a C-function that will perform initialization actions on SQLite that 11558 ** occur just before or after sqlite3_initialize(). Use this compile-time 11559 ** option to embed this shell program in larger applications. */ 11560 extern void SQLITE_SHELL_INIT_PROC(void); 11561 SQLITE_SHELL_INIT_PROC(); 11562 } 11563#else 11564 /* All the sqlite3_config() calls have now been made. So it is safe 11565 ** to call sqlite3_initialize() and process any command line -vfs option. */ 11566 sqlite3_initialize(); 11567#endif 11568 11569 if( zVfs ){ 11570 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 11571 if( pVfs ){ 11572 sqlite3_vfs_register(pVfs, 1); 11573 }else{ 11574 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 11575 exit(1); 11576 } 11577 } 11578 11579 if( data.pAuxDb->zDbFilename==0 ){ 11580#ifndef SQLITE_OMIT_MEMORYDB 11581 data.pAuxDb->zDbFilename = ":memory:"; 11582 warnInmemoryDb = argc==1; 11583#else 11584 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 11585 return 1; 11586#endif 11587 } 11588 data.out = stdout; 11589 sqlite3_appendvfs_init(0,0,0); 11590 11591 /* Go ahead and open the database file if it already exists. If the 11592 ** file does not exist, delay opening it. This prevents empty database 11593 ** files from being created if a user mistypes the database name argument 11594 ** to the sqlite command-line tool. 11595 */ 11596 if( access(data.pAuxDb->zDbFilename, 0)==0 ){ 11597 open_db(&data, 0); 11598 } 11599 11600 /* Process the initialization file if there is one. If no -init option 11601 ** is given on the command line, look for a file named ~/.sqliterc and 11602 ** try to process it. 11603 */ 11604 process_sqliterc(&data,zInitFile); 11605 11606 /* Make a second pass through the command-line argument and set 11607 ** options. This second pass is delayed until after the initialization 11608 ** file is processed so that the command-line arguments will override 11609 ** settings in the initialization file. 11610 */ 11611 for(i=1; i<argc; i++){ 11612 char *z = argv[i]; 11613 if( z[0]!='-' ) continue; 11614 if( z[1]=='-' ){ z++; } 11615 if( strcmp(z,"-init")==0 ){ 11616 i++; 11617 }else if( strcmp(z,"-html")==0 ){ 11618 data.mode = MODE_Html; 11619 }else if( strcmp(z,"-list")==0 ){ 11620 data.mode = MODE_List; 11621 }else if( strcmp(z,"-quote")==0 ){ 11622 data.mode = MODE_Quote; 11623 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma); 11624 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11625 }else if( strcmp(z,"-line")==0 ){ 11626 data.mode = MODE_Line; 11627 }else if( strcmp(z,"-column")==0 ){ 11628 data.mode = MODE_Column; 11629 }else if( strcmp(z,"-json")==0 ){ 11630 data.mode = MODE_Json; 11631 }else if( strcmp(z,"-markdown")==0 ){ 11632 data.mode = MODE_Markdown; 11633 }else if( strcmp(z,"-table")==0 ){ 11634 data.mode = MODE_Table; 11635 }else if( strcmp(z,"-box")==0 ){ 11636 data.mode = MODE_Box; 11637 }else if( strcmp(z,"-csv")==0 ){ 11638 data.mode = MODE_Csv; 11639 memcpy(data.colSeparator,",",2); 11640#ifdef SQLITE_HAVE_ZLIB 11641 }else if( strcmp(z,"-zip")==0 ){ 11642 data.openMode = SHELL_OPEN_ZIPFILE; 11643#endif 11644 }else if( strcmp(z,"-append")==0 ){ 11645 data.openMode = SHELL_OPEN_APPENDVFS; 11646#ifndef SQLITE_OMIT_DESERIALIZE 11647 }else if( strcmp(z,"-deserialize")==0 ){ 11648 data.openMode = SHELL_OPEN_DESERIALIZE; 11649 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 11650 data.szMax = integerValue(argv[++i]); 11651#endif 11652 }else if( strcmp(z,"-readonly")==0 ){ 11653 data.openMode = SHELL_OPEN_READONLY; 11654 }else if( strcmp(z,"-nofollow")==0 ){ 11655 data.openFlags |= SQLITE_OPEN_NOFOLLOW; 11656 }else if( strcmp(z,"-ascii")==0 ){ 11657 data.mode = MODE_Ascii; 11658 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit); 11659 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record); 11660 }else if( strcmp(z,"-tabs")==0 ){ 11661 data.mode = MODE_List; 11662 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab); 11663 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11664 }else if( strcmp(z,"-separator")==0 ){ 11665 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 11666 "%s",cmdline_option_value(argc,argv,++i)); 11667 }else if( strcmp(z,"-newline")==0 ){ 11668 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 11669 "%s",cmdline_option_value(argc,argv,++i)); 11670 }else if( strcmp(z,"-nullvalue")==0 ){ 11671 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 11672 "%s",cmdline_option_value(argc,argv,++i)); 11673 }else if( strcmp(z,"-header")==0 ){ 11674 data.showHeader = 1; 11675 ShellSetFlag(&data, SHFLG_HeaderSet); 11676 }else if( strcmp(z,"-noheader")==0 ){ 11677 data.showHeader = 0; 11678 ShellSetFlag(&data, SHFLG_HeaderSet); 11679 }else if( strcmp(z,"-echo")==0 ){ 11680 ShellSetFlag(&data, SHFLG_Echo); 11681 }else if( strcmp(z,"-eqp")==0 ){ 11682 data.autoEQP = AUTOEQP_on; 11683 }else if( strcmp(z,"-eqpfull")==0 ){ 11684 data.autoEQP = AUTOEQP_full; 11685 }else if( strcmp(z,"-stats")==0 ){ 11686 data.statsOn = 1; 11687 }else if( strcmp(z,"-scanstats")==0 ){ 11688 data.scanstatsOn = 1; 11689 }else if( strcmp(z,"-backslash")==0 ){ 11690 /* Undocumented command-line option: -backslash 11691 ** Causes C-style backslash escapes to be evaluated in SQL statements 11692 ** prior to sending the SQL into SQLite. Useful for injecting 11693 ** crazy bytes in the middle of SQL statements for testing and debugging. 11694 */ 11695 ShellSetFlag(&data, SHFLG_Backslash); 11696 }else if( strcmp(z,"-bail")==0 ){ 11697 /* No-op. The bail_on_error flag should already be set. */ 11698 }else if( strcmp(z,"-version")==0 ){ 11699 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 11700 return 0; 11701 }else if( strcmp(z,"-interactive")==0 ){ 11702 stdin_is_interactive = 1; 11703 }else if( strcmp(z,"-batch")==0 ){ 11704 stdin_is_interactive = 0; 11705 }else if( strcmp(z,"-heap")==0 ){ 11706 i++; 11707 }else if( strcmp(z,"-pagecache")==0 ){ 11708 i+=2; 11709 }else if( strcmp(z,"-lookaside")==0 ){ 11710 i+=2; 11711 }else if( strcmp(z,"-threadsafe")==0 ){ 11712 i+=2; 11713 }else if( strcmp(z,"-nonce")==0 ){ 11714 i += 2; 11715 }else if( strcmp(z,"-mmap")==0 ){ 11716 i++; 11717 }else if( strcmp(z,"-memtrace")==0 ){ 11718 i++; 11719#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11720 }else if( strcmp(z,"-sorterref")==0 ){ 11721 i++; 11722#endif 11723 }else if( strcmp(z,"-vfs")==0 ){ 11724 i++; 11725#ifdef SQLITE_ENABLE_VFSTRACE 11726 }else if( strcmp(z,"-vfstrace")==0 ){ 11727 i++; 11728#endif 11729#ifdef SQLITE_ENABLE_MULTIPLEX 11730 }else if( strcmp(z,"-multiplex")==0 ){ 11731 i++; 11732#endif 11733 }else if( strcmp(z,"-help")==0 ){ 11734 usage(1); 11735 }else if( strcmp(z,"-cmd")==0 ){ 11736 /* Run commands that follow -cmd first and separately from commands 11737 ** that simply appear on the command-line. This seems goofy. It would 11738 ** be better if all commands ran in the order that they appear. But 11739 ** we retain the goofy behavior for historical compatibility. */ 11740 if( i==argc-1 ) break; 11741 z = cmdline_option_value(argc,argv,++i); 11742 if( z[0]=='.' ){ 11743 rc = do_meta_command(z, &data); 11744 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 11745 }else{ 11746 open_db(&data, 0); 11747 rc = shell_exec(&data, z, &zErrMsg); 11748 if( zErrMsg!=0 ){ 11749 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11750 if( bail_on_error ) return rc!=0 ? rc : 1; 11751 }else if( rc!=0 ){ 11752 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 11753 if( bail_on_error ) return rc; 11754 } 11755 } 11756#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11757 }else if( strncmp(z, "-A", 2)==0 ){ 11758 if( nCmd>0 ){ 11759 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 11760 " with \"%s\"\n", z); 11761 return 1; 11762 } 11763 open_db(&data, OPEN_DB_ZIPFILE); 11764 if( z[2] ){ 11765 argv[i] = &z[2]; 11766 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 11767 }else{ 11768 arDotCommand(&data, 1, argv+i, argc-i); 11769 } 11770 readStdin = 0; 11771 break; 11772#endif 11773 }else if( strcmp(z,"-safe")==0 ){ 11774 data.bSafeMode = data.bSafeModePersist = 1; 11775 }else{ 11776 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 11777 raw_printf(stderr,"Use -help for a list of options.\n"); 11778 return 1; 11779 } 11780 data.cMode = data.mode; 11781 } 11782 11783 if( !readStdin ){ 11784 /* Run all arguments that do not begin with '-' as if they were separate 11785 ** command-line inputs, except for the argToSkip argument which contains 11786 ** the database filename. 11787 */ 11788 for(i=0; i<nCmd; i++){ 11789 if( azCmd[i][0]=='.' ){ 11790 rc = do_meta_command(azCmd[i], &data); 11791 if( rc ){ 11792 free(azCmd); 11793 return rc==2 ? 0 : rc; 11794 } 11795 }else{ 11796 open_db(&data, 0); 11797 rc = shell_exec(&data, azCmd[i], &zErrMsg); 11798 if( zErrMsg || rc ){ 11799 if( zErrMsg!=0 ){ 11800 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11801 }else{ 11802 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 11803 } 11804 sqlite3_free(zErrMsg); 11805 free(azCmd); 11806 return rc!=0 ? rc : 1; 11807 } 11808 } 11809 } 11810 }else{ 11811 /* Run commands received from standard input 11812 */ 11813 if( stdin_is_interactive ){ 11814 char *zHome; 11815 char *zHistory; 11816 int nHistory; 11817 printf( 11818 "SQLite version %s %.19s\n" /*extra-version-info*/ 11819 "Enter \".help\" for usage hints.\n", 11820 sqlite3_libversion(), sqlite3_sourceid() 11821 ); 11822 if( warnInmemoryDb ){ 11823 printf("Connected to a "); 11824 printBold("transient in-memory database"); 11825 printf(".\nUse \".open FILENAME\" to reopen on a " 11826 "persistent database.\n"); 11827 } 11828 zHistory = getenv("SQLITE_HISTORY"); 11829 if( zHistory ){ 11830 zHistory = strdup(zHistory); 11831 }else if( (zHome = find_home_dir(0))!=0 ){ 11832 nHistory = strlen30(zHome) + 20; 11833 if( (zHistory = malloc(nHistory))!=0 ){ 11834 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 11835 } 11836 } 11837 if( zHistory ){ shell_read_history(zHistory); } 11838#if HAVE_READLINE || HAVE_EDITLINE 11839 rl_attempted_completion_function = readline_completion; 11840#elif HAVE_LINENOISE 11841 linenoiseSetCompletionCallback(linenoise_completion); 11842#endif 11843 data.in = 0; 11844 rc = process_input(&data); 11845 if( zHistory ){ 11846 shell_stifle_history(2000); 11847 shell_write_history(zHistory); 11848 free(zHistory); 11849 } 11850 }else{ 11851 data.in = stdin; 11852 rc = process_input(&data); 11853 } 11854 } 11855 free(azCmd); 11856 set_table_name(&data, 0); 11857 if( data.db ){ 11858 session_close_all(&data, -1); 11859 close_db(data.db); 11860 } 11861 for(i=0; i<ArraySize(data.aAuxDb); i++){ 11862 sqlite3_free(data.aAuxDb[i].zFreeOnClose); 11863 if( data.aAuxDb[i].db ){ 11864 session_close_all(&data, i); 11865 close_db(data.aAuxDb[i].db); 11866 } 11867 } 11868 find_home_dir(1); 11869 output_reset(&data); 11870 data.doXdgOpen = 0; 11871 clearTempFile(&data); 11872#if !SQLITE_SHELL_IS_UTF8 11873 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 11874 free(argvToFree); 11875#endif 11876 free(data.colWidth); 11877 free(data.zNonce); 11878 /* Clear the global data structure so that valgrind will detect memory 11879 ** leaks */ 11880 memset(&data, 0, sizeof(data)); 11881 return rc; 11882} 11883