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 outCount; /* Revert to stdout when reaching zero */ 1090 int cnt; /* Number of records displayed so far */ 1091 int lineno; /* Line number of last line read from in */ 1092 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ 1093 FILE *in; /* Read commands from this stream */ 1094 FILE *out; /* Write results here */ 1095 FILE *traceOut; /* Output for sqlite3_trace() */ 1096 int nErr; /* Number of errors seen */ 1097 int mode; /* An output mode setting */ 1098 int modePrior; /* Saved mode */ 1099 int cMode; /* temporary output mode for the current query */ 1100 int normalMode; /* Output mode before ".explain on" */ 1101 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1102 int showHeader; /* True to show column names in List or Column mode */ 1103 int nCheck; /* Number of ".check" commands run */ 1104 unsigned nProgress; /* Number of progress callbacks encountered */ 1105 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1106 unsigned flgProgress; /* Flags for the progress callback */ 1107 unsigned shellFlgs; /* Various flags */ 1108 unsigned priorShFlgs; /* Saved copy of flags */ 1109 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1110 char *zDestTable; /* Name of destination table when MODE_Insert */ 1111 char *zTempFile; /* Temporary file that might need deleting */ 1112 char zTestcase[30]; /* Name of current test case */ 1113 char colSeparator[20]; /* Column separator character for several modes */ 1114 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1115 char colSepPrior[20]; /* Saved column separator */ 1116 char rowSepPrior[20]; /* Saved row separator */ 1117 int *colWidth; /* Requested width of each column in columnar modes */ 1118 int *actualWidth; /* Actual width of each column */ 1119 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */ 1120 char nullValue[20]; /* The text to print when a NULL comes back from 1121 ** the database */ 1122 char outfile[FILENAME_MAX]; /* Filename for *out */ 1123 sqlite3_stmt *pStmt; /* Current statement if any. */ 1124 FILE *pLog; /* Write log output here */ 1125 struct AuxDb { /* Storage space for auxiliary database connections */ 1126 sqlite3 *db; /* Connection pointer */ 1127 const char *zDbFilename; /* Filename used to open the connection */ 1128 char *zFreeOnClose; /* Free this memory allocation on close */ 1129#if defined(SQLITE_ENABLE_SESSION) 1130 int nSession; /* Number of active sessions */ 1131 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1132#endif 1133 } aAuxDb[5], /* Array of all database connections */ 1134 *pAuxDb; /* Currently active database connection */ 1135 int *aiIndent; /* Array of indents used in MODE_Explain */ 1136 int nIndent; /* Size of array aiIndent[] */ 1137 int iIndent; /* Index of current op in aiIndent[] */ 1138 char *zNonce; /* Nonce for temporary safe-mode excapes */ 1139 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1140 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1141}; 1142 1143 1144/* Allowed values for ShellState.autoEQP 1145*/ 1146#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1147#define AUTOEQP_on 1 /* Automatic EQP is on */ 1148#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1149#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1150 1151/* Allowed values for ShellState.openMode 1152*/ 1153#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1154#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1155#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1156#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1157#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1158#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1159#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1160 1161/* Allowed values for ShellState.eTraceType 1162*/ 1163#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1164#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1165#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1166 1167/* Bits in the ShellState.flgProgress variable */ 1168#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1169#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1170 ** callback limit is reached, and for each 1171 ** top-level SQL statement */ 1172#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1173 1174/* 1175** These are the allowed shellFlgs values 1176*/ 1177#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1178#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1179#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1180#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1181#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1182#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1183#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1184#define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */ 1185#define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */ 1186#define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */ 1187 1188/* 1189** Macros for testing and setting shellFlgs 1190*/ 1191#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1192#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1193#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1194 1195/* 1196** These are the allowed modes. 1197*/ 1198#define MODE_Line 0 /* One column per line. Blank line between records */ 1199#define MODE_Column 1 /* One record per line in neat columns */ 1200#define MODE_List 2 /* One record per line with a separator */ 1201#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1202#define MODE_Html 4 /* Generate an XHTML table */ 1203#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1204#define MODE_Quote 6 /* Quote values as for SQL */ 1205#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1206#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1207#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1208#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1209#define MODE_Pretty 11 /* Pretty-print schemas */ 1210#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1211#define MODE_Json 13 /* Output JSON */ 1212#define MODE_Markdown 14 /* Markdown formatting */ 1213#define MODE_Table 15 /* MySQL-style table formatting */ 1214#define MODE_Box 16 /* Unicode box-drawing characters */ 1215#define MODE_Count 17 /* Output only a count of the rows of output */ 1216#define MODE_Off 18 /* No query output shown */ 1217 1218static const char *modeDescr[] = { 1219 "line", 1220 "column", 1221 "list", 1222 "semi", 1223 "html", 1224 "insert", 1225 "quote", 1226 "tcl", 1227 "csv", 1228 "explain", 1229 "ascii", 1230 "prettyprint", 1231 "eqp", 1232 "json", 1233 "markdown", 1234 "table", 1235 "box", 1236 "count", 1237 "off" 1238}; 1239 1240/* 1241** These are the column/row/line separators used by the various 1242** import/export modes. 1243*/ 1244#define SEP_Column "|" 1245#define SEP_Row "\n" 1246#define SEP_Tab "\t" 1247#define SEP_Space " " 1248#define SEP_Comma "," 1249#define SEP_CrLf "\r\n" 1250#define SEP_Unit "\x1F" 1251#define SEP_Record "\x1E" 1252 1253/* 1254** A callback for the sqlite3_log() interface. 1255*/ 1256static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1257 ShellState *p = (ShellState*)pArg; 1258 if( p->pLog==0 ) return; 1259 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1260 fflush(p->pLog); 1261} 1262 1263/* 1264** SQL function: shell_putsnl(X) 1265** 1266** Write the text X to the screen (or whatever output is being directed) 1267** adding a newline at the end, and then return X. 1268*/ 1269static void shellPutsFunc( 1270 sqlite3_context *pCtx, 1271 int nVal, 1272 sqlite3_value **apVal 1273){ 1274 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1275 (void)nVal; 1276 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1277 sqlite3_result_value(pCtx, apVal[0]); 1278} 1279 1280/* 1281** If in safe mode, print an error message described by the arguments 1282** and exit immediately. 1283*/ 1284static void failIfSafeMode( 1285 ShellState *p, 1286 const char *zErrMsg, 1287 ... 1288){ 1289 if( p->bSafeMode ){ 1290 va_list ap; 1291 char *zMsg; 1292 va_start(ap, zErrMsg); 1293 zMsg = sqlite3_vmprintf(zErrMsg, ap); 1294 va_end(ap); 1295 raw_printf(stderr, "line %d: ", p->lineno); 1296 utf8_printf(stderr, "%s\n", zMsg); 1297 exit(1); 1298 } 1299} 1300 1301/* 1302** SQL function: edit(VALUE) 1303** edit(VALUE,EDITOR) 1304** 1305** These steps: 1306** 1307** (1) Write VALUE into a temporary file. 1308** (2) Run program EDITOR on that temporary file. 1309** (3) Read the temporary file back and return its content as the result. 1310** (4) Delete the temporary file 1311** 1312** If the EDITOR argument is omitted, use the value in the VISUAL 1313** environment variable. If still there is no EDITOR, through an error. 1314** 1315** Also throw an error if the EDITOR program returns a non-zero exit code. 1316*/ 1317#ifndef SQLITE_NOHAVE_SYSTEM 1318static void editFunc( 1319 sqlite3_context *context, 1320 int argc, 1321 sqlite3_value **argv 1322){ 1323 const char *zEditor; 1324 char *zTempFile = 0; 1325 sqlite3 *db; 1326 char *zCmd = 0; 1327 int bBin; 1328 int rc; 1329 int hasCRNL = 0; 1330 FILE *f = 0; 1331 sqlite3_int64 sz; 1332 sqlite3_int64 x; 1333 unsigned char *p = 0; 1334 1335 if( argc==2 ){ 1336 zEditor = (const char*)sqlite3_value_text(argv[1]); 1337 }else{ 1338 zEditor = getenv("VISUAL"); 1339 } 1340 if( zEditor==0 ){ 1341 sqlite3_result_error(context, "no editor for edit()", -1); 1342 return; 1343 } 1344 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1345 sqlite3_result_error(context, "NULL input to edit()", -1); 1346 return; 1347 } 1348 db = sqlite3_context_db_handle(context); 1349 zTempFile = 0; 1350 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1351 if( zTempFile==0 ){ 1352 sqlite3_uint64 r = 0; 1353 sqlite3_randomness(sizeof(r), &r); 1354 zTempFile = sqlite3_mprintf("temp%llx", r); 1355 if( zTempFile==0 ){ 1356 sqlite3_result_error_nomem(context); 1357 return; 1358 } 1359 } 1360 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1361 /* When writing the file to be edited, do \n to \r\n conversions on systems 1362 ** that want \r\n line endings */ 1363 f = fopen(zTempFile, bBin ? "wb" : "w"); 1364 if( f==0 ){ 1365 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1366 goto edit_func_end; 1367 } 1368 sz = sqlite3_value_bytes(argv[0]); 1369 if( bBin ){ 1370 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); 1371 }else{ 1372 const char *z = (const char*)sqlite3_value_text(argv[0]); 1373 /* Remember whether or not the value originally contained \r\n */ 1374 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1375 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); 1376 } 1377 fclose(f); 1378 f = 0; 1379 if( x!=sz ){ 1380 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1381 goto edit_func_end; 1382 } 1383 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1384 if( zCmd==0 ){ 1385 sqlite3_result_error_nomem(context); 1386 goto edit_func_end; 1387 } 1388 rc = system(zCmd); 1389 sqlite3_free(zCmd); 1390 if( rc ){ 1391 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1392 goto edit_func_end; 1393 } 1394 f = fopen(zTempFile, "rb"); 1395 if( f==0 ){ 1396 sqlite3_result_error(context, 1397 "edit() cannot reopen temp file after edit", -1); 1398 goto edit_func_end; 1399 } 1400 fseek(f, 0, SEEK_END); 1401 sz = ftell(f); 1402 rewind(f); 1403 p = sqlite3_malloc64( sz+1 ); 1404 if( p==0 ){ 1405 sqlite3_result_error_nomem(context); 1406 goto edit_func_end; 1407 } 1408 x = fread(p, 1, (size_t)sz, f); 1409 fclose(f); 1410 f = 0; 1411 if( x!=sz ){ 1412 sqlite3_result_error(context, "could not read back the whole file", -1); 1413 goto edit_func_end; 1414 } 1415 if( bBin ){ 1416 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1417 }else{ 1418 sqlite3_int64 i, j; 1419 if( hasCRNL ){ 1420 /* If the original contains \r\n then do no conversions back to \n */ 1421 }else{ 1422 /* If the file did not originally contain \r\n then convert any new 1423 ** \r\n back into \n */ 1424 for(i=j=0; i<sz; i++){ 1425 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1426 p[j++] = p[i]; 1427 } 1428 sz = j; 1429 p[sz] = 0; 1430 } 1431 sqlite3_result_text64(context, (const char*)p, sz, 1432 sqlite3_free, SQLITE_UTF8); 1433 } 1434 p = 0; 1435 1436edit_func_end: 1437 if( f ) fclose(f); 1438 unlink(zTempFile); 1439 sqlite3_free(zTempFile); 1440 sqlite3_free(p); 1441} 1442#endif /* SQLITE_NOHAVE_SYSTEM */ 1443 1444/* 1445** Save or restore the current output mode 1446*/ 1447static void outputModePush(ShellState *p){ 1448 p->modePrior = p->mode; 1449 p->priorShFlgs = p->shellFlgs; 1450 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1451 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1452} 1453static void outputModePop(ShellState *p){ 1454 p->mode = p->modePrior; 1455 p->shellFlgs = p->priorShFlgs; 1456 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1457 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1458} 1459 1460/* 1461** Output the given string as a hex-encoded blob (eg. X'1234' ) 1462*/ 1463static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1464 int i; 1465 char *zBlob = (char *)pBlob; 1466 raw_printf(out,"X'"); 1467 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1468 raw_printf(out,"'"); 1469} 1470 1471/* 1472** Find a string that is not found anywhere in z[]. Return a pointer 1473** to that string. 1474** 1475** Try to use zA and zB first. If both of those are already found in z[] 1476** then make up some string and store it in the buffer zBuf. 1477*/ 1478static const char *unused_string( 1479 const char *z, /* Result must not appear anywhere in z */ 1480 const char *zA, const char *zB, /* Try these first */ 1481 char *zBuf /* Space to store a generated string */ 1482){ 1483 unsigned i = 0; 1484 if( strstr(z, zA)==0 ) return zA; 1485 if( strstr(z, zB)==0 ) return zB; 1486 do{ 1487 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1488 }while( strstr(z,zBuf)!=0 ); 1489 return zBuf; 1490} 1491 1492/* 1493** Output the given string as a quoted string using SQL quoting conventions. 1494** 1495** See also: output_quoted_escaped_string() 1496*/ 1497static void output_quoted_string(FILE *out, const char *z){ 1498 int i; 1499 char c; 1500 setBinaryMode(out, 1); 1501 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1502 if( c==0 ){ 1503 utf8_printf(out,"'%s'",z); 1504 }else{ 1505 raw_printf(out, "'"); 1506 while( *z ){ 1507 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1508 if( c=='\'' ) i++; 1509 if( i ){ 1510 utf8_printf(out, "%.*s", i, z); 1511 z += i; 1512 } 1513 if( c=='\'' ){ 1514 raw_printf(out, "'"); 1515 continue; 1516 } 1517 if( c==0 ){ 1518 break; 1519 } 1520 z++; 1521 } 1522 raw_printf(out, "'"); 1523 } 1524 setTextMode(out, 1); 1525} 1526 1527/* 1528** Output the given string as a quoted string using SQL quoting conventions. 1529** Additionallly , escape the "\n" and "\r" characters so that they do not 1530** get corrupted by end-of-line translation facilities in some operating 1531** systems. 1532** 1533** This is like output_quoted_string() but with the addition of the \r\n 1534** escape mechanism. 1535*/ 1536static void output_quoted_escaped_string(FILE *out, const char *z){ 1537 int i; 1538 char c; 1539 setBinaryMode(out, 1); 1540 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1541 if( c==0 ){ 1542 utf8_printf(out,"'%s'",z); 1543 }else{ 1544 const char *zNL = 0; 1545 const char *zCR = 0; 1546 int nNL = 0; 1547 int nCR = 0; 1548 char zBuf1[20], zBuf2[20]; 1549 for(i=0; z[i]; i++){ 1550 if( z[i]=='\n' ) nNL++; 1551 if( z[i]=='\r' ) nCR++; 1552 } 1553 if( nNL ){ 1554 raw_printf(out, "replace("); 1555 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1556 } 1557 if( nCR ){ 1558 raw_printf(out, "replace("); 1559 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1560 } 1561 raw_printf(out, "'"); 1562 while( *z ){ 1563 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1564 if( c=='\'' ) i++; 1565 if( i ){ 1566 utf8_printf(out, "%.*s", i, z); 1567 z += i; 1568 } 1569 if( c=='\'' ){ 1570 raw_printf(out, "'"); 1571 continue; 1572 } 1573 if( c==0 ){ 1574 break; 1575 } 1576 z++; 1577 if( c=='\n' ){ 1578 raw_printf(out, "%s", zNL); 1579 continue; 1580 } 1581 raw_printf(out, "%s", zCR); 1582 } 1583 raw_printf(out, "'"); 1584 if( nCR ){ 1585 raw_printf(out, ",'%s',char(13))", zCR); 1586 } 1587 if( nNL ){ 1588 raw_printf(out, ",'%s',char(10))", zNL); 1589 } 1590 } 1591 setTextMode(out, 1); 1592} 1593 1594/* 1595** Output the given string as a quoted according to C or TCL quoting rules. 1596*/ 1597static void output_c_string(FILE *out, const char *z){ 1598 unsigned int c; 1599 fputc('"', out); 1600 while( (c = *(z++))!=0 ){ 1601 if( c=='\\' ){ 1602 fputc(c, out); 1603 fputc(c, out); 1604 }else if( c=='"' ){ 1605 fputc('\\', out); 1606 fputc('"', out); 1607 }else if( c=='\t' ){ 1608 fputc('\\', out); 1609 fputc('t', out); 1610 }else if( c=='\n' ){ 1611 fputc('\\', out); 1612 fputc('n', out); 1613 }else if( c=='\r' ){ 1614 fputc('\\', out); 1615 fputc('r', out); 1616 }else if( !isprint(c&0xff) ){ 1617 raw_printf(out, "\\%03o", c&0xff); 1618 }else{ 1619 fputc(c, out); 1620 } 1621 } 1622 fputc('"', out); 1623} 1624 1625/* 1626** Output the given string as a quoted according to JSON quoting rules. 1627*/ 1628static void output_json_string(FILE *out, const char *z, int n){ 1629 unsigned int c; 1630 if( n<0 ) n = (int)strlen(z); 1631 fputc('"', out); 1632 while( n-- ){ 1633 c = *(z++); 1634 if( c=='\\' || c=='"' ){ 1635 fputc('\\', out); 1636 fputc(c, out); 1637 }else if( c<=0x1f ){ 1638 fputc('\\', out); 1639 if( c=='\b' ){ 1640 fputc('b', out); 1641 }else if( c=='\f' ){ 1642 fputc('f', out); 1643 }else if( c=='\n' ){ 1644 fputc('n', out); 1645 }else if( c=='\r' ){ 1646 fputc('r', out); 1647 }else if( c=='\t' ){ 1648 fputc('t', out); 1649 }else{ 1650 raw_printf(out, "u%04x",c); 1651 } 1652 }else{ 1653 fputc(c, out); 1654 } 1655 } 1656 fputc('"', out); 1657} 1658 1659/* 1660** Output the given string with characters that are special to 1661** HTML escaped. 1662*/ 1663static void output_html_string(FILE *out, const char *z){ 1664 int i; 1665 if( z==0 ) z = ""; 1666 while( *z ){ 1667 for(i=0; z[i] 1668 && z[i]!='<' 1669 && z[i]!='&' 1670 && z[i]!='>' 1671 && z[i]!='\"' 1672 && z[i]!='\''; 1673 i++){} 1674 if( i>0 ){ 1675 utf8_printf(out,"%.*s",i,z); 1676 } 1677 if( z[i]=='<' ){ 1678 raw_printf(out,"<"); 1679 }else if( z[i]=='&' ){ 1680 raw_printf(out,"&"); 1681 }else if( z[i]=='>' ){ 1682 raw_printf(out,">"); 1683 }else if( z[i]=='\"' ){ 1684 raw_printf(out,"""); 1685 }else if( z[i]=='\'' ){ 1686 raw_printf(out,"'"); 1687 }else{ 1688 break; 1689 } 1690 z += i + 1; 1691 } 1692} 1693 1694/* 1695** If a field contains any character identified by a 1 in the following 1696** array, then the string must be quoted for CSV. 1697*/ 1698static const char needCsvQuote[] = { 1699 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1700 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1701 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1702 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1703 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1704 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1705 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1706 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1707 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1708 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1709 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1710 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1711 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1712 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1713 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1714 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1715}; 1716 1717/* 1718** Output a single term of CSV. Actually, p->colSeparator is used for 1719** the separator, which may or may not be a comma. p->nullValue is 1720** the null value. Strings are quoted if necessary. The separator 1721** is only issued if bSep is true. 1722*/ 1723static void output_csv(ShellState *p, const char *z, int bSep){ 1724 FILE *out = p->out; 1725 if( z==0 ){ 1726 utf8_printf(out,"%s",p->nullValue); 1727 }else{ 1728 unsigned i; 1729 for(i=0; z[i]; i++){ 1730 if( needCsvQuote[((unsigned char*)z)[i]] ){ 1731 i = 0; 1732 break; 1733 } 1734 } 1735 if( i==0 || strstr(z, p->colSeparator)!=0 ){ 1736 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1737 shell_check_oom(zQuoted); 1738 utf8_printf(out, "%s", zQuoted); 1739 sqlite3_free(zQuoted); 1740 }else{ 1741 utf8_printf(out, "%s", z); 1742 } 1743 } 1744 if( bSep ){ 1745 utf8_printf(p->out, "%s", p->colSeparator); 1746 } 1747} 1748 1749/* 1750** This routine runs when the user presses Ctrl-C 1751*/ 1752static void interrupt_handler(int NotUsed){ 1753 UNUSED_PARAMETER(NotUsed); 1754 seenInterrupt++; 1755 if( seenInterrupt>2 ) exit(1); 1756 if( globalDb ) sqlite3_interrupt(globalDb); 1757} 1758 1759#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1760/* 1761** This routine runs for console events (e.g. Ctrl-C) on Win32 1762*/ 1763static BOOL WINAPI ConsoleCtrlHandler( 1764 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1765){ 1766 if( dwCtrlType==CTRL_C_EVENT ){ 1767 interrupt_handler(0); 1768 return TRUE; 1769 } 1770 return FALSE; 1771} 1772#endif 1773 1774#ifndef SQLITE_OMIT_AUTHORIZATION 1775/* 1776** This authorizer runs in safe mode. 1777*/ 1778static int safeModeAuth( 1779 void *pClientData, 1780 int op, 1781 const char *zA1, 1782 const char *zA2, 1783 const char *zA3, 1784 const char *zA4 1785){ 1786 ShellState *p = (ShellState*)pClientData; 1787 static const char *azProhibitedFunctions[] = { 1788 "edit", 1789 "fts3_tokenizer", 1790 "load_extension", 1791 "readfile", 1792 "writefile", 1793 "zipfile", 1794 "zipfile_cds", 1795 }; 1796 UNUSED_PARAMETER(zA2); 1797 UNUSED_PARAMETER(zA3); 1798 UNUSED_PARAMETER(zA4); 1799 switch( op ){ 1800 case SQLITE_ATTACH: { 1801 failIfSafeMode(p, "cannot run ATTACH in safe mode"); 1802 break; 1803 } 1804 case SQLITE_FUNCTION: { 1805 int i; 1806 for(i=0; i<ArraySize(azProhibitedFunctions); i++){ 1807 if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){ 1808 failIfSafeMode(p, "cannot use the %s() function in safe mode", 1809 azProhibitedFunctions[i]); 1810 } 1811 } 1812 break; 1813 } 1814 } 1815 return SQLITE_OK; 1816} 1817 1818/* 1819** When the ".auth ON" is set, the following authorizer callback is 1820** invoked. It always returns SQLITE_OK. 1821*/ 1822static int shellAuth( 1823 void *pClientData, 1824 int op, 1825 const char *zA1, 1826 const char *zA2, 1827 const char *zA3, 1828 const char *zA4 1829){ 1830 ShellState *p = (ShellState*)pClientData; 1831 static const char *azAction[] = { 0, 1832 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1833 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1834 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1835 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1836 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1837 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1838 "PRAGMA", "READ", "SELECT", 1839 "TRANSACTION", "UPDATE", "ATTACH", 1840 "DETACH", "ALTER_TABLE", "REINDEX", 1841 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1842 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1843 }; 1844 int i; 1845 const char *az[4]; 1846 az[0] = zA1; 1847 az[1] = zA2; 1848 az[2] = zA3; 1849 az[3] = zA4; 1850 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1851 for(i=0; i<4; i++){ 1852 raw_printf(p->out, " "); 1853 if( az[i] ){ 1854 output_c_string(p->out, az[i]); 1855 }else{ 1856 raw_printf(p->out, "NULL"); 1857 } 1858 } 1859 raw_printf(p->out, "\n"); 1860 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); 1861 return SQLITE_OK; 1862} 1863#endif 1864 1865/* 1866** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1867** 1868** This routine converts some CREATE TABLE statements for shadow tables 1869** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1870*/ 1871static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1872 if( z==0 ) return; 1873 if( zTail==0 ) return; 1874 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1875 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1876 }else{ 1877 utf8_printf(out, "%s%s", z, zTail); 1878 } 1879} 1880static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1881 char c = z[n]; 1882 z[n] = 0; 1883 printSchemaLine(out, z, zTail); 1884 z[n] = c; 1885} 1886 1887/* 1888** Return true if string z[] has nothing but whitespace and comments to the 1889** end of the first line. 1890*/ 1891static int wsToEol(const char *z){ 1892 int i; 1893 for(i=0; z[i]; i++){ 1894 if( z[i]=='\n' ) return 1; 1895 if( IsSpace(z[i]) ) continue; 1896 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1897 return 0; 1898 } 1899 return 1; 1900} 1901 1902/* 1903** Add a new entry to the EXPLAIN QUERY PLAN data 1904*/ 1905static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1906 EQPGraphRow *pNew; 1907 int nText = strlen30(zText); 1908 if( p->autoEQPtest ){ 1909 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1910 } 1911 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1912 shell_check_oom(pNew); 1913 pNew->iEqpId = iEqpId; 1914 pNew->iParentId = p2; 1915 memcpy(pNew->zText, zText, nText+1); 1916 pNew->pNext = 0; 1917 if( p->sGraph.pLast ){ 1918 p->sGraph.pLast->pNext = pNew; 1919 }else{ 1920 p->sGraph.pRow = pNew; 1921 } 1922 p->sGraph.pLast = pNew; 1923} 1924 1925/* 1926** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1927** in p->sGraph. 1928*/ 1929static void eqp_reset(ShellState *p){ 1930 EQPGraphRow *pRow, *pNext; 1931 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1932 pNext = pRow->pNext; 1933 sqlite3_free(pRow); 1934 } 1935 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1936} 1937 1938/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1939** pOld, or return the first such line if pOld is NULL 1940*/ 1941static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1942 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1943 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1944 return pRow; 1945} 1946 1947/* Render a single level of the graph that has iEqpId as its parent. Called 1948** recursively to render sublevels. 1949*/ 1950static void eqp_render_level(ShellState *p, int iEqpId){ 1951 EQPGraphRow *pRow, *pNext; 1952 int n = strlen30(p->sGraph.zPrefix); 1953 char *z; 1954 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1955 pNext = eqp_next_row(p, iEqpId, pRow); 1956 z = pRow->zText; 1957 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, 1958 pNext ? "|--" : "`--", z); 1959 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1960 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 1961 eqp_render_level(p, pRow->iEqpId); 1962 p->sGraph.zPrefix[n] = 0; 1963 } 1964 } 1965} 1966 1967/* 1968** Display and reset the EXPLAIN QUERY PLAN data 1969*/ 1970static void eqp_render(ShellState *p){ 1971 EQPGraphRow *pRow = p->sGraph.pRow; 1972 if( pRow ){ 1973 if( pRow->zText[0]=='-' ){ 1974 if( pRow->pNext==0 ){ 1975 eqp_reset(p); 1976 return; 1977 } 1978 utf8_printf(p->out, "%s\n", pRow->zText+3); 1979 p->sGraph.pRow = pRow->pNext; 1980 sqlite3_free(pRow); 1981 }else{ 1982 utf8_printf(p->out, "QUERY PLAN\n"); 1983 } 1984 p->sGraph.zPrefix[0] = 0; 1985 eqp_render_level(p, 0); 1986 eqp_reset(p); 1987 } 1988} 1989 1990#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1991/* 1992** Progress handler callback. 1993*/ 1994static int progress_handler(void *pClientData) { 1995 ShellState *p = (ShellState*)pClientData; 1996 p->nProgress++; 1997 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 1998 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 1999 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 2000 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 2001 return 1; 2002 } 2003 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 2004 raw_printf(p->out, "Progress %u\n", p->nProgress); 2005 } 2006 return 0; 2007} 2008#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 2009 2010/* 2011** Print N dashes 2012*/ 2013static void print_dashes(FILE *out, int N){ 2014 const char zDash[] = "--------------------------------------------------"; 2015 const int nDash = sizeof(zDash) - 1; 2016 while( N>nDash ){ 2017 fputs(zDash, out); 2018 N -= nDash; 2019 } 2020 raw_printf(out, "%.*s", N, zDash); 2021} 2022 2023/* 2024** Print a markdown or table-style row separator using ascii-art 2025*/ 2026static void print_row_separator( 2027 ShellState *p, 2028 int nArg, 2029 const char *zSep 2030){ 2031 int i; 2032 if( nArg>0 ){ 2033 fputs(zSep, p->out); 2034 print_dashes(p->out, p->actualWidth[0]+2); 2035 for(i=1; i<nArg; i++){ 2036 fputs(zSep, p->out); 2037 print_dashes(p->out, p->actualWidth[i]+2); 2038 } 2039 fputs(zSep, p->out); 2040 } 2041 fputs("\n", p->out); 2042} 2043 2044/* 2045** This is the callback routine that the shell 2046** invokes for each row of a query result. 2047*/ 2048static int shell_callback( 2049 void *pArg, 2050 int nArg, /* Number of result columns */ 2051 char **azArg, /* Text of each result column */ 2052 char **azCol, /* Column names */ 2053 int *aiType /* Column types. Might be NULL */ 2054){ 2055 int i; 2056 ShellState *p = (ShellState*)pArg; 2057 2058 if( azArg==0 ) return 0; 2059 switch( p->cMode ){ 2060 case MODE_Count: 2061 case MODE_Off: { 2062 break; 2063 } 2064 case MODE_Line: { 2065 int w = 5; 2066 if( azArg==0 ) break; 2067 for(i=0; i<nArg; i++){ 2068 int len = strlen30(azCol[i] ? azCol[i] : ""); 2069 if( len>w ) w = len; 2070 } 2071 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 2072 for(i=0; i<nArg; i++){ 2073 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 2074 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 2075 } 2076 break; 2077 } 2078 case MODE_Explain: { 2079 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13}; 2080 if( nArg>ArraySize(aExplainWidth) ){ 2081 nArg = ArraySize(aExplainWidth); 2082 } 2083 if( p->cnt++==0 ){ 2084 for(i=0; i<nArg; i++){ 2085 int w = aExplainWidth[i]; 2086 utf8_width_print(p->out, w, azCol[i]); 2087 fputs(i==nArg-1 ? "\n" : " ", p->out); 2088 } 2089 for(i=0; i<nArg; i++){ 2090 int w = aExplainWidth[i]; 2091 print_dashes(p->out, w); 2092 fputs(i==nArg-1 ? "\n" : " ", p->out); 2093 } 2094 } 2095 if( azArg==0 ) break; 2096 for(i=0; i<nArg; i++){ 2097 int w = aExplainWidth[i]; 2098 if( i==nArg-1 ) w = 0; 2099 if( azArg[i] && strlenChar(azArg[i])>w ){ 2100 w = strlenChar(azArg[i]); 2101 } 2102 if( i==1 && p->aiIndent && p->pStmt ){ 2103 if( p->iIndent<p->nIndent ){ 2104 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 2105 } 2106 p->iIndent++; 2107 } 2108 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 2109 fputs(i==nArg-1 ? "\n" : " ", p->out); 2110 } 2111 break; 2112 } 2113 case MODE_Semi: { /* .schema and .fullschema output */ 2114 printSchemaLine(p->out, azArg[0], ";\n"); 2115 break; 2116 } 2117 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 2118 char *z; 2119 int j; 2120 int nParen = 0; 2121 char cEnd = 0; 2122 char c; 2123 int nLine = 0; 2124 assert( nArg==1 ); 2125 if( azArg[0]==0 ) break; 2126 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 2127 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 2128 ){ 2129 utf8_printf(p->out, "%s;\n", azArg[0]); 2130 break; 2131 } 2132 z = sqlite3_mprintf("%s", azArg[0]); 2133 shell_check_oom(z); 2134 j = 0; 2135 for(i=0; IsSpace(z[i]); i++){} 2136 for(; (c = z[i])!=0; i++){ 2137 if( IsSpace(c) ){ 2138 if( z[j-1]=='\r' ) z[j-1] = '\n'; 2139 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 2140 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 2141 j--; 2142 } 2143 z[j++] = c; 2144 } 2145 while( j>0 && IsSpace(z[j-1]) ){ j--; } 2146 z[j] = 0; 2147 if( strlen30(z)>=79 ){ 2148 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ 2149 if( c==cEnd ){ 2150 cEnd = 0; 2151 }else if( c=='"' || c=='\'' || c=='`' ){ 2152 cEnd = c; 2153 }else if( c=='[' ){ 2154 cEnd = ']'; 2155 }else if( c=='-' && z[i+1]=='-' ){ 2156 cEnd = '\n'; 2157 }else if( c=='(' ){ 2158 nParen++; 2159 }else if( c==')' ){ 2160 nParen--; 2161 if( nLine>0 && nParen==0 && j>0 ){ 2162 printSchemaLineN(p->out, z, j, "\n"); 2163 j = 0; 2164 } 2165 } 2166 z[j++] = c; 2167 if( nParen==1 && cEnd==0 2168 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 2169 ){ 2170 if( c=='\n' ) j--; 2171 printSchemaLineN(p->out, z, j, "\n "); 2172 j = 0; 2173 nLine++; 2174 while( IsSpace(z[i+1]) ){ i++; } 2175 } 2176 } 2177 z[j] = 0; 2178 } 2179 printSchemaLine(p->out, z, ";\n"); 2180 sqlite3_free(z); 2181 break; 2182 } 2183 case MODE_List: { 2184 if( p->cnt++==0 && p->showHeader ){ 2185 for(i=0; i<nArg; i++){ 2186 utf8_printf(p->out,"%s%s",azCol[i], 2187 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2188 } 2189 } 2190 if( azArg==0 ) break; 2191 for(i=0; i<nArg; i++){ 2192 char *z = azArg[i]; 2193 if( z==0 ) z = p->nullValue; 2194 utf8_printf(p->out, "%s", z); 2195 if( i<nArg-1 ){ 2196 utf8_printf(p->out, "%s", p->colSeparator); 2197 }else{ 2198 utf8_printf(p->out, "%s", p->rowSeparator); 2199 } 2200 } 2201 break; 2202 } 2203 case MODE_Html: { 2204 if( p->cnt++==0 && p->showHeader ){ 2205 raw_printf(p->out,"<TR>"); 2206 for(i=0; i<nArg; i++){ 2207 raw_printf(p->out,"<TH>"); 2208 output_html_string(p->out, azCol[i]); 2209 raw_printf(p->out,"</TH>\n"); 2210 } 2211 raw_printf(p->out,"</TR>\n"); 2212 } 2213 if( azArg==0 ) break; 2214 raw_printf(p->out,"<TR>"); 2215 for(i=0; i<nArg; i++){ 2216 raw_printf(p->out,"<TD>"); 2217 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2218 raw_printf(p->out,"</TD>\n"); 2219 } 2220 raw_printf(p->out,"</TR>\n"); 2221 break; 2222 } 2223 case MODE_Tcl: { 2224 if( p->cnt++==0 && p->showHeader ){ 2225 for(i=0; i<nArg; i++){ 2226 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2227 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2228 } 2229 utf8_printf(p->out, "%s", p->rowSeparator); 2230 } 2231 if( azArg==0 ) break; 2232 for(i=0; i<nArg; i++){ 2233 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2234 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2235 } 2236 utf8_printf(p->out, "%s", p->rowSeparator); 2237 break; 2238 } 2239 case MODE_Csv: { 2240 setBinaryMode(p->out, 1); 2241 if( p->cnt++==0 && p->showHeader ){ 2242 for(i=0; i<nArg; i++){ 2243 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2244 } 2245 utf8_printf(p->out, "%s", p->rowSeparator); 2246 } 2247 if( nArg>0 ){ 2248 for(i=0; i<nArg; i++){ 2249 output_csv(p, azArg[i], i<nArg-1); 2250 } 2251 utf8_printf(p->out, "%s", p->rowSeparator); 2252 } 2253 setTextMode(p->out, 1); 2254 break; 2255 } 2256 case MODE_Insert: { 2257 if( azArg==0 ) break; 2258 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2259 if( p->showHeader ){ 2260 raw_printf(p->out,"("); 2261 for(i=0; i<nArg; i++){ 2262 if( i>0 ) raw_printf(p->out, ","); 2263 if( quoteChar(azCol[i]) ){ 2264 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2265 shell_check_oom(z); 2266 utf8_printf(p->out, "%s", z); 2267 sqlite3_free(z); 2268 }else{ 2269 raw_printf(p->out, "%s", azCol[i]); 2270 } 2271 } 2272 raw_printf(p->out,")"); 2273 } 2274 p->cnt++; 2275 for(i=0; i<nArg; i++){ 2276 raw_printf(p->out, i>0 ? "," : " VALUES("); 2277 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2278 utf8_printf(p->out,"NULL"); 2279 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2280 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2281 output_quoted_string(p->out, azArg[i]); 2282 }else{ 2283 output_quoted_escaped_string(p->out, azArg[i]); 2284 } 2285 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2286 utf8_printf(p->out,"%s", azArg[i]); 2287 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2288 char z[50]; 2289 double r = sqlite3_column_double(p->pStmt, i); 2290 sqlite3_uint64 ur; 2291 memcpy(&ur,&r,sizeof(r)); 2292 if( ur==0x7ff0000000000000LL ){ 2293 raw_printf(p->out, "1e999"); 2294 }else if( ur==0xfff0000000000000LL ){ 2295 raw_printf(p->out, "-1e999"); 2296 }else{ 2297 sqlite3_snprintf(50,z,"%!.20g", r); 2298 raw_printf(p->out, "%s", z); 2299 } 2300 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2301 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2302 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2303 output_hex_blob(p->out, pBlob, nBlob); 2304 }else if( isNumber(azArg[i], 0) ){ 2305 utf8_printf(p->out,"%s", azArg[i]); 2306 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2307 output_quoted_string(p->out, azArg[i]); 2308 }else{ 2309 output_quoted_escaped_string(p->out, azArg[i]); 2310 } 2311 } 2312 raw_printf(p->out,");\n"); 2313 break; 2314 } 2315 case MODE_Json: { 2316 if( azArg==0 ) break; 2317 if( p->cnt==0 ){ 2318 fputs("[{", p->out); 2319 }else{ 2320 fputs(",\n{", p->out); 2321 } 2322 p->cnt++; 2323 for(i=0; i<nArg; i++){ 2324 output_json_string(p->out, azCol[i], -1); 2325 putc(':', p->out); 2326 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2327 fputs("null",p->out); 2328 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2329 char z[50]; 2330 double r = sqlite3_column_double(p->pStmt, i); 2331 sqlite3_uint64 ur; 2332 memcpy(&ur,&r,sizeof(r)); 2333 if( ur==0x7ff0000000000000LL ){ 2334 raw_printf(p->out, "1e999"); 2335 }else if( ur==0xfff0000000000000LL ){ 2336 raw_printf(p->out, "-1e999"); 2337 }else{ 2338 sqlite3_snprintf(50,z,"%!.20g", r); 2339 raw_printf(p->out, "%s", z); 2340 } 2341 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2342 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2343 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2344 output_json_string(p->out, pBlob, nBlob); 2345 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2346 output_json_string(p->out, azArg[i], -1); 2347 }else{ 2348 utf8_printf(p->out,"%s", azArg[i]); 2349 } 2350 if( i<nArg-1 ){ 2351 putc(',', p->out); 2352 } 2353 } 2354 putc('}', p->out); 2355 break; 2356 } 2357 case MODE_Quote: { 2358 if( azArg==0 ) break; 2359 if( p->cnt==0 && p->showHeader ){ 2360 for(i=0; i<nArg; i++){ 2361 if( i>0 ) fputs(p->colSeparator, p->out); 2362 output_quoted_string(p->out, azCol[i]); 2363 } 2364 fputs(p->rowSeparator, p->out); 2365 } 2366 p->cnt++; 2367 for(i=0; i<nArg; i++){ 2368 if( i>0 ) fputs(p->colSeparator, p->out); 2369 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2370 utf8_printf(p->out,"NULL"); 2371 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2372 output_quoted_string(p->out, azArg[i]); 2373 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2374 utf8_printf(p->out,"%s", azArg[i]); 2375 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2376 char z[50]; 2377 double r = sqlite3_column_double(p->pStmt, i); 2378 sqlite3_snprintf(50,z,"%!.20g", r); 2379 raw_printf(p->out, "%s", z); 2380 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2381 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2382 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2383 output_hex_blob(p->out, pBlob, nBlob); 2384 }else if( isNumber(azArg[i], 0) ){ 2385 utf8_printf(p->out,"%s", azArg[i]); 2386 }else{ 2387 output_quoted_string(p->out, azArg[i]); 2388 } 2389 } 2390 fputs(p->rowSeparator, p->out); 2391 break; 2392 } 2393 case MODE_Ascii: { 2394 if( p->cnt++==0 && p->showHeader ){ 2395 for(i=0; i<nArg; i++){ 2396 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2397 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2398 } 2399 utf8_printf(p->out, "%s", p->rowSeparator); 2400 } 2401 if( azArg==0 ) break; 2402 for(i=0; i<nArg; i++){ 2403 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2404 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2405 } 2406 utf8_printf(p->out, "%s", p->rowSeparator); 2407 break; 2408 } 2409 case MODE_EQP: { 2410 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2411 break; 2412 } 2413 } 2414 return 0; 2415} 2416 2417/* 2418** This is the callback routine that the SQLite library 2419** invokes for each row of a query result. 2420*/ 2421static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2422 /* since we don't have type info, call the shell_callback with a NULL value */ 2423 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2424} 2425 2426/* 2427** This is the callback routine from sqlite3_exec() that appends all 2428** output onto the end of a ShellText object. 2429*/ 2430static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2431 ShellText *p = (ShellText*)pArg; 2432 int i; 2433 UNUSED_PARAMETER(az); 2434 if( azArg==0 ) return 0; 2435 if( p->n ) appendText(p, "|", 0); 2436 for(i=0; i<nArg; i++){ 2437 if( i ) appendText(p, ",", 0); 2438 if( azArg[i] ) appendText(p, azArg[i], 0); 2439 } 2440 return 0; 2441} 2442 2443/* 2444** Generate an appropriate SELFTEST table in the main database. 2445*/ 2446static void createSelftestTable(ShellState *p){ 2447 char *zErrMsg = 0; 2448 sqlite3_exec(p->db, 2449 "SAVEPOINT selftest_init;\n" 2450 "CREATE TABLE IF NOT EXISTS selftest(\n" 2451 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2452 " op TEXT,\n" /* Operator: memo run */ 2453 " cmd TEXT,\n" /* Command text */ 2454 " ans TEXT\n" /* Desired answer */ 2455 ");" 2456 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2457 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2458 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2459 " 'memo','Tests generated by --init');\n" 2460 "INSERT INTO [_shell$self]\n" 2461 " SELECT 'run',\n" 2462 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2463 "FROM sqlite_schema ORDER BY 2'',224))',\n" 2464 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2465 "FROM sqlite_schema ORDER BY 2',224));\n" 2466 "INSERT INTO [_shell$self]\n" 2467 " SELECT 'run'," 2468 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2469 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2470 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2471 " FROM (\n" 2472 " SELECT name FROM sqlite_schema\n" 2473 " WHERE type='table'\n" 2474 " AND name<>'selftest'\n" 2475 " AND coalesce(rootpage,0)>0\n" 2476 " )\n" 2477 " ORDER BY name;\n" 2478 "INSERT INTO [_shell$self]\n" 2479 " VALUES('run','PRAGMA integrity_check','ok');\n" 2480 "INSERT INTO selftest(tno,op,cmd,ans)" 2481 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2482 "DROP TABLE [_shell$self];" 2483 ,0,0,&zErrMsg); 2484 if( zErrMsg ){ 2485 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2486 sqlite3_free(zErrMsg); 2487 } 2488 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2489} 2490 2491 2492/* 2493** Set the destination table field of the ShellState structure to 2494** the name of the table given. Escape any quote characters in the 2495** table name. 2496*/ 2497static void set_table_name(ShellState *p, const char *zName){ 2498 int i, n; 2499 char cQuote; 2500 char *z; 2501 2502 if( p->zDestTable ){ 2503 free(p->zDestTable); 2504 p->zDestTable = 0; 2505 } 2506 if( zName==0 ) return; 2507 cQuote = quoteChar(zName); 2508 n = strlen30(zName); 2509 if( cQuote ) n += n+2; 2510 z = p->zDestTable = malloc( n+1 ); 2511 shell_check_oom(z); 2512 n = 0; 2513 if( cQuote ) z[n++] = cQuote; 2514 for(i=0; zName[i]; i++){ 2515 z[n++] = zName[i]; 2516 if( zName[i]==cQuote ) z[n++] = cQuote; 2517 } 2518 if( cQuote ) z[n++] = cQuote; 2519 z[n] = 0; 2520} 2521 2522/* 2523** Maybe construct two lines of text that point out the position of a 2524** syntax error. Return a pointer to the text, in memory obtained from 2525** sqlite3_malloc(). Or, if the most recent error does not involve a 2526** specific token that we can point to, return an empty string. 2527** 2528** In all cases, the memory returned is obtained from sqlite3_malloc64() 2529** and should be released by the caller invoking sqlite3_free(). 2530*/ 2531static char *shell_error_context(const char *zSql, sqlite3 *db){ 2532 int iOffset; 2533 size_t len; 2534 char *zCode; 2535 char *zMsg; 2536 int i; 2537 if( db==0 2538 || zSql==0 2539 || (iOffset = sqlite3_error_offset(db))<0 2540 ){ 2541 return sqlite3_mprintf(""); 2542 } 2543 while( iOffset>50 ){ 2544 iOffset--; 2545 zSql++; 2546 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } 2547 } 2548 len = strlen(zSql); 2549 if( len>78 ){ 2550 len = 78; 2551 while( (zSql[len]&0xc0)==0x80 ) len--; 2552 } 2553 zCode = sqlite3_mprintf("%.*s", len, zSql); 2554 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; } 2555 if( iOffset<25 ){ 2556 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode, iOffset, ""); 2557 }else{ 2558 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode, iOffset-14, ""); 2559 } 2560 return zMsg; 2561} 2562 2563 2564/* 2565** Execute a query statement that will generate SQL output. Print 2566** the result columns, comma-separated, on a line and then add a 2567** semicolon terminator to the end of that line. 2568** 2569** If the number of columns is 1 and that column contains text "--" 2570** then write the semicolon on a separate line. That way, if a 2571** "--" comment occurs at the end of the statement, the comment 2572** won't consume the semicolon terminator. 2573*/ 2574static int run_table_dump_query( 2575 ShellState *p, /* Query context */ 2576 const char *zSelect /* SELECT statement to extract content */ 2577){ 2578 sqlite3_stmt *pSelect; 2579 int rc; 2580 int nResult; 2581 int i; 2582 const char *z; 2583 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2584 if( rc!=SQLITE_OK || !pSelect ){ 2585 char *zContext = shell_error_context(zSelect, p->db); 2586 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc, 2587 sqlite3_errmsg(p->db), zContext); 2588 sqlite3_free(zContext); 2589 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2590 return rc; 2591 } 2592 rc = sqlite3_step(pSelect); 2593 nResult = sqlite3_column_count(pSelect); 2594 while( rc==SQLITE_ROW ){ 2595 z = (const char*)sqlite3_column_text(pSelect, 0); 2596 utf8_printf(p->out, "%s", z); 2597 for(i=1; i<nResult; i++){ 2598 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2599 } 2600 if( z==0 ) z = ""; 2601 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2602 if( z[0] ){ 2603 raw_printf(p->out, "\n;\n"); 2604 }else{ 2605 raw_printf(p->out, ";\n"); 2606 } 2607 rc = sqlite3_step(pSelect); 2608 } 2609 rc = sqlite3_finalize(pSelect); 2610 if( rc!=SQLITE_OK ){ 2611 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2612 sqlite3_errmsg(p->db)); 2613 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2614 } 2615 return rc; 2616} 2617 2618/* 2619** Allocate space and save off string indicating current error. 2620*/ 2621static char *save_err_msg( 2622 sqlite3 *db, /* Database to query */ 2623 const char *zWhen, /* Qualifier (format) wrapper */ 2624 int rc, /* Error code returned from API */ 2625 const char *zSql /* SQL string, or NULL */ 2626){ 2627 char *zErr; 2628 char *zContext; 2629 if( zWhen==0 ) zWhen = "%s (%d)%s"; 2630 zContext = shell_error_context(zSql, db); 2631 zErr = sqlite3_mprintf(zWhen, sqlite3_errmsg(db), rc, zContext); 2632 shell_check_oom(zErr); 2633 sqlite3_free(zContext); 2634 return zErr; 2635} 2636 2637#ifdef __linux__ 2638/* 2639** Attempt to display I/O stats on Linux using /proc/PID/io 2640*/ 2641static void displayLinuxIoStats(FILE *out){ 2642 FILE *in; 2643 char z[200]; 2644 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2645 in = fopen(z, "rb"); 2646 if( in==0 ) return; 2647 while( fgets(z, sizeof(z), in)!=0 ){ 2648 static const struct { 2649 const char *zPattern; 2650 const char *zDesc; 2651 } aTrans[] = { 2652 { "rchar: ", "Bytes received by read():" }, 2653 { "wchar: ", "Bytes sent to write():" }, 2654 { "syscr: ", "Read() system calls:" }, 2655 { "syscw: ", "Write() system calls:" }, 2656 { "read_bytes: ", "Bytes read from storage:" }, 2657 { "write_bytes: ", "Bytes written to storage:" }, 2658 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2659 }; 2660 int i; 2661 for(i=0; i<ArraySize(aTrans); i++){ 2662 int n = strlen30(aTrans[i].zPattern); 2663 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2664 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2665 break; 2666 } 2667 } 2668 } 2669 fclose(in); 2670} 2671#endif 2672 2673/* 2674** Display a single line of status using 64-bit values. 2675*/ 2676static void displayStatLine( 2677 ShellState *p, /* The shell context */ 2678 char *zLabel, /* Label for this one line */ 2679 char *zFormat, /* Format for the result */ 2680 int iStatusCtrl, /* Which status to display */ 2681 int bReset /* True to reset the stats */ 2682){ 2683 sqlite3_int64 iCur = -1; 2684 sqlite3_int64 iHiwtr = -1; 2685 int i, nPercent; 2686 char zLine[200]; 2687 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2688 for(i=0, nPercent=0; zFormat[i]; i++){ 2689 if( zFormat[i]=='%' ) nPercent++; 2690 } 2691 if( nPercent>1 ){ 2692 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2693 }else{ 2694 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2695 } 2696 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2697} 2698 2699/* 2700** Display memory stats. 2701*/ 2702static int display_stats( 2703 sqlite3 *db, /* Database to query */ 2704 ShellState *pArg, /* Pointer to ShellState */ 2705 int bReset /* True to reset the stats */ 2706){ 2707 int iCur; 2708 int iHiwtr; 2709 FILE *out; 2710 if( pArg==0 || pArg->out==0 ) return 0; 2711 out = pArg->out; 2712 2713 if( pArg->pStmt && pArg->statsOn==2 ){ 2714 int nCol, i, x; 2715 sqlite3_stmt *pStmt = pArg->pStmt; 2716 char z[100]; 2717 nCol = sqlite3_column_count(pStmt); 2718 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2719 for(i=0; i<nCol; i++){ 2720 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2721 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2722#ifndef SQLITE_OMIT_DECLTYPE 2723 sqlite3_snprintf(30, z+x, "declared type:"); 2724 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2725#endif 2726#ifdef SQLITE_ENABLE_COLUMN_METADATA 2727 sqlite3_snprintf(30, z+x, "database name:"); 2728 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2729 sqlite3_snprintf(30, z+x, "table name:"); 2730 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2731 sqlite3_snprintf(30, z+x, "origin name:"); 2732 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2733#endif 2734 } 2735 } 2736 2737 if( pArg->statsOn==3 ){ 2738 if( pArg->pStmt ){ 2739 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2740 raw_printf(pArg->out, "VM-steps: %d\n", iCur); 2741 } 2742 return 0; 2743 } 2744 2745 displayStatLine(pArg, "Memory Used:", 2746 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2747 displayStatLine(pArg, "Number of Outstanding Allocations:", 2748 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2749 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2750 displayStatLine(pArg, "Number of Pcache Pages Used:", 2751 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2752 } 2753 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2754 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2755 displayStatLine(pArg, "Largest Allocation:", 2756 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2757 displayStatLine(pArg, "Largest Pcache Allocation:", 2758 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2759#ifdef YYTRACKMAXSTACKDEPTH 2760 displayStatLine(pArg, "Deepest Parser Stack:", 2761 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2762#endif 2763 2764 if( db ){ 2765 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2766 iHiwtr = iCur = -1; 2767 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2768 &iCur, &iHiwtr, bReset); 2769 raw_printf(pArg->out, 2770 "Lookaside Slots Used: %d (max %d)\n", 2771 iCur, iHiwtr); 2772 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2773 &iCur, &iHiwtr, bReset); 2774 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2775 iHiwtr); 2776 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2777 &iCur, &iHiwtr, bReset); 2778 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2779 iHiwtr); 2780 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2781 &iCur, &iHiwtr, bReset); 2782 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2783 iHiwtr); 2784 } 2785 iHiwtr = iCur = -1; 2786 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2787 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2788 iCur); 2789 iHiwtr = iCur = -1; 2790 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2791 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2792 iHiwtr = iCur = -1; 2793 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2794 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2795 iHiwtr = iCur = -1; 2796 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2797 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2798 iHiwtr = iCur = -1; 2799 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2800 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2801 iHiwtr = iCur = -1; 2802 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2803 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2804 iCur); 2805 iHiwtr = iCur = -1; 2806 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2807 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2808 iCur); 2809 } 2810 2811 if( pArg->pStmt ){ 2812 int iHit, iMiss; 2813 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2814 bReset); 2815 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2816 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2817 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2818 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2819 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2820 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset); 2821 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset); 2822 if( iHit || iMiss ){ 2823 raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n", 2824 iHit, iHit+iMiss); 2825 } 2826 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2827 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2828 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); 2829 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2830 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2831 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2832 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2833 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2834 } 2835 2836#ifdef __linux__ 2837 displayLinuxIoStats(pArg->out); 2838#endif 2839 2840 /* Do not remove this machine readable comment: extra-stats-output-here */ 2841 2842 return 0; 2843} 2844 2845/* 2846** Display scan stats. 2847*/ 2848static void display_scanstats( 2849 sqlite3 *db, /* Database to query */ 2850 ShellState *pArg /* Pointer to ShellState */ 2851){ 2852#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2853 UNUSED_PARAMETER(db); 2854 UNUSED_PARAMETER(pArg); 2855#else 2856 int i, k, n, mx; 2857 raw_printf(pArg->out, "-------- scanstats --------\n"); 2858 mx = 0; 2859 for(k=0; k<=mx; k++){ 2860 double rEstLoop = 1.0; 2861 for(i=n=0; 1; i++){ 2862 sqlite3_stmt *p = pArg->pStmt; 2863 sqlite3_int64 nLoop, nVisit; 2864 double rEst; 2865 int iSid; 2866 const char *zExplain; 2867 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2868 break; 2869 } 2870 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2871 if( iSid>mx ) mx = iSid; 2872 if( iSid!=k ) continue; 2873 if( n==0 ){ 2874 rEstLoop = (double)nLoop; 2875 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2876 } 2877 n++; 2878 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2879 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2880 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2881 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2882 rEstLoop *= rEst; 2883 raw_printf(pArg->out, 2884 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2885 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2886 ); 2887 } 2888 } 2889 raw_printf(pArg->out, "---------------------------\n"); 2890#endif 2891} 2892 2893/* 2894** Parameter azArray points to a zero-terminated array of strings. zStr 2895** points to a single nul-terminated string. Return non-zero if zStr 2896** is equal, according to strcmp(), to any of the strings in the array. 2897** Otherwise, return zero. 2898*/ 2899static int str_in_array(const char *zStr, const char **azArray){ 2900 int i; 2901 for(i=0; azArray[i]; i++){ 2902 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2903 } 2904 return 0; 2905} 2906 2907/* 2908** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2909** and populate the ShellState.aiIndent[] array with the number of 2910** spaces each opcode should be indented before it is output. 2911** 2912** The indenting rules are: 2913** 2914** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2915** all opcodes that occur between the p2 jump destination and the opcode 2916** itself by 2 spaces. 2917** 2918** * For each "Goto", if the jump destination is earlier in the program 2919** and ends on one of: 2920** Yield SeekGt SeekLt RowSetRead Rewind 2921** or if the P1 parameter is one instead of zero, 2922** then indent all opcodes between the earlier instruction 2923** and "Goto" by 2 spaces. 2924*/ 2925static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2926 const char *zSql; /* The text of the SQL statement */ 2927 const char *z; /* Used to check if this is an EXPLAIN */ 2928 int *abYield = 0; /* True if op is an OP_Yield */ 2929 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2930 int iOp; /* Index of operation in p->aiIndent[] */ 2931 2932 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2933 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2934 "Rewind", 0 }; 2935 const char *azGoto[] = { "Goto", 0 }; 2936 2937 /* Try to figure out if this is really an EXPLAIN statement. If this 2938 ** cannot be verified, return early. */ 2939 if( sqlite3_column_count(pSql)!=8 ){ 2940 p->cMode = p->mode; 2941 return; 2942 } 2943 zSql = sqlite3_sql(pSql); 2944 if( zSql==0 ) return; 2945 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2946 if( sqlite3_strnicmp(z, "explain", 7) ){ 2947 p->cMode = p->mode; 2948 return; 2949 } 2950 2951 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2952 int i; 2953 int iAddr = sqlite3_column_int(pSql, 0); 2954 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2955 2956 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2957 ** p2 is an instruction address, set variable p2op to the index of that 2958 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2959 ** the current instruction is part of a sub-program generated by an 2960 ** SQL trigger or foreign key. */ 2961 int p2 = sqlite3_column_int(pSql, 3); 2962 int p2op = (p2 + (iOp-iAddr)); 2963 2964 /* Grow the p->aiIndent array as required */ 2965 if( iOp>=nAlloc ){ 2966 if( iOp==0 ){ 2967 /* Do further verfication that this is explain output. Abort if 2968 ** it is not */ 2969 static const char *explainCols[] = { 2970 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2971 int jj; 2972 for(jj=0; jj<ArraySize(explainCols); jj++){ 2973 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2974 p->cMode = p->mode; 2975 sqlite3_reset(pSql); 2976 return; 2977 } 2978 } 2979 } 2980 nAlloc += 100; 2981 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2982 shell_check_oom(p->aiIndent); 2983 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2984 shell_check_oom(abYield); 2985 } 2986 abYield[iOp] = str_in_array(zOp, azYield); 2987 p->aiIndent[iOp] = 0; 2988 p->nIndent = iOp+1; 2989 2990 if( str_in_array(zOp, azNext) ){ 2991 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2992 } 2993 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 2994 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 2995 ){ 2996 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2997 } 2998 } 2999 3000 p->iIndent = 0; 3001 sqlite3_free(abYield); 3002 sqlite3_reset(pSql); 3003} 3004 3005/* 3006** Free the array allocated by explain_data_prepare(). 3007*/ 3008static void explain_data_delete(ShellState *p){ 3009 sqlite3_free(p->aiIndent); 3010 p->aiIndent = 0; 3011 p->nIndent = 0; 3012 p->iIndent = 0; 3013} 3014 3015/* 3016** Disable and restore .wheretrace and .selecttrace settings. 3017*/ 3018static unsigned int savedSelectTrace; 3019static unsigned int savedWhereTrace; 3020static void disable_debug_trace_modes(void){ 3021 unsigned int zero = 0; 3022 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace); 3023 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero); 3024 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace); 3025 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero); 3026} 3027static void restore_debug_trace_modes(void){ 3028 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace); 3029 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace); 3030} 3031 3032/* Create the TEMP table used to store parameter bindings */ 3033static void bind_table_init(ShellState *p){ 3034 int wrSchema = 0; 3035 int defensiveMode = 0; 3036 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); 3037 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); 3038 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 3039 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 3040 sqlite3_exec(p->db, 3041 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 3042 " key TEXT PRIMARY KEY,\n" 3043 " value\n" 3044 ") WITHOUT ROWID;", 3045 0, 0, 0); 3046 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 3047 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); 3048} 3049 3050/* 3051** Bind parameters on a prepared statement. 3052** 3053** Parameter bindings are taken from a TEMP table of the form: 3054** 3055** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 3056** WITHOUT ROWID; 3057** 3058** No bindings occur if this table does not exist. The name of the table 3059** begins with "sqlite_" so that it will not collide with ordinary application 3060** tables. The table must be in the TEMP schema. 3061*/ 3062static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 3063 int nVar; 3064 int i; 3065 int rc; 3066 sqlite3_stmt *pQ = 0; 3067 3068 nVar = sqlite3_bind_parameter_count(pStmt); 3069 if( nVar==0 ) return; /* Nothing to do */ 3070 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 3071 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 3072 return; /* Parameter table does not exist */ 3073 } 3074 rc = sqlite3_prepare_v2(pArg->db, 3075 "SELECT value FROM temp.sqlite_parameters" 3076 " WHERE key=?1", -1, &pQ, 0); 3077 if( rc || pQ==0 ) return; 3078 for(i=1; i<=nVar; i++){ 3079 char zNum[30]; 3080 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 3081 if( zVar==0 ){ 3082 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 3083 zVar = zNum; 3084 } 3085 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 3086 if( sqlite3_step(pQ)==SQLITE_ROW ){ 3087 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 3088 }else{ 3089 sqlite3_bind_null(pStmt, i); 3090 } 3091 sqlite3_reset(pQ); 3092 } 3093 sqlite3_finalize(pQ); 3094} 3095 3096/* 3097** UTF8 box-drawing characters. Imagine box lines like this: 3098** 3099** 1 3100** | 3101** 4 --+-- 2 3102** | 3103** 3 3104** 3105** Each box characters has between 2 and 4 of the lines leading from 3106** the center. The characters are here identified by the numbers of 3107** their corresponding lines. 3108*/ 3109#define BOX_24 "\342\224\200" /* U+2500 --- */ 3110#define BOX_13 "\342\224\202" /* U+2502 | */ 3111#define BOX_23 "\342\224\214" /* U+250c ,- */ 3112#define BOX_34 "\342\224\220" /* U+2510 -, */ 3113#define BOX_12 "\342\224\224" /* U+2514 '- */ 3114#define BOX_14 "\342\224\230" /* U+2518 -' */ 3115#define BOX_123 "\342\224\234" /* U+251c |- */ 3116#define BOX_134 "\342\224\244" /* U+2524 -| */ 3117#define BOX_234 "\342\224\254" /* U+252c -,- */ 3118#define BOX_124 "\342\224\264" /* U+2534 -'- */ 3119#define BOX_1234 "\342\224\274" /* U+253c -|- */ 3120 3121/* Draw horizontal line N characters long using unicode box 3122** characters 3123*/ 3124static void print_box_line(FILE *out, int N){ 3125 const char zDash[] = 3126 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 3127 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24; 3128 const int nDash = sizeof(zDash) - 1; 3129 N *= 3; 3130 while( N>nDash ){ 3131 utf8_printf(out, zDash); 3132 N -= nDash; 3133 } 3134 utf8_printf(out, "%.*s", N, zDash); 3135} 3136 3137/* 3138** Draw a horizontal separator for a MODE_Box table. 3139*/ 3140static void print_box_row_separator( 3141 ShellState *p, 3142 int nArg, 3143 const char *zSep1, 3144 const char *zSep2, 3145 const char *zSep3 3146){ 3147 int i; 3148 if( nArg>0 ){ 3149 utf8_printf(p->out, "%s", zSep1); 3150 print_box_line(p->out, p->actualWidth[0]+2); 3151 for(i=1; i<nArg; i++){ 3152 utf8_printf(p->out, "%s", zSep2); 3153 print_box_line(p->out, p->actualWidth[i]+2); 3154 } 3155 utf8_printf(p->out, "%s", zSep3); 3156 } 3157 fputs("\n", p->out); 3158} 3159 3160 3161 3162/* 3163** Run a prepared statement and output the result in one of the 3164** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table, 3165** or MODE_Box. 3166** 3167** This is different from ordinary exec_prepared_stmt() in that 3168** it has to run the entire query and gather the results into memory 3169** first, in order to determine column widths, before providing 3170** any output. 3171*/ 3172static void exec_prepared_stmt_columnar( 3173 ShellState *p, /* Pointer to ShellState */ 3174 sqlite3_stmt *pStmt /* Statment to run */ 3175){ 3176 sqlite3_int64 nRow = 0; 3177 int nColumn = 0; 3178 char **azData = 0; 3179 sqlite3_int64 nAlloc = 0; 3180 const char *z; 3181 int rc; 3182 sqlite3_int64 i, nData; 3183 int j, nTotal, w, n; 3184 const char *colSep = 0; 3185 const char *rowSep = 0; 3186 3187 rc = sqlite3_step(pStmt); 3188 if( rc!=SQLITE_ROW ) return; 3189 nColumn = sqlite3_column_count(pStmt); 3190 nAlloc = nColumn*4; 3191 if( nAlloc<=0 ) nAlloc = 1; 3192 azData = sqlite3_malloc64( nAlloc*sizeof(char*) ); 3193 shell_check_oom(azData); 3194 for(i=0; i<nColumn; i++){ 3195 azData[i] = strdup(sqlite3_column_name(pStmt,i)); 3196 } 3197 do{ 3198 if( (nRow+2)*nColumn >= nAlloc ){ 3199 nAlloc *= 2; 3200 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*)); 3201 shell_check_oom(azData); 3202 } 3203 nRow++; 3204 for(i=0; i<nColumn; i++){ 3205 z = (const char*)sqlite3_column_text(pStmt,i); 3206 azData[nRow*nColumn + i] = z ? strdup(z) : 0; 3207 } 3208 }while( sqlite3_step(pStmt)==SQLITE_ROW ); 3209 if( nColumn>p->nWidth ){ 3210 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); 3211 shell_check_oom(p->colWidth); 3212 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; 3213 p->nWidth = nColumn; 3214 p->actualWidth = &p->colWidth[nColumn]; 3215 } 3216 memset(p->actualWidth, 0, nColumn*sizeof(int)); 3217 for(i=0; i<nColumn; i++){ 3218 w = p->colWidth[i]; 3219 if( w<0 ) w = -w; 3220 p->actualWidth[i] = w; 3221 } 3222 nTotal = nColumn*(nRow+1); 3223 for(i=0; i<nTotal; i++){ 3224 z = azData[i]; 3225 if( z==0 ) z = p->nullValue; 3226 n = strlenChar(z); 3227 j = i%nColumn; 3228 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; 3229 } 3230 if( seenInterrupt ) goto columnar_end; 3231 if( nColumn==0 ) goto columnar_end; 3232 switch( p->cMode ){ 3233 case MODE_Column: { 3234 colSep = " "; 3235 rowSep = "\n"; 3236 if( p->showHeader ){ 3237 for(i=0; i<nColumn; i++){ 3238 w = p->actualWidth[i]; 3239 if( p->colWidth[i]<0 ) w = -w; 3240 utf8_width_print(p->out, w, azData[i]); 3241 fputs(i==nColumn-1?"\n":" ", p->out); 3242 } 3243 for(i=0; i<nColumn; i++){ 3244 print_dashes(p->out, p->actualWidth[i]); 3245 fputs(i==nColumn-1?"\n":" ", p->out); 3246 } 3247 } 3248 break; 3249 } 3250 case MODE_Table: { 3251 colSep = " | "; 3252 rowSep = " |\n"; 3253 print_row_separator(p, nColumn, "+"); 3254 fputs("| ", p->out); 3255 for(i=0; i<nColumn; i++){ 3256 w = p->actualWidth[i]; 3257 n = strlenChar(azData[i]); 3258 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3259 fputs(i==nColumn-1?" |\n":" | ", p->out); 3260 } 3261 print_row_separator(p, nColumn, "+"); 3262 break; 3263 } 3264 case MODE_Markdown: { 3265 colSep = " | "; 3266 rowSep = " |\n"; 3267 fputs("| ", p->out); 3268 for(i=0; i<nColumn; i++){ 3269 w = p->actualWidth[i]; 3270 n = strlenChar(azData[i]); 3271 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3272 fputs(i==nColumn-1?" |\n":" | ", p->out); 3273 } 3274 print_row_separator(p, nColumn, "|"); 3275 break; 3276 } 3277 case MODE_Box: { 3278 colSep = " " BOX_13 " "; 3279 rowSep = " " BOX_13 "\n"; 3280 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34); 3281 utf8_printf(p->out, BOX_13 " "); 3282 for(i=0; i<nColumn; i++){ 3283 w = p->actualWidth[i]; 3284 n = strlenChar(azData[i]); 3285 utf8_printf(p->out, "%*s%s%*s%s", 3286 (w-n)/2, "", azData[i], (w-n+1)/2, "", 3287 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); 3288 } 3289 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); 3290 break; 3291 } 3292 } 3293 for(i=nColumn, j=0; i<nTotal; i++, j++){ 3294 if( j==0 && p->cMode!=MODE_Column ){ 3295 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| "); 3296 } 3297 z = azData[i]; 3298 if( z==0 ) z = p->nullValue; 3299 w = p->actualWidth[j]; 3300 if( p->colWidth[j]<0 ) w = -w; 3301 utf8_width_print(p->out, w, z); 3302 if( j==nColumn-1 ){ 3303 utf8_printf(p->out, "%s", rowSep); 3304 j = -1; 3305 if( seenInterrupt ) goto columnar_end; 3306 }else{ 3307 utf8_printf(p->out, "%s", colSep); 3308 } 3309 } 3310 if( p->cMode==MODE_Table ){ 3311 print_row_separator(p, nColumn, "+"); 3312 }else if( p->cMode==MODE_Box ){ 3313 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14); 3314 } 3315columnar_end: 3316 if( seenInterrupt ){ 3317 utf8_printf(p->out, "Interrupt\n"); 3318 } 3319 nData = (nRow+1)*nColumn; 3320 for(i=0; i<nData; i++) free(azData[i]); 3321 sqlite3_free(azData); 3322} 3323 3324/* 3325** Run a prepared statement 3326*/ 3327static void exec_prepared_stmt( 3328 ShellState *pArg, /* Pointer to ShellState */ 3329 sqlite3_stmt *pStmt /* Statment to run */ 3330){ 3331 int rc; 3332 sqlite3_uint64 nRow = 0; 3333 3334 if( pArg->cMode==MODE_Column 3335 || pArg->cMode==MODE_Table 3336 || pArg->cMode==MODE_Box 3337 || pArg->cMode==MODE_Markdown 3338 ){ 3339 exec_prepared_stmt_columnar(pArg, pStmt); 3340 return; 3341 } 3342 3343 /* perform the first step. this will tell us if we 3344 ** have a result set or not and how wide it is. 3345 */ 3346 rc = sqlite3_step(pStmt); 3347 /* if we have a result set... */ 3348 if( SQLITE_ROW == rc ){ 3349 /* allocate space for col name ptr, value ptr, and type */ 3350 int nCol = sqlite3_column_count(pStmt); 3351 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 3352 if( !pData ){ 3353 shell_out_of_memory(); 3354 }else{ 3355 char **azCols = (char **)pData; /* Names of result columns */ 3356 char **azVals = &azCols[nCol]; /* Results */ 3357 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 3358 int i, x; 3359 assert(sizeof(int) <= sizeof(char *)); 3360 /* save off ptrs to column names */ 3361 for(i=0; i<nCol; i++){ 3362 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 3363 } 3364 do{ 3365 nRow++; 3366 /* extract the data and data types */ 3367 for(i=0; i<nCol; i++){ 3368 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 3369 if( x==SQLITE_BLOB 3370 && pArg 3371 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote) 3372 ){ 3373 azVals[i] = ""; 3374 }else{ 3375 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 3376 } 3377 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 3378 rc = SQLITE_NOMEM; 3379 break; /* from for */ 3380 } 3381 } /* end for */ 3382 3383 /* if data and types extracted successfully... */ 3384 if( SQLITE_ROW == rc ){ 3385 /* call the supplied callback with the result row data */ 3386 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 3387 rc = SQLITE_ABORT; 3388 }else{ 3389 rc = sqlite3_step(pStmt); 3390 } 3391 } 3392 } while( SQLITE_ROW == rc ); 3393 sqlite3_free(pData); 3394 if( pArg->cMode==MODE_Json ){ 3395 fputs("]\n", pArg->out); 3396 }else if( pArg->cMode==MODE_Count ){ 3397 char zBuf[200]; 3398 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n", 3399 nRow, nRow!=1 ? "s" : ""); 3400 printf("%s", zBuf); 3401 } 3402 } 3403 } 3404} 3405 3406#ifndef SQLITE_OMIT_VIRTUALTABLE 3407/* 3408** This function is called to process SQL if the previous shell command 3409** was ".expert". It passes the SQL in the second argument directly to 3410** the sqlite3expert object. 3411** 3412** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3413** code. In this case, (*pzErr) may be set to point to a buffer containing 3414** an English language error message. It is the responsibility of the 3415** caller to eventually free this buffer using sqlite3_free(). 3416*/ 3417static int expertHandleSQL( 3418 ShellState *pState, 3419 const char *zSql, 3420 char **pzErr 3421){ 3422 assert( pState->expert.pExpert ); 3423 assert( pzErr==0 || *pzErr==0 ); 3424 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 3425} 3426 3427/* 3428** This function is called either to silently clean up the object 3429** created by the ".expert" command (if bCancel==1), or to generate a 3430** report from it and then clean it up (if bCancel==0). 3431** 3432** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3433** code. In this case, (*pzErr) may be set to point to a buffer containing 3434** an English language error message. It is the responsibility of the 3435** caller to eventually free this buffer using sqlite3_free(). 3436*/ 3437static int expertFinish( 3438 ShellState *pState, 3439 int bCancel, 3440 char **pzErr 3441){ 3442 int rc = SQLITE_OK; 3443 sqlite3expert *p = pState->expert.pExpert; 3444 assert( p ); 3445 assert( bCancel || pzErr==0 || *pzErr==0 ); 3446 if( bCancel==0 ){ 3447 FILE *out = pState->out; 3448 int bVerbose = pState->expert.bVerbose; 3449 3450 rc = sqlite3_expert_analyze(p, pzErr); 3451 if( rc==SQLITE_OK ){ 3452 int nQuery = sqlite3_expert_count(p); 3453 int i; 3454 3455 if( bVerbose ){ 3456 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 3457 raw_printf(out, "-- Candidates -----------------------------\n"); 3458 raw_printf(out, "%s\n", zCand); 3459 } 3460 for(i=0; i<nQuery; i++){ 3461 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 3462 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 3463 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 3464 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 3465 if( bVerbose ){ 3466 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 3467 raw_printf(out, "%s\n\n", zSql); 3468 } 3469 raw_printf(out, "%s\n", zIdx); 3470 raw_printf(out, "%s\n", zEQP); 3471 } 3472 } 3473 } 3474 sqlite3_expert_destroy(p); 3475 pState->expert.pExpert = 0; 3476 return rc; 3477} 3478 3479/* 3480** Implementation of ".expert" dot command. 3481*/ 3482static int expertDotCommand( 3483 ShellState *pState, /* Current shell tool state */ 3484 char **azArg, /* Array of arguments passed to dot command */ 3485 int nArg /* Number of entries in azArg[] */ 3486){ 3487 int rc = SQLITE_OK; 3488 char *zErr = 0; 3489 int i; 3490 int iSample = 0; 3491 3492 assert( pState->expert.pExpert==0 ); 3493 memset(&pState->expert, 0, sizeof(ExpertInfo)); 3494 3495 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 3496 char *z = azArg[i]; 3497 int n; 3498 if( z[0]=='-' && z[1]=='-' ) z++; 3499 n = strlen30(z); 3500 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 3501 pState->expert.bVerbose = 1; 3502 } 3503 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 3504 if( i==(nArg-1) ){ 3505 raw_printf(stderr, "option requires an argument: %s\n", z); 3506 rc = SQLITE_ERROR; 3507 }else{ 3508 iSample = (int)integerValue(azArg[++i]); 3509 if( iSample<0 || iSample>100 ){ 3510 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 3511 rc = SQLITE_ERROR; 3512 } 3513 } 3514 } 3515 else{ 3516 raw_printf(stderr, "unknown option: %s\n", z); 3517 rc = SQLITE_ERROR; 3518 } 3519 } 3520 3521 if( rc==SQLITE_OK ){ 3522 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 3523 if( pState->expert.pExpert==0 ){ 3524 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory"); 3525 rc = SQLITE_ERROR; 3526 }else{ 3527 sqlite3_expert_config( 3528 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 3529 ); 3530 } 3531 } 3532 sqlite3_free(zErr); 3533 3534 return rc; 3535} 3536#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3537 3538/* 3539** Execute a statement or set of statements. Print 3540** any result rows/columns depending on the current mode 3541** set via the supplied callback. 3542** 3543** This is very similar to SQLite's built-in sqlite3_exec() 3544** function except it takes a slightly different callback 3545** and callback data argument. 3546*/ 3547static int shell_exec( 3548 ShellState *pArg, /* Pointer to ShellState */ 3549 const char *zSql, /* SQL to be evaluated */ 3550 char **pzErrMsg /* Error msg written here */ 3551){ 3552 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3553 int rc = SQLITE_OK; /* Return Code */ 3554 int rc2; 3555 const char *zLeftover; /* Tail of unprocessed SQL */ 3556 sqlite3 *db = pArg->db; 3557 3558 if( pzErrMsg ){ 3559 *pzErrMsg = NULL; 3560 } 3561 3562#ifndef SQLITE_OMIT_VIRTUALTABLE 3563 if( pArg->expert.pExpert ){ 3564 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3565 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3566 } 3567#endif 3568 3569 while( zSql[0] && (SQLITE_OK == rc) ){ 3570 static const char *zStmtSql; 3571 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3572 if( SQLITE_OK != rc ){ 3573 if( pzErrMsg ){ 3574 *pzErrMsg = save_err_msg(db, "in prepare, %s (%d)%s", rc, zSql); 3575 } 3576 }else{ 3577 if( !pStmt ){ 3578 /* this happens for a comment or white-space */ 3579 zSql = zLeftover; 3580 while( IsSpace(zSql[0]) ) zSql++; 3581 continue; 3582 } 3583 zStmtSql = sqlite3_sql(pStmt); 3584 if( zStmtSql==0 ) zStmtSql = ""; 3585 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3586 3587 /* save off the prepared statment handle and reset row count */ 3588 if( pArg ){ 3589 pArg->pStmt = pStmt; 3590 pArg->cnt = 0; 3591 } 3592 3593 /* echo the sql statement if echo on */ 3594 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3595 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3596 } 3597 3598 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3599 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3600 sqlite3_stmt *pExplain; 3601 char *zEQP; 3602 int triggerEQP = 0; 3603 disable_debug_trace_modes(); 3604 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3605 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3606 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3607 } 3608 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3609 shell_check_oom(zEQP); 3610 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3611 if( rc==SQLITE_OK ){ 3612 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3613 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3614 int iEqpId = sqlite3_column_int(pExplain, 0); 3615 int iParentId = sqlite3_column_int(pExplain, 1); 3616 if( zEQPLine==0 ) zEQPLine = ""; 3617 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3618 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3619 } 3620 eqp_render(pArg); 3621 } 3622 sqlite3_finalize(pExplain); 3623 sqlite3_free(zEQP); 3624 if( pArg->autoEQP>=AUTOEQP_full ){ 3625 /* Also do an EXPLAIN for ".eqp full" mode */ 3626 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3627 shell_check_oom(zEQP); 3628 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3629 if( rc==SQLITE_OK ){ 3630 pArg->cMode = MODE_Explain; 3631 explain_data_prepare(pArg, pExplain); 3632 exec_prepared_stmt(pArg, pExplain); 3633 explain_data_delete(pArg); 3634 } 3635 sqlite3_finalize(pExplain); 3636 sqlite3_free(zEQP); 3637 } 3638 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3639 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3640 /* Reprepare pStmt before reactiving trace modes */ 3641 sqlite3_finalize(pStmt); 3642 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3643 if( pArg ) pArg->pStmt = pStmt; 3644 } 3645 restore_debug_trace_modes(); 3646 } 3647 3648 if( pArg ){ 3649 pArg->cMode = pArg->mode; 3650 if( pArg->autoExplain ){ 3651 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3652 pArg->cMode = MODE_Explain; 3653 } 3654 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3655 pArg->cMode = MODE_EQP; 3656 } 3657 } 3658 3659 /* If the shell is currently in ".explain" mode, gather the extra 3660 ** data required to add indents to the output.*/ 3661 if( pArg->cMode==MODE_Explain ){ 3662 explain_data_prepare(pArg, pStmt); 3663 } 3664 } 3665 3666 bind_prepared_stmt(pArg, pStmt); 3667 exec_prepared_stmt(pArg, pStmt); 3668 explain_data_delete(pArg); 3669 eqp_render(pArg); 3670 3671 /* print usage stats if stats on */ 3672 if( pArg && pArg->statsOn ){ 3673 display_stats(db, pArg, 0); 3674 } 3675 3676 /* print loop-counters if required */ 3677 if( pArg && pArg->scanstatsOn ){ 3678 display_scanstats(db, pArg); 3679 } 3680 3681 /* Finalize the statement just executed. If this fails, save a 3682 ** copy of the error message. Otherwise, set zSql to point to the 3683 ** next statement to execute. */ 3684 rc2 = sqlite3_finalize(pStmt); 3685 if( rc!=SQLITE_NOMEM ) rc = rc2; 3686 if( rc==SQLITE_OK ){ 3687 zSql = zLeftover; 3688 while( IsSpace(zSql[0]) ) zSql++; 3689 }else if( pzErrMsg ){ 3690 *pzErrMsg = save_err_msg(db, "stepping, %s (%d)", rc, 0); 3691 } 3692 3693 /* clear saved stmt handle */ 3694 if( pArg ){ 3695 pArg->pStmt = NULL; 3696 } 3697 } 3698 } /* end while */ 3699 3700 return rc; 3701} 3702 3703/* 3704** Release memory previously allocated by tableColumnList(). 3705*/ 3706static void freeColumnList(char **azCol){ 3707 int i; 3708 for(i=1; azCol[i]; i++){ 3709 sqlite3_free(azCol[i]); 3710 } 3711 /* azCol[0] is a static string */ 3712 sqlite3_free(azCol); 3713} 3714 3715/* 3716** Return a list of pointers to strings which are the names of all 3717** columns in table zTab. The memory to hold the names is dynamically 3718** allocated and must be released by the caller using a subsequent call 3719** to freeColumnList(). 3720** 3721** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3722** value that needs to be preserved, then azCol[0] is filled in with the 3723** name of the rowid column. 3724** 3725** The first regular column in the table is azCol[1]. The list is terminated 3726** by an entry with azCol[i]==0. 3727*/ 3728static char **tableColumnList(ShellState *p, const char *zTab){ 3729 char **azCol = 0; 3730 sqlite3_stmt *pStmt; 3731 char *zSql; 3732 int nCol = 0; 3733 int nAlloc = 0; 3734 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3735 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3736 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3737 int rc; 3738 3739 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3740 shell_check_oom(zSql); 3741 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3742 sqlite3_free(zSql); 3743 if( rc ) return 0; 3744 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3745 if( nCol>=nAlloc-2 ){ 3746 nAlloc = nAlloc*2 + nCol + 10; 3747 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3748 shell_check_oom(azCol); 3749 } 3750 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3751 shell_check_oom(azCol[nCol]); 3752 if( sqlite3_column_int(pStmt, 5) ){ 3753 nPK++; 3754 if( nPK==1 3755 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3756 "INTEGER")==0 3757 ){ 3758 isIPK = 1; 3759 }else{ 3760 isIPK = 0; 3761 } 3762 } 3763 } 3764 sqlite3_finalize(pStmt); 3765 if( azCol==0 ) return 0; 3766 azCol[0] = 0; 3767 azCol[nCol+1] = 0; 3768 3769 /* The decision of whether or not a rowid really needs to be preserved 3770 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3771 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3772 ** rowids on tables where the rowid is inaccessible because there are other 3773 ** columns in the table named "rowid", "_rowid_", and "oid". 3774 */ 3775 if( preserveRowid && isIPK ){ 3776 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3777 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3778 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3779 ** ROWID aliases. To distinguish these cases, check to see if 3780 ** there is a "pk" entry in "PRAGMA index_list". There will be 3781 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3782 */ 3783 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3784 " WHERE origin='pk'", zTab); 3785 shell_check_oom(zSql); 3786 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3787 sqlite3_free(zSql); 3788 if( rc ){ 3789 freeColumnList(azCol); 3790 return 0; 3791 } 3792 rc = sqlite3_step(pStmt); 3793 sqlite3_finalize(pStmt); 3794 preserveRowid = rc==SQLITE_ROW; 3795 } 3796 if( preserveRowid ){ 3797 /* Only preserve the rowid if we can find a name to use for the 3798 ** rowid */ 3799 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3800 int i, j; 3801 for(j=0; j<3; j++){ 3802 for(i=1; i<=nCol; i++){ 3803 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3804 } 3805 if( i>nCol ){ 3806 /* At this point, we know that azRowid[j] is not the name of any 3807 ** ordinary column in the table. Verify that azRowid[j] is a valid 3808 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3809 ** tables will fail this last check */ 3810 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3811 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3812 break; 3813 } 3814 } 3815 } 3816 return azCol; 3817} 3818 3819/* 3820** Toggle the reverse_unordered_selects setting. 3821*/ 3822static void toggleSelectOrder(sqlite3 *db){ 3823 sqlite3_stmt *pStmt = 0; 3824 int iSetting = 0; 3825 char zStmt[100]; 3826 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3827 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3828 iSetting = sqlite3_column_int(pStmt, 0); 3829 } 3830 sqlite3_finalize(pStmt); 3831 sqlite3_snprintf(sizeof(zStmt), zStmt, 3832 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3833 sqlite3_exec(db, zStmt, 0, 0, 0); 3834} 3835 3836/* 3837** This is a different callback routine used for dumping the database. 3838** Each row received by this callback consists of a table name, 3839** the table type ("index" or "table") and SQL to create the table. 3840** This routine should print text sufficient to recreate the table. 3841*/ 3842static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3843 int rc; 3844 const char *zTable; 3845 const char *zType; 3846 const char *zSql; 3847 ShellState *p = (ShellState *)pArg; 3848 int dataOnly; 3849 int noSys; 3850 3851 UNUSED_PARAMETER(azNotUsed); 3852 if( nArg!=3 || azArg==0 ) return 0; 3853 zTable = azArg[0]; 3854 zType = azArg[1]; 3855 zSql = azArg[2]; 3856 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; 3857 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; 3858 3859 if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){ 3860 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3861 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){ 3862 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 3863 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3864 return 0; 3865 }else if( dataOnly ){ 3866 /* no-op */ 3867 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3868 char *zIns; 3869 if( !p->writableSchema ){ 3870 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3871 p->writableSchema = 1; 3872 } 3873 zIns = sqlite3_mprintf( 3874 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" 3875 "VALUES('table','%q','%q',0,'%q');", 3876 zTable, zTable, zSql); 3877 shell_check_oom(zIns); 3878 utf8_printf(p->out, "%s\n", zIns); 3879 sqlite3_free(zIns); 3880 return 0; 3881 }else{ 3882 printSchemaLine(p->out, zSql, ";\n"); 3883 } 3884 3885 if( strcmp(zType, "table")==0 ){ 3886 ShellText sSelect; 3887 ShellText sTable; 3888 char **azCol; 3889 int i; 3890 char *savedDestTable; 3891 int savedMode; 3892 3893 azCol = tableColumnList(p, zTable); 3894 if( azCol==0 ){ 3895 p->nErr++; 3896 return 0; 3897 } 3898 3899 /* Always quote the table name, even if it appears to be pure ascii, 3900 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3901 initText(&sTable); 3902 appendText(&sTable, zTable, quoteChar(zTable)); 3903 /* If preserving the rowid, add a column list after the table name. 3904 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3905 ** instead of the usual "INSERT INTO tab VALUES(...)". 3906 */ 3907 if( azCol[0] ){ 3908 appendText(&sTable, "(", 0); 3909 appendText(&sTable, azCol[0], 0); 3910 for(i=1; azCol[i]; i++){ 3911 appendText(&sTable, ",", 0); 3912 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3913 } 3914 appendText(&sTable, ")", 0); 3915 } 3916 3917 /* Build an appropriate SELECT statement */ 3918 initText(&sSelect); 3919 appendText(&sSelect, "SELECT ", 0); 3920 if( azCol[0] ){ 3921 appendText(&sSelect, azCol[0], 0); 3922 appendText(&sSelect, ",", 0); 3923 } 3924 for(i=1; azCol[i]; i++){ 3925 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3926 if( azCol[i+1] ){ 3927 appendText(&sSelect, ",", 0); 3928 } 3929 } 3930 freeColumnList(azCol); 3931 appendText(&sSelect, " FROM ", 0); 3932 appendText(&sSelect, zTable, quoteChar(zTable)); 3933 3934 savedDestTable = p->zDestTable; 3935 savedMode = p->mode; 3936 p->zDestTable = sTable.z; 3937 p->mode = p->cMode = MODE_Insert; 3938 rc = shell_exec(p, sSelect.z, 0); 3939 if( (rc&0xff)==SQLITE_CORRUPT ){ 3940 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3941 toggleSelectOrder(p->db); 3942 shell_exec(p, sSelect.z, 0); 3943 toggleSelectOrder(p->db); 3944 } 3945 p->zDestTable = savedDestTable; 3946 p->mode = savedMode; 3947 freeText(&sTable); 3948 freeText(&sSelect); 3949 if( rc ) p->nErr++; 3950 } 3951 return 0; 3952} 3953 3954/* 3955** Run zQuery. Use dump_callback() as the callback routine so that 3956** the contents of the query are output as SQL statements. 3957** 3958** If we get a SQLITE_CORRUPT error, rerun the query after appending 3959** "ORDER BY rowid DESC" to the end. 3960*/ 3961static int run_schema_dump_query( 3962 ShellState *p, 3963 const char *zQuery 3964){ 3965 int rc; 3966 char *zErr = 0; 3967 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3968 if( rc==SQLITE_CORRUPT ){ 3969 char *zQ2; 3970 int len = strlen30(zQuery); 3971 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3972 if( zErr ){ 3973 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3974 sqlite3_free(zErr); 3975 zErr = 0; 3976 } 3977 zQ2 = malloc( len+100 ); 3978 if( zQ2==0 ) return rc; 3979 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3980 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3981 if( rc ){ 3982 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3983 }else{ 3984 rc = SQLITE_CORRUPT; 3985 } 3986 sqlite3_free(zErr); 3987 free(zQ2); 3988 } 3989 return rc; 3990} 3991 3992/* 3993** Text of help messages. 3994** 3995** The help text for each individual command begins with a line that starts 3996** with ".". Subsequent lines are supplimental information. 3997** 3998** There must be two or more spaces between the end of the command and the 3999** start of the description of what that command does. 4000*/ 4001static const char *(azHelp[]) = { 4002#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 4003 ".archive ... Manage SQL archives", 4004 " Each command must have exactly one of the following options:", 4005 " -c, --create Create a new archive", 4006 " -u, --update Add or update files with changed mtime", 4007 " -i, --insert Like -u but always add even if unchanged", 4008 " -r, --remove Remove files from archive", 4009 " -t, --list List contents of archive", 4010 " -x, --extract Extract files from archive", 4011 " Optional arguments:", 4012 " -v, --verbose Print each filename as it is processed", 4013 " -f FILE, --file FILE Use archive FILE (default is current db)", 4014 " -a FILE, --append FILE Open FILE using the apndvfs VFS", 4015 " -C DIR, --directory DIR Read/extract files from directory DIR", 4016 " -g, --glob Use glob matching for names in archive", 4017 " -n, --dryrun Show the SQL that would have occurred", 4018 " Examples:", 4019 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", 4020 " .ar -tf ARCHIVE # List members of ARCHIVE", 4021 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", 4022 " See also:", 4023 " http://sqlite.org/cli.html#sqlite_archive_support", 4024#endif 4025#ifndef SQLITE_OMIT_AUTHORIZATION 4026 ".auth ON|OFF Show authorizer callbacks", 4027#endif 4028 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 4029 " --append Use the appendvfs", 4030 " --async Write to FILE without journal and fsync()", 4031 ".bail on|off Stop after hitting an error. Default OFF", 4032 ".binary on|off Turn binary output on or off. Default OFF", 4033 ".cd DIRECTORY Change the working directory to DIRECTORY", 4034 ".changes on|off Show number of rows changed by SQL", 4035 ".check GLOB Fail if output since .testcase does not match", 4036 ".clone NEWDB Clone data into NEWDB from the existing database", 4037 ".connection [close] [#] Open or close an auxiliary database connection", 4038 ".databases List names and files of attached databases", 4039 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 4040 ".dbinfo ?DB? Show status information about the database", 4041 ".dump ?OBJECTS? Render database content as SQL", 4042 " Options:", 4043 " --data-only Output only INSERT statements", 4044 " --newlines Allow unescaped newline characters in output", 4045 " --nosys Omit system tables (ex: \"sqlite_stat1\")", 4046 " --preserve-rowids Include ROWID values in the output", 4047 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump", 4048 " Additional LIKE patterns can be given in subsequent arguments", 4049 ".echo on|off Turn command echo on or off", 4050 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 4051 " Other Modes:", 4052#ifdef SQLITE_DEBUG 4053 " test Show raw EXPLAIN QUERY PLAN output", 4054 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", 4055#endif 4056 " trigger Like \"full\" but also show trigger bytecode", 4057 ".excel Display the output of next command in spreadsheet", 4058 " --bom Put a UTF8 byte-order mark on intermediate file", 4059 ".exit ?CODE? Exit this program with return-code CODE", 4060 ".expert EXPERIMENTAL. Suggest indexes for queries", 4061 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", 4062 ".filectrl CMD ... Run various sqlite3_file_control() operations", 4063 " --schema SCHEMA Use SCHEMA instead of \"main\"", 4064 " --help Show CMD details", 4065 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 4066 ".headers on|off Turn display of headers on or off", 4067 ".help ?-all? ?PATTERN? Show help text for PATTERN", 4068 ".import FILE TABLE Import data from FILE into TABLE", 4069 " Options:", 4070 " --ascii Use \\037 and \\036 as column and row separators", 4071 " --csv Use , and \\n as column and row separators", 4072 " --skip N Skip the first N rows of input", 4073 " --schema S Target table to be S.TABLE", 4074 " -v \"Verbose\" - increase auxiliary output", 4075 " Notes:", 4076 " * If TABLE does not exist, it is created. The first row of input", 4077 " determines the column names.", 4078 " * If neither --csv or --ascii are used, the input mode is derived", 4079 " from the \".mode\" output mode", 4080 " * If FILE begins with \"|\" then it is a command that generates the", 4081 " input text.", 4082#ifndef SQLITE_OMIT_TEST_CONTROL 4083 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 4084#endif 4085 ".indexes ?TABLE? Show names of indexes", 4086 " If TABLE is specified, only show indexes for", 4087 " tables matching TABLE using the LIKE operator.", 4088#ifdef SQLITE_ENABLE_IOTRACE 4089 ".iotrace FILE Enable I/O diagnostic logging to FILE", 4090#endif 4091 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 4092 ".lint OPTIONS Report potential schema issues.", 4093 " Options:", 4094 " fkey-indexes Find missing foreign key indexes", 4095#ifndef SQLITE_OMIT_LOAD_EXTENSION 4096 ".load FILE ?ENTRY? Load an extension library", 4097#endif 4098 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 4099 ".mode MODE ?TABLE? Set output mode", 4100 " MODE is one of:", 4101 " ascii Columns/rows delimited by 0x1F and 0x1E", 4102 " box Tables using unicode box-drawing characters", 4103 " csv Comma-separated values", 4104 " column Output in columns. (See .width)", 4105 " html HTML <table> code", 4106 " insert SQL insert statements for TABLE", 4107 " json Results in a JSON array", 4108 " line One value per line", 4109 " list Values delimited by \"|\"", 4110 " markdown Markdown table format", 4111 " quote Escape answers as for SQL", 4112 " table ASCII-art table", 4113 " tabs Tab-separated values", 4114 " tcl TCL list elements", 4115 ".nonce STRING Disable safe mode for one command if the nonce matches", 4116 ".nullvalue STRING Use STRING in place of NULL values", 4117 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE", 4118 " If FILE begins with '|' then open as a pipe", 4119 " --bom Put a UTF8 byte-order mark at the beginning", 4120 " -e Send output to the system text editor", 4121 " -x Send output as CSV to a spreadsheet (same as \".excel\")", 4122 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 4123 " Options:", 4124 " --append Use appendvfs to append database to the end of FILE", 4125#ifndef SQLITE_OMIT_DESERIALIZE 4126 " --deserialize Load into memory using sqlite3_deserialize()", 4127 " --hexdb Load the output of \"dbtotxt\" as an in-memory db", 4128 " --maxsize N Maximum size for --hexdb or --deserialized database", 4129#endif 4130 " --new Initialize FILE to an empty database", 4131 " --nofollow Do not follow symbolic links", 4132 " --readonly Open FILE readonly", 4133 " --zip FILE is a ZIP archive", 4134 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 4135 " If FILE begins with '|' then open it as a pipe.", 4136 " Options:", 4137 " --bom Prefix output with a UTF8 byte-order mark", 4138 " -e Send output to the system text editor", 4139 " -x Send output as CSV to a spreadsheet", 4140 ".parameter CMD ... Manage SQL parameter bindings", 4141 " clear Erase all bindings", 4142 " init Initialize the TEMP table that holds bindings", 4143 " list List the current parameter bindings", 4144 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 4145 " PARAMETER should start with one of: $ : @ ?", 4146 " unset PARAMETER Remove PARAMETER from the binding table", 4147 ".print STRING... Print literal STRING", 4148#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 4149 ".progress N Invoke progress handler after every N opcodes", 4150 " --limit N Interrupt after N progress callbacks", 4151 " --once Do no more than one progress interrupt", 4152 " --quiet|-q No output except at interrupts", 4153 " --reset Reset the count for each input and interrupt", 4154#endif 4155 ".prompt MAIN CONTINUE Replace the standard prompts", 4156 ".quit Exit this program", 4157 ".read FILE Read input from FILE or command output", 4158 " If FILE begins with \"|\", it is a command that generates the input.", 4159#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4160 ".recover Recover as much data as possible from corrupt db.", 4161 " --freelist-corrupt Assume the freelist is corrupt", 4162 " --recovery-db NAME Store recovery metadata in database file NAME", 4163 " --lost-and-found TABLE Alternative name for the lost-and-found table", 4164 " --no-rowids Do not attempt to recover rowid values", 4165 " that are not also INTEGER PRIMARY KEYs", 4166#endif 4167 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 4168 ".save FILE Write in-memory database into FILE", 4169 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 4170 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 4171 " Options:", 4172 " --indent Try to pretty-print the schema", 4173 " --nosys Omit objects whose names start with \"sqlite_\"", 4174 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 4175 " Options:", 4176 " --init Create a new SELFTEST table", 4177 " -v Verbose output", 4178 ".separator COL ?ROW? Change the column and row separators", 4179#if defined(SQLITE_ENABLE_SESSION) 4180 ".session ?NAME? CMD ... Create or control sessions", 4181 " Subcommands:", 4182 " attach TABLE Attach TABLE", 4183 " changeset FILE Write a changeset into FILE", 4184 " close Close one session", 4185 " enable ?BOOLEAN? Set or query the enable bit", 4186 " filter GLOB... Reject tables matching GLOBs", 4187 " indirect ?BOOLEAN? Mark or query the indirect status", 4188 " isempty Query whether the session is empty", 4189 " list List currently open session names", 4190 " open DB NAME Open a new session on DB", 4191 " patchset FILE Write a patchset into FILE", 4192 " If ?NAME? is omitted, the first defined session is used.", 4193#endif 4194 ".sha3sum ... Compute a SHA3 hash of database content", 4195 " Options:", 4196 " --schema Also hash the sqlite_schema table", 4197 " --sha3-224 Use the sha3-224 algorithm", 4198 " --sha3-256 Use the sha3-256 algorithm (default)", 4199 " --sha3-384 Use the sha3-384 algorithm", 4200 " --sha3-512 Use the sha3-512 algorithm", 4201 " Any other argument is a LIKE pattern for tables to hash", 4202#ifndef SQLITE_NOHAVE_SYSTEM 4203 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 4204#endif 4205 ".show Show the current values for various settings", 4206 ".stats ?ARG? Show stats or turn stats on or off", 4207 " off Turn off automatic stat display", 4208 " on Turn on automatic stat display", 4209 " stmt Show statement stats", 4210 " vmstep Show the virtual machine step count only", 4211#ifndef SQLITE_NOHAVE_SYSTEM 4212 ".system CMD ARGS... Run CMD ARGS... in a system shell", 4213#endif 4214 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 4215 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 4216 ".testctrl CMD ... Run various sqlite3_test_control() operations", 4217 " Run \".testctrl\" with no arguments for details", 4218 ".timeout MS Try opening locked tables for MS milliseconds", 4219 ".timer on|off Turn SQL timer on or off", 4220#ifndef SQLITE_OMIT_TRACE 4221 ".trace ?OPTIONS? Output each SQL statement as it is run", 4222 " FILE Send output to FILE", 4223 " stdout Send output to stdout", 4224 " stderr Send output to stderr", 4225 " off Disable tracing", 4226 " --expanded Expand query parameters", 4227#ifdef SQLITE_ENABLE_NORMALIZE 4228 " --normalized Normal the SQL statements", 4229#endif 4230 " --plain Show SQL as it is input", 4231 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 4232 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 4233 " --row Trace each row (SQLITE_TRACE_ROW)", 4234 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 4235#endif /* SQLITE_OMIT_TRACE */ 4236#ifdef SQLITE_DEBUG 4237 ".unmodule NAME ... Unregister virtual table modules", 4238 " --allexcept Unregister everything except those named", 4239#endif 4240 ".vfsinfo ?AUX? Information about the top-level VFS", 4241 ".vfslist List all available VFSes", 4242 ".vfsname ?AUX? Print the name of the VFS stack", 4243 ".width NUM1 NUM2 ... Set minimum column widths for columnar output", 4244 " Negative values right-justify", 4245}; 4246 4247/* 4248** Output help text. 4249** 4250** zPattern describes the set of commands for which help text is provided. 4251** If zPattern is NULL, then show all commands, but only give a one-line 4252** description of each. 4253** 4254** Return the number of matches. 4255*/ 4256static int showHelp(FILE *out, const char *zPattern){ 4257 int i = 0; 4258 int j = 0; 4259 int n = 0; 4260 char *zPat; 4261 if( zPattern==0 4262 || zPattern[0]=='0' 4263 || strcmp(zPattern,"-a")==0 4264 || strcmp(zPattern,"-all")==0 4265 || strcmp(zPattern,"--all")==0 4266 ){ 4267 /* Show all commands, but only one line per command */ 4268 if( zPattern==0 ) zPattern = ""; 4269 for(i=0; i<ArraySize(azHelp); i++){ 4270 if( azHelp[i][0]=='.' || zPattern[0] ){ 4271 utf8_printf(out, "%s\n", azHelp[i]); 4272 n++; 4273 } 4274 } 4275 }else{ 4276 /* Look for commands that for which zPattern is an exact prefix */ 4277 zPat = sqlite3_mprintf(".%s*", zPattern); 4278 shell_check_oom(zPat); 4279 for(i=0; i<ArraySize(azHelp); i++){ 4280 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 4281 utf8_printf(out, "%s\n", azHelp[i]); 4282 j = i+1; 4283 n++; 4284 } 4285 } 4286 sqlite3_free(zPat); 4287 if( n ){ 4288 if( n==1 ){ 4289 /* when zPattern is a prefix of exactly one command, then include the 4290 ** details of that command, which should begin at offset j */ 4291 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 4292 utf8_printf(out, "%s\n", azHelp[j]); 4293 j++; 4294 } 4295 } 4296 return n; 4297 } 4298 /* Look for commands that contain zPattern anywhere. Show the complete 4299 ** text of all commands that match. */ 4300 zPat = sqlite3_mprintf("%%%s%%", zPattern); 4301 shell_check_oom(zPat); 4302 for(i=0; i<ArraySize(azHelp); i++){ 4303 if( azHelp[i][0]=='.' ) j = i; 4304 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 4305 utf8_printf(out, "%s\n", azHelp[j]); 4306 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 4307 j++; 4308 utf8_printf(out, "%s\n", azHelp[j]); 4309 } 4310 i = j; 4311 n++; 4312 } 4313 } 4314 sqlite3_free(zPat); 4315 } 4316 return n; 4317} 4318 4319/* Forward reference */ 4320static int process_input(ShellState *p); 4321 4322/* 4323** Read the content of file zName into memory obtained from sqlite3_malloc64() 4324** and return a pointer to the buffer. The caller is responsible for freeing 4325** the memory. 4326** 4327** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 4328** read. 4329** 4330** For convenience, a nul-terminator byte is always appended to the data read 4331** from the file before the buffer is returned. This byte is not included in 4332** the final value of (*pnByte), if applicable. 4333** 4334** NULL is returned if any error is encountered. The final value of *pnByte 4335** is undefined in this case. 4336*/ 4337static char *readFile(const char *zName, int *pnByte){ 4338 FILE *in = fopen(zName, "rb"); 4339 long nIn; 4340 size_t nRead; 4341 char *pBuf; 4342 if( in==0 ) return 0; 4343 fseek(in, 0, SEEK_END); 4344 nIn = ftell(in); 4345 rewind(in); 4346 pBuf = sqlite3_malloc64( nIn+1 ); 4347 if( pBuf==0 ){ fclose(in); return 0; } 4348 nRead = fread(pBuf, nIn, 1, in); 4349 fclose(in); 4350 if( nRead!=1 ){ 4351 sqlite3_free(pBuf); 4352 return 0; 4353 } 4354 pBuf[nIn] = 0; 4355 if( pnByte ) *pnByte = nIn; 4356 return pBuf; 4357} 4358 4359#if defined(SQLITE_ENABLE_SESSION) 4360/* 4361** Close a single OpenSession object and release all of its associated 4362** resources. 4363*/ 4364static void session_close(OpenSession *pSession){ 4365 int i; 4366 sqlite3session_delete(pSession->p); 4367 sqlite3_free(pSession->zName); 4368 for(i=0; i<pSession->nFilter; i++){ 4369 sqlite3_free(pSession->azFilter[i]); 4370 } 4371 sqlite3_free(pSession->azFilter); 4372 memset(pSession, 0, sizeof(OpenSession)); 4373} 4374#endif 4375 4376/* 4377** Close all OpenSession objects and release all associated resources. 4378*/ 4379#if defined(SQLITE_ENABLE_SESSION) 4380static void session_close_all(ShellState *p, int i){ 4381 int j; 4382 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; 4383 for(j=0; j<pAuxDb->nSession; j++){ 4384 session_close(&pAuxDb->aSession[j]); 4385 } 4386 pAuxDb->nSession = 0; 4387} 4388#else 4389# define session_close_all(X,Y) 4390#endif 4391 4392/* 4393** Implementation of the xFilter function for an open session. Omit 4394** any tables named by ".session filter" but let all other table through. 4395*/ 4396#if defined(SQLITE_ENABLE_SESSION) 4397static int session_filter(void *pCtx, const char *zTab){ 4398 OpenSession *pSession = (OpenSession*)pCtx; 4399 int i; 4400 for(i=0; i<pSession->nFilter; i++){ 4401 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 4402 } 4403 return 1; 4404} 4405#endif 4406 4407/* 4408** Try to deduce the type of file for zName based on its content. Return 4409** one of the SHELL_OPEN_* constants. 4410** 4411** If the file does not exist or is empty but its name looks like a ZIP 4412** archive and the dfltZip flag is true, then assume it is a ZIP archive. 4413** Otherwise, assume an ordinary database regardless of the filename if 4414** the type cannot be determined from content. 4415*/ 4416int deduceDatabaseType(const char *zName, int dfltZip){ 4417 FILE *f = fopen(zName, "rb"); 4418 size_t n; 4419 int rc = SHELL_OPEN_UNSPEC; 4420 char zBuf[100]; 4421 if( f==0 ){ 4422 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4423 return SHELL_OPEN_ZIPFILE; 4424 }else{ 4425 return SHELL_OPEN_NORMAL; 4426 } 4427 } 4428 n = fread(zBuf, 16, 1, f); 4429 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 4430 fclose(f); 4431 return SHELL_OPEN_NORMAL; 4432 } 4433 fseek(f, -25, SEEK_END); 4434 n = fread(zBuf, 25, 1, f); 4435 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 4436 rc = SHELL_OPEN_APPENDVFS; 4437 }else{ 4438 fseek(f, -22, SEEK_END); 4439 n = fread(zBuf, 22, 1, f); 4440 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 4441 && zBuf[3]==0x06 ){ 4442 rc = SHELL_OPEN_ZIPFILE; 4443 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4444 rc = SHELL_OPEN_ZIPFILE; 4445 } 4446 } 4447 fclose(f); 4448 return rc; 4449} 4450 4451#ifndef SQLITE_OMIT_DESERIALIZE 4452/* 4453** Reconstruct an in-memory database using the output from the "dbtotxt" 4454** program. Read content from the file in p->aAuxDb[].zDbFilename. 4455** If p->aAuxDb[].zDbFilename is 0, then read from standard input. 4456*/ 4457static unsigned char *readHexDb(ShellState *p, int *pnData){ 4458 unsigned char *a = 0; 4459 int nLine; 4460 int n = 0; 4461 int pgsz = 0; 4462 int iOffset = 0; 4463 int j, k; 4464 int rc; 4465 FILE *in; 4466 const char *zDbFilename = p->pAuxDb->zDbFilename; 4467 unsigned int x[16]; 4468 char zLine[1000]; 4469 if( zDbFilename ){ 4470 in = fopen(zDbFilename, "r"); 4471 if( in==0 ){ 4472 utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename); 4473 return 0; 4474 } 4475 nLine = 0; 4476 }else{ 4477 in = p->in; 4478 nLine = p->lineno; 4479 if( in==0 ) in = stdin; 4480 } 4481 *pnData = 0; 4482 nLine++; 4483 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 4484 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 4485 if( rc!=2 ) goto readHexDb_error; 4486 if( n<0 ) goto readHexDb_error; 4487 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 4488 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 4489 a = sqlite3_malloc( n ? n : 1 ); 4490 shell_check_oom(a); 4491 memset(a, 0, n); 4492 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 4493 utf8_printf(stderr, "invalid pagesize\n"); 4494 goto readHexDb_error; 4495 } 4496 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 4497 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 4498 if( rc==2 ){ 4499 iOffset = k; 4500 continue; 4501 } 4502 if( strncmp(zLine, "| end ", 6)==0 ){ 4503 break; 4504 } 4505 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 4506 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 4507 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 4508 if( rc==17 ){ 4509 k = iOffset+j; 4510 if( k+16<=n && k>=0 ){ 4511 int ii; 4512 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 4513 } 4514 } 4515 } 4516 *pnData = n; 4517 if( in!=p->in ){ 4518 fclose(in); 4519 }else{ 4520 p->lineno = nLine; 4521 } 4522 return a; 4523 4524readHexDb_error: 4525 if( in!=p->in ){ 4526 fclose(in); 4527 }else{ 4528 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 4529 nLine++; 4530 if(strncmp(zLine, "| end ", 6)==0 ) break; 4531 } 4532 p->lineno = nLine; 4533 } 4534 sqlite3_free(a); 4535 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 4536 return 0; 4537} 4538#endif /* SQLITE_OMIT_DESERIALIZE */ 4539 4540/* 4541** Scalar function "shell_int32". The first argument to this function 4542** must be a blob. The second a non-negative integer. This function 4543** reads and returns a 32-bit big-endian integer from byte 4544** offset (4*<arg2>) of the blob. 4545*/ 4546static void shellInt32( 4547 sqlite3_context *context, 4548 int argc, 4549 sqlite3_value **argv 4550){ 4551 const unsigned char *pBlob; 4552 int nBlob; 4553 int iInt; 4554 4555 UNUSED_PARAMETER(argc); 4556 nBlob = sqlite3_value_bytes(argv[0]); 4557 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 4558 iInt = sqlite3_value_int(argv[1]); 4559 4560 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 4561 const unsigned char *a = &pBlob[iInt*4]; 4562 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 4563 + ((sqlite3_int64)a[1]<<16) 4564 + ((sqlite3_int64)a[2]<< 8) 4565 + ((sqlite3_int64)a[3]<< 0); 4566 sqlite3_result_int64(context, iVal); 4567 } 4568} 4569 4570/* 4571** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 4572** using "..." with internal double-quote characters doubled. 4573*/ 4574static void shellIdQuote( 4575 sqlite3_context *context, 4576 int argc, 4577 sqlite3_value **argv 4578){ 4579 const char *zName = (const char*)sqlite3_value_text(argv[0]); 4580 UNUSED_PARAMETER(argc); 4581 if( zName ){ 4582 char *z = sqlite3_mprintf("\"%w\"", zName); 4583 sqlite3_result_text(context, z, -1, sqlite3_free); 4584 } 4585} 4586 4587/* 4588** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X. 4589*/ 4590static void shellUSleepFunc( 4591 sqlite3_context *context, 4592 int argcUnused, 4593 sqlite3_value **argv 4594){ 4595 int sleep = sqlite3_value_int(argv[0]); 4596 (void)argcUnused; 4597 sqlite3_sleep(sleep/1000); 4598 sqlite3_result_int(context, sleep); 4599} 4600 4601/* 4602** Scalar function "shell_escape_crnl" used by the .recover command. 4603** The argument passed to this function is the output of built-in 4604** function quote(). If the first character of the input is "'", 4605** indicating that the value passed to quote() was a text value, 4606** then this function searches the input for "\n" and "\r" characters 4607** and adds a wrapper similar to the following: 4608** 4609** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4610** 4611** Or, if the first character of the input is not "'", then a copy 4612** of the input is returned. 4613*/ 4614static void shellEscapeCrnl( 4615 sqlite3_context *context, 4616 int argc, 4617 sqlite3_value **argv 4618){ 4619 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4620 UNUSED_PARAMETER(argc); 4621 if( zText && zText[0]=='\'' ){ 4622 int nText = sqlite3_value_bytes(argv[0]); 4623 int i; 4624 char zBuf1[20]; 4625 char zBuf2[20]; 4626 const char *zNL = 0; 4627 const char *zCR = 0; 4628 int nCR = 0; 4629 int nNL = 0; 4630 4631 for(i=0; zText[i]; i++){ 4632 if( zNL==0 && zText[i]=='\n' ){ 4633 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4634 nNL = (int)strlen(zNL); 4635 } 4636 if( zCR==0 && zText[i]=='\r' ){ 4637 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4638 nCR = (int)strlen(zCR); 4639 } 4640 } 4641 4642 if( zNL || zCR ){ 4643 int iOut = 0; 4644 i64 nMax = (nNL > nCR) ? nNL : nCR; 4645 i64 nAlloc = nMax * nText + (nMax+64)*2; 4646 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4647 if( zOut==0 ){ 4648 sqlite3_result_error_nomem(context); 4649 return; 4650 } 4651 4652 if( zNL && zCR ){ 4653 memcpy(&zOut[iOut], "replace(replace(", 16); 4654 iOut += 16; 4655 }else{ 4656 memcpy(&zOut[iOut], "replace(", 8); 4657 iOut += 8; 4658 } 4659 for(i=0; zText[i]; i++){ 4660 if( zText[i]=='\n' ){ 4661 memcpy(&zOut[iOut], zNL, nNL); 4662 iOut += nNL; 4663 }else if( zText[i]=='\r' ){ 4664 memcpy(&zOut[iOut], zCR, nCR); 4665 iOut += nCR; 4666 }else{ 4667 zOut[iOut] = zText[i]; 4668 iOut++; 4669 } 4670 } 4671 4672 if( zNL ){ 4673 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4674 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4675 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4676 } 4677 if( zCR ){ 4678 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4679 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4680 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4681 } 4682 4683 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4684 sqlite3_free(zOut); 4685 return; 4686 } 4687 } 4688 4689 sqlite3_result_value(context, argv[0]); 4690} 4691 4692/* Flags for open_db(). 4693** 4694** The default behavior of open_db() is to exit(1) if the database fails to 4695** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4696** but still returns without calling exit. 4697** 4698** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4699** ZIP archive if the file does not exist or is empty and its name matches 4700** the *.zip pattern. 4701*/ 4702#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4703#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4704 4705/* 4706** Make sure the database is open. If it is not, then open it. If 4707** the database fails to open, print an error message and exit. 4708*/ 4709static void open_db(ShellState *p, int openFlags){ 4710 if( p->db==0 ){ 4711 const char *zDbFilename = p->pAuxDb->zDbFilename; 4712 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4713 if( zDbFilename==0 || zDbFilename[0]==0 ){ 4714 p->openMode = SHELL_OPEN_NORMAL; 4715 }else{ 4716 p->openMode = (u8)deduceDatabaseType(zDbFilename, 4717 (openFlags & OPEN_DB_ZIPFILE)!=0); 4718 } 4719 } 4720 switch( p->openMode ){ 4721 case SHELL_OPEN_APPENDVFS: { 4722 sqlite3_open_v2(zDbFilename, &p->db, 4723 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); 4724 break; 4725 } 4726 case SHELL_OPEN_HEXDB: 4727 case SHELL_OPEN_DESERIALIZE: { 4728 sqlite3_open(0, &p->db); 4729 break; 4730 } 4731 case SHELL_OPEN_ZIPFILE: { 4732 sqlite3_open(":memory:", &p->db); 4733 break; 4734 } 4735 case SHELL_OPEN_READONLY: { 4736 sqlite3_open_v2(zDbFilename, &p->db, 4737 SQLITE_OPEN_READONLY|p->openFlags, 0); 4738 break; 4739 } 4740 case SHELL_OPEN_UNSPEC: 4741 case SHELL_OPEN_NORMAL: { 4742 sqlite3_open_v2(zDbFilename, &p->db, 4743 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); 4744 break; 4745 } 4746 } 4747 globalDb = p->db; 4748 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4749 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4750 zDbFilename, sqlite3_errmsg(p->db)); 4751 if( openFlags & OPEN_DB_KEEPALIVE ){ 4752 sqlite3_open(":memory:", &p->db); 4753 return; 4754 } 4755 exit(1); 4756 } 4757#ifndef SQLITE_OMIT_LOAD_EXTENSION 4758 sqlite3_enable_load_extension(p->db, 1); 4759#endif 4760 sqlite3_fileio_init(p->db, 0, 0); 4761 sqlite3_shathree_init(p->db, 0, 0); 4762 sqlite3_completion_init(p->db, 0, 0); 4763 sqlite3_uint_init(p->db, 0, 0); 4764 sqlite3_decimal_init(p->db, 0, 0); 4765 sqlite3_regexp_init(p->db, 0, 0); 4766 sqlite3_ieee_init(p->db, 0, 0); 4767 sqlite3_series_init(p->db, 0, 0); 4768#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4769 sqlite3_dbdata_init(p->db, 0, 0); 4770#endif 4771#ifdef SQLITE_HAVE_ZLIB 4772 sqlite3_zipfile_init(p->db, 0, 0); 4773 sqlite3_sqlar_init(p->db, 0, 0); 4774#endif 4775 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4776 shellAddSchemaName, 0, 0); 4777 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4778 shellModuleSchema, 0, 0); 4779 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4780 shellPutsFunc, 0, 0); 4781 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4782 shellEscapeCrnl, 0, 0); 4783 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4784 shellInt32, 0, 0); 4785 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 4786 shellIdQuote, 0, 0); 4787 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, 4788 shellUSleepFunc, 0, 0); 4789#ifndef SQLITE_NOHAVE_SYSTEM 4790 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4791 editFunc, 0, 0); 4792 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4793 editFunc, 0, 0); 4794#endif 4795 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4796 char *zSql = sqlite3_mprintf( 4797 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename); 4798 shell_check_oom(zSql); 4799 sqlite3_exec(p->db, zSql, 0, 0, 0); 4800 sqlite3_free(zSql); 4801 } 4802#ifndef SQLITE_OMIT_DESERIALIZE 4803 else 4804 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4805 int rc; 4806 int nData = 0; 4807 unsigned char *aData; 4808 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4809 aData = (unsigned char*)readFile(zDbFilename, &nData); 4810 }else{ 4811 aData = readHexDb(p, &nData); 4812 if( aData==0 ){ 4813 return; 4814 } 4815 } 4816 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4817 SQLITE_DESERIALIZE_RESIZEABLE | 4818 SQLITE_DESERIALIZE_FREEONCLOSE); 4819 if( rc ){ 4820 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4821 } 4822 if( p->szMax>0 ){ 4823 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4824 } 4825 } 4826#endif 4827 } 4828 if( p->bSafeModePersist && p->db!=0 ){ 4829 sqlite3_set_authorizer(p->db, safeModeAuth, p); 4830 } 4831} 4832 4833/* 4834** Attempt to close the databaes connection. Report errors. 4835*/ 4836void close_db(sqlite3 *db){ 4837 int rc = sqlite3_close(db); 4838 if( rc ){ 4839 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4840 rc, sqlite3_errmsg(db)); 4841 } 4842} 4843 4844#if HAVE_READLINE || HAVE_EDITLINE 4845/* 4846** Readline completion callbacks 4847*/ 4848static char *readline_completion_generator(const char *text, int state){ 4849 static sqlite3_stmt *pStmt = 0; 4850 char *zRet; 4851 if( state==0 ){ 4852 char *zSql; 4853 sqlite3_finalize(pStmt); 4854 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4855 " FROM completion(%Q) ORDER BY 1", text); 4856 shell_check_oom(zSql); 4857 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4858 sqlite3_free(zSql); 4859 } 4860 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4861 const char *z = (const char*)sqlite3_column_text(pStmt,0); 4862 zRet = z ? strdup(z) : 0; 4863 }else{ 4864 sqlite3_finalize(pStmt); 4865 pStmt = 0; 4866 zRet = 0; 4867 } 4868 return zRet; 4869} 4870static char **readline_completion(const char *zText, int iStart, int iEnd){ 4871 rl_attempted_completion_over = 1; 4872 return rl_completion_matches(zText, readline_completion_generator); 4873} 4874 4875#elif HAVE_LINENOISE 4876/* 4877** Linenoise completion callback 4878*/ 4879static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4880 int nLine = strlen30(zLine); 4881 int i, iStart; 4882 sqlite3_stmt *pStmt = 0; 4883 char *zSql; 4884 char zBuf[1000]; 4885 4886 if( nLine>sizeof(zBuf)-30 ) return; 4887 if( zLine[0]=='.' || zLine[0]=='#') return; 4888 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4889 if( i==nLine-1 ) return; 4890 iStart = i+1; 4891 memcpy(zBuf, zLine, iStart); 4892 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4893 " FROM completion(%Q,%Q) ORDER BY 1", 4894 &zLine[iStart], zLine); 4895 shell_check_oom(zSql); 4896 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4897 sqlite3_free(zSql); 4898 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4899 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4900 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4901 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4902 if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){ 4903 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4904 linenoiseAddCompletion(lc, zBuf); 4905 } 4906 } 4907 sqlite3_finalize(pStmt); 4908} 4909#endif 4910 4911/* 4912** Do C-language style dequoting. 4913** 4914** \a -> alarm 4915** \b -> backspace 4916** \t -> tab 4917** \n -> newline 4918** \v -> vertical tab 4919** \f -> form feed 4920** \r -> carriage return 4921** \s -> space 4922** \" -> " 4923** \' -> ' 4924** \\ -> backslash 4925** \NNN -> ascii character NNN in octal 4926*/ 4927static void resolve_backslashes(char *z){ 4928 int i, j; 4929 char c; 4930 while( *z && *z!='\\' ) z++; 4931 for(i=j=0; (c = z[i])!=0; i++, j++){ 4932 if( c=='\\' && z[i+1]!=0 ){ 4933 c = z[++i]; 4934 if( c=='a' ){ 4935 c = '\a'; 4936 }else if( c=='b' ){ 4937 c = '\b'; 4938 }else if( c=='t' ){ 4939 c = '\t'; 4940 }else if( c=='n' ){ 4941 c = '\n'; 4942 }else if( c=='v' ){ 4943 c = '\v'; 4944 }else if( c=='f' ){ 4945 c = '\f'; 4946 }else if( c=='r' ){ 4947 c = '\r'; 4948 }else if( c=='"' ){ 4949 c = '"'; 4950 }else if( c=='\'' ){ 4951 c = '\''; 4952 }else if( c=='\\' ){ 4953 c = '\\'; 4954 }else if( c>='0' && c<='7' ){ 4955 c -= '0'; 4956 if( z[i+1]>='0' && z[i+1]<='7' ){ 4957 i++; 4958 c = (c<<3) + z[i] - '0'; 4959 if( z[i+1]>='0' && z[i+1]<='7' ){ 4960 i++; 4961 c = (c<<3) + z[i] - '0'; 4962 } 4963 } 4964 } 4965 } 4966 z[j] = c; 4967 } 4968 if( j<i ) z[j] = 0; 4969} 4970 4971/* 4972** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4973** for TRUE and FALSE. Return the integer value if appropriate. 4974*/ 4975static int booleanValue(const char *zArg){ 4976 int i; 4977 if( zArg[0]=='0' && zArg[1]=='x' ){ 4978 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4979 }else{ 4980 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4981 } 4982 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4983 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4984 return 1; 4985 } 4986 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4987 return 0; 4988 } 4989 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4990 zArg); 4991 return 0; 4992} 4993 4994/* 4995** Set or clear a shell flag according to a boolean value. 4996*/ 4997static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4998 if( booleanValue(zArg) ){ 4999 ShellSetFlag(p, mFlag); 5000 }else{ 5001 ShellClearFlag(p, mFlag); 5002 } 5003} 5004 5005/* 5006** Close an output file, assuming it is not stderr or stdout 5007*/ 5008static void output_file_close(FILE *f){ 5009 if( f && f!=stdout && f!=stderr ) fclose(f); 5010} 5011 5012/* 5013** Try to open an output file. The names "stdout" and "stderr" are 5014** recognized and do the right thing. NULL is returned if the output 5015** filename is "off". 5016*/ 5017static FILE *output_file_open(const char *zFile, int bTextMode){ 5018 FILE *f; 5019 if( strcmp(zFile,"stdout")==0 ){ 5020 f = stdout; 5021 }else if( strcmp(zFile, "stderr")==0 ){ 5022 f = stderr; 5023 }else if( strcmp(zFile, "off")==0 ){ 5024 f = 0; 5025 }else{ 5026 f = fopen(zFile, bTextMode ? "w" : "wb"); 5027 if( f==0 ){ 5028 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 5029 } 5030 } 5031 return f; 5032} 5033 5034#ifndef SQLITE_OMIT_TRACE 5035/* 5036** A routine for handling output from sqlite3_trace(). 5037*/ 5038static int sql_trace_callback( 5039 unsigned mType, /* The trace type */ 5040 void *pArg, /* The ShellState pointer */ 5041 void *pP, /* Usually a pointer to sqlite_stmt */ 5042 void *pX /* Auxiliary output */ 5043){ 5044 ShellState *p = (ShellState*)pArg; 5045 sqlite3_stmt *pStmt; 5046 const char *zSql; 5047 int nSql; 5048 if( p->traceOut==0 ) return 0; 5049 if( mType==SQLITE_TRACE_CLOSE ){ 5050 utf8_printf(p->traceOut, "-- closing database connection\n"); 5051 return 0; 5052 } 5053 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 5054 zSql = (const char*)pX; 5055 }else{ 5056 pStmt = (sqlite3_stmt*)pP; 5057 switch( p->eTraceType ){ 5058 case SHELL_TRACE_EXPANDED: { 5059 zSql = sqlite3_expanded_sql(pStmt); 5060 break; 5061 } 5062#ifdef SQLITE_ENABLE_NORMALIZE 5063 case SHELL_TRACE_NORMALIZED: { 5064 zSql = sqlite3_normalized_sql(pStmt); 5065 break; 5066 } 5067#endif 5068 default: { 5069 zSql = sqlite3_sql(pStmt); 5070 break; 5071 } 5072 } 5073 } 5074 if( zSql==0 ) return 0; 5075 nSql = strlen30(zSql); 5076 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 5077 switch( mType ){ 5078 case SQLITE_TRACE_ROW: 5079 case SQLITE_TRACE_STMT: { 5080 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 5081 break; 5082 } 5083 case SQLITE_TRACE_PROFILE: { 5084 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 5085 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 5086 break; 5087 } 5088 } 5089 return 0; 5090} 5091#endif 5092 5093/* 5094** A no-op routine that runs with the ".breakpoint" doc-command. This is 5095** a useful spot to set a debugger breakpoint. 5096*/ 5097static void test_breakpoint(void){ 5098 static int nCall = 0; 5099 nCall++; 5100} 5101 5102/* 5103** An object used to read a CSV and other files for import. 5104*/ 5105typedef struct ImportCtx ImportCtx; 5106struct ImportCtx { 5107 const char *zFile; /* Name of the input file */ 5108 FILE *in; /* Read the CSV text from this input stream */ 5109 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */ 5110 char *z; /* Accumulated text for a field */ 5111 int n; /* Number of bytes in z */ 5112 int nAlloc; /* Space allocated for z[] */ 5113 int nLine; /* Current line number */ 5114 int nRow; /* Number of rows imported */ 5115 int nErr; /* Number of errors encountered */ 5116 int bNotFirst; /* True if one or more bytes already read */ 5117 int cTerm; /* Character that terminated the most recent field */ 5118 int cColSep; /* The column separator character. (Usually ",") */ 5119 int cRowSep; /* The row separator character. (Usually "\n") */ 5120}; 5121 5122/* Clean up resourced used by an ImportCtx */ 5123static void import_cleanup(ImportCtx *p){ 5124 if( p->in!=0 && p->xCloser!=0 ){ 5125 p->xCloser(p->in); 5126 p->in = 0; 5127 } 5128 sqlite3_free(p->z); 5129 p->z = 0; 5130} 5131 5132/* Append a single byte to z[] */ 5133static void import_append_char(ImportCtx *p, int c){ 5134 if( p->n+1>=p->nAlloc ){ 5135 p->nAlloc += p->nAlloc + 100; 5136 p->z = sqlite3_realloc64(p->z, p->nAlloc); 5137 shell_check_oom(p->z); 5138 } 5139 p->z[p->n++] = (char)c; 5140} 5141 5142/* Read a single field of CSV text. Compatible with rfc4180 and extended 5143** with the option of having a separator other than ",". 5144** 5145** + Input comes from p->in. 5146** + Store results in p->z of length p->n. Space to hold p->z comes 5147** from sqlite3_malloc64(). 5148** + Use p->cSep as the column separator. The default is ",". 5149** + Use p->rSep as the row separator. The default is "\n". 5150** + Keep track of the line number in p->nLine. 5151** + Store the character that terminates the field in p->cTerm. Store 5152** EOF on end-of-file. 5153** + Report syntax errors on stderr 5154*/ 5155static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 5156 int c; 5157 int cSep = p->cColSep; 5158 int rSep = p->cRowSep; 5159 p->n = 0; 5160 c = fgetc(p->in); 5161 if( c==EOF || seenInterrupt ){ 5162 p->cTerm = EOF; 5163 return 0; 5164 } 5165 if( c=='"' ){ 5166 int pc, ppc; 5167 int startLine = p->nLine; 5168 int cQuote = c; 5169 pc = ppc = 0; 5170 while( 1 ){ 5171 c = fgetc(p->in); 5172 if( c==rSep ) p->nLine++; 5173 if( c==cQuote ){ 5174 if( pc==cQuote ){ 5175 pc = 0; 5176 continue; 5177 } 5178 } 5179 if( (c==cSep && pc==cQuote) 5180 || (c==rSep && pc==cQuote) 5181 || (c==rSep && pc=='\r' && ppc==cQuote) 5182 || (c==EOF && pc==cQuote) 5183 ){ 5184 do{ p->n--; }while( p->z[p->n]!=cQuote ); 5185 p->cTerm = c; 5186 break; 5187 } 5188 if( pc==cQuote && c!='\r' ){ 5189 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 5190 p->zFile, p->nLine, cQuote); 5191 } 5192 if( c==EOF ){ 5193 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 5194 p->zFile, startLine, cQuote); 5195 p->cTerm = c; 5196 break; 5197 } 5198 import_append_char(p, c); 5199 ppc = pc; 5200 pc = c; 5201 } 5202 }else{ 5203 /* If this is the first field being parsed and it begins with the 5204 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 5205 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 5206 import_append_char(p, c); 5207 c = fgetc(p->in); 5208 if( (c&0xff)==0xbb ){ 5209 import_append_char(p, c); 5210 c = fgetc(p->in); 5211 if( (c&0xff)==0xbf ){ 5212 p->bNotFirst = 1; 5213 p->n = 0; 5214 return csv_read_one_field(p); 5215 } 5216 } 5217 } 5218 while( c!=EOF && c!=cSep && c!=rSep ){ 5219 import_append_char(p, c); 5220 c = fgetc(p->in); 5221 } 5222 if( c==rSep ){ 5223 p->nLine++; 5224 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 5225 } 5226 p->cTerm = c; 5227 } 5228 if( p->z ) p->z[p->n] = 0; 5229 p->bNotFirst = 1; 5230 return p->z; 5231} 5232 5233/* Read a single field of ASCII delimited text. 5234** 5235** + Input comes from p->in. 5236** + Store results in p->z of length p->n. Space to hold p->z comes 5237** from sqlite3_malloc64(). 5238** + Use p->cSep as the column separator. The default is "\x1F". 5239** + Use p->rSep as the row separator. The default is "\x1E". 5240** + Keep track of the row number in p->nLine. 5241** + Store the character that terminates the field in p->cTerm. Store 5242** EOF on end-of-file. 5243** + Report syntax errors on stderr 5244*/ 5245static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 5246 int c; 5247 int cSep = p->cColSep; 5248 int rSep = p->cRowSep; 5249 p->n = 0; 5250 c = fgetc(p->in); 5251 if( c==EOF || seenInterrupt ){ 5252 p->cTerm = EOF; 5253 return 0; 5254 } 5255 while( c!=EOF && c!=cSep && c!=rSep ){ 5256 import_append_char(p, c); 5257 c = fgetc(p->in); 5258 } 5259 if( c==rSep ){ 5260 p->nLine++; 5261 } 5262 p->cTerm = c; 5263 if( p->z ) p->z[p->n] = 0; 5264 return p->z; 5265} 5266 5267/* 5268** Try to transfer data for table zTable. If an error is seen while 5269** moving forward, try to go backwards. The backwards movement won't 5270** work for WITHOUT ROWID tables. 5271*/ 5272static void tryToCloneData( 5273 ShellState *p, 5274 sqlite3 *newDb, 5275 const char *zTable 5276){ 5277 sqlite3_stmt *pQuery = 0; 5278 sqlite3_stmt *pInsert = 0; 5279 char *zQuery = 0; 5280 char *zInsert = 0; 5281 int rc; 5282 int i, j, n; 5283 int nTable = strlen30(zTable); 5284 int k = 0; 5285 int cnt = 0; 5286 const int spinRate = 10000; 5287 5288 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 5289 shell_check_oom(zQuery); 5290 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5291 if( rc ){ 5292 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5293 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5294 zQuery); 5295 goto end_data_xfer; 5296 } 5297 n = sqlite3_column_count(pQuery); 5298 zInsert = sqlite3_malloc64(200 + nTable + n*3); 5299 shell_check_oom(zInsert); 5300 sqlite3_snprintf(200+nTable,zInsert, 5301 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 5302 i = strlen30(zInsert); 5303 for(j=1; j<n; j++){ 5304 memcpy(zInsert+i, ",?", 2); 5305 i += 2; 5306 } 5307 memcpy(zInsert+i, ");", 3); 5308 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 5309 if( rc ){ 5310 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5311 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 5312 zQuery); 5313 goto end_data_xfer; 5314 } 5315 for(k=0; k<2; k++){ 5316 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5317 for(i=0; i<n; i++){ 5318 switch( sqlite3_column_type(pQuery, i) ){ 5319 case SQLITE_NULL: { 5320 sqlite3_bind_null(pInsert, i+1); 5321 break; 5322 } 5323 case SQLITE_INTEGER: { 5324 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 5325 break; 5326 } 5327 case SQLITE_FLOAT: { 5328 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 5329 break; 5330 } 5331 case SQLITE_TEXT: { 5332 sqlite3_bind_text(pInsert, i+1, 5333 (const char*)sqlite3_column_text(pQuery,i), 5334 -1, SQLITE_STATIC); 5335 break; 5336 } 5337 case SQLITE_BLOB: { 5338 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 5339 sqlite3_column_bytes(pQuery,i), 5340 SQLITE_STATIC); 5341 break; 5342 } 5343 } 5344 } /* End for */ 5345 rc = sqlite3_step(pInsert); 5346 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 5347 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 5348 sqlite3_errmsg(newDb)); 5349 } 5350 sqlite3_reset(pInsert); 5351 cnt++; 5352 if( (cnt%spinRate)==0 ){ 5353 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 5354 fflush(stdout); 5355 } 5356 } /* End while */ 5357 if( rc==SQLITE_DONE ) break; 5358 sqlite3_finalize(pQuery); 5359 sqlite3_free(zQuery); 5360 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 5361 zTable); 5362 shell_check_oom(zQuery); 5363 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5364 if( rc ){ 5365 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 5366 break; 5367 } 5368 } /* End for(k=0...) */ 5369 5370end_data_xfer: 5371 sqlite3_finalize(pQuery); 5372 sqlite3_finalize(pInsert); 5373 sqlite3_free(zQuery); 5374 sqlite3_free(zInsert); 5375} 5376 5377 5378/* 5379** Try to transfer all rows of the schema that match zWhere. For 5380** each row, invoke xForEach() on the object defined by that row. 5381** If an error is encountered while moving forward through the 5382** sqlite_schema table, try again moving backwards. 5383*/ 5384static void tryToCloneSchema( 5385 ShellState *p, 5386 sqlite3 *newDb, 5387 const char *zWhere, 5388 void (*xForEach)(ShellState*,sqlite3*,const char*) 5389){ 5390 sqlite3_stmt *pQuery = 0; 5391 char *zQuery = 0; 5392 int rc; 5393 const unsigned char *zName; 5394 const unsigned char *zSql; 5395 char *zErrMsg = 0; 5396 5397 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5398 " WHERE %s", zWhere); 5399 shell_check_oom(zQuery); 5400 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5401 if( rc ){ 5402 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5403 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5404 zQuery); 5405 goto end_schema_xfer; 5406 } 5407 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5408 zName = sqlite3_column_text(pQuery, 0); 5409 zSql = sqlite3_column_text(pQuery, 1); 5410 if( zName==0 || zSql==0 ) continue; 5411 printf("%s... ", zName); fflush(stdout); 5412 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5413 if( zErrMsg ){ 5414 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5415 sqlite3_free(zErrMsg); 5416 zErrMsg = 0; 5417 } 5418 if( xForEach ){ 5419 xForEach(p, newDb, (const char*)zName); 5420 } 5421 printf("done\n"); 5422 } 5423 if( rc!=SQLITE_DONE ){ 5424 sqlite3_finalize(pQuery); 5425 sqlite3_free(zQuery); 5426 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5427 " WHERE %s ORDER BY rowid DESC", zWhere); 5428 shell_check_oom(zQuery); 5429 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5430 if( rc ){ 5431 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5432 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5433 zQuery); 5434 goto end_schema_xfer; 5435 } 5436 while( sqlite3_step(pQuery)==SQLITE_ROW ){ 5437 zName = sqlite3_column_text(pQuery, 0); 5438 zSql = sqlite3_column_text(pQuery, 1); 5439 if( zName==0 || zSql==0 ) continue; 5440 printf("%s... ", zName); fflush(stdout); 5441 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5442 if( zErrMsg ){ 5443 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5444 sqlite3_free(zErrMsg); 5445 zErrMsg = 0; 5446 } 5447 if( xForEach ){ 5448 xForEach(p, newDb, (const char*)zName); 5449 } 5450 printf("done\n"); 5451 } 5452 } 5453end_schema_xfer: 5454 sqlite3_finalize(pQuery); 5455 sqlite3_free(zQuery); 5456} 5457 5458/* 5459** Open a new database file named "zNewDb". Try to recover as much information 5460** as possible out of the main database (which might be corrupt) and write it 5461** into zNewDb. 5462*/ 5463static void tryToClone(ShellState *p, const char *zNewDb){ 5464 int rc; 5465 sqlite3 *newDb = 0; 5466 if( access(zNewDb,0)==0 ){ 5467 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 5468 return; 5469 } 5470 rc = sqlite3_open(zNewDb, &newDb); 5471 if( rc ){ 5472 utf8_printf(stderr, "Cannot create output database: %s\n", 5473 sqlite3_errmsg(newDb)); 5474 }else{ 5475 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 5476 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 5477 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 5478 tryToCloneSchema(p, newDb, "type!='table'", 0); 5479 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 5480 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 5481 } 5482 close_db(newDb); 5483} 5484 5485/* 5486** Change the output file back to stdout. 5487** 5488** If the p->doXdgOpen flag is set, that means the output was being 5489** redirected to a temporary file named by p->zTempFile. In that case, 5490** launch start/open/xdg-open on that temporary file. 5491*/ 5492static void output_reset(ShellState *p){ 5493 if( p->outfile[0]=='|' ){ 5494#ifndef SQLITE_OMIT_POPEN 5495 pclose(p->out); 5496#endif 5497 }else{ 5498 output_file_close(p->out); 5499#ifndef SQLITE_NOHAVE_SYSTEM 5500 if( p->doXdgOpen ){ 5501 const char *zXdgOpenCmd = 5502#if defined(_WIN32) 5503 "start"; 5504#elif defined(__APPLE__) 5505 "open"; 5506#else 5507 "xdg-open"; 5508#endif 5509 char *zCmd; 5510 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 5511 if( system(zCmd) ){ 5512 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 5513 }else{ 5514 /* Give the start/open/xdg-open command some time to get 5515 ** going before we continue, and potential delete the 5516 ** p->zTempFile data file out from under it */ 5517 sqlite3_sleep(2000); 5518 } 5519 sqlite3_free(zCmd); 5520 outputModePop(p); 5521 p->doXdgOpen = 0; 5522 } 5523#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 5524 } 5525 p->outfile[0] = 0; 5526 p->out = stdout; 5527} 5528 5529/* 5530** Run an SQL command and return the single integer result. 5531*/ 5532static int db_int(ShellState *p, const char *zSql){ 5533 sqlite3_stmt *pStmt; 5534 int res = 0; 5535 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 5536 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 5537 res = sqlite3_column_int(pStmt,0); 5538 } 5539 sqlite3_finalize(pStmt); 5540 return res; 5541} 5542 5543/* 5544** Convert a 2-byte or 4-byte big-endian integer into a native integer 5545*/ 5546static unsigned int get2byteInt(unsigned char *a){ 5547 return (a[0]<<8) + a[1]; 5548} 5549static unsigned int get4byteInt(unsigned char *a){ 5550 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 5551} 5552 5553/* 5554** Implementation of the ".dbinfo" command. 5555** 5556** Return 1 on error, 2 to exit, and 0 otherwise. 5557*/ 5558static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 5559 static const struct { const char *zName; int ofst; } aField[] = { 5560 { "file change counter:", 24 }, 5561 { "database page count:", 28 }, 5562 { "freelist page count:", 36 }, 5563 { "schema cookie:", 40 }, 5564 { "schema format:", 44 }, 5565 { "default cache size:", 48 }, 5566 { "autovacuum top root:", 52 }, 5567 { "incremental vacuum:", 64 }, 5568 { "text encoding:", 56 }, 5569 { "user version:", 60 }, 5570 { "application id:", 68 }, 5571 { "software version:", 96 }, 5572 }; 5573 static const struct { const char *zName; const char *zSql; } aQuery[] = { 5574 { "number of tables:", 5575 "SELECT count(*) FROM %s WHERE type='table'" }, 5576 { "number of indexes:", 5577 "SELECT count(*) FROM %s WHERE type='index'" }, 5578 { "number of triggers:", 5579 "SELECT count(*) FROM %s WHERE type='trigger'" }, 5580 { "number of views:", 5581 "SELECT count(*) FROM %s WHERE type='view'" }, 5582 { "schema size:", 5583 "SELECT total(length(sql)) FROM %s" }, 5584 }; 5585 int i, rc; 5586 unsigned iDataVersion; 5587 char *zSchemaTab; 5588 char *zDb = nArg>=2 ? azArg[1] : "main"; 5589 sqlite3_stmt *pStmt = 0; 5590 unsigned char aHdr[100]; 5591 open_db(p, 0); 5592 if( p->db==0 ) return 1; 5593 rc = sqlite3_prepare_v2(p->db, 5594 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 5595 -1, &pStmt, 0); 5596 if( rc ){ 5597 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 5598 sqlite3_finalize(pStmt); 5599 return 1; 5600 } 5601 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 5602 if( sqlite3_step(pStmt)==SQLITE_ROW 5603 && sqlite3_column_bytes(pStmt,0)>100 5604 ){ 5605 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 5606 sqlite3_finalize(pStmt); 5607 }else{ 5608 raw_printf(stderr, "unable to read database header\n"); 5609 sqlite3_finalize(pStmt); 5610 return 1; 5611 } 5612 i = get2byteInt(aHdr+16); 5613 if( i==1 ) i = 65536; 5614 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 5615 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 5616 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 5617 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 5618 for(i=0; i<ArraySize(aField); i++){ 5619 int ofst = aField[i].ofst; 5620 unsigned int val = get4byteInt(aHdr + ofst); 5621 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 5622 switch( ofst ){ 5623 case 56: { 5624 if( val==1 ) raw_printf(p->out, " (utf8)"); 5625 if( val==2 ) raw_printf(p->out, " (utf16le)"); 5626 if( val==3 ) raw_printf(p->out, " (utf16be)"); 5627 } 5628 } 5629 raw_printf(p->out, "\n"); 5630 } 5631 if( zDb==0 ){ 5632 zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); 5633 }else if( strcmp(zDb,"temp")==0 ){ 5634 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); 5635 }else{ 5636 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); 5637 } 5638 for(i=0; i<ArraySize(aQuery); i++){ 5639 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 5640 int val = db_int(p, zSql); 5641 sqlite3_free(zSql); 5642 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 5643 } 5644 sqlite3_free(zSchemaTab); 5645 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 5646 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 5647 return 0; 5648} 5649 5650/* 5651** Print the current sqlite3_errmsg() value to stderr and return 1. 5652*/ 5653static int shellDatabaseError(sqlite3 *db){ 5654 const char *zErr = sqlite3_errmsg(db); 5655 utf8_printf(stderr, "Error: %s\n", zErr); 5656 return 1; 5657} 5658 5659/* 5660** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 5661** if they match and FALSE (0) if they do not match. 5662** 5663** Globbing rules: 5664** 5665** '*' Matches any sequence of zero or more characters. 5666** 5667** '?' Matches exactly one character. 5668** 5669** [...] Matches one character from the enclosed list of 5670** characters. 5671** 5672** [^...] Matches one character not in the enclosed list. 5673** 5674** '#' Matches any sequence of one or more digits with an 5675** optional + or - sign in front 5676** 5677** ' ' Any span of whitespace matches any other span of 5678** whitespace. 5679** 5680** Extra whitespace at the end of z[] is ignored. 5681*/ 5682static int testcase_glob(const char *zGlob, const char *z){ 5683 int c, c2; 5684 int invert; 5685 int seen; 5686 5687 while( (c = (*(zGlob++)))!=0 ){ 5688 if( IsSpace(c) ){ 5689 if( !IsSpace(*z) ) return 0; 5690 while( IsSpace(*zGlob) ) zGlob++; 5691 while( IsSpace(*z) ) z++; 5692 }else if( c=='*' ){ 5693 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5694 if( c=='?' && (*(z++))==0 ) return 0; 5695 } 5696 if( c==0 ){ 5697 return 1; 5698 }else if( c=='[' ){ 5699 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5700 z++; 5701 } 5702 return (*z)!=0; 5703 } 5704 while( (c2 = (*(z++)))!=0 ){ 5705 while( c2!=c ){ 5706 c2 = *(z++); 5707 if( c2==0 ) return 0; 5708 } 5709 if( testcase_glob(zGlob,z) ) return 1; 5710 } 5711 return 0; 5712 }else if( c=='?' ){ 5713 if( (*(z++))==0 ) return 0; 5714 }else if( c=='[' ){ 5715 int prior_c = 0; 5716 seen = 0; 5717 invert = 0; 5718 c = *(z++); 5719 if( c==0 ) return 0; 5720 c2 = *(zGlob++); 5721 if( c2=='^' ){ 5722 invert = 1; 5723 c2 = *(zGlob++); 5724 } 5725 if( c2==']' ){ 5726 if( c==']' ) seen = 1; 5727 c2 = *(zGlob++); 5728 } 5729 while( c2 && c2!=']' ){ 5730 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5731 c2 = *(zGlob++); 5732 if( c>=prior_c && c<=c2 ) seen = 1; 5733 prior_c = 0; 5734 }else{ 5735 if( c==c2 ){ 5736 seen = 1; 5737 } 5738 prior_c = c2; 5739 } 5740 c2 = *(zGlob++); 5741 } 5742 if( c2==0 || (seen ^ invert)==0 ) return 0; 5743 }else if( c=='#' ){ 5744 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5745 if( !IsDigit(z[0]) ) return 0; 5746 z++; 5747 while( IsDigit(z[0]) ){ z++; } 5748 }else{ 5749 if( c!=(*(z++)) ) return 0; 5750 } 5751 } 5752 while( IsSpace(*z) ){ z++; } 5753 return *z==0; 5754} 5755 5756 5757/* 5758** Compare the string as a command-line option with either one or two 5759** initial "-" characters. 5760*/ 5761static int optionMatch(const char *zStr, const char *zOpt){ 5762 if( zStr[0]!='-' ) return 0; 5763 zStr++; 5764 if( zStr[0]=='-' ) zStr++; 5765 return strcmp(zStr, zOpt)==0; 5766} 5767 5768/* 5769** Delete a file. 5770*/ 5771int shellDeleteFile(const char *zFilename){ 5772 int rc; 5773#ifdef _WIN32 5774 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5775 rc = _wunlink(z); 5776 sqlite3_free(z); 5777#else 5778 rc = unlink(zFilename); 5779#endif 5780 return rc; 5781} 5782 5783/* 5784** Try to delete the temporary file (if there is one) and free the 5785** memory used to hold the name of the temp file. 5786*/ 5787static void clearTempFile(ShellState *p){ 5788 if( p->zTempFile==0 ) return; 5789 if( p->doXdgOpen ) return; 5790 if( shellDeleteFile(p->zTempFile) ) return; 5791 sqlite3_free(p->zTempFile); 5792 p->zTempFile = 0; 5793} 5794 5795/* 5796** Create a new temp file name with the given suffix. 5797*/ 5798static void newTempFile(ShellState *p, const char *zSuffix){ 5799 clearTempFile(p); 5800 sqlite3_free(p->zTempFile); 5801 p->zTempFile = 0; 5802 if( p->db ){ 5803 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5804 } 5805 if( p->zTempFile==0 ){ 5806 /* If p->db is an in-memory database then the TEMPFILENAME file-control 5807 ** will not work and we will need to fallback to guessing */ 5808 char *zTemp; 5809 sqlite3_uint64 r; 5810 sqlite3_randomness(sizeof(r), &r); 5811 zTemp = getenv("TEMP"); 5812 if( zTemp==0 ) zTemp = getenv("TMP"); 5813 if( zTemp==0 ){ 5814#ifdef _WIN32 5815 zTemp = "\\tmp"; 5816#else 5817 zTemp = "/tmp"; 5818#endif 5819 } 5820 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); 5821 }else{ 5822 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5823 } 5824 shell_check_oom(p->zTempFile); 5825} 5826 5827 5828/* 5829** The implementation of SQL scalar function fkey_collate_clause(), used 5830** by the ".lint fkey-indexes" command. This scalar function is always 5831** called with four arguments - the parent table name, the parent column name, 5832** the child table name and the child column name. 5833** 5834** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5835** 5836** If either of the named tables or columns do not exist, this function 5837** returns an empty string. An empty string is also returned if both tables 5838** and columns exist but have the same default collation sequence. Or, 5839** if both exist but the default collation sequences are different, this 5840** function returns the string " COLLATE <parent-collation>", where 5841** <parent-collation> is the default collation sequence of the parent column. 5842*/ 5843static void shellFkeyCollateClause( 5844 sqlite3_context *pCtx, 5845 int nVal, 5846 sqlite3_value **apVal 5847){ 5848 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5849 const char *zParent; 5850 const char *zParentCol; 5851 const char *zParentSeq; 5852 const char *zChild; 5853 const char *zChildCol; 5854 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5855 int rc; 5856 5857 assert( nVal==4 ); 5858 zParent = (const char*)sqlite3_value_text(apVal[0]); 5859 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5860 zChild = (const char*)sqlite3_value_text(apVal[2]); 5861 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5862 5863 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5864 rc = sqlite3_table_column_metadata( 5865 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5866 ); 5867 if( rc==SQLITE_OK ){ 5868 rc = sqlite3_table_column_metadata( 5869 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5870 ); 5871 } 5872 5873 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5874 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5875 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5876 sqlite3_free(z); 5877 } 5878} 5879 5880 5881/* 5882** The implementation of dot-command ".lint fkey-indexes". 5883*/ 5884static int lintFkeyIndexes( 5885 ShellState *pState, /* Current shell tool state */ 5886 char **azArg, /* Array of arguments passed to dot command */ 5887 int nArg /* Number of entries in azArg[] */ 5888){ 5889 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5890 FILE *out = pState->out; /* Stream to write non-error output to */ 5891 int bVerbose = 0; /* If -verbose is present */ 5892 int bGroupByParent = 0; /* If -groupbyparent is present */ 5893 int i; /* To iterate through azArg[] */ 5894 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5895 int rc; /* Return code */ 5896 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5897 5898 /* 5899 ** This SELECT statement returns one row for each foreign key constraint 5900 ** in the schema of the main database. The column values are: 5901 ** 5902 ** 0. The text of an SQL statement similar to: 5903 ** 5904 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5905 ** 5906 ** This SELECT is similar to the one that the foreign keys implementation 5907 ** needs to run internally on child tables. If there is an index that can 5908 ** be used to optimize this query, then it can also be used by the FK 5909 ** implementation to optimize DELETE or UPDATE statements on the parent 5910 ** table. 5911 ** 5912 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5913 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5914 ** contains an index that can be used to optimize the query. 5915 ** 5916 ** 2. Human readable text that describes the child table and columns. e.g. 5917 ** 5918 ** "child_table(child_key1, child_key2)" 5919 ** 5920 ** 3. Human readable text that describes the parent table and columns. e.g. 5921 ** 5922 ** "parent_table(parent_key1, parent_key2)" 5923 ** 5924 ** 4. A full CREATE INDEX statement for an index that could be used to 5925 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5926 ** 5927 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5928 ** 5929 ** 5. The name of the parent table. 5930 ** 5931 ** These six values are used by the C logic below to generate the report. 5932 */ 5933 const char *zSql = 5934 "SELECT " 5935 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5936 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5937 " || fkey_collate_clause(" 5938 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5939 ", " 5940 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('" 5941 " || group_concat('*=?', ' AND ') || ')'" 5942 ", " 5943 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5944 ", " 5945 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5946 ", " 5947 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5948 " || ' ON ' || quote(s.name) || '('" 5949 " || group_concat(quote(f.[from]) ||" 5950 " fkey_collate_clause(" 5951 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5952 " || ');'" 5953 ", " 5954 " f.[table] " 5955 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " 5956 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5957 "GROUP BY s.name, f.id " 5958 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5959 ; 5960 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)"; 5961 5962 for(i=2; i<nArg; i++){ 5963 int n = strlen30(azArg[i]); 5964 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5965 bVerbose = 1; 5966 } 5967 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5968 bGroupByParent = 1; 5969 zIndent = " "; 5970 } 5971 else{ 5972 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5973 azArg[0], azArg[1] 5974 ); 5975 return SQLITE_ERROR; 5976 } 5977 } 5978 5979 /* Register the fkey_collate_clause() SQL function */ 5980 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5981 0, shellFkeyCollateClause, 0, 0 5982 ); 5983 5984 5985 if( rc==SQLITE_OK ){ 5986 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5987 } 5988 if( rc==SQLITE_OK ){ 5989 sqlite3_bind_int(pSql, 1, bGroupByParent); 5990 } 5991 5992 if( rc==SQLITE_OK ){ 5993 int rc2; 5994 char *zPrev = 0; 5995 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5996 int res = -1; 5997 sqlite3_stmt *pExplain = 0; 5998 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5999 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 6000 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 6001 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 6002 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 6003 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 6004 6005 if( zEQP==0 ) continue; 6006 if( zGlob==0 ) continue; 6007 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 6008 if( rc!=SQLITE_OK ) break; 6009 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 6010 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 6011 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan) 6012 || 0==sqlite3_strglob(zGlobIPK, zPlan)); 6013 } 6014 rc = sqlite3_finalize(pExplain); 6015 if( rc!=SQLITE_OK ) break; 6016 6017 if( res<0 ){ 6018 raw_printf(stderr, "Error: internal error"); 6019 break; 6020 }else{ 6021 if( bGroupByParent 6022 && (bVerbose || res==0) 6023 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 6024 ){ 6025 raw_printf(out, "-- Parent table %s\n", zParent); 6026 sqlite3_free(zPrev); 6027 zPrev = sqlite3_mprintf("%s", zParent); 6028 } 6029 6030 if( res==0 ){ 6031 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 6032 }else if( bVerbose ){ 6033 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 6034 zIndent, zFrom, zTarget 6035 ); 6036 } 6037 } 6038 } 6039 sqlite3_free(zPrev); 6040 6041 if( rc!=SQLITE_OK ){ 6042 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6043 } 6044 6045 rc2 = sqlite3_finalize(pSql); 6046 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 6047 rc = rc2; 6048 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6049 } 6050 }else{ 6051 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6052 } 6053 6054 return rc; 6055} 6056 6057/* 6058** Implementation of ".lint" dot command. 6059*/ 6060static int lintDotCommand( 6061 ShellState *pState, /* Current shell tool state */ 6062 char **azArg, /* Array of arguments passed to dot command */ 6063 int nArg /* Number of entries in azArg[] */ 6064){ 6065 int n; 6066 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 6067 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 6068 return lintFkeyIndexes(pState, azArg, nArg); 6069 6070 usage: 6071 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 6072 raw_printf(stderr, "Where sub-commands are:\n"); 6073 raw_printf(stderr, " fkey-indexes\n"); 6074 return SQLITE_ERROR; 6075} 6076 6077#if !defined SQLITE_OMIT_VIRTUALTABLE 6078static void shellPrepare( 6079 sqlite3 *db, 6080 int *pRc, 6081 const char *zSql, 6082 sqlite3_stmt **ppStmt 6083){ 6084 *ppStmt = 0; 6085 if( *pRc==SQLITE_OK ){ 6086 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 6087 if( rc!=SQLITE_OK ){ 6088 raw_printf(stderr, "sql error: %s (%d)\n", 6089 sqlite3_errmsg(db), sqlite3_errcode(db) 6090 ); 6091 *pRc = rc; 6092 } 6093 } 6094} 6095 6096/* 6097** Create a prepared statement using printf-style arguments for the SQL. 6098** 6099** This routine is could be marked "static". But it is not always used, 6100** depending on compile-time options. By omitting the "static", we avoid 6101** nuisance compiler warnings about "defined but not used". 6102*/ 6103void shellPreparePrintf( 6104 sqlite3 *db, 6105 int *pRc, 6106 sqlite3_stmt **ppStmt, 6107 const char *zFmt, 6108 ... 6109){ 6110 *ppStmt = 0; 6111 if( *pRc==SQLITE_OK ){ 6112 va_list ap; 6113 char *z; 6114 va_start(ap, zFmt); 6115 z = sqlite3_vmprintf(zFmt, ap); 6116 va_end(ap); 6117 if( z==0 ){ 6118 *pRc = SQLITE_NOMEM; 6119 }else{ 6120 shellPrepare(db, pRc, z, ppStmt); 6121 sqlite3_free(z); 6122 } 6123 } 6124} 6125 6126/* Finalize the prepared statement created using shellPreparePrintf(). 6127** 6128** This routine is could be marked "static". But it is not always used, 6129** depending on compile-time options. By omitting the "static", we avoid 6130** nuisance compiler warnings about "defined but not used". 6131*/ 6132void shellFinalize( 6133 int *pRc, 6134 sqlite3_stmt *pStmt 6135){ 6136 if( pStmt ){ 6137 sqlite3 *db = sqlite3_db_handle(pStmt); 6138 int rc = sqlite3_finalize(pStmt); 6139 if( *pRc==SQLITE_OK ){ 6140 if( rc!=SQLITE_OK ){ 6141 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6142 } 6143 *pRc = rc; 6144 } 6145 } 6146} 6147 6148/* Reset the prepared statement created using shellPreparePrintf(). 6149** 6150** This routine is could be marked "static". But it is not always used, 6151** depending on compile-time options. By omitting the "static", we avoid 6152** nuisance compiler warnings about "defined but not used". 6153*/ 6154void shellReset( 6155 int *pRc, 6156 sqlite3_stmt *pStmt 6157){ 6158 int rc = sqlite3_reset(pStmt); 6159 if( *pRc==SQLITE_OK ){ 6160 if( rc!=SQLITE_OK ){ 6161 sqlite3 *db = sqlite3_db_handle(pStmt); 6162 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6163 } 6164 *pRc = rc; 6165 } 6166} 6167#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 6168 6169#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6170/****************************************************************************** 6171** The ".archive" or ".ar" command. 6172*/ 6173/* 6174** Structure representing a single ".ar" command. 6175*/ 6176typedef struct ArCommand ArCommand; 6177struct ArCommand { 6178 u8 eCmd; /* An AR_CMD_* value */ 6179 u8 bVerbose; /* True if --verbose */ 6180 u8 bZip; /* True if the archive is a ZIP */ 6181 u8 bDryRun; /* True if --dry-run */ 6182 u8 bAppend; /* True if --append */ 6183 u8 bGlob; /* True if --glob */ 6184 u8 fromCmdLine; /* Run from -A instead of .archive */ 6185 int nArg; /* Number of command arguments */ 6186 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 6187 const char *zFile; /* --file argument, or NULL */ 6188 const char *zDir; /* --directory argument, or NULL */ 6189 char **azArg; /* Array of command arguments */ 6190 ShellState *p; /* Shell state */ 6191 sqlite3 *db; /* Database containing the archive */ 6192}; 6193 6194/* 6195** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 6196*/ 6197static int arUsage(FILE *f){ 6198 showHelp(f,"archive"); 6199 return SQLITE_ERROR; 6200} 6201 6202/* 6203** Print an error message for the .ar command to stderr and return 6204** SQLITE_ERROR. 6205*/ 6206static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 6207 va_list ap; 6208 char *z; 6209 va_start(ap, zFmt); 6210 z = sqlite3_vmprintf(zFmt, ap); 6211 va_end(ap); 6212 utf8_printf(stderr, "Error: %s\n", z); 6213 if( pAr->fromCmdLine ){ 6214 utf8_printf(stderr, "Use \"-A\" for more help\n"); 6215 }else{ 6216 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 6217 } 6218 sqlite3_free(z); 6219 return SQLITE_ERROR; 6220} 6221 6222/* 6223** Values for ArCommand.eCmd. 6224*/ 6225#define AR_CMD_CREATE 1 6226#define AR_CMD_UPDATE 2 6227#define AR_CMD_INSERT 3 6228#define AR_CMD_EXTRACT 4 6229#define AR_CMD_LIST 5 6230#define AR_CMD_HELP 6 6231#define AR_CMD_REMOVE 7 6232 6233/* 6234** Other (non-command) switches. 6235*/ 6236#define AR_SWITCH_VERBOSE 8 6237#define AR_SWITCH_FILE 9 6238#define AR_SWITCH_DIRECTORY 10 6239#define AR_SWITCH_APPEND 11 6240#define AR_SWITCH_DRYRUN 12 6241#define AR_SWITCH_GLOB 13 6242 6243static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 6244 switch( eSwitch ){ 6245 case AR_CMD_CREATE: 6246 case AR_CMD_EXTRACT: 6247 case AR_CMD_LIST: 6248 case AR_CMD_REMOVE: 6249 case AR_CMD_UPDATE: 6250 case AR_CMD_INSERT: 6251 case AR_CMD_HELP: 6252 if( pAr->eCmd ){ 6253 return arErrorMsg(pAr, "multiple command options"); 6254 } 6255 pAr->eCmd = eSwitch; 6256 break; 6257 6258 case AR_SWITCH_DRYRUN: 6259 pAr->bDryRun = 1; 6260 break; 6261 case AR_SWITCH_GLOB: 6262 pAr->bGlob = 1; 6263 break; 6264 case AR_SWITCH_VERBOSE: 6265 pAr->bVerbose = 1; 6266 break; 6267 case AR_SWITCH_APPEND: 6268 pAr->bAppend = 1; 6269 /* Fall thru into --file */ 6270 case AR_SWITCH_FILE: 6271 pAr->zFile = zArg; 6272 break; 6273 case AR_SWITCH_DIRECTORY: 6274 pAr->zDir = zArg; 6275 break; 6276 } 6277 6278 return SQLITE_OK; 6279} 6280 6281/* 6282** Parse the command line for an ".ar" command. The results are written into 6283** structure (*pAr). SQLITE_OK is returned if the command line is parsed 6284** successfully, otherwise an error message is written to stderr and 6285** SQLITE_ERROR returned. 6286*/ 6287static int arParseCommand( 6288 char **azArg, /* Array of arguments passed to dot command */ 6289 int nArg, /* Number of entries in azArg[] */ 6290 ArCommand *pAr /* Populate this object */ 6291){ 6292 struct ArSwitch { 6293 const char *zLong; 6294 char cShort; 6295 u8 eSwitch; 6296 u8 bArg; 6297 } aSwitch[] = { 6298 { "create", 'c', AR_CMD_CREATE, 0 }, 6299 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 6300 { "insert", 'i', AR_CMD_INSERT, 0 }, 6301 { "list", 't', AR_CMD_LIST, 0 }, 6302 { "remove", 'r', AR_CMD_REMOVE, 0 }, 6303 { "update", 'u', AR_CMD_UPDATE, 0 }, 6304 { "help", 'h', AR_CMD_HELP, 0 }, 6305 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 6306 { "file", 'f', AR_SWITCH_FILE, 1 }, 6307 { "append", 'a', AR_SWITCH_APPEND, 1 }, 6308 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 6309 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 6310 { "glob", 'g', AR_SWITCH_GLOB, 0 }, 6311 }; 6312 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 6313 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 6314 6315 if( nArg<=1 ){ 6316 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 6317 return arUsage(stderr); 6318 }else{ 6319 char *z = azArg[1]; 6320 if( z[0]!='-' ){ 6321 /* Traditional style [tar] invocation */ 6322 int i; 6323 int iArg = 2; 6324 for(i=0; z[i]; i++){ 6325 const char *zArg = 0; 6326 struct ArSwitch *pOpt; 6327 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6328 if( z[i]==pOpt->cShort ) break; 6329 } 6330 if( pOpt==pEnd ){ 6331 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6332 } 6333 if( pOpt->bArg ){ 6334 if( iArg>=nArg ){ 6335 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 6336 } 6337 zArg = azArg[iArg++]; 6338 } 6339 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6340 } 6341 pAr->nArg = nArg-iArg; 6342 if( pAr->nArg>0 ){ 6343 pAr->azArg = &azArg[iArg]; 6344 } 6345 }else{ 6346 /* Non-traditional invocation */ 6347 int iArg; 6348 for(iArg=1; iArg<nArg; iArg++){ 6349 int n; 6350 z = azArg[iArg]; 6351 if( z[0]!='-' ){ 6352 /* All remaining command line words are command arguments. */ 6353 pAr->azArg = &azArg[iArg]; 6354 pAr->nArg = nArg-iArg; 6355 break; 6356 } 6357 n = strlen30(z); 6358 6359 if( z[1]!='-' ){ 6360 int i; 6361 /* One or more short options */ 6362 for(i=1; i<n; i++){ 6363 const char *zArg = 0; 6364 struct ArSwitch *pOpt; 6365 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6366 if( z[i]==pOpt->cShort ) break; 6367 } 6368 if( pOpt==pEnd ){ 6369 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6370 } 6371 if( pOpt->bArg ){ 6372 if( i<(n-1) ){ 6373 zArg = &z[i+1]; 6374 i = n; 6375 }else{ 6376 if( iArg>=(nArg-1) ){ 6377 return arErrorMsg(pAr, "option requires an argument: %c", 6378 z[i]); 6379 } 6380 zArg = azArg[++iArg]; 6381 } 6382 } 6383 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6384 } 6385 }else if( z[2]=='\0' ){ 6386 /* A -- option, indicating that all remaining command line words 6387 ** are command arguments. */ 6388 pAr->azArg = &azArg[iArg+1]; 6389 pAr->nArg = nArg-iArg-1; 6390 break; 6391 }else{ 6392 /* A long option */ 6393 const char *zArg = 0; /* Argument for option, if any */ 6394 struct ArSwitch *pMatch = 0; /* Matching option */ 6395 struct ArSwitch *pOpt; /* Iterator */ 6396 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6397 const char *zLong = pOpt->zLong; 6398 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 6399 if( pMatch ){ 6400 return arErrorMsg(pAr, "ambiguous option: %s",z); 6401 }else{ 6402 pMatch = pOpt; 6403 } 6404 } 6405 } 6406 6407 if( pMatch==0 ){ 6408 return arErrorMsg(pAr, "unrecognized option: %s", z); 6409 } 6410 if( pMatch->bArg ){ 6411 if( iArg>=(nArg-1) ){ 6412 return arErrorMsg(pAr, "option requires an argument: %s", z); 6413 } 6414 zArg = azArg[++iArg]; 6415 } 6416 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 6417 } 6418 } 6419 } 6420 } 6421 6422 return SQLITE_OK; 6423} 6424 6425/* 6426** This function assumes that all arguments within the ArCommand.azArg[] 6427** array refer to archive members, as for the --extract, --list or --remove 6428** commands. It checks that each of them are "present". If any specified 6429** file is not present in the archive, an error is printed to stderr and an 6430** error code returned. Otherwise, if all specified arguments are present 6431** in the archive, SQLITE_OK is returned. Here, "present" means either an 6432** exact equality when pAr->bGlob is false or a "name GLOB pattern" match 6433** when pAr->bGlob is true. 6434** 6435** This function strips any trailing '/' characters from each argument. 6436** This is consistent with the way the [tar] command seems to work on 6437** Linux. 6438*/ 6439static int arCheckEntries(ArCommand *pAr){ 6440 int rc = SQLITE_OK; 6441 if( pAr->nArg ){ 6442 int i, j; 6443 sqlite3_stmt *pTest = 0; 6444 const char *zSel = (pAr->bGlob) 6445 ? "SELECT name FROM %s WHERE glob($name,name)" 6446 : "SELECT name FROM %s WHERE name=$name"; 6447 6448 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); 6449 j = sqlite3_bind_parameter_index(pTest, "$name"); 6450 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6451 char *z = pAr->azArg[i]; 6452 int n = strlen30(z); 6453 int bOk = 0; 6454 while( n>0 && z[n-1]=='/' ) n--; 6455 z[n] = '\0'; 6456 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 6457 if( SQLITE_ROW==sqlite3_step(pTest) ){ 6458 bOk = 1; 6459 } 6460 shellReset(&rc, pTest); 6461 if( rc==SQLITE_OK && bOk==0 ){ 6462 utf8_printf(stderr, "not found in archive: %s\n", z); 6463 rc = SQLITE_ERROR; 6464 } 6465 } 6466 shellFinalize(&rc, pTest); 6467 } 6468 return rc; 6469} 6470 6471/* 6472** Format a WHERE clause that can be used against the "sqlar" table to 6473** identify all archive members that match the command arguments held 6474** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 6475** The caller is responsible for eventually calling sqlite3_free() on 6476** any non-NULL (*pzWhere) value. Here, "match" means strict equality 6477** when pAr->bGlob is false and GLOB match when pAr->bGlob is true. 6478*/ 6479static void arWhereClause( 6480 int *pRc, 6481 ArCommand *pAr, 6482 char **pzWhere /* OUT: New WHERE clause */ 6483){ 6484 char *zWhere = 0; 6485 const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; 6486 if( *pRc==SQLITE_OK ){ 6487 if( pAr->nArg==0 ){ 6488 zWhere = sqlite3_mprintf("1"); 6489 }else{ 6490 int i; 6491 const char *zSep = ""; 6492 for(i=0; i<pAr->nArg; i++){ 6493 const char *z = pAr->azArg[i]; 6494 zWhere = sqlite3_mprintf( 6495 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'", 6496 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z 6497 ); 6498 if( zWhere==0 ){ 6499 *pRc = SQLITE_NOMEM; 6500 break; 6501 } 6502 zSep = " OR "; 6503 } 6504 } 6505 } 6506 *pzWhere = zWhere; 6507} 6508 6509/* 6510** Implementation of .ar "lisT" command. 6511*/ 6512static int arListCommand(ArCommand *pAr){ 6513 const char *zSql = "SELECT %s FROM %s WHERE %s"; 6514 const char *azCols[] = { 6515 "name", 6516 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 6517 }; 6518 6519 char *zWhere = 0; 6520 sqlite3_stmt *pSql = 0; 6521 int rc; 6522 6523 rc = arCheckEntries(pAr); 6524 arWhereClause(&rc, pAr, &zWhere); 6525 6526 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 6527 pAr->zSrcTable, zWhere); 6528 if( pAr->bDryRun ){ 6529 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6530 }else{ 6531 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6532 if( pAr->bVerbose ){ 6533 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 6534 sqlite3_column_text(pSql, 0), 6535 sqlite3_column_int(pSql, 1), 6536 sqlite3_column_text(pSql, 2), 6537 sqlite3_column_text(pSql, 3) 6538 ); 6539 }else{ 6540 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6541 } 6542 } 6543 } 6544 shellFinalize(&rc, pSql); 6545 sqlite3_free(zWhere); 6546 return rc; 6547} 6548 6549 6550/* 6551** Implementation of .ar "Remove" command. 6552*/ 6553static int arRemoveCommand(ArCommand *pAr){ 6554 int rc = 0; 6555 char *zSql = 0; 6556 char *zWhere = 0; 6557 6558 if( pAr->nArg ){ 6559 /* Verify that args actually exist within the archive before proceeding. 6560 ** And formulate a WHERE clause to match them. */ 6561 rc = arCheckEntries(pAr); 6562 arWhereClause(&rc, pAr, &zWhere); 6563 } 6564 if( rc==SQLITE_OK ){ 6565 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;", 6566 pAr->zSrcTable, zWhere); 6567 if( pAr->bDryRun ){ 6568 utf8_printf(pAr->p->out, "%s\n", zSql); 6569 }else{ 6570 char *zErr = 0; 6571 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); 6572 if( rc==SQLITE_OK ){ 6573 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6574 if( rc!=SQLITE_OK ){ 6575 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6576 }else{ 6577 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); 6578 } 6579 } 6580 if( zErr ){ 6581 utf8_printf(stdout, "ERROR: %s\n", zErr); 6582 sqlite3_free(zErr); 6583 } 6584 } 6585 } 6586 sqlite3_free(zWhere); 6587 sqlite3_free(zSql); 6588 return rc; 6589} 6590 6591/* 6592** Implementation of .ar "eXtract" command. 6593*/ 6594static int arExtractCommand(ArCommand *pAr){ 6595 const char *zSql1 = 6596 "SELECT " 6597 " ($dir || name)," 6598 " writefile(($dir || name), %s, mode, mtime) " 6599 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 6600 " AND name NOT GLOB '*..[/\\]*'"; 6601 6602 const char *azExtraArg[] = { 6603 "sqlar_uncompress(data, sz)", 6604 "data" 6605 }; 6606 6607 sqlite3_stmt *pSql = 0; 6608 int rc = SQLITE_OK; 6609 char *zDir = 0; 6610 char *zWhere = 0; 6611 int i, j; 6612 6613 /* If arguments are specified, check that they actually exist within 6614 ** the archive before proceeding. And formulate a WHERE clause to 6615 ** match them. */ 6616 rc = arCheckEntries(pAr); 6617 arWhereClause(&rc, pAr, &zWhere); 6618 6619 if( rc==SQLITE_OK ){ 6620 if( pAr->zDir ){ 6621 zDir = sqlite3_mprintf("%s/", pAr->zDir); 6622 }else{ 6623 zDir = sqlite3_mprintf(""); 6624 } 6625 if( zDir==0 ) rc = SQLITE_NOMEM; 6626 } 6627 6628 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 6629 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 6630 ); 6631 6632 if( rc==SQLITE_OK ){ 6633 j = sqlite3_bind_parameter_index(pSql, "$dir"); 6634 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 6635 6636 /* Run the SELECT statement twice. The first time, writefile() is called 6637 ** for all archive members that should be extracted. The second time, 6638 ** only for the directories. This is because the timestamps for 6639 ** extracted directories must be reset after they are populated (as 6640 ** populating them changes the timestamp). */ 6641 for(i=0; i<2; i++){ 6642 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 6643 sqlite3_bind_int(pSql, j, i); 6644 if( pAr->bDryRun ){ 6645 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6646 }else{ 6647 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6648 if( i==0 && pAr->bVerbose ){ 6649 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6650 } 6651 } 6652 } 6653 shellReset(&rc, pSql); 6654 } 6655 shellFinalize(&rc, pSql); 6656 } 6657 6658 sqlite3_free(zDir); 6659 sqlite3_free(zWhere); 6660 return rc; 6661} 6662 6663/* 6664** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 6665*/ 6666static int arExecSql(ArCommand *pAr, const char *zSql){ 6667 int rc; 6668 if( pAr->bDryRun ){ 6669 utf8_printf(pAr->p->out, "%s\n", zSql); 6670 rc = SQLITE_OK; 6671 }else{ 6672 char *zErr = 0; 6673 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6674 if( zErr ){ 6675 utf8_printf(stdout, "ERROR: %s\n", zErr); 6676 sqlite3_free(zErr); 6677 } 6678 } 6679 return rc; 6680} 6681 6682 6683/* 6684** Implementation of .ar "create", "insert", and "update" commands. 6685** 6686** create -> Create a new SQL archive 6687** insert -> Insert or reinsert all files listed 6688** update -> Insert files that have changed or that were not 6689** previously in the archive 6690** 6691** Create the "sqlar" table in the database if it does not already exist. 6692** Then add each file in the azFile[] array to the archive. Directories 6693** are added recursively. If argument bVerbose is non-zero, a message is 6694** printed on stdout for each file archived. 6695** 6696** The create command is the same as update, except that it drops 6697** any existing "sqlar" table before beginning. The "insert" command 6698** always overwrites every file named on the command-line, where as 6699** "update" only overwrites if the size or mtime or mode has changed. 6700*/ 6701static int arCreateOrUpdateCommand( 6702 ArCommand *pAr, /* Command arguments and options */ 6703 int bUpdate, /* true for a --create. */ 6704 int bOnlyIfChanged /* Only update if file has changed */ 6705){ 6706 const char *zCreate = 6707 "CREATE TABLE IF NOT EXISTS sqlar(\n" 6708 " name TEXT PRIMARY KEY, -- name of the file\n" 6709 " mode INT, -- access permissions\n" 6710 " mtime INT, -- last modification time\n" 6711 " sz INT, -- original file size\n" 6712 " data BLOB -- compressed content\n" 6713 ")"; 6714 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 6715 const char *zInsertFmt[2] = { 6716 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 6717 " SELECT\n" 6718 " %s,\n" 6719 " mode,\n" 6720 " mtime,\n" 6721 " CASE substr(lsmode(mode),1,1)\n" 6722 " WHEN '-' THEN length(data)\n" 6723 " WHEN 'd' THEN 0\n" 6724 " ELSE -1 END,\n" 6725 " sqlar_compress(data)\n" 6726 " FROM fsdir(%Q,%Q) AS disk\n" 6727 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6728 , 6729 "REPLACE INTO %s(name,mode,mtime,data)\n" 6730 " SELECT\n" 6731 " %s,\n" 6732 " mode,\n" 6733 " mtime,\n" 6734 " data\n" 6735 " FROM fsdir(%Q,%Q) AS disk\n" 6736 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6737 }; 6738 int i; /* For iterating through azFile[] */ 6739 int rc; /* Return code */ 6740 const char *zTab = 0; /* SQL table into which to insert */ 6741 char *zSql; 6742 char zTemp[50]; 6743 char *zExists = 0; 6744 6745 arExecSql(pAr, "PRAGMA page_size=512"); 6746 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6747 if( rc!=SQLITE_OK ) return rc; 6748 zTemp[0] = 0; 6749 if( pAr->bZip ){ 6750 /* Initialize the zipfile virtual table, if necessary */ 6751 if( pAr->zFile ){ 6752 sqlite3_uint64 r; 6753 sqlite3_randomness(sizeof(r),&r); 6754 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6755 zTab = zTemp; 6756 zSql = sqlite3_mprintf( 6757 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6758 zTab, pAr->zFile 6759 ); 6760 rc = arExecSql(pAr, zSql); 6761 sqlite3_free(zSql); 6762 }else{ 6763 zTab = "zip"; 6764 } 6765 }else{ 6766 /* Initialize the table for an SQLAR */ 6767 zTab = "sqlar"; 6768 if( bUpdate==0 ){ 6769 rc = arExecSql(pAr, zDrop); 6770 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6771 } 6772 rc = arExecSql(pAr, zCreate); 6773 } 6774 if( bOnlyIfChanged ){ 6775 zExists = sqlite3_mprintf( 6776 " AND NOT EXISTS(" 6777 "SELECT 1 FROM %s AS mem" 6778 " WHERE mem.name=disk.name" 6779 " AND mem.mtime=disk.mtime" 6780 " AND mem.mode=disk.mode)", zTab); 6781 }else{ 6782 zExists = sqlite3_mprintf(""); 6783 } 6784 if( zExists==0 ) rc = SQLITE_NOMEM; 6785 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6786 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6787 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6788 pAr->azArg[i], pAr->zDir, zExists); 6789 rc = arExecSql(pAr, zSql2); 6790 sqlite3_free(zSql2); 6791 } 6792end_ar_transaction: 6793 if( rc!=SQLITE_OK ){ 6794 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6795 }else{ 6796 rc = arExecSql(pAr, "RELEASE ar;"); 6797 if( pAr->bZip && pAr->zFile ){ 6798 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6799 arExecSql(pAr, zSql); 6800 sqlite3_free(zSql); 6801 } 6802 } 6803 sqlite3_free(zExists); 6804 return rc; 6805} 6806 6807/* 6808** Implementation of ".ar" dot command. 6809*/ 6810static int arDotCommand( 6811 ShellState *pState, /* Current shell tool state */ 6812 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6813 char **azArg, /* Array of arguments passed to dot command */ 6814 int nArg /* Number of entries in azArg[] */ 6815){ 6816 ArCommand cmd; 6817 int rc; 6818 memset(&cmd, 0, sizeof(cmd)); 6819 cmd.fromCmdLine = fromCmdLine; 6820 rc = arParseCommand(azArg, nArg, &cmd); 6821 if( rc==SQLITE_OK ){ 6822 int eDbType = SHELL_OPEN_UNSPEC; 6823 cmd.p = pState; 6824 cmd.db = pState->db; 6825 if( cmd.zFile ){ 6826 eDbType = deduceDatabaseType(cmd.zFile, 1); 6827 }else{ 6828 eDbType = pState->openMode; 6829 } 6830 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6831 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6832 if( cmd.zFile==0 ){ 6833 cmd.zSrcTable = sqlite3_mprintf("zip"); 6834 }else{ 6835 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6836 } 6837 } 6838 cmd.bZip = 1; 6839 }else if( cmd.zFile ){ 6840 int flags; 6841 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6842 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6843 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){ 6844 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6845 }else{ 6846 flags = SQLITE_OPEN_READONLY; 6847 } 6848 cmd.db = 0; 6849 if( cmd.bDryRun ){ 6850 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6851 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6852 } 6853 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6854 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6855 if( rc!=SQLITE_OK ){ 6856 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6857 cmd.zFile, sqlite3_errmsg(cmd.db) 6858 ); 6859 goto end_ar_command; 6860 } 6861 sqlite3_fileio_init(cmd.db, 0, 0); 6862 sqlite3_sqlar_init(cmd.db, 0, 0); 6863 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6864 shellPutsFunc, 0, 0); 6865 6866 } 6867 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6868 if( cmd.eCmd!=AR_CMD_CREATE 6869 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6870 ){ 6871 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6872 rc = SQLITE_ERROR; 6873 goto end_ar_command; 6874 } 6875 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6876 } 6877 6878 switch( cmd.eCmd ){ 6879 case AR_CMD_CREATE: 6880 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6881 break; 6882 6883 case AR_CMD_EXTRACT: 6884 rc = arExtractCommand(&cmd); 6885 break; 6886 6887 case AR_CMD_LIST: 6888 rc = arListCommand(&cmd); 6889 break; 6890 6891 case AR_CMD_HELP: 6892 arUsage(pState->out); 6893 break; 6894 6895 case AR_CMD_INSERT: 6896 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6897 break; 6898 6899 case AR_CMD_REMOVE: 6900 rc = arRemoveCommand(&cmd); 6901 break; 6902 6903 default: 6904 assert( cmd.eCmd==AR_CMD_UPDATE ); 6905 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6906 break; 6907 } 6908 } 6909end_ar_command: 6910 if( cmd.db!=pState->db ){ 6911 close_db(cmd.db); 6912 } 6913 sqlite3_free(cmd.zSrcTable); 6914 6915 return rc; 6916} 6917/* End of the ".archive" or ".ar" command logic 6918*******************************************************************************/ 6919#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6920 6921#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6922/* 6923** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6924** Otherwise, the SQL statement or statements in zSql are executed using 6925** database connection db and the error code written to *pRc before 6926** this function returns. 6927*/ 6928static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6929 int rc = *pRc; 6930 if( rc==SQLITE_OK ){ 6931 char *zErr = 0; 6932 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6933 if( rc!=SQLITE_OK ){ 6934 raw_printf(stderr, "SQL error: %s\n", zErr); 6935 } 6936 sqlite3_free(zErr); 6937 *pRc = rc; 6938 } 6939} 6940 6941/* 6942** Like shellExec(), except that zFmt is a printf() style format string. 6943*/ 6944static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6945 char *z = 0; 6946 if( *pRc==SQLITE_OK ){ 6947 va_list ap; 6948 va_start(ap, zFmt); 6949 z = sqlite3_vmprintf(zFmt, ap); 6950 va_end(ap); 6951 if( z==0 ){ 6952 *pRc = SQLITE_NOMEM; 6953 }else{ 6954 shellExec(db, pRc, z); 6955 } 6956 sqlite3_free(z); 6957 } 6958} 6959 6960/* 6961** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6962** Otherwise, an attempt is made to allocate, zero and return a pointer 6963** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6964** to SQLITE_NOMEM and NULL returned. 6965*/ 6966static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6967 void *pRet = 0; 6968 if( *pRc==SQLITE_OK ){ 6969 pRet = sqlite3_malloc64(nByte); 6970 if( pRet==0 ){ 6971 *pRc = SQLITE_NOMEM; 6972 }else{ 6973 memset(pRet, 0, nByte); 6974 } 6975 } 6976 return pRet; 6977} 6978 6979/* 6980** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6981** Otherwise, zFmt is treated as a printf() style string. The result of 6982** formatting it along with any trailing arguments is written into a 6983** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6984** It is the responsibility of the caller to eventually free this buffer 6985** using a call to sqlite3_free(). 6986** 6987** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6988** pointer returned. 6989*/ 6990static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6991 char *z = 0; 6992 if( *pRc==SQLITE_OK ){ 6993 va_list ap; 6994 va_start(ap, zFmt); 6995 z = sqlite3_vmprintf(zFmt, ap); 6996 va_end(ap); 6997 if( z==0 ){ 6998 *pRc = SQLITE_NOMEM; 6999 } 7000 } 7001 return z; 7002} 7003 7004/* 7005** When running the ".recover" command, each output table, and the special 7006** orphaned row table if it is required, is represented by an instance 7007** of the following struct. 7008*/ 7009typedef struct RecoverTable RecoverTable; 7010struct RecoverTable { 7011 char *zQuoted; /* Quoted version of table name */ 7012 int nCol; /* Number of columns in table */ 7013 char **azlCol; /* Array of column lists */ 7014 int iPk; /* Index of IPK column */ 7015}; 7016 7017/* 7018** Free a RecoverTable object allocated by recoverFindTable() or 7019** recoverOrphanTable(). 7020*/ 7021static void recoverFreeTable(RecoverTable *pTab){ 7022 if( pTab ){ 7023 sqlite3_free(pTab->zQuoted); 7024 if( pTab->azlCol ){ 7025 int i; 7026 for(i=0; i<=pTab->nCol; i++){ 7027 sqlite3_free(pTab->azlCol[i]); 7028 } 7029 sqlite3_free(pTab->azlCol); 7030 } 7031 sqlite3_free(pTab); 7032 } 7033} 7034 7035/* 7036** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 7037** Otherwise, it allocates and returns a RecoverTable object based on the 7038** final four arguments passed to this function. It is the responsibility 7039** of the caller to eventually free the returned object using 7040** recoverFreeTable(). 7041*/ 7042static RecoverTable *recoverNewTable( 7043 int *pRc, /* IN/OUT: Error code */ 7044 const char *zName, /* Name of table */ 7045 const char *zSql, /* CREATE TABLE statement */ 7046 int bIntkey, 7047 int nCol 7048){ 7049 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 7050 int rc = *pRc; 7051 RecoverTable *pTab = 0; 7052 7053 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 7054 if( rc==SQLITE_OK ){ 7055 int nSqlCol = 0; 7056 int bSqlIntkey = 0; 7057 sqlite3_stmt *pStmt = 0; 7058 7059 rc = sqlite3_open("", &dbtmp); 7060 if( rc==SQLITE_OK ){ 7061 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, 7062 shellIdQuote, 0, 0); 7063 } 7064 if( rc==SQLITE_OK ){ 7065 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 7066 } 7067 if( rc==SQLITE_OK ){ 7068 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 7069 if( rc==SQLITE_ERROR ){ 7070 rc = SQLITE_OK; 7071 goto finished; 7072 } 7073 } 7074 shellPreparePrintf(dbtmp, &rc, &pStmt, 7075 "SELECT count(*) FROM pragma_table_info(%Q)", zName 7076 ); 7077 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7078 nSqlCol = sqlite3_column_int(pStmt, 0); 7079 } 7080 shellFinalize(&rc, pStmt); 7081 7082 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 7083 goto finished; 7084 } 7085 7086 shellPreparePrintf(dbtmp, &rc, &pStmt, 7087 "SELECT (" 7088 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 7089 ") FROM sqlite_schema WHERE name = %Q", zName 7090 ); 7091 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7092 bSqlIntkey = sqlite3_column_int(pStmt, 0); 7093 } 7094 shellFinalize(&rc, pStmt); 7095 7096 if( bIntkey==bSqlIntkey ){ 7097 int i; 7098 const char *zPk = "_rowid_"; 7099 sqlite3_stmt *pPkFinder = 0; 7100 7101 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 7102 ** set zPk to the name of the PK column, and pTab->iPk to the index 7103 ** of the column, where columns are 0-numbered from left to right. 7104 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 7105 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 7106 pTab->iPk = -2; 7107 if( bIntkey ){ 7108 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 7109 "SELECT cid, name FROM pragma_table_info(%Q) " 7110 " WHERE pk=1 AND type='integer' COLLATE nocase" 7111 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 7112 , zName, zName 7113 ); 7114 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 7115 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 7116 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 7117 if( zPk==0 ){ zPk = "_"; /* Defensive. Should never happen */ } 7118 } 7119 } 7120 7121 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); 7122 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 7123 pTab->nCol = nSqlCol; 7124 7125 if( bIntkey ){ 7126 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); 7127 }else{ 7128 pTab->azlCol[0] = shellMPrintf(&rc, ""); 7129 } 7130 i = 1; 7131 shellPreparePrintf(dbtmp, &rc, &pStmt, 7132 "SELECT %Q || group_concat(shell_idquote(name), ', ') " 7133 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 7134 "FROM pragma_table_info(%Q)", 7135 bIntkey ? ", " : "", pTab->iPk, 7136 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 7137 zName 7138 ); 7139 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7140 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 7141 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 7142 i++; 7143 } 7144 shellFinalize(&rc, pStmt); 7145 7146 shellFinalize(&rc, pPkFinder); 7147 } 7148 } 7149 7150 finished: 7151 sqlite3_close(dbtmp); 7152 *pRc = rc; 7153 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 7154 recoverFreeTable(pTab); 7155 pTab = 0; 7156 } 7157 return pTab; 7158} 7159 7160/* 7161** This function is called to search the schema recovered from the 7162** sqlite_schema table of the (possibly) corrupt database as part 7163** of a ".recover" command. Specifically, for a table with root page 7164** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 7165** table must be a WITHOUT ROWID table, or if non-zero, not one of 7166** those. 7167** 7168** If a table is found, a (RecoverTable*) object is returned. Or, if 7169** no such table is found, but bIntkey is false and iRoot is the 7170** root page of an index in the recovered schema, then (*pbNoop) is 7171** set to true and NULL returned. Or, if there is no such table or 7172** index, NULL is returned and (*pbNoop) set to 0, indicating that 7173** the caller should write data to the orphans table. 7174*/ 7175static RecoverTable *recoverFindTable( 7176 ShellState *pState, /* Shell state object */ 7177 int *pRc, /* IN/OUT: Error code */ 7178 int iRoot, /* Root page of table */ 7179 int bIntkey, /* True for an intkey table */ 7180 int nCol, /* Number of columns in table */ 7181 int *pbNoop /* OUT: True if iRoot is root of index */ 7182){ 7183 sqlite3_stmt *pStmt = 0; 7184 RecoverTable *pRet = 0; 7185 int bNoop = 0; 7186 const char *zSql = 0; 7187 const char *zName = 0; 7188 7189 /* Search the recovered schema for an object with root page iRoot. */ 7190 shellPreparePrintf(pState->db, pRc, &pStmt, 7191 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 7192 ); 7193 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7194 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 7195 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 7196 bNoop = 1; 7197 break; 7198 } 7199 if( sqlite3_stricmp(zType, "table")==0 ){ 7200 zName = (const char*)sqlite3_column_text(pStmt, 1); 7201 zSql = (const char*)sqlite3_column_text(pStmt, 2); 7202 if( zName!=0 && zSql!=0 ){ 7203 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 7204 break; 7205 } 7206 } 7207 } 7208 7209 shellFinalize(pRc, pStmt); 7210 *pbNoop = bNoop; 7211 return pRet; 7212} 7213 7214/* 7215** Return a RecoverTable object representing the orphans table. 7216*/ 7217static RecoverTable *recoverOrphanTable( 7218 ShellState *pState, /* Shell state object */ 7219 int *pRc, /* IN/OUT: Error code */ 7220 const char *zLostAndFound, /* Base name for orphans table */ 7221 int nCol /* Number of user data columns */ 7222){ 7223 RecoverTable *pTab = 0; 7224 if( nCol>=0 && *pRc==SQLITE_OK ){ 7225 int i; 7226 7227 /* This block determines the name of the orphan table. The prefered 7228 ** name is zLostAndFound. But if that clashes with another name 7229 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 7230 ** and so on until a non-clashing name is found. */ 7231 int iTab = 0; 7232 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 7233 sqlite3_stmt *pTest = 0; 7234 shellPrepare(pState->db, pRc, 7235 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 7236 ); 7237 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 7238 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 7239 shellReset(pRc, pTest); 7240 sqlite3_free(zTab); 7241 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 7242 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 7243 } 7244 shellFinalize(pRc, pTest); 7245 7246 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 7247 if( pTab ){ 7248 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); 7249 pTab->nCol = nCol; 7250 pTab->iPk = -2; 7251 if( nCol>0 ){ 7252 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 7253 if( pTab->azlCol ){ 7254 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 7255 for(i=nCol-1; i>=0; i--){ 7256 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 7257 } 7258 } 7259 } 7260 7261 if( *pRc!=SQLITE_OK ){ 7262 recoverFreeTable(pTab); 7263 pTab = 0; 7264 }else{ 7265 raw_printf(pState->out, 7266 "CREATE TABLE %s(rootpgno INTEGER, " 7267 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 7268 ); 7269 for(i=0; i<nCol; i++){ 7270 raw_printf(pState->out, ", c%d", i); 7271 } 7272 raw_printf(pState->out, ");\n"); 7273 } 7274 } 7275 sqlite3_free(zTab); 7276 } 7277 return pTab; 7278} 7279 7280/* 7281** This function is called to recover data from the database. A script 7282** to construct a new database containing all recovered data is output 7283** on stream pState->out. 7284*/ 7285static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 7286 int rc = SQLITE_OK; 7287 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 7288 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 7289 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 7290 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 7291 const char *zLostAndFound = "lost_and_found"; 7292 int i; 7293 int nOrphan = -1; 7294 RecoverTable *pOrphan = 0; 7295 7296 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 7297 int bRowids = 1; /* 0 if --no-rowids */ 7298 for(i=1; i<nArg; i++){ 7299 char *z = azArg[i]; 7300 int n; 7301 if( z[0]=='-' && z[1]=='-' ) z++; 7302 n = strlen30(z); 7303 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 7304 bFreelist = 0; 7305 }else 7306 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 7307 i++; 7308 zRecoveryDb = azArg[i]; 7309 }else 7310 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 7311 i++; 7312 zLostAndFound = azArg[i]; 7313 }else 7314 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ 7315 bRowids = 0; 7316 } 7317 else{ 7318 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 7319 showHelp(pState->out, azArg[0]); 7320 return 1; 7321 } 7322 } 7323 7324 shellExecPrintf(pState->db, &rc, 7325 /* Attach an in-memory database named 'recovery'. Create an indexed 7326 ** cache of the sqlite_dbptr virtual table. */ 7327 "PRAGMA writable_schema = on;" 7328 "ATTACH %Q AS recovery;" 7329 "DROP TABLE IF EXISTS recovery.dbptr;" 7330 "DROP TABLE IF EXISTS recovery.freelist;" 7331 "DROP TABLE IF EXISTS recovery.map;" 7332 "DROP TABLE IF EXISTS recovery.schema;" 7333 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 7334 ); 7335 7336 if( bFreelist ){ 7337 shellExec(pState->db, &rc, 7338 "WITH trunk(pgno) AS (" 7339 " SELECT shell_int32(" 7340 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 7341 " WHERE x>0" 7342 " UNION" 7343 " SELECT shell_int32(" 7344 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 7345 " FROM trunk WHERE x>0" 7346 ")," 7347 "freelist(data, n, freepgno) AS (" 7348 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 7349 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 7350 " UNION ALL" 7351 " SELECT data, n-1, shell_int32(data, 2+n) " 7352 " FROM freelist WHERE n>=0" 7353 ")" 7354 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 7355 ); 7356 } 7357 7358 /* If this is an auto-vacuum database, add all pointer-map pages to 7359 ** the freelist table. Do this regardless of whether or not 7360 ** --freelist-corrupt was specified. */ 7361 shellExec(pState->db, &rc, 7362 "WITH ptrmap(pgno) AS (" 7363 " SELECT 2 WHERE shell_int32(" 7364 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" 7365 " )" 7366 " UNION ALL " 7367 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " 7368 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" 7369 ")" 7370 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" 7371 ); 7372 7373 shellExec(pState->db, &rc, 7374 "CREATE TABLE recovery.dbptr(" 7375 " pgno, child, PRIMARY KEY(child, pgno)" 7376 ") WITHOUT ROWID;" 7377 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 7378 " SELECT * FROM sqlite_dbptr" 7379 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 7380 7381 /* Delete any pointer to page 1. This ensures that page 1 is considered 7382 ** a root page, regardless of how corrupt the db is. */ 7383 "DELETE FROM recovery.dbptr WHERE child = 1;" 7384 7385 /* Delete all pointers to any pages that have more than one pointer 7386 ** to them. Such pages will be treated as root pages when recovering 7387 ** data. */ 7388 "DELETE FROM recovery.dbptr WHERE child IN (" 7389 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 7390 ");" 7391 7392 /* Create the "map" table that will (eventually) contain instructions 7393 ** for dealing with each page in the db that contains one or more 7394 ** records. */ 7395 "CREATE TABLE recovery.map(" 7396 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 7397 ");" 7398 7399 /* Populate table [map]. If there are circular loops of pages in the 7400 ** database, the following adds all pages in such a loop to the map 7401 ** as individual root pages. This could be handled better. */ 7402 "WITH pages(i, maxlen) AS (" 7403 " SELECT page_count, (" 7404 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 7405 " ) FROM pragma_page_count WHERE page_count>0" 7406 " UNION ALL" 7407 " SELECT i-1, (" 7408 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 7409 " ) FROM pages WHERE i>=2" 7410 ")" 7411 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 7412 " SELECT i, maxlen, NULL, (" 7413 " WITH p(orig, pgno, parent) AS (" 7414 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 7415 " UNION " 7416 " SELECT i, p.parent, " 7417 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 7418 " )" 7419 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 7420 ") " 7421 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;" 7422 "UPDATE recovery.map AS o SET intkey = (" 7423 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 7424 ");" 7425 7426 /* Extract data from page 1 and any linked pages into table 7427 ** recovery.schema. With the same schema as an sqlite_schema table. */ 7428 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 7429 "INSERT INTO recovery.schema SELECT " 7430 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 7431 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 7432 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 7433 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 7434 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 7435 "FROM sqlite_dbdata WHERE pgno IN (" 7436 " SELECT pgno FROM recovery.map WHERE root=1" 7437 ")" 7438 "GROUP BY pgno, cell;" 7439 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 7440 ); 7441 7442 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 7443 ** CREATE TABLE statements that extracted from the existing schema. */ 7444 if( rc==SQLITE_OK ){ 7445 sqlite3_stmt *pStmt = 0; 7446 /* ".recover" might output content in an order which causes immediate 7447 ** foreign key constraints to be violated. So disable foreign-key 7448 ** constraint enforcement to prevent problems when running the output 7449 ** script. */ 7450 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); 7451 raw_printf(pState->out, "BEGIN;\n"); 7452 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 7453 shellPrepare(pState->db, &rc, 7454 "SELECT sql FROM recovery.schema " 7455 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 7456 ); 7457 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7458 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 7459 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 7460 &zCreateTable[12] 7461 ); 7462 } 7463 shellFinalize(&rc, pStmt); 7464 } 7465 7466 /* Figure out if an orphan table will be required. And if so, how many 7467 ** user columns it should contain */ 7468 shellPrepare(pState->db, &rc, 7469 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 7470 , &pLoop 7471 ); 7472 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 7473 nOrphan = sqlite3_column_int(pLoop, 0); 7474 } 7475 shellFinalize(&rc, pLoop); 7476 pLoop = 0; 7477 7478 shellPrepare(pState->db, &rc, 7479 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 7480 ); 7481 7482 shellPrepare(pState->db, &rc, 7483 "SELECT max(field), group_concat(shell_escape_crnl(quote" 7484 "(case when (? AND field<0) then NULL else value end)" 7485 "), ', ')" 7486 ", min(field) " 7487 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 7488 "GROUP BY cell", &pCells 7489 ); 7490 7491 /* Loop through each root page. */ 7492 shellPrepare(pState->db, &rc, 7493 "SELECT root, intkey, max(maxlen) FROM recovery.map" 7494 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 7495 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 7496 ")", &pLoop 7497 ); 7498 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 7499 int iRoot = sqlite3_column_int(pLoop, 0); 7500 int bIntkey = sqlite3_column_int(pLoop, 1); 7501 int nCol = sqlite3_column_int(pLoop, 2); 7502 int bNoop = 0; 7503 RecoverTable *pTab; 7504 7505 assert( bIntkey==0 || bIntkey==1 ); 7506 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 7507 if( bNoop || rc ) continue; 7508 if( pTab==0 ){ 7509 if( pOrphan==0 ){ 7510 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 7511 } 7512 pTab = pOrphan; 7513 if( pTab==0 ) break; 7514 } 7515 7516 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ 7517 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 7518 } 7519 sqlite3_bind_int(pPages, 1, iRoot); 7520 if( bRowids==0 && pTab->iPk<0 ){ 7521 sqlite3_bind_int(pCells, 1, 1); 7522 }else{ 7523 sqlite3_bind_int(pCells, 1, 0); 7524 } 7525 sqlite3_bind_int(pCells, 3, pTab->iPk); 7526 7527 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 7528 int iPgno = sqlite3_column_int(pPages, 0); 7529 sqlite3_bind_int(pCells, 2, iPgno); 7530 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 7531 int nField = sqlite3_column_int(pCells, 0); 7532 int iMin = sqlite3_column_int(pCells, 2); 7533 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 7534 7535 RecoverTable *pTab2 = pTab; 7536 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ 7537 if( pOrphan==0 ){ 7538 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 7539 } 7540 pTab2 = pOrphan; 7541 if( pTab2==0 ) break; 7542 } 7543 7544 nField = nField+1; 7545 if( pTab2==pOrphan ){ 7546 raw_printf(pState->out, 7547 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 7548 pTab2->zQuoted, iRoot, iPgno, nField, 7549 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] 7550 ); 7551 }else{ 7552 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 7553 pTab2->zQuoted, pTab2->azlCol[nField], zVal 7554 ); 7555 } 7556 } 7557 shellReset(&rc, pCells); 7558 } 7559 shellReset(&rc, pPages); 7560 if( pTab!=pOrphan ) recoverFreeTable(pTab); 7561 } 7562 shellFinalize(&rc, pLoop); 7563 shellFinalize(&rc, pPages); 7564 shellFinalize(&rc, pCells); 7565 recoverFreeTable(pOrphan); 7566 7567 /* The rest of the schema */ 7568 if( rc==SQLITE_OK ){ 7569 sqlite3_stmt *pStmt = 0; 7570 shellPrepare(pState->db, &rc, 7571 "SELECT sql, name FROM recovery.schema " 7572 "WHERE sql NOT LIKE 'create table%'", &pStmt 7573 ); 7574 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7575 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 7576 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 7577 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 7578 char *zPrint = shellMPrintf(&rc, 7579 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", 7580 zName, zName, zSql 7581 ); 7582 raw_printf(pState->out, "%s;\n", zPrint); 7583 sqlite3_free(zPrint); 7584 }else{ 7585 raw_printf(pState->out, "%s;\n", zSql); 7586 } 7587 } 7588 shellFinalize(&rc, pStmt); 7589 } 7590 7591 if( rc==SQLITE_OK ){ 7592 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 7593 raw_printf(pState->out, "COMMIT;\n"); 7594 } 7595 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 7596 return rc; 7597} 7598#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7599 7600/* 7601** If an input line begins with "." then invoke this routine to 7602** process that line. 7603** 7604** Return 1 on error, 2 to exit, and 0 otherwise. 7605*/ 7606static int do_meta_command(char *zLine, ShellState *p){ 7607 int h = 1; 7608 int nArg = 0; 7609 int n, c; 7610 int rc = 0; 7611 char *azArg[52]; 7612 7613#ifndef SQLITE_OMIT_VIRTUALTABLE 7614 if( p->expert.pExpert ){ 7615 expertFinish(p, 1, 0); 7616 } 7617#endif 7618 7619 /* Parse the input line into tokens. 7620 */ 7621 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ 7622 while( IsSpace(zLine[h]) ){ h++; } 7623 if( zLine[h]==0 ) break; 7624 if( zLine[h]=='\'' || zLine[h]=='"' ){ 7625 int delim = zLine[h++]; 7626 azArg[nArg++] = &zLine[h]; 7627 while( zLine[h] && zLine[h]!=delim ){ 7628 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 7629 h++; 7630 } 7631 if( zLine[h]==delim ){ 7632 zLine[h++] = 0; 7633 } 7634 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 7635 }else{ 7636 azArg[nArg++] = &zLine[h]; 7637 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 7638 if( zLine[h] ) zLine[h++] = 0; 7639 resolve_backslashes(azArg[nArg-1]); 7640 } 7641 } 7642 azArg[nArg] = 0; 7643 7644 /* Process the input line. 7645 */ 7646 if( nArg==0 ) return 0; /* no tokens, no error */ 7647 n = strlen30(azArg[0]); 7648 c = azArg[0][0]; 7649 clearTempFile(p); 7650 7651#ifndef SQLITE_OMIT_AUTHORIZATION 7652 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 7653 if( nArg!=2 ){ 7654 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 7655 rc = 1; 7656 goto meta_command_exit; 7657 } 7658 open_db(p, 0); 7659 if( booleanValue(azArg[1]) ){ 7660 sqlite3_set_authorizer(p->db, shellAuth, p); 7661 }else if( p->bSafeModePersist ){ 7662 sqlite3_set_authorizer(p->db, safeModeAuth, p); 7663 }else{ 7664 sqlite3_set_authorizer(p->db, 0, 0); 7665 } 7666 }else 7667#endif 7668 7669#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 7670 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 7671 open_db(p, 0); 7672 failIfSafeMode(p, "cannot run .archive in safe mode"); 7673 rc = arDotCommand(p, 0, azArg, nArg); 7674 }else 7675#endif 7676 7677 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 7678 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 7679 ){ 7680 const char *zDestFile = 0; 7681 const char *zDb = 0; 7682 sqlite3 *pDest; 7683 sqlite3_backup *pBackup; 7684 int j; 7685 int bAsync = 0; 7686 const char *zVfs = 0; 7687 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 7688 for(j=1; j<nArg; j++){ 7689 const char *z = azArg[j]; 7690 if( z[0]=='-' ){ 7691 if( z[1]=='-' ) z++; 7692 if( strcmp(z, "-append")==0 ){ 7693 zVfs = "apndvfs"; 7694 }else 7695 if( strcmp(z, "-async")==0 ){ 7696 bAsync = 1; 7697 }else 7698 { 7699 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 7700 return 1; 7701 } 7702 }else if( zDestFile==0 ){ 7703 zDestFile = azArg[j]; 7704 }else if( zDb==0 ){ 7705 zDb = zDestFile; 7706 zDestFile = azArg[j]; 7707 }else{ 7708 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 7709 return 1; 7710 } 7711 } 7712 if( zDestFile==0 ){ 7713 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 7714 return 1; 7715 } 7716 if( zDb==0 ) zDb = "main"; 7717 rc = sqlite3_open_v2(zDestFile, &pDest, 7718 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 7719 if( rc!=SQLITE_OK ){ 7720 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 7721 close_db(pDest); 7722 return 1; 7723 } 7724 if( bAsync ){ 7725 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7726 0, 0, 0); 7727 } 7728 open_db(p, 0); 7729 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7730 if( pBackup==0 ){ 7731 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7732 close_db(pDest); 7733 return 1; 7734 } 7735 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7736 sqlite3_backup_finish(pBackup); 7737 if( rc==SQLITE_DONE ){ 7738 rc = 0; 7739 }else{ 7740 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7741 rc = 1; 7742 } 7743 close_db(pDest); 7744 }else 7745 7746 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 7747 if( nArg==2 ){ 7748 bail_on_error = booleanValue(azArg[1]); 7749 }else{ 7750 raw_printf(stderr, "Usage: .bail on|off\n"); 7751 rc = 1; 7752 } 7753 }else 7754 7755 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 7756 if( nArg==2 ){ 7757 if( booleanValue(azArg[1]) ){ 7758 setBinaryMode(p->out, 1); 7759 }else{ 7760 setTextMode(p->out, 1); 7761 } 7762 }else{ 7763 raw_printf(stderr, "Usage: .binary on|off\n"); 7764 rc = 1; 7765 } 7766 }else 7767 7768 /* The undocumented ".breakpoint" command causes a call to the no-op 7769 ** routine named test_breakpoint(). 7770 */ 7771 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7772 test_breakpoint(); 7773 }else 7774 7775 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 7776 failIfSafeMode(p, "cannot run .cd in safe mode"); 7777 if( nArg==2 ){ 7778#if defined(_WIN32) || defined(WIN32) 7779 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7780 rc = !SetCurrentDirectoryW(z); 7781 sqlite3_free(z); 7782#else 7783 rc = chdir(azArg[1]); 7784#endif 7785 if( rc ){ 7786 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7787 rc = 1; 7788 } 7789 }else{ 7790 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7791 rc = 1; 7792 } 7793 }else 7794 7795 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7796 if( nArg==2 ){ 7797 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7798 }else{ 7799 raw_printf(stderr, "Usage: .changes on|off\n"); 7800 rc = 1; 7801 } 7802 }else 7803 7804 /* Cancel output redirection, if it is currently set (by .testcase) 7805 ** Then read the content of the testcase-out.txt file and compare against 7806 ** azArg[1]. If there are differences, report an error and exit. 7807 */ 7808 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7809 char *zRes = 0; 7810 output_reset(p); 7811 if( nArg!=2 ){ 7812 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7813 rc = 2; 7814 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7815 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7816 rc = 2; 7817 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7818 utf8_printf(stderr, 7819 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7820 p->zTestcase, azArg[1], zRes); 7821 rc = 1; 7822 }else{ 7823 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7824 p->nCheck++; 7825 } 7826 sqlite3_free(zRes); 7827 }else 7828 7829 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7830 failIfSafeMode(p, "cannot run .clone in safe mode"); 7831 if( nArg==2 ){ 7832 tryToClone(p, azArg[1]); 7833 }else{ 7834 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7835 rc = 1; 7836 } 7837 }else 7838 7839 if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){ 7840 if( nArg==1 ){ 7841 /* List available connections */ 7842 int i; 7843 for(i=0; i<ArraySize(p->aAuxDb); i++){ 7844 const char *zFile = p->aAuxDb[i].zDbFilename; 7845 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ 7846 zFile = "(not open)"; 7847 }else if( zFile==0 ){ 7848 zFile = "(memory)"; 7849 }else if( zFile[0]==0 ){ 7850 zFile = "(temporary-file)"; 7851 } 7852 if( p->pAuxDb == &p->aAuxDb[i] ){ 7853 utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile); 7854 }else if( p->aAuxDb[i].db!=0 ){ 7855 utf8_printf(stdout, " %d: %s\n", i, zFile); 7856 } 7857 } 7858 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){ 7859 int i = azArg[1][0] - '0'; 7860 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ 7861 p->pAuxDb->db = p->db; 7862 p->pAuxDb = &p->aAuxDb[i]; 7863 globalDb = p->db = p->pAuxDb->db; 7864 p->pAuxDb->db = 0; 7865 } 7866 }else if( nArg==3 && strcmp(azArg[1], "close")==0 7867 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){ 7868 int i = azArg[2][0] - '0'; 7869 if( i<0 || i>=ArraySize(p->aAuxDb) ){ 7870 /* No-op */ 7871 }else if( p->pAuxDb == &p->aAuxDb[i] ){ 7872 raw_printf(stderr, "cannot close the active database connection\n"); 7873 rc = 1; 7874 }else if( p->aAuxDb[i].db ){ 7875 session_close_all(p, i); 7876 close_db(p->aAuxDb[i].db); 7877 p->aAuxDb[i].db = 0; 7878 } 7879 }else{ 7880 raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n"); 7881 rc = 1; 7882 } 7883 }else 7884 7885 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7886 char **azName = 0; 7887 int nName = 0; 7888 sqlite3_stmt *pStmt; 7889 int i; 7890 open_db(p, 0); 7891 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 7892 if( rc ){ 7893 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7894 rc = 1; 7895 }else{ 7896 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7897 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1); 7898 const char *zFile = (const char*)sqlite3_column_text(pStmt,2); 7899 if( zSchema==0 || zFile==0 ) continue; 7900 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*)); 7901 shell_check_oom(azName); 7902 azName[nName*2] = strdup(zSchema); 7903 azName[nName*2+1] = strdup(zFile); 7904 nName++; 7905 } 7906 } 7907 sqlite3_finalize(pStmt); 7908 for(i=0; i<nName; i++){ 7909 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); 7910 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); 7911 const char *z = azName[i*2+1]; 7912 utf8_printf(p->out, "%s: %s %s%s\n", 7913 azName[i*2], 7914 z && z[0] ? z : "\"\"", 7915 bRdonly ? "r/o" : "r/w", 7916 eTxn==SQLITE_TXN_NONE ? "" : 7917 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); 7918 free(azName[i*2]); 7919 free(azName[i*2+1]); 7920 } 7921 sqlite3_free(azName); 7922 }else 7923 7924 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7925 static const struct DbConfigChoices { 7926 const char *zName; 7927 int op; 7928 } aDbConfig[] = { 7929 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7930 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7931 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7932 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7933 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7934 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7935 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, 7936 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7937 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7938 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, 7939 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7940 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7941 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7942 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7943 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, 7944 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7945 }; 7946 int ii, v; 7947 open_db(p, 0); 7948 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7949 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7950 if( nArg>=3 ){ 7951 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7952 } 7953 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7954 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7955 if( nArg>1 ) break; 7956 } 7957 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7958 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7959 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7960 } 7961 }else 7962 7963 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7964 rc = shell_dbinfo_command(p, nArg, azArg); 7965 }else 7966 7967#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7968 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7969 open_db(p, 0); 7970 rc = recoverDatabaseCmd(p, nArg, azArg); 7971 }else 7972#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7973 7974 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7975 char *zLike = 0; 7976 char *zSql; 7977 int i; 7978 int savedShowHeader = p->showHeader; 7979 int savedShellFlags = p->shellFlgs; 7980 ShellClearFlag(p, 7981 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo 7982 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys); 7983 for(i=1; i<nArg; i++){ 7984 if( azArg[i][0]=='-' ){ 7985 const char *z = azArg[i]+1; 7986 if( z[0]=='-' ) z++; 7987 if( strcmp(z,"preserve-rowids")==0 ){ 7988#ifdef SQLITE_OMIT_VIRTUALTABLE 7989 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7990 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7991 rc = 1; 7992 sqlite3_free(zLike); 7993 goto meta_command_exit; 7994#else 7995 ShellSetFlag(p, SHFLG_PreserveRowid); 7996#endif 7997 }else 7998 if( strcmp(z,"newlines")==0 ){ 7999 ShellSetFlag(p, SHFLG_Newlines); 8000 }else 8001 if( strcmp(z,"data-only")==0 ){ 8002 ShellSetFlag(p, SHFLG_DumpDataOnly); 8003 }else 8004 if( strcmp(z,"nosys")==0 ){ 8005 ShellSetFlag(p, SHFLG_DumpNoSys); 8006 }else 8007 { 8008 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 8009 rc = 1; 8010 sqlite3_free(zLike); 8011 goto meta_command_exit; 8012 } 8013 }else{ 8014 /* azArg[i] contains a LIKE pattern. This ".dump" request should 8015 ** only dump data for tables for which either the table name matches 8016 ** the LIKE pattern, or the table appears to be a shadow table of 8017 ** a virtual table for which the name matches the LIKE pattern. 8018 */ 8019 char *zExpr = sqlite3_mprintf( 8020 "name LIKE %Q ESCAPE '\\' OR EXISTS (" 8021 " SELECT 1 FROM sqlite_schema WHERE " 8022 " name LIKE %Q ESCAPE '\\' AND" 8023 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND" 8024 " substr(o.name, 1, length(name)+1) == (name||'_')" 8025 ")", azArg[i], azArg[i] 8026 ); 8027 8028 if( zLike ){ 8029 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr); 8030 }else{ 8031 zLike = zExpr; 8032 } 8033 } 8034 } 8035 8036 open_db(p, 0); 8037 8038 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8039 /* When playing back a "dump", the content might appear in an order 8040 ** which causes immediate foreign key constraints to be violated. 8041 ** So disable foreign-key constraint enforcement to prevent problems. */ 8042 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 8043 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 8044 } 8045 p->writableSchema = 0; 8046 p->showHeader = 0; 8047 /* Set writable_schema=ON since doing so forces SQLite to initialize 8048 ** as much of the schema as it can even if the sqlite_schema table is 8049 ** corrupt. */ 8050 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 8051 p->nErr = 0; 8052 if( zLike==0 ) zLike = sqlite3_mprintf("true"); 8053 zSql = sqlite3_mprintf( 8054 "SELECT name, type, sql FROM sqlite_schema AS o " 8055 "WHERE (%s) AND type=='table'" 8056 " AND sql NOT NULL" 8057 " ORDER BY tbl_name='sqlite_sequence', rowid", 8058 zLike 8059 ); 8060 run_schema_dump_query(p,zSql); 8061 sqlite3_free(zSql); 8062 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8063 zSql = sqlite3_mprintf( 8064 "SELECT sql FROM sqlite_schema AS o " 8065 "WHERE (%s) AND sql NOT NULL" 8066 " AND type IN ('index','trigger','view')", 8067 zLike 8068 ); 8069 run_table_dump_query(p, zSql); 8070 sqlite3_free(zSql); 8071 } 8072 sqlite3_free(zLike); 8073 if( p->writableSchema ){ 8074 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 8075 p->writableSchema = 0; 8076 } 8077 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 8078 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 8079 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8080 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 8081 } 8082 p->showHeader = savedShowHeader; 8083 p->shellFlgs = savedShellFlags; 8084 }else 8085 8086 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 8087 if( nArg==2 ){ 8088 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 8089 }else{ 8090 raw_printf(stderr, "Usage: .echo on|off\n"); 8091 rc = 1; 8092 } 8093 }else 8094 8095 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 8096 if( nArg==2 ){ 8097 p->autoEQPtest = 0; 8098 if( p->autoEQPtrace ){ 8099 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 8100 p->autoEQPtrace = 0; 8101 } 8102 if( strcmp(azArg[1],"full")==0 ){ 8103 p->autoEQP = AUTOEQP_full; 8104 }else if( strcmp(azArg[1],"trigger")==0 ){ 8105 p->autoEQP = AUTOEQP_trigger; 8106#ifdef SQLITE_DEBUG 8107 }else if( strcmp(azArg[1],"test")==0 ){ 8108 p->autoEQP = AUTOEQP_on; 8109 p->autoEQPtest = 1; 8110 }else if( strcmp(azArg[1],"trace")==0 ){ 8111 p->autoEQP = AUTOEQP_full; 8112 p->autoEQPtrace = 1; 8113 open_db(p, 0); 8114 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); 8115 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 8116#endif 8117 }else{ 8118 p->autoEQP = (u8)booleanValue(azArg[1]); 8119 } 8120 }else{ 8121 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 8122 rc = 1; 8123 } 8124 }else 8125 8126 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 8127 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 8128 rc = 2; 8129 }else 8130 8131 /* The ".explain" command is automatic now. It is largely pointless. It 8132 ** retained purely for backwards compatibility */ 8133 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 8134 int val = 1; 8135 if( nArg>=2 ){ 8136 if( strcmp(azArg[1],"auto")==0 ){ 8137 val = 99; 8138 }else{ 8139 val = booleanValue(azArg[1]); 8140 } 8141 } 8142 if( val==1 && p->mode!=MODE_Explain ){ 8143 p->normalMode = p->mode; 8144 p->mode = MODE_Explain; 8145 p->autoExplain = 0; 8146 }else if( val==0 ){ 8147 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8148 p->autoExplain = 0; 8149 }else if( val==99 ){ 8150 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8151 p->autoExplain = 1; 8152 } 8153 }else 8154 8155#ifndef SQLITE_OMIT_VIRTUALTABLE 8156 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 8157 if( p->bSafeMode ){ 8158 raw_printf(stderr, 8159 "Cannot run experimental commands such as \"%s\" in safe mode\n", 8160 azArg[0]); 8161 rc = 1; 8162 }else{ 8163 open_db(p, 0); 8164 expertDotCommand(p, azArg, nArg); 8165 } 8166 }else 8167#endif 8168 8169 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ 8170 static const struct { 8171 const char *zCtrlName; /* Name of a test-control option */ 8172 int ctrlCode; /* Integer code for that option */ 8173 const char *zUsage; /* Usage notes */ 8174 } aCtrl[] = { 8175 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 8176 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" }, 8177 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 8178 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 8179 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 8180 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 8181 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 8182 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, 8183 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 8184 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 8185 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 8186 }; 8187 int filectrl = -1; 8188 int iCtrl = -1; 8189 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 8190 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 8191 int n2, i; 8192 const char *zCmd = 0; 8193 const char *zSchema = 0; 8194 8195 open_db(p, 0); 8196 zCmd = nArg>=2 ? azArg[1] : "help"; 8197 8198 if( zCmd[0]=='-' 8199 && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0) 8200 && nArg>=4 8201 ){ 8202 zSchema = azArg[2]; 8203 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; 8204 nArg -= 2; 8205 zCmd = azArg[1]; 8206 } 8207 8208 /* The argument can optionally begin with "-" or "--" */ 8209 if( zCmd[0]=='-' && zCmd[1] ){ 8210 zCmd++; 8211 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 8212 } 8213 8214 /* --help lists all file-controls */ 8215 if( strcmp(zCmd,"help")==0 ){ 8216 utf8_printf(p->out, "Available file-controls:\n"); 8217 for(i=0; i<ArraySize(aCtrl); i++){ 8218 utf8_printf(p->out, " .filectrl %s %s\n", 8219 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 8220 } 8221 rc = 1; 8222 goto meta_command_exit; 8223 } 8224 8225 /* convert filectrl text option to value. allow any unique prefix 8226 ** of the option name, or a numerical value. */ 8227 n2 = strlen30(zCmd); 8228 for(i=0; i<ArraySize(aCtrl); i++){ 8229 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 8230 if( filectrl<0 ){ 8231 filectrl = aCtrl[i].ctrlCode; 8232 iCtrl = i; 8233 }else{ 8234 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 8235 "Use \".filectrl --help\" for help\n", zCmd); 8236 rc = 1; 8237 goto meta_command_exit; 8238 } 8239 } 8240 } 8241 if( filectrl<0 ){ 8242 utf8_printf(stderr,"Error: unknown file-control: %s\n" 8243 "Use \".filectrl --help\" for help\n", zCmd); 8244 }else{ 8245 switch(filectrl){ 8246 case SQLITE_FCNTL_SIZE_LIMIT: { 8247 if( nArg!=2 && nArg!=3 ) break; 8248 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 8249 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 8250 isOk = 1; 8251 break; 8252 } 8253 case SQLITE_FCNTL_LOCK_TIMEOUT: 8254 case SQLITE_FCNTL_CHUNK_SIZE: { 8255 int x; 8256 if( nArg!=3 ) break; 8257 x = (int)integerValue(azArg[2]); 8258 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8259 isOk = 2; 8260 break; 8261 } 8262 case SQLITE_FCNTL_PERSIST_WAL: 8263 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 8264 int x; 8265 if( nArg!=2 && nArg!=3 ) break; 8266 x = nArg==3 ? booleanValue(azArg[2]) : -1; 8267 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8268 iRes = x; 8269 isOk = 1; 8270 break; 8271 } 8272 case SQLITE_FCNTL_DATA_VERSION: 8273 case SQLITE_FCNTL_HAS_MOVED: { 8274 int x; 8275 if( nArg!=2 ) break; 8276 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8277 iRes = x; 8278 isOk = 1; 8279 break; 8280 } 8281 case SQLITE_FCNTL_TEMPFILENAME: { 8282 char *z = 0; 8283 if( nArg!=2 ) break; 8284 sqlite3_file_control(p->db, zSchema, filectrl, &z); 8285 if( z ){ 8286 utf8_printf(p->out, "%s\n", z); 8287 sqlite3_free(z); 8288 } 8289 isOk = 2; 8290 break; 8291 } 8292 case SQLITE_FCNTL_RESERVE_BYTES: { 8293 int x; 8294 if( nArg>=3 ){ 8295 x = atoi(azArg[2]); 8296 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8297 } 8298 x = -1; 8299 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8300 utf8_printf(p->out,"%d\n", x); 8301 isOk = 2; 8302 break; 8303 } 8304 } 8305 } 8306 if( isOk==0 && iCtrl>=0 ){ 8307 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 8308 rc = 1; 8309 }else if( isOk==1 ){ 8310 char zBuf[100]; 8311 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 8312 raw_printf(p->out, "%s\n", zBuf); 8313 } 8314 }else 8315 8316 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 8317 ShellState data; 8318 int doStats = 0; 8319 memcpy(&data, p, sizeof(data)); 8320 data.showHeader = 0; 8321 data.cMode = data.mode = MODE_Semi; 8322 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 8323 data.cMode = data.mode = MODE_Pretty; 8324 nArg = 1; 8325 } 8326 if( nArg!=1 ){ 8327 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 8328 rc = 1; 8329 goto meta_command_exit; 8330 } 8331 open_db(p, 0); 8332 rc = sqlite3_exec(p->db, 8333 "SELECT sql FROM" 8334 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 8335 " FROM sqlite_schema UNION ALL" 8336 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " 8337 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 8338 "ORDER BY x", 8339 callback, &data, 0 8340 ); 8341 if( rc==SQLITE_OK ){ 8342 sqlite3_stmt *pStmt; 8343 rc = sqlite3_prepare_v2(p->db, 8344 "SELECT rowid FROM sqlite_schema" 8345 " WHERE name GLOB 'sqlite_stat[134]'", 8346 -1, &pStmt, 0); 8347 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 8348 sqlite3_finalize(pStmt); 8349 } 8350 if( doStats==0 ){ 8351 raw_printf(p->out, "/* No STAT tables available */\n"); 8352 }else{ 8353 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8354 data.cMode = data.mode = MODE_Insert; 8355 data.zDestTable = "sqlite_stat1"; 8356 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0); 8357 data.zDestTable = "sqlite_stat4"; 8358 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0); 8359 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8360 } 8361 }else 8362 8363 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 8364 if( nArg==2 ){ 8365 p->showHeader = booleanValue(azArg[1]); 8366 p->shellFlgs |= SHFLG_HeaderSet; 8367 }else{ 8368 raw_printf(stderr, "Usage: .headers on|off\n"); 8369 rc = 1; 8370 } 8371 }else 8372 8373 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 8374 if( nArg>=2 ){ 8375 n = showHelp(p->out, azArg[1]); 8376 if( n==0 ){ 8377 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 8378 } 8379 }else{ 8380 showHelp(p->out, 0); 8381 } 8382 }else 8383 8384 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 8385 char *zTable = 0; /* Insert data into this table */ 8386 char *zSchema = "main"; /* within this schema */ 8387 char *zFile = 0; /* Name of file to extra content from */ 8388 sqlite3_stmt *pStmt = NULL; /* A statement */ 8389 int nCol; /* Number of columns in the table */ 8390 int nByte; /* Number of bytes in an SQL string */ 8391 int i, j; /* Loop counters */ 8392 int needCommit; /* True to COMMIT or ROLLBACK at end */ 8393 int nSep; /* Number of bytes in p->colSeparator[] */ 8394 char *zSql; /* An SQL statement */ 8395 ImportCtx sCtx; /* Reader context */ 8396 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 8397 int eVerbose = 0; /* Larger for more console output */ 8398 int nSkip = 0; /* Initial lines to skip */ 8399 int useOutputMode = 1; /* Use output mode to determine separators */ 8400 8401 failIfSafeMode(p, "cannot run .import in safe mode"); 8402 memset(&sCtx, 0, sizeof(sCtx)); 8403 sCtx.z = sqlite3_malloc64(120); 8404 if( sCtx.z==0 ){ 8405 import_cleanup(&sCtx); 8406 shell_out_of_memory(); 8407 } 8408 if( p->mode==MODE_Ascii ){ 8409 xRead = ascii_read_one_field; 8410 }else{ 8411 xRead = csv_read_one_field; 8412 } 8413 for(i=1; i<nArg; i++){ 8414 char *z = azArg[i]; 8415 if( z[0]=='-' && z[1]=='-' ) z++; 8416 if( z[0]!='-' ){ 8417 if( zFile==0 ){ 8418 zFile = z; 8419 }else if( zTable==0 ){ 8420 zTable = z; 8421 }else{ 8422 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z); 8423 showHelp(p->out, "import"); 8424 rc = 1; 8425 goto meta_command_exit; 8426 } 8427 }else if( strcmp(z,"-v")==0 ){ 8428 eVerbose++; 8429 }else if( strcmp(z,"-schema")==0 && i<nArg-1 ){ 8430 zSchema = azArg[++i]; 8431 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){ 8432 nSkip = integerValue(azArg[++i]); 8433 }else if( strcmp(z,"-ascii")==0 ){ 8434 sCtx.cColSep = SEP_Unit[0]; 8435 sCtx.cRowSep = SEP_Record[0]; 8436 xRead = ascii_read_one_field; 8437 useOutputMode = 0; 8438 }else if( strcmp(z,"-csv")==0 ){ 8439 sCtx.cColSep = ','; 8440 sCtx.cRowSep = '\n'; 8441 xRead = csv_read_one_field; 8442 useOutputMode = 0; 8443 }else{ 8444 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z); 8445 showHelp(p->out, "import"); 8446 rc = 1; 8447 goto meta_command_exit; 8448 } 8449 } 8450 if( zTable==0 ){ 8451 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n", 8452 zFile==0 ? "FILE" : "TABLE"); 8453 showHelp(p->out, "import"); 8454 rc = 1; 8455 goto meta_command_exit; 8456 } 8457 seenInterrupt = 0; 8458 open_db(p, 0); 8459 if( useOutputMode ){ 8460 /* If neither the --csv or --ascii options are specified, then set 8461 ** the column and row separator characters from the output mode. */ 8462 nSep = strlen30(p->colSeparator); 8463 if( nSep==0 ){ 8464 raw_printf(stderr, 8465 "Error: non-null column separator required for import\n"); 8466 rc = 1; 8467 goto meta_command_exit; 8468 } 8469 if( nSep>1 ){ 8470 raw_printf(stderr, 8471 "Error: multi-character column separators not allowed" 8472 " for import\n"); 8473 rc = 1; 8474 goto meta_command_exit; 8475 } 8476 nSep = strlen30(p->rowSeparator); 8477 if( nSep==0 ){ 8478 raw_printf(stderr, 8479 "Error: non-null row separator required for import\n"); 8480 rc = 1; 8481 goto meta_command_exit; 8482 } 8483 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){ 8484 /* When importing CSV (only), if the row separator is set to the 8485 ** default output row separator, change it to the default input 8486 ** row separator. This avoids having to maintain different input 8487 ** and output row separators. */ 8488 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8489 nSep = strlen30(p->rowSeparator); 8490 } 8491 if( nSep>1 ){ 8492 raw_printf(stderr, "Error: multi-character row separators not allowed" 8493 " for import\n"); 8494 rc = 1; 8495 goto meta_command_exit; 8496 } 8497 sCtx.cColSep = p->colSeparator[0]; 8498 sCtx.cRowSep = p->rowSeparator[0]; 8499 } 8500 sCtx.zFile = zFile; 8501 sCtx.nLine = 1; 8502 if( sCtx.zFile[0]=='|' ){ 8503#ifdef SQLITE_OMIT_POPEN 8504 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8505 rc = 1; 8506 goto meta_command_exit; 8507#else 8508 sCtx.in = popen(sCtx.zFile+1, "r"); 8509 sCtx.zFile = "<pipe>"; 8510 sCtx.xCloser = pclose; 8511#endif 8512 }else{ 8513 sCtx.in = fopen(sCtx.zFile, "rb"); 8514 sCtx.xCloser = fclose; 8515 } 8516 if( sCtx.in==0 ){ 8517 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 8518 rc = 1; 8519 import_cleanup(&sCtx); 8520 goto meta_command_exit; 8521 } 8522 /* Below, resources must be freed before exit. */ 8523 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ 8524 char zSep[2]; 8525 zSep[1] = 0; 8526 zSep[0] = sCtx.cColSep; 8527 utf8_printf(p->out, "Column separator "); 8528 output_c_string(p->out, zSep); 8529 utf8_printf(p->out, ", row separator "); 8530 zSep[0] = sCtx.cRowSep; 8531 output_c_string(p->out, zSep); 8532 utf8_printf(p->out, "\n"); 8533 } 8534 while( (nSkip--)>0 ){ 8535 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} 8536 } 8537 zSql = sqlite3_mprintf("SELECT * FROM \"%w\".\"%w\"", zSchema, zTable); 8538 if( zSql==0 ){ 8539 import_cleanup(&sCtx); 8540 shell_out_of_memory(); 8541 } 8542 nByte = strlen30(zSql); 8543 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8544 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 8545 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 8546 char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\".\"%w\"", 8547 zSchema, zTable); 8548 char cSep = '('; 8549 while( xRead(&sCtx) ){ 8550 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 8551 cSep = ','; 8552 if( sCtx.cTerm!=sCtx.cColSep ) break; 8553 } 8554 if( cSep=='(' ){ 8555 sqlite3_free(zCreate); 8556 import_cleanup(&sCtx); 8557 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 8558 rc = 1; 8559 goto meta_command_exit; 8560 } 8561 zCreate = sqlite3_mprintf("%z\n)", zCreate); 8562 if( eVerbose>=1 ){ 8563 utf8_printf(p->out, "%s\n", zCreate); 8564 } 8565 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 8566 if( rc ){ 8567 utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); 8568 sqlite3_free(zCreate); 8569 import_cleanup(&sCtx); 8570 rc = 1; 8571 goto meta_command_exit; 8572 } 8573 sqlite3_free(zCreate); 8574 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8575 } 8576 sqlite3_free(zSql); 8577 if( rc ){ 8578 if (pStmt) sqlite3_finalize(pStmt); 8579 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 8580 import_cleanup(&sCtx); 8581 rc = 1; 8582 goto meta_command_exit; 8583 } 8584 nCol = sqlite3_column_count(pStmt); 8585 sqlite3_finalize(pStmt); 8586 pStmt = 0; 8587 if( nCol==0 ) return 0; /* no columns, no error */ 8588 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 8589 if( zSql==0 ){ 8590 import_cleanup(&sCtx); 8591 shell_out_of_memory(); 8592 } 8593 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\".\"%w\" VALUES(?", 8594 zSchema, zTable); 8595 j = strlen30(zSql); 8596 for(i=1; i<nCol; i++){ 8597 zSql[j++] = ','; 8598 zSql[j++] = '?'; 8599 } 8600 zSql[j++] = ')'; 8601 zSql[j] = 0; 8602 if( eVerbose>=2 ){ 8603 utf8_printf(p->out, "Insert using: %s\n", zSql); 8604 } 8605 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8606 sqlite3_free(zSql); 8607 if( rc ){ 8608 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8609 if (pStmt) sqlite3_finalize(pStmt); 8610 import_cleanup(&sCtx); 8611 rc = 1; 8612 goto meta_command_exit; 8613 } 8614 needCommit = sqlite3_get_autocommit(p->db); 8615 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 8616 do{ 8617 int startLine = sCtx.nLine; 8618 for(i=0; i<nCol; i++){ 8619 char *z = xRead(&sCtx); 8620 /* 8621 ** Did we reach end-of-file before finding any columns? 8622 ** If so, stop instead of NULL filling the remaining columns. 8623 */ 8624 if( z==0 && i==0 ) break; 8625 /* 8626 ** Did we reach end-of-file OR end-of-line before finding any 8627 ** columns in ASCII mode? If so, stop instead of NULL filling 8628 ** the remaining columns. 8629 */ 8630 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 8631 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 8632 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 8633 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8634 "filling the rest with NULL\n", 8635 sCtx.zFile, startLine, nCol, i+1); 8636 i += 2; 8637 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 8638 } 8639 } 8640 if( sCtx.cTerm==sCtx.cColSep ){ 8641 do{ 8642 xRead(&sCtx); 8643 i++; 8644 }while( sCtx.cTerm==sCtx.cColSep ); 8645 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8646 "extras ignored\n", 8647 sCtx.zFile, startLine, nCol, i); 8648 } 8649 if( i>=nCol ){ 8650 sqlite3_step(pStmt); 8651 rc = sqlite3_reset(pStmt); 8652 if( rc!=SQLITE_OK ){ 8653 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 8654 startLine, sqlite3_errmsg(p->db)); 8655 sCtx.nErr++; 8656 }else{ 8657 sCtx.nRow++; 8658 } 8659 } 8660 }while( sCtx.cTerm!=EOF ); 8661 8662 import_cleanup(&sCtx); 8663 sqlite3_finalize(pStmt); 8664 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 8665 if( eVerbose>0 ){ 8666 utf8_printf(p->out, 8667 "Added %d rows with %d errors using %d lines of input\n", 8668 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); 8669 } 8670 }else 8671 8672#ifndef SQLITE_UNTESTABLE 8673 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 8674 char *zSql; 8675 char *zCollist = 0; 8676 sqlite3_stmt *pStmt; 8677 int tnum = 0; 8678 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ 8679 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ 8680 int i; 8681 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 8682 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 8683 " .imposter off\n"); 8684 /* Also allowed, but not documented: 8685 ** 8686 ** .imposter TABLE IMPOSTER 8687 ** 8688 ** where TABLE is a WITHOUT ROWID table. In that case, the 8689 ** imposter is another WITHOUT ROWID table with the columns in 8690 ** storage order. */ 8691 rc = 1; 8692 goto meta_command_exit; 8693 } 8694 open_db(p, 0); 8695 if( nArg==2 ){ 8696 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 8697 goto meta_command_exit; 8698 } 8699 zSql = sqlite3_mprintf( 8700 "SELECT rootpage, 0 FROM sqlite_schema" 8701 " WHERE name='%q' AND type='index'" 8702 "UNION ALL " 8703 "SELECT rootpage, 1 FROM sqlite_schema" 8704 " WHERE name='%q' AND type='table'" 8705 " AND sql LIKE '%%without%%rowid%%'", 8706 azArg[1], azArg[1] 8707 ); 8708 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8709 sqlite3_free(zSql); 8710 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 8711 tnum = sqlite3_column_int(pStmt, 0); 8712 isWO = sqlite3_column_int(pStmt, 1); 8713 } 8714 sqlite3_finalize(pStmt); 8715 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 8716 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8717 sqlite3_free(zSql); 8718 i = 0; 8719 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8720 char zLabel[20]; 8721 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 8722 i++; 8723 if( zCol==0 ){ 8724 if( sqlite3_column_int(pStmt,1)==-1 ){ 8725 zCol = "_ROWID_"; 8726 }else{ 8727 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 8728 zCol = zLabel; 8729 } 8730 } 8731 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ 8732 lenPK = (int)strlen(zCollist); 8733 } 8734 if( zCollist==0 ){ 8735 zCollist = sqlite3_mprintf("\"%w\"", zCol); 8736 }else{ 8737 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 8738 } 8739 } 8740 sqlite3_finalize(pStmt); 8741 if( i==0 || tnum==0 ){ 8742 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 8743 rc = 1; 8744 sqlite3_free(zCollist); 8745 goto meta_command_exit; 8746 } 8747 if( lenPK==0 ) lenPK = 100000; 8748 zSql = sqlite3_mprintf( 8749 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", 8750 azArg[2], zCollist, lenPK, zCollist); 8751 sqlite3_free(zCollist); 8752 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 8753 if( rc==SQLITE_OK ){ 8754 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 8755 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 8756 if( rc ){ 8757 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 8758 }else{ 8759 utf8_printf(stdout, "%s;\n", zSql); 8760 raw_printf(stdout, 8761 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n", 8762 azArg[1], isWO ? "table" : "index" 8763 ); 8764 } 8765 }else{ 8766 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 8767 rc = 1; 8768 } 8769 sqlite3_free(zSql); 8770 }else 8771#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 8772 8773#ifdef SQLITE_ENABLE_IOTRACE 8774 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 8775 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 8776 if( iotrace && iotrace!=stdout ) fclose(iotrace); 8777 iotrace = 0; 8778 if( nArg<2 ){ 8779 sqlite3IoTrace = 0; 8780 }else if( strcmp(azArg[1], "-")==0 ){ 8781 sqlite3IoTrace = iotracePrintf; 8782 iotrace = stdout; 8783 }else{ 8784 iotrace = fopen(azArg[1], "w"); 8785 if( iotrace==0 ){ 8786 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 8787 sqlite3IoTrace = 0; 8788 rc = 1; 8789 }else{ 8790 sqlite3IoTrace = iotracePrintf; 8791 } 8792 } 8793 }else 8794#endif 8795 8796 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 8797 static const struct { 8798 const char *zLimitName; /* Name of a limit */ 8799 int limitCode; /* Integer code for that limit */ 8800 } aLimit[] = { 8801 { "length", SQLITE_LIMIT_LENGTH }, 8802 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 8803 { "column", SQLITE_LIMIT_COLUMN }, 8804 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 8805 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 8806 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 8807 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 8808 { "attached", SQLITE_LIMIT_ATTACHED }, 8809 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 8810 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 8811 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 8812 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 8813 }; 8814 int i, n2; 8815 open_db(p, 0); 8816 if( nArg==1 ){ 8817 for(i=0; i<ArraySize(aLimit); i++){ 8818 printf("%20s %d\n", aLimit[i].zLimitName, 8819 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 8820 } 8821 }else if( nArg>3 ){ 8822 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 8823 rc = 1; 8824 goto meta_command_exit; 8825 }else{ 8826 int iLimit = -1; 8827 n2 = strlen30(azArg[1]); 8828 for(i=0; i<ArraySize(aLimit); i++){ 8829 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 8830 if( iLimit<0 ){ 8831 iLimit = i; 8832 }else{ 8833 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 8834 rc = 1; 8835 goto meta_command_exit; 8836 } 8837 } 8838 } 8839 if( iLimit<0 ){ 8840 utf8_printf(stderr, "unknown limit: \"%s\"\n" 8841 "enter \".limits\" with no arguments for a list.\n", 8842 azArg[1]); 8843 rc = 1; 8844 goto meta_command_exit; 8845 } 8846 if( nArg==3 ){ 8847 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 8848 (int)integerValue(azArg[2])); 8849 } 8850 printf("%20s %d\n", aLimit[iLimit].zLimitName, 8851 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 8852 } 8853 }else 8854 8855 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 8856 open_db(p, 0); 8857 lintDotCommand(p, azArg, nArg); 8858 }else 8859 8860#ifndef SQLITE_OMIT_LOAD_EXTENSION 8861 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 8862 const char *zFile, *zProc; 8863 char *zErrMsg = 0; 8864 failIfSafeMode(p, "cannot run .load in safe mode"); 8865 if( nArg<2 ){ 8866 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 8867 rc = 1; 8868 goto meta_command_exit; 8869 } 8870 zFile = azArg[1]; 8871 zProc = nArg>=3 ? azArg[2] : 0; 8872 open_db(p, 0); 8873 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 8874 if( rc!=SQLITE_OK ){ 8875 utf8_printf(stderr, "Error: %s\n", zErrMsg); 8876 sqlite3_free(zErrMsg); 8877 rc = 1; 8878 } 8879 }else 8880#endif 8881 8882 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 8883 failIfSafeMode(p, "cannot run .log in safe mode"); 8884 if( nArg!=2 ){ 8885 raw_printf(stderr, "Usage: .log FILENAME\n"); 8886 rc = 1; 8887 }else{ 8888 const char *zFile = azArg[1]; 8889 output_file_close(p->pLog); 8890 p->pLog = output_file_open(zFile, 0); 8891 } 8892 }else 8893 8894 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 8895 const char *zMode = nArg>=2 ? azArg[1] : ""; 8896 int n2 = strlen30(zMode); 8897 int c2 = zMode[0]; 8898 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 8899 p->mode = MODE_Line; 8900 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8901 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 8902 p->mode = MODE_Column; 8903 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ 8904 p->showHeader = 1; 8905 } 8906 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8907 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 8908 p->mode = MODE_List; 8909 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 8910 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8911 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 8912 p->mode = MODE_Html; 8913 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 8914 p->mode = MODE_Tcl; 8915 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 8916 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8917 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 8918 p->mode = MODE_Csv; 8919 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8920 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8921 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 8922 p->mode = MODE_List; 8923 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 8924 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 8925 p->mode = MODE_Insert; 8926 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 8927 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 8928 p->mode = MODE_Quote; 8929 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8930 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8931 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 8932 p->mode = MODE_Ascii; 8933 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 8934 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 8935 }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){ 8936 p->mode = MODE_Markdown; 8937 }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){ 8938 p->mode = MODE_Table; 8939 }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){ 8940 p->mode = MODE_Box; 8941 }else if( c2=='c' && strncmp(azArg[1],"count",n2)==0 ){ 8942 p->mode = MODE_Count; 8943 }else if( c2=='o' && strncmp(azArg[1],"off",n2)==0 ){ 8944 p->mode = MODE_Off; 8945 }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){ 8946 p->mode = MODE_Json; 8947 }else if( nArg==1 ){ 8948 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 8949 }else{ 8950 raw_printf(stderr, "Error: mode should be one of: " 8951 "ascii box column csv html insert json line list markdown " 8952 "quote table tabs tcl\n"); 8953 rc = 1; 8954 } 8955 p->cMode = p->mode; 8956 }else 8957 8958 if( c=='n' && strcmp(azArg[0], "nonce")==0 ){ 8959 if( nArg!=2 ){ 8960 raw_printf(stderr, "Usage: .nonce NONCE\n"); 8961 rc = 1; 8962 }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){ 8963 raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", 8964 p->lineno, azArg[1]); 8965 exit(1); 8966 }else{ 8967 p->bSafeMode = 0; 8968 return 0; /* Return immediately to bypass the safe mode reset 8969 ** at the end of this procedure */ 8970 } 8971 }else 8972 8973 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 8974 if( nArg==2 ){ 8975 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 8976 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 8977 }else{ 8978 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 8979 rc = 1; 8980 } 8981 }else 8982 8983 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 8984 const char *zFN = 0; /* Pointer to constant filename */ 8985 char *zNewFilename = 0; /* Name of the database file to open */ 8986 int iName = 1; /* Index in azArg[] of the filename */ 8987 int newFlag = 0; /* True to delete file before opening */ 8988 int openMode = SHELL_OPEN_UNSPEC; 8989 8990 /* Check for command-line arguments */ 8991 for(iName=1; iName<nArg; iName++){ 8992 const char *z = azArg[iName]; 8993 if( optionMatch(z,"new") ){ 8994 newFlag = 1; 8995#ifdef SQLITE_HAVE_ZLIB 8996 }else if( optionMatch(z, "zip") ){ 8997 openMode = SHELL_OPEN_ZIPFILE; 8998#endif 8999 }else if( optionMatch(z, "append") ){ 9000 openMode = SHELL_OPEN_APPENDVFS; 9001 }else if( optionMatch(z, "readonly") ){ 9002 openMode = SHELL_OPEN_READONLY; 9003 }else if( optionMatch(z, "nofollow") ){ 9004 p->openFlags |= SQLITE_OPEN_NOFOLLOW; 9005#ifndef SQLITE_OMIT_DESERIALIZE 9006 }else if( optionMatch(z, "deserialize") ){ 9007 openMode = SHELL_OPEN_DESERIALIZE; 9008 }else if( optionMatch(z, "hexdb") ){ 9009 openMode = SHELL_OPEN_HEXDB; 9010 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 9011 p->szMax = integerValue(azArg[++iName]); 9012#endif /* SQLITE_OMIT_DESERIALIZE */ 9013 }else if( z[0]=='-' ){ 9014 utf8_printf(stderr, "unknown option: %s\n", z); 9015 rc = 1; 9016 goto meta_command_exit; 9017 }else if( zFN ){ 9018 utf8_printf(stderr, "extra argument: \"%s\"\n", z); 9019 rc = 1; 9020 goto meta_command_exit; 9021 }else{ 9022 zFN = z; 9023 } 9024 } 9025 9026 /* Close the existing database */ 9027 session_close_all(p, -1); 9028 close_db(p->db); 9029 p->db = 0; 9030 p->pAuxDb->zDbFilename = 0; 9031 sqlite3_free(p->pAuxDb->zFreeOnClose); 9032 p->pAuxDb->zFreeOnClose = 0; 9033 p->openMode = openMode; 9034 p->openFlags = 0; 9035 p->szMax = 0; 9036 9037 /* If a filename is specified, try to open it first */ 9038 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ 9039 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); 9040 if( p->bSafeMode 9041 && p->openMode!=SHELL_OPEN_HEXDB 9042 && zFN 9043 && strcmp(zFN,":memory:")!=0 9044 ){ 9045 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); 9046 } 9047 if( zFN ){ 9048 zNewFilename = sqlite3_mprintf("%s", zFN); 9049 shell_check_oom(zNewFilename); 9050 }else{ 9051 zNewFilename = 0; 9052 } 9053 p->pAuxDb->zDbFilename = zNewFilename; 9054 open_db(p, OPEN_DB_KEEPALIVE); 9055 if( p->db==0 ){ 9056 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 9057 sqlite3_free(zNewFilename); 9058 }else{ 9059 p->pAuxDb->zFreeOnClose = zNewFilename; 9060 } 9061 } 9062 if( p->db==0 ){ 9063 /* As a fall-back open a TEMP database */ 9064 p->pAuxDb->zDbFilename = 0; 9065 open_db(p, 0); 9066 } 9067 }else 9068 9069 if( (c=='o' 9070 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 9071 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 9072 ){ 9073 char *zFile = 0; 9074 int bTxtMode = 0; 9075 int i; 9076 int eMode = 0; 9077 int bBOM = 0; 9078 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */ 9079 9080 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 9081 if( c=='e' ){ 9082 eMode = 'x'; 9083 bOnce = 2; 9084 }else if( strncmp(azArg[0],"once",n)==0 ){ 9085 bOnce = 1; 9086 } 9087 for(i=1; i<nArg; i++){ 9088 char *z = azArg[i]; 9089 if( z[0]=='-' ){ 9090 if( z[1]=='-' ) z++; 9091 if( strcmp(z,"-bom")==0 ){ 9092 bBOM = 1; 9093 }else if( c!='e' && strcmp(z,"-x")==0 ){ 9094 eMode = 'x'; /* spreadsheet */ 9095 }else if( c!='e' && strcmp(z,"-e")==0 ){ 9096 eMode = 'e'; /* text editor */ 9097 }else{ 9098 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", 9099 azArg[i]); 9100 showHelp(p->out, azArg[0]); 9101 rc = 1; 9102 goto meta_command_exit; 9103 } 9104 }else if( zFile==0 && eMode!='e' && eMode!='x' ){ 9105 zFile = sqlite3_mprintf("%s", z); 9106 if( zFile && zFile[0]=='|' ){ 9107 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]); 9108 break; 9109 } 9110 }else{ 9111 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n", 9112 azArg[i]); 9113 showHelp(p->out, azArg[0]); 9114 rc = 1; 9115 sqlite3_free(zFile); 9116 goto meta_command_exit; 9117 } 9118 } 9119 if( zFile==0 ){ 9120 zFile = sqlite3_mprintf("stdout"); 9121 } 9122 if( bOnce ){ 9123 p->outCount = 2; 9124 }else{ 9125 p->outCount = 0; 9126 } 9127 output_reset(p); 9128#ifndef SQLITE_NOHAVE_SYSTEM 9129 if( eMode=='e' || eMode=='x' ){ 9130 p->doXdgOpen = 1; 9131 outputModePush(p); 9132 if( eMode=='x' ){ 9133 /* spreadsheet mode. Output as CSV. */ 9134 newTempFile(p, "csv"); 9135 ShellClearFlag(p, SHFLG_Echo); 9136 p->mode = MODE_Csv; 9137 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 9138 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 9139 }else{ 9140 /* text editor mode */ 9141 newTempFile(p, "txt"); 9142 bTxtMode = 1; 9143 } 9144 sqlite3_free(zFile); 9145 zFile = sqlite3_mprintf("%s", p->zTempFile); 9146 } 9147#endif /* SQLITE_NOHAVE_SYSTEM */ 9148 shell_check_oom(zFile); 9149 if( zFile[0]=='|' ){ 9150#ifdef SQLITE_OMIT_POPEN 9151 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9152 rc = 1; 9153 p->out = stdout; 9154#else 9155 p->out = popen(zFile + 1, "w"); 9156 if( p->out==0 ){ 9157 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 9158 p->out = stdout; 9159 rc = 1; 9160 }else{ 9161 if( bBOM ) fprintf(p->out,"\357\273\277"); 9162 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9163 } 9164#endif 9165 }else{ 9166 p->out = output_file_open(zFile, bTxtMode); 9167 if( p->out==0 ){ 9168 if( strcmp(zFile,"off")!=0 ){ 9169 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 9170 } 9171 p->out = stdout; 9172 rc = 1; 9173 } else { 9174 if( bBOM ) fprintf(p->out,"\357\273\277"); 9175 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9176 } 9177 } 9178 sqlite3_free(zFile); 9179 }else 9180 9181 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 9182 open_db(p,0); 9183 if( nArg<=1 ) goto parameter_syntax_error; 9184 9185 /* .parameter clear 9186 ** Clear all bind parameters by dropping the TEMP table that holds them. 9187 */ 9188 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 9189 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 9190 0, 0, 0); 9191 }else 9192 9193 /* .parameter list 9194 ** List all bind parameters. 9195 */ 9196 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 9197 sqlite3_stmt *pStmt = 0; 9198 int rx; 9199 int len = 0; 9200 rx = sqlite3_prepare_v2(p->db, 9201 "SELECT max(length(key)) " 9202 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9203 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9204 len = sqlite3_column_int(pStmt, 0); 9205 if( len>40 ) len = 40; 9206 } 9207 sqlite3_finalize(pStmt); 9208 pStmt = 0; 9209 if( len ){ 9210 rx = sqlite3_prepare_v2(p->db, 9211 "SELECT key, quote(value) " 9212 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9213 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9214 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 9215 sqlite3_column_text(pStmt,1)); 9216 } 9217 sqlite3_finalize(pStmt); 9218 } 9219 }else 9220 9221 /* .parameter init 9222 ** Make sure the TEMP table used to hold bind parameters exists. 9223 ** Create it if necessary. 9224 */ 9225 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 9226 bind_table_init(p); 9227 }else 9228 9229 /* .parameter set NAME VALUE 9230 ** Set or reset a bind parameter. NAME should be the full parameter 9231 ** name exactly as it appears in the query. (ex: $abc, @def). The 9232 ** VALUE can be in either SQL literal notation, or if not it will be 9233 ** understood to be a text string. 9234 */ 9235 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 9236 int rx; 9237 char *zSql; 9238 sqlite3_stmt *pStmt; 9239 const char *zKey = azArg[2]; 9240 const char *zValue = azArg[3]; 9241 bind_table_init(p); 9242 zSql = sqlite3_mprintf( 9243 "REPLACE INTO temp.sqlite_parameters(key,value)" 9244 "VALUES(%Q,%s);", zKey, zValue); 9245 shell_check_oom(zSql); 9246 pStmt = 0; 9247 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9248 sqlite3_free(zSql); 9249 if( rx!=SQLITE_OK ){ 9250 sqlite3_finalize(pStmt); 9251 pStmt = 0; 9252 zSql = sqlite3_mprintf( 9253 "REPLACE INTO temp.sqlite_parameters(key,value)" 9254 "VALUES(%Q,%Q);", zKey, zValue); 9255 shell_check_oom(zSql); 9256 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9257 sqlite3_free(zSql); 9258 if( rx!=SQLITE_OK ){ 9259 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 9260 sqlite3_finalize(pStmt); 9261 pStmt = 0; 9262 rc = 1; 9263 } 9264 } 9265 sqlite3_step(pStmt); 9266 sqlite3_finalize(pStmt); 9267 }else 9268 9269 /* .parameter unset NAME 9270 ** Remove the NAME binding from the parameter binding table, if it 9271 ** exists. 9272 */ 9273 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 9274 char *zSql = sqlite3_mprintf( 9275 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 9276 shell_check_oom(zSql); 9277 sqlite3_exec(p->db, zSql, 0, 0, 0); 9278 sqlite3_free(zSql); 9279 }else 9280 /* If no command name matches, show a syntax error */ 9281 parameter_syntax_error: 9282 showHelp(p->out, "parameter"); 9283 }else 9284 9285 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 9286 int i; 9287 for(i=1; i<nArg; i++){ 9288 if( i>1 ) raw_printf(p->out, " "); 9289 utf8_printf(p->out, "%s", azArg[i]); 9290 } 9291 raw_printf(p->out, "\n"); 9292 }else 9293 9294#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 9295 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 9296 int i; 9297 int nn = 0; 9298 p->flgProgress = 0; 9299 p->mxProgress = 0; 9300 p->nProgress = 0; 9301 for(i=1; i<nArg; i++){ 9302 const char *z = azArg[i]; 9303 if( z[0]=='-' ){ 9304 z++; 9305 if( z[0]=='-' ) z++; 9306 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 9307 p->flgProgress |= SHELL_PROGRESS_QUIET; 9308 continue; 9309 } 9310 if( strcmp(z,"reset")==0 ){ 9311 p->flgProgress |= SHELL_PROGRESS_RESET; 9312 continue; 9313 } 9314 if( strcmp(z,"once")==0 ){ 9315 p->flgProgress |= SHELL_PROGRESS_ONCE; 9316 continue; 9317 } 9318 if( strcmp(z,"limit")==0 ){ 9319 if( i+1>=nArg ){ 9320 utf8_printf(stderr, "Error: missing argument on --limit\n"); 9321 rc = 1; 9322 goto meta_command_exit; 9323 }else{ 9324 p->mxProgress = (int)integerValue(azArg[++i]); 9325 } 9326 continue; 9327 } 9328 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 9329 rc = 1; 9330 goto meta_command_exit; 9331 }else{ 9332 nn = (int)integerValue(z); 9333 } 9334 } 9335 open_db(p, 0); 9336 sqlite3_progress_handler(p->db, nn, progress_handler, p); 9337 }else 9338#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 9339 9340 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 9341 if( nArg >= 2) { 9342 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 9343 } 9344 if( nArg >= 3) { 9345 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 9346 } 9347 }else 9348 9349 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 9350 rc = 2; 9351 }else 9352 9353 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 9354 FILE *inSaved = p->in; 9355 int savedLineno = p->lineno; 9356 failIfSafeMode(p, "cannot run .read in safe mode"); 9357 if( nArg!=2 ){ 9358 raw_printf(stderr, "Usage: .read FILE\n"); 9359 rc = 1; 9360 goto meta_command_exit; 9361 } 9362 if( azArg[1][0]=='|' ){ 9363#ifdef SQLITE_OMIT_POPEN 9364 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9365 rc = 1; 9366 p->out = stdout; 9367#else 9368 p->in = popen(azArg[1]+1, "r"); 9369 if( p->in==0 ){ 9370 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 9371 rc = 1; 9372 }else{ 9373 rc = process_input(p); 9374 pclose(p->in); 9375 } 9376#endif 9377 }else if( (p->in = openChrSource(azArg[1]))==0 ){ 9378 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 9379 rc = 1; 9380 }else{ 9381 rc = process_input(p); 9382 fclose(p->in); 9383 } 9384 p->in = inSaved; 9385 p->lineno = savedLineno; 9386 }else 9387 9388 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 9389 const char *zSrcFile; 9390 const char *zDb; 9391 sqlite3 *pSrc; 9392 sqlite3_backup *pBackup; 9393 int nTimeout = 0; 9394 9395 failIfSafeMode(p, "cannot run .restore in safe mode"); 9396 if( nArg==2 ){ 9397 zSrcFile = azArg[1]; 9398 zDb = "main"; 9399 }else if( nArg==3 ){ 9400 zSrcFile = azArg[2]; 9401 zDb = azArg[1]; 9402 }else{ 9403 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 9404 rc = 1; 9405 goto meta_command_exit; 9406 } 9407 rc = sqlite3_open(zSrcFile, &pSrc); 9408 if( rc!=SQLITE_OK ){ 9409 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 9410 close_db(pSrc); 9411 return 1; 9412 } 9413 open_db(p, 0); 9414 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 9415 if( pBackup==0 ){ 9416 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9417 close_db(pSrc); 9418 return 1; 9419 } 9420 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 9421 || rc==SQLITE_BUSY ){ 9422 if( rc==SQLITE_BUSY ){ 9423 if( nTimeout++ >= 3 ) break; 9424 sqlite3_sleep(100); 9425 } 9426 } 9427 sqlite3_backup_finish(pBackup); 9428 if( rc==SQLITE_DONE ){ 9429 rc = 0; 9430 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 9431 raw_printf(stderr, "Error: source database is busy\n"); 9432 rc = 1; 9433 }else{ 9434 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9435 rc = 1; 9436 } 9437 close_db(pSrc); 9438 }else 9439 9440 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 9441 if( nArg==2 ){ 9442 p->scanstatsOn = (u8)booleanValue(azArg[1]); 9443#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 9444 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 9445#endif 9446 }else{ 9447 raw_printf(stderr, "Usage: .scanstats on|off\n"); 9448 rc = 1; 9449 } 9450 }else 9451 9452 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 9453 ShellText sSelect; 9454 ShellState data; 9455 char *zErrMsg = 0; 9456 const char *zDiv = "("; 9457 const char *zName = 0; 9458 int iSchema = 0; 9459 int bDebug = 0; 9460 int bNoSystemTabs = 0; 9461 int ii; 9462 9463 open_db(p, 0); 9464 memcpy(&data, p, sizeof(data)); 9465 data.showHeader = 0; 9466 data.cMode = data.mode = MODE_Semi; 9467 initText(&sSelect); 9468 for(ii=1; ii<nArg; ii++){ 9469 if( optionMatch(azArg[ii],"indent") ){ 9470 data.cMode = data.mode = MODE_Pretty; 9471 }else if( optionMatch(azArg[ii],"debug") ){ 9472 bDebug = 1; 9473 }else if( optionMatch(azArg[ii],"nosys") ){ 9474 bNoSystemTabs = 1; 9475 }else if( azArg[ii][0]=='-' ){ 9476 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]); 9477 rc = 1; 9478 goto meta_command_exit; 9479 }else if( zName==0 ){ 9480 zName = azArg[ii]; 9481 }else{ 9482 raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); 9483 rc = 1; 9484 goto meta_command_exit; 9485 } 9486 } 9487 if( zName!=0 ){ 9488 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0 9489 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0 9490 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 9491 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0; 9492 if( isSchema ){ 9493 char *new_argv[2], *new_colv[2]; 9494 new_argv[0] = sqlite3_mprintf( 9495 "CREATE TABLE %s (\n" 9496 " type text,\n" 9497 " name text,\n" 9498 " tbl_name text,\n" 9499 " rootpage integer,\n" 9500 " sql text\n" 9501 ")", zName); 9502 shell_check_oom(new_argv[0]); 9503 new_argv[1] = 0; 9504 new_colv[0] = "sql"; 9505 new_colv[1] = 0; 9506 callback(&data, 1, new_argv, new_colv); 9507 sqlite3_free(new_argv[0]); 9508 } 9509 } 9510 if( zDiv ){ 9511 sqlite3_stmt *pStmt = 0; 9512 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 9513 -1, &pStmt, 0); 9514 if( rc ){ 9515 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9516 sqlite3_finalize(pStmt); 9517 rc = 1; 9518 goto meta_command_exit; 9519 } 9520 appendText(&sSelect, "SELECT sql FROM", 0); 9521 iSchema = 0; 9522 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9523 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 9524 char zScNum[30]; 9525 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 9526 appendText(&sSelect, zDiv, 0); 9527 zDiv = " UNION ALL "; 9528 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 9529 if( sqlite3_stricmp(zDb, "main")!=0 ){ 9530 appendText(&sSelect, zDb, '\''); 9531 }else{ 9532 appendText(&sSelect, "NULL", 0); 9533 } 9534 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 9535 appendText(&sSelect, zScNum, 0); 9536 appendText(&sSelect, " AS snum, ", 0); 9537 appendText(&sSelect, zDb, '\''); 9538 appendText(&sSelect, " AS sname FROM ", 0); 9539 appendText(&sSelect, zDb, quoteChar(zDb)); 9540 appendText(&sSelect, ".sqlite_schema", 0); 9541 } 9542 sqlite3_finalize(pStmt); 9543#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 9544 if( zName ){ 9545 appendText(&sSelect, 9546 " UNION ALL SELECT shell_module_schema(name)," 9547 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 9548 0); 9549 } 9550#endif 9551 appendText(&sSelect, ") WHERE ", 0); 9552 if( zName ){ 9553 char *zQarg = sqlite3_mprintf("%Q", zName); 9554 int bGlob; 9555 shell_check_oom(zQarg); 9556 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 9557 strchr(zName, '[') != 0; 9558 if( strchr(zName, '.') ){ 9559 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 9560 }else{ 9561 appendText(&sSelect, "lower(tbl_name)", 0); 9562 } 9563 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 9564 appendText(&sSelect, zQarg, 0); 9565 if( !bGlob ){ 9566 appendText(&sSelect, " ESCAPE '\\' ", 0); 9567 } 9568 appendText(&sSelect, " AND ", 0); 9569 sqlite3_free(zQarg); 9570 } 9571 if( bNoSystemTabs ){ 9572 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0); 9573 } 9574 appendText(&sSelect, "sql IS NOT NULL" 9575 " ORDER BY snum, rowid", 0); 9576 if( bDebug ){ 9577 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 9578 }else{ 9579 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 9580 } 9581 freeText(&sSelect); 9582 } 9583 if( zErrMsg ){ 9584 utf8_printf(stderr,"Error: %s\n", zErrMsg); 9585 sqlite3_free(zErrMsg); 9586 rc = 1; 9587 }else if( rc != SQLITE_OK ){ 9588 raw_printf(stderr,"Error: querying schema information\n"); 9589 rc = 1; 9590 }else{ 9591 rc = 0; 9592 } 9593 }else 9594 9595 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 9596 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 9597 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x); 9598 }else 9599 9600#if defined(SQLITE_ENABLE_SESSION) 9601 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 9602 struct AuxDb *pAuxDb = p->pAuxDb; 9603 OpenSession *pSession = &pAuxDb->aSession[0]; 9604 char **azCmd = &azArg[1]; 9605 int iSes = 0; 9606 int nCmd = nArg - 1; 9607 int i; 9608 if( nArg<=1 ) goto session_syntax_error; 9609 open_db(p, 0); 9610 if( nArg>=3 ){ 9611 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ 9612 if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; 9613 } 9614 if( iSes<pAuxDb->nSession ){ 9615 pSession = &pAuxDb->aSession[iSes]; 9616 azCmd++; 9617 nCmd--; 9618 }else{ 9619 pSession = &pAuxDb->aSession[0]; 9620 iSes = 0; 9621 } 9622 } 9623 9624 /* .session attach TABLE 9625 ** Invoke the sqlite3session_attach() interface to attach a particular 9626 ** table so that it is never filtered. 9627 */ 9628 if( strcmp(azCmd[0],"attach")==0 ){ 9629 if( nCmd!=2 ) goto session_syntax_error; 9630 if( pSession->p==0 ){ 9631 session_not_open: 9632 raw_printf(stderr, "ERROR: No sessions are open\n"); 9633 }else{ 9634 rc = sqlite3session_attach(pSession->p, azCmd[1]); 9635 if( rc ){ 9636 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 9637 rc = 0; 9638 } 9639 } 9640 }else 9641 9642 /* .session changeset FILE 9643 ** .session patchset FILE 9644 ** Write a changeset or patchset into a file. The file is overwritten. 9645 */ 9646 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 9647 FILE *out = 0; 9648 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]); 9649 if( nCmd!=2 ) goto session_syntax_error; 9650 if( pSession->p==0 ) goto session_not_open; 9651 out = fopen(azCmd[1], "wb"); 9652 if( out==0 ){ 9653 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", 9654 azCmd[1]); 9655 }else{ 9656 int szChng; 9657 void *pChng; 9658 if( azCmd[0][0]=='c' ){ 9659 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 9660 }else{ 9661 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 9662 } 9663 if( rc ){ 9664 printf("Error: error code %d\n", rc); 9665 rc = 0; 9666 } 9667 if( pChng 9668 && fwrite(pChng, szChng, 1, out)!=1 ){ 9669 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 9670 szChng); 9671 } 9672 sqlite3_free(pChng); 9673 fclose(out); 9674 } 9675 }else 9676 9677 /* .session close 9678 ** Close the identified session 9679 */ 9680 if( strcmp(azCmd[0], "close")==0 ){ 9681 if( nCmd!=1 ) goto session_syntax_error; 9682 if( pAuxDb->nSession ){ 9683 session_close(pSession); 9684 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; 9685 } 9686 }else 9687 9688 /* .session enable ?BOOLEAN? 9689 ** Query or set the enable flag 9690 */ 9691 if( strcmp(azCmd[0], "enable")==0 ){ 9692 int ii; 9693 if( nCmd>2 ) goto session_syntax_error; 9694 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9695 if( pAuxDb->nSession ){ 9696 ii = sqlite3session_enable(pSession->p, ii); 9697 utf8_printf(p->out, "session %s enable flag = %d\n", 9698 pSession->zName, ii); 9699 } 9700 }else 9701 9702 /* .session filter GLOB .... 9703 ** Set a list of GLOB patterns of table names to be excluded. 9704 */ 9705 if( strcmp(azCmd[0], "filter")==0 ){ 9706 int ii, nByte; 9707 if( nCmd<2 ) goto session_syntax_error; 9708 if( pAuxDb->nSession ){ 9709 for(ii=0; ii<pSession->nFilter; ii++){ 9710 sqlite3_free(pSession->azFilter[ii]); 9711 } 9712 sqlite3_free(pSession->azFilter); 9713 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 9714 pSession->azFilter = sqlite3_malloc( nByte ); 9715 if( pSession->azFilter==0 ){ 9716 raw_printf(stderr, "Error: out or memory\n"); 9717 exit(1); 9718 } 9719 for(ii=1; ii<nCmd; ii++){ 9720 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 9721 shell_check_oom(x); 9722 } 9723 pSession->nFilter = ii-1; 9724 } 9725 }else 9726 9727 /* .session indirect ?BOOLEAN? 9728 ** Query or set the indirect flag 9729 */ 9730 if( strcmp(azCmd[0], "indirect")==0 ){ 9731 int ii; 9732 if( nCmd>2 ) goto session_syntax_error; 9733 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9734 if( pAuxDb->nSession ){ 9735 ii = sqlite3session_indirect(pSession->p, ii); 9736 utf8_printf(p->out, "session %s indirect flag = %d\n", 9737 pSession->zName, ii); 9738 } 9739 }else 9740 9741 /* .session isempty 9742 ** Determine if the session is empty 9743 */ 9744 if( strcmp(azCmd[0], "isempty")==0 ){ 9745 int ii; 9746 if( nCmd!=1 ) goto session_syntax_error; 9747 if( pAuxDb->nSession ){ 9748 ii = sqlite3session_isempty(pSession->p); 9749 utf8_printf(p->out, "session %s isempty flag = %d\n", 9750 pSession->zName, ii); 9751 } 9752 }else 9753 9754 /* .session list 9755 ** List all currently open sessions 9756 */ 9757 if( strcmp(azCmd[0],"list")==0 ){ 9758 for(i=0; i<pAuxDb->nSession; i++){ 9759 utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); 9760 } 9761 }else 9762 9763 /* .session open DB NAME 9764 ** Open a new session called NAME on the attached database DB. 9765 ** DB is normally "main". 9766 */ 9767 if( strcmp(azCmd[0],"open")==0 ){ 9768 char *zName; 9769 if( nCmd!=3 ) goto session_syntax_error; 9770 zName = azCmd[2]; 9771 if( zName[0]==0 ) goto session_syntax_error; 9772 for(i=0; i<pAuxDb->nSession; i++){ 9773 if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ 9774 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 9775 goto meta_command_exit; 9776 } 9777 } 9778 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ 9779 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); 9780 goto meta_command_exit; 9781 } 9782 pSession = &pAuxDb->aSession[pAuxDb->nSession]; 9783 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 9784 if( rc ){ 9785 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 9786 rc = 0; 9787 goto meta_command_exit; 9788 } 9789 pSession->nFilter = 0; 9790 sqlite3session_table_filter(pSession->p, session_filter, pSession); 9791 pAuxDb->nSession++; 9792 pSession->zName = sqlite3_mprintf("%s", zName); 9793 shell_check_oom(pSession->zName); 9794 }else 9795 /* If no command name matches, show a syntax error */ 9796 session_syntax_error: 9797 showHelp(p->out, "session"); 9798 }else 9799#endif 9800 9801#ifdef SQLITE_DEBUG 9802 /* Undocumented commands for internal testing. Subject to change 9803 ** without notice. */ 9804 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 9805 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 9806 int i, v; 9807 for(i=1; i<nArg; i++){ 9808 v = booleanValue(azArg[i]); 9809 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 9810 } 9811 } 9812 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 9813 int i; sqlite3_int64 v; 9814 for(i=1; i<nArg; i++){ 9815 char zBuf[200]; 9816 v = integerValue(azArg[i]); 9817 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 9818 utf8_printf(p->out, "%s", zBuf); 9819 } 9820 } 9821 }else 9822#endif 9823 9824 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 9825 int bIsInit = 0; /* True to initialize the SELFTEST table */ 9826 int bVerbose = 0; /* Verbose output */ 9827 int bSelftestExists; /* True if SELFTEST already exists */ 9828 int i, k; /* Loop counters */ 9829 int nTest = 0; /* Number of tests runs */ 9830 int nErr = 0; /* Number of errors seen */ 9831 ShellText str; /* Answer for a query */ 9832 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 9833 9834 open_db(p,0); 9835 for(i=1; i<nArg; i++){ 9836 const char *z = azArg[i]; 9837 if( z[0]=='-' && z[1]=='-' ) z++; 9838 if( strcmp(z,"-init")==0 ){ 9839 bIsInit = 1; 9840 }else 9841 if( strcmp(z,"-v")==0 ){ 9842 bVerbose++; 9843 }else 9844 { 9845 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9846 azArg[i], azArg[0]); 9847 raw_printf(stderr, "Should be one of: --init -v\n"); 9848 rc = 1; 9849 goto meta_command_exit; 9850 } 9851 } 9852 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 9853 != SQLITE_OK ){ 9854 bSelftestExists = 0; 9855 }else{ 9856 bSelftestExists = 1; 9857 } 9858 if( bIsInit ){ 9859 createSelftestTable(p); 9860 bSelftestExists = 1; 9861 } 9862 initText(&str); 9863 appendText(&str, "x", 0); 9864 for(k=bSelftestExists; k>=0; k--){ 9865 if( k==1 ){ 9866 rc = sqlite3_prepare_v2(p->db, 9867 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 9868 -1, &pStmt, 0); 9869 }else{ 9870 rc = sqlite3_prepare_v2(p->db, 9871 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 9872 " (1,'run','PRAGMA integrity_check','ok')", 9873 -1, &pStmt, 0); 9874 } 9875 if( rc ){ 9876 raw_printf(stderr, "Error querying the selftest table\n"); 9877 rc = 1; 9878 sqlite3_finalize(pStmt); 9879 goto meta_command_exit; 9880 } 9881 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 9882 int tno = sqlite3_column_int(pStmt, 0); 9883 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 9884 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 9885 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 9886 9887 if( zOp==0 ) continue; 9888 if( zSql==0 ) continue; 9889 if( zAns==0 ) continue; 9890 k = 0; 9891 if( bVerbose>0 ){ 9892 printf("%d: %s %s\n", tno, zOp, zSql); 9893 } 9894 if( strcmp(zOp,"memo")==0 ){ 9895 utf8_printf(p->out, "%s\n", zSql); 9896 }else 9897 if( strcmp(zOp,"run")==0 ){ 9898 char *zErrMsg = 0; 9899 str.n = 0; 9900 str.z[0] = 0; 9901 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 9902 nTest++; 9903 if( bVerbose ){ 9904 utf8_printf(p->out, "Result: %s\n", str.z); 9905 } 9906 if( rc || zErrMsg ){ 9907 nErr++; 9908 rc = 1; 9909 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 9910 sqlite3_free(zErrMsg); 9911 }else if( strcmp(zAns,str.z)!=0 ){ 9912 nErr++; 9913 rc = 1; 9914 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 9915 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 9916 } 9917 }else 9918 { 9919 utf8_printf(stderr, 9920 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 9921 rc = 1; 9922 break; 9923 } 9924 } /* End loop over rows of content from SELFTEST */ 9925 sqlite3_finalize(pStmt); 9926 } /* End loop over k */ 9927 freeText(&str); 9928 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 9929 }else 9930 9931 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 9932 if( nArg<2 || nArg>3 ){ 9933 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 9934 rc = 1; 9935 } 9936 if( nArg>=2 ){ 9937 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 9938 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 9939 } 9940 if( nArg>=3 ){ 9941 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 9942 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 9943 } 9944 }else 9945 9946 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 9947 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 9948 int i; /* Loop counter */ 9949 int bSchema = 0; /* Also hash the schema */ 9950 int bSeparate = 0; /* Hash each table separately */ 9951 int iSize = 224; /* Hash algorithm to use */ 9952 int bDebug = 0; /* Only show the query that would have run */ 9953 sqlite3_stmt *pStmt; /* For querying tables names */ 9954 char *zSql; /* SQL to be run */ 9955 char *zSep; /* Separator */ 9956 ShellText sSql; /* Complete SQL for the query to run the hash */ 9957 ShellText sQuery; /* Set of queries used to read all content */ 9958 open_db(p, 0); 9959 for(i=1; i<nArg; i++){ 9960 const char *z = azArg[i]; 9961 if( z[0]=='-' ){ 9962 z++; 9963 if( z[0]=='-' ) z++; 9964 if( strcmp(z,"schema")==0 ){ 9965 bSchema = 1; 9966 }else 9967 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 9968 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 9969 ){ 9970 iSize = atoi(&z[5]); 9971 }else 9972 if( strcmp(z,"debug")==0 ){ 9973 bDebug = 1; 9974 }else 9975 { 9976 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9977 azArg[i], azArg[0]); 9978 showHelp(p->out, azArg[0]); 9979 rc = 1; 9980 goto meta_command_exit; 9981 } 9982 }else if( zLike ){ 9983 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 9984 rc = 1; 9985 goto meta_command_exit; 9986 }else{ 9987 zLike = z; 9988 bSeparate = 1; 9989 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 9990 } 9991 } 9992 if( bSchema ){ 9993 zSql = "SELECT lower(name) FROM sqlite_schema" 9994 " WHERE type='table' AND coalesce(rootpage,0)>1" 9995 " UNION ALL SELECT 'sqlite_schema'" 9996 " ORDER BY 1 collate nocase"; 9997 }else{ 9998 zSql = "SELECT lower(name) FROM sqlite_schema" 9999 " WHERE type='table' AND coalesce(rootpage,0)>1" 10000 " AND name NOT LIKE 'sqlite_%'" 10001 " ORDER BY 1 collate nocase"; 10002 } 10003 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 10004 initText(&sQuery); 10005 initText(&sSql); 10006 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 10007 zSep = "VALUES("; 10008 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 10009 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 10010 if( zTab==0 ) continue; 10011 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 10012 if( strncmp(zTab, "sqlite_",7)!=0 ){ 10013 appendText(&sQuery,"SELECT * FROM ", 0); 10014 appendText(&sQuery,zTab,'"'); 10015 appendText(&sQuery," NOT INDEXED;", 0); 10016 }else if( strcmp(zTab, "sqlite_schema")==0 ){ 10017 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" 10018 " ORDER BY name;", 0); 10019 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 10020 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 10021 " ORDER BY name;", 0); 10022 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 10023 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 10024 " ORDER BY tbl,idx;", 0); 10025 }else if( strcmp(zTab, "sqlite_stat4")==0 ){ 10026 appendText(&sQuery, "SELECT * FROM ", 0); 10027 appendText(&sQuery, zTab, 0); 10028 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 10029 } 10030 appendText(&sSql, zSep, 0); 10031 appendText(&sSql, sQuery.z, '\''); 10032 sQuery.n = 0; 10033 appendText(&sSql, ",", 0); 10034 appendText(&sSql, zTab, '\''); 10035 zSep = "),("; 10036 } 10037 sqlite3_finalize(pStmt); 10038 if( bSeparate ){ 10039 zSql = sqlite3_mprintf( 10040 "%s))" 10041 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 10042 " FROM [sha3sum$query]", 10043 sSql.z, iSize); 10044 }else{ 10045 zSql = sqlite3_mprintf( 10046 "%s))" 10047 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 10048 " FROM [sha3sum$query]", 10049 sSql.z, iSize); 10050 } 10051 shell_check_oom(zSql); 10052 freeText(&sQuery); 10053 freeText(&sSql); 10054 if( bDebug ){ 10055 utf8_printf(p->out, "%s\n", zSql); 10056 }else{ 10057 shell_exec(p, zSql, 0); 10058 } 10059 sqlite3_free(zSql); 10060 }else 10061 10062#ifndef SQLITE_NOHAVE_SYSTEM 10063 if( c=='s' 10064 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 10065 ){ 10066 char *zCmd; 10067 int i, x; 10068 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 10069 if( nArg<2 ){ 10070 raw_printf(stderr, "Usage: .system COMMAND\n"); 10071 rc = 1; 10072 goto meta_command_exit; 10073 } 10074 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 10075 for(i=2; i<nArg && zCmd!=0; i++){ 10076 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 10077 zCmd, azArg[i]); 10078 } 10079 x = zCmd!=0 ? system(zCmd) : 1; 10080 sqlite3_free(zCmd); 10081 if( x ) raw_printf(stderr, "System command returns %d\n", x); 10082 }else 10083#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 10084 10085 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 10086 static const char *azBool[] = { "off", "on", "trigger", "full"}; 10087 const char *zOut; 10088 int i; 10089 if( nArg!=1 ){ 10090 raw_printf(stderr, "Usage: .show\n"); 10091 rc = 1; 10092 goto meta_command_exit; 10093 } 10094 utf8_printf(p->out, "%12.12s: %s\n","echo", 10095 azBool[ShellHasFlag(p, SHFLG_Echo)]); 10096 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 10097 utf8_printf(p->out, "%12.12s: %s\n","explain", 10098 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 10099 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 10100 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 10101 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 10102 output_c_string(p->out, p->nullValue); 10103 raw_printf(p->out, "\n"); 10104 utf8_printf(p->out,"%12.12s: %s\n","output", 10105 strlen30(p->outfile) ? p->outfile : "stdout"); 10106 utf8_printf(p->out,"%12.12s: ", "colseparator"); 10107 output_c_string(p->out, p->colSeparator); 10108 raw_printf(p->out, "\n"); 10109 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 10110 output_c_string(p->out, p->rowSeparator); 10111 raw_printf(p->out, "\n"); 10112 switch( p->statsOn ){ 10113 case 0: zOut = "off"; break; 10114 default: zOut = "on"; break; 10115 case 2: zOut = "stmt"; break; 10116 case 3: zOut = "vmstep"; break; 10117 } 10118 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut); 10119 utf8_printf(p->out, "%12.12s: ", "width"); 10120 for (i=0;i<p->nWidth;i++) { 10121 raw_printf(p->out, "%d ", p->colWidth[i]); 10122 } 10123 raw_printf(p->out, "\n"); 10124 utf8_printf(p->out, "%12.12s: %s\n", "filename", 10125 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); 10126 }else 10127 10128 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 10129 if( nArg==2 ){ 10130 if( strcmp(azArg[1],"stmt")==0 ){ 10131 p->statsOn = 2; 10132 }else if( strcmp(azArg[1],"vmstep")==0 ){ 10133 p->statsOn = 3; 10134 }else{ 10135 p->statsOn = (u8)booleanValue(azArg[1]); 10136 } 10137 }else if( nArg==1 ){ 10138 display_stats(p->db, p, 0); 10139 }else{ 10140 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n"); 10141 rc = 1; 10142 } 10143 }else 10144 10145 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 10146 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 10147 || strncmp(azArg[0], "indexes", n)==0) ) 10148 ){ 10149 sqlite3_stmt *pStmt; 10150 char **azResult; 10151 int nRow, nAlloc; 10152 int ii; 10153 ShellText s; 10154 initText(&s); 10155 open_db(p, 0); 10156 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 10157 if( rc ){ 10158 sqlite3_finalize(pStmt); 10159 return shellDatabaseError(p->db); 10160 } 10161 10162 if( nArg>2 && c=='i' ){ 10163 /* It is an historical accident that the .indexes command shows an error 10164 ** when called with the wrong number of arguments whereas the .tables 10165 ** command does not. */ 10166 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 10167 rc = 1; 10168 sqlite3_finalize(pStmt); 10169 goto meta_command_exit; 10170 } 10171 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 10172 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 10173 if( zDbName==0 ) continue; 10174 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 10175 if( sqlite3_stricmp(zDbName, "main")==0 ){ 10176 appendText(&s, "SELECT name FROM ", 0); 10177 }else{ 10178 appendText(&s, "SELECT ", 0); 10179 appendText(&s, zDbName, '\''); 10180 appendText(&s, "||'.'||name FROM ", 0); 10181 } 10182 appendText(&s, zDbName, '"'); 10183 appendText(&s, ".sqlite_schema ", 0); 10184 if( c=='t' ){ 10185 appendText(&s," WHERE type IN ('table','view')" 10186 " AND name NOT LIKE 'sqlite_%'" 10187 " AND name LIKE ?1", 0); 10188 }else{ 10189 appendText(&s," WHERE type='index'" 10190 " AND tbl_name LIKE ?1", 0); 10191 } 10192 } 10193 rc = sqlite3_finalize(pStmt); 10194 if( rc==SQLITE_OK ){ 10195 appendText(&s, " ORDER BY 1", 0); 10196 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 10197 } 10198 freeText(&s); 10199 if( rc ) return shellDatabaseError(p->db); 10200 10201 /* Run the SQL statement prepared by the above block. Store the results 10202 ** as an array of nul-terminated strings in azResult[]. */ 10203 nRow = nAlloc = 0; 10204 azResult = 0; 10205 if( nArg>1 ){ 10206 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 10207 }else{ 10208 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 10209 } 10210 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 10211 if( nRow>=nAlloc ){ 10212 char **azNew; 10213 int n2 = nAlloc*2 + 10; 10214 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 10215 shell_check_oom(azNew); 10216 nAlloc = n2; 10217 azResult = azNew; 10218 } 10219 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 10220 shell_check_oom(azResult[nRow]); 10221 nRow++; 10222 } 10223 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 10224 rc = shellDatabaseError(p->db); 10225 } 10226 10227 /* Pretty-print the contents of array azResult[] to the output */ 10228 if( rc==0 && nRow>0 ){ 10229 int len, maxlen = 0; 10230 int i, j; 10231 int nPrintCol, nPrintRow; 10232 for(i=0; i<nRow; i++){ 10233 len = strlen30(azResult[i]); 10234 if( len>maxlen ) maxlen = len; 10235 } 10236 nPrintCol = 80/(maxlen+2); 10237 if( nPrintCol<1 ) nPrintCol = 1; 10238 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 10239 for(i=0; i<nPrintRow; i++){ 10240 for(j=i; j<nRow; j+=nPrintRow){ 10241 char *zSp = j<nPrintRow ? "" : " "; 10242 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 10243 azResult[j] ? azResult[j]:""); 10244 } 10245 raw_printf(p->out, "\n"); 10246 } 10247 } 10248 10249 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 10250 sqlite3_free(azResult); 10251 }else 10252 10253 /* Begin redirecting output to the file "testcase-out.txt" */ 10254 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 10255 output_reset(p); 10256 p->out = output_file_open("testcase-out.txt", 0); 10257 if( p->out==0 ){ 10258 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 10259 } 10260 if( nArg>=2 ){ 10261 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 10262 }else{ 10263 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 10264 } 10265 }else 10266 10267#ifndef SQLITE_UNTESTABLE 10268 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 10269 static const struct { 10270 const char *zCtrlName; /* Name of a test-control option */ 10271 int ctrlCode; /* Integer code for that option */ 10272 int unSafe; /* Not valid for --safe mode */ 10273 const char *zUsage; /* Usage notes */ 10274 } aCtrl[] = { 10275 { "always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" }, 10276 { "assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" }, 10277 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/ 10278 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/ 10279 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" }, 10280 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" }, 10281 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/ 10282 { "imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"}, 10283 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" }, 10284 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" }, 10285 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" }, 10286 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" }, 10287#ifdef YYCOVERAGE 10288 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" }, 10289#endif 10290 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " }, 10291 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" }, 10292 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" }, 10293 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" }, 10294 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" }, 10295 { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" }, 10296 { "tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" }, 10297 }; 10298 int testctrl = -1; 10299 int iCtrl = -1; 10300 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 10301 int isOk = 0; 10302 int i, n2; 10303 const char *zCmd = 0; 10304 10305 open_db(p, 0); 10306 zCmd = nArg>=2 ? azArg[1] : "help"; 10307 10308 /* The argument can optionally begin with "-" or "--" */ 10309 if( zCmd[0]=='-' && zCmd[1] ){ 10310 zCmd++; 10311 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 10312 } 10313 10314 /* --help lists all test-controls */ 10315 if( strcmp(zCmd,"help")==0 ){ 10316 utf8_printf(p->out, "Available test-controls:\n"); 10317 for(i=0; i<ArraySize(aCtrl); i++){ 10318 utf8_printf(p->out, " .testctrl %s %s\n", 10319 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 10320 } 10321 rc = 1; 10322 goto meta_command_exit; 10323 } 10324 10325 /* convert testctrl text option to value. allow any unique prefix 10326 ** of the option name, or a numerical value. */ 10327 n2 = strlen30(zCmd); 10328 for(i=0; i<ArraySize(aCtrl); i++){ 10329 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 10330 if( testctrl<0 ){ 10331 testctrl = aCtrl[i].ctrlCode; 10332 iCtrl = i; 10333 }else{ 10334 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 10335 "Use \".testctrl --help\" for help\n", zCmd); 10336 rc = 1; 10337 goto meta_command_exit; 10338 } 10339 } 10340 } 10341 if( testctrl<0 ){ 10342 utf8_printf(stderr,"Error: unknown test-control: %s\n" 10343 "Use \".testctrl --help\" for help\n", zCmd); 10344 }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){ 10345 utf8_printf(stderr, 10346 "line %d: \".testctrl %s\" may not be used in safe mode\n", 10347 p->lineno, aCtrl[iCtrl].zCtrlName); 10348 exit(1); 10349 }else{ 10350 switch(testctrl){ 10351 10352 /* sqlite3_test_control(int, db, int) */ 10353 case SQLITE_TESTCTRL_OPTIMIZATIONS: 10354 if( nArg==3 ){ 10355 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0); 10356 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10357 isOk = 3; 10358 } 10359 break; 10360 10361 /* sqlite3_test_control(int) */ 10362 case SQLITE_TESTCTRL_PRNG_SAVE: 10363 case SQLITE_TESTCTRL_PRNG_RESTORE: 10364 case SQLITE_TESTCTRL_BYTEORDER: 10365 if( nArg==2 ){ 10366 rc2 = sqlite3_test_control(testctrl); 10367 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 10368 } 10369 break; 10370 10371 /* sqlite3_test_control(int, uint) */ 10372 case SQLITE_TESTCTRL_PENDING_BYTE: 10373 if( nArg==3 ){ 10374 unsigned int opt = (unsigned int)integerValue(azArg[2]); 10375 rc2 = sqlite3_test_control(testctrl, opt); 10376 isOk = 3; 10377 } 10378 break; 10379 10380 /* sqlite3_test_control(int, int, sqlite3*) */ 10381 case SQLITE_TESTCTRL_PRNG_SEED: 10382 if( nArg==3 || nArg==4 ){ 10383 int ii = (int)integerValue(azArg[2]); 10384 sqlite3 *db; 10385 if( ii==0 && strcmp(azArg[2],"random")==0 ){ 10386 sqlite3_randomness(sizeof(ii),&ii); 10387 printf("-- random seed: %d\n", ii); 10388 } 10389 if( nArg==3 ){ 10390 db = 0; 10391 }else{ 10392 db = p->db; 10393 /* Make sure the schema has been loaded */ 10394 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 10395 } 10396 rc2 = sqlite3_test_control(testctrl, ii, db); 10397 isOk = 3; 10398 } 10399 break; 10400 10401 /* sqlite3_test_control(int, int) */ 10402 case SQLITE_TESTCTRL_ASSERT: 10403 case SQLITE_TESTCTRL_ALWAYS: 10404 if( nArg==3 ){ 10405 int opt = booleanValue(azArg[2]); 10406 rc2 = sqlite3_test_control(testctrl, opt); 10407 isOk = 1; 10408 } 10409 break; 10410 10411 /* sqlite3_test_control(int, int) */ 10412 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 10413 case SQLITE_TESTCTRL_NEVER_CORRUPT: 10414 if( nArg==3 ){ 10415 int opt = booleanValue(azArg[2]); 10416 rc2 = sqlite3_test_control(testctrl, opt); 10417 isOk = 3; 10418 } 10419 break; 10420 10421 /* sqlite3_test_control(sqlite3*) */ 10422 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 10423 rc2 = sqlite3_test_control(testctrl, p->db); 10424 isOk = 3; 10425 break; 10426 10427 case SQLITE_TESTCTRL_IMPOSTER: 10428 if( nArg==5 ){ 10429 rc2 = sqlite3_test_control(testctrl, p->db, 10430 azArg[2], 10431 integerValue(azArg[3]), 10432 integerValue(azArg[4])); 10433 isOk = 3; 10434 } 10435 break; 10436 10437 case SQLITE_TESTCTRL_SEEK_COUNT: { 10438 u64 x = 0; 10439 rc2 = sqlite3_test_control(testctrl, p->db, &x); 10440 utf8_printf(p->out, "%llu\n", x); 10441 isOk = 3; 10442 break; 10443 } 10444 10445#ifdef YYCOVERAGE 10446 case SQLITE_TESTCTRL_PARSER_COVERAGE: { 10447 if( nArg==2 ){ 10448 sqlite3_test_control(testctrl, p->out); 10449 isOk = 3; 10450 } 10451 break; 10452 } 10453#endif 10454#ifdef SQLITE_DEBUG 10455 case SQLITE_TESTCTRL_TUNE: { 10456 if( nArg==4 ){ 10457 int id = (int)integerValue(azArg[2]); 10458 int val = (int)integerValue(azArg[3]); 10459 sqlite3_test_control(testctrl, id, &val); 10460 isOk = 3; 10461 }else if( nArg==3 ){ 10462 int id = (int)integerValue(azArg[2]); 10463 sqlite3_test_control(testctrl, -id, &rc2); 10464 isOk = 1; 10465 }else if( nArg==2 ){ 10466 int id = 1; 10467 while(1){ 10468 int val = 0; 10469 rc2 = sqlite3_test_control(testctrl, -id, &val); 10470 if( rc2!=SQLITE_OK ) break; 10471 if( id>1 ) utf8_printf(p->out, " "); 10472 utf8_printf(p->out, "%d: %d", id, val); 10473 id++; 10474 } 10475 if( id>1 ) utf8_printf(p->out, "\n"); 10476 isOk = 3; 10477 } 10478 break; 10479 } 10480#endif 10481 case SQLITE_TESTCTRL_SORTER_MMAP: 10482 if( nArg==3 ){ 10483 int opt = (unsigned int)integerValue(azArg[2]); 10484 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10485 isOk = 3; 10486 } 10487 break; 10488 } 10489 } 10490 if( isOk==0 && iCtrl>=0 ){ 10491 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 10492 rc = 1; 10493 }else if( isOk==1 ){ 10494 raw_printf(p->out, "%d\n", rc2); 10495 }else if( isOk==2 ){ 10496 raw_printf(p->out, "0x%08x\n", rc2); 10497 } 10498 }else 10499#endif /* !defined(SQLITE_UNTESTABLE) */ 10500 10501 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 10502 open_db(p, 0); 10503 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 10504 }else 10505 10506 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 10507 if( nArg==2 ){ 10508 enableTimer = booleanValue(azArg[1]); 10509 if( enableTimer && !HAS_TIMER ){ 10510 raw_printf(stderr, "Error: timer not available on this system.\n"); 10511 enableTimer = 0; 10512 } 10513 }else{ 10514 raw_printf(stderr, "Usage: .timer on|off\n"); 10515 rc = 1; 10516 } 10517 }else 10518 10519#ifndef SQLITE_OMIT_TRACE 10520 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 10521 int mType = 0; 10522 int jj; 10523 open_db(p, 0); 10524 for(jj=1; jj<nArg; jj++){ 10525 const char *z = azArg[jj]; 10526 if( z[0]=='-' ){ 10527 if( optionMatch(z, "expanded") ){ 10528 p->eTraceType = SHELL_TRACE_EXPANDED; 10529 } 10530#ifdef SQLITE_ENABLE_NORMALIZE 10531 else if( optionMatch(z, "normalized") ){ 10532 p->eTraceType = SHELL_TRACE_NORMALIZED; 10533 } 10534#endif 10535 else if( optionMatch(z, "plain") ){ 10536 p->eTraceType = SHELL_TRACE_PLAIN; 10537 } 10538 else if( optionMatch(z, "profile") ){ 10539 mType |= SQLITE_TRACE_PROFILE; 10540 } 10541 else if( optionMatch(z, "row") ){ 10542 mType |= SQLITE_TRACE_ROW; 10543 } 10544 else if( optionMatch(z, "stmt") ){ 10545 mType |= SQLITE_TRACE_STMT; 10546 } 10547 else if( optionMatch(z, "close") ){ 10548 mType |= SQLITE_TRACE_CLOSE; 10549 } 10550 else { 10551 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 10552 rc = 1; 10553 goto meta_command_exit; 10554 } 10555 }else{ 10556 output_file_close(p->traceOut); 10557 p->traceOut = output_file_open(azArg[1], 0); 10558 } 10559 } 10560 if( p->traceOut==0 ){ 10561 sqlite3_trace_v2(p->db, 0, 0, 0); 10562 }else{ 10563 if( mType==0 ) mType = SQLITE_TRACE_STMT; 10564 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 10565 } 10566 }else 10567#endif /* !defined(SQLITE_OMIT_TRACE) */ 10568 10569#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) 10570 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){ 10571 int ii; 10572 int lenOpt; 10573 char *zOpt; 10574 if( nArg<2 ){ 10575 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n"); 10576 rc = 1; 10577 goto meta_command_exit; 10578 } 10579 open_db(p, 0); 10580 zOpt = azArg[1]; 10581 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; 10582 lenOpt = (int)strlen(zOpt); 10583 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){ 10584 assert( azArg[nArg]==0 ); 10585 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); 10586 }else{ 10587 for(ii=1; ii<nArg; ii++){ 10588 sqlite3_create_module(p->db, azArg[ii], 0, 0); 10589 } 10590 } 10591 }else 10592#endif 10593 10594#if SQLITE_USER_AUTHENTICATION 10595 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 10596 if( nArg<2 ){ 10597 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 10598 rc = 1; 10599 goto meta_command_exit; 10600 } 10601 open_db(p, 0); 10602 if( strcmp(azArg[1],"login")==0 ){ 10603 if( nArg!=4 ){ 10604 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 10605 rc = 1; 10606 goto meta_command_exit; 10607 } 10608 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], 10609 strlen30(azArg[3])); 10610 if( rc ){ 10611 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 10612 rc = 1; 10613 } 10614 }else if( strcmp(azArg[1],"add")==0 ){ 10615 if( nArg!=5 ){ 10616 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 10617 rc = 1; 10618 goto meta_command_exit; 10619 } 10620 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10621 booleanValue(azArg[4])); 10622 if( rc ){ 10623 raw_printf(stderr, "User-Add failed: %d\n", rc); 10624 rc = 1; 10625 } 10626 }else if( strcmp(azArg[1],"edit")==0 ){ 10627 if( nArg!=5 ){ 10628 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 10629 rc = 1; 10630 goto meta_command_exit; 10631 } 10632 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10633 booleanValue(azArg[4])); 10634 if( rc ){ 10635 raw_printf(stderr, "User-Edit failed: %d\n", rc); 10636 rc = 1; 10637 } 10638 }else if( strcmp(azArg[1],"delete")==0 ){ 10639 if( nArg!=3 ){ 10640 raw_printf(stderr, "Usage: .user delete USER\n"); 10641 rc = 1; 10642 goto meta_command_exit; 10643 } 10644 rc = sqlite3_user_delete(p->db, azArg[2]); 10645 if( rc ){ 10646 raw_printf(stderr, "User-Delete failed: %d\n", rc); 10647 rc = 1; 10648 } 10649 }else{ 10650 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 10651 rc = 1; 10652 goto meta_command_exit; 10653 } 10654 }else 10655#endif /* SQLITE_USER_AUTHENTICATION */ 10656 10657 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 10658 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 10659 sqlite3_libversion(), sqlite3_sourceid()); 10660#if SQLITE_HAVE_ZLIB 10661 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 10662#endif 10663#define CTIMEOPT_VAL_(opt) #opt 10664#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 10665#if defined(__clang__) && defined(__clang_major__) 10666 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 10667 CTIMEOPT_VAL(__clang_minor__) "." 10668 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 10669#elif defined(_MSC_VER) 10670 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 10671#elif defined(__GNUC__) && defined(__VERSION__) 10672 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 10673#endif 10674 }else 10675 10676 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 10677 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10678 sqlite3_vfs *pVfs = 0; 10679 if( p->db ){ 10680 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 10681 if( pVfs ){ 10682 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 10683 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10684 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10685 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10686 } 10687 } 10688 }else 10689 10690 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 10691 sqlite3_vfs *pVfs; 10692 sqlite3_vfs *pCurrent = 0; 10693 if( p->db ){ 10694 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 10695 } 10696 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 10697 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 10698 pVfs==pCurrent ? " <--- CURRENT" : ""); 10699 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10700 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10701 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10702 if( pVfs->pNext ){ 10703 raw_printf(p->out, "-----------------------------------\n"); 10704 } 10705 } 10706 }else 10707 10708 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 10709 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10710 char *zVfsName = 0; 10711 if( p->db ){ 10712 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 10713 if( zVfsName ){ 10714 utf8_printf(p->out, "%s\n", zVfsName); 10715 sqlite3_free(zVfsName); 10716 } 10717 } 10718 }else 10719 10720 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 10721 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 10722 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x); 10723 }else 10724 10725 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 10726 int j; 10727 assert( nArg<=ArraySize(azArg) ); 10728 p->nWidth = nArg-1; 10729 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); 10730 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); 10731 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; 10732 for(j=1; j<nArg; j++){ 10733 p->colWidth[j-1] = (int)integerValue(azArg[j]); 10734 } 10735 }else 10736 10737 { 10738 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 10739 " \"%s\". Enter \".help\" for help\n", azArg[0]); 10740 rc = 1; 10741 } 10742 10743meta_command_exit: 10744 if( p->outCount ){ 10745 p->outCount--; 10746 if( p->outCount==0 ) output_reset(p); 10747 } 10748 p->bSafeMode = p->bSafeModePersist; 10749 return rc; 10750} 10751 10752/* Line scan result and intermediate states (supporting scan resumption) 10753*/ 10754#ifndef CHAR_BIT 10755# define CHAR_BIT 8 10756#endif 10757typedef enum { 10758 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT, 10759 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT, 10760 QSS_Start = 0 10761} QuickScanState; 10762#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask)) 10763#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start) 10764#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start) 10765#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark) 10766#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi) 10767 10768/* 10769** Scan line for classification to guide shell's handling. 10770** The scan is resumable for subsequent lines when prior 10771** return values are passed as the 2nd argument. 10772*/ 10773static QuickScanState quickscan(char *zLine, QuickScanState qss){ 10774 char cin; 10775 char cWait = (char)qss; /* intentional narrowing loss */ 10776 if( cWait==0 ){ 10777 PlainScan: 10778 assert( cWait==0 ); 10779 while( (cin = *zLine++)!=0 ){ 10780 if( IsSpace(cin) ) 10781 continue; 10782 switch (cin){ 10783 case '-': 10784 if( *zLine!='-' ) 10785 break; 10786 while((cin = *++zLine)!=0 ) 10787 if( cin=='\n') 10788 goto PlainScan; 10789 return qss; 10790 case ';': 10791 qss |= QSS_EndingSemi; 10792 continue; 10793 case '/': 10794 if( *zLine=='*' ){ 10795 ++zLine; 10796 cWait = '*'; 10797 qss = QSS_SETV(qss, cWait); 10798 goto TermScan; 10799 } 10800 break; 10801 case '[': 10802 cin = ']'; 10803 /* fall thru */ 10804 case '`': case '\'': case '"': 10805 cWait = cin; 10806 qss = QSS_HasDark | cWait; 10807 goto TermScan; 10808 default: 10809 break; 10810 } 10811 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark; 10812 } 10813 }else{ 10814 TermScan: 10815 while( (cin = *zLine++)!=0 ){ 10816 if( cin==cWait ){ 10817 switch( cWait ){ 10818 case '*': 10819 if( *zLine != '/' ) 10820 continue; 10821 ++zLine; 10822 cWait = 0; 10823 qss = QSS_SETV(qss, 0); 10824 goto PlainScan; 10825 case '`': case '\'': case '"': 10826 if(*zLine==cWait){ 10827 ++zLine; 10828 continue; 10829 } 10830 /* fall thru */ 10831 case ']': 10832 cWait = 0; 10833 qss = QSS_SETV(qss, 0); 10834 goto PlainScan; 10835 default: assert(0); 10836 } 10837 } 10838 } 10839 } 10840 return qss; 10841} 10842 10843/* 10844** Return TRUE if the line typed in is an SQL command terminator other 10845** than a semi-colon. The SQL Server style "go" command is understood 10846** as is the Oracle "/". 10847*/ 10848static int line_is_command_terminator(char *zLine){ 10849 while( IsSpace(zLine[0]) ){ zLine++; }; 10850 if( zLine[0]=='/' ) 10851 zLine += 1; /* Oracle */ 10852 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' ) 10853 zLine += 2; /* SQL Server */ 10854 else 10855 return 0; 10856 return quickscan(zLine,QSS_Start)==QSS_Start; 10857} 10858 10859/* 10860** We need a default sqlite3_complete() implementation to use in case 10861** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 10862** any arbitrary text is a complete SQL statement. This is not very 10863** user-friendly, but it does seem to work. 10864*/ 10865#ifdef SQLITE_OMIT_COMPLETE 10866#define sqlite3_complete(x) 1 10867#endif 10868 10869/* 10870** Return true if zSql is a complete SQL statement. Return false if it 10871** ends in the middle of a string literal or C-style comment. 10872*/ 10873static int line_is_complete(char *zSql, int nSql){ 10874 int rc; 10875 if( zSql==0 ) return 1; 10876 zSql[nSql] = ';'; 10877 zSql[nSql+1] = 0; 10878 rc = sqlite3_complete(zSql); 10879 zSql[nSql] = 0; 10880 return rc; 10881} 10882 10883/* 10884** Run a single line of SQL. Return the number of errors. 10885*/ 10886static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 10887 int rc; 10888 char *zErrMsg = 0; 10889 10890 open_db(p, 0); 10891 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 10892 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 10893 BEGIN_TIMER; 10894 rc = shell_exec(p, zSql, &zErrMsg); 10895 END_TIMER; 10896 if( rc || zErrMsg ){ 10897 char zPrefix[100]; 10898 if( in!=0 || !stdin_is_interactive ){ 10899 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 10900 "Error: near line %d:", startline); 10901 }else{ 10902 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 10903 } 10904 if( zErrMsg!=0 ){ 10905 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 10906 sqlite3_free(zErrMsg); 10907 zErrMsg = 0; 10908 }else{ 10909 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 10910 } 10911 return 1; 10912 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 10913 char zLineBuf[2000]; 10914 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf, 10915 "changes: %lld total_changes: %lld", 10916 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); 10917 raw_printf(p->out, "%s\n", zLineBuf); 10918 } 10919 return 0; 10920} 10921 10922 10923/* 10924** Read input from *in and process it. If *in==0 then input 10925** is interactive - the user is typing it it. Otherwise, input 10926** is coming from a file or device. A prompt is issued and history 10927** is saved only if input is interactive. An interrupt signal will 10928** cause this routine to exit immediately, unless input is interactive. 10929** 10930** Return the number of errors. 10931*/ 10932static int process_input(ShellState *p){ 10933 char *zLine = 0; /* A single input line */ 10934 char *zSql = 0; /* Accumulated SQL text */ 10935 int nLine; /* Length of current line */ 10936 int nSql = 0; /* Bytes of zSql[] used */ 10937 int nAlloc = 0; /* Allocated zSql[] space */ 10938 int rc; /* Error code */ 10939 int errCnt = 0; /* Number of errors seen */ 10940 int startline = 0; /* Line number for start of current input */ 10941 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */ 10942 10943 p->lineno = 0; 10944 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 10945 fflush(p->out); 10946 zLine = one_input_line(p->in, zLine, nSql>0); 10947 if( zLine==0 ){ 10948 /* End of input */ 10949 if( p->in==0 && stdin_is_interactive ) printf("\n"); 10950 break; 10951 } 10952 if( seenInterrupt ){ 10953 if( p->in!=0 ) break; 10954 seenInterrupt = 0; 10955 } 10956 p->lineno++; 10957 if( QSS_INPLAIN(qss) 10958 && line_is_command_terminator(zLine) 10959 && line_is_complete(zSql, nSql) ){ 10960 memcpy(zLine,";",2); 10961 } 10962 qss = quickscan(zLine, qss); 10963 if( QSS_PLAINWHITE(qss) && nSql==0 ){ 10964 if( ShellHasFlag(p, SHFLG_Echo) ) 10965 printf("%s\n", zLine); 10966 /* Just swallow single-line whitespace */ 10967 qss = QSS_Start; 10968 continue; 10969 } 10970 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 10971 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 10972 if( zLine[0]=='.' ){ 10973 rc = do_meta_command(zLine, p); 10974 if( rc==2 ){ /* exit requested */ 10975 break; 10976 }else if( rc ){ 10977 errCnt++; 10978 } 10979 } 10980 qss = QSS_Start; 10981 continue; 10982 } 10983 /* No single-line dispositions remain; accumulate line(s). */ 10984 nLine = strlen30(zLine); 10985 if( nSql+nLine+2>=nAlloc ){ 10986 /* Grow buffer by half-again increments when big. */ 10987 nAlloc = nSql+(nSql>>1)+nLine+100; 10988 zSql = realloc(zSql, nAlloc); 10989 shell_check_oom(zSql); 10990 } 10991 if( nSql==0 ){ 10992 int i; 10993 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 10994 assert( nAlloc>0 && zSql!=0 ); 10995 memcpy(zSql, zLine+i, nLine+1-i); 10996 startline = p->lineno; 10997 nSql = nLine-i; 10998 }else{ 10999 zSql[nSql++] = '\n'; 11000 memcpy(zSql+nSql, zLine, nLine+1); 11001 nSql += nLine; 11002 } 11003 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){ 11004 errCnt += runOneSqlLine(p, zSql, p->in, startline); 11005 nSql = 0; 11006 if( p->outCount ){ 11007 output_reset(p); 11008 p->outCount = 0; 11009 }else{ 11010 clearTempFile(p); 11011 } 11012 p->bSafeMode = p->bSafeModePersist; 11013 qss = QSS_Start; 11014 }else if( nSql && QSS_PLAINWHITE(qss) ){ 11015 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 11016 nSql = 0; 11017 qss = QSS_Start; 11018 } 11019 } 11020 if( nSql && QSS_PLAINDARK(qss) ){ 11021 errCnt += runOneSqlLine(p, zSql, p->in, startline); 11022 } 11023 free(zSql); 11024 free(zLine); 11025 return errCnt>0; 11026} 11027 11028/* 11029** Return a pathname which is the user's home directory. A 11030** 0 return indicates an error of some kind. 11031*/ 11032static char *find_home_dir(int clearFlag){ 11033 static char *home_dir = NULL; 11034 if( clearFlag ){ 11035 free(home_dir); 11036 home_dir = 0; 11037 return 0; 11038 } 11039 if( home_dir ) return home_dir; 11040 11041#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 11042 && !defined(__RTP__) && !defined(_WRS_KERNEL) 11043 { 11044 struct passwd *pwent; 11045 uid_t uid = getuid(); 11046 if( (pwent=getpwuid(uid)) != NULL) { 11047 home_dir = pwent->pw_dir; 11048 } 11049 } 11050#endif 11051 11052#if defined(_WIN32_WCE) 11053 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 11054 */ 11055 home_dir = "/"; 11056#else 11057 11058#if defined(_WIN32) || defined(WIN32) 11059 if (!home_dir) { 11060 home_dir = getenv("USERPROFILE"); 11061 } 11062#endif 11063 11064 if (!home_dir) { 11065 home_dir = getenv("HOME"); 11066 } 11067 11068#if defined(_WIN32) || defined(WIN32) 11069 if (!home_dir) { 11070 char *zDrive, *zPath; 11071 int n; 11072 zDrive = getenv("HOMEDRIVE"); 11073 zPath = getenv("HOMEPATH"); 11074 if( zDrive && zPath ){ 11075 n = strlen30(zDrive) + strlen30(zPath) + 1; 11076 home_dir = malloc( n ); 11077 if( home_dir==0 ) return 0; 11078 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 11079 return home_dir; 11080 } 11081 home_dir = "c:\\"; 11082 } 11083#endif 11084 11085#endif /* !_WIN32_WCE */ 11086 11087 if( home_dir ){ 11088 int n = strlen30(home_dir) + 1; 11089 char *z = malloc( n ); 11090 if( z ) memcpy(z, home_dir, n); 11091 home_dir = z; 11092 } 11093 11094 return home_dir; 11095} 11096 11097/* 11098** Read input from the file given by sqliterc_override. Or if that 11099** parameter is NULL, take input from ~/.sqliterc 11100** 11101** Returns the number of errors. 11102*/ 11103static void process_sqliterc( 11104 ShellState *p, /* Configuration data */ 11105 const char *sqliterc_override /* Name of config file. NULL to use default */ 11106){ 11107 char *home_dir = NULL; 11108 const char *sqliterc = sqliterc_override; 11109 char *zBuf = 0; 11110 FILE *inSaved = p->in; 11111 int savedLineno = p->lineno; 11112 11113 if (sqliterc == NULL) { 11114 home_dir = find_home_dir(0); 11115 if( home_dir==0 ){ 11116 raw_printf(stderr, "-- warning: cannot find home directory;" 11117 " cannot read ~/.sqliterc\n"); 11118 return; 11119 } 11120 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 11121 shell_check_oom(zBuf); 11122 sqliterc = zBuf; 11123 } 11124 p->in = fopen(sqliterc,"rb"); 11125 if( p->in ){ 11126 if( stdin_is_interactive ){ 11127 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 11128 } 11129 if( process_input(p) && bail_on_error ) exit(1); 11130 fclose(p->in); 11131 }else if( sqliterc_override!=0 ){ 11132 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc); 11133 if( bail_on_error ) exit(1); 11134 } 11135 p->in = inSaved; 11136 p->lineno = savedLineno; 11137 sqlite3_free(zBuf); 11138} 11139 11140/* 11141** Show available command line options 11142*/ 11143static const char zOptions[] = 11144#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 11145 " -A ARGS... run \".archive ARGS\" and exit\n" 11146#endif 11147 " -append append the database to the end of the file\n" 11148 " -ascii set output mode to 'ascii'\n" 11149 " -bail stop after hitting an error\n" 11150 " -batch force batch I/O\n" 11151 " -box set output mode to 'box'\n" 11152 " -column set output mode to 'column'\n" 11153 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 11154 " -csv set output mode to 'csv'\n" 11155#if !defined(SQLITE_OMIT_DESERIALIZE) 11156 " -deserialize open the database using sqlite3_deserialize()\n" 11157#endif 11158 " -echo print commands before execution\n" 11159 " -init FILENAME read/process named file\n" 11160 " -[no]header turn headers on or off\n" 11161#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11162 " -heap SIZE Size of heap for memsys3 or memsys5\n" 11163#endif 11164 " -help show this message\n" 11165 " -html set output mode to HTML\n" 11166 " -interactive force interactive I/O\n" 11167 " -json set output mode to 'json'\n" 11168 " -line set output mode to 'line'\n" 11169 " -list set output mode to 'list'\n" 11170 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 11171 " -markdown set output mode to 'markdown'\n" 11172#if !defined(SQLITE_OMIT_DESERIALIZE) 11173 " -maxsize N maximum size for a --deserialize database\n" 11174#endif 11175 " -memtrace trace all memory allocations and deallocations\n" 11176 " -mmap N default mmap size set to N\n" 11177#ifdef SQLITE_ENABLE_MULTIPLEX 11178 " -multiplex enable the multiplexor VFS\n" 11179#endif 11180 " -newline SEP set output row separator. Default: '\\n'\n" 11181 " -nofollow refuse to open symbolic links to database files\n" 11182 " -nonce STRING set the safe-mode escape nonce\n" 11183 " -nullvalue TEXT set text string for NULL values. Default ''\n" 11184 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 11185 " -quote set output mode to 'quote'\n" 11186 " -readonly open the database read-only\n" 11187 " -safe enable safe-mode\n" 11188 " -separator SEP set output column separator. Default: '|'\n" 11189#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11190 " -sorterref SIZE sorter references threshold size\n" 11191#endif 11192 " -stats print memory stats before each finalize\n" 11193 " -table set output mode to 'table'\n" 11194 " -tabs set output mode to 'tabs'\n" 11195 " -version show SQLite version\n" 11196 " -vfs NAME use NAME as the default VFS\n" 11197#ifdef SQLITE_ENABLE_VFSTRACE 11198 " -vfstrace enable tracing of all VFS calls\n" 11199#endif 11200#ifdef SQLITE_HAVE_ZLIB 11201 " -zip open the file as a ZIP Archive\n" 11202#endif 11203; 11204static void usage(int showDetail){ 11205 utf8_printf(stderr, 11206 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 11207 "FILENAME is the name of an SQLite database. A new database is created\n" 11208 "if the file does not previously exist.\n", Argv0); 11209 if( showDetail ){ 11210 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 11211 }else{ 11212 raw_printf(stderr, "Use the -help option for additional information\n"); 11213 } 11214 exit(1); 11215} 11216 11217/* 11218** Internal check: Verify that the SQLite is uninitialized. Print a 11219** error message if it is initialized. 11220*/ 11221static void verify_uninitialized(void){ 11222 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 11223 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 11224 " initialization.\n"); 11225 } 11226} 11227 11228/* 11229** Initialize the state information in data 11230*/ 11231static void main_init(ShellState *data) { 11232 memset(data, 0, sizeof(*data)); 11233 data->normalMode = data->cMode = data->mode = MODE_List; 11234 data->autoExplain = 1; 11235 data->pAuxDb = &data->aAuxDb[0]; 11236 memcpy(data->colSeparator,SEP_Column, 2); 11237 memcpy(data->rowSeparator,SEP_Row, 2); 11238 data->showHeader = 0; 11239 data->shellFlgs = SHFLG_Lookaside; 11240 verify_uninitialized(); 11241 sqlite3_config(SQLITE_CONFIG_URI, 1); 11242 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 11243 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 11244 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 11245 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 11246} 11247 11248/* 11249** Output text to the console in a font that attracts extra attention. 11250*/ 11251#ifdef _WIN32 11252static void printBold(const char *zText){ 11253#if !SQLITE_OS_WINRT 11254 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 11255 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 11256 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 11257 SetConsoleTextAttribute(out, 11258 FOREGROUND_RED|FOREGROUND_INTENSITY 11259 ); 11260#endif 11261 printf("%s", zText); 11262#if !SQLITE_OS_WINRT 11263 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 11264#endif 11265} 11266#else 11267static void printBold(const char *zText){ 11268 printf("\033[1m%s\033[0m", zText); 11269} 11270#endif 11271 11272/* 11273** Get the argument to an --option. Throw an error and die if no argument 11274** is available. 11275*/ 11276static char *cmdline_option_value(int argc, char **argv, int i){ 11277 if( i==argc ){ 11278 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 11279 argv[0], argv[argc-1]); 11280 exit(1); 11281 } 11282 return argv[i]; 11283} 11284 11285#ifndef SQLITE_SHELL_IS_UTF8 11286# if (defined(_WIN32) || defined(WIN32)) \ 11287 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__))) 11288# define SQLITE_SHELL_IS_UTF8 (0) 11289# else 11290# define SQLITE_SHELL_IS_UTF8 (1) 11291# endif 11292#endif 11293 11294#if SQLITE_SHELL_IS_UTF8 11295int SQLITE_CDECL main(int argc, char **argv){ 11296#else 11297int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 11298 char **argv; 11299#endif 11300 char *zErrMsg = 0; 11301 ShellState data; 11302 const char *zInitFile = 0; 11303 int i; 11304 int rc = 0; 11305 int warnInmemoryDb = 0; 11306 int readStdin = 1; 11307 int nCmd = 0; 11308 char **azCmd = 0; 11309 const char *zVfs = 0; /* Value of -vfs command-line option */ 11310#if !SQLITE_SHELL_IS_UTF8 11311 char **argvToFree = 0; 11312 int argcToFree = 0; 11313#endif 11314 11315 setBinaryMode(stdin, 0); 11316 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 11317 stdin_is_interactive = isatty(0); 11318 stdout_is_console = isatty(1); 11319 11320#if !defined(_WIN32_WCE) 11321 if( getenv("SQLITE_DEBUG_BREAK") ){ 11322 if( isatty(0) && isatty(2) ){ 11323 fprintf(stderr, 11324 "attach debugger to process %d and press any key to continue.\n", 11325 GETPID()); 11326 fgetc(stdin); 11327 }else{ 11328#if defined(_WIN32) || defined(WIN32) 11329#if SQLITE_OS_WINRT 11330 __debugbreak(); 11331#else 11332 DebugBreak(); 11333#endif 11334#elif defined(SIGTRAP) 11335 raise(SIGTRAP); 11336#endif 11337 } 11338 } 11339#endif 11340 11341#if USE_SYSTEM_SQLITE+0!=1 11342 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 11343 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 11344 sqlite3_sourceid(), SQLITE_SOURCE_ID); 11345 exit(1); 11346 } 11347#endif 11348 main_init(&data); 11349 11350 /* On Windows, we must translate command-line arguments into UTF-8. 11351 ** The SQLite memory allocator subsystem has to be enabled in order to 11352 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 11353 ** subsequent sqlite3_config() calls will work. So copy all results into 11354 ** memory that does not come from the SQLite memory allocator. 11355 */ 11356#if !SQLITE_SHELL_IS_UTF8 11357 sqlite3_initialize(); 11358 argvToFree = malloc(sizeof(argv[0])*argc*2); 11359 shell_check_oom(argvToFree); 11360 argcToFree = argc; 11361 argv = argvToFree + argc; 11362 for(i=0; i<argc; i++){ 11363 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 11364 int n; 11365 shell_check_oom(z); 11366 n = (int)strlen(z); 11367 argv[i] = malloc( n+1 ); 11368 shell_check_oom(argv[i]); 11369 memcpy(argv[i], z, n+1); 11370 argvToFree[i] = argv[i]; 11371 sqlite3_free(z); 11372 } 11373 sqlite3_shutdown(); 11374#endif 11375 11376 assert( argc>=1 && argv && argv[0] ); 11377 Argv0 = argv[0]; 11378 11379 /* Make sure we have a valid signal handler early, before anything 11380 ** else is done. 11381 */ 11382#ifdef SIGINT 11383 signal(SIGINT, interrupt_handler); 11384#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 11385 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 11386#endif 11387 11388#ifdef SQLITE_SHELL_DBNAME_PROC 11389 { 11390 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 11391 ** of a C-function that will provide the name of the database file. Use 11392 ** this compile-time option to embed this shell program in larger 11393 ** applications. */ 11394 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 11395 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename); 11396 warnInmemoryDb = 0; 11397 } 11398#endif 11399 11400 /* Do an initial pass through the command-line argument to locate 11401 ** the name of the database file, the name of the initialization file, 11402 ** the size of the alternative malloc heap, 11403 ** and the first command to execute. 11404 */ 11405 verify_uninitialized(); 11406 for(i=1; i<argc; i++){ 11407 char *z; 11408 z = argv[i]; 11409 if( z[0]!='-' ){ 11410 if( data.aAuxDb->zDbFilename==0 ){ 11411 data.aAuxDb->zDbFilename = z; 11412 }else{ 11413 /* Excesss arguments are interpreted as SQL (or dot-commands) and 11414 ** mean that nothing is read from stdin */ 11415 readStdin = 0; 11416 nCmd++; 11417 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 11418 shell_check_oom(azCmd); 11419 azCmd[nCmd-1] = z; 11420 } 11421 } 11422 if( z[1]=='-' ) z++; 11423 if( strcmp(z,"-separator")==0 11424 || strcmp(z,"-nullvalue")==0 11425 || strcmp(z,"-newline")==0 11426 || strcmp(z,"-cmd")==0 11427 ){ 11428 (void)cmdline_option_value(argc, argv, ++i); 11429 }else if( strcmp(z,"-init")==0 ){ 11430 zInitFile = cmdline_option_value(argc, argv, ++i); 11431 }else if( strcmp(z,"-batch")==0 ){ 11432 /* Need to check for batch mode here to so we can avoid printing 11433 ** informational messages (like from process_sqliterc) before 11434 ** we do the actual processing of arguments later in a second pass. 11435 */ 11436 stdin_is_interactive = 0; 11437 }else if( strcmp(z,"-heap")==0 ){ 11438#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11439 const char *zSize; 11440 sqlite3_int64 szHeap; 11441 11442 zSize = cmdline_option_value(argc, argv, ++i); 11443 szHeap = integerValue(zSize); 11444 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 11445 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 11446#else 11447 (void)cmdline_option_value(argc, argv, ++i); 11448#endif 11449 }else if( strcmp(z,"-pagecache")==0 ){ 11450 sqlite3_int64 n, sz; 11451 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11452 if( sz>70000 ) sz = 70000; 11453 if( sz<0 ) sz = 0; 11454 n = integerValue(cmdline_option_value(argc,argv,++i)); 11455 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){ 11456 n = 0xffffffffffffLL/sz; 11457 } 11458 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 11459 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 11460 data.shellFlgs |= SHFLG_Pagecache; 11461 }else if( strcmp(z,"-lookaside")==0 ){ 11462 int n, sz; 11463 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11464 if( sz<0 ) sz = 0; 11465 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11466 if( n<0 ) n = 0; 11467 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 11468 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 11469 }else if( strcmp(z,"-threadsafe")==0 ){ 11470 int n; 11471 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11472 switch( n ){ 11473 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break; 11474 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break; 11475 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break; 11476 } 11477#ifdef SQLITE_ENABLE_VFSTRACE 11478 }else if( strcmp(z,"-vfstrace")==0 ){ 11479 extern int vfstrace_register( 11480 const char *zTraceName, 11481 const char *zOldVfsName, 11482 int (*xOut)(const char*,void*), 11483 void *pOutArg, 11484 int makeDefault 11485 ); 11486 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 11487#endif 11488#ifdef SQLITE_ENABLE_MULTIPLEX 11489 }else if( strcmp(z,"-multiplex")==0 ){ 11490 extern int sqlite3_multiple_initialize(const char*,int); 11491 sqlite3_multiplex_initialize(0, 1); 11492#endif 11493 }else if( strcmp(z,"-mmap")==0 ){ 11494 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11495 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 11496#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11497 }else if( strcmp(z,"-sorterref")==0 ){ 11498 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11499 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 11500#endif 11501 }else if( strcmp(z,"-vfs")==0 ){ 11502 zVfs = cmdline_option_value(argc, argv, ++i); 11503#ifdef SQLITE_HAVE_ZLIB 11504 }else if( strcmp(z,"-zip")==0 ){ 11505 data.openMode = SHELL_OPEN_ZIPFILE; 11506#endif 11507 }else if( strcmp(z,"-append")==0 ){ 11508 data.openMode = SHELL_OPEN_APPENDVFS; 11509#ifndef SQLITE_OMIT_DESERIALIZE 11510 }else if( strcmp(z,"-deserialize")==0 ){ 11511 data.openMode = SHELL_OPEN_DESERIALIZE; 11512 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 11513 data.szMax = integerValue(argv[++i]); 11514#endif 11515 }else if( strcmp(z,"-readonly")==0 ){ 11516 data.openMode = SHELL_OPEN_READONLY; 11517 }else if( strcmp(z,"-nofollow")==0 ){ 11518 data.openFlags = SQLITE_OPEN_NOFOLLOW; 11519#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11520 }else if( strncmp(z, "-A",2)==0 ){ 11521 /* All remaining command-line arguments are passed to the ".archive" 11522 ** command, so ignore them */ 11523 break; 11524#endif 11525 }else if( strcmp(z, "-memtrace")==0 ){ 11526 sqlite3MemTraceActivate(stderr); 11527 }else if( strcmp(z,"-bail")==0 ){ 11528 bail_on_error = 1; 11529 }else if( strcmp(z,"-nonce")==0 ){ 11530 free(data.zNonce); 11531 data.zNonce = strdup(argv[++i]); 11532 }else if( strcmp(z,"-safe")==0 ){ 11533 /* no-op - catch this on the second pass */ 11534 } 11535 } 11536 verify_uninitialized(); 11537 11538 11539#ifdef SQLITE_SHELL_INIT_PROC 11540 { 11541 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 11542 ** of a C-function that will perform initialization actions on SQLite that 11543 ** occur just before or after sqlite3_initialize(). Use this compile-time 11544 ** option to embed this shell program in larger applications. */ 11545 extern void SQLITE_SHELL_INIT_PROC(void); 11546 SQLITE_SHELL_INIT_PROC(); 11547 } 11548#else 11549 /* All the sqlite3_config() calls have now been made. So it is safe 11550 ** to call sqlite3_initialize() and process any command line -vfs option. */ 11551 sqlite3_initialize(); 11552#endif 11553 11554 if( zVfs ){ 11555 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 11556 if( pVfs ){ 11557 sqlite3_vfs_register(pVfs, 1); 11558 }else{ 11559 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 11560 exit(1); 11561 } 11562 } 11563 11564 if( data.pAuxDb->zDbFilename==0 ){ 11565#ifndef SQLITE_OMIT_MEMORYDB 11566 data.pAuxDb->zDbFilename = ":memory:"; 11567 warnInmemoryDb = argc==1; 11568#else 11569 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 11570 return 1; 11571#endif 11572 } 11573 data.out = stdout; 11574 sqlite3_appendvfs_init(0,0,0); 11575 11576 /* Go ahead and open the database file if it already exists. If the 11577 ** file does not exist, delay opening it. This prevents empty database 11578 ** files from being created if a user mistypes the database name argument 11579 ** to the sqlite command-line tool. 11580 */ 11581 if( access(data.pAuxDb->zDbFilename, 0)==0 ){ 11582 open_db(&data, 0); 11583 } 11584 11585 /* Process the initialization file if there is one. If no -init option 11586 ** is given on the command line, look for a file named ~/.sqliterc and 11587 ** try to process it. 11588 */ 11589 process_sqliterc(&data,zInitFile); 11590 11591 /* Make a second pass through the command-line argument and set 11592 ** options. This second pass is delayed until after the initialization 11593 ** file is processed so that the command-line arguments will override 11594 ** settings in the initialization file. 11595 */ 11596 for(i=1; i<argc; i++){ 11597 char *z = argv[i]; 11598 if( z[0]!='-' ) continue; 11599 if( z[1]=='-' ){ z++; } 11600 if( strcmp(z,"-init")==0 ){ 11601 i++; 11602 }else if( strcmp(z,"-html")==0 ){ 11603 data.mode = MODE_Html; 11604 }else if( strcmp(z,"-list")==0 ){ 11605 data.mode = MODE_List; 11606 }else if( strcmp(z,"-quote")==0 ){ 11607 data.mode = MODE_Quote; 11608 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma); 11609 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11610 }else if( strcmp(z,"-line")==0 ){ 11611 data.mode = MODE_Line; 11612 }else if( strcmp(z,"-column")==0 ){ 11613 data.mode = MODE_Column; 11614 }else if( strcmp(z,"-json")==0 ){ 11615 data.mode = MODE_Json; 11616 }else if( strcmp(z,"-markdown")==0 ){ 11617 data.mode = MODE_Markdown; 11618 }else if( strcmp(z,"-table")==0 ){ 11619 data.mode = MODE_Table; 11620 }else if( strcmp(z,"-box")==0 ){ 11621 data.mode = MODE_Box; 11622 }else if( strcmp(z,"-csv")==0 ){ 11623 data.mode = MODE_Csv; 11624 memcpy(data.colSeparator,",",2); 11625#ifdef SQLITE_HAVE_ZLIB 11626 }else if( strcmp(z,"-zip")==0 ){ 11627 data.openMode = SHELL_OPEN_ZIPFILE; 11628#endif 11629 }else if( strcmp(z,"-append")==0 ){ 11630 data.openMode = SHELL_OPEN_APPENDVFS; 11631#ifndef SQLITE_OMIT_DESERIALIZE 11632 }else if( strcmp(z,"-deserialize")==0 ){ 11633 data.openMode = SHELL_OPEN_DESERIALIZE; 11634 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 11635 data.szMax = integerValue(argv[++i]); 11636#endif 11637 }else if( strcmp(z,"-readonly")==0 ){ 11638 data.openMode = SHELL_OPEN_READONLY; 11639 }else if( strcmp(z,"-nofollow")==0 ){ 11640 data.openFlags |= SQLITE_OPEN_NOFOLLOW; 11641 }else if( strcmp(z,"-ascii")==0 ){ 11642 data.mode = MODE_Ascii; 11643 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit); 11644 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record); 11645 }else if( strcmp(z,"-tabs")==0 ){ 11646 data.mode = MODE_List; 11647 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab); 11648 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11649 }else if( strcmp(z,"-separator")==0 ){ 11650 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 11651 "%s",cmdline_option_value(argc,argv,++i)); 11652 }else if( strcmp(z,"-newline")==0 ){ 11653 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 11654 "%s",cmdline_option_value(argc,argv,++i)); 11655 }else if( strcmp(z,"-nullvalue")==0 ){ 11656 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 11657 "%s",cmdline_option_value(argc,argv,++i)); 11658 }else if( strcmp(z,"-header")==0 ){ 11659 data.showHeader = 1; 11660 ShellSetFlag(&data, SHFLG_HeaderSet); 11661 }else if( strcmp(z,"-noheader")==0 ){ 11662 data.showHeader = 0; 11663 ShellSetFlag(&data, SHFLG_HeaderSet); 11664 }else if( strcmp(z,"-echo")==0 ){ 11665 ShellSetFlag(&data, SHFLG_Echo); 11666 }else if( strcmp(z,"-eqp")==0 ){ 11667 data.autoEQP = AUTOEQP_on; 11668 }else if( strcmp(z,"-eqpfull")==0 ){ 11669 data.autoEQP = AUTOEQP_full; 11670 }else if( strcmp(z,"-stats")==0 ){ 11671 data.statsOn = 1; 11672 }else if( strcmp(z,"-scanstats")==0 ){ 11673 data.scanstatsOn = 1; 11674 }else if( strcmp(z,"-backslash")==0 ){ 11675 /* Undocumented command-line option: -backslash 11676 ** Causes C-style backslash escapes to be evaluated in SQL statements 11677 ** prior to sending the SQL into SQLite. Useful for injecting 11678 ** crazy bytes in the middle of SQL statements for testing and debugging. 11679 */ 11680 ShellSetFlag(&data, SHFLG_Backslash); 11681 }else if( strcmp(z,"-bail")==0 ){ 11682 /* No-op. The bail_on_error flag should already be set. */ 11683 }else if( strcmp(z,"-version")==0 ){ 11684 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 11685 return 0; 11686 }else if( strcmp(z,"-interactive")==0 ){ 11687 stdin_is_interactive = 1; 11688 }else if( strcmp(z,"-batch")==0 ){ 11689 stdin_is_interactive = 0; 11690 }else if( strcmp(z,"-heap")==0 ){ 11691 i++; 11692 }else if( strcmp(z,"-pagecache")==0 ){ 11693 i+=2; 11694 }else if( strcmp(z,"-lookaside")==0 ){ 11695 i+=2; 11696 }else if( strcmp(z,"-threadsafe")==0 ){ 11697 i+=2; 11698 }else if( strcmp(z,"-nonce")==0 ){ 11699 i += 2; 11700 }else if( strcmp(z,"-mmap")==0 ){ 11701 i++; 11702 }else if( strcmp(z,"-memtrace")==0 ){ 11703 i++; 11704#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11705 }else if( strcmp(z,"-sorterref")==0 ){ 11706 i++; 11707#endif 11708 }else if( strcmp(z,"-vfs")==0 ){ 11709 i++; 11710#ifdef SQLITE_ENABLE_VFSTRACE 11711 }else if( strcmp(z,"-vfstrace")==0 ){ 11712 i++; 11713#endif 11714#ifdef SQLITE_ENABLE_MULTIPLEX 11715 }else if( strcmp(z,"-multiplex")==0 ){ 11716 i++; 11717#endif 11718 }else if( strcmp(z,"-help")==0 ){ 11719 usage(1); 11720 }else if( strcmp(z,"-cmd")==0 ){ 11721 /* Run commands that follow -cmd first and separately from commands 11722 ** that simply appear on the command-line. This seems goofy. It would 11723 ** be better if all commands ran in the order that they appear. But 11724 ** we retain the goofy behavior for historical compatibility. */ 11725 if( i==argc-1 ) break; 11726 z = cmdline_option_value(argc,argv,++i); 11727 if( z[0]=='.' ){ 11728 rc = do_meta_command(z, &data); 11729 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 11730 }else{ 11731 open_db(&data, 0); 11732 rc = shell_exec(&data, z, &zErrMsg); 11733 if( zErrMsg!=0 ){ 11734 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11735 if( bail_on_error ) return rc!=0 ? rc : 1; 11736 }else if( rc!=0 ){ 11737 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 11738 if( bail_on_error ) return rc; 11739 } 11740 } 11741#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11742 }else if( strncmp(z, "-A", 2)==0 ){ 11743 if( nCmd>0 ){ 11744 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 11745 " with \"%s\"\n", z); 11746 return 1; 11747 } 11748 open_db(&data, OPEN_DB_ZIPFILE); 11749 if( z[2] ){ 11750 argv[i] = &z[2]; 11751 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 11752 }else{ 11753 arDotCommand(&data, 1, argv+i, argc-i); 11754 } 11755 readStdin = 0; 11756 break; 11757#endif 11758 }else if( strcmp(z,"-safe")==0 ){ 11759 data.bSafeMode = data.bSafeModePersist = 1; 11760 }else{ 11761 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 11762 raw_printf(stderr,"Use -help for a list of options.\n"); 11763 return 1; 11764 } 11765 data.cMode = data.mode; 11766 } 11767 11768 if( !readStdin ){ 11769 /* Run all arguments that do not begin with '-' as if they were separate 11770 ** command-line inputs, except for the argToSkip argument which contains 11771 ** the database filename. 11772 */ 11773 for(i=0; i<nCmd; i++){ 11774 if( azCmd[i][0]=='.' ){ 11775 rc = do_meta_command(azCmd[i], &data); 11776 if( rc ){ 11777 free(azCmd); 11778 return rc==2 ? 0 : rc; 11779 } 11780 }else{ 11781 open_db(&data, 0); 11782 rc = shell_exec(&data, azCmd[i], &zErrMsg); 11783 if( zErrMsg || rc ){ 11784 if( zErrMsg!=0 ){ 11785 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11786 }else{ 11787 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 11788 } 11789 sqlite3_free(zErrMsg); 11790 free(azCmd); 11791 return rc!=0 ? rc : 1; 11792 } 11793 } 11794 } 11795 }else{ 11796 /* Run commands received from standard input 11797 */ 11798 if( stdin_is_interactive ){ 11799 char *zHome; 11800 char *zHistory; 11801 int nHistory; 11802 printf( 11803 "SQLite version %s %.19s\n" /*extra-version-info*/ 11804 "Enter \".help\" for usage hints.\n", 11805 sqlite3_libversion(), sqlite3_sourceid() 11806 ); 11807 if( warnInmemoryDb ){ 11808 printf("Connected to a "); 11809 printBold("transient in-memory database"); 11810 printf(".\nUse \".open FILENAME\" to reopen on a " 11811 "persistent database.\n"); 11812 } 11813 zHistory = getenv("SQLITE_HISTORY"); 11814 if( zHistory ){ 11815 zHistory = strdup(zHistory); 11816 }else if( (zHome = find_home_dir(0))!=0 ){ 11817 nHistory = strlen30(zHome) + 20; 11818 if( (zHistory = malloc(nHistory))!=0 ){ 11819 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 11820 } 11821 } 11822 if( zHistory ){ shell_read_history(zHistory); } 11823#if HAVE_READLINE || HAVE_EDITLINE 11824 rl_attempted_completion_function = readline_completion; 11825#elif HAVE_LINENOISE 11826 linenoiseSetCompletionCallback(linenoise_completion); 11827#endif 11828 data.in = 0; 11829 rc = process_input(&data); 11830 if( zHistory ){ 11831 shell_stifle_history(2000); 11832 shell_write_history(zHistory); 11833 free(zHistory); 11834 } 11835 }else{ 11836 data.in = stdin; 11837 rc = process_input(&data); 11838 } 11839 } 11840 free(azCmd); 11841 set_table_name(&data, 0); 11842 if( data.db ){ 11843 session_close_all(&data, -1); 11844 close_db(data.db); 11845 } 11846 for(i=0; i<ArraySize(data.aAuxDb); i++){ 11847 sqlite3_free(data.aAuxDb[i].zFreeOnClose); 11848 if( data.aAuxDb[i].db ){ 11849 session_close_all(&data, i); 11850 close_db(data.aAuxDb[i].db); 11851 } 11852 } 11853 find_home_dir(1); 11854 output_reset(&data); 11855 data.doXdgOpen = 0; 11856 clearTempFile(&data); 11857#if !SQLITE_SHELL_IS_UTF8 11858 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 11859 free(argvToFree); 11860#endif 11861 free(data.colWidth); 11862 free(data.zNonce); 11863 /* Clear the global data structure so that valgrind will detect memory 11864 ** leaks */ 11865 memset(&data, 0, sizeof(data)); 11866 return rc; 11867} 11868