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#ifdef SQLITE_DEBUG 431/* 432** Out-of-memory simulator variables 433*/ 434static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */ 435static unsigned int oomRepeat = 0; /* Number of OOMs in a row */ 436static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */ 437#endif /* SQLITE_DEBUG */ 438 439/* 440** This is the name of our program. It is set in main(), used 441** in a number of other places, mostly for error messages. 442*/ 443static char *Argv0; 444 445/* 446** Prompt strings. Initialized in main. Settable with 447** .prompt main continue 448*/ 449static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 450static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 451 452/* 453** Render output like fprintf(). Except, if the output is going to the 454** console and if this is running on a Windows machine, translate the 455** output from UTF-8 into MBCS. 456*/ 457#if defined(_WIN32) || defined(WIN32) 458void utf8_printf(FILE *out, const char *zFormat, ...){ 459 va_list ap; 460 va_start(ap, zFormat); 461 if( stdout_is_console && (out==stdout || out==stderr) ){ 462 char *z1 = sqlite3_vmprintf(zFormat, ap); 463 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 464 sqlite3_free(z1); 465 fputs(z2, out); 466 sqlite3_free(z2); 467 }else{ 468 vfprintf(out, zFormat, ap); 469 } 470 va_end(ap); 471} 472#elif !defined(utf8_printf) 473# define utf8_printf fprintf 474#endif 475 476/* 477** Render output like fprintf(). This should not be used on anything that 478** includes string formatting (e.g. "%s"). 479*/ 480#if !defined(raw_printf) 481# define raw_printf fprintf 482#endif 483 484/* Indicate out-of-memory and exit. */ 485static void shell_out_of_memory(void){ 486 raw_printf(stderr,"Error: out of memory\n"); 487 exit(1); 488} 489 490#ifdef SQLITE_DEBUG 491/* This routine is called when a simulated OOM occurs. It is broken 492** out as a separate routine to make it easy to set a breakpoint on 493** the OOM 494*/ 495void shellOomFault(void){ 496 if( oomRepeat>0 ){ 497 oomRepeat--; 498 }else{ 499 oomCounter--; 500 } 501} 502#endif /* SQLITE_DEBUG */ 503 504#ifdef SQLITE_DEBUG 505/* This routine is a replacement malloc() that is used to simulate 506** Out-Of-Memory (OOM) errors for testing purposes. 507*/ 508static void *oomMalloc(int nByte){ 509 if( oomCounter ){ 510 if( oomCounter==1 ){ 511 shellOomFault(); 512 return 0; 513 }else{ 514 oomCounter--; 515 } 516 } 517 return defaultMalloc(nByte); 518} 519#endif /* SQLITE_DEBUG */ 520 521#ifdef SQLITE_DEBUG 522/* Register the OOM simulator. This must occur before any memory 523** allocations */ 524static void registerOomSimulator(void){ 525 sqlite3_mem_methods mem; 526 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem); 527 defaultMalloc = mem.xMalloc; 528 mem.xMalloc = oomMalloc; 529 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem); 530} 531#endif 532 533/* 534** Write I/O traces to the following stream. 535*/ 536#ifdef SQLITE_ENABLE_IOTRACE 537static FILE *iotrace = 0; 538#endif 539 540/* 541** This routine works like printf in that its first argument is a 542** format string and subsequent arguments are values to be substituted 543** in place of % fields. The result of formatting this string 544** is written to iotrace. 545*/ 546#ifdef SQLITE_ENABLE_IOTRACE 547static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 548 va_list ap; 549 char *z; 550 if( iotrace==0 ) return; 551 va_start(ap, zFormat); 552 z = sqlite3_vmprintf(zFormat, ap); 553 va_end(ap); 554 utf8_printf(iotrace, "%s", z); 555 sqlite3_free(z); 556} 557#endif 558 559/* 560** Output string zUtf to stream pOut as w characters. If w is negative, 561** then right-justify the text. W is the width in UTF-8 characters, not 562** in bytes. This is different from the %*.*s specification in printf 563** since with %*.*s the width is measured in bytes, not characters. 564*/ 565static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 566 int i; 567 int n; 568 int aw = w<0 ? -w : w; 569 for(i=n=0; zUtf[i]; i++){ 570 if( (zUtf[i]&0xc0)!=0x80 ){ 571 n++; 572 if( n==aw ){ 573 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 574 break; 575 } 576 } 577 } 578 if( n>=aw ){ 579 utf8_printf(pOut, "%.*s", i, zUtf); 580 }else if( w<0 ){ 581 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 582 }else{ 583 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 584 } 585} 586 587 588/* 589** Determines if a string is a number of not. 590*/ 591static int isNumber(const char *z, int *realnum){ 592 if( *z=='-' || *z=='+' ) z++; 593 if( !IsDigit(*z) ){ 594 return 0; 595 } 596 z++; 597 if( realnum ) *realnum = 0; 598 while( IsDigit(*z) ){ z++; } 599 if( *z=='.' ){ 600 z++; 601 if( !IsDigit(*z) ) return 0; 602 while( IsDigit(*z) ){ z++; } 603 if( realnum ) *realnum = 1; 604 } 605 if( *z=='e' || *z=='E' ){ 606 z++; 607 if( *z=='+' || *z=='-' ) z++; 608 if( !IsDigit(*z) ) return 0; 609 while( IsDigit(*z) ){ z++; } 610 if( realnum ) *realnum = 1; 611 } 612 return *z==0; 613} 614 615/* 616** Compute a string length that is limited to what can be stored in 617** lower 30 bits of a 32-bit signed integer. 618*/ 619static int strlen30(const char *z){ 620 const char *z2 = z; 621 while( *z2 ){ z2++; } 622 return 0x3fffffff & (int)(z2 - z); 623} 624 625/* 626** Return the length of a string in characters. Multibyte UTF8 characters 627** count as a single character. 628*/ 629static int strlenChar(const char *z){ 630 int n = 0; 631 while( *z ){ 632 if( (0xc0&*(z++))!=0x80 ) n++; 633 } 634 return n; 635} 636 637/* 638** Return open FILE * if zFile exists, can be opened for read 639** and is an ordinary file or a character stream source. 640** Otherwise return 0. 641*/ 642static FILE * openChrSource(const char *zFile){ 643#ifdef _WIN32 644 struct _stat x = {0}; 645# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0) 646 /* On Windows, open first, then check the stream nature. This order 647 ** is necessary because _stat() and sibs, when checking a named pipe, 648 ** effectively break the pipe as its supplier sees it. */ 649 FILE *rv = fopen(zFile, "rb"); 650 if( rv==0 ) return 0; 651 if( _fstat(_fileno(rv), &x) != 0 652 || !STAT_CHR_SRC(x.st_mode)){ 653 fclose(rv); 654 rv = 0; 655 } 656 return rv; 657#else 658 struct stat x = {0}; 659 int rc = stat(zFile, &x); 660# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode)) 661 if( rc!=0 ) return 0; 662 if( STAT_CHR_SRC(x.st_mode) ){ 663 return fopen(zFile, "rb"); 664 }else{ 665 return 0; 666 } 667#endif 668#undef STAT_CHR_SRC 669} 670 671/* 672** This routine reads a line of text from FILE in, stores 673** the text in memory obtained from malloc() and returns a pointer 674** to the text. NULL is returned at end of file, or if malloc() 675** fails. 676** 677** If zLine is not NULL then it is a malloced buffer returned from 678** a previous call to this routine that may be reused. 679*/ 680static char *local_getline(char *zLine, FILE *in){ 681 int nLine = zLine==0 ? 0 : 100; 682 int n = 0; 683 684 while( 1 ){ 685 if( n+100>nLine ){ 686 nLine = nLine*2 + 100; 687 zLine = realloc(zLine, nLine); 688 if( zLine==0 ) shell_out_of_memory(); 689 } 690 if( fgets(&zLine[n], nLine - n, in)==0 ){ 691 if( n==0 ){ 692 free(zLine); 693 return 0; 694 } 695 zLine[n] = 0; 696 break; 697 } 698 while( zLine[n] ) n++; 699 if( n>0 && zLine[n-1]=='\n' ){ 700 n--; 701 if( n>0 && zLine[n-1]=='\r' ) n--; 702 zLine[n] = 0; 703 break; 704 } 705 } 706#if defined(_WIN32) || defined(WIN32) 707 /* For interactive input on Windows systems, translate the 708 ** multi-byte characterset characters into UTF-8. */ 709 if( stdin_is_interactive && in==stdin ){ 710 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 711 if( zTrans ){ 712 int nTrans = strlen30(zTrans)+1; 713 if( nTrans>nLine ){ 714 zLine = realloc(zLine, nTrans); 715 if( zLine==0 ) shell_out_of_memory(); 716 } 717 memcpy(zLine, zTrans, nTrans); 718 sqlite3_free(zTrans); 719 } 720 } 721#endif /* defined(_WIN32) || defined(WIN32) */ 722 return zLine; 723} 724 725/* 726** Retrieve a single line of input text. 727** 728** If in==0 then read from standard input and prompt before each line. 729** If isContinuation is true, then a continuation prompt is appropriate. 730** If isContinuation is zero, then the main prompt should be used. 731** 732** If zPrior is not NULL then it is a buffer from a prior call to this 733** routine that can be reused. 734** 735** The result is stored in space obtained from malloc() and must either 736** be freed by the caller or else passed back into this routine via the 737** zPrior argument for reuse. 738*/ 739static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 740 char *zPrompt; 741 char *zResult; 742 if( in!=0 ){ 743 zResult = local_getline(zPrior, in); 744 }else{ 745 zPrompt = isContinuation ? continuePrompt : mainPrompt; 746#if SHELL_USE_LOCAL_GETLINE 747 printf("%s", zPrompt); 748 fflush(stdout); 749 zResult = local_getline(zPrior, stdin); 750#else 751 free(zPrior); 752 zResult = shell_readline(zPrompt); 753 if( zResult && *zResult ) shell_add_history(zResult); 754#endif 755 } 756 return zResult; 757} 758 759 760/* 761** Return the value of a hexadecimal digit. Return -1 if the input 762** is not a hex digit. 763*/ 764static int hexDigitValue(char c){ 765 if( c>='0' && c<='9' ) return c - '0'; 766 if( c>='a' && c<='f' ) return c - 'a' + 10; 767 if( c>='A' && c<='F' ) return c - 'A' + 10; 768 return -1; 769} 770 771/* 772** Interpret zArg as an integer value, possibly with suffixes. 773*/ 774static sqlite3_int64 integerValue(const char *zArg){ 775 sqlite3_int64 v = 0; 776 static const struct { char *zSuffix; int iMult; } aMult[] = { 777 { "KiB", 1024 }, 778 { "MiB", 1024*1024 }, 779 { "GiB", 1024*1024*1024 }, 780 { "KB", 1000 }, 781 { "MB", 1000000 }, 782 { "GB", 1000000000 }, 783 { "K", 1000 }, 784 { "M", 1000000 }, 785 { "G", 1000000000 }, 786 }; 787 int i; 788 int isNeg = 0; 789 if( zArg[0]=='-' ){ 790 isNeg = 1; 791 zArg++; 792 }else if( zArg[0]=='+' ){ 793 zArg++; 794 } 795 if( zArg[0]=='0' && zArg[1]=='x' ){ 796 int x; 797 zArg += 2; 798 while( (x = hexDigitValue(zArg[0]))>=0 ){ 799 v = (v<<4) + x; 800 zArg++; 801 } 802 }else{ 803 while( IsDigit(zArg[0]) ){ 804 v = v*10 + zArg[0] - '0'; 805 zArg++; 806 } 807 } 808 for(i=0; i<ArraySize(aMult); i++){ 809 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 810 v *= aMult[i].iMult; 811 break; 812 } 813 } 814 return isNeg? -v : v; 815} 816 817/* 818** A variable length string to which one can append text. 819*/ 820typedef struct ShellText ShellText; 821struct ShellText { 822 char *z; 823 int n; 824 int nAlloc; 825}; 826 827/* 828** Initialize and destroy a ShellText object 829*/ 830static void initText(ShellText *p){ 831 memset(p, 0, sizeof(*p)); 832} 833static void freeText(ShellText *p){ 834 free(p->z); 835 initText(p); 836} 837 838/* zIn is either a pointer to a NULL-terminated string in memory obtained 839** from malloc(), or a NULL pointer. The string pointed to by zAppend is 840** added to zIn, and the result returned in memory obtained from malloc(). 841** zIn, if it was not NULL, is freed. 842** 843** If the third argument, quote, is not '\0', then it is used as a 844** quote character for zAppend. 845*/ 846static void appendText(ShellText *p, char const *zAppend, char quote){ 847 int len; 848 int i; 849 int nAppend = strlen30(zAppend); 850 851 len = nAppend+p->n+1; 852 if( quote ){ 853 len += 2; 854 for(i=0; i<nAppend; i++){ 855 if( zAppend[i]==quote ) len++; 856 } 857 } 858 859 if( p->z==0 || p->n+len>=p->nAlloc ){ 860 p->nAlloc = p->nAlloc*2 + len + 20; 861 p->z = realloc(p->z, p->nAlloc); 862 if( p->z==0 ) shell_out_of_memory(); 863 } 864 865 if( quote ){ 866 char *zCsr = p->z+p->n; 867 *zCsr++ = quote; 868 for(i=0; i<nAppend; i++){ 869 *zCsr++ = zAppend[i]; 870 if( zAppend[i]==quote ) *zCsr++ = quote; 871 } 872 *zCsr++ = quote; 873 p->n = (int)(zCsr - p->z); 874 *zCsr = '\0'; 875 }else{ 876 memcpy(p->z+p->n, zAppend, nAppend); 877 p->n += nAppend; 878 p->z[p->n] = '\0'; 879 } 880} 881 882/* 883** Attempt to determine if identifier zName needs to be quoted, either 884** because it contains non-alphanumeric characters, or because it is an 885** SQLite keyword. Be conservative in this estimate: When in doubt assume 886** that quoting is required. 887** 888** Return '"' if quoting is required. Return 0 if no quoting is required. 889*/ 890static char quoteChar(const char *zName){ 891 int i; 892 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 893 for(i=0; zName[i]; i++){ 894 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 895 } 896 return sqlite3_keyword_check(zName, i) ? '"' : 0; 897} 898 899/* 900** Construct a fake object name and column list to describe the structure 901** of the view, virtual table, or table valued function zSchema.zName. 902*/ 903static char *shellFakeSchema( 904 sqlite3 *db, /* The database connection containing the vtab */ 905 const char *zSchema, /* Schema of the database holding the vtab */ 906 const char *zName /* The name of the virtual table */ 907){ 908 sqlite3_stmt *pStmt = 0; 909 char *zSql; 910 ShellText s; 911 char cQuote; 912 char *zDiv = "("; 913 int nRow = 0; 914 915 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 916 zSchema ? zSchema : "main", zName); 917 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 918 sqlite3_free(zSql); 919 initText(&s); 920 if( zSchema ){ 921 cQuote = quoteChar(zSchema); 922 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 923 appendText(&s, zSchema, cQuote); 924 appendText(&s, ".", 0); 925 } 926 cQuote = quoteChar(zName); 927 appendText(&s, zName, cQuote); 928 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 929 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 930 nRow++; 931 appendText(&s, zDiv, 0); 932 zDiv = ","; 933 cQuote = quoteChar(zCol); 934 appendText(&s, zCol, cQuote); 935 } 936 appendText(&s, ")", 0); 937 sqlite3_finalize(pStmt); 938 if( nRow==0 ){ 939 freeText(&s); 940 s.z = 0; 941 } 942 return s.z; 943} 944 945/* 946** SQL function: shell_module_schema(X) 947** 948** Return a fake schema for the table-valued function or eponymous virtual 949** table X. 950*/ 951static void shellModuleSchema( 952 sqlite3_context *pCtx, 953 int nVal, 954 sqlite3_value **apVal 955){ 956 const char *zName = (const char*)sqlite3_value_text(apVal[0]); 957 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); 958 UNUSED_PARAMETER(nVal); 959 if( zFake ){ 960 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 961 -1, sqlite3_free); 962 free(zFake); 963 } 964} 965 966/* 967** SQL function: shell_add_schema(S,X) 968** 969** Add the schema name X to the CREATE statement in S and return the result. 970** Examples: 971** 972** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 973** 974** Also works on 975** 976** CREATE INDEX 977** CREATE UNIQUE INDEX 978** CREATE VIEW 979** CREATE TRIGGER 980** CREATE VIRTUAL TABLE 981** 982** This UDF is used by the .schema command to insert the schema name of 983** attached databases into the middle of the sqlite_schema.sql field. 984*/ 985static void shellAddSchemaName( 986 sqlite3_context *pCtx, 987 int nVal, 988 sqlite3_value **apVal 989){ 990 static const char *aPrefix[] = { 991 "TABLE", 992 "INDEX", 993 "UNIQUE INDEX", 994 "VIEW", 995 "TRIGGER", 996 "VIRTUAL TABLE" 997 }; 998 int i = 0; 999 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 1000 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 1001 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 1002 sqlite3 *db = sqlite3_context_db_handle(pCtx); 1003 UNUSED_PARAMETER(nVal); 1004 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ 1005 for(i=0; i<ArraySize(aPrefix); i++){ 1006 int n = strlen30(aPrefix[i]); 1007 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 1008 char *z = 0; 1009 char *zFake = 0; 1010 if( zSchema ){ 1011 char cQuote = quoteChar(zSchema); 1012 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 1013 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 1014 }else{ 1015 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 1016 } 1017 } 1018 if( zName 1019 && aPrefix[i][0]=='V' 1020 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 1021 ){ 1022 if( z==0 ){ 1023 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 1024 }else{ 1025 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 1026 } 1027 free(zFake); 1028 } 1029 if( z ){ 1030 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 1031 return; 1032 } 1033 } 1034 } 1035 } 1036 sqlite3_result_value(pCtx, apVal[0]); 1037} 1038 1039/* 1040** The source code for several run-time loadable extensions is inserted 1041** below by the ../tool/mkshellc.tcl script. Before processing that included 1042** code, we need to override some macros to make the included program code 1043** work here in the middle of this regular program. 1044*/ 1045#define SQLITE_EXTENSION_INIT1 1046#define SQLITE_EXTENSION_INIT2(X) (void)(X) 1047 1048#if defined(_WIN32) && defined(_MSC_VER) 1049INCLUDE test_windirent.h 1050INCLUDE test_windirent.c 1051#define dirent DIRENT 1052#endif 1053INCLUDE ../ext/misc/shathree.c 1054INCLUDE ../ext/misc/fileio.c 1055INCLUDE ../ext/misc/completion.c 1056INCLUDE ../ext/misc/appendvfs.c 1057INCLUDE ../ext/misc/memtrace.c 1058INCLUDE ../ext/misc/uint.c 1059INCLUDE ../ext/misc/decimal.c 1060INCLUDE ../ext/misc/ieee754.c 1061INCLUDE ../ext/misc/series.c 1062INCLUDE ../ext/misc/regexp.c 1063#ifdef SQLITE_HAVE_ZLIB 1064INCLUDE ../ext/misc/zipfile.c 1065INCLUDE ../ext/misc/sqlar.c 1066#endif 1067INCLUDE ../ext/expert/sqlite3expert.h 1068INCLUDE ../ext/expert/sqlite3expert.c 1069 1070#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 1071INCLUDE ../ext/misc/dbdata.c 1072#endif 1073 1074#if defined(SQLITE_ENABLE_SESSION) 1075/* 1076** State information for a single open session 1077*/ 1078typedef struct OpenSession OpenSession; 1079struct OpenSession { 1080 char *zName; /* Symbolic name for this session */ 1081 int nFilter; /* Number of xFilter rejection GLOB patterns */ 1082 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 1083 sqlite3_session *p; /* The open session */ 1084}; 1085#endif 1086 1087typedef struct ExpertInfo ExpertInfo; 1088struct ExpertInfo { 1089 sqlite3expert *pExpert; 1090 int bVerbose; 1091}; 1092 1093/* A single line in the EQP output */ 1094typedef struct EQPGraphRow EQPGraphRow; 1095struct EQPGraphRow { 1096 int iEqpId; /* ID for this row */ 1097 int iParentId; /* ID of the parent row */ 1098 EQPGraphRow *pNext; /* Next row in sequence */ 1099 char zText[1]; /* Text to display for this row */ 1100}; 1101 1102/* All EQP output is collected into an instance of the following */ 1103typedef struct EQPGraph EQPGraph; 1104struct EQPGraph { 1105 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 1106 EQPGraphRow *pLast; /* Last element of the pRow list */ 1107 char zPrefix[100]; /* Graph prefix */ 1108}; 1109 1110/* 1111** State information about the database connection is contained in an 1112** instance of the following structure. 1113*/ 1114typedef struct ShellState ShellState; 1115struct ShellState { 1116 sqlite3 *db; /* The database */ 1117 u8 autoExplain; /* Automatically turn on .explain mode */ 1118 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1119 u8 autoEQPtest; /* autoEQP is in test mode */ 1120 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1121 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1122 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1123 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1124 u8 nEqpLevel; /* Depth of the EQP output graph */ 1125 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1126 u8 bSafeMode; /* True to prohibit unsafe operations */ 1127 u8 bSafeModePersist; /* The long-term value of bSafeMode */ 1128 unsigned statsOn; /* True to display memory stats before each finalize */ 1129 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1130 int outCount; /* Revert to stdout when reaching zero */ 1131 int cnt; /* Number of records displayed so far */ 1132 int lineno; /* Line number of last line read from in */ 1133 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ 1134 FILE *in; /* Read commands from this stream */ 1135 FILE *out; /* Write results here */ 1136 FILE *traceOut; /* Output for sqlite3_trace() */ 1137 int nErr; /* Number of errors seen */ 1138 int mode; /* An output mode setting */ 1139 int modePrior; /* Saved mode */ 1140 int cMode; /* temporary output mode for the current query */ 1141 int normalMode; /* Output mode before ".explain on" */ 1142 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1143 int showHeader; /* True to show column names in List or Column mode */ 1144 int nCheck; /* Number of ".check" commands run */ 1145 unsigned nProgress; /* Number of progress callbacks encountered */ 1146 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1147 unsigned flgProgress; /* Flags for the progress callback */ 1148 unsigned shellFlgs; /* Various flags */ 1149 unsigned priorShFlgs; /* Saved copy of flags */ 1150 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1151 char *zDestTable; /* Name of destination table when MODE_Insert */ 1152 char *zTempFile; /* Temporary file that might need deleting */ 1153 char zTestcase[30]; /* Name of current test case */ 1154 char colSeparator[20]; /* Column separator character for several modes */ 1155 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1156 char colSepPrior[20]; /* Saved column separator */ 1157 char rowSepPrior[20]; /* Saved row separator */ 1158 int *colWidth; /* Requested width of each column in columnar modes */ 1159 int *actualWidth; /* Actual width of each column */ 1160 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */ 1161 char nullValue[20]; /* The text to print when a NULL comes back from 1162 ** the database */ 1163 char outfile[FILENAME_MAX]; /* Filename for *out */ 1164 sqlite3_stmt *pStmt; /* Current statement if any. */ 1165 FILE *pLog; /* Write log output here */ 1166 struct AuxDb { /* Storage space for auxiliary database connections */ 1167 sqlite3 *db; /* Connection pointer */ 1168 const char *zDbFilename; /* Filename used to open the connection */ 1169 char *zFreeOnClose; /* Free this memory allocation on close */ 1170#if defined(SQLITE_ENABLE_SESSION) 1171 int nSession; /* Number of active sessions */ 1172 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1173#endif 1174 } aAuxDb[5], /* Array of all database connections */ 1175 *pAuxDb; /* Currently active database connection */ 1176 int *aiIndent; /* Array of indents used in MODE_Explain */ 1177 int nIndent; /* Size of array aiIndent[] */ 1178 int iIndent; /* Index of current op in aiIndent[] */ 1179 char *zNonce; /* Nonce for temporary safe-mode excapes */ 1180 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1181 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1182}; 1183 1184 1185/* Allowed values for ShellState.autoEQP 1186*/ 1187#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1188#define AUTOEQP_on 1 /* Automatic EQP is on */ 1189#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1190#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1191 1192/* Allowed values for ShellState.openMode 1193*/ 1194#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1195#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1196#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1197#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1198#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1199#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1200#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1201 1202/* Allowed values for ShellState.eTraceType 1203*/ 1204#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1205#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1206#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1207 1208/* Bits in the ShellState.flgProgress variable */ 1209#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1210#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1211 ** callback limit is reached, and for each 1212 ** top-level SQL statement */ 1213#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1214 1215/* 1216** These are the allowed shellFlgs values 1217*/ 1218#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1219#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1220#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1221#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1222#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1223#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1224#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1225#define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */ 1226#define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */ 1227#define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */ 1228 1229/* 1230** Macros for testing and setting shellFlgs 1231*/ 1232#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1233#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1234#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1235 1236/* 1237** These are the allowed modes. 1238*/ 1239#define MODE_Line 0 /* One column per line. Blank line between records */ 1240#define MODE_Column 1 /* One record per line in neat columns */ 1241#define MODE_List 2 /* One record per line with a separator */ 1242#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1243#define MODE_Html 4 /* Generate an XHTML table */ 1244#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1245#define MODE_Quote 6 /* Quote values as for SQL */ 1246#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1247#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1248#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1249#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1250#define MODE_Pretty 11 /* Pretty-print schemas */ 1251#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1252#define MODE_Json 13 /* Output JSON */ 1253#define MODE_Markdown 14 /* Markdown formatting */ 1254#define MODE_Table 15 /* MySQL-style table formatting */ 1255#define MODE_Box 16 /* Unicode box-drawing characters */ 1256 1257static const char *modeDescr[] = { 1258 "line", 1259 "column", 1260 "list", 1261 "semi", 1262 "html", 1263 "insert", 1264 "quote", 1265 "tcl", 1266 "csv", 1267 "explain", 1268 "ascii", 1269 "prettyprint", 1270 "eqp", 1271 "json", 1272 "markdown", 1273 "table", 1274 "box" 1275}; 1276 1277/* 1278** These are the column/row/line separators used by the various 1279** import/export modes. 1280*/ 1281#define SEP_Column "|" 1282#define SEP_Row "\n" 1283#define SEP_Tab "\t" 1284#define SEP_Space " " 1285#define SEP_Comma "," 1286#define SEP_CrLf "\r\n" 1287#define SEP_Unit "\x1F" 1288#define SEP_Record "\x1E" 1289 1290/* 1291** A callback for the sqlite3_log() interface. 1292*/ 1293static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1294 ShellState *p = (ShellState*)pArg; 1295 if( p->pLog==0 ) return; 1296 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1297 fflush(p->pLog); 1298} 1299 1300/* 1301** SQL function: shell_putsnl(X) 1302** 1303** Write the text X to the screen (or whatever output is being directed) 1304** adding a newline at the end, and then return X. 1305*/ 1306static void shellPutsFunc( 1307 sqlite3_context *pCtx, 1308 int nVal, 1309 sqlite3_value **apVal 1310){ 1311 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1312 (void)nVal; 1313 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1314 sqlite3_result_value(pCtx, apVal[0]); 1315} 1316 1317/* 1318** If in safe mode, print an error message described by the arguments 1319** and exit immediately. 1320*/ 1321static void failIfSafeMode( 1322 ShellState *p, 1323 const char *zErrMsg, 1324 ... 1325){ 1326 if( p->bSafeMode ){ 1327 va_list ap; 1328 char *zMsg; 1329 va_start(ap, zErrMsg); 1330 zMsg = sqlite3_vmprintf(zErrMsg, ap); 1331 va_end(ap); 1332 raw_printf(stderr, "line %d: ", p->lineno); 1333 utf8_printf(stderr, "%s\n", zMsg); 1334 exit(1); 1335 } 1336} 1337 1338/* 1339** SQL function: edit(VALUE) 1340** edit(VALUE,EDITOR) 1341** 1342** These steps: 1343** 1344** (1) Write VALUE into a temporary file. 1345** (2) Run program EDITOR on that temporary file. 1346** (3) Read the temporary file back and return its content as the result. 1347** (4) Delete the temporary file 1348** 1349** If the EDITOR argument is omitted, use the value in the VISUAL 1350** environment variable. If still there is no EDITOR, through an error. 1351** 1352** Also throw an error if the EDITOR program returns a non-zero exit code. 1353*/ 1354#ifndef SQLITE_NOHAVE_SYSTEM 1355static void editFunc( 1356 sqlite3_context *context, 1357 int argc, 1358 sqlite3_value **argv 1359){ 1360 const char *zEditor; 1361 char *zTempFile = 0; 1362 sqlite3 *db; 1363 char *zCmd = 0; 1364 int bBin; 1365 int rc; 1366 int hasCRNL = 0; 1367 FILE *f = 0; 1368 sqlite3_int64 sz; 1369 sqlite3_int64 x; 1370 unsigned char *p = 0; 1371 1372 if( argc==2 ){ 1373 zEditor = (const char*)sqlite3_value_text(argv[1]); 1374 }else{ 1375 zEditor = getenv("VISUAL"); 1376 } 1377 if( zEditor==0 ){ 1378 sqlite3_result_error(context, "no editor for edit()", -1); 1379 return; 1380 } 1381 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1382 sqlite3_result_error(context, "NULL input to edit()", -1); 1383 return; 1384 } 1385 db = sqlite3_context_db_handle(context); 1386 zTempFile = 0; 1387 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1388 if( zTempFile==0 ){ 1389 sqlite3_uint64 r = 0; 1390 sqlite3_randomness(sizeof(r), &r); 1391 zTempFile = sqlite3_mprintf("temp%llx", r); 1392 if( zTempFile==0 ){ 1393 sqlite3_result_error_nomem(context); 1394 return; 1395 } 1396 } 1397 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1398 /* When writing the file to be edited, do \n to \r\n conversions on systems 1399 ** that want \r\n line endings */ 1400 f = fopen(zTempFile, bBin ? "wb" : "w"); 1401 if( f==0 ){ 1402 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1403 goto edit_func_end; 1404 } 1405 sz = sqlite3_value_bytes(argv[0]); 1406 if( bBin ){ 1407 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); 1408 }else{ 1409 const char *z = (const char*)sqlite3_value_text(argv[0]); 1410 /* Remember whether or not the value originally contained \r\n */ 1411 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1412 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); 1413 } 1414 fclose(f); 1415 f = 0; 1416 if( x!=sz ){ 1417 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1418 goto edit_func_end; 1419 } 1420 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1421 if( zCmd==0 ){ 1422 sqlite3_result_error_nomem(context); 1423 goto edit_func_end; 1424 } 1425 rc = system(zCmd); 1426 sqlite3_free(zCmd); 1427 if( rc ){ 1428 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1429 goto edit_func_end; 1430 } 1431 f = fopen(zTempFile, "rb"); 1432 if( f==0 ){ 1433 sqlite3_result_error(context, 1434 "edit() cannot reopen temp file after edit", -1); 1435 goto edit_func_end; 1436 } 1437 fseek(f, 0, SEEK_END); 1438 sz = ftell(f); 1439 rewind(f); 1440 p = sqlite3_malloc64( sz+1 ); 1441 if( p==0 ){ 1442 sqlite3_result_error_nomem(context); 1443 goto edit_func_end; 1444 } 1445 x = fread(p, 1, (size_t)sz, f); 1446 fclose(f); 1447 f = 0; 1448 if( x!=sz ){ 1449 sqlite3_result_error(context, "could not read back the whole file", -1); 1450 goto edit_func_end; 1451 } 1452 if( bBin ){ 1453 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1454 }else{ 1455 sqlite3_int64 i, j; 1456 if( hasCRNL ){ 1457 /* If the original contains \r\n then do no conversions back to \n */ 1458 }else{ 1459 /* If the file did not originally contain \r\n then convert any new 1460 ** \r\n back into \n */ 1461 for(i=j=0; i<sz; i++){ 1462 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1463 p[j++] = p[i]; 1464 } 1465 sz = j; 1466 p[sz] = 0; 1467 } 1468 sqlite3_result_text64(context, (const char*)p, sz, 1469 sqlite3_free, SQLITE_UTF8); 1470 } 1471 p = 0; 1472 1473edit_func_end: 1474 if( f ) fclose(f); 1475 unlink(zTempFile); 1476 sqlite3_free(zTempFile); 1477 sqlite3_free(p); 1478} 1479#endif /* SQLITE_NOHAVE_SYSTEM */ 1480 1481/* 1482** Save or restore the current output mode 1483*/ 1484static void outputModePush(ShellState *p){ 1485 p->modePrior = p->mode; 1486 p->priorShFlgs = p->shellFlgs; 1487 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1488 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1489} 1490static void outputModePop(ShellState *p){ 1491 p->mode = p->modePrior; 1492 p->shellFlgs = p->priorShFlgs; 1493 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1494 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1495} 1496 1497/* 1498** Output the given string as a hex-encoded blob (eg. X'1234' ) 1499*/ 1500static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1501 int i; 1502 char *zBlob = (char *)pBlob; 1503 raw_printf(out,"X'"); 1504 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1505 raw_printf(out,"'"); 1506} 1507 1508/* 1509** Find a string that is not found anywhere in z[]. Return a pointer 1510** to that string. 1511** 1512** Try to use zA and zB first. If both of those are already found in z[] 1513** then make up some string and store it in the buffer zBuf. 1514*/ 1515static const char *unused_string( 1516 const char *z, /* Result must not appear anywhere in z */ 1517 const char *zA, const char *zB, /* Try these first */ 1518 char *zBuf /* Space to store a generated string */ 1519){ 1520 unsigned i = 0; 1521 if( strstr(z, zA)==0 ) return zA; 1522 if( strstr(z, zB)==0 ) return zB; 1523 do{ 1524 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1525 }while( strstr(z,zBuf)!=0 ); 1526 return zBuf; 1527} 1528 1529/* 1530** Output the given string as a quoted string using SQL quoting conventions. 1531** 1532** See also: output_quoted_escaped_string() 1533*/ 1534static void output_quoted_string(FILE *out, const char *z){ 1535 int i; 1536 char c; 1537 setBinaryMode(out, 1); 1538 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1539 if( c==0 ){ 1540 utf8_printf(out,"'%s'",z); 1541 }else{ 1542 raw_printf(out, "'"); 1543 while( *z ){ 1544 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1545 if( c=='\'' ) i++; 1546 if( i ){ 1547 utf8_printf(out, "%.*s", i, z); 1548 z += i; 1549 } 1550 if( c=='\'' ){ 1551 raw_printf(out, "'"); 1552 continue; 1553 } 1554 if( c==0 ){ 1555 break; 1556 } 1557 z++; 1558 } 1559 raw_printf(out, "'"); 1560 } 1561 setTextMode(out, 1); 1562} 1563 1564/* 1565** Output the given string as a quoted string using SQL quoting conventions. 1566** Additionallly , escape the "\n" and "\r" characters so that they do not 1567** get corrupted by end-of-line translation facilities in some operating 1568** systems. 1569** 1570** This is like output_quoted_string() but with the addition of the \r\n 1571** escape mechanism. 1572*/ 1573static void output_quoted_escaped_string(FILE *out, const char *z){ 1574 int i; 1575 char c; 1576 setBinaryMode(out, 1); 1577 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1578 if( c==0 ){ 1579 utf8_printf(out,"'%s'",z); 1580 }else{ 1581 const char *zNL = 0; 1582 const char *zCR = 0; 1583 int nNL = 0; 1584 int nCR = 0; 1585 char zBuf1[20], zBuf2[20]; 1586 for(i=0; z[i]; i++){ 1587 if( z[i]=='\n' ) nNL++; 1588 if( z[i]=='\r' ) nCR++; 1589 } 1590 if( nNL ){ 1591 raw_printf(out, "replace("); 1592 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1593 } 1594 if( nCR ){ 1595 raw_printf(out, "replace("); 1596 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1597 } 1598 raw_printf(out, "'"); 1599 while( *z ){ 1600 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1601 if( c=='\'' ) i++; 1602 if( i ){ 1603 utf8_printf(out, "%.*s", i, z); 1604 z += i; 1605 } 1606 if( c=='\'' ){ 1607 raw_printf(out, "'"); 1608 continue; 1609 } 1610 if( c==0 ){ 1611 break; 1612 } 1613 z++; 1614 if( c=='\n' ){ 1615 raw_printf(out, "%s", zNL); 1616 continue; 1617 } 1618 raw_printf(out, "%s", zCR); 1619 } 1620 raw_printf(out, "'"); 1621 if( nCR ){ 1622 raw_printf(out, ",'%s',char(13))", zCR); 1623 } 1624 if( nNL ){ 1625 raw_printf(out, ",'%s',char(10))", zNL); 1626 } 1627 } 1628 setTextMode(out, 1); 1629} 1630 1631/* 1632** Output the given string as a quoted according to C or TCL quoting rules. 1633*/ 1634static void output_c_string(FILE *out, const char *z){ 1635 unsigned int c; 1636 fputc('"', out); 1637 while( (c = *(z++))!=0 ){ 1638 if( c=='\\' ){ 1639 fputc(c, out); 1640 fputc(c, out); 1641 }else if( c=='"' ){ 1642 fputc('\\', out); 1643 fputc('"', out); 1644 }else if( c=='\t' ){ 1645 fputc('\\', out); 1646 fputc('t', out); 1647 }else if( c=='\n' ){ 1648 fputc('\\', out); 1649 fputc('n', out); 1650 }else if( c=='\r' ){ 1651 fputc('\\', out); 1652 fputc('r', out); 1653 }else if( !isprint(c&0xff) ){ 1654 raw_printf(out, "\\%03o", c&0xff); 1655 }else{ 1656 fputc(c, out); 1657 } 1658 } 1659 fputc('"', out); 1660} 1661 1662/* 1663** Output the given string as a quoted according to JSON quoting rules. 1664*/ 1665static void output_json_string(FILE *out, const char *z, int n){ 1666 unsigned int c; 1667 if( n<0 ) n = (int)strlen(z); 1668 fputc('"', out); 1669 while( n-- ){ 1670 c = *(z++); 1671 if( c=='\\' || c=='"' ){ 1672 fputc('\\', out); 1673 fputc(c, out); 1674 }else if( c<=0x1f ){ 1675 fputc('\\', out); 1676 if( c=='\b' ){ 1677 fputc('b', out); 1678 }else if( c=='\f' ){ 1679 fputc('f', out); 1680 }else if( c=='\n' ){ 1681 fputc('n', out); 1682 }else if( c=='\r' ){ 1683 fputc('r', out); 1684 }else if( c=='\t' ){ 1685 fputc('t', out); 1686 }else{ 1687 raw_printf(out, "u%04x",c); 1688 } 1689 }else{ 1690 fputc(c, out); 1691 } 1692 } 1693 fputc('"', out); 1694} 1695 1696/* 1697** Output the given string with characters that are special to 1698** HTML escaped. 1699*/ 1700static void output_html_string(FILE *out, const char *z){ 1701 int i; 1702 if( z==0 ) z = ""; 1703 while( *z ){ 1704 for(i=0; z[i] 1705 && z[i]!='<' 1706 && z[i]!='&' 1707 && z[i]!='>' 1708 && z[i]!='\"' 1709 && z[i]!='\''; 1710 i++){} 1711 if( i>0 ){ 1712 utf8_printf(out,"%.*s",i,z); 1713 } 1714 if( z[i]=='<' ){ 1715 raw_printf(out,"<"); 1716 }else if( z[i]=='&' ){ 1717 raw_printf(out,"&"); 1718 }else if( z[i]=='>' ){ 1719 raw_printf(out,">"); 1720 }else if( z[i]=='\"' ){ 1721 raw_printf(out,"""); 1722 }else if( z[i]=='\'' ){ 1723 raw_printf(out,"'"); 1724 }else{ 1725 break; 1726 } 1727 z += i + 1; 1728 } 1729} 1730 1731/* 1732** If a field contains any character identified by a 1 in the following 1733** array, then the string must be quoted for CSV. 1734*/ 1735static const char needCsvQuote[] = { 1736 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1737 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1738 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1739 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1740 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1741 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1742 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1743 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1744 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1745 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1746 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1747 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1748 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1749 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1750 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1751 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1752}; 1753 1754/* 1755** Output a single term of CSV. Actually, p->colSeparator is used for 1756** the separator, which may or may not be a comma. p->nullValue is 1757** the null value. Strings are quoted if necessary. The separator 1758** is only issued if bSep is true. 1759*/ 1760static void output_csv(ShellState *p, const char *z, int bSep){ 1761 FILE *out = p->out; 1762 if( z==0 ){ 1763 utf8_printf(out,"%s",p->nullValue); 1764 }else{ 1765 int i; 1766 int nSep = strlen30(p->colSeparator); 1767 for(i=0; z[i]; i++){ 1768 if( needCsvQuote[((unsigned char*)z)[i]] 1769 || (z[i]==p->colSeparator[0] && 1770 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ 1771 i = 0; 1772 break; 1773 } 1774 } 1775 if( i==0 ){ 1776 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1777 utf8_printf(out, "%s", zQuoted); 1778 sqlite3_free(zQuoted); 1779 }else{ 1780 utf8_printf(out, "%s", z); 1781 } 1782 } 1783 if( bSep ){ 1784 utf8_printf(p->out, "%s", p->colSeparator); 1785 } 1786} 1787 1788/* 1789** This routine runs when the user presses Ctrl-C 1790*/ 1791static void interrupt_handler(int NotUsed){ 1792 UNUSED_PARAMETER(NotUsed); 1793 seenInterrupt++; 1794 if( seenInterrupt>2 ) exit(1); 1795 if( globalDb ) sqlite3_interrupt(globalDb); 1796} 1797 1798#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1799/* 1800** This routine runs for console events (e.g. Ctrl-C) on Win32 1801*/ 1802static BOOL WINAPI ConsoleCtrlHandler( 1803 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1804){ 1805 if( dwCtrlType==CTRL_C_EVENT ){ 1806 interrupt_handler(0); 1807 return TRUE; 1808 } 1809 return FALSE; 1810} 1811#endif 1812 1813#ifndef SQLITE_OMIT_AUTHORIZATION 1814/* 1815** This authorizer runs in safe mode. 1816*/ 1817static int safeModeAuth( 1818 void *pClientData, 1819 int op, 1820 const char *zA1, 1821 const char *zA2, 1822 const char *zA3, 1823 const char *zA4 1824){ 1825 ShellState *p = (ShellState*)pClientData; 1826 static const char *azProhibitedFunctions[] = { 1827 "edit", 1828 "fts3_tokenizer", 1829 "load_extension", 1830 "readfile", 1831 "writefile", 1832 "zipfile", 1833 "zipfile_cds", 1834 }; 1835 UNUSED_PARAMETER(zA2); 1836 UNUSED_PARAMETER(zA3); 1837 UNUSED_PARAMETER(zA4); 1838 switch( op ){ 1839 case SQLITE_ATTACH: { 1840 failIfSafeMode(p, "cannot run ATTACH in safe mode"); 1841 break; 1842 } 1843 case SQLITE_FUNCTION: { 1844 int i; 1845 for(i=0; i<ArraySize(azProhibitedFunctions); i++){ 1846 if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){ 1847 failIfSafeMode(p, "cannot use the %s() function in safe mode", 1848 azProhibitedFunctions[i]); 1849 } 1850 } 1851 break; 1852 } 1853 } 1854 return SQLITE_OK; 1855} 1856 1857/* 1858** When the ".auth ON" is set, the following authorizer callback is 1859** invoked. It always returns SQLITE_OK. 1860*/ 1861static int shellAuth( 1862 void *pClientData, 1863 int op, 1864 const char *zA1, 1865 const char *zA2, 1866 const char *zA3, 1867 const char *zA4 1868){ 1869 ShellState *p = (ShellState*)pClientData; 1870 static const char *azAction[] = { 0, 1871 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1872 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1873 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1874 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1875 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1876 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1877 "PRAGMA", "READ", "SELECT", 1878 "TRANSACTION", "UPDATE", "ATTACH", 1879 "DETACH", "ALTER_TABLE", "REINDEX", 1880 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1881 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1882 }; 1883 int i; 1884 const char *az[4]; 1885 az[0] = zA1; 1886 az[1] = zA2; 1887 az[2] = zA3; 1888 az[3] = zA4; 1889 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1890 for(i=0; i<4; i++){ 1891 raw_printf(p->out, " "); 1892 if( az[i] ){ 1893 output_c_string(p->out, az[i]); 1894 }else{ 1895 raw_printf(p->out, "NULL"); 1896 } 1897 } 1898 raw_printf(p->out, "\n"); 1899 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); 1900 return SQLITE_OK; 1901} 1902#endif 1903 1904/* 1905** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1906** 1907** This routine converts some CREATE TABLE statements for shadow tables 1908** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1909*/ 1910static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1911 if( z==0 ) return; 1912 if( zTail==0 ) return; 1913 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1914 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1915 }else{ 1916 utf8_printf(out, "%s%s", z, zTail); 1917 } 1918} 1919static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1920 char c = z[n]; 1921 z[n] = 0; 1922 printSchemaLine(out, z, zTail); 1923 z[n] = c; 1924} 1925 1926/* 1927** Return true if string z[] has nothing but whitespace and comments to the 1928** end of the first line. 1929*/ 1930static int wsToEol(const char *z){ 1931 int i; 1932 for(i=0; z[i]; i++){ 1933 if( z[i]=='\n' ) return 1; 1934 if( IsSpace(z[i]) ) continue; 1935 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1936 return 0; 1937 } 1938 return 1; 1939} 1940 1941/* 1942** Add a new entry to the EXPLAIN QUERY PLAN data 1943*/ 1944static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1945 EQPGraphRow *pNew; 1946 int nText = strlen30(zText); 1947 if( p->autoEQPtest ){ 1948 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1949 } 1950 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1951 if( pNew==0 ) shell_out_of_memory(); 1952 pNew->iEqpId = iEqpId; 1953 pNew->iParentId = p2; 1954 memcpy(pNew->zText, zText, nText+1); 1955 pNew->pNext = 0; 1956 if( p->sGraph.pLast ){ 1957 p->sGraph.pLast->pNext = pNew; 1958 }else{ 1959 p->sGraph.pRow = pNew; 1960 } 1961 p->sGraph.pLast = pNew; 1962} 1963 1964/* 1965** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1966** in p->sGraph. 1967*/ 1968static void eqp_reset(ShellState *p){ 1969 EQPGraphRow *pRow, *pNext; 1970 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1971 pNext = pRow->pNext; 1972 sqlite3_free(pRow); 1973 } 1974 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1975} 1976 1977/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1978** pOld, or return the first such line if pOld is NULL 1979*/ 1980static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1981 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1982 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1983 return pRow; 1984} 1985 1986/* Render a single level of the graph that has iEqpId as its parent. Called 1987** recursively to render sublevels. 1988*/ 1989static void eqp_render_level(ShellState *p, int iEqpId){ 1990 EQPGraphRow *pRow, *pNext; 1991 int n = strlen30(p->sGraph.zPrefix); 1992 char *z; 1993 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1994 pNext = eqp_next_row(p, iEqpId, pRow); 1995 z = pRow->zText; 1996 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, 1997 pNext ? "|--" : "`--", z); 1998 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1999 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 2000 eqp_render_level(p, pRow->iEqpId); 2001 p->sGraph.zPrefix[n] = 0; 2002 } 2003 } 2004} 2005 2006/* 2007** Display and reset the EXPLAIN QUERY PLAN data 2008*/ 2009static void eqp_render(ShellState *p){ 2010 EQPGraphRow *pRow = p->sGraph.pRow; 2011 if( pRow ){ 2012 if( pRow->zText[0]=='-' ){ 2013 if( pRow->pNext==0 ){ 2014 eqp_reset(p); 2015 return; 2016 } 2017 utf8_printf(p->out, "%s\n", pRow->zText+3); 2018 p->sGraph.pRow = pRow->pNext; 2019 sqlite3_free(pRow); 2020 }else{ 2021 utf8_printf(p->out, "QUERY PLAN\n"); 2022 } 2023 p->sGraph.zPrefix[0] = 0; 2024 eqp_render_level(p, 0); 2025 eqp_reset(p); 2026 } 2027} 2028 2029#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 2030/* 2031** Progress handler callback. 2032*/ 2033static int progress_handler(void *pClientData) { 2034 ShellState *p = (ShellState*)pClientData; 2035 p->nProgress++; 2036 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 2037 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 2038 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 2039 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 2040 return 1; 2041 } 2042 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 2043 raw_printf(p->out, "Progress %u\n", p->nProgress); 2044 } 2045 return 0; 2046} 2047#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 2048 2049/* 2050** Print N dashes 2051*/ 2052static void print_dashes(FILE *out, int N){ 2053 const char zDash[] = "--------------------------------------------------"; 2054 const int nDash = sizeof(zDash) - 1; 2055 while( N>nDash ){ 2056 fputs(zDash, out); 2057 N -= nDash; 2058 } 2059 raw_printf(out, "%.*s", N, zDash); 2060} 2061 2062/* 2063** Print a markdown or table-style row separator using ascii-art 2064*/ 2065static void print_row_separator( 2066 ShellState *p, 2067 int nArg, 2068 const char *zSep 2069){ 2070 int i; 2071 if( nArg>0 ){ 2072 fputs(zSep, p->out); 2073 print_dashes(p->out, p->actualWidth[0]+2); 2074 for(i=1; i<nArg; i++){ 2075 fputs(zSep, p->out); 2076 print_dashes(p->out, p->actualWidth[i]+2); 2077 } 2078 fputs(zSep, p->out); 2079 } 2080 fputs("\n", p->out); 2081} 2082 2083/* 2084** This is the callback routine that the shell 2085** invokes for each row of a query result. 2086*/ 2087static int shell_callback( 2088 void *pArg, 2089 int nArg, /* Number of result columns */ 2090 char **azArg, /* Text of each result column */ 2091 char **azCol, /* Column names */ 2092 int *aiType /* Column types. Might be NULL */ 2093){ 2094 int i; 2095 ShellState *p = (ShellState*)pArg; 2096 2097 if( azArg==0 ) return 0; 2098 switch( p->cMode ){ 2099 case MODE_Line: { 2100 int w = 5; 2101 if( azArg==0 ) break; 2102 for(i=0; i<nArg; i++){ 2103 int len = strlen30(azCol[i] ? azCol[i] : ""); 2104 if( len>w ) w = len; 2105 } 2106 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 2107 for(i=0; i<nArg; i++){ 2108 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 2109 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 2110 } 2111 break; 2112 } 2113 case MODE_Explain: { 2114 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13}; 2115 if( nArg>ArraySize(aExplainWidth) ){ 2116 nArg = ArraySize(aExplainWidth); 2117 } 2118 if( p->cnt++==0 ){ 2119 for(i=0; i<nArg; i++){ 2120 int w = aExplainWidth[i]; 2121 utf8_width_print(p->out, w, azCol[i]); 2122 fputs(i==nArg-1 ? "\n" : " ", p->out); 2123 } 2124 for(i=0; i<nArg; i++){ 2125 int w = aExplainWidth[i]; 2126 print_dashes(p->out, w); 2127 fputs(i==nArg-1 ? "\n" : " ", p->out); 2128 } 2129 } 2130 if( azArg==0 ) break; 2131 for(i=0; i<nArg; i++){ 2132 int w = aExplainWidth[i]; 2133 if( i==nArg-1 ) w = 0; 2134 if( azArg[i] && strlenChar(azArg[i])>w ){ 2135 w = strlenChar(azArg[i]); 2136 } 2137 if( i==1 && p->aiIndent && p->pStmt ){ 2138 if( p->iIndent<p->nIndent ){ 2139 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 2140 } 2141 p->iIndent++; 2142 } 2143 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 2144 fputs(i==nArg-1 ? "\n" : " ", p->out); 2145 } 2146 break; 2147 } 2148 case MODE_Semi: { /* .schema and .fullschema output */ 2149 printSchemaLine(p->out, azArg[0], ";\n"); 2150 break; 2151 } 2152 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 2153 char *z; 2154 int j; 2155 int nParen = 0; 2156 char cEnd = 0; 2157 char c; 2158 int nLine = 0; 2159 assert( nArg==1 ); 2160 if( azArg[0]==0 ) break; 2161 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 2162 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 2163 ){ 2164 utf8_printf(p->out, "%s;\n", azArg[0]); 2165 break; 2166 } 2167 z = sqlite3_mprintf("%s", azArg[0]); 2168 j = 0; 2169 for(i=0; IsSpace(z[i]); i++){} 2170 for(; (c = z[i])!=0; i++){ 2171 if( IsSpace(c) ){ 2172 if( z[j-1]=='\r' ) z[j-1] = '\n'; 2173 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 2174 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 2175 j--; 2176 } 2177 z[j++] = c; 2178 } 2179 while( j>0 && IsSpace(z[j-1]) ){ j--; } 2180 z[j] = 0; 2181 if( strlen30(z)>=79 ){ 2182 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ 2183 if( c==cEnd ){ 2184 cEnd = 0; 2185 }else if( c=='"' || c=='\'' || c=='`' ){ 2186 cEnd = c; 2187 }else if( c=='[' ){ 2188 cEnd = ']'; 2189 }else if( c=='-' && z[i+1]=='-' ){ 2190 cEnd = '\n'; 2191 }else if( c=='(' ){ 2192 nParen++; 2193 }else if( c==')' ){ 2194 nParen--; 2195 if( nLine>0 && nParen==0 && j>0 ){ 2196 printSchemaLineN(p->out, z, j, "\n"); 2197 j = 0; 2198 } 2199 } 2200 z[j++] = c; 2201 if( nParen==1 && cEnd==0 2202 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 2203 ){ 2204 if( c=='\n' ) j--; 2205 printSchemaLineN(p->out, z, j, "\n "); 2206 j = 0; 2207 nLine++; 2208 while( IsSpace(z[i+1]) ){ i++; } 2209 } 2210 } 2211 z[j] = 0; 2212 } 2213 printSchemaLine(p->out, z, ";\n"); 2214 sqlite3_free(z); 2215 break; 2216 } 2217 case MODE_List: { 2218 if( p->cnt++==0 && p->showHeader ){ 2219 for(i=0; i<nArg; i++){ 2220 utf8_printf(p->out,"%s%s",azCol[i], 2221 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2222 } 2223 } 2224 if( azArg==0 ) break; 2225 for(i=0; i<nArg; i++){ 2226 char *z = azArg[i]; 2227 if( z==0 ) z = p->nullValue; 2228 utf8_printf(p->out, "%s", z); 2229 if( i<nArg-1 ){ 2230 utf8_printf(p->out, "%s", p->colSeparator); 2231 }else{ 2232 utf8_printf(p->out, "%s", p->rowSeparator); 2233 } 2234 } 2235 break; 2236 } 2237 case MODE_Html: { 2238 if( p->cnt++==0 && p->showHeader ){ 2239 raw_printf(p->out,"<TR>"); 2240 for(i=0; i<nArg; i++){ 2241 raw_printf(p->out,"<TH>"); 2242 output_html_string(p->out, azCol[i]); 2243 raw_printf(p->out,"</TH>\n"); 2244 } 2245 raw_printf(p->out,"</TR>\n"); 2246 } 2247 if( azArg==0 ) break; 2248 raw_printf(p->out,"<TR>"); 2249 for(i=0; i<nArg; i++){ 2250 raw_printf(p->out,"<TD>"); 2251 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2252 raw_printf(p->out,"</TD>\n"); 2253 } 2254 raw_printf(p->out,"</TR>\n"); 2255 break; 2256 } 2257 case MODE_Tcl: { 2258 if( p->cnt++==0 && p->showHeader ){ 2259 for(i=0; i<nArg; i++){ 2260 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2261 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2262 } 2263 utf8_printf(p->out, "%s", p->rowSeparator); 2264 } 2265 if( azArg==0 ) break; 2266 for(i=0; i<nArg; i++){ 2267 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2268 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2269 } 2270 utf8_printf(p->out, "%s", p->rowSeparator); 2271 break; 2272 } 2273 case MODE_Csv: { 2274 setBinaryMode(p->out, 1); 2275 if( p->cnt++==0 && p->showHeader ){ 2276 for(i=0; i<nArg; i++){ 2277 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2278 } 2279 utf8_printf(p->out, "%s", p->rowSeparator); 2280 } 2281 if( nArg>0 ){ 2282 for(i=0; i<nArg; i++){ 2283 output_csv(p, azArg[i], i<nArg-1); 2284 } 2285 utf8_printf(p->out, "%s", p->rowSeparator); 2286 } 2287 setTextMode(p->out, 1); 2288 break; 2289 } 2290 case MODE_Insert: { 2291 if( azArg==0 ) break; 2292 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2293 if( p->showHeader ){ 2294 raw_printf(p->out,"("); 2295 for(i=0; i<nArg; i++){ 2296 if( i>0 ) raw_printf(p->out, ","); 2297 if( quoteChar(azCol[i]) ){ 2298 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2299 utf8_printf(p->out, "%s", z); 2300 sqlite3_free(z); 2301 }else{ 2302 raw_printf(p->out, "%s", azCol[i]); 2303 } 2304 } 2305 raw_printf(p->out,")"); 2306 } 2307 p->cnt++; 2308 for(i=0; i<nArg; i++){ 2309 raw_printf(p->out, i>0 ? "," : " VALUES("); 2310 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2311 utf8_printf(p->out,"NULL"); 2312 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2313 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2314 output_quoted_string(p->out, azArg[i]); 2315 }else{ 2316 output_quoted_escaped_string(p->out, azArg[i]); 2317 } 2318 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2319 utf8_printf(p->out,"%s", azArg[i]); 2320 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2321 char z[50]; 2322 double r = sqlite3_column_double(p->pStmt, i); 2323 sqlite3_uint64 ur; 2324 memcpy(&ur,&r,sizeof(r)); 2325 if( ur==0x7ff0000000000000LL ){ 2326 raw_printf(p->out, "1e999"); 2327 }else if( ur==0xfff0000000000000LL ){ 2328 raw_printf(p->out, "-1e999"); 2329 }else{ 2330 sqlite3_snprintf(50,z,"%!.20g", r); 2331 raw_printf(p->out, "%s", z); 2332 } 2333 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2334 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2335 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2336 output_hex_blob(p->out, pBlob, nBlob); 2337 }else if( isNumber(azArg[i], 0) ){ 2338 utf8_printf(p->out,"%s", azArg[i]); 2339 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2340 output_quoted_string(p->out, azArg[i]); 2341 }else{ 2342 output_quoted_escaped_string(p->out, azArg[i]); 2343 } 2344 } 2345 raw_printf(p->out,");\n"); 2346 break; 2347 } 2348 case MODE_Json: { 2349 if( azArg==0 ) break; 2350 if( p->cnt==0 ){ 2351 fputs("[{", p->out); 2352 }else{ 2353 fputs(",\n{", p->out); 2354 } 2355 p->cnt++; 2356 for(i=0; i<nArg; i++){ 2357 output_json_string(p->out, azCol[i], -1); 2358 putc(':', p->out); 2359 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2360 fputs("null",p->out); 2361 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2362 char z[50]; 2363 double r = sqlite3_column_double(p->pStmt, i); 2364 sqlite3_uint64 ur; 2365 memcpy(&ur,&r,sizeof(r)); 2366 if( ur==0x7ff0000000000000LL ){ 2367 raw_printf(p->out, "1e999"); 2368 }else if( ur==0xfff0000000000000LL ){ 2369 raw_printf(p->out, "-1e999"); 2370 }else{ 2371 sqlite3_snprintf(50,z,"%!.20g", r); 2372 raw_printf(p->out, "%s", z); 2373 } 2374 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2375 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2376 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2377 output_json_string(p->out, pBlob, nBlob); 2378 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2379 output_json_string(p->out, azArg[i], -1); 2380 }else{ 2381 utf8_printf(p->out,"%s", azArg[i]); 2382 } 2383 if( i<nArg-1 ){ 2384 putc(',', p->out); 2385 } 2386 } 2387 putc('}', p->out); 2388 break; 2389 } 2390 case MODE_Quote: { 2391 if( azArg==0 ) break; 2392 if( p->cnt==0 && p->showHeader ){ 2393 for(i=0; i<nArg; i++){ 2394 if( i>0 ) fputs(p->colSeparator, p->out); 2395 output_quoted_string(p->out, azCol[i]); 2396 } 2397 fputs(p->rowSeparator, p->out); 2398 } 2399 p->cnt++; 2400 for(i=0; i<nArg; i++){ 2401 if( i>0 ) fputs(p->colSeparator, p->out); 2402 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2403 utf8_printf(p->out,"NULL"); 2404 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2405 output_quoted_string(p->out, azArg[i]); 2406 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2407 utf8_printf(p->out,"%s", azArg[i]); 2408 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2409 char z[50]; 2410 double r = sqlite3_column_double(p->pStmt, i); 2411 sqlite3_snprintf(50,z,"%!.20g", r); 2412 raw_printf(p->out, "%s", z); 2413 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2414 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2415 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2416 output_hex_blob(p->out, pBlob, nBlob); 2417 }else if( isNumber(azArg[i], 0) ){ 2418 utf8_printf(p->out,"%s", azArg[i]); 2419 }else{ 2420 output_quoted_string(p->out, azArg[i]); 2421 } 2422 } 2423 fputs(p->rowSeparator, p->out); 2424 break; 2425 } 2426 case MODE_Ascii: { 2427 if( p->cnt++==0 && p->showHeader ){ 2428 for(i=0; i<nArg; i++){ 2429 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2430 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2431 } 2432 utf8_printf(p->out, "%s", p->rowSeparator); 2433 } 2434 if( azArg==0 ) break; 2435 for(i=0; i<nArg; i++){ 2436 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2437 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2438 } 2439 utf8_printf(p->out, "%s", p->rowSeparator); 2440 break; 2441 } 2442 case MODE_EQP: { 2443 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2444 break; 2445 } 2446 } 2447 return 0; 2448} 2449 2450/* 2451** This is the callback routine that the SQLite library 2452** invokes for each row of a query result. 2453*/ 2454static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2455 /* since we don't have type info, call the shell_callback with a NULL value */ 2456 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2457} 2458 2459/* 2460** This is the callback routine from sqlite3_exec() that appends all 2461** output onto the end of a ShellText object. 2462*/ 2463static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2464 ShellText *p = (ShellText*)pArg; 2465 int i; 2466 UNUSED_PARAMETER(az); 2467 if( azArg==0 ) return 0; 2468 if( p->n ) appendText(p, "|", 0); 2469 for(i=0; i<nArg; i++){ 2470 if( i ) appendText(p, ",", 0); 2471 if( azArg[i] ) appendText(p, azArg[i], 0); 2472 } 2473 return 0; 2474} 2475 2476/* 2477** Generate an appropriate SELFTEST table in the main database. 2478*/ 2479static void createSelftestTable(ShellState *p){ 2480 char *zErrMsg = 0; 2481 sqlite3_exec(p->db, 2482 "SAVEPOINT selftest_init;\n" 2483 "CREATE TABLE IF NOT EXISTS selftest(\n" 2484 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2485 " op TEXT,\n" /* Operator: memo run */ 2486 " cmd TEXT,\n" /* Command text */ 2487 " ans TEXT\n" /* Desired answer */ 2488 ");" 2489 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2490 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2491 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2492 " 'memo','Tests generated by --init');\n" 2493 "INSERT INTO [_shell$self]\n" 2494 " SELECT 'run',\n" 2495 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2496 "FROM sqlite_schema ORDER BY 2'',224))',\n" 2497 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2498 "FROM sqlite_schema ORDER BY 2',224));\n" 2499 "INSERT INTO [_shell$self]\n" 2500 " SELECT 'run'," 2501 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2502 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2503 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2504 " FROM (\n" 2505 " SELECT name FROM sqlite_schema\n" 2506 " WHERE type='table'\n" 2507 " AND name<>'selftest'\n" 2508 " AND coalesce(rootpage,0)>0\n" 2509 " )\n" 2510 " ORDER BY name;\n" 2511 "INSERT INTO [_shell$self]\n" 2512 " VALUES('run','PRAGMA integrity_check','ok');\n" 2513 "INSERT INTO selftest(tno,op,cmd,ans)" 2514 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2515 "DROP TABLE [_shell$self];" 2516 ,0,0,&zErrMsg); 2517 if( zErrMsg ){ 2518 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2519 sqlite3_free(zErrMsg); 2520 } 2521 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2522} 2523 2524 2525/* 2526** Set the destination table field of the ShellState structure to 2527** the name of the table given. Escape any quote characters in the 2528** table name. 2529*/ 2530static void set_table_name(ShellState *p, const char *zName){ 2531 int i, n; 2532 char cQuote; 2533 char *z; 2534 2535 if( p->zDestTable ){ 2536 free(p->zDestTable); 2537 p->zDestTable = 0; 2538 } 2539 if( zName==0 ) return; 2540 cQuote = quoteChar(zName); 2541 n = strlen30(zName); 2542 if( cQuote ) n += n+2; 2543 z = p->zDestTable = malloc( n+1 ); 2544 if( z==0 ) shell_out_of_memory(); 2545 n = 0; 2546 if( cQuote ) z[n++] = cQuote; 2547 for(i=0; zName[i]; i++){ 2548 z[n++] = zName[i]; 2549 if( zName[i]==cQuote ) z[n++] = cQuote; 2550 } 2551 if( cQuote ) z[n++] = cQuote; 2552 z[n] = 0; 2553} 2554 2555 2556/* 2557** Execute a query statement that will generate SQL output. Print 2558** the result columns, comma-separated, on a line and then add a 2559** semicolon terminator to the end of that line. 2560** 2561** If the number of columns is 1 and that column contains text "--" 2562** then write the semicolon on a separate line. That way, if a 2563** "--" comment occurs at the end of the statement, the comment 2564** won't consume the semicolon terminator. 2565*/ 2566static int run_table_dump_query( 2567 ShellState *p, /* Query context */ 2568 const char *zSelect /* SELECT statement to extract content */ 2569){ 2570 sqlite3_stmt *pSelect; 2571 int rc; 2572 int nResult; 2573 int i; 2574 const char *z; 2575 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2576 if( rc!=SQLITE_OK || !pSelect ){ 2577 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2578 sqlite3_errmsg(p->db)); 2579 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2580 return rc; 2581 } 2582 rc = sqlite3_step(pSelect); 2583 nResult = sqlite3_column_count(pSelect); 2584 while( rc==SQLITE_ROW ){ 2585 z = (const char*)sqlite3_column_text(pSelect, 0); 2586 utf8_printf(p->out, "%s", z); 2587 for(i=1; i<nResult; i++){ 2588 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2589 } 2590 if( z==0 ) z = ""; 2591 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2592 if( z[0] ){ 2593 raw_printf(p->out, "\n;\n"); 2594 }else{ 2595 raw_printf(p->out, ";\n"); 2596 } 2597 rc = sqlite3_step(pSelect); 2598 } 2599 rc = sqlite3_finalize(pSelect); 2600 if( rc!=SQLITE_OK ){ 2601 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2602 sqlite3_errmsg(p->db)); 2603 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2604 } 2605 return rc; 2606} 2607 2608/* 2609** Allocate space and save off current error string. 2610*/ 2611static char *save_err_msg( 2612 sqlite3 *db /* Database to query */ 2613){ 2614 int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); 2615 char *zErrMsg = sqlite3_malloc64(nErrMsg); 2616 if( zErrMsg ){ 2617 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); 2618 } 2619 return zErrMsg; 2620} 2621 2622#ifdef __linux__ 2623/* 2624** Attempt to display I/O stats on Linux using /proc/PID/io 2625*/ 2626static void displayLinuxIoStats(FILE *out){ 2627 FILE *in; 2628 char z[200]; 2629 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2630 in = fopen(z, "rb"); 2631 if( in==0 ) return; 2632 while( fgets(z, sizeof(z), in)!=0 ){ 2633 static const struct { 2634 const char *zPattern; 2635 const char *zDesc; 2636 } aTrans[] = { 2637 { "rchar: ", "Bytes received by read():" }, 2638 { "wchar: ", "Bytes sent to write():" }, 2639 { "syscr: ", "Read() system calls:" }, 2640 { "syscw: ", "Write() system calls:" }, 2641 { "read_bytes: ", "Bytes read from storage:" }, 2642 { "write_bytes: ", "Bytes written to storage:" }, 2643 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2644 }; 2645 int i; 2646 for(i=0; i<ArraySize(aTrans); i++){ 2647 int n = strlen30(aTrans[i].zPattern); 2648 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2649 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2650 break; 2651 } 2652 } 2653 } 2654 fclose(in); 2655} 2656#endif 2657 2658/* 2659** Display a single line of status using 64-bit values. 2660*/ 2661static void displayStatLine( 2662 ShellState *p, /* The shell context */ 2663 char *zLabel, /* Label for this one line */ 2664 char *zFormat, /* Format for the result */ 2665 int iStatusCtrl, /* Which status to display */ 2666 int bReset /* True to reset the stats */ 2667){ 2668 sqlite3_int64 iCur = -1; 2669 sqlite3_int64 iHiwtr = -1; 2670 int i, nPercent; 2671 char zLine[200]; 2672 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2673 for(i=0, nPercent=0; zFormat[i]; i++){ 2674 if( zFormat[i]=='%' ) nPercent++; 2675 } 2676 if( nPercent>1 ){ 2677 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2678 }else{ 2679 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2680 } 2681 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2682} 2683 2684/* 2685** Display memory stats. 2686*/ 2687static int display_stats( 2688 sqlite3 *db, /* Database to query */ 2689 ShellState *pArg, /* Pointer to ShellState */ 2690 int bReset /* True to reset the stats */ 2691){ 2692 int iCur; 2693 int iHiwtr; 2694 FILE *out; 2695 if( pArg==0 || pArg->out==0 ) return 0; 2696 out = pArg->out; 2697 2698 if( pArg->pStmt && pArg->statsOn==2 ){ 2699 int nCol, i, x; 2700 sqlite3_stmt *pStmt = pArg->pStmt; 2701 char z[100]; 2702 nCol = sqlite3_column_count(pStmt); 2703 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2704 for(i=0; i<nCol; i++){ 2705 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2706 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2707#ifndef SQLITE_OMIT_DECLTYPE 2708 sqlite3_snprintf(30, z+x, "declared type:"); 2709 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2710#endif 2711#ifdef SQLITE_ENABLE_COLUMN_METADATA 2712 sqlite3_snprintf(30, z+x, "database name:"); 2713 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2714 sqlite3_snprintf(30, z+x, "table name:"); 2715 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2716 sqlite3_snprintf(30, z+x, "origin name:"); 2717 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2718#endif 2719 } 2720 } 2721 2722 if( pArg->statsOn==3 ){ 2723 if( pArg->pStmt ){ 2724 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2725 raw_printf(pArg->out, "VM-steps: %d\n", iCur); 2726 } 2727 return 0; 2728 } 2729 2730 displayStatLine(pArg, "Memory Used:", 2731 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2732 displayStatLine(pArg, "Number of Outstanding Allocations:", 2733 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2734 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2735 displayStatLine(pArg, "Number of Pcache Pages Used:", 2736 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2737 } 2738 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2739 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2740 displayStatLine(pArg, "Largest Allocation:", 2741 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2742 displayStatLine(pArg, "Largest Pcache Allocation:", 2743 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2744#ifdef YYTRACKMAXSTACKDEPTH 2745 displayStatLine(pArg, "Deepest Parser Stack:", 2746 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2747#endif 2748 2749 if( db ){ 2750 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2751 iHiwtr = iCur = -1; 2752 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2753 &iCur, &iHiwtr, bReset); 2754 raw_printf(pArg->out, 2755 "Lookaside Slots Used: %d (max %d)\n", 2756 iCur, iHiwtr); 2757 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2758 &iCur, &iHiwtr, bReset); 2759 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2760 iHiwtr); 2761 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2762 &iCur, &iHiwtr, bReset); 2763 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2764 iHiwtr); 2765 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2766 &iCur, &iHiwtr, bReset); 2767 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2768 iHiwtr); 2769 } 2770 iHiwtr = iCur = -1; 2771 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2772 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2773 iCur); 2774 iHiwtr = iCur = -1; 2775 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2776 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2777 iHiwtr = iCur = -1; 2778 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2779 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2780 iHiwtr = iCur = -1; 2781 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2782 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2783 iHiwtr = iCur = -1; 2784 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2785 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2786 iHiwtr = iCur = -1; 2787 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2788 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2789 iCur); 2790 iHiwtr = iCur = -1; 2791 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2792 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2793 iCur); 2794 } 2795 2796 if( pArg->pStmt ){ 2797 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2798 bReset); 2799 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2800 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2801 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2802 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2803 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2804 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2805 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2806 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); 2807 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2808 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2809 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2810 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2811 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2812 } 2813 2814#ifdef __linux__ 2815 displayLinuxIoStats(pArg->out); 2816#endif 2817 2818 /* Do not remove this machine readable comment: extra-stats-output-here */ 2819 2820 return 0; 2821} 2822 2823/* 2824** Display scan stats. 2825*/ 2826static void display_scanstats( 2827 sqlite3 *db, /* Database to query */ 2828 ShellState *pArg /* Pointer to ShellState */ 2829){ 2830#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2831 UNUSED_PARAMETER(db); 2832 UNUSED_PARAMETER(pArg); 2833#else 2834 int i, k, n, mx; 2835 raw_printf(pArg->out, "-------- scanstats --------\n"); 2836 mx = 0; 2837 for(k=0; k<=mx; k++){ 2838 double rEstLoop = 1.0; 2839 for(i=n=0; 1; i++){ 2840 sqlite3_stmt *p = pArg->pStmt; 2841 sqlite3_int64 nLoop, nVisit; 2842 double rEst; 2843 int iSid; 2844 const char *zExplain; 2845 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2846 break; 2847 } 2848 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2849 if( iSid>mx ) mx = iSid; 2850 if( iSid!=k ) continue; 2851 if( n==0 ){ 2852 rEstLoop = (double)nLoop; 2853 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2854 } 2855 n++; 2856 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2857 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2858 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2859 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2860 rEstLoop *= rEst; 2861 raw_printf(pArg->out, 2862 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2863 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2864 ); 2865 } 2866 } 2867 raw_printf(pArg->out, "---------------------------\n"); 2868#endif 2869} 2870 2871/* 2872** Parameter azArray points to a zero-terminated array of strings. zStr 2873** points to a single nul-terminated string. Return non-zero if zStr 2874** is equal, according to strcmp(), to any of the strings in the array. 2875** Otherwise, return zero. 2876*/ 2877static int str_in_array(const char *zStr, const char **azArray){ 2878 int i; 2879 for(i=0; azArray[i]; i++){ 2880 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2881 } 2882 return 0; 2883} 2884 2885/* 2886** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2887** and populate the ShellState.aiIndent[] array with the number of 2888** spaces each opcode should be indented before it is output. 2889** 2890** The indenting rules are: 2891** 2892** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2893** all opcodes that occur between the p2 jump destination and the opcode 2894** itself by 2 spaces. 2895** 2896** * For each "Goto", if the jump destination is earlier in the program 2897** and ends on one of: 2898** Yield SeekGt SeekLt RowSetRead Rewind 2899** or if the P1 parameter is one instead of zero, 2900** then indent all opcodes between the earlier instruction 2901** and "Goto" by 2 spaces. 2902*/ 2903static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2904 const char *zSql; /* The text of the SQL statement */ 2905 const char *z; /* Used to check if this is an EXPLAIN */ 2906 int *abYield = 0; /* True if op is an OP_Yield */ 2907 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2908 int iOp; /* Index of operation in p->aiIndent[] */ 2909 2910 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2911 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2912 "Rewind", 0 }; 2913 const char *azGoto[] = { "Goto", 0 }; 2914 2915 /* Try to figure out if this is really an EXPLAIN statement. If this 2916 ** cannot be verified, return early. */ 2917 if( sqlite3_column_count(pSql)!=8 ){ 2918 p->cMode = p->mode; 2919 return; 2920 } 2921 zSql = sqlite3_sql(pSql); 2922 if( zSql==0 ) return; 2923 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2924 if( sqlite3_strnicmp(z, "explain", 7) ){ 2925 p->cMode = p->mode; 2926 return; 2927 } 2928 2929 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2930 int i; 2931 int iAddr = sqlite3_column_int(pSql, 0); 2932 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2933 2934 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2935 ** p2 is an instruction address, set variable p2op to the index of that 2936 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2937 ** the current instruction is part of a sub-program generated by an 2938 ** SQL trigger or foreign key. */ 2939 int p2 = sqlite3_column_int(pSql, 3); 2940 int p2op = (p2 + (iOp-iAddr)); 2941 2942 /* Grow the p->aiIndent array as required */ 2943 if( iOp>=nAlloc ){ 2944 if( iOp==0 ){ 2945 /* Do further verfication that this is explain output. Abort if 2946 ** it is not */ 2947 static const char *explainCols[] = { 2948 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2949 int jj; 2950 for(jj=0; jj<ArraySize(explainCols); jj++){ 2951 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2952 p->cMode = p->mode; 2953 sqlite3_reset(pSql); 2954 return; 2955 } 2956 } 2957 } 2958 nAlloc += 100; 2959 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2960 if( p->aiIndent==0 ) shell_out_of_memory(); 2961 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2962 if( abYield==0 ) shell_out_of_memory(); 2963 } 2964 abYield[iOp] = str_in_array(zOp, azYield); 2965 p->aiIndent[iOp] = 0; 2966 p->nIndent = iOp+1; 2967 2968 if( str_in_array(zOp, azNext) ){ 2969 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2970 } 2971 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 2972 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 2973 ){ 2974 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2975 } 2976 } 2977 2978 p->iIndent = 0; 2979 sqlite3_free(abYield); 2980 sqlite3_reset(pSql); 2981} 2982 2983/* 2984** Free the array allocated by explain_data_prepare(). 2985*/ 2986static void explain_data_delete(ShellState *p){ 2987 sqlite3_free(p->aiIndent); 2988 p->aiIndent = 0; 2989 p->nIndent = 0; 2990 p->iIndent = 0; 2991} 2992 2993/* 2994** Disable and restore .wheretrace and .selecttrace settings. 2995*/ 2996static unsigned int savedSelectTrace; 2997static unsigned int savedWhereTrace; 2998static void disable_debug_trace_modes(void){ 2999 unsigned int zero = 0; 3000 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace); 3001 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero); 3002 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace); 3003 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero); 3004} 3005static void restore_debug_trace_modes(void){ 3006 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace); 3007 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace); 3008} 3009 3010/* Create the TEMP table used to store parameter bindings */ 3011static void bind_table_init(ShellState *p){ 3012 int wrSchema = 0; 3013 int defensiveMode = 0; 3014 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); 3015 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); 3016 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 3017 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 3018 sqlite3_exec(p->db, 3019 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 3020 " key TEXT PRIMARY KEY,\n" 3021 " value\n" 3022 ") WITHOUT ROWID;", 3023 0, 0, 0); 3024 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 3025 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); 3026} 3027 3028/* 3029** Bind parameters on a prepared statement. 3030** 3031** Parameter bindings are taken from a TEMP table of the form: 3032** 3033** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 3034** WITHOUT ROWID; 3035** 3036** No bindings occur if this table does not exist. The name of the table 3037** begins with "sqlite_" so that it will not collide with ordinary application 3038** tables. The table must be in the TEMP schema. 3039*/ 3040static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 3041 int nVar; 3042 int i; 3043 int rc; 3044 sqlite3_stmt *pQ = 0; 3045 3046 nVar = sqlite3_bind_parameter_count(pStmt); 3047 if( nVar==0 ) return; /* Nothing to do */ 3048 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 3049 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 3050 return; /* Parameter table does not exist */ 3051 } 3052 rc = sqlite3_prepare_v2(pArg->db, 3053 "SELECT value FROM temp.sqlite_parameters" 3054 " WHERE key=?1", -1, &pQ, 0); 3055 if( rc || pQ==0 ) return; 3056 for(i=1; i<=nVar; i++){ 3057 char zNum[30]; 3058 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 3059 if( zVar==0 ){ 3060 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 3061 zVar = zNum; 3062 } 3063 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 3064 if( sqlite3_step(pQ)==SQLITE_ROW ){ 3065 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 3066 }else{ 3067 sqlite3_bind_null(pStmt, i); 3068 } 3069 sqlite3_reset(pQ); 3070 } 3071 sqlite3_finalize(pQ); 3072} 3073 3074/* 3075** UTF8 box-drawing characters. Imagine box lines like this: 3076** 3077** 1 3078** | 3079** 4 --+-- 2 3080** | 3081** 3 3082** 3083** Each box characters has between 2 and 4 of the lines leading from 3084** the center. The characters are here identified by the numbers of 3085** their corresponding lines. 3086*/ 3087#define BOX_24 "\342\224\200" /* U+2500 --- */ 3088#define BOX_13 "\342\224\202" /* U+2502 | */ 3089#define BOX_23 "\342\224\214" /* U+250c ,- */ 3090#define BOX_34 "\342\224\220" /* U+2510 -, */ 3091#define BOX_12 "\342\224\224" /* U+2514 '- */ 3092#define BOX_14 "\342\224\230" /* U+2518 -' */ 3093#define BOX_123 "\342\224\234" /* U+251c |- */ 3094#define BOX_134 "\342\224\244" /* U+2524 -| */ 3095#define BOX_234 "\342\224\254" /* U+252c -,- */ 3096#define BOX_124 "\342\224\264" /* U+2534 -'- */ 3097#define BOX_1234 "\342\224\274" /* U+253c -|- */ 3098 3099/* Draw horizontal line N characters long using unicode box 3100** characters 3101*/ 3102static void print_box_line(FILE *out, int N){ 3103 const char zDash[] = 3104 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 3105 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24; 3106 const int nDash = sizeof(zDash) - 1; 3107 N *= 3; 3108 while( N>nDash ){ 3109 utf8_printf(out, zDash); 3110 N -= nDash; 3111 } 3112 utf8_printf(out, "%.*s", N, zDash); 3113} 3114 3115/* 3116** Draw a horizontal separator for a MODE_Box table. 3117*/ 3118static void print_box_row_separator( 3119 ShellState *p, 3120 int nArg, 3121 const char *zSep1, 3122 const char *zSep2, 3123 const char *zSep3 3124){ 3125 int i; 3126 if( nArg>0 ){ 3127 utf8_printf(p->out, "%s", zSep1); 3128 print_box_line(p->out, p->actualWidth[0]+2); 3129 for(i=1; i<nArg; i++){ 3130 utf8_printf(p->out, "%s", zSep2); 3131 print_box_line(p->out, p->actualWidth[i]+2); 3132 } 3133 utf8_printf(p->out, "%s", zSep3); 3134 } 3135 fputs("\n", p->out); 3136} 3137 3138 3139 3140/* 3141** Run a prepared statement and output the result in one of the 3142** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table, 3143** or MODE_Box. 3144** 3145** This is different from ordinary exec_prepared_stmt() in that 3146** it has to run the entire query and gather the results into memory 3147** first, in order to determine column widths, before providing 3148** any output. 3149*/ 3150static void exec_prepared_stmt_columnar( 3151 ShellState *p, /* Pointer to ShellState */ 3152 sqlite3_stmt *pStmt /* Statment to run */ 3153){ 3154 sqlite3_int64 nRow = 0; 3155 int nColumn = 0; 3156 char **azData = 0; 3157 sqlite3_int64 nAlloc = 0; 3158 const char *z; 3159 int rc; 3160 sqlite3_int64 i, nData; 3161 int j, nTotal, w, n; 3162 const char *colSep = 0; 3163 const char *rowSep = 0; 3164 3165 rc = sqlite3_step(pStmt); 3166 if( rc!=SQLITE_ROW ) return; 3167 nColumn = sqlite3_column_count(pStmt); 3168 nAlloc = nColumn*4; 3169 if( nAlloc<=0 ) nAlloc = 1; 3170 azData = sqlite3_malloc64( nAlloc*sizeof(char*) ); 3171 if( azData==0 ) shell_out_of_memory(); 3172 for(i=0; i<nColumn; i++){ 3173 azData[i] = strdup(sqlite3_column_name(pStmt,i)); 3174 } 3175 do{ 3176 if( (nRow+2)*nColumn >= nAlloc ){ 3177 nAlloc *= 2; 3178 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*)); 3179 if( azData==0 ) shell_out_of_memory(); 3180 } 3181 nRow++; 3182 for(i=0; i<nColumn; i++){ 3183 z = (const char*)sqlite3_column_text(pStmt,i); 3184 azData[nRow*nColumn + i] = z ? strdup(z) : 0; 3185 } 3186 }while( sqlite3_step(pStmt)==SQLITE_ROW ); 3187 if( nColumn>p->nWidth ){ 3188 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); 3189 if( p->colWidth==0 ) shell_out_of_memory(); 3190 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; 3191 p->nWidth = nColumn; 3192 p->actualWidth = &p->colWidth[nColumn]; 3193 } 3194 memset(p->actualWidth, 0, nColumn*sizeof(int)); 3195 for(i=0; i<nColumn; i++){ 3196 w = p->colWidth[i]; 3197 if( w<0 ) w = -w; 3198 p->actualWidth[i] = w; 3199 } 3200 nTotal = nColumn*(nRow+1); 3201 for(i=0; i<nTotal; i++){ 3202 z = azData[i]; 3203 if( z==0 ) z = p->nullValue; 3204 n = strlenChar(z); 3205 j = i%nColumn; 3206 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; 3207 } 3208 if( seenInterrupt ) goto columnar_end; 3209 if( nColumn==0 ) goto columnar_end; 3210 switch( p->cMode ){ 3211 case MODE_Column: { 3212 colSep = " "; 3213 rowSep = "\n"; 3214 if( p->showHeader ){ 3215 for(i=0; i<nColumn; i++){ 3216 w = p->actualWidth[i]; 3217 if( p->colWidth[i]<0 ) w = -w; 3218 utf8_width_print(p->out, w, azData[i]); 3219 fputs(i==nColumn-1?"\n":" ", p->out); 3220 } 3221 for(i=0; i<nColumn; i++){ 3222 print_dashes(p->out, p->actualWidth[i]); 3223 fputs(i==nColumn-1?"\n":" ", p->out); 3224 } 3225 } 3226 break; 3227 } 3228 case MODE_Table: { 3229 colSep = " | "; 3230 rowSep = " |\n"; 3231 print_row_separator(p, nColumn, "+"); 3232 fputs("| ", p->out); 3233 for(i=0; i<nColumn; i++){ 3234 w = p->actualWidth[i]; 3235 n = strlenChar(azData[i]); 3236 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3237 fputs(i==nColumn-1?" |\n":" | ", p->out); 3238 } 3239 print_row_separator(p, nColumn, "+"); 3240 break; 3241 } 3242 case MODE_Markdown: { 3243 colSep = " | "; 3244 rowSep = " |\n"; 3245 fputs("| ", p->out); 3246 for(i=0; i<nColumn; i++){ 3247 w = p->actualWidth[i]; 3248 n = strlenChar(azData[i]); 3249 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3250 fputs(i==nColumn-1?" |\n":" | ", p->out); 3251 } 3252 print_row_separator(p, nColumn, "|"); 3253 break; 3254 } 3255 case MODE_Box: { 3256 colSep = " " BOX_13 " "; 3257 rowSep = " " BOX_13 "\n"; 3258 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34); 3259 utf8_printf(p->out, BOX_13 " "); 3260 for(i=0; i<nColumn; i++){ 3261 w = p->actualWidth[i]; 3262 n = strlenChar(azData[i]); 3263 utf8_printf(p->out, "%*s%s%*s%s", 3264 (w-n)/2, "", azData[i], (w-n+1)/2, "", 3265 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); 3266 } 3267 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); 3268 break; 3269 } 3270 } 3271 for(i=nColumn, j=0; i<nTotal; i++, j++){ 3272 if( j==0 && p->cMode!=MODE_Column ){ 3273 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| "); 3274 } 3275 z = azData[i]; 3276 if( z==0 ) z = p->nullValue; 3277 w = p->actualWidth[j]; 3278 if( p->colWidth[j]<0 ) w = -w; 3279 utf8_width_print(p->out, w, z); 3280 if( j==nColumn-1 ){ 3281 utf8_printf(p->out, "%s", rowSep); 3282 j = -1; 3283 if( seenInterrupt ) goto columnar_end; 3284 }else{ 3285 utf8_printf(p->out, "%s", colSep); 3286 } 3287 } 3288 if( p->cMode==MODE_Table ){ 3289 print_row_separator(p, nColumn, "+"); 3290 }else if( p->cMode==MODE_Box ){ 3291 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14); 3292 } 3293columnar_end: 3294 if( seenInterrupt ){ 3295 utf8_printf(p->out, "Interrupt\n"); 3296 } 3297 nData = (nRow+1)*nColumn; 3298 for(i=0; i<nData; i++) free(azData[i]); 3299 sqlite3_free(azData); 3300} 3301 3302/* 3303** Run a prepared statement 3304*/ 3305static void exec_prepared_stmt( 3306 ShellState *pArg, /* Pointer to ShellState */ 3307 sqlite3_stmt *pStmt /* Statment to run */ 3308){ 3309 int rc; 3310 3311 if( pArg->cMode==MODE_Column 3312 || pArg->cMode==MODE_Table 3313 || pArg->cMode==MODE_Box 3314 || pArg->cMode==MODE_Markdown 3315 ){ 3316 exec_prepared_stmt_columnar(pArg, pStmt); 3317 return; 3318 } 3319 3320 /* perform the first step. this will tell us if we 3321 ** have a result set or not and how wide it is. 3322 */ 3323 rc = sqlite3_step(pStmt); 3324 /* if we have a result set... */ 3325 if( SQLITE_ROW == rc ){ 3326 /* allocate space for col name ptr, value ptr, and type */ 3327 int nCol = sqlite3_column_count(pStmt); 3328 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 3329 if( !pData ){ 3330 shell_out_of_memory(); 3331 }else{ 3332 char **azCols = (char **)pData; /* Names of result columns */ 3333 char **azVals = &azCols[nCol]; /* Results */ 3334 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 3335 int i, x; 3336 assert(sizeof(int) <= sizeof(char *)); 3337 /* save off ptrs to column names */ 3338 for(i=0; i<nCol; i++){ 3339 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 3340 } 3341 do{ 3342 /* extract the data and data types */ 3343 for(i=0; i<nCol; i++){ 3344 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 3345 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ 3346 azVals[i] = ""; 3347 }else{ 3348 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 3349 } 3350 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 3351 rc = SQLITE_NOMEM; 3352 break; /* from for */ 3353 } 3354 } /* end for */ 3355 3356 /* if data and types extracted successfully... */ 3357 if( SQLITE_ROW == rc ){ 3358 /* call the supplied callback with the result row data */ 3359 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 3360 rc = SQLITE_ABORT; 3361 }else{ 3362 rc = sqlite3_step(pStmt); 3363 } 3364 } 3365 } while( SQLITE_ROW == rc ); 3366 sqlite3_free(pData); 3367 if( pArg->cMode==MODE_Json ){ 3368 fputs("]\n", pArg->out); 3369 } 3370 } 3371 } 3372} 3373 3374#ifndef SQLITE_OMIT_VIRTUALTABLE 3375/* 3376** This function is called to process SQL if the previous shell command 3377** was ".expert". It passes the SQL in the second argument directly to 3378** the sqlite3expert object. 3379** 3380** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3381** code. In this case, (*pzErr) may be set to point to a buffer containing 3382** an English language error message. It is the responsibility of the 3383** caller to eventually free this buffer using sqlite3_free(). 3384*/ 3385static int expertHandleSQL( 3386 ShellState *pState, 3387 const char *zSql, 3388 char **pzErr 3389){ 3390 assert( pState->expert.pExpert ); 3391 assert( pzErr==0 || *pzErr==0 ); 3392 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 3393} 3394 3395/* 3396** This function is called either to silently clean up the object 3397** created by the ".expert" command (if bCancel==1), or to generate a 3398** report from it and then clean it up (if bCancel==0). 3399** 3400** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3401** code. In this case, (*pzErr) may be set to point to a buffer containing 3402** an English language error message. It is the responsibility of the 3403** caller to eventually free this buffer using sqlite3_free(). 3404*/ 3405static int expertFinish( 3406 ShellState *pState, 3407 int bCancel, 3408 char **pzErr 3409){ 3410 int rc = SQLITE_OK; 3411 sqlite3expert *p = pState->expert.pExpert; 3412 assert( p ); 3413 assert( bCancel || pzErr==0 || *pzErr==0 ); 3414 if( bCancel==0 ){ 3415 FILE *out = pState->out; 3416 int bVerbose = pState->expert.bVerbose; 3417 3418 rc = sqlite3_expert_analyze(p, pzErr); 3419 if( rc==SQLITE_OK ){ 3420 int nQuery = sqlite3_expert_count(p); 3421 int i; 3422 3423 if( bVerbose ){ 3424 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 3425 raw_printf(out, "-- Candidates -----------------------------\n"); 3426 raw_printf(out, "%s\n", zCand); 3427 } 3428 for(i=0; i<nQuery; i++){ 3429 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 3430 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 3431 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 3432 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 3433 if( bVerbose ){ 3434 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 3435 raw_printf(out, "%s\n\n", zSql); 3436 } 3437 raw_printf(out, "%s\n", zIdx); 3438 raw_printf(out, "%s\n", zEQP); 3439 } 3440 } 3441 } 3442 sqlite3_expert_destroy(p); 3443 pState->expert.pExpert = 0; 3444 return rc; 3445} 3446 3447/* 3448** Implementation of ".expert" dot command. 3449*/ 3450static int expertDotCommand( 3451 ShellState *pState, /* Current shell tool state */ 3452 char **azArg, /* Array of arguments passed to dot command */ 3453 int nArg /* Number of entries in azArg[] */ 3454){ 3455 int rc = SQLITE_OK; 3456 char *zErr = 0; 3457 int i; 3458 int iSample = 0; 3459 3460 assert( pState->expert.pExpert==0 ); 3461 memset(&pState->expert, 0, sizeof(ExpertInfo)); 3462 3463 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 3464 char *z = azArg[i]; 3465 int n; 3466 if( z[0]=='-' && z[1]=='-' ) z++; 3467 n = strlen30(z); 3468 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 3469 pState->expert.bVerbose = 1; 3470 } 3471 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 3472 if( i==(nArg-1) ){ 3473 raw_printf(stderr, "option requires an argument: %s\n", z); 3474 rc = SQLITE_ERROR; 3475 }else{ 3476 iSample = (int)integerValue(azArg[++i]); 3477 if( iSample<0 || iSample>100 ){ 3478 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 3479 rc = SQLITE_ERROR; 3480 } 3481 } 3482 } 3483 else{ 3484 raw_printf(stderr, "unknown option: %s\n", z); 3485 rc = SQLITE_ERROR; 3486 } 3487 } 3488 3489 if( rc==SQLITE_OK ){ 3490 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 3491 if( pState->expert.pExpert==0 ){ 3492 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); 3493 rc = SQLITE_ERROR; 3494 }else{ 3495 sqlite3_expert_config( 3496 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 3497 ); 3498 } 3499 } 3500 3501 return rc; 3502} 3503#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3504 3505/* 3506** Execute a statement or set of statements. Print 3507** any result rows/columns depending on the current mode 3508** set via the supplied callback. 3509** 3510** This is very similar to SQLite's built-in sqlite3_exec() 3511** function except it takes a slightly different callback 3512** and callback data argument. 3513*/ 3514static int shell_exec( 3515 ShellState *pArg, /* Pointer to ShellState */ 3516 const char *zSql, /* SQL to be evaluated */ 3517 char **pzErrMsg /* Error msg written here */ 3518){ 3519 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3520 int rc = SQLITE_OK; /* Return Code */ 3521 int rc2; 3522 const char *zLeftover; /* Tail of unprocessed SQL */ 3523 sqlite3 *db = pArg->db; 3524 3525 if( pzErrMsg ){ 3526 *pzErrMsg = NULL; 3527 } 3528 3529#ifndef SQLITE_OMIT_VIRTUALTABLE 3530 if( pArg->expert.pExpert ){ 3531 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3532 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3533 } 3534#endif 3535 3536 while( zSql[0] && (SQLITE_OK == rc) ){ 3537 static const char *zStmtSql; 3538 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3539 if( SQLITE_OK != rc ){ 3540 if( pzErrMsg ){ 3541 *pzErrMsg = save_err_msg(db); 3542 } 3543 }else{ 3544 if( !pStmt ){ 3545 /* this happens for a comment or white-space */ 3546 zSql = zLeftover; 3547 while( IsSpace(zSql[0]) ) zSql++; 3548 continue; 3549 } 3550 zStmtSql = sqlite3_sql(pStmt); 3551 if( zStmtSql==0 ) zStmtSql = ""; 3552 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3553 3554 /* save off the prepared statment handle and reset row count */ 3555 if( pArg ){ 3556 pArg->pStmt = pStmt; 3557 pArg->cnt = 0; 3558 } 3559 3560 /* echo the sql statement if echo on */ 3561 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3562 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3563 } 3564 3565 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3566 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3567 sqlite3_stmt *pExplain; 3568 char *zEQP; 3569 int triggerEQP = 0; 3570 disable_debug_trace_modes(); 3571 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3572 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3573 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3574 } 3575 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3576 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3577 if( rc==SQLITE_OK ){ 3578 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3579 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3580 int iEqpId = sqlite3_column_int(pExplain, 0); 3581 int iParentId = sqlite3_column_int(pExplain, 1); 3582 if( zEQPLine==0 ) zEQPLine = ""; 3583 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3584 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3585 } 3586 eqp_render(pArg); 3587 } 3588 sqlite3_finalize(pExplain); 3589 sqlite3_free(zEQP); 3590 if( pArg->autoEQP>=AUTOEQP_full ){ 3591 /* Also do an EXPLAIN for ".eqp full" mode */ 3592 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3593 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3594 if( rc==SQLITE_OK ){ 3595 pArg->cMode = MODE_Explain; 3596 explain_data_prepare(pArg, pExplain); 3597 exec_prepared_stmt(pArg, pExplain); 3598 explain_data_delete(pArg); 3599 } 3600 sqlite3_finalize(pExplain); 3601 sqlite3_free(zEQP); 3602 } 3603 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3604 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3605 /* Reprepare pStmt before reactiving trace modes */ 3606 sqlite3_finalize(pStmt); 3607 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3608 if( pArg ) pArg->pStmt = pStmt; 3609 } 3610 restore_debug_trace_modes(); 3611 } 3612 3613 if( pArg ){ 3614 pArg->cMode = pArg->mode; 3615 if( pArg->autoExplain ){ 3616 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3617 pArg->cMode = MODE_Explain; 3618 } 3619 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3620 pArg->cMode = MODE_EQP; 3621 } 3622 } 3623 3624 /* If the shell is currently in ".explain" mode, gather the extra 3625 ** data required to add indents to the output.*/ 3626 if( pArg->cMode==MODE_Explain ){ 3627 explain_data_prepare(pArg, pStmt); 3628 } 3629 } 3630 3631 bind_prepared_stmt(pArg, pStmt); 3632 exec_prepared_stmt(pArg, pStmt); 3633 explain_data_delete(pArg); 3634 eqp_render(pArg); 3635 3636 /* print usage stats if stats on */ 3637 if( pArg && pArg->statsOn ){ 3638 display_stats(db, pArg, 0); 3639 } 3640 3641 /* print loop-counters if required */ 3642 if( pArg && pArg->scanstatsOn ){ 3643 display_scanstats(db, pArg); 3644 } 3645 3646 /* Finalize the statement just executed. If this fails, save a 3647 ** copy of the error message. Otherwise, set zSql to point to the 3648 ** next statement to execute. */ 3649 rc2 = sqlite3_finalize(pStmt); 3650 if( rc!=SQLITE_NOMEM ) rc = rc2; 3651 if( rc==SQLITE_OK ){ 3652 zSql = zLeftover; 3653 while( IsSpace(zSql[0]) ) zSql++; 3654 }else if( pzErrMsg ){ 3655 *pzErrMsg = save_err_msg(db); 3656 } 3657 3658 /* clear saved stmt handle */ 3659 if( pArg ){ 3660 pArg->pStmt = NULL; 3661 } 3662 } 3663 } /* end while */ 3664 3665 return rc; 3666} 3667 3668/* 3669** Release memory previously allocated by tableColumnList(). 3670*/ 3671static void freeColumnList(char **azCol){ 3672 int i; 3673 for(i=1; azCol[i]; i++){ 3674 sqlite3_free(azCol[i]); 3675 } 3676 /* azCol[0] is a static string */ 3677 sqlite3_free(azCol); 3678} 3679 3680/* 3681** Return a list of pointers to strings which are the names of all 3682** columns in table zTab. The memory to hold the names is dynamically 3683** allocated and must be released by the caller using a subsequent call 3684** to freeColumnList(). 3685** 3686** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3687** value that needs to be preserved, then azCol[0] is filled in with the 3688** name of the rowid column. 3689** 3690** The first regular column in the table is azCol[1]. The list is terminated 3691** by an entry with azCol[i]==0. 3692*/ 3693static char **tableColumnList(ShellState *p, const char *zTab){ 3694 char **azCol = 0; 3695 sqlite3_stmt *pStmt; 3696 char *zSql; 3697 int nCol = 0; 3698 int nAlloc = 0; 3699 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3700 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3701 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3702 int rc; 3703 3704 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3705 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3706 sqlite3_free(zSql); 3707 if( rc ) return 0; 3708 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3709 if( nCol>=nAlloc-2 ){ 3710 nAlloc = nAlloc*2 + nCol + 10; 3711 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3712 if( azCol==0 ) shell_out_of_memory(); 3713 } 3714 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3715 if( sqlite3_column_int(pStmt, 5) ){ 3716 nPK++; 3717 if( nPK==1 3718 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3719 "INTEGER")==0 3720 ){ 3721 isIPK = 1; 3722 }else{ 3723 isIPK = 0; 3724 } 3725 } 3726 } 3727 sqlite3_finalize(pStmt); 3728 if( azCol==0 ) return 0; 3729 azCol[0] = 0; 3730 azCol[nCol+1] = 0; 3731 3732 /* The decision of whether or not a rowid really needs to be preserved 3733 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3734 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3735 ** rowids on tables where the rowid is inaccessible because there are other 3736 ** columns in the table named "rowid", "_rowid_", and "oid". 3737 */ 3738 if( preserveRowid && isIPK ){ 3739 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3740 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3741 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3742 ** ROWID aliases. To distinguish these cases, check to see if 3743 ** there is a "pk" entry in "PRAGMA index_list". There will be 3744 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3745 */ 3746 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3747 " WHERE origin='pk'", zTab); 3748 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3749 sqlite3_free(zSql); 3750 if( rc ){ 3751 freeColumnList(azCol); 3752 return 0; 3753 } 3754 rc = sqlite3_step(pStmt); 3755 sqlite3_finalize(pStmt); 3756 preserveRowid = rc==SQLITE_ROW; 3757 } 3758 if( preserveRowid ){ 3759 /* Only preserve the rowid if we can find a name to use for the 3760 ** rowid */ 3761 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3762 int i, j; 3763 for(j=0; j<3; j++){ 3764 for(i=1; i<=nCol; i++){ 3765 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3766 } 3767 if( i>nCol ){ 3768 /* At this point, we know that azRowid[j] is not the name of any 3769 ** ordinary column in the table. Verify that azRowid[j] is a valid 3770 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3771 ** tables will fail this last check */ 3772 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3773 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3774 break; 3775 } 3776 } 3777 } 3778 return azCol; 3779} 3780 3781/* 3782** Toggle the reverse_unordered_selects setting. 3783*/ 3784static void toggleSelectOrder(sqlite3 *db){ 3785 sqlite3_stmt *pStmt = 0; 3786 int iSetting = 0; 3787 char zStmt[100]; 3788 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3789 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3790 iSetting = sqlite3_column_int(pStmt, 0); 3791 } 3792 sqlite3_finalize(pStmt); 3793 sqlite3_snprintf(sizeof(zStmt), zStmt, 3794 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3795 sqlite3_exec(db, zStmt, 0, 0, 0); 3796} 3797 3798/* 3799** This is a different callback routine used for dumping the database. 3800** Each row received by this callback consists of a table name, 3801** the table type ("index" or "table") and SQL to create the table. 3802** This routine should print text sufficient to recreate the table. 3803*/ 3804static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3805 int rc; 3806 const char *zTable; 3807 const char *zType; 3808 const char *zSql; 3809 ShellState *p = (ShellState *)pArg; 3810 int dataOnly; 3811 int noSys; 3812 3813 UNUSED_PARAMETER(azNotUsed); 3814 if( nArg!=3 || azArg==0 ) return 0; 3815 zTable = azArg[0]; 3816 zType = azArg[1]; 3817 zSql = azArg[2]; 3818 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; 3819 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; 3820 3821 if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){ 3822 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3823 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){ 3824 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 3825 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3826 return 0; 3827 }else if( dataOnly ){ 3828 /* no-op */ 3829 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3830 char *zIns; 3831 if( !p->writableSchema ){ 3832 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3833 p->writableSchema = 1; 3834 } 3835 zIns = sqlite3_mprintf( 3836 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" 3837 "VALUES('table','%q','%q',0,'%q');", 3838 zTable, zTable, zSql); 3839 utf8_printf(p->out, "%s\n", zIns); 3840 sqlite3_free(zIns); 3841 return 0; 3842 }else{ 3843 printSchemaLine(p->out, zSql, ";\n"); 3844 } 3845 3846 if( strcmp(zType, "table")==0 ){ 3847 ShellText sSelect; 3848 ShellText sTable; 3849 char **azCol; 3850 int i; 3851 char *savedDestTable; 3852 int savedMode; 3853 3854 azCol = tableColumnList(p, zTable); 3855 if( azCol==0 ){ 3856 p->nErr++; 3857 return 0; 3858 } 3859 3860 /* Always quote the table name, even if it appears to be pure ascii, 3861 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3862 initText(&sTable); 3863 appendText(&sTable, zTable, quoteChar(zTable)); 3864 /* If preserving the rowid, add a column list after the table name. 3865 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3866 ** instead of the usual "INSERT INTO tab VALUES(...)". 3867 */ 3868 if( azCol[0] ){ 3869 appendText(&sTable, "(", 0); 3870 appendText(&sTable, azCol[0], 0); 3871 for(i=1; azCol[i]; i++){ 3872 appendText(&sTable, ",", 0); 3873 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3874 } 3875 appendText(&sTable, ")", 0); 3876 } 3877 3878 /* Build an appropriate SELECT statement */ 3879 initText(&sSelect); 3880 appendText(&sSelect, "SELECT ", 0); 3881 if( azCol[0] ){ 3882 appendText(&sSelect, azCol[0], 0); 3883 appendText(&sSelect, ",", 0); 3884 } 3885 for(i=1; azCol[i]; i++){ 3886 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3887 if( azCol[i+1] ){ 3888 appendText(&sSelect, ",", 0); 3889 } 3890 } 3891 freeColumnList(azCol); 3892 appendText(&sSelect, " FROM ", 0); 3893 appendText(&sSelect, zTable, quoteChar(zTable)); 3894 3895 savedDestTable = p->zDestTable; 3896 savedMode = p->mode; 3897 p->zDestTable = sTable.z; 3898 p->mode = p->cMode = MODE_Insert; 3899 rc = shell_exec(p, sSelect.z, 0); 3900 if( (rc&0xff)==SQLITE_CORRUPT ){ 3901 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3902 toggleSelectOrder(p->db); 3903 shell_exec(p, sSelect.z, 0); 3904 toggleSelectOrder(p->db); 3905 } 3906 p->zDestTable = savedDestTable; 3907 p->mode = savedMode; 3908 freeText(&sTable); 3909 freeText(&sSelect); 3910 if( rc ) p->nErr++; 3911 } 3912 return 0; 3913} 3914 3915/* 3916** Run zQuery. Use dump_callback() as the callback routine so that 3917** the contents of the query are output as SQL statements. 3918** 3919** If we get a SQLITE_CORRUPT error, rerun the query after appending 3920** "ORDER BY rowid DESC" to the end. 3921*/ 3922static int run_schema_dump_query( 3923 ShellState *p, 3924 const char *zQuery 3925){ 3926 int rc; 3927 char *zErr = 0; 3928 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3929 if( rc==SQLITE_CORRUPT ){ 3930 char *zQ2; 3931 int len = strlen30(zQuery); 3932 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3933 if( zErr ){ 3934 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3935 sqlite3_free(zErr); 3936 zErr = 0; 3937 } 3938 zQ2 = malloc( len+100 ); 3939 if( zQ2==0 ) return rc; 3940 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3941 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3942 if( rc ){ 3943 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3944 }else{ 3945 rc = SQLITE_CORRUPT; 3946 } 3947 sqlite3_free(zErr); 3948 free(zQ2); 3949 } 3950 return rc; 3951} 3952 3953/* 3954** Text of help messages. 3955** 3956** The help text for each individual command begins with a line that starts 3957** with ".". Subsequent lines are supplimental information. 3958** 3959** There must be two or more spaces between the end of the command and the 3960** start of the description of what that command does. 3961*/ 3962static const char *(azHelp[]) = { 3963#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 3964 ".archive ... Manage SQL archives", 3965 " Each command must have exactly one of the following options:", 3966 " -c, --create Create a new archive", 3967 " -u, --update Add or update files with changed mtime", 3968 " -i, --insert Like -u but always add even if unchanged", 3969 " -t, --list List contents of archive", 3970 " -x, --extract Extract files from archive", 3971 " Optional arguments:", 3972 " -v, --verbose Print each filename as it is processed", 3973 " -f FILE, --file FILE Use archive FILE (default is current db)", 3974 " -a FILE, --append FILE Open FILE using the apndvfs VFS", 3975 " -C DIR, --directory DIR Read/extract files from directory DIR", 3976 " -n, --dryrun Show the SQL that would have occurred", 3977 " Examples:", 3978 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", 3979 " .ar -tf ARCHIVE # List members of ARCHIVE", 3980 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", 3981 " See also:", 3982 " http://sqlite.org/cli.html#sqlite_archive_support", 3983#endif 3984#ifndef SQLITE_OMIT_AUTHORIZATION 3985 ".auth ON|OFF Show authorizer callbacks", 3986#endif 3987 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 3988 " --append Use the appendvfs", 3989 " --async Write to FILE without journal and fsync()", 3990 ".bail on|off Stop after hitting an error. Default OFF", 3991 ".binary on|off Turn binary output on or off. Default OFF", 3992 ".cd DIRECTORY Change the working directory to DIRECTORY", 3993 ".changes on|off Show number of rows changed by SQL", 3994 ".check GLOB Fail if output since .testcase does not match", 3995 ".clone NEWDB Clone data into NEWDB from the existing database", 3996 ".connection [close] [#] Open or close an auxiliary database connection", 3997 ".databases List names and files of attached databases", 3998 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 3999 ".dbinfo ?DB? Show status information about the database", 4000 ".dump ?OBJECTS? Render database content as SQL", 4001 " Options:", 4002 " --data-only Output only INSERT statements", 4003 " --newlines Allow unescaped newline characters in output", 4004 " --nosys Omit system tables (ex: \"sqlite_stat1\")", 4005 " --preserve-rowids Include ROWID values in the output", 4006 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump", 4007 " Additional LIKE patterns can be given in subsequent arguments", 4008 ".echo on|off Turn command echo on or off", 4009 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 4010 " Other Modes:", 4011#ifdef SQLITE_DEBUG 4012 " test Show raw EXPLAIN QUERY PLAN output", 4013 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", 4014#endif 4015 " trigger Like \"full\" but also show trigger bytecode", 4016 ".excel Display the output of next command in spreadsheet", 4017 " --bom Put a UTF8 byte-order mark on intermediate file", 4018 ".exit ?CODE? Exit this program with return-code CODE", 4019 ".expert EXPERIMENTAL. Suggest indexes for queries", 4020 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", 4021 ".filectrl CMD ... Run various sqlite3_file_control() operations", 4022 " --schema SCHEMA Use SCHEMA instead of \"main\"", 4023 " --help Show CMD details", 4024 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 4025 ".headers on|off Turn display of headers on or off", 4026 ".help ?-all? ?PATTERN? Show help text for PATTERN", 4027 ".import FILE TABLE Import data from FILE into TABLE", 4028 " Options:", 4029 " --ascii Use \\037 and \\036 as column and row separators", 4030 " --csv Use , and \\n as column and row separators", 4031 " --skip N Skip the first N rows of input", 4032 " -v \"Verbose\" - increase auxiliary output", 4033 " Notes:", 4034 " * If TABLE does not exist, it is created. The first row of input", 4035 " determines the column names.", 4036 " * If neither --csv or --ascii are used, the input mode is derived", 4037 " from the \".mode\" output mode", 4038 " * If FILE begins with \"|\" then it is a command that generates the", 4039 " input text.", 4040#ifndef SQLITE_OMIT_TEST_CONTROL 4041 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 4042#endif 4043 ".indexes ?TABLE? Show names of indexes", 4044 " If TABLE is specified, only show indexes for", 4045 " tables matching TABLE using the LIKE operator.", 4046#ifdef SQLITE_ENABLE_IOTRACE 4047 ".iotrace FILE Enable I/O diagnostic logging to FILE", 4048#endif 4049 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 4050 ".lint OPTIONS Report potential schema issues.", 4051 " Options:", 4052 " fkey-indexes Find missing foreign key indexes", 4053#ifndef SQLITE_OMIT_LOAD_EXTENSION 4054 ".load FILE ?ENTRY? Load an extension library", 4055#endif 4056 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 4057 ".mode MODE ?TABLE? Set output mode", 4058 " MODE is one of:", 4059 " ascii Columns/rows delimited by 0x1F and 0x1E", 4060 " box Tables using unicode box-drawing characters", 4061 " csv Comma-separated values", 4062 " column Output in columns. (See .width)", 4063 " html HTML <table> code", 4064 " insert SQL insert statements for TABLE", 4065 " json Results in a JSON array", 4066 " line One value per line", 4067 " list Values delimited by \"|\"", 4068 " markdown Markdown table format", 4069 " quote Escape answers as for SQL", 4070 " table ASCII-art table", 4071 " tabs Tab-separated values", 4072 " tcl TCL list elements", 4073 ".nonce STRING Disable safe mode for one command if the nonce matches", 4074 ".nullvalue STRING Use STRING in place of NULL values", 4075 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE", 4076 " If FILE begins with '|' then open as a pipe", 4077 " --bom Put a UTF8 byte-order mark at the beginning", 4078 " -e Send output to the system text editor", 4079 " -x Send output as CSV to a spreadsheet (same as \".excel\")", 4080#ifdef SQLITE_DEBUG 4081 ".oom ?--repeat M? ?N? Simulate an OOM error on the N-th allocation", 4082#endif 4083 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 4084 " Options:", 4085 " --append Use appendvfs to append database to the end of FILE", 4086#ifndef SQLITE_OMIT_DESERIALIZE 4087 " --deserialize Load into memory using sqlite3_deserialize()", 4088 " --hexdb Load the output of \"dbtotxt\" as an in-memory db", 4089 " --maxsize N Maximum size for --hexdb or --deserialized database", 4090#endif 4091 " --new Initialize FILE to an empty database", 4092 " --nofollow Do not follow symbolic links", 4093 " --readonly Open FILE readonly", 4094 " --zip FILE is a ZIP archive", 4095 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 4096 " If FILE begins with '|' then open it as a pipe.", 4097 " Options:", 4098 " --bom Prefix output with a UTF8 byte-order mark", 4099 " -e Send output to the system text editor", 4100 " -x Send output as CSV to a spreadsheet", 4101 ".parameter CMD ... Manage SQL parameter bindings", 4102 " clear Erase all bindings", 4103 " init Initialize the TEMP table that holds bindings", 4104 " list List the current parameter bindings", 4105 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 4106 " PARAMETER should start with one of: $ : @ ?", 4107 " unset PARAMETER Remove PARAMETER from the binding table", 4108 ".print STRING... Print literal STRING", 4109#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 4110 ".progress N Invoke progress handler after every N opcodes", 4111 " --limit N Interrupt after N progress callbacks", 4112 " --once Do no more than one progress interrupt", 4113 " --quiet|-q No output except at interrupts", 4114 " --reset Reset the count for each input and interrupt", 4115#endif 4116 ".prompt MAIN CONTINUE Replace the standard prompts", 4117 ".quit Exit this program", 4118 ".read FILE Read input from FILE", 4119#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4120 ".recover Recover as much data as possible from corrupt db.", 4121 " --freelist-corrupt Assume the freelist is corrupt", 4122 " --recovery-db NAME Store recovery metadata in database file NAME", 4123 " --lost-and-found TABLE Alternative name for the lost-and-found table", 4124 " --no-rowids Do not attempt to recover rowid values", 4125 " that are not also INTEGER PRIMARY KEYs", 4126#endif 4127 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 4128 ".save FILE Write in-memory database into FILE", 4129 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 4130 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 4131 " Options:", 4132 " --indent Try to pretty-print the schema", 4133 " --nosys Omit objects whose names start with \"sqlite_\"", 4134 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 4135 " Options:", 4136 " --init Create a new SELFTEST table", 4137 " -v Verbose output", 4138 ".separator COL ?ROW? Change the column and row separators", 4139#if defined(SQLITE_ENABLE_SESSION) 4140 ".session ?NAME? CMD ... Create or control sessions", 4141 " Subcommands:", 4142 " attach TABLE Attach TABLE", 4143 " changeset FILE Write a changeset into FILE", 4144 " close Close one session", 4145 " enable ?BOOLEAN? Set or query the enable bit", 4146 " filter GLOB... Reject tables matching GLOBs", 4147 " indirect ?BOOLEAN? Mark or query the indirect status", 4148 " isempty Query whether the session is empty", 4149 " list List currently open session names", 4150 " open DB NAME Open a new session on DB", 4151 " patchset FILE Write a patchset into FILE", 4152 " If ?NAME? is omitted, the first defined session is used.", 4153#endif 4154 ".sha3sum ... Compute a SHA3 hash of database content", 4155 " Options:", 4156 " --schema Also hash the sqlite_schema table", 4157 " --sha3-224 Use the sha3-224 algorithm", 4158 " --sha3-256 Use the sha3-256 algorithm (default)", 4159 " --sha3-384 Use the sha3-384 algorithm", 4160 " --sha3-512 Use the sha3-512 algorithm", 4161 " Any other argument is a LIKE pattern for tables to hash", 4162#ifndef SQLITE_NOHAVE_SYSTEM 4163 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 4164#endif 4165 ".show Show the current values for various settings", 4166 ".stats ?ARG? Show stats or turn stats on or off", 4167 " off Turn off automatic stat display", 4168 " on Turn on automatic stat display", 4169 " stmt Show statement stats", 4170 " vmstep Show the virtual machine step count only", 4171#ifndef SQLITE_NOHAVE_SYSTEM 4172 ".system CMD ARGS... Run CMD ARGS... in a system shell", 4173#endif 4174 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 4175 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 4176 ".testctrl CMD ... Run various sqlite3_test_control() operations", 4177 " Run \".testctrl\" with no arguments for details", 4178 ".timeout MS Try opening locked tables for MS milliseconds", 4179 ".timer on|off Turn SQL timer on or off", 4180#ifndef SQLITE_OMIT_TRACE 4181 ".trace ?OPTIONS? Output each SQL statement as it is run", 4182 " FILE Send output to FILE", 4183 " stdout Send output to stdout", 4184 " stderr Send output to stderr", 4185 " off Disable tracing", 4186 " --expanded Expand query parameters", 4187#ifdef SQLITE_ENABLE_NORMALIZE 4188 " --normalized Normal the SQL statements", 4189#endif 4190 " --plain Show SQL as it is input", 4191 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 4192 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 4193 " --row Trace each row (SQLITE_TRACE_ROW)", 4194 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 4195#endif /* SQLITE_OMIT_TRACE */ 4196#ifdef SQLITE_DEBUG 4197 ".unmodule NAME ... Unregister virtual table modules", 4198 " --allexcept Unregister everything except those named", 4199#endif 4200 ".vfsinfo ?AUX? Information about the top-level VFS", 4201 ".vfslist List all available VFSes", 4202 ".vfsname ?AUX? Print the name of the VFS stack", 4203 ".width NUM1 NUM2 ... Set minimum column widths for columnar output", 4204 " Negative values right-justify", 4205}; 4206 4207/* 4208** Output help text. 4209** 4210** zPattern describes the set of commands for which help text is provided. 4211** If zPattern is NULL, then show all commands, but only give a one-line 4212** description of each. 4213** 4214** Return the number of matches. 4215*/ 4216static int showHelp(FILE *out, const char *zPattern){ 4217 int i = 0; 4218 int j = 0; 4219 int n = 0; 4220 char *zPat; 4221 if( zPattern==0 4222 || zPattern[0]=='0' 4223 || strcmp(zPattern,"-a")==0 4224 || strcmp(zPattern,"-all")==0 4225 || strcmp(zPattern,"--all")==0 4226 ){ 4227 /* Show all commands, but only one line per command */ 4228 if( zPattern==0 ) zPattern = ""; 4229 for(i=0; i<ArraySize(azHelp); i++){ 4230 if( azHelp[i][0]=='.' || zPattern[0] ){ 4231 utf8_printf(out, "%s\n", azHelp[i]); 4232 n++; 4233 } 4234 } 4235 }else{ 4236 /* Look for commands that for which zPattern is an exact prefix */ 4237 zPat = sqlite3_mprintf(".%s*", zPattern); 4238 for(i=0; i<ArraySize(azHelp); i++){ 4239 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 4240 utf8_printf(out, "%s\n", azHelp[i]); 4241 j = i+1; 4242 n++; 4243 } 4244 } 4245 sqlite3_free(zPat); 4246 if( n ){ 4247 if( n==1 ){ 4248 /* when zPattern is a prefix of exactly one command, then include the 4249 ** details of that command, which should begin at offset j */ 4250 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 4251 utf8_printf(out, "%s\n", azHelp[j]); 4252 j++; 4253 } 4254 } 4255 return n; 4256 } 4257 /* Look for commands that contain zPattern anywhere. Show the complete 4258 ** text of all commands that match. */ 4259 zPat = sqlite3_mprintf("%%%s%%", zPattern); 4260 for(i=0; i<ArraySize(azHelp); i++){ 4261 if( azHelp[i][0]=='.' ) j = i; 4262 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 4263 utf8_printf(out, "%s\n", azHelp[j]); 4264 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 4265 j++; 4266 utf8_printf(out, "%s\n", azHelp[j]); 4267 } 4268 i = j; 4269 n++; 4270 } 4271 } 4272 sqlite3_free(zPat); 4273 } 4274 return n; 4275} 4276 4277/* Forward reference */ 4278static int process_input(ShellState *p); 4279 4280/* 4281** Read the content of file zName into memory obtained from sqlite3_malloc64() 4282** and return a pointer to the buffer. The caller is responsible for freeing 4283** the memory. 4284** 4285** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 4286** read. 4287** 4288** For convenience, a nul-terminator byte is always appended to the data read 4289** from the file before the buffer is returned. This byte is not included in 4290** the final value of (*pnByte), if applicable. 4291** 4292** NULL is returned if any error is encountered. The final value of *pnByte 4293** is undefined in this case. 4294*/ 4295static char *readFile(const char *zName, int *pnByte){ 4296 FILE *in = fopen(zName, "rb"); 4297 long nIn; 4298 size_t nRead; 4299 char *pBuf; 4300 if( in==0 ) return 0; 4301 fseek(in, 0, SEEK_END); 4302 nIn = ftell(in); 4303 rewind(in); 4304 pBuf = sqlite3_malloc64( nIn+1 ); 4305 if( pBuf==0 ){ fclose(in); return 0; } 4306 nRead = fread(pBuf, nIn, 1, in); 4307 fclose(in); 4308 if( nRead!=1 ){ 4309 sqlite3_free(pBuf); 4310 return 0; 4311 } 4312 pBuf[nIn] = 0; 4313 if( pnByte ) *pnByte = nIn; 4314 return pBuf; 4315} 4316 4317#if defined(SQLITE_ENABLE_SESSION) 4318/* 4319** Close a single OpenSession object and release all of its associated 4320** resources. 4321*/ 4322static void session_close(OpenSession *pSession){ 4323 int i; 4324 sqlite3session_delete(pSession->p); 4325 sqlite3_free(pSession->zName); 4326 for(i=0; i<pSession->nFilter; i++){ 4327 sqlite3_free(pSession->azFilter[i]); 4328 } 4329 sqlite3_free(pSession->azFilter); 4330 memset(pSession, 0, sizeof(OpenSession)); 4331} 4332#endif 4333 4334/* 4335** Close all OpenSession objects and release all associated resources. 4336*/ 4337#if defined(SQLITE_ENABLE_SESSION) 4338static void session_close_all(ShellState *p, int i){ 4339 int j; 4340 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; 4341 for(j=0; j<pAuxDb->nSession; j++){ 4342 session_close(&pAuxDb->aSession[j]); 4343 } 4344 pAuxDb->nSession = 0; 4345} 4346#else 4347# define session_close_all(X,Y) 4348#endif 4349 4350/* 4351** Implementation of the xFilter function for an open session. Omit 4352** any tables named by ".session filter" but let all other table through. 4353*/ 4354#if defined(SQLITE_ENABLE_SESSION) 4355static int session_filter(void *pCtx, const char *zTab){ 4356 OpenSession *pSession = (OpenSession*)pCtx; 4357 int i; 4358 for(i=0; i<pSession->nFilter; i++){ 4359 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 4360 } 4361 return 1; 4362} 4363#endif 4364 4365/* 4366** Try to deduce the type of file for zName based on its content. Return 4367** one of the SHELL_OPEN_* constants. 4368** 4369** If the file does not exist or is empty but its name looks like a ZIP 4370** archive and the dfltZip flag is true, then assume it is a ZIP archive. 4371** Otherwise, assume an ordinary database regardless of the filename if 4372** the type cannot be determined from content. 4373*/ 4374int deduceDatabaseType(const char *zName, int dfltZip){ 4375 FILE *f = fopen(zName, "rb"); 4376 size_t n; 4377 int rc = SHELL_OPEN_UNSPEC; 4378 char zBuf[100]; 4379 if( f==0 ){ 4380 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4381 return SHELL_OPEN_ZIPFILE; 4382 }else{ 4383 return SHELL_OPEN_NORMAL; 4384 } 4385 } 4386 n = fread(zBuf, 16, 1, f); 4387 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 4388 fclose(f); 4389 return SHELL_OPEN_NORMAL; 4390 } 4391 fseek(f, -25, SEEK_END); 4392 n = fread(zBuf, 25, 1, f); 4393 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 4394 rc = SHELL_OPEN_APPENDVFS; 4395 }else{ 4396 fseek(f, -22, SEEK_END); 4397 n = fread(zBuf, 22, 1, f); 4398 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 4399 && zBuf[3]==0x06 ){ 4400 rc = SHELL_OPEN_ZIPFILE; 4401 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4402 rc = SHELL_OPEN_ZIPFILE; 4403 } 4404 } 4405 fclose(f); 4406 return rc; 4407} 4408 4409#ifndef SQLITE_OMIT_DESERIALIZE 4410/* 4411** Reconstruct an in-memory database using the output from the "dbtotxt" 4412** program. Read content from the file in p->aAuxDb[].zDbFilename. 4413** If p->aAuxDb[].zDbFilename is 0, then read from standard input. 4414*/ 4415static unsigned char *readHexDb(ShellState *p, int *pnData){ 4416 unsigned char *a = 0; 4417 int nLine; 4418 int n = 0; 4419 int pgsz = 0; 4420 int iOffset = 0; 4421 int j, k; 4422 int rc; 4423 FILE *in; 4424 const char *zDbFilename = p->pAuxDb->zDbFilename; 4425 unsigned int x[16]; 4426 char zLine[1000]; 4427 if( zDbFilename ){ 4428 in = fopen(zDbFilename, "r"); 4429 if( in==0 ){ 4430 utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename); 4431 return 0; 4432 } 4433 nLine = 0; 4434 }else{ 4435 in = p->in; 4436 nLine = p->lineno; 4437 if( in==0 ) in = stdin; 4438 } 4439 *pnData = 0; 4440 nLine++; 4441 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 4442 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 4443 if( rc!=2 ) goto readHexDb_error; 4444 if( n<0 ) goto readHexDb_error; 4445 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 4446 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 4447 a = sqlite3_malloc( n ? n : 1 ); 4448 if( a==0 ){ 4449 utf8_printf(stderr, "Out of memory!\n"); 4450 goto readHexDb_error; 4451 } 4452 memset(a, 0, n); 4453 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 4454 utf8_printf(stderr, "invalid pagesize\n"); 4455 goto readHexDb_error; 4456 } 4457 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 4458 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 4459 if( rc==2 ){ 4460 iOffset = k; 4461 continue; 4462 } 4463 if( strncmp(zLine, "| end ", 6)==0 ){ 4464 break; 4465 } 4466 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 4467 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 4468 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 4469 if( rc==17 ){ 4470 k = iOffset+j; 4471 if( k+16<=n && k>=0 ){ 4472 int ii; 4473 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 4474 } 4475 } 4476 } 4477 *pnData = n; 4478 if( in!=p->in ){ 4479 fclose(in); 4480 }else{ 4481 p->lineno = nLine; 4482 } 4483 return a; 4484 4485readHexDb_error: 4486 if( in!=p->in ){ 4487 fclose(in); 4488 }else{ 4489 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 4490 nLine++; 4491 if(strncmp(zLine, "| end ", 6)==0 ) break; 4492 } 4493 p->lineno = nLine; 4494 } 4495 sqlite3_free(a); 4496 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 4497 return 0; 4498} 4499#endif /* SQLITE_OMIT_DESERIALIZE */ 4500 4501/* 4502** Scalar function "shell_int32". The first argument to this function 4503** must be a blob. The second a non-negative integer. This function 4504** reads and returns a 32-bit big-endian integer from byte 4505** offset (4*<arg2>) of the blob. 4506*/ 4507static void shellInt32( 4508 sqlite3_context *context, 4509 int argc, 4510 sqlite3_value **argv 4511){ 4512 const unsigned char *pBlob; 4513 int nBlob; 4514 int iInt; 4515 4516 UNUSED_PARAMETER(argc); 4517 nBlob = sqlite3_value_bytes(argv[0]); 4518 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 4519 iInt = sqlite3_value_int(argv[1]); 4520 4521 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 4522 const unsigned char *a = &pBlob[iInt*4]; 4523 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 4524 + ((sqlite3_int64)a[1]<<16) 4525 + ((sqlite3_int64)a[2]<< 8) 4526 + ((sqlite3_int64)a[3]<< 0); 4527 sqlite3_result_int64(context, iVal); 4528 } 4529} 4530 4531/* 4532** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 4533** using "..." with internal double-quote characters doubled. 4534*/ 4535static void shellIdQuote( 4536 sqlite3_context *context, 4537 int argc, 4538 sqlite3_value **argv 4539){ 4540 const char *zName = (const char*)sqlite3_value_text(argv[0]); 4541 UNUSED_PARAMETER(argc); 4542 if( zName ){ 4543 char *z = sqlite3_mprintf("\"%w\"", zName); 4544 sqlite3_result_text(context, z, -1, sqlite3_free); 4545 } 4546} 4547 4548/* 4549** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X. 4550*/ 4551static void shellUSleepFunc( 4552 sqlite3_context *context, 4553 int argcUnused, 4554 sqlite3_value **argv 4555){ 4556 int sleep = sqlite3_value_int(argv[0]); 4557 (void)argcUnused; 4558 sqlite3_sleep(sleep/1000); 4559 sqlite3_result_int(context, sleep); 4560} 4561 4562/* 4563** Scalar function "shell_escape_crnl" used by the .recover command. 4564** The argument passed to this function is the output of built-in 4565** function quote(). If the first character of the input is "'", 4566** indicating that the value passed to quote() was a text value, 4567** then this function searches the input for "\n" and "\r" characters 4568** and adds a wrapper similar to the following: 4569** 4570** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4571** 4572** Or, if the first character of the input is not "'", then a copy 4573** of the input is returned. 4574*/ 4575static void shellEscapeCrnl( 4576 sqlite3_context *context, 4577 int argc, 4578 sqlite3_value **argv 4579){ 4580 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4581 UNUSED_PARAMETER(argc); 4582 if( zText[0]=='\'' ){ 4583 int nText = sqlite3_value_bytes(argv[0]); 4584 int i; 4585 char zBuf1[20]; 4586 char zBuf2[20]; 4587 const char *zNL = 0; 4588 const char *zCR = 0; 4589 int nCR = 0; 4590 int nNL = 0; 4591 4592 for(i=0; zText[i]; i++){ 4593 if( zNL==0 && zText[i]=='\n' ){ 4594 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4595 nNL = (int)strlen(zNL); 4596 } 4597 if( zCR==0 && zText[i]=='\r' ){ 4598 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4599 nCR = (int)strlen(zCR); 4600 } 4601 } 4602 4603 if( zNL || zCR ){ 4604 int iOut = 0; 4605 i64 nMax = (nNL > nCR) ? nNL : nCR; 4606 i64 nAlloc = nMax * nText + (nMax+64)*2; 4607 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4608 if( zOut==0 ){ 4609 sqlite3_result_error_nomem(context); 4610 return; 4611 } 4612 4613 if( zNL && zCR ){ 4614 memcpy(&zOut[iOut], "replace(replace(", 16); 4615 iOut += 16; 4616 }else{ 4617 memcpy(&zOut[iOut], "replace(", 8); 4618 iOut += 8; 4619 } 4620 for(i=0; zText[i]; i++){ 4621 if( zText[i]=='\n' ){ 4622 memcpy(&zOut[iOut], zNL, nNL); 4623 iOut += nNL; 4624 }else if( zText[i]=='\r' ){ 4625 memcpy(&zOut[iOut], zCR, nCR); 4626 iOut += nCR; 4627 }else{ 4628 zOut[iOut] = zText[i]; 4629 iOut++; 4630 } 4631 } 4632 4633 if( zNL ){ 4634 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4635 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4636 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4637 } 4638 if( zCR ){ 4639 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4640 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4641 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4642 } 4643 4644 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4645 sqlite3_free(zOut); 4646 return; 4647 } 4648 } 4649 4650 sqlite3_result_value(context, argv[0]); 4651} 4652 4653/* Flags for open_db(). 4654** 4655** The default behavior of open_db() is to exit(1) if the database fails to 4656** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4657** but still returns without calling exit. 4658** 4659** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4660** ZIP archive if the file does not exist or is empty and its name matches 4661** the *.zip pattern. 4662*/ 4663#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4664#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4665 4666/* 4667** Make sure the database is open. If it is not, then open it. If 4668** the database fails to open, print an error message and exit. 4669*/ 4670static void open_db(ShellState *p, int openFlags){ 4671 if( p->db==0 ){ 4672 const char *zDbFilename = p->pAuxDb->zDbFilename; 4673 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4674 if( zDbFilename==0 || zDbFilename[0]==0 ){ 4675 p->openMode = SHELL_OPEN_NORMAL; 4676 }else{ 4677 p->openMode = (u8)deduceDatabaseType(zDbFilename, 4678 (openFlags & OPEN_DB_ZIPFILE)!=0); 4679 } 4680 } 4681 switch( p->openMode ){ 4682 case SHELL_OPEN_APPENDVFS: { 4683 sqlite3_open_v2(zDbFilename, &p->db, 4684 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); 4685 break; 4686 } 4687 case SHELL_OPEN_HEXDB: 4688 case SHELL_OPEN_DESERIALIZE: { 4689 sqlite3_open(0, &p->db); 4690 break; 4691 } 4692 case SHELL_OPEN_ZIPFILE: { 4693 sqlite3_open(":memory:", &p->db); 4694 break; 4695 } 4696 case SHELL_OPEN_READONLY: { 4697 sqlite3_open_v2(zDbFilename, &p->db, 4698 SQLITE_OPEN_READONLY|p->openFlags, 0); 4699 break; 4700 } 4701 case SHELL_OPEN_UNSPEC: 4702 case SHELL_OPEN_NORMAL: { 4703 sqlite3_open_v2(zDbFilename, &p->db, 4704 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); 4705 break; 4706 } 4707 } 4708 globalDb = p->db; 4709 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4710 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4711 zDbFilename, sqlite3_errmsg(p->db)); 4712 if( openFlags & OPEN_DB_KEEPALIVE ){ 4713 sqlite3_open(":memory:", &p->db); 4714 return; 4715 } 4716 exit(1); 4717 } 4718#ifndef SQLITE_OMIT_LOAD_EXTENSION 4719 sqlite3_enable_load_extension(p->db, 1); 4720#endif 4721 sqlite3_fileio_init(p->db, 0, 0); 4722 sqlite3_shathree_init(p->db, 0, 0); 4723 sqlite3_completion_init(p->db, 0, 0); 4724 sqlite3_uint_init(p->db, 0, 0); 4725 sqlite3_decimal_init(p->db, 0, 0); 4726 sqlite3_regexp_init(p->db, 0, 0); 4727 sqlite3_ieee_init(p->db, 0, 0); 4728 sqlite3_series_init(p->db, 0, 0); 4729#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4730 sqlite3_dbdata_init(p->db, 0, 0); 4731#endif 4732#ifdef SQLITE_HAVE_ZLIB 4733 sqlite3_zipfile_init(p->db, 0, 0); 4734 sqlite3_sqlar_init(p->db, 0, 0); 4735#endif 4736 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4737 shellAddSchemaName, 0, 0); 4738 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4739 shellModuleSchema, 0, 0); 4740 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4741 shellPutsFunc, 0, 0); 4742 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4743 shellEscapeCrnl, 0, 0); 4744 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4745 shellInt32, 0, 0); 4746 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 4747 shellIdQuote, 0, 0); 4748 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, 4749 shellUSleepFunc, 0, 0); 4750#ifndef SQLITE_NOHAVE_SYSTEM 4751 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4752 editFunc, 0, 0); 4753 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4754 editFunc, 0, 0); 4755#endif 4756 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4757 char *zSql = sqlite3_mprintf( 4758 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename); 4759 sqlite3_exec(p->db, zSql, 0, 0, 0); 4760 sqlite3_free(zSql); 4761 } 4762#ifndef SQLITE_OMIT_DESERIALIZE 4763 else 4764 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4765 int rc; 4766 int nData = 0; 4767 unsigned char *aData; 4768 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4769 aData = (unsigned char*)readFile(zDbFilename, &nData); 4770 }else{ 4771 aData = readHexDb(p, &nData); 4772 if( aData==0 ){ 4773 return; 4774 } 4775 } 4776 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4777 SQLITE_DESERIALIZE_RESIZEABLE | 4778 SQLITE_DESERIALIZE_FREEONCLOSE); 4779 if( rc ){ 4780 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4781 } 4782 if( p->szMax>0 ){ 4783 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4784 } 4785 } 4786#endif 4787 } 4788 if( p->bSafeModePersist && p->db!=0 ){ 4789 sqlite3_set_authorizer(p->db, safeModeAuth, p); 4790 } 4791} 4792 4793/* 4794** Attempt to close the databaes connection. Report errors. 4795*/ 4796void close_db(sqlite3 *db){ 4797 int rc = sqlite3_close(db); 4798 if( rc ){ 4799 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4800 rc, sqlite3_errmsg(db)); 4801 } 4802} 4803 4804#if HAVE_READLINE || HAVE_EDITLINE 4805/* 4806** Readline completion callbacks 4807*/ 4808static char *readline_completion_generator(const char *text, int state){ 4809 static sqlite3_stmt *pStmt = 0; 4810 char *zRet; 4811 if( state==0 ){ 4812 char *zSql; 4813 sqlite3_finalize(pStmt); 4814 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4815 " FROM completion(%Q) ORDER BY 1", text); 4816 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4817 sqlite3_free(zSql); 4818 } 4819 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4820 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); 4821 }else{ 4822 sqlite3_finalize(pStmt); 4823 pStmt = 0; 4824 zRet = 0; 4825 } 4826 return zRet; 4827} 4828static char **readline_completion(const char *zText, int iStart, int iEnd){ 4829 rl_attempted_completion_over = 1; 4830 return rl_completion_matches(zText, readline_completion_generator); 4831} 4832 4833#elif HAVE_LINENOISE 4834/* 4835** Linenoise completion callback 4836*/ 4837static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4838 int nLine = strlen30(zLine); 4839 int i, iStart; 4840 sqlite3_stmt *pStmt = 0; 4841 char *zSql; 4842 char zBuf[1000]; 4843 4844 if( nLine>sizeof(zBuf)-30 ) return; 4845 if( zLine[0]=='.' || zLine[0]=='#') return; 4846 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4847 if( i==nLine-1 ) return; 4848 iStart = i+1; 4849 memcpy(zBuf, zLine, iStart); 4850 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4851 " FROM completion(%Q,%Q) ORDER BY 1", 4852 &zLine[iStart], zLine); 4853 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4854 sqlite3_free(zSql); 4855 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4856 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4857 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4858 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4859 if( iStart+nCompletion < sizeof(zBuf)-1 ){ 4860 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4861 linenoiseAddCompletion(lc, zBuf); 4862 } 4863 } 4864 sqlite3_finalize(pStmt); 4865} 4866#endif 4867 4868/* 4869** Do C-language style dequoting. 4870** 4871** \a -> alarm 4872** \b -> backspace 4873** \t -> tab 4874** \n -> newline 4875** \v -> vertical tab 4876** \f -> form feed 4877** \r -> carriage return 4878** \s -> space 4879** \" -> " 4880** \' -> ' 4881** \\ -> backslash 4882** \NNN -> ascii character NNN in octal 4883*/ 4884static void resolve_backslashes(char *z){ 4885 int i, j; 4886 char c; 4887 while( *z && *z!='\\' ) z++; 4888 for(i=j=0; (c = z[i])!=0; i++, j++){ 4889 if( c=='\\' && z[i+1]!=0 ){ 4890 c = z[++i]; 4891 if( c=='a' ){ 4892 c = '\a'; 4893 }else if( c=='b' ){ 4894 c = '\b'; 4895 }else if( c=='t' ){ 4896 c = '\t'; 4897 }else if( c=='n' ){ 4898 c = '\n'; 4899 }else if( c=='v' ){ 4900 c = '\v'; 4901 }else if( c=='f' ){ 4902 c = '\f'; 4903 }else if( c=='r' ){ 4904 c = '\r'; 4905 }else if( c=='"' ){ 4906 c = '"'; 4907 }else if( c=='\'' ){ 4908 c = '\''; 4909 }else if( c=='\\' ){ 4910 c = '\\'; 4911 }else if( c>='0' && c<='7' ){ 4912 c -= '0'; 4913 if( z[i+1]>='0' && z[i+1]<='7' ){ 4914 i++; 4915 c = (c<<3) + z[i] - '0'; 4916 if( z[i+1]>='0' && z[i+1]<='7' ){ 4917 i++; 4918 c = (c<<3) + z[i] - '0'; 4919 } 4920 } 4921 } 4922 } 4923 z[j] = c; 4924 } 4925 if( j<i ) z[j] = 0; 4926} 4927 4928/* 4929** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4930** for TRUE and FALSE. Return the integer value if appropriate. 4931*/ 4932static int booleanValue(const char *zArg){ 4933 int i; 4934 if( zArg[0]=='0' && zArg[1]=='x' ){ 4935 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4936 }else{ 4937 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4938 } 4939 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4940 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4941 return 1; 4942 } 4943 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4944 return 0; 4945 } 4946 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4947 zArg); 4948 return 0; 4949} 4950 4951/* 4952** Set or clear a shell flag according to a boolean value. 4953*/ 4954static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4955 if( booleanValue(zArg) ){ 4956 ShellSetFlag(p, mFlag); 4957 }else{ 4958 ShellClearFlag(p, mFlag); 4959 } 4960} 4961 4962/* 4963** Close an output file, assuming it is not stderr or stdout 4964*/ 4965static void output_file_close(FILE *f){ 4966 if( f && f!=stdout && f!=stderr ) fclose(f); 4967} 4968 4969/* 4970** Try to open an output file. The names "stdout" and "stderr" are 4971** recognized and do the right thing. NULL is returned if the output 4972** filename is "off". 4973*/ 4974static FILE *output_file_open(const char *zFile, int bTextMode){ 4975 FILE *f; 4976 if( strcmp(zFile,"stdout")==0 ){ 4977 f = stdout; 4978 }else if( strcmp(zFile, "stderr")==0 ){ 4979 f = stderr; 4980 }else if( strcmp(zFile, "off")==0 ){ 4981 f = 0; 4982 }else{ 4983 f = fopen(zFile, bTextMode ? "w" : "wb"); 4984 if( f==0 ){ 4985 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 4986 } 4987 } 4988 return f; 4989} 4990 4991#ifndef SQLITE_OMIT_TRACE 4992/* 4993** A routine for handling output from sqlite3_trace(). 4994*/ 4995static int sql_trace_callback( 4996 unsigned mType, /* The trace type */ 4997 void *pArg, /* The ShellState pointer */ 4998 void *pP, /* Usually a pointer to sqlite_stmt */ 4999 void *pX /* Auxiliary output */ 5000){ 5001 ShellState *p = (ShellState*)pArg; 5002 sqlite3_stmt *pStmt; 5003 const char *zSql; 5004 int nSql; 5005 if( p->traceOut==0 ) return 0; 5006 if( mType==SQLITE_TRACE_CLOSE ){ 5007 utf8_printf(p->traceOut, "-- closing database connection\n"); 5008 return 0; 5009 } 5010 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 5011 zSql = (const char*)pX; 5012 }else{ 5013 pStmt = (sqlite3_stmt*)pP; 5014 switch( p->eTraceType ){ 5015 case SHELL_TRACE_EXPANDED: { 5016 zSql = sqlite3_expanded_sql(pStmt); 5017 break; 5018 } 5019#ifdef SQLITE_ENABLE_NORMALIZE 5020 case SHELL_TRACE_NORMALIZED: { 5021 zSql = sqlite3_normalized_sql(pStmt); 5022 break; 5023 } 5024#endif 5025 default: { 5026 zSql = sqlite3_sql(pStmt); 5027 break; 5028 } 5029 } 5030 } 5031 if( zSql==0 ) return 0; 5032 nSql = strlen30(zSql); 5033 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 5034 switch( mType ){ 5035 case SQLITE_TRACE_ROW: 5036 case SQLITE_TRACE_STMT: { 5037 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 5038 break; 5039 } 5040 case SQLITE_TRACE_PROFILE: { 5041 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 5042 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 5043 break; 5044 } 5045 } 5046 return 0; 5047} 5048#endif 5049 5050/* 5051** A no-op routine that runs with the ".breakpoint" doc-command. This is 5052** a useful spot to set a debugger breakpoint. 5053*/ 5054static void test_breakpoint(void){ 5055 static int nCall = 0; 5056 nCall++; 5057} 5058 5059/* 5060** An object used to read a CSV and other files for import. 5061*/ 5062typedef struct ImportCtx ImportCtx; 5063struct ImportCtx { 5064 const char *zFile; /* Name of the input file */ 5065 FILE *in; /* Read the CSV text from this input stream */ 5066 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */ 5067 char *z; /* Accumulated text for a field */ 5068 int n; /* Number of bytes in z */ 5069 int nAlloc; /* Space allocated for z[] */ 5070 int nLine; /* Current line number */ 5071 int nRow; /* Number of rows imported */ 5072 int nErr; /* Number of errors encountered */ 5073 int bNotFirst; /* True if one or more bytes already read */ 5074 int cTerm; /* Character that terminated the most recent field */ 5075 int cColSep; /* The column separator character. (Usually ",") */ 5076 int cRowSep; /* The row separator character. (Usually "\n") */ 5077}; 5078 5079/* Clean up resourced used by an ImportCtx */ 5080static void import_cleanup(ImportCtx *p){ 5081 if( p->in!=0 && p->xCloser!=0 ){ 5082 p->xCloser(p->in); 5083 p->in = 0; 5084 } 5085 sqlite3_free(p->z); 5086 p->z = 0; 5087} 5088 5089/* Append a single byte to z[] */ 5090static void import_append_char(ImportCtx *p, int c){ 5091 if( p->n+1>=p->nAlloc ){ 5092 p->nAlloc += p->nAlloc + 100; 5093 p->z = sqlite3_realloc64(p->z, p->nAlloc); 5094 if( p->z==0 ) shell_out_of_memory(); 5095 } 5096 p->z[p->n++] = (char)c; 5097} 5098 5099/* Read a single field of CSV text. Compatible with rfc4180 and extended 5100** with the option of having a separator other than ",". 5101** 5102** + Input comes from p->in. 5103** + Store results in p->z of length p->n. Space to hold p->z comes 5104** from sqlite3_malloc64(). 5105** + Use p->cSep as the column separator. The default is ",". 5106** + Use p->rSep as the row separator. The default is "\n". 5107** + Keep track of the line number in p->nLine. 5108** + Store the character that terminates the field in p->cTerm. Store 5109** EOF on end-of-file. 5110** + Report syntax errors on stderr 5111*/ 5112static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 5113 int c; 5114 int cSep = p->cColSep; 5115 int rSep = p->cRowSep; 5116 p->n = 0; 5117 c = fgetc(p->in); 5118 if( c==EOF || seenInterrupt ){ 5119 p->cTerm = EOF; 5120 return 0; 5121 } 5122 if( c=='"' ){ 5123 int pc, ppc; 5124 int startLine = p->nLine; 5125 int cQuote = c; 5126 pc = ppc = 0; 5127 while( 1 ){ 5128 c = fgetc(p->in); 5129 if( c==rSep ) p->nLine++; 5130 if( c==cQuote ){ 5131 if( pc==cQuote ){ 5132 pc = 0; 5133 continue; 5134 } 5135 } 5136 if( (c==cSep && pc==cQuote) 5137 || (c==rSep && pc==cQuote) 5138 || (c==rSep && pc=='\r' && ppc==cQuote) 5139 || (c==EOF && pc==cQuote) 5140 ){ 5141 do{ p->n--; }while( p->z[p->n]!=cQuote ); 5142 p->cTerm = c; 5143 break; 5144 } 5145 if( pc==cQuote && c!='\r' ){ 5146 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 5147 p->zFile, p->nLine, cQuote); 5148 } 5149 if( c==EOF ){ 5150 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 5151 p->zFile, startLine, cQuote); 5152 p->cTerm = c; 5153 break; 5154 } 5155 import_append_char(p, c); 5156 ppc = pc; 5157 pc = c; 5158 } 5159 }else{ 5160 /* If this is the first field being parsed and it begins with the 5161 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 5162 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 5163 import_append_char(p, c); 5164 c = fgetc(p->in); 5165 if( (c&0xff)==0xbb ){ 5166 import_append_char(p, c); 5167 c = fgetc(p->in); 5168 if( (c&0xff)==0xbf ){ 5169 p->bNotFirst = 1; 5170 p->n = 0; 5171 return csv_read_one_field(p); 5172 } 5173 } 5174 } 5175 while( c!=EOF && c!=cSep && c!=rSep ){ 5176 import_append_char(p, c); 5177 c = fgetc(p->in); 5178 } 5179 if( c==rSep ){ 5180 p->nLine++; 5181 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 5182 } 5183 p->cTerm = c; 5184 } 5185 if( p->z ) p->z[p->n] = 0; 5186 p->bNotFirst = 1; 5187 return p->z; 5188} 5189 5190/* Read a single field of ASCII delimited text. 5191** 5192** + Input comes from p->in. 5193** + Store results in p->z of length p->n. Space to hold p->z comes 5194** from sqlite3_malloc64(). 5195** + Use p->cSep as the column separator. The default is "\x1F". 5196** + Use p->rSep as the row separator. The default is "\x1E". 5197** + Keep track of the row number in p->nLine. 5198** + Store the character that terminates the field in p->cTerm. Store 5199** EOF on end-of-file. 5200** + Report syntax errors on stderr 5201*/ 5202static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 5203 int c; 5204 int cSep = p->cColSep; 5205 int rSep = p->cRowSep; 5206 p->n = 0; 5207 c = fgetc(p->in); 5208 if( c==EOF || seenInterrupt ){ 5209 p->cTerm = EOF; 5210 return 0; 5211 } 5212 while( c!=EOF && c!=cSep && c!=rSep ){ 5213 import_append_char(p, c); 5214 c = fgetc(p->in); 5215 } 5216 if( c==rSep ){ 5217 p->nLine++; 5218 } 5219 p->cTerm = c; 5220 if( p->z ) p->z[p->n] = 0; 5221 return p->z; 5222} 5223 5224/* 5225** Try to transfer data for table zTable. If an error is seen while 5226** moving forward, try to go backwards. The backwards movement won't 5227** work for WITHOUT ROWID tables. 5228*/ 5229static void tryToCloneData( 5230 ShellState *p, 5231 sqlite3 *newDb, 5232 const char *zTable 5233){ 5234 sqlite3_stmt *pQuery = 0; 5235 sqlite3_stmt *pInsert = 0; 5236 char *zQuery = 0; 5237 char *zInsert = 0; 5238 int rc; 5239 int i, j, n; 5240 int nTable = strlen30(zTable); 5241 int k = 0; 5242 int cnt = 0; 5243 const int spinRate = 10000; 5244 5245 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 5246 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5247 if( rc ){ 5248 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5249 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5250 zQuery); 5251 goto end_data_xfer; 5252 } 5253 n = sqlite3_column_count(pQuery); 5254 zInsert = sqlite3_malloc64(200 + nTable + n*3); 5255 if( zInsert==0 ) shell_out_of_memory(); 5256 sqlite3_snprintf(200+nTable,zInsert, 5257 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 5258 i = strlen30(zInsert); 5259 for(j=1; j<n; j++){ 5260 memcpy(zInsert+i, ",?", 2); 5261 i += 2; 5262 } 5263 memcpy(zInsert+i, ");", 3); 5264 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 5265 if( rc ){ 5266 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5267 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 5268 zQuery); 5269 goto end_data_xfer; 5270 } 5271 for(k=0; k<2; k++){ 5272 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5273 for(i=0; i<n; i++){ 5274 switch( sqlite3_column_type(pQuery, i) ){ 5275 case SQLITE_NULL: { 5276 sqlite3_bind_null(pInsert, i+1); 5277 break; 5278 } 5279 case SQLITE_INTEGER: { 5280 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 5281 break; 5282 } 5283 case SQLITE_FLOAT: { 5284 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 5285 break; 5286 } 5287 case SQLITE_TEXT: { 5288 sqlite3_bind_text(pInsert, i+1, 5289 (const char*)sqlite3_column_text(pQuery,i), 5290 -1, SQLITE_STATIC); 5291 break; 5292 } 5293 case SQLITE_BLOB: { 5294 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 5295 sqlite3_column_bytes(pQuery,i), 5296 SQLITE_STATIC); 5297 break; 5298 } 5299 } 5300 } /* End for */ 5301 rc = sqlite3_step(pInsert); 5302 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 5303 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 5304 sqlite3_errmsg(newDb)); 5305 } 5306 sqlite3_reset(pInsert); 5307 cnt++; 5308 if( (cnt%spinRate)==0 ){ 5309 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 5310 fflush(stdout); 5311 } 5312 } /* End while */ 5313 if( rc==SQLITE_DONE ) break; 5314 sqlite3_finalize(pQuery); 5315 sqlite3_free(zQuery); 5316 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 5317 zTable); 5318 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5319 if( rc ){ 5320 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 5321 break; 5322 } 5323 } /* End for(k=0...) */ 5324 5325end_data_xfer: 5326 sqlite3_finalize(pQuery); 5327 sqlite3_finalize(pInsert); 5328 sqlite3_free(zQuery); 5329 sqlite3_free(zInsert); 5330} 5331 5332 5333/* 5334** Try to transfer all rows of the schema that match zWhere. For 5335** each row, invoke xForEach() on the object defined by that row. 5336** If an error is encountered while moving forward through the 5337** sqlite_schema table, try again moving backwards. 5338*/ 5339static void tryToCloneSchema( 5340 ShellState *p, 5341 sqlite3 *newDb, 5342 const char *zWhere, 5343 void (*xForEach)(ShellState*,sqlite3*,const char*) 5344){ 5345 sqlite3_stmt *pQuery = 0; 5346 char *zQuery = 0; 5347 int rc; 5348 const unsigned char *zName; 5349 const unsigned char *zSql; 5350 char *zErrMsg = 0; 5351 5352 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5353 " WHERE %s", zWhere); 5354 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5355 if( rc ){ 5356 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5357 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5358 zQuery); 5359 goto end_schema_xfer; 5360 } 5361 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5362 zName = sqlite3_column_text(pQuery, 0); 5363 zSql = sqlite3_column_text(pQuery, 1); 5364 printf("%s... ", zName); fflush(stdout); 5365 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5366 if( zErrMsg ){ 5367 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5368 sqlite3_free(zErrMsg); 5369 zErrMsg = 0; 5370 } 5371 if( xForEach ){ 5372 xForEach(p, newDb, (const char*)zName); 5373 } 5374 printf("done\n"); 5375 } 5376 if( rc!=SQLITE_DONE ){ 5377 sqlite3_finalize(pQuery); 5378 sqlite3_free(zQuery); 5379 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5380 " WHERE %s ORDER BY rowid DESC", zWhere); 5381 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5382 if( rc ){ 5383 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5384 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5385 zQuery); 5386 goto end_schema_xfer; 5387 } 5388 while( sqlite3_step(pQuery)==SQLITE_ROW ){ 5389 zName = sqlite3_column_text(pQuery, 0); 5390 zSql = sqlite3_column_text(pQuery, 1); 5391 printf("%s... ", zName); fflush(stdout); 5392 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5393 if( zErrMsg ){ 5394 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5395 sqlite3_free(zErrMsg); 5396 zErrMsg = 0; 5397 } 5398 if( xForEach ){ 5399 xForEach(p, newDb, (const char*)zName); 5400 } 5401 printf("done\n"); 5402 } 5403 } 5404end_schema_xfer: 5405 sqlite3_finalize(pQuery); 5406 sqlite3_free(zQuery); 5407} 5408 5409/* 5410** Open a new database file named "zNewDb". Try to recover as much information 5411** as possible out of the main database (which might be corrupt) and write it 5412** into zNewDb. 5413*/ 5414static void tryToClone(ShellState *p, const char *zNewDb){ 5415 int rc; 5416 sqlite3 *newDb = 0; 5417 if( access(zNewDb,0)==0 ){ 5418 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 5419 return; 5420 } 5421 rc = sqlite3_open(zNewDb, &newDb); 5422 if( rc ){ 5423 utf8_printf(stderr, "Cannot create output database: %s\n", 5424 sqlite3_errmsg(newDb)); 5425 }else{ 5426 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 5427 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 5428 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 5429 tryToCloneSchema(p, newDb, "type!='table'", 0); 5430 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 5431 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 5432 } 5433 close_db(newDb); 5434} 5435 5436/* 5437** Change the output file back to stdout. 5438** 5439** If the p->doXdgOpen flag is set, that means the output was being 5440** redirected to a temporary file named by p->zTempFile. In that case, 5441** launch start/open/xdg-open on that temporary file. 5442*/ 5443static void output_reset(ShellState *p){ 5444 if( p->outfile[0]=='|' ){ 5445#ifndef SQLITE_OMIT_POPEN 5446 pclose(p->out); 5447#endif 5448 }else{ 5449 output_file_close(p->out); 5450#ifndef SQLITE_NOHAVE_SYSTEM 5451 if( p->doXdgOpen ){ 5452 const char *zXdgOpenCmd = 5453#if defined(_WIN32) 5454 "start"; 5455#elif defined(__APPLE__) 5456 "open"; 5457#else 5458 "xdg-open"; 5459#endif 5460 char *zCmd; 5461 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 5462 if( system(zCmd) ){ 5463 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 5464 }else{ 5465 /* Give the start/open/xdg-open command some time to get 5466 ** going before we continue, and potential delete the 5467 ** p->zTempFile data file out from under it */ 5468 sqlite3_sleep(2000); 5469 } 5470 sqlite3_free(zCmd); 5471 outputModePop(p); 5472 p->doXdgOpen = 0; 5473 } 5474#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 5475 } 5476 p->outfile[0] = 0; 5477 p->out = stdout; 5478} 5479 5480/* 5481** Run an SQL command and return the single integer result. 5482*/ 5483static int db_int(ShellState *p, const char *zSql){ 5484 sqlite3_stmt *pStmt; 5485 int res = 0; 5486 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 5487 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 5488 res = sqlite3_column_int(pStmt,0); 5489 } 5490 sqlite3_finalize(pStmt); 5491 return res; 5492} 5493 5494/* 5495** Convert a 2-byte or 4-byte big-endian integer into a native integer 5496*/ 5497static unsigned int get2byteInt(unsigned char *a){ 5498 return (a[0]<<8) + a[1]; 5499} 5500static unsigned int get4byteInt(unsigned char *a){ 5501 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 5502} 5503 5504/* 5505** Implementation of the ".dbinfo" command. 5506** 5507** Return 1 on error, 2 to exit, and 0 otherwise. 5508*/ 5509static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 5510 static const struct { const char *zName; int ofst; } aField[] = { 5511 { "file change counter:", 24 }, 5512 { "database page count:", 28 }, 5513 { "freelist page count:", 36 }, 5514 { "schema cookie:", 40 }, 5515 { "schema format:", 44 }, 5516 { "default cache size:", 48 }, 5517 { "autovacuum top root:", 52 }, 5518 { "incremental vacuum:", 64 }, 5519 { "text encoding:", 56 }, 5520 { "user version:", 60 }, 5521 { "application id:", 68 }, 5522 { "software version:", 96 }, 5523 }; 5524 static const struct { const char *zName; const char *zSql; } aQuery[] = { 5525 { "number of tables:", 5526 "SELECT count(*) FROM %s WHERE type='table'" }, 5527 { "number of indexes:", 5528 "SELECT count(*) FROM %s WHERE type='index'" }, 5529 { "number of triggers:", 5530 "SELECT count(*) FROM %s WHERE type='trigger'" }, 5531 { "number of views:", 5532 "SELECT count(*) FROM %s WHERE type='view'" }, 5533 { "schema size:", 5534 "SELECT total(length(sql)) FROM %s" }, 5535 }; 5536 int i, rc; 5537 unsigned iDataVersion; 5538 char *zSchemaTab; 5539 char *zDb = nArg>=2 ? azArg[1] : "main"; 5540 sqlite3_stmt *pStmt = 0; 5541 unsigned char aHdr[100]; 5542 open_db(p, 0); 5543 if( p->db==0 ) return 1; 5544 rc = sqlite3_prepare_v2(p->db, 5545 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 5546 -1, &pStmt, 0); 5547 if( rc ){ 5548 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 5549 sqlite3_finalize(pStmt); 5550 return 1; 5551 } 5552 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 5553 if( sqlite3_step(pStmt)==SQLITE_ROW 5554 && sqlite3_column_bytes(pStmt,0)>100 5555 ){ 5556 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 5557 sqlite3_finalize(pStmt); 5558 }else{ 5559 raw_printf(stderr, "unable to read database header\n"); 5560 sqlite3_finalize(pStmt); 5561 return 1; 5562 } 5563 i = get2byteInt(aHdr+16); 5564 if( i==1 ) i = 65536; 5565 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 5566 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 5567 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 5568 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 5569 for(i=0; i<ArraySize(aField); i++){ 5570 int ofst = aField[i].ofst; 5571 unsigned int val = get4byteInt(aHdr + ofst); 5572 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 5573 switch( ofst ){ 5574 case 56: { 5575 if( val==1 ) raw_printf(p->out, " (utf8)"); 5576 if( val==2 ) raw_printf(p->out, " (utf16le)"); 5577 if( val==3 ) raw_printf(p->out, " (utf16be)"); 5578 } 5579 } 5580 raw_printf(p->out, "\n"); 5581 } 5582 if( zDb==0 ){ 5583 zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); 5584 }else if( strcmp(zDb,"temp")==0 ){ 5585 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); 5586 }else{ 5587 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); 5588 } 5589 for(i=0; i<ArraySize(aQuery); i++){ 5590 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 5591 int val = db_int(p, zSql); 5592 sqlite3_free(zSql); 5593 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 5594 } 5595 sqlite3_free(zSchemaTab); 5596 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 5597 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 5598 return 0; 5599} 5600 5601/* 5602** Print the current sqlite3_errmsg() value to stderr and return 1. 5603*/ 5604static int shellDatabaseError(sqlite3 *db){ 5605 const char *zErr = sqlite3_errmsg(db); 5606 utf8_printf(stderr, "Error: %s\n", zErr); 5607 return 1; 5608} 5609 5610/* 5611** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 5612** if they match and FALSE (0) if they do not match. 5613** 5614** Globbing rules: 5615** 5616** '*' Matches any sequence of zero or more characters. 5617** 5618** '?' Matches exactly one character. 5619** 5620** [...] Matches one character from the enclosed list of 5621** characters. 5622** 5623** [^...] Matches one character not in the enclosed list. 5624** 5625** '#' Matches any sequence of one or more digits with an 5626** optional + or - sign in front 5627** 5628** ' ' Any span of whitespace matches any other span of 5629** whitespace. 5630** 5631** Extra whitespace at the end of z[] is ignored. 5632*/ 5633static int testcase_glob(const char *zGlob, const char *z){ 5634 int c, c2; 5635 int invert; 5636 int seen; 5637 5638 while( (c = (*(zGlob++)))!=0 ){ 5639 if( IsSpace(c) ){ 5640 if( !IsSpace(*z) ) return 0; 5641 while( IsSpace(*zGlob) ) zGlob++; 5642 while( IsSpace(*z) ) z++; 5643 }else if( c=='*' ){ 5644 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5645 if( c=='?' && (*(z++))==0 ) return 0; 5646 } 5647 if( c==0 ){ 5648 return 1; 5649 }else if( c=='[' ){ 5650 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5651 z++; 5652 } 5653 return (*z)!=0; 5654 } 5655 while( (c2 = (*(z++)))!=0 ){ 5656 while( c2!=c ){ 5657 c2 = *(z++); 5658 if( c2==0 ) return 0; 5659 } 5660 if( testcase_glob(zGlob,z) ) return 1; 5661 } 5662 return 0; 5663 }else if( c=='?' ){ 5664 if( (*(z++))==0 ) return 0; 5665 }else if( c=='[' ){ 5666 int prior_c = 0; 5667 seen = 0; 5668 invert = 0; 5669 c = *(z++); 5670 if( c==0 ) return 0; 5671 c2 = *(zGlob++); 5672 if( c2=='^' ){ 5673 invert = 1; 5674 c2 = *(zGlob++); 5675 } 5676 if( c2==']' ){ 5677 if( c==']' ) seen = 1; 5678 c2 = *(zGlob++); 5679 } 5680 while( c2 && c2!=']' ){ 5681 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5682 c2 = *(zGlob++); 5683 if( c>=prior_c && c<=c2 ) seen = 1; 5684 prior_c = 0; 5685 }else{ 5686 if( c==c2 ){ 5687 seen = 1; 5688 } 5689 prior_c = c2; 5690 } 5691 c2 = *(zGlob++); 5692 } 5693 if( c2==0 || (seen ^ invert)==0 ) return 0; 5694 }else if( c=='#' ){ 5695 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5696 if( !IsDigit(z[0]) ) return 0; 5697 z++; 5698 while( IsDigit(z[0]) ){ z++; } 5699 }else{ 5700 if( c!=(*(z++)) ) return 0; 5701 } 5702 } 5703 while( IsSpace(*z) ){ z++; } 5704 return *z==0; 5705} 5706 5707 5708/* 5709** Compare the string as a command-line option with either one or two 5710** initial "-" characters. 5711*/ 5712static int optionMatch(const char *zStr, const char *zOpt){ 5713 if( zStr[0]!='-' ) return 0; 5714 zStr++; 5715 if( zStr[0]=='-' ) zStr++; 5716 return strcmp(zStr, zOpt)==0; 5717} 5718 5719/* 5720** Delete a file. 5721*/ 5722int shellDeleteFile(const char *zFilename){ 5723 int rc; 5724#ifdef _WIN32 5725 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5726 rc = _wunlink(z); 5727 sqlite3_free(z); 5728#else 5729 rc = unlink(zFilename); 5730#endif 5731 return rc; 5732} 5733 5734/* 5735** Try to delete the temporary file (if there is one) and free the 5736** memory used to hold the name of the temp file. 5737*/ 5738static void clearTempFile(ShellState *p){ 5739 if( p->zTempFile==0 ) return; 5740 if( p->doXdgOpen ) return; 5741 if( shellDeleteFile(p->zTempFile) ) return; 5742 sqlite3_free(p->zTempFile); 5743 p->zTempFile = 0; 5744} 5745 5746/* 5747** Create a new temp file name with the given suffix. 5748*/ 5749static void newTempFile(ShellState *p, const char *zSuffix){ 5750 clearTempFile(p); 5751 sqlite3_free(p->zTempFile); 5752 p->zTempFile = 0; 5753 if( p->db ){ 5754 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5755 } 5756 if( p->zTempFile==0 ){ 5757 /* If p->db is an in-memory database then the TEMPFILENAME file-control 5758 ** will not work and we will need to fallback to guessing */ 5759 char *zTemp; 5760 sqlite3_uint64 r; 5761 sqlite3_randomness(sizeof(r), &r); 5762 zTemp = getenv("TEMP"); 5763 if( zTemp==0 ) zTemp = getenv("TMP"); 5764 if( zTemp==0 ){ 5765#ifdef _WIN32 5766 zTemp = "\\tmp"; 5767#else 5768 zTemp = "/tmp"; 5769#endif 5770 } 5771 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); 5772 }else{ 5773 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5774 } 5775 if( p->zTempFile==0 ){ 5776 shell_out_of_memory(); 5777 } 5778} 5779 5780 5781/* 5782** The implementation of SQL scalar function fkey_collate_clause(), used 5783** by the ".lint fkey-indexes" command. This scalar function is always 5784** called with four arguments - the parent table name, the parent column name, 5785** the child table name and the child column name. 5786** 5787** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5788** 5789** If either of the named tables or columns do not exist, this function 5790** returns an empty string. An empty string is also returned if both tables 5791** and columns exist but have the same default collation sequence. Or, 5792** if both exist but the default collation sequences are different, this 5793** function returns the string " COLLATE <parent-collation>", where 5794** <parent-collation> is the default collation sequence of the parent column. 5795*/ 5796static void shellFkeyCollateClause( 5797 sqlite3_context *pCtx, 5798 int nVal, 5799 sqlite3_value **apVal 5800){ 5801 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5802 const char *zParent; 5803 const char *zParentCol; 5804 const char *zParentSeq; 5805 const char *zChild; 5806 const char *zChildCol; 5807 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5808 int rc; 5809 5810 assert( nVal==4 ); 5811 zParent = (const char*)sqlite3_value_text(apVal[0]); 5812 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5813 zChild = (const char*)sqlite3_value_text(apVal[2]); 5814 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5815 5816 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5817 rc = sqlite3_table_column_metadata( 5818 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5819 ); 5820 if( rc==SQLITE_OK ){ 5821 rc = sqlite3_table_column_metadata( 5822 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5823 ); 5824 } 5825 5826 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5827 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5828 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5829 sqlite3_free(z); 5830 } 5831} 5832 5833 5834/* 5835** The implementation of dot-command ".lint fkey-indexes". 5836*/ 5837static int lintFkeyIndexes( 5838 ShellState *pState, /* Current shell tool state */ 5839 char **azArg, /* Array of arguments passed to dot command */ 5840 int nArg /* Number of entries in azArg[] */ 5841){ 5842 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5843 FILE *out = pState->out; /* Stream to write non-error output to */ 5844 int bVerbose = 0; /* If -verbose is present */ 5845 int bGroupByParent = 0; /* If -groupbyparent is present */ 5846 int i; /* To iterate through azArg[] */ 5847 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5848 int rc; /* Return code */ 5849 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5850 5851 /* 5852 ** This SELECT statement returns one row for each foreign key constraint 5853 ** in the schema of the main database. The column values are: 5854 ** 5855 ** 0. The text of an SQL statement similar to: 5856 ** 5857 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5858 ** 5859 ** This SELECT is similar to the one that the foreign keys implementation 5860 ** needs to run internally on child tables. If there is an index that can 5861 ** be used to optimize this query, then it can also be used by the FK 5862 ** implementation to optimize DELETE or UPDATE statements on the parent 5863 ** table. 5864 ** 5865 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5866 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5867 ** contains an index that can be used to optimize the query. 5868 ** 5869 ** 2. Human readable text that describes the child table and columns. e.g. 5870 ** 5871 ** "child_table(child_key1, child_key2)" 5872 ** 5873 ** 3. Human readable text that describes the parent table and columns. e.g. 5874 ** 5875 ** "parent_table(parent_key1, parent_key2)" 5876 ** 5877 ** 4. A full CREATE INDEX statement for an index that could be used to 5878 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5879 ** 5880 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5881 ** 5882 ** 5. The name of the parent table. 5883 ** 5884 ** These six values are used by the C logic below to generate the report. 5885 */ 5886 const char *zSql = 5887 "SELECT " 5888 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5889 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5890 " || fkey_collate_clause(" 5891 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5892 ", " 5893 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('" 5894 " || group_concat('*=?', ' AND ') || ')'" 5895 ", " 5896 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5897 ", " 5898 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5899 ", " 5900 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5901 " || ' ON ' || quote(s.name) || '('" 5902 " || group_concat(quote(f.[from]) ||" 5903 " fkey_collate_clause(" 5904 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5905 " || ');'" 5906 ", " 5907 " f.[table] " 5908 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " 5909 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5910 "GROUP BY s.name, f.id " 5911 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5912 ; 5913 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)"; 5914 5915 for(i=2; i<nArg; i++){ 5916 int n = strlen30(azArg[i]); 5917 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5918 bVerbose = 1; 5919 } 5920 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5921 bGroupByParent = 1; 5922 zIndent = " "; 5923 } 5924 else{ 5925 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5926 azArg[0], azArg[1] 5927 ); 5928 return SQLITE_ERROR; 5929 } 5930 } 5931 5932 /* Register the fkey_collate_clause() SQL function */ 5933 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5934 0, shellFkeyCollateClause, 0, 0 5935 ); 5936 5937 5938 if( rc==SQLITE_OK ){ 5939 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5940 } 5941 if( rc==SQLITE_OK ){ 5942 sqlite3_bind_int(pSql, 1, bGroupByParent); 5943 } 5944 5945 if( rc==SQLITE_OK ){ 5946 int rc2; 5947 char *zPrev = 0; 5948 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5949 int res = -1; 5950 sqlite3_stmt *pExplain = 0; 5951 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5952 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 5953 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 5954 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 5955 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 5956 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 5957 5958 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 5959 if( rc!=SQLITE_OK ) break; 5960 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 5961 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 5962 res = ( 5963 0==sqlite3_strglob(zGlob, zPlan) 5964 || 0==sqlite3_strglob(zGlobIPK, zPlan) 5965 ); 5966 } 5967 rc = sqlite3_finalize(pExplain); 5968 if( rc!=SQLITE_OK ) break; 5969 5970 if( res<0 ){ 5971 raw_printf(stderr, "Error: internal error"); 5972 break; 5973 }else{ 5974 if( bGroupByParent 5975 && (bVerbose || res==0) 5976 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 5977 ){ 5978 raw_printf(out, "-- Parent table %s\n", zParent); 5979 sqlite3_free(zPrev); 5980 zPrev = sqlite3_mprintf("%s", zParent); 5981 } 5982 5983 if( res==0 ){ 5984 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 5985 }else if( bVerbose ){ 5986 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 5987 zIndent, zFrom, zTarget 5988 ); 5989 } 5990 } 5991 } 5992 sqlite3_free(zPrev); 5993 5994 if( rc!=SQLITE_OK ){ 5995 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5996 } 5997 5998 rc2 = sqlite3_finalize(pSql); 5999 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 6000 rc = rc2; 6001 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6002 } 6003 }else{ 6004 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6005 } 6006 6007 return rc; 6008} 6009 6010/* 6011** Implementation of ".lint" dot command. 6012*/ 6013static int lintDotCommand( 6014 ShellState *pState, /* Current shell tool state */ 6015 char **azArg, /* Array of arguments passed to dot command */ 6016 int nArg /* Number of entries in azArg[] */ 6017){ 6018 int n; 6019 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 6020 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 6021 return lintFkeyIndexes(pState, azArg, nArg); 6022 6023 usage: 6024 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 6025 raw_printf(stderr, "Where sub-commands are:\n"); 6026 raw_printf(stderr, " fkey-indexes\n"); 6027 return SQLITE_ERROR; 6028} 6029 6030#if !defined SQLITE_OMIT_VIRTUALTABLE 6031static void shellPrepare( 6032 sqlite3 *db, 6033 int *pRc, 6034 const char *zSql, 6035 sqlite3_stmt **ppStmt 6036){ 6037 *ppStmt = 0; 6038 if( *pRc==SQLITE_OK ){ 6039 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 6040 if( rc!=SQLITE_OK ){ 6041 raw_printf(stderr, "sql error: %s (%d)\n", 6042 sqlite3_errmsg(db), sqlite3_errcode(db) 6043 ); 6044 *pRc = rc; 6045 } 6046 } 6047} 6048 6049/* 6050** Create a prepared statement using printf-style arguments for the SQL. 6051** 6052** This routine is could be marked "static". But it is not always used, 6053** depending on compile-time options. By omitting the "static", we avoid 6054** nuisance compiler warnings about "defined but not used". 6055*/ 6056void shellPreparePrintf( 6057 sqlite3 *db, 6058 int *pRc, 6059 sqlite3_stmt **ppStmt, 6060 const char *zFmt, 6061 ... 6062){ 6063 *ppStmt = 0; 6064 if( *pRc==SQLITE_OK ){ 6065 va_list ap; 6066 char *z; 6067 va_start(ap, zFmt); 6068 z = sqlite3_vmprintf(zFmt, ap); 6069 va_end(ap); 6070 if( z==0 ){ 6071 *pRc = SQLITE_NOMEM; 6072 }else{ 6073 shellPrepare(db, pRc, z, ppStmt); 6074 sqlite3_free(z); 6075 } 6076 } 6077} 6078 6079/* Finalize the prepared statement created using shellPreparePrintf(). 6080** 6081** This routine is could be marked "static". But it is not always used, 6082** depending on compile-time options. By omitting the "static", we avoid 6083** nuisance compiler warnings about "defined but not used". 6084*/ 6085void shellFinalize( 6086 int *pRc, 6087 sqlite3_stmt *pStmt 6088){ 6089 if( pStmt ){ 6090 sqlite3 *db = sqlite3_db_handle(pStmt); 6091 int rc = sqlite3_finalize(pStmt); 6092 if( *pRc==SQLITE_OK ){ 6093 if( rc!=SQLITE_OK ){ 6094 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6095 } 6096 *pRc = rc; 6097 } 6098 } 6099} 6100 6101/* Reset the prepared statement created using shellPreparePrintf(). 6102** 6103** This routine is could be marked "static". But it is not always used, 6104** depending on compile-time options. By omitting the "static", we avoid 6105** nuisance compiler warnings about "defined but not used". 6106*/ 6107void shellReset( 6108 int *pRc, 6109 sqlite3_stmt *pStmt 6110){ 6111 int rc = sqlite3_reset(pStmt); 6112 if( *pRc==SQLITE_OK ){ 6113 if( rc!=SQLITE_OK ){ 6114 sqlite3 *db = sqlite3_db_handle(pStmt); 6115 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6116 } 6117 *pRc = rc; 6118 } 6119} 6120#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 6121 6122#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6123/****************************************************************************** 6124** The ".archive" or ".ar" command. 6125*/ 6126/* 6127** Structure representing a single ".ar" command. 6128*/ 6129typedef struct ArCommand ArCommand; 6130struct ArCommand { 6131 u8 eCmd; /* An AR_CMD_* value */ 6132 u8 bVerbose; /* True if --verbose */ 6133 u8 bZip; /* True if the archive is a ZIP */ 6134 u8 bDryRun; /* True if --dry-run */ 6135 u8 bAppend; /* True if --append */ 6136 u8 fromCmdLine; /* Run from -A instead of .archive */ 6137 int nArg; /* Number of command arguments */ 6138 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 6139 const char *zFile; /* --file argument, or NULL */ 6140 const char *zDir; /* --directory argument, or NULL */ 6141 char **azArg; /* Array of command arguments */ 6142 ShellState *p; /* Shell state */ 6143 sqlite3 *db; /* Database containing the archive */ 6144}; 6145 6146/* 6147** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 6148*/ 6149static int arUsage(FILE *f){ 6150 showHelp(f,"archive"); 6151 return SQLITE_ERROR; 6152} 6153 6154/* 6155** Print an error message for the .ar command to stderr and return 6156** SQLITE_ERROR. 6157*/ 6158static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 6159 va_list ap; 6160 char *z; 6161 va_start(ap, zFmt); 6162 z = sqlite3_vmprintf(zFmt, ap); 6163 va_end(ap); 6164 utf8_printf(stderr, "Error: %s\n", z); 6165 if( pAr->fromCmdLine ){ 6166 utf8_printf(stderr, "Use \"-A\" for more help\n"); 6167 }else{ 6168 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 6169 } 6170 sqlite3_free(z); 6171 return SQLITE_ERROR; 6172} 6173 6174/* 6175** Values for ArCommand.eCmd. 6176*/ 6177#define AR_CMD_CREATE 1 6178#define AR_CMD_UPDATE 2 6179#define AR_CMD_INSERT 3 6180#define AR_CMD_EXTRACT 4 6181#define AR_CMD_LIST 5 6182#define AR_CMD_HELP 6 6183 6184/* 6185** Other (non-command) switches. 6186*/ 6187#define AR_SWITCH_VERBOSE 7 6188#define AR_SWITCH_FILE 8 6189#define AR_SWITCH_DIRECTORY 9 6190#define AR_SWITCH_APPEND 10 6191#define AR_SWITCH_DRYRUN 11 6192 6193static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 6194 switch( eSwitch ){ 6195 case AR_CMD_CREATE: 6196 case AR_CMD_EXTRACT: 6197 case AR_CMD_LIST: 6198 case AR_CMD_UPDATE: 6199 case AR_CMD_INSERT: 6200 case AR_CMD_HELP: 6201 if( pAr->eCmd ){ 6202 return arErrorMsg(pAr, "multiple command options"); 6203 } 6204 pAr->eCmd = eSwitch; 6205 break; 6206 6207 case AR_SWITCH_DRYRUN: 6208 pAr->bDryRun = 1; 6209 break; 6210 case AR_SWITCH_VERBOSE: 6211 pAr->bVerbose = 1; 6212 break; 6213 case AR_SWITCH_APPEND: 6214 pAr->bAppend = 1; 6215 /* Fall thru into --file */ 6216 case AR_SWITCH_FILE: 6217 pAr->zFile = zArg; 6218 break; 6219 case AR_SWITCH_DIRECTORY: 6220 pAr->zDir = zArg; 6221 break; 6222 } 6223 6224 return SQLITE_OK; 6225} 6226 6227/* 6228** Parse the command line for an ".ar" command. The results are written into 6229** structure (*pAr). SQLITE_OK is returned if the command line is parsed 6230** successfully, otherwise an error message is written to stderr and 6231** SQLITE_ERROR returned. 6232*/ 6233static int arParseCommand( 6234 char **azArg, /* Array of arguments passed to dot command */ 6235 int nArg, /* Number of entries in azArg[] */ 6236 ArCommand *pAr /* Populate this object */ 6237){ 6238 struct ArSwitch { 6239 const char *zLong; 6240 char cShort; 6241 u8 eSwitch; 6242 u8 bArg; 6243 } aSwitch[] = { 6244 { "create", 'c', AR_CMD_CREATE, 0 }, 6245 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 6246 { "insert", 'i', AR_CMD_INSERT, 0 }, 6247 { "list", 't', AR_CMD_LIST, 0 }, 6248 { "update", 'u', AR_CMD_UPDATE, 0 }, 6249 { "help", 'h', AR_CMD_HELP, 0 }, 6250 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 6251 { "file", 'f', AR_SWITCH_FILE, 1 }, 6252 { "append", 'a', AR_SWITCH_APPEND, 1 }, 6253 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 6254 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 6255 }; 6256 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 6257 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 6258 6259 if( nArg<=1 ){ 6260 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 6261 return arUsage(stderr); 6262 }else{ 6263 char *z = azArg[1]; 6264 if( z[0]!='-' ){ 6265 /* Traditional style [tar] invocation */ 6266 int i; 6267 int iArg = 2; 6268 for(i=0; z[i]; i++){ 6269 const char *zArg = 0; 6270 struct ArSwitch *pOpt; 6271 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6272 if( z[i]==pOpt->cShort ) break; 6273 } 6274 if( pOpt==pEnd ){ 6275 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6276 } 6277 if( pOpt->bArg ){ 6278 if( iArg>=nArg ){ 6279 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 6280 } 6281 zArg = azArg[iArg++]; 6282 } 6283 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6284 } 6285 pAr->nArg = nArg-iArg; 6286 if( pAr->nArg>0 ){ 6287 pAr->azArg = &azArg[iArg]; 6288 } 6289 }else{ 6290 /* Non-traditional invocation */ 6291 int iArg; 6292 for(iArg=1; iArg<nArg; iArg++){ 6293 int n; 6294 z = azArg[iArg]; 6295 if( z[0]!='-' ){ 6296 /* All remaining command line words are command arguments. */ 6297 pAr->azArg = &azArg[iArg]; 6298 pAr->nArg = nArg-iArg; 6299 break; 6300 } 6301 n = strlen30(z); 6302 6303 if( z[1]!='-' ){ 6304 int i; 6305 /* One or more short options */ 6306 for(i=1; i<n; i++){ 6307 const char *zArg = 0; 6308 struct ArSwitch *pOpt; 6309 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6310 if( z[i]==pOpt->cShort ) break; 6311 } 6312 if( pOpt==pEnd ){ 6313 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6314 } 6315 if( pOpt->bArg ){ 6316 if( i<(n-1) ){ 6317 zArg = &z[i+1]; 6318 i = n; 6319 }else{ 6320 if( iArg>=(nArg-1) ){ 6321 return arErrorMsg(pAr, "option requires an argument: %c", 6322 z[i]); 6323 } 6324 zArg = azArg[++iArg]; 6325 } 6326 } 6327 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6328 } 6329 }else if( z[2]=='\0' ){ 6330 /* A -- option, indicating that all remaining command line words 6331 ** are command arguments. */ 6332 pAr->azArg = &azArg[iArg+1]; 6333 pAr->nArg = nArg-iArg-1; 6334 break; 6335 }else{ 6336 /* A long option */ 6337 const char *zArg = 0; /* Argument for option, if any */ 6338 struct ArSwitch *pMatch = 0; /* Matching option */ 6339 struct ArSwitch *pOpt; /* Iterator */ 6340 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6341 const char *zLong = pOpt->zLong; 6342 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 6343 if( pMatch ){ 6344 return arErrorMsg(pAr, "ambiguous option: %s",z); 6345 }else{ 6346 pMatch = pOpt; 6347 } 6348 } 6349 } 6350 6351 if( pMatch==0 ){ 6352 return arErrorMsg(pAr, "unrecognized option: %s", z); 6353 } 6354 if( pMatch->bArg ){ 6355 if( iArg>=(nArg-1) ){ 6356 return arErrorMsg(pAr, "option requires an argument: %s", z); 6357 } 6358 zArg = azArg[++iArg]; 6359 } 6360 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 6361 } 6362 } 6363 } 6364 } 6365 6366 return SQLITE_OK; 6367} 6368 6369/* 6370** This function assumes that all arguments within the ArCommand.azArg[] 6371** array refer to archive members, as for the --extract or --list commands. 6372** It checks that each of them are present. If any specified file is not 6373** present in the archive, an error is printed to stderr and an error 6374** code returned. Otherwise, if all specified arguments are present in 6375** the archive, SQLITE_OK is returned. 6376** 6377** This function strips any trailing '/' characters from each argument. 6378** This is consistent with the way the [tar] command seems to work on 6379** Linux. 6380*/ 6381static int arCheckEntries(ArCommand *pAr){ 6382 int rc = SQLITE_OK; 6383 if( pAr->nArg ){ 6384 int i, j; 6385 sqlite3_stmt *pTest = 0; 6386 6387 shellPreparePrintf(pAr->db, &rc, &pTest, 6388 "SELECT name FROM %s WHERE name=$name", 6389 pAr->zSrcTable 6390 ); 6391 j = sqlite3_bind_parameter_index(pTest, "$name"); 6392 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6393 char *z = pAr->azArg[i]; 6394 int n = strlen30(z); 6395 int bOk = 0; 6396 while( n>0 && z[n-1]=='/' ) n--; 6397 z[n] = '\0'; 6398 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 6399 if( SQLITE_ROW==sqlite3_step(pTest) ){ 6400 bOk = 1; 6401 } 6402 shellReset(&rc, pTest); 6403 if( rc==SQLITE_OK && bOk==0 ){ 6404 utf8_printf(stderr, "not found in archive: %s\n", z); 6405 rc = SQLITE_ERROR; 6406 } 6407 } 6408 shellFinalize(&rc, pTest); 6409 } 6410 return rc; 6411} 6412 6413/* 6414** Format a WHERE clause that can be used against the "sqlar" table to 6415** identify all archive members that match the command arguments held 6416** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 6417** The caller is responsible for eventually calling sqlite3_free() on 6418** any non-NULL (*pzWhere) value. 6419*/ 6420static void arWhereClause( 6421 int *pRc, 6422 ArCommand *pAr, 6423 char **pzWhere /* OUT: New WHERE clause */ 6424){ 6425 char *zWhere = 0; 6426 if( *pRc==SQLITE_OK ){ 6427 if( pAr->nArg==0 ){ 6428 zWhere = sqlite3_mprintf("1"); 6429 }else{ 6430 int i; 6431 const char *zSep = ""; 6432 for(i=0; i<pAr->nArg; i++){ 6433 const char *z = pAr->azArg[i]; 6434 zWhere = sqlite3_mprintf( 6435 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 6436 zWhere, zSep, z, strlen30(z)+1, z 6437 ); 6438 if( zWhere==0 ){ 6439 *pRc = SQLITE_NOMEM; 6440 break; 6441 } 6442 zSep = " OR "; 6443 } 6444 } 6445 } 6446 *pzWhere = zWhere; 6447} 6448 6449/* 6450** Implementation of .ar "lisT" command. 6451*/ 6452static int arListCommand(ArCommand *pAr){ 6453 const char *zSql = "SELECT %s FROM %s WHERE %s"; 6454 const char *azCols[] = { 6455 "name", 6456 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 6457 }; 6458 6459 char *zWhere = 0; 6460 sqlite3_stmt *pSql = 0; 6461 int rc; 6462 6463 rc = arCheckEntries(pAr); 6464 arWhereClause(&rc, pAr, &zWhere); 6465 6466 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 6467 pAr->zSrcTable, zWhere); 6468 if( pAr->bDryRun ){ 6469 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6470 }else{ 6471 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6472 if( pAr->bVerbose ){ 6473 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 6474 sqlite3_column_text(pSql, 0), 6475 sqlite3_column_int(pSql, 1), 6476 sqlite3_column_text(pSql, 2), 6477 sqlite3_column_text(pSql, 3) 6478 ); 6479 }else{ 6480 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6481 } 6482 } 6483 } 6484 shellFinalize(&rc, pSql); 6485 sqlite3_free(zWhere); 6486 return rc; 6487} 6488 6489 6490/* 6491** Implementation of .ar "eXtract" command. 6492*/ 6493static int arExtractCommand(ArCommand *pAr){ 6494 const char *zSql1 = 6495 "SELECT " 6496 " ($dir || name)," 6497 " writefile(($dir || name), %s, mode, mtime) " 6498 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 6499 " AND name NOT GLOB '*..[/\\]*'"; 6500 6501 const char *azExtraArg[] = { 6502 "sqlar_uncompress(data, sz)", 6503 "data" 6504 }; 6505 6506 sqlite3_stmt *pSql = 0; 6507 int rc = SQLITE_OK; 6508 char *zDir = 0; 6509 char *zWhere = 0; 6510 int i, j; 6511 6512 /* If arguments are specified, check that they actually exist within 6513 ** the archive before proceeding. And formulate a WHERE clause to 6514 ** match them. */ 6515 rc = arCheckEntries(pAr); 6516 arWhereClause(&rc, pAr, &zWhere); 6517 6518 if( rc==SQLITE_OK ){ 6519 if( pAr->zDir ){ 6520 zDir = sqlite3_mprintf("%s/", pAr->zDir); 6521 }else{ 6522 zDir = sqlite3_mprintf(""); 6523 } 6524 if( zDir==0 ) rc = SQLITE_NOMEM; 6525 } 6526 6527 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 6528 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 6529 ); 6530 6531 if( rc==SQLITE_OK ){ 6532 j = sqlite3_bind_parameter_index(pSql, "$dir"); 6533 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 6534 6535 /* Run the SELECT statement twice. The first time, writefile() is called 6536 ** for all archive members that should be extracted. The second time, 6537 ** only for the directories. This is because the timestamps for 6538 ** extracted directories must be reset after they are populated (as 6539 ** populating them changes the timestamp). */ 6540 for(i=0; i<2; i++){ 6541 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 6542 sqlite3_bind_int(pSql, j, i); 6543 if( pAr->bDryRun ){ 6544 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6545 }else{ 6546 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6547 if( i==0 && pAr->bVerbose ){ 6548 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6549 } 6550 } 6551 } 6552 shellReset(&rc, pSql); 6553 } 6554 shellFinalize(&rc, pSql); 6555 } 6556 6557 sqlite3_free(zDir); 6558 sqlite3_free(zWhere); 6559 return rc; 6560} 6561 6562/* 6563** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 6564*/ 6565static int arExecSql(ArCommand *pAr, const char *zSql){ 6566 int rc; 6567 if( pAr->bDryRun ){ 6568 utf8_printf(pAr->p->out, "%s\n", zSql); 6569 rc = SQLITE_OK; 6570 }else{ 6571 char *zErr = 0; 6572 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6573 if( zErr ){ 6574 utf8_printf(stdout, "ERROR: %s\n", zErr); 6575 sqlite3_free(zErr); 6576 } 6577 } 6578 return rc; 6579} 6580 6581 6582/* 6583** Implementation of .ar "create", "insert", and "update" commands. 6584** 6585** create -> Create a new SQL archive 6586** insert -> Insert or reinsert all files listed 6587** update -> Insert files that have changed or that were not 6588** previously in the archive 6589** 6590** Create the "sqlar" table in the database if it does not already exist. 6591** Then add each file in the azFile[] array to the archive. Directories 6592** are added recursively. If argument bVerbose is non-zero, a message is 6593** printed on stdout for each file archived. 6594** 6595** The create command is the same as update, except that it drops 6596** any existing "sqlar" table before beginning. The "insert" command 6597** always overwrites every file named on the command-line, where as 6598** "update" only overwrites if the size or mtime or mode has changed. 6599*/ 6600static int arCreateOrUpdateCommand( 6601 ArCommand *pAr, /* Command arguments and options */ 6602 int bUpdate, /* true for a --create. */ 6603 int bOnlyIfChanged /* Only update if file has changed */ 6604){ 6605 const char *zCreate = 6606 "CREATE TABLE IF NOT EXISTS sqlar(\n" 6607 " name TEXT PRIMARY KEY, -- name of the file\n" 6608 " mode INT, -- access permissions\n" 6609 " mtime INT, -- last modification time\n" 6610 " sz INT, -- original file size\n" 6611 " data BLOB -- compressed content\n" 6612 ")"; 6613 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 6614 const char *zInsertFmt[2] = { 6615 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 6616 " SELECT\n" 6617 " %s,\n" 6618 " mode,\n" 6619 " mtime,\n" 6620 " CASE substr(lsmode(mode),1,1)\n" 6621 " WHEN '-' THEN length(data)\n" 6622 " WHEN 'd' THEN 0\n" 6623 " ELSE -1 END,\n" 6624 " sqlar_compress(data)\n" 6625 " FROM fsdir(%Q,%Q) AS disk\n" 6626 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6627 , 6628 "REPLACE INTO %s(name,mode,mtime,data)\n" 6629 " SELECT\n" 6630 " %s,\n" 6631 " mode,\n" 6632 " mtime,\n" 6633 " data\n" 6634 " FROM fsdir(%Q,%Q) AS disk\n" 6635 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6636 }; 6637 int i; /* For iterating through azFile[] */ 6638 int rc; /* Return code */ 6639 const char *zTab = 0; /* SQL table into which to insert */ 6640 char *zSql; 6641 char zTemp[50]; 6642 char *zExists = 0; 6643 6644 arExecSql(pAr, "PRAGMA page_size=512"); 6645 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6646 if( rc!=SQLITE_OK ) return rc; 6647 zTemp[0] = 0; 6648 if( pAr->bZip ){ 6649 /* Initialize the zipfile virtual table, if necessary */ 6650 if( pAr->zFile ){ 6651 sqlite3_uint64 r; 6652 sqlite3_randomness(sizeof(r),&r); 6653 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6654 zTab = zTemp; 6655 zSql = sqlite3_mprintf( 6656 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6657 zTab, pAr->zFile 6658 ); 6659 rc = arExecSql(pAr, zSql); 6660 sqlite3_free(zSql); 6661 }else{ 6662 zTab = "zip"; 6663 } 6664 }else{ 6665 /* Initialize the table for an SQLAR */ 6666 zTab = "sqlar"; 6667 if( bUpdate==0 ){ 6668 rc = arExecSql(pAr, zDrop); 6669 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6670 } 6671 rc = arExecSql(pAr, zCreate); 6672 } 6673 if( bOnlyIfChanged ){ 6674 zExists = sqlite3_mprintf( 6675 " AND NOT EXISTS(" 6676 "SELECT 1 FROM %s AS mem" 6677 " WHERE mem.name=disk.name" 6678 " AND mem.mtime=disk.mtime" 6679 " AND mem.mode=disk.mode)", zTab); 6680 }else{ 6681 zExists = sqlite3_mprintf(""); 6682 } 6683 if( zExists==0 ) rc = SQLITE_NOMEM; 6684 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6685 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6686 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6687 pAr->azArg[i], pAr->zDir, zExists); 6688 rc = arExecSql(pAr, zSql2); 6689 sqlite3_free(zSql2); 6690 } 6691end_ar_transaction: 6692 if( rc!=SQLITE_OK ){ 6693 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6694 }else{ 6695 rc = arExecSql(pAr, "RELEASE ar;"); 6696 if( pAr->bZip && pAr->zFile ){ 6697 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6698 arExecSql(pAr, zSql); 6699 sqlite3_free(zSql); 6700 } 6701 } 6702 sqlite3_free(zExists); 6703 return rc; 6704} 6705 6706/* 6707** Implementation of ".ar" dot command. 6708*/ 6709static int arDotCommand( 6710 ShellState *pState, /* Current shell tool state */ 6711 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6712 char **azArg, /* Array of arguments passed to dot command */ 6713 int nArg /* Number of entries in azArg[] */ 6714){ 6715 ArCommand cmd; 6716 int rc; 6717 memset(&cmd, 0, sizeof(cmd)); 6718 cmd.fromCmdLine = fromCmdLine; 6719 rc = arParseCommand(azArg, nArg, &cmd); 6720 if( rc==SQLITE_OK ){ 6721 int eDbType = SHELL_OPEN_UNSPEC; 6722 cmd.p = pState; 6723 cmd.db = pState->db; 6724 if( cmd.zFile ){ 6725 eDbType = deduceDatabaseType(cmd.zFile, 1); 6726 }else{ 6727 eDbType = pState->openMode; 6728 } 6729 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6730 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6731 if( cmd.zFile==0 ){ 6732 cmd.zSrcTable = sqlite3_mprintf("zip"); 6733 }else{ 6734 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6735 } 6736 } 6737 cmd.bZip = 1; 6738 }else if( cmd.zFile ){ 6739 int flags; 6740 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6741 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6742 || cmd.eCmd==AR_CMD_UPDATE ){ 6743 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6744 }else{ 6745 flags = SQLITE_OPEN_READONLY; 6746 } 6747 cmd.db = 0; 6748 if( cmd.bDryRun ){ 6749 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6750 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6751 } 6752 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6753 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6754 if( rc!=SQLITE_OK ){ 6755 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6756 cmd.zFile, sqlite3_errmsg(cmd.db) 6757 ); 6758 goto end_ar_command; 6759 } 6760 sqlite3_fileio_init(cmd.db, 0, 0); 6761 sqlite3_sqlar_init(cmd.db, 0, 0); 6762 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6763 shellPutsFunc, 0, 0); 6764 6765 } 6766 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6767 if( cmd.eCmd!=AR_CMD_CREATE 6768 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6769 ){ 6770 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6771 rc = SQLITE_ERROR; 6772 goto end_ar_command; 6773 } 6774 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6775 } 6776 6777 switch( cmd.eCmd ){ 6778 case AR_CMD_CREATE: 6779 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6780 break; 6781 6782 case AR_CMD_EXTRACT: 6783 rc = arExtractCommand(&cmd); 6784 break; 6785 6786 case AR_CMD_LIST: 6787 rc = arListCommand(&cmd); 6788 break; 6789 6790 case AR_CMD_HELP: 6791 arUsage(pState->out); 6792 break; 6793 6794 case AR_CMD_INSERT: 6795 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6796 break; 6797 6798 default: 6799 assert( cmd.eCmd==AR_CMD_UPDATE ); 6800 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6801 break; 6802 } 6803 } 6804end_ar_command: 6805 if( cmd.db!=pState->db ){ 6806 close_db(cmd.db); 6807 } 6808 sqlite3_free(cmd.zSrcTable); 6809 6810 return rc; 6811} 6812/* End of the ".archive" or ".ar" command logic 6813*******************************************************************************/ 6814#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6815 6816#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6817/* 6818** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6819** Otherwise, the SQL statement or statements in zSql are executed using 6820** database connection db and the error code written to *pRc before 6821** this function returns. 6822*/ 6823static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6824 int rc = *pRc; 6825 if( rc==SQLITE_OK ){ 6826 char *zErr = 0; 6827 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6828 if( rc!=SQLITE_OK ){ 6829 raw_printf(stderr, "SQL error: %s\n", zErr); 6830 } 6831 sqlite3_free(zErr); 6832 *pRc = rc; 6833 } 6834} 6835 6836/* 6837** Like shellExec(), except that zFmt is a printf() style format string. 6838*/ 6839static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6840 char *z = 0; 6841 if( *pRc==SQLITE_OK ){ 6842 va_list ap; 6843 va_start(ap, zFmt); 6844 z = sqlite3_vmprintf(zFmt, ap); 6845 va_end(ap); 6846 if( z==0 ){ 6847 *pRc = SQLITE_NOMEM; 6848 }else{ 6849 shellExec(db, pRc, z); 6850 } 6851 sqlite3_free(z); 6852 } 6853} 6854 6855/* 6856** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6857** Otherwise, an attempt is made to allocate, zero and return a pointer 6858** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6859** to SQLITE_NOMEM and NULL returned. 6860*/ 6861static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6862 void *pRet = 0; 6863 if( *pRc==SQLITE_OK ){ 6864 pRet = sqlite3_malloc64(nByte); 6865 if( pRet==0 ){ 6866 *pRc = SQLITE_NOMEM; 6867 }else{ 6868 memset(pRet, 0, nByte); 6869 } 6870 } 6871 return pRet; 6872} 6873 6874/* 6875** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6876** Otherwise, zFmt is treated as a printf() style string. The result of 6877** formatting it along with any trailing arguments is written into a 6878** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6879** It is the responsibility of the caller to eventually free this buffer 6880** using a call to sqlite3_free(). 6881** 6882** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6883** pointer returned. 6884*/ 6885static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6886 char *z = 0; 6887 if( *pRc==SQLITE_OK ){ 6888 va_list ap; 6889 va_start(ap, zFmt); 6890 z = sqlite3_vmprintf(zFmt, ap); 6891 va_end(ap); 6892 if( z==0 ){ 6893 *pRc = SQLITE_NOMEM; 6894 } 6895 } 6896 return z; 6897} 6898 6899/* 6900** When running the ".recover" command, each output table, and the special 6901** orphaned row table if it is required, is represented by an instance 6902** of the following struct. 6903*/ 6904typedef struct RecoverTable RecoverTable; 6905struct RecoverTable { 6906 char *zQuoted; /* Quoted version of table name */ 6907 int nCol; /* Number of columns in table */ 6908 char **azlCol; /* Array of column lists */ 6909 int iPk; /* Index of IPK column */ 6910}; 6911 6912/* 6913** Free a RecoverTable object allocated by recoverFindTable() or 6914** recoverOrphanTable(). 6915*/ 6916static void recoverFreeTable(RecoverTable *pTab){ 6917 if( pTab ){ 6918 sqlite3_free(pTab->zQuoted); 6919 if( pTab->azlCol ){ 6920 int i; 6921 for(i=0; i<=pTab->nCol; i++){ 6922 sqlite3_free(pTab->azlCol[i]); 6923 } 6924 sqlite3_free(pTab->azlCol); 6925 } 6926 sqlite3_free(pTab); 6927 } 6928} 6929 6930/* 6931** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 6932** Otherwise, it allocates and returns a RecoverTable object based on the 6933** final four arguments passed to this function. It is the responsibility 6934** of the caller to eventually free the returned object using 6935** recoverFreeTable(). 6936*/ 6937static RecoverTable *recoverNewTable( 6938 int *pRc, /* IN/OUT: Error code */ 6939 const char *zName, /* Name of table */ 6940 const char *zSql, /* CREATE TABLE statement */ 6941 int bIntkey, 6942 int nCol 6943){ 6944 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 6945 int rc = *pRc; 6946 RecoverTable *pTab = 0; 6947 6948 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 6949 if( rc==SQLITE_OK ){ 6950 int nSqlCol = 0; 6951 int bSqlIntkey = 0; 6952 sqlite3_stmt *pStmt = 0; 6953 6954 rc = sqlite3_open("", &dbtmp); 6955 if( rc==SQLITE_OK ){ 6956 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, 6957 shellIdQuote, 0, 0); 6958 } 6959 if( rc==SQLITE_OK ){ 6960 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 6961 } 6962 if( rc==SQLITE_OK ){ 6963 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 6964 if( rc==SQLITE_ERROR ){ 6965 rc = SQLITE_OK; 6966 goto finished; 6967 } 6968 } 6969 shellPreparePrintf(dbtmp, &rc, &pStmt, 6970 "SELECT count(*) FROM pragma_table_info(%Q)", zName 6971 ); 6972 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6973 nSqlCol = sqlite3_column_int(pStmt, 0); 6974 } 6975 shellFinalize(&rc, pStmt); 6976 6977 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 6978 goto finished; 6979 } 6980 6981 shellPreparePrintf(dbtmp, &rc, &pStmt, 6982 "SELECT (" 6983 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 6984 ") FROM sqlite_schema WHERE name = %Q", zName 6985 ); 6986 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6987 bSqlIntkey = sqlite3_column_int(pStmt, 0); 6988 } 6989 shellFinalize(&rc, pStmt); 6990 6991 if( bIntkey==bSqlIntkey ){ 6992 int i; 6993 const char *zPk = "_rowid_"; 6994 sqlite3_stmt *pPkFinder = 0; 6995 6996 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 6997 ** set zPk to the name of the PK column, and pTab->iPk to the index 6998 ** of the column, where columns are 0-numbered from left to right. 6999 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 7000 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 7001 pTab->iPk = -2; 7002 if( bIntkey ){ 7003 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 7004 "SELECT cid, name FROM pragma_table_info(%Q) " 7005 " WHERE pk=1 AND type='integer' COLLATE nocase" 7006 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 7007 , zName, zName 7008 ); 7009 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 7010 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 7011 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 7012 } 7013 } 7014 7015 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); 7016 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 7017 pTab->nCol = nSqlCol; 7018 7019 if( bIntkey ){ 7020 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); 7021 }else{ 7022 pTab->azlCol[0] = shellMPrintf(&rc, ""); 7023 } 7024 i = 1; 7025 shellPreparePrintf(dbtmp, &rc, &pStmt, 7026 "SELECT %Q || group_concat(shell_idquote(name), ', ') " 7027 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 7028 "FROM pragma_table_info(%Q)", 7029 bIntkey ? ", " : "", pTab->iPk, 7030 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 7031 zName 7032 ); 7033 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7034 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 7035 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 7036 i++; 7037 } 7038 shellFinalize(&rc, pStmt); 7039 7040 shellFinalize(&rc, pPkFinder); 7041 } 7042 } 7043 7044 finished: 7045 sqlite3_close(dbtmp); 7046 *pRc = rc; 7047 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 7048 recoverFreeTable(pTab); 7049 pTab = 0; 7050 } 7051 return pTab; 7052} 7053 7054/* 7055** This function is called to search the schema recovered from the 7056** sqlite_schema table of the (possibly) corrupt database as part 7057** of a ".recover" command. Specifically, for a table with root page 7058** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 7059** table must be a WITHOUT ROWID table, or if non-zero, not one of 7060** those. 7061** 7062** If a table is found, a (RecoverTable*) object is returned. Or, if 7063** no such table is found, but bIntkey is false and iRoot is the 7064** root page of an index in the recovered schema, then (*pbNoop) is 7065** set to true and NULL returned. Or, if there is no such table or 7066** index, NULL is returned and (*pbNoop) set to 0, indicating that 7067** the caller should write data to the orphans table. 7068*/ 7069static RecoverTable *recoverFindTable( 7070 ShellState *pState, /* Shell state object */ 7071 int *pRc, /* IN/OUT: Error code */ 7072 int iRoot, /* Root page of table */ 7073 int bIntkey, /* True for an intkey table */ 7074 int nCol, /* Number of columns in table */ 7075 int *pbNoop /* OUT: True if iRoot is root of index */ 7076){ 7077 sqlite3_stmt *pStmt = 0; 7078 RecoverTable *pRet = 0; 7079 int bNoop = 0; 7080 const char *zSql = 0; 7081 const char *zName = 0; 7082 7083 /* Search the recovered schema for an object with root page iRoot. */ 7084 shellPreparePrintf(pState->db, pRc, &pStmt, 7085 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 7086 ); 7087 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7088 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 7089 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 7090 bNoop = 1; 7091 break; 7092 } 7093 if( sqlite3_stricmp(zType, "table")==0 ){ 7094 zName = (const char*)sqlite3_column_text(pStmt, 1); 7095 zSql = (const char*)sqlite3_column_text(pStmt, 2); 7096 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 7097 break; 7098 } 7099 } 7100 7101 shellFinalize(pRc, pStmt); 7102 *pbNoop = bNoop; 7103 return pRet; 7104} 7105 7106/* 7107** Return a RecoverTable object representing the orphans table. 7108*/ 7109static RecoverTable *recoverOrphanTable( 7110 ShellState *pState, /* Shell state object */ 7111 int *pRc, /* IN/OUT: Error code */ 7112 const char *zLostAndFound, /* Base name for orphans table */ 7113 int nCol /* Number of user data columns */ 7114){ 7115 RecoverTable *pTab = 0; 7116 if( nCol>=0 && *pRc==SQLITE_OK ){ 7117 int i; 7118 7119 /* This block determines the name of the orphan table. The prefered 7120 ** name is zLostAndFound. But if that clashes with another name 7121 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 7122 ** and so on until a non-clashing name is found. */ 7123 int iTab = 0; 7124 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 7125 sqlite3_stmt *pTest = 0; 7126 shellPrepare(pState->db, pRc, 7127 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 7128 ); 7129 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 7130 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 7131 shellReset(pRc, pTest); 7132 sqlite3_free(zTab); 7133 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 7134 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 7135 } 7136 shellFinalize(pRc, pTest); 7137 7138 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 7139 if( pTab ){ 7140 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); 7141 pTab->nCol = nCol; 7142 pTab->iPk = -2; 7143 if( nCol>0 ){ 7144 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 7145 if( pTab->azlCol ){ 7146 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 7147 for(i=nCol-1; i>=0; i--){ 7148 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 7149 } 7150 } 7151 } 7152 7153 if( *pRc!=SQLITE_OK ){ 7154 recoverFreeTable(pTab); 7155 pTab = 0; 7156 }else{ 7157 raw_printf(pState->out, 7158 "CREATE TABLE %s(rootpgno INTEGER, " 7159 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 7160 ); 7161 for(i=0; i<nCol; i++){ 7162 raw_printf(pState->out, ", c%d", i); 7163 } 7164 raw_printf(pState->out, ");\n"); 7165 } 7166 } 7167 sqlite3_free(zTab); 7168 } 7169 return pTab; 7170} 7171 7172/* 7173** This function is called to recover data from the database. A script 7174** to construct a new database containing all recovered data is output 7175** on stream pState->out. 7176*/ 7177static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 7178 int rc = SQLITE_OK; 7179 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 7180 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 7181 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 7182 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 7183 const char *zLostAndFound = "lost_and_found"; 7184 int i; 7185 int nOrphan = -1; 7186 RecoverTable *pOrphan = 0; 7187 7188 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 7189 int bRowids = 1; /* 0 if --no-rowids */ 7190 for(i=1; i<nArg; i++){ 7191 char *z = azArg[i]; 7192 int n; 7193 if( z[0]=='-' && z[1]=='-' ) z++; 7194 n = strlen30(z); 7195 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 7196 bFreelist = 0; 7197 }else 7198 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 7199 i++; 7200 zRecoveryDb = azArg[i]; 7201 }else 7202 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 7203 i++; 7204 zLostAndFound = azArg[i]; 7205 }else 7206 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ 7207 bRowids = 0; 7208 } 7209 else{ 7210 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 7211 showHelp(pState->out, azArg[0]); 7212 return 1; 7213 } 7214 } 7215 7216 shellExecPrintf(pState->db, &rc, 7217 /* Attach an in-memory database named 'recovery'. Create an indexed 7218 ** cache of the sqlite_dbptr virtual table. */ 7219 "PRAGMA writable_schema = on;" 7220 "ATTACH %Q AS recovery;" 7221 "DROP TABLE IF EXISTS recovery.dbptr;" 7222 "DROP TABLE IF EXISTS recovery.freelist;" 7223 "DROP TABLE IF EXISTS recovery.map;" 7224 "DROP TABLE IF EXISTS recovery.schema;" 7225 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 7226 ); 7227 7228 if( bFreelist ){ 7229 shellExec(pState->db, &rc, 7230 "WITH trunk(pgno) AS (" 7231 " SELECT shell_int32(" 7232 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 7233 " WHERE x>0" 7234 " UNION" 7235 " SELECT shell_int32(" 7236 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 7237 " FROM trunk WHERE x>0" 7238 ")," 7239 "freelist(data, n, freepgno) AS (" 7240 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 7241 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 7242 " UNION ALL" 7243 " SELECT data, n-1, shell_int32(data, 2+n) " 7244 " FROM freelist WHERE n>=0" 7245 ")" 7246 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 7247 ); 7248 } 7249 7250 /* If this is an auto-vacuum database, add all pointer-map pages to 7251 ** the freelist table. Do this regardless of whether or not 7252 ** --freelist-corrupt was specified. */ 7253 shellExec(pState->db, &rc, 7254 "WITH ptrmap(pgno) AS (" 7255 " SELECT 2 WHERE shell_int32(" 7256 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" 7257 " )" 7258 " UNION ALL " 7259 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " 7260 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" 7261 ")" 7262 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" 7263 ); 7264 7265 shellExec(pState->db, &rc, 7266 "CREATE TABLE recovery.dbptr(" 7267 " pgno, child, PRIMARY KEY(child, pgno)" 7268 ") WITHOUT ROWID;" 7269 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 7270 " SELECT * FROM sqlite_dbptr" 7271 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 7272 7273 /* Delete any pointer to page 1. This ensures that page 1 is considered 7274 ** a root page, regardless of how corrupt the db is. */ 7275 "DELETE FROM recovery.dbptr WHERE child = 1;" 7276 7277 /* Delete all pointers to any pages that have more than one pointer 7278 ** to them. Such pages will be treated as root pages when recovering 7279 ** data. */ 7280 "DELETE FROM recovery.dbptr WHERE child IN (" 7281 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 7282 ");" 7283 7284 /* Create the "map" table that will (eventually) contain instructions 7285 ** for dealing with each page in the db that contains one or more 7286 ** records. */ 7287 "CREATE TABLE recovery.map(" 7288 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 7289 ");" 7290 7291 /* Populate table [map]. If there are circular loops of pages in the 7292 ** database, the following adds all pages in such a loop to the map 7293 ** as individual root pages. This could be handled better. */ 7294 "WITH pages(i, maxlen) AS (" 7295 " SELECT page_count, (" 7296 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 7297 " ) FROM pragma_page_count WHERE page_count>0" 7298 " UNION ALL" 7299 " SELECT i-1, (" 7300 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 7301 " ) FROM pages WHERE i>=2" 7302 ")" 7303 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 7304 " SELECT i, maxlen, NULL, (" 7305 " WITH p(orig, pgno, parent) AS (" 7306 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 7307 " UNION " 7308 " SELECT i, p.parent, " 7309 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 7310 " )" 7311 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 7312 ") " 7313 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;" 7314 "UPDATE recovery.map AS o SET intkey = (" 7315 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 7316 ");" 7317 7318 /* Extract data from page 1 and any linked pages into table 7319 ** recovery.schema. With the same schema as an sqlite_schema table. */ 7320 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 7321 "INSERT INTO recovery.schema SELECT " 7322 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 7323 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 7324 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 7325 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 7326 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 7327 "FROM sqlite_dbdata WHERE pgno IN (" 7328 " SELECT pgno FROM recovery.map WHERE root=1" 7329 ")" 7330 "GROUP BY pgno, cell;" 7331 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 7332 ); 7333 7334 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 7335 ** CREATE TABLE statements that extracted from the existing schema. */ 7336 if( rc==SQLITE_OK ){ 7337 sqlite3_stmt *pStmt = 0; 7338 /* ".recover" might output content in an order which causes immediate 7339 ** foreign key constraints to be violated. So disable foreign-key 7340 ** constraint enforcement to prevent problems when running the output 7341 ** script. */ 7342 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); 7343 raw_printf(pState->out, "BEGIN;\n"); 7344 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 7345 shellPrepare(pState->db, &rc, 7346 "SELECT sql FROM recovery.schema " 7347 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 7348 ); 7349 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7350 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 7351 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 7352 &zCreateTable[12] 7353 ); 7354 } 7355 shellFinalize(&rc, pStmt); 7356 } 7357 7358 /* Figure out if an orphan table will be required. And if so, how many 7359 ** user columns it should contain */ 7360 shellPrepare(pState->db, &rc, 7361 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 7362 , &pLoop 7363 ); 7364 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 7365 nOrphan = sqlite3_column_int(pLoop, 0); 7366 } 7367 shellFinalize(&rc, pLoop); 7368 pLoop = 0; 7369 7370 shellPrepare(pState->db, &rc, 7371 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 7372 ); 7373 7374 shellPrepare(pState->db, &rc, 7375 "SELECT max(field), group_concat(shell_escape_crnl(quote" 7376 "(case when (? AND field<0) then NULL else value end)" 7377 "), ', ')" 7378 ", min(field) " 7379 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 7380 "GROUP BY cell", &pCells 7381 ); 7382 7383 /* Loop through each root page. */ 7384 shellPrepare(pState->db, &rc, 7385 "SELECT root, intkey, max(maxlen) FROM recovery.map" 7386 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 7387 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 7388 ")", &pLoop 7389 ); 7390 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 7391 int iRoot = sqlite3_column_int(pLoop, 0); 7392 int bIntkey = sqlite3_column_int(pLoop, 1); 7393 int nCol = sqlite3_column_int(pLoop, 2); 7394 int bNoop = 0; 7395 RecoverTable *pTab; 7396 7397 assert( bIntkey==0 || bIntkey==1 ); 7398 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 7399 if( bNoop || rc ) continue; 7400 if( pTab==0 ){ 7401 if( pOrphan==0 ){ 7402 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 7403 } 7404 pTab = pOrphan; 7405 if( pTab==0 ) break; 7406 } 7407 7408 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ 7409 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 7410 } 7411 sqlite3_bind_int(pPages, 1, iRoot); 7412 if( bRowids==0 && pTab->iPk<0 ){ 7413 sqlite3_bind_int(pCells, 1, 1); 7414 }else{ 7415 sqlite3_bind_int(pCells, 1, 0); 7416 } 7417 sqlite3_bind_int(pCells, 3, pTab->iPk); 7418 7419 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 7420 int iPgno = sqlite3_column_int(pPages, 0); 7421 sqlite3_bind_int(pCells, 2, iPgno); 7422 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 7423 int nField = sqlite3_column_int(pCells, 0); 7424 int iMin = sqlite3_column_int(pCells, 2); 7425 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 7426 7427 RecoverTable *pTab2 = pTab; 7428 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ 7429 if( pOrphan==0 ){ 7430 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 7431 } 7432 pTab2 = pOrphan; 7433 if( pTab2==0 ) break; 7434 } 7435 7436 nField = nField+1; 7437 if( pTab2==pOrphan ){ 7438 raw_printf(pState->out, 7439 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 7440 pTab2->zQuoted, iRoot, iPgno, nField, 7441 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] 7442 ); 7443 }else{ 7444 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 7445 pTab2->zQuoted, pTab2->azlCol[nField], zVal 7446 ); 7447 } 7448 } 7449 shellReset(&rc, pCells); 7450 } 7451 shellReset(&rc, pPages); 7452 if( pTab!=pOrphan ) recoverFreeTable(pTab); 7453 } 7454 shellFinalize(&rc, pLoop); 7455 shellFinalize(&rc, pPages); 7456 shellFinalize(&rc, pCells); 7457 recoverFreeTable(pOrphan); 7458 7459 /* The rest of the schema */ 7460 if( rc==SQLITE_OK ){ 7461 sqlite3_stmt *pStmt = 0; 7462 shellPrepare(pState->db, &rc, 7463 "SELECT sql, name FROM recovery.schema " 7464 "WHERE sql NOT LIKE 'create table%'", &pStmt 7465 ); 7466 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 7467 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 7468 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 7469 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 7470 char *zPrint = shellMPrintf(&rc, 7471 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", 7472 zName, zName, zSql 7473 ); 7474 raw_printf(pState->out, "%s;\n", zPrint); 7475 sqlite3_free(zPrint); 7476 }else{ 7477 raw_printf(pState->out, "%s;\n", zSql); 7478 } 7479 } 7480 shellFinalize(&rc, pStmt); 7481 } 7482 7483 if( rc==SQLITE_OK ){ 7484 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 7485 raw_printf(pState->out, "COMMIT;\n"); 7486 } 7487 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 7488 return rc; 7489} 7490#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7491 7492/* 7493** If an input line begins with "." then invoke this routine to 7494** process that line. 7495** 7496** Return 1 on error, 2 to exit, and 0 otherwise. 7497*/ 7498static int do_meta_command(char *zLine, ShellState *p){ 7499 int h = 1; 7500 int nArg = 0; 7501 int n, c; 7502 int rc = 0; 7503 char *azArg[52]; 7504 7505#ifndef SQLITE_OMIT_VIRTUALTABLE 7506 if( p->expert.pExpert ){ 7507 expertFinish(p, 1, 0); 7508 } 7509#endif 7510 7511 /* Parse the input line into tokens. 7512 */ 7513 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ 7514 while( IsSpace(zLine[h]) ){ h++; } 7515 if( zLine[h]==0 ) break; 7516 if( zLine[h]=='\'' || zLine[h]=='"' ){ 7517 int delim = zLine[h++]; 7518 azArg[nArg++] = &zLine[h]; 7519 while( zLine[h] && zLine[h]!=delim ){ 7520 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 7521 h++; 7522 } 7523 if( zLine[h]==delim ){ 7524 zLine[h++] = 0; 7525 } 7526 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 7527 }else{ 7528 azArg[nArg++] = &zLine[h]; 7529 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 7530 if( zLine[h] ) zLine[h++] = 0; 7531 resolve_backslashes(azArg[nArg-1]); 7532 } 7533 } 7534 azArg[nArg] = 0; 7535 7536 /* Process the input line. 7537 */ 7538 if( nArg==0 ) return 0; /* no tokens, no error */ 7539 n = strlen30(azArg[0]); 7540 c = azArg[0][0]; 7541 clearTempFile(p); 7542 7543#ifndef SQLITE_OMIT_AUTHORIZATION 7544 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 7545 if( nArg!=2 ){ 7546 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 7547 rc = 1; 7548 goto meta_command_exit; 7549 } 7550 open_db(p, 0); 7551 if( booleanValue(azArg[1]) ){ 7552 sqlite3_set_authorizer(p->db, shellAuth, p); 7553 }else if( p->bSafeModePersist ){ 7554 sqlite3_set_authorizer(p->db, safeModeAuth, p); 7555 }else{ 7556 sqlite3_set_authorizer(p->db, 0, 0); 7557 } 7558 }else 7559#endif 7560 7561#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 7562 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 7563 open_db(p, 0); 7564 failIfSafeMode(p, "cannot run .archive in safe mode"); 7565 rc = arDotCommand(p, 0, azArg, nArg); 7566 }else 7567#endif 7568 7569 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 7570 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 7571 ){ 7572 const char *zDestFile = 0; 7573 const char *zDb = 0; 7574 sqlite3 *pDest; 7575 sqlite3_backup *pBackup; 7576 int j; 7577 int bAsync = 0; 7578 const char *zVfs = 0; 7579 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 7580 for(j=1; j<nArg; j++){ 7581 const char *z = azArg[j]; 7582 if( z[0]=='-' ){ 7583 if( z[1]=='-' ) z++; 7584 if( strcmp(z, "-append")==0 ){ 7585 zVfs = "apndvfs"; 7586 }else 7587 if( strcmp(z, "-async")==0 ){ 7588 bAsync = 1; 7589 }else 7590 { 7591 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 7592 return 1; 7593 } 7594 }else if( zDestFile==0 ){ 7595 zDestFile = azArg[j]; 7596 }else if( zDb==0 ){ 7597 zDb = zDestFile; 7598 zDestFile = azArg[j]; 7599 }else{ 7600 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 7601 return 1; 7602 } 7603 } 7604 if( zDestFile==0 ){ 7605 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 7606 return 1; 7607 } 7608 if( zDb==0 ) zDb = "main"; 7609 rc = sqlite3_open_v2(zDestFile, &pDest, 7610 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 7611 if( rc!=SQLITE_OK ){ 7612 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 7613 close_db(pDest); 7614 return 1; 7615 } 7616 if( bAsync ){ 7617 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7618 0, 0, 0); 7619 } 7620 open_db(p, 0); 7621 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7622 if( pBackup==0 ){ 7623 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7624 close_db(pDest); 7625 return 1; 7626 } 7627 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7628 sqlite3_backup_finish(pBackup); 7629 if( rc==SQLITE_DONE ){ 7630 rc = 0; 7631 }else{ 7632 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7633 rc = 1; 7634 } 7635 close_db(pDest); 7636 }else 7637 7638 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 7639 if( nArg==2 ){ 7640 bail_on_error = booleanValue(azArg[1]); 7641 }else{ 7642 raw_printf(stderr, "Usage: .bail on|off\n"); 7643 rc = 1; 7644 } 7645 }else 7646 7647 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 7648 if( nArg==2 ){ 7649 if( booleanValue(azArg[1]) ){ 7650 setBinaryMode(p->out, 1); 7651 }else{ 7652 setTextMode(p->out, 1); 7653 } 7654 }else{ 7655 raw_printf(stderr, "Usage: .binary on|off\n"); 7656 rc = 1; 7657 } 7658 }else 7659 7660 /* The undocumented ".breakpoint" command causes a call to the no-op 7661 ** routine named test_breakpoint(). 7662 */ 7663 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7664 test_breakpoint(); 7665 }else 7666 7667 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 7668 failIfSafeMode(p, "cannot run .cd in safe mode"); 7669 if( nArg==2 ){ 7670#if defined(_WIN32) || defined(WIN32) 7671 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7672 rc = !SetCurrentDirectoryW(z); 7673 sqlite3_free(z); 7674#else 7675 rc = chdir(azArg[1]); 7676#endif 7677 if( rc ){ 7678 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7679 rc = 1; 7680 } 7681 }else{ 7682 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7683 rc = 1; 7684 } 7685 }else 7686 7687 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7688 if( nArg==2 ){ 7689 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7690 }else{ 7691 raw_printf(stderr, "Usage: .changes on|off\n"); 7692 rc = 1; 7693 } 7694 }else 7695 7696 /* Cancel output redirection, if it is currently set (by .testcase) 7697 ** Then read the content of the testcase-out.txt file and compare against 7698 ** azArg[1]. If there are differences, report an error and exit. 7699 */ 7700 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7701 char *zRes = 0; 7702 output_reset(p); 7703 if( nArg!=2 ){ 7704 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7705 rc = 2; 7706 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7707 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7708 rc = 2; 7709 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7710 utf8_printf(stderr, 7711 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7712 p->zTestcase, azArg[1], zRes); 7713 rc = 1; 7714 }else{ 7715 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7716 p->nCheck++; 7717 } 7718 sqlite3_free(zRes); 7719 }else 7720 7721 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7722 failIfSafeMode(p, "cannot run .clone in safe mode"); 7723 if( nArg==2 ){ 7724 tryToClone(p, azArg[1]); 7725 }else{ 7726 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7727 rc = 1; 7728 } 7729 }else 7730 7731 if( c=='c' && strncmp(azArg[0], "connection", n)==0 ){ 7732 if( nArg==1 ){ 7733 /* List available connections */ 7734 int i; 7735 for(i=0; i<ArraySize(p->aAuxDb); i++){ 7736 const char *zFile = p->aAuxDb[i].zDbFilename; 7737 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ 7738 zFile = "(not open)"; 7739 }else if( zFile==0 ){ 7740 zFile = "(memory)"; 7741 }else if( zFile[0]==0 ){ 7742 zFile = "(temporary-file)"; 7743 } 7744 if( p->pAuxDb == &p->aAuxDb[i] ){ 7745 utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile); 7746 }else if( p->aAuxDb[i].db!=0 ){ 7747 utf8_printf(stdout, " %d: %s\n", i, zFile); 7748 } 7749 } 7750 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){ 7751 int i = azArg[1][0] - '0'; 7752 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ 7753 p->pAuxDb->db = p->db; 7754 p->pAuxDb = &p->aAuxDb[i]; 7755 globalDb = p->db = p->pAuxDb->db; 7756 p->pAuxDb->db = 0; 7757 } 7758 }else if( nArg==3 && strcmp(azArg[1], "close")==0 7759 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){ 7760 int i = azArg[2][0] - '0'; 7761 if( i<0 || i>=ArraySize(p->aAuxDb) ){ 7762 /* No-op */ 7763 }else if( p->pAuxDb == &p->aAuxDb[i] ){ 7764 raw_printf(stderr, "cannot close the active database connection\n"); 7765 rc = 1; 7766 }else if( p->aAuxDb[i].db ){ 7767 session_close_all(p, i); 7768 close_db(p->aAuxDb[i].db); 7769 p->aAuxDb[i].db = 0; 7770 } 7771 }else{ 7772 raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n"); 7773 rc = 1; 7774 } 7775 }else 7776 7777 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7778 char **azName = 0; 7779 int nName = 0; 7780 sqlite3_stmt *pStmt; 7781 int i; 7782 open_db(p, 0); 7783 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 7784 if( rc ){ 7785 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7786 rc = 1; 7787 }else{ 7788 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7789 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1); 7790 const char *zFile = (const char*)sqlite3_column_text(pStmt,2); 7791 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*)); 7792 if( azName==0 ){ shell_out_of_memory(); /* Does not return */ } 7793 azName[nName*2] = strdup(zSchema); 7794 azName[nName*2+1] = strdup(zFile); 7795 nName++; 7796 } 7797 } 7798 sqlite3_finalize(pStmt); 7799 for(i=0; i<nName; i++){ 7800 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); 7801 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); 7802 const char *z = azName[i*2+1]; 7803 utf8_printf(p->out, "%s: %s %s%s\n", 7804 azName[i*2], 7805 z && z[0] ? z : "\"\"", 7806 bRdonly ? "r/o" : "r/w", 7807 eTxn==SQLITE_TXN_NONE ? "" : 7808 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); 7809 free(azName[i*2]); 7810 free(azName[i*2+1]); 7811 } 7812 sqlite3_free(azName); 7813 }else 7814 7815 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7816 static const struct DbConfigChoices { 7817 const char *zName; 7818 int op; 7819 } aDbConfig[] = { 7820 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7821 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7822 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7823 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7824 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7825 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7826 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, 7827 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7828 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7829 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, 7830 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7831 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7832 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7833 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7834 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, 7835 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7836 }; 7837 int ii, v; 7838 open_db(p, 0); 7839 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7840 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7841 if( nArg>=3 ){ 7842 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7843 } 7844 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7845 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7846 if( nArg>1 ) break; 7847 } 7848 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7849 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7850 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7851 } 7852 }else 7853 7854 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7855 rc = shell_dbinfo_command(p, nArg, azArg); 7856 }else 7857 7858#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7859 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7860 open_db(p, 0); 7861 rc = recoverDatabaseCmd(p, nArg, azArg); 7862 }else 7863#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7864 7865 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7866 char *zLike = 0; 7867 char *zSql; 7868 int i; 7869 int savedShowHeader = p->showHeader; 7870 int savedShellFlags = p->shellFlgs; 7871 ShellClearFlag(p, 7872 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo 7873 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys); 7874 for(i=1; i<nArg; i++){ 7875 if( azArg[i][0]=='-' ){ 7876 const char *z = azArg[i]+1; 7877 if( z[0]=='-' ) z++; 7878 if( strcmp(z,"preserve-rowids")==0 ){ 7879#ifdef SQLITE_OMIT_VIRTUALTABLE 7880 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7881 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7882 rc = 1; 7883 sqlite3_free(zLike); 7884 goto meta_command_exit; 7885#else 7886 ShellSetFlag(p, SHFLG_PreserveRowid); 7887#endif 7888 }else 7889 if( strcmp(z,"newlines")==0 ){ 7890 ShellSetFlag(p, SHFLG_Newlines); 7891 }else 7892 if( strcmp(z,"data-only")==0 ){ 7893 ShellSetFlag(p, SHFLG_DumpDataOnly); 7894 }else 7895 if( strcmp(z,"nosys")==0 ){ 7896 ShellSetFlag(p, SHFLG_DumpNoSys); 7897 }else 7898 { 7899 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 7900 rc = 1; 7901 sqlite3_free(zLike); 7902 goto meta_command_exit; 7903 } 7904 }else{ 7905 /* azArg[i] contains a LIKE pattern. This ".dump" request should 7906 ** only dump data for tables for which either the table name matches 7907 ** the LIKE pattern, or the table appears to be a shadow table of 7908 ** a virtual table for which the name matches the LIKE pattern. 7909 */ 7910 char *zExpr = sqlite3_mprintf( 7911 "name LIKE %Q ESCAPE '\\' OR EXISTS (" 7912 " SELECT 1 FROM sqlite_schema WHERE " 7913 " name LIKE %Q ESCAPE '\\' AND" 7914 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND" 7915 " substr(o.name, 1, length(name)+1) == (name||'_')" 7916 ")", azArg[i], azArg[i] 7917 ); 7918 7919 if( zLike ){ 7920 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr); 7921 }else{ 7922 zLike = zExpr; 7923 } 7924 } 7925 } 7926 7927 open_db(p, 0); 7928 7929 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 7930 /* When playing back a "dump", the content might appear in an order 7931 ** which causes immediate foreign key constraints to be violated. 7932 ** So disable foreign-key constraint enforcement to prevent problems. */ 7933 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 7934 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 7935 } 7936 p->writableSchema = 0; 7937 p->showHeader = 0; 7938 /* Set writable_schema=ON since doing so forces SQLite to initialize 7939 ** as much of the schema as it can even if the sqlite_schema table is 7940 ** corrupt. */ 7941 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 7942 p->nErr = 0; 7943 if( zLike==0 ) zLike = sqlite3_mprintf("true"); 7944 zSql = sqlite3_mprintf( 7945 "SELECT name, type, sql FROM sqlite_schema AS o " 7946 "WHERE (%s) AND type=='table'" 7947 " AND sql NOT NULL" 7948 " ORDER BY tbl_name='sqlite_sequence', rowid", 7949 zLike 7950 ); 7951 run_schema_dump_query(p,zSql); 7952 sqlite3_free(zSql); 7953 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 7954 zSql = sqlite3_mprintf( 7955 "SELECT sql FROM sqlite_schema AS o " 7956 "WHERE (%s) AND sql NOT NULL" 7957 " AND type IN ('index','trigger','view')", 7958 zLike 7959 ); 7960 run_table_dump_query(p, zSql); 7961 sqlite3_free(zSql); 7962 } 7963 sqlite3_free(zLike); 7964 if( p->writableSchema ){ 7965 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 7966 p->writableSchema = 0; 7967 } 7968 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 7969 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 7970 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 7971 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 7972 } 7973 p->showHeader = savedShowHeader; 7974 p->shellFlgs = savedShellFlags; 7975 }else 7976 7977 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 7978 if( nArg==2 ){ 7979 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 7980 }else{ 7981 raw_printf(stderr, "Usage: .echo on|off\n"); 7982 rc = 1; 7983 } 7984 }else 7985 7986 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 7987 if( nArg==2 ){ 7988 p->autoEQPtest = 0; 7989 if( p->autoEQPtrace ){ 7990 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 7991 p->autoEQPtrace = 0; 7992 } 7993 if( strcmp(azArg[1],"full")==0 ){ 7994 p->autoEQP = AUTOEQP_full; 7995 }else if( strcmp(azArg[1],"trigger")==0 ){ 7996 p->autoEQP = AUTOEQP_trigger; 7997#ifdef SQLITE_DEBUG 7998 }else if( strcmp(azArg[1],"test")==0 ){ 7999 p->autoEQP = AUTOEQP_on; 8000 p->autoEQPtest = 1; 8001 }else if( strcmp(azArg[1],"trace")==0 ){ 8002 p->autoEQP = AUTOEQP_full; 8003 p->autoEQPtrace = 1; 8004 open_db(p, 0); 8005 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); 8006 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 8007#endif 8008 }else{ 8009 p->autoEQP = (u8)booleanValue(azArg[1]); 8010 } 8011 }else{ 8012 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 8013 rc = 1; 8014 } 8015 }else 8016 8017 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 8018 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 8019 rc = 2; 8020 }else 8021 8022 /* The ".explain" command is automatic now. It is largely pointless. It 8023 ** retained purely for backwards compatibility */ 8024 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 8025 int val = 1; 8026 if( nArg>=2 ){ 8027 if( strcmp(azArg[1],"auto")==0 ){ 8028 val = 99; 8029 }else{ 8030 val = booleanValue(azArg[1]); 8031 } 8032 } 8033 if( val==1 && p->mode!=MODE_Explain ){ 8034 p->normalMode = p->mode; 8035 p->mode = MODE_Explain; 8036 p->autoExplain = 0; 8037 }else if( val==0 ){ 8038 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8039 p->autoExplain = 0; 8040 }else if( val==99 ){ 8041 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8042 p->autoExplain = 1; 8043 } 8044 }else 8045 8046#ifndef SQLITE_OMIT_VIRTUALTABLE 8047 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 8048 open_db(p, 0); 8049 expertDotCommand(p, azArg, nArg); 8050 }else 8051#endif 8052 8053 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ 8054 static const struct { 8055 const char *zCtrlName; /* Name of a test-control option */ 8056 int ctrlCode; /* Integer code for that option */ 8057 const char *zUsage; /* Usage notes */ 8058 } aCtrl[] = { 8059 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 8060 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" }, 8061 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 8062 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 8063 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 8064 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 8065 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 8066 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, 8067 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 8068 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 8069 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 8070 }; 8071 int filectrl = -1; 8072 int iCtrl = -1; 8073 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 8074 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 8075 int n2, i; 8076 const char *zCmd = 0; 8077 const char *zSchema = 0; 8078 8079 open_db(p, 0); 8080 zCmd = nArg>=2 ? azArg[1] : "help"; 8081 8082 if( zCmd[0]=='-' 8083 && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0) 8084 && nArg>=4 8085 ){ 8086 zSchema = azArg[2]; 8087 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; 8088 nArg -= 2; 8089 zCmd = azArg[1]; 8090 } 8091 8092 /* The argument can optionally begin with "-" or "--" */ 8093 if( zCmd[0]=='-' && zCmd[1] ){ 8094 zCmd++; 8095 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 8096 } 8097 8098 /* --help lists all file-controls */ 8099 if( strcmp(zCmd,"help")==0 ){ 8100 utf8_printf(p->out, "Available file-controls:\n"); 8101 for(i=0; i<ArraySize(aCtrl); i++){ 8102 utf8_printf(p->out, " .filectrl %s %s\n", 8103 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 8104 } 8105 rc = 1; 8106 goto meta_command_exit; 8107 } 8108 8109 /* convert filectrl text option to value. allow any unique prefix 8110 ** of the option name, or a numerical value. */ 8111 n2 = strlen30(zCmd); 8112 for(i=0; i<ArraySize(aCtrl); i++){ 8113 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 8114 if( filectrl<0 ){ 8115 filectrl = aCtrl[i].ctrlCode; 8116 iCtrl = i; 8117 }else{ 8118 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 8119 "Use \".filectrl --help\" for help\n", zCmd); 8120 rc = 1; 8121 goto meta_command_exit; 8122 } 8123 } 8124 } 8125 if( filectrl<0 ){ 8126 utf8_printf(stderr,"Error: unknown file-control: %s\n" 8127 "Use \".filectrl --help\" for help\n", zCmd); 8128 }else{ 8129 switch(filectrl){ 8130 case SQLITE_FCNTL_SIZE_LIMIT: { 8131 if( nArg!=2 && nArg!=3 ) break; 8132 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 8133 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 8134 isOk = 1; 8135 break; 8136 } 8137 case SQLITE_FCNTL_LOCK_TIMEOUT: 8138 case SQLITE_FCNTL_CHUNK_SIZE: { 8139 int x; 8140 if( nArg!=3 ) break; 8141 x = (int)integerValue(azArg[2]); 8142 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8143 isOk = 2; 8144 break; 8145 } 8146 case SQLITE_FCNTL_PERSIST_WAL: 8147 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 8148 int x; 8149 if( nArg!=2 && nArg!=3 ) break; 8150 x = nArg==3 ? booleanValue(azArg[2]) : -1; 8151 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8152 iRes = x; 8153 isOk = 1; 8154 break; 8155 } 8156 case SQLITE_FCNTL_DATA_VERSION: 8157 case SQLITE_FCNTL_HAS_MOVED: { 8158 int x; 8159 if( nArg!=2 ) break; 8160 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8161 iRes = x; 8162 isOk = 1; 8163 break; 8164 } 8165 case SQLITE_FCNTL_TEMPFILENAME: { 8166 char *z = 0; 8167 if( nArg!=2 ) break; 8168 sqlite3_file_control(p->db, zSchema, filectrl, &z); 8169 if( z ){ 8170 utf8_printf(p->out, "%s\n", z); 8171 sqlite3_free(z); 8172 } 8173 isOk = 2; 8174 break; 8175 } 8176 case SQLITE_FCNTL_RESERVE_BYTES: { 8177 int x; 8178 if( nArg>=3 ){ 8179 x = atoi(azArg[2]); 8180 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8181 } 8182 x = -1; 8183 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8184 utf8_printf(p->out,"%d\n", x); 8185 isOk = 2; 8186 break; 8187 } 8188 } 8189 } 8190 if( isOk==0 && iCtrl>=0 ){ 8191 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 8192 rc = 1; 8193 }else if( isOk==1 ){ 8194 char zBuf[100]; 8195 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 8196 raw_printf(p->out, "%s\n", zBuf); 8197 } 8198 }else 8199 8200 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 8201 ShellState data; 8202 int doStats = 0; 8203 memcpy(&data, p, sizeof(data)); 8204 data.showHeader = 0; 8205 data.cMode = data.mode = MODE_Semi; 8206 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 8207 data.cMode = data.mode = MODE_Pretty; 8208 nArg = 1; 8209 } 8210 if( nArg!=1 ){ 8211 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 8212 rc = 1; 8213 goto meta_command_exit; 8214 } 8215 open_db(p, 0); 8216 rc = sqlite3_exec(p->db, 8217 "SELECT sql FROM" 8218 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 8219 " FROM sqlite_schema UNION ALL" 8220 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " 8221 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 8222 "ORDER BY x", 8223 callback, &data, 0 8224 ); 8225 if( rc==SQLITE_OK ){ 8226 sqlite3_stmt *pStmt; 8227 rc = sqlite3_prepare_v2(p->db, 8228 "SELECT rowid FROM sqlite_schema" 8229 " WHERE name GLOB 'sqlite_stat[134]'", 8230 -1, &pStmt, 0); 8231 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 8232 sqlite3_finalize(pStmt); 8233 } 8234 if( doStats==0 ){ 8235 raw_printf(p->out, "/* No STAT tables available */\n"); 8236 }else{ 8237 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8238 data.cMode = data.mode = MODE_Insert; 8239 data.zDestTable = "sqlite_stat1"; 8240 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0); 8241 data.zDestTable = "sqlite_stat4"; 8242 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0); 8243 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8244 } 8245 }else 8246 8247 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 8248 if( nArg==2 ){ 8249 p->showHeader = booleanValue(azArg[1]); 8250 p->shellFlgs |= SHFLG_HeaderSet; 8251 }else{ 8252 raw_printf(stderr, "Usage: .headers on|off\n"); 8253 rc = 1; 8254 } 8255 }else 8256 8257 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 8258 if( nArg>=2 ){ 8259 n = showHelp(p->out, azArg[1]); 8260 if( n==0 ){ 8261 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 8262 } 8263 }else{ 8264 showHelp(p->out, 0); 8265 } 8266 }else 8267 8268 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 8269 char *zTable = 0; /* Insert data into this table */ 8270 char *zFile = 0; /* Name of file to extra content from */ 8271 sqlite3_stmt *pStmt = NULL; /* A statement */ 8272 int nCol; /* Number of columns in the table */ 8273 int nByte; /* Number of bytes in an SQL string */ 8274 int i, j; /* Loop counters */ 8275 int needCommit; /* True to COMMIT or ROLLBACK at end */ 8276 int nSep; /* Number of bytes in p->colSeparator[] */ 8277 char *zSql; /* An SQL statement */ 8278 ImportCtx sCtx; /* Reader context */ 8279 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 8280 int eVerbose = 0; /* Larger for more console output */ 8281 int nSkip = 0; /* Initial lines to skip */ 8282 int useOutputMode = 1; /* Use output mode to determine separators */ 8283 8284 failIfSafeMode(p, "cannot run .import in safe mode"); 8285 memset(&sCtx, 0, sizeof(sCtx)); 8286 if( p->mode==MODE_Ascii ){ 8287 xRead = ascii_read_one_field; 8288 }else{ 8289 xRead = csv_read_one_field; 8290 } 8291 for(i=1; i<nArg; i++){ 8292 char *z = azArg[i]; 8293 if( z[0]=='-' && z[1]=='-' ) z++; 8294 if( z[0]!='-' ){ 8295 if( zFile==0 ){ 8296 zFile = z; 8297 }else if( zTable==0 ){ 8298 zTable = z; 8299 }else{ 8300 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z); 8301 showHelp(p->out, "import"); 8302 rc = 1; 8303 goto meta_command_exit; 8304 } 8305 }else if( strcmp(z,"-v")==0 ){ 8306 eVerbose++; 8307 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){ 8308 nSkip = integerValue(azArg[++i]); 8309 }else if( strcmp(z,"-ascii")==0 ){ 8310 sCtx.cColSep = SEP_Unit[0]; 8311 sCtx.cRowSep = SEP_Record[0]; 8312 xRead = ascii_read_one_field; 8313 useOutputMode = 0; 8314 }else if( strcmp(z,"-csv")==0 ){ 8315 sCtx.cColSep = ','; 8316 sCtx.cRowSep = '\n'; 8317 xRead = csv_read_one_field; 8318 useOutputMode = 0; 8319 }else{ 8320 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z); 8321 showHelp(p->out, "import"); 8322 rc = 1; 8323 goto meta_command_exit; 8324 } 8325 } 8326 if( zTable==0 ){ 8327 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n", 8328 zFile==0 ? "FILE" : "TABLE"); 8329 showHelp(p->out, "import"); 8330 rc = 1; 8331 goto meta_command_exit; 8332 } 8333 seenInterrupt = 0; 8334 open_db(p, 0); 8335 if( useOutputMode ){ 8336 /* If neither the --csv or --ascii options are specified, then set 8337 ** the column and row separator characters from the output mode. */ 8338 nSep = strlen30(p->colSeparator); 8339 if( nSep==0 ){ 8340 raw_printf(stderr, 8341 "Error: non-null column separator required for import\n"); 8342 rc = 1; 8343 goto meta_command_exit; 8344 } 8345 if( nSep>1 ){ 8346 raw_printf(stderr, 8347 "Error: multi-character column separators not allowed" 8348 " for import\n"); 8349 rc = 1; 8350 goto meta_command_exit; 8351 } 8352 nSep = strlen30(p->rowSeparator); 8353 if( nSep==0 ){ 8354 raw_printf(stderr, 8355 "Error: non-null row separator required for import\n"); 8356 rc = 1; 8357 goto meta_command_exit; 8358 } 8359 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){ 8360 /* When importing CSV (only), if the row separator is set to the 8361 ** default output row separator, change it to the default input 8362 ** row separator. This avoids having to maintain different input 8363 ** and output row separators. */ 8364 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8365 nSep = strlen30(p->rowSeparator); 8366 } 8367 if( nSep>1 ){ 8368 raw_printf(stderr, "Error: multi-character row separators not allowed" 8369 " for import\n"); 8370 rc = 1; 8371 goto meta_command_exit; 8372 } 8373 sCtx.cColSep = p->colSeparator[0]; 8374 sCtx.cRowSep = p->rowSeparator[0]; 8375 } 8376 sCtx.zFile = zFile; 8377 sCtx.nLine = 1; 8378 if( sCtx.zFile[0]=='|' ){ 8379#ifdef SQLITE_OMIT_POPEN 8380 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8381 rc = 1; 8382 goto meta_command_exit; 8383#else 8384 sCtx.in = popen(sCtx.zFile+1, "r"); 8385 sCtx.zFile = "<pipe>"; 8386 sCtx.xCloser = pclose; 8387#endif 8388 }else{ 8389 sCtx.in = fopen(sCtx.zFile, "rb"); 8390 sCtx.xCloser = fclose; 8391 } 8392 if( sCtx.in==0 ){ 8393 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 8394 rc = 1; 8395 goto meta_command_exit; 8396 } 8397 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ 8398 char zSep[2]; 8399 zSep[1] = 0; 8400 zSep[0] = sCtx.cColSep; 8401 utf8_printf(p->out, "Column separator "); 8402 output_c_string(p->out, zSep); 8403 utf8_printf(p->out, ", row separator "); 8404 zSep[0] = sCtx.cRowSep; 8405 output_c_string(p->out, zSep); 8406 utf8_printf(p->out, "\n"); 8407 } 8408 while( (nSkip--)>0 ){ 8409 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} 8410 } 8411 zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 8412 if( zSql==0 ){ 8413 import_cleanup(&sCtx); 8414 shell_out_of_memory(); 8415 } 8416 nByte = strlen30(zSql); 8417 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8418 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 8419 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 8420 char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable); 8421 char cSep = '('; 8422 while( xRead(&sCtx) ){ 8423 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 8424 cSep = ','; 8425 if( sCtx.cTerm!=sCtx.cColSep ) break; 8426 } 8427 if( cSep=='(' ){ 8428 sqlite3_free(zCreate); 8429 import_cleanup(&sCtx); 8430 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 8431 rc = 1; 8432 goto meta_command_exit; 8433 } 8434 zCreate = sqlite3_mprintf("%z\n)", zCreate); 8435 if( eVerbose>=1 ){ 8436 utf8_printf(p->out, "%s\n", zCreate); 8437 } 8438 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 8439 sqlite3_free(zCreate); 8440 if( rc ){ 8441 utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable, 8442 sqlite3_errmsg(p->db)); 8443 import_cleanup(&sCtx); 8444 rc = 1; 8445 goto meta_command_exit; 8446 } 8447 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8448 } 8449 sqlite3_free(zSql); 8450 if( rc ){ 8451 if (pStmt) sqlite3_finalize(pStmt); 8452 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 8453 import_cleanup(&sCtx); 8454 rc = 1; 8455 goto meta_command_exit; 8456 } 8457 nCol = sqlite3_column_count(pStmt); 8458 sqlite3_finalize(pStmt); 8459 pStmt = 0; 8460 if( nCol==0 ) return 0; /* no columns, no error */ 8461 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 8462 if( zSql==0 ){ 8463 import_cleanup(&sCtx); 8464 shell_out_of_memory(); 8465 } 8466 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); 8467 j = strlen30(zSql); 8468 for(i=1; i<nCol; i++){ 8469 zSql[j++] = ','; 8470 zSql[j++] = '?'; 8471 } 8472 zSql[j++] = ')'; 8473 zSql[j] = 0; 8474 if( eVerbose>=2 ){ 8475 utf8_printf(p->out, "Insert using: %s\n", zSql); 8476 } 8477 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8478 sqlite3_free(zSql); 8479 if( rc ){ 8480 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8481 if (pStmt) sqlite3_finalize(pStmt); 8482 import_cleanup(&sCtx); 8483 rc = 1; 8484 goto meta_command_exit; 8485 } 8486 needCommit = sqlite3_get_autocommit(p->db); 8487 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 8488 do{ 8489 int startLine = sCtx.nLine; 8490 for(i=0; i<nCol; i++){ 8491 char *z = xRead(&sCtx); 8492 /* 8493 ** Did we reach end-of-file before finding any columns? 8494 ** If so, stop instead of NULL filling the remaining columns. 8495 */ 8496 if( z==0 && i==0 ) break; 8497 /* 8498 ** Did we reach end-of-file OR end-of-line before finding any 8499 ** columns in ASCII mode? If so, stop instead of NULL filling 8500 ** the remaining columns. 8501 */ 8502 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 8503 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 8504 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 8505 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8506 "filling the rest with NULL\n", 8507 sCtx.zFile, startLine, nCol, i+1); 8508 i += 2; 8509 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 8510 } 8511 } 8512 if( sCtx.cTerm==sCtx.cColSep ){ 8513 do{ 8514 xRead(&sCtx); 8515 i++; 8516 }while( sCtx.cTerm==sCtx.cColSep ); 8517 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8518 "extras ignored\n", 8519 sCtx.zFile, startLine, nCol, i); 8520 } 8521 if( i>=nCol ){ 8522 sqlite3_step(pStmt); 8523 rc = sqlite3_reset(pStmt); 8524 if( rc!=SQLITE_OK ){ 8525 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 8526 startLine, sqlite3_errmsg(p->db)); 8527 sCtx.nErr++; 8528 }else{ 8529 sCtx.nRow++; 8530 } 8531 } 8532 }while( sCtx.cTerm!=EOF ); 8533 8534 import_cleanup(&sCtx); 8535 sqlite3_finalize(pStmt); 8536 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 8537 if( eVerbose>0 ){ 8538 utf8_printf(p->out, 8539 "Added %d rows with %d errors using %d lines of input\n", 8540 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); 8541 } 8542 }else 8543 8544#ifndef SQLITE_UNTESTABLE 8545 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 8546 char *zSql; 8547 char *zCollist = 0; 8548 sqlite3_stmt *pStmt; 8549 int tnum = 0; 8550 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ 8551 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ 8552 int i; 8553 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 8554 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 8555 " .imposter off\n"); 8556 /* Also allowed, but not documented: 8557 ** 8558 ** .imposter TABLE IMPOSTER 8559 ** 8560 ** where TABLE is a WITHOUT ROWID table. In that case, the 8561 ** imposter is another WITHOUT ROWID table with the columns in 8562 ** storage order. */ 8563 rc = 1; 8564 goto meta_command_exit; 8565 } 8566 open_db(p, 0); 8567 if( nArg==2 ){ 8568 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 8569 goto meta_command_exit; 8570 } 8571 zSql = sqlite3_mprintf( 8572 "SELECT rootpage, 0 FROM sqlite_schema" 8573 " WHERE name='%q' AND type='index'" 8574 "UNION ALL " 8575 "SELECT rootpage, 1 FROM sqlite_schema" 8576 " WHERE name='%q' AND type='table'" 8577 " AND sql LIKE '%%without%%rowid%%'", 8578 azArg[1], azArg[1] 8579 ); 8580 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8581 sqlite3_free(zSql); 8582 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 8583 tnum = sqlite3_column_int(pStmt, 0); 8584 isWO = sqlite3_column_int(pStmt, 1); 8585 } 8586 sqlite3_finalize(pStmt); 8587 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 8588 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8589 sqlite3_free(zSql); 8590 i = 0; 8591 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8592 char zLabel[20]; 8593 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 8594 i++; 8595 if( zCol==0 ){ 8596 if( sqlite3_column_int(pStmt,1)==-1 ){ 8597 zCol = "_ROWID_"; 8598 }else{ 8599 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 8600 zCol = zLabel; 8601 } 8602 } 8603 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ 8604 lenPK = (int)strlen(zCollist); 8605 } 8606 if( zCollist==0 ){ 8607 zCollist = sqlite3_mprintf("\"%w\"", zCol); 8608 }else{ 8609 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 8610 } 8611 } 8612 sqlite3_finalize(pStmt); 8613 if( i==0 || tnum==0 ){ 8614 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 8615 rc = 1; 8616 sqlite3_free(zCollist); 8617 goto meta_command_exit; 8618 } 8619 if( lenPK==0 ) lenPK = 100000; 8620 zSql = sqlite3_mprintf( 8621 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", 8622 azArg[2], zCollist, lenPK, zCollist); 8623 sqlite3_free(zCollist); 8624 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 8625 if( rc==SQLITE_OK ){ 8626 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 8627 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 8628 if( rc ){ 8629 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 8630 }else{ 8631 utf8_printf(stdout, "%s;\n", zSql); 8632 raw_printf(stdout, 8633 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n", 8634 azArg[1], isWO ? "table" : "index" 8635 ); 8636 } 8637 }else{ 8638 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 8639 rc = 1; 8640 } 8641 sqlite3_free(zSql); 8642 }else 8643#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 8644 8645#ifdef SQLITE_ENABLE_IOTRACE 8646 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 8647 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 8648 if( iotrace && iotrace!=stdout ) fclose(iotrace); 8649 iotrace = 0; 8650 if( nArg<2 ){ 8651 sqlite3IoTrace = 0; 8652 }else if( strcmp(azArg[1], "-")==0 ){ 8653 sqlite3IoTrace = iotracePrintf; 8654 iotrace = stdout; 8655 }else{ 8656 iotrace = fopen(azArg[1], "w"); 8657 if( iotrace==0 ){ 8658 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 8659 sqlite3IoTrace = 0; 8660 rc = 1; 8661 }else{ 8662 sqlite3IoTrace = iotracePrintf; 8663 } 8664 } 8665 }else 8666#endif 8667 8668 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 8669 static const struct { 8670 const char *zLimitName; /* Name of a limit */ 8671 int limitCode; /* Integer code for that limit */ 8672 } aLimit[] = { 8673 { "length", SQLITE_LIMIT_LENGTH }, 8674 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 8675 { "column", SQLITE_LIMIT_COLUMN }, 8676 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 8677 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 8678 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 8679 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 8680 { "attached", SQLITE_LIMIT_ATTACHED }, 8681 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 8682 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 8683 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 8684 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 8685 }; 8686 int i, n2; 8687 open_db(p, 0); 8688 if( nArg==1 ){ 8689 for(i=0; i<ArraySize(aLimit); i++){ 8690 printf("%20s %d\n", aLimit[i].zLimitName, 8691 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 8692 } 8693 }else if( nArg>3 ){ 8694 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 8695 rc = 1; 8696 goto meta_command_exit; 8697 }else{ 8698 int iLimit = -1; 8699 n2 = strlen30(azArg[1]); 8700 for(i=0; i<ArraySize(aLimit); i++){ 8701 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 8702 if( iLimit<0 ){ 8703 iLimit = i; 8704 }else{ 8705 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 8706 rc = 1; 8707 goto meta_command_exit; 8708 } 8709 } 8710 } 8711 if( iLimit<0 ){ 8712 utf8_printf(stderr, "unknown limit: \"%s\"\n" 8713 "enter \".limits\" with no arguments for a list.\n", 8714 azArg[1]); 8715 rc = 1; 8716 goto meta_command_exit; 8717 } 8718 if( nArg==3 ){ 8719 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 8720 (int)integerValue(azArg[2])); 8721 } 8722 printf("%20s %d\n", aLimit[iLimit].zLimitName, 8723 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 8724 } 8725 }else 8726 8727 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 8728 open_db(p, 0); 8729 lintDotCommand(p, azArg, nArg); 8730 }else 8731 8732#ifndef SQLITE_OMIT_LOAD_EXTENSION 8733 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 8734 const char *zFile, *zProc; 8735 char *zErrMsg = 0; 8736 failIfSafeMode(p, "cannot run .load in safe mode"); 8737 if( nArg<2 ){ 8738 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 8739 rc = 1; 8740 goto meta_command_exit; 8741 } 8742 zFile = azArg[1]; 8743 zProc = nArg>=3 ? azArg[2] : 0; 8744 open_db(p, 0); 8745 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 8746 if( rc!=SQLITE_OK ){ 8747 utf8_printf(stderr, "Error: %s\n", zErrMsg); 8748 sqlite3_free(zErrMsg); 8749 rc = 1; 8750 } 8751 }else 8752#endif 8753 8754 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 8755 failIfSafeMode(p, "cannot run .log in safe mode"); 8756 if( nArg!=2 ){ 8757 raw_printf(stderr, "Usage: .log FILENAME\n"); 8758 rc = 1; 8759 }else{ 8760 const char *zFile = azArg[1]; 8761 output_file_close(p->pLog); 8762 p->pLog = output_file_open(zFile, 0); 8763 } 8764 }else 8765 8766 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 8767 const char *zMode = nArg>=2 ? azArg[1] : ""; 8768 int n2 = strlen30(zMode); 8769 int c2 = zMode[0]; 8770 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 8771 p->mode = MODE_Line; 8772 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8773 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 8774 p->mode = MODE_Column; 8775 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ 8776 p->showHeader = 1; 8777 } 8778 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8779 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 8780 p->mode = MODE_List; 8781 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 8782 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8783 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 8784 p->mode = MODE_Html; 8785 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 8786 p->mode = MODE_Tcl; 8787 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 8788 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8789 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 8790 p->mode = MODE_Csv; 8791 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8792 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8793 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 8794 p->mode = MODE_List; 8795 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 8796 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 8797 p->mode = MODE_Insert; 8798 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 8799 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 8800 p->mode = MODE_Quote; 8801 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8802 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8803 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 8804 p->mode = MODE_Ascii; 8805 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 8806 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 8807 }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){ 8808 p->mode = MODE_Markdown; 8809 }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){ 8810 p->mode = MODE_Table; 8811 }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){ 8812 p->mode = MODE_Box; 8813 }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){ 8814 p->mode = MODE_Json; 8815 }else if( nArg==1 ){ 8816 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 8817 }else{ 8818 raw_printf(stderr, "Error: mode should be one of: " 8819 "ascii box column csv html insert json line list markdown " 8820 "quote table tabs tcl\n"); 8821 rc = 1; 8822 } 8823 p->cMode = p->mode; 8824 }else 8825 8826 if( c=='n' && strcmp(azArg[0], "nonce")==0 ){ 8827 if( nArg!=2 ){ 8828 raw_printf(stderr, "Usage: .nonce NONCE\n"); 8829 rc = 1; 8830 }else if( p->zNonce==0 || strcmp(azArg[1],p->zNonce)!=0 ){ 8831 raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", p->lineno, azArg[1]); 8832 exit(1); 8833 }else{ 8834 p->bSafeMode = 0; 8835 return 0; /* Return immediately to bypass the safe mode reset 8836 ** at the end of this procedure */ 8837 } 8838 }else 8839 8840 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 8841 if( nArg==2 ){ 8842 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 8843 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 8844 }else{ 8845 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 8846 rc = 1; 8847 } 8848 }else 8849 8850#ifdef SQLITE_DEBUG 8851 if( c=='o' && strcmp(azArg[0],"oom")==0 ){ 8852 int i; 8853 for(i=1; i<nArg; i++){ 8854 const char *z = azArg[i]; 8855 if( z[0]=='-' && z[1]=='-' ) z++; 8856 if( strcmp(z,"-repeat")==0 ){ 8857 if( i==nArg-1 ){ 8858 raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]); 8859 rc = 1; 8860 }else{ 8861 oomRepeat = (int)integerValue(azArg[++i]); 8862 } 8863 }else if( IsDigit(z[0]) ){ 8864 oomCounter = (int)integerValue(azArg[i]); 8865 }else{ 8866 raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]); 8867 raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n"); 8868 rc = 1; 8869 } 8870 } 8871 if( rc==0 ){ 8872 raw_printf(p->out, "oomCounter = %d\n", oomCounter); 8873 raw_printf(p->out, "oomRepeat = %d\n", oomRepeat); 8874 } 8875 }else 8876#endif /* SQLITE_DEBUG */ 8877 8878 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 8879 char *zNewFilename = 0; /* Name of the database file to open */ 8880 int iName = 1; /* Index in azArg[] of the filename */ 8881 int newFlag = 0; /* True to delete file before opening */ 8882 /* Close the existing database */ 8883 session_close_all(p, -1); 8884 close_db(p->db); 8885 p->db = 0; 8886 p->pAuxDb->zDbFilename = 0; 8887 sqlite3_free(p->pAuxDb->zFreeOnClose); 8888 p->pAuxDb->zFreeOnClose = 0; 8889 p->openMode = SHELL_OPEN_UNSPEC; 8890 p->openFlags = 0; 8891 p->szMax = 0; 8892 /* Check for command-line arguments */ 8893 for(iName=1; iName<nArg; iName++){ 8894 const char *z = azArg[iName]; 8895 if( optionMatch(z,"new") ){ 8896 newFlag = 1; 8897#ifdef SQLITE_HAVE_ZLIB 8898 }else if( optionMatch(z, "zip") ){ 8899 p->openMode = SHELL_OPEN_ZIPFILE; 8900#endif 8901 }else if( optionMatch(z, "append") ){ 8902 p->openMode = SHELL_OPEN_APPENDVFS; 8903 }else if( optionMatch(z, "readonly") ){ 8904 p->openMode = SHELL_OPEN_READONLY; 8905 }else if( optionMatch(z, "nofollow") ){ 8906 p->openFlags |= SQLITE_OPEN_NOFOLLOW; 8907#ifndef SQLITE_OMIT_DESERIALIZE 8908 }else if( optionMatch(z, "deserialize") ){ 8909 p->openMode = SHELL_OPEN_DESERIALIZE; 8910 }else if( optionMatch(z, "hexdb") ){ 8911 p->openMode = SHELL_OPEN_HEXDB; 8912 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 8913 p->szMax = integerValue(azArg[++iName]); 8914#endif /* SQLITE_OMIT_DESERIALIZE */ 8915 }else if( z[0]=='-' ){ 8916 utf8_printf(stderr, "unknown option: %s\n", z); 8917 rc = 1; 8918 goto meta_command_exit; 8919 }else if( zNewFilename ){ 8920 utf8_printf(stderr, "extra argument: \"%s\"\n", z); 8921 rc = 1; 8922 goto meta_command_exit; 8923 }else{ 8924 zNewFilename = sqlite3_mprintf("%s", z); 8925 } 8926 } 8927 /* If a filename is specified, try to open it first */ 8928 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ 8929 if( newFlag && !p->bSafeMode ) shellDeleteFile(zNewFilename); 8930 if( p->bSafeMode 8931 && p->openMode!=SHELL_OPEN_HEXDB 8932 && zNewFilename 8933 && strcmp(zNewFilename,":memory:")!=0 8934 ){ 8935 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); 8936 } 8937 p->pAuxDb->zDbFilename = zNewFilename; 8938 open_db(p, OPEN_DB_KEEPALIVE); 8939 if( p->db==0 ){ 8940 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 8941 sqlite3_free(zNewFilename); 8942 }else{ 8943 p->pAuxDb->zFreeOnClose = zNewFilename; 8944 } 8945 } 8946 if( p->db==0 ){ 8947 /* As a fall-back open a TEMP database */ 8948 p->pAuxDb->zDbFilename = 0; 8949 open_db(p, 0); 8950 } 8951 }else 8952 8953 if( (c=='o' 8954 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 8955 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 8956 ){ 8957 char *zFile = 0; 8958 int bTxtMode = 0; 8959 int i; 8960 int eMode = 0; 8961 int bBOM = 0; 8962 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */ 8963 8964 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 8965 if( c=='e' ){ 8966 eMode = 'x'; 8967 bOnce = 2; 8968 }else if( strncmp(azArg[0],"once",n)==0 ){ 8969 bOnce = 1; 8970 } 8971 for(i=1; i<nArg; i++){ 8972 char *z = azArg[i]; 8973 if( z[0]=='-' ){ 8974 if( z[1]=='-' ) z++; 8975 if( strcmp(z,"-bom")==0 ){ 8976 bBOM = 1; 8977 }else if( c!='e' && strcmp(z,"-x")==0 ){ 8978 eMode = 'x'; /* spreadsheet */ 8979 }else if( c!='e' && strcmp(z,"-e")==0 ){ 8980 eMode = 'e'; /* text editor */ 8981 }else{ 8982 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", 8983 azArg[i]); 8984 showHelp(p->out, azArg[0]); 8985 rc = 1; 8986 goto meta_command_exit; 8987 } 8988 }else if( zFile==0 && eMode!='e' && eMode!='x' ){ 8989 zFile = sqlite3_mprintf("%s", z); 8990 if( zFile[0]=='|' ){ 8991 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]); 8992 break; 8993 } 8994 }else{ 8995 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n", 8996 azArg[i]); 8997 showHelp(p->out, azArg[0]); 8998 rc = 1; 8999 sqlite3_free(zFile); 9000 goto meta_command_exit; 9001 } 9002 } 9003 if( zFile==0 ) zFile = sqlite3_mprintf("stdout"); 9004 if( bOnce ){ 9005 p->outCount = 2; 9006 }else{ 9007 p->outCount = 0; 9008 } 9009 output_reset(p); 9010#ifndef SQLITE_NOHAVE_SYSTEM 9011 if( eMode=='e' || eMode=='x' ){ 9012 p->doXdgOpen = 1; 9013 outputModePush(p); 9014 if( eMode=='x' ){ 9015 /* spreadsheet mode. Output as CSV. */ 9016 newTempFile(p, "csv"); 9017 ShellClearFlag(p, SHFLG_Echo); 9018 p->mode = MODE_Csv; 9019 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 9020 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 9021 }else{ 9022 /* text editor mode */ 9023 newTempFile(p, "txt"); 9024 bTxtMode = 1; 9025 } 9026 sqlite3_free(zFile); 9027 zFile = sqlite3_mprintf("%s", p->zTempFile); 9028 } 9029#endif /* SQLITE_NOHAVE_SYSTEM */ 9030 if( zFile[0]=='|' ){ 9031#ifdef SQLITE_OMIT_POPEN 9032 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9033 rc = 1; 9034 p->out = stdout; 9035#else 9036 p->out = popen(zFile + 1, "w"); 9037 if( p->out==0 ){ 9038 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 9039 p->out = stdout; 9040 rc = 1; 9041 }else{ 9042 if( bBOM ) fprintf(p->out,"\357\273\277"); 9043 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9044 } 9045#endif 9046 }else{ 9047 p->out = output_file_open(zFile, bTxtMode); 9048 if( p->out==0 ){ 9049 if( strcmp(zFile,"off")!=0 ){ 9050 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 9051 } 9052 p->out = stdout; 9053 rc = 1; 9054 } else { 9055 if( bBOM ) fprintf(p->out,"\357\273\277"); 9056 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9057 } 9058 } 9059 sqlite3_free(zFile); 9060 }else 9061 9062 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 9063 open_db(p,0); 9064 if( nArg<=1 ) goto parameter_syntax_error; 9065 9066 /* .parameter clear 9067 ** Clear all bind parameters by dropping the TEMP table that holds them. 9068 */ 9069 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 9070 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 9071 0, 0, 0); 9072 }else 9073 9074 /* .parameter list 9075 ** List all bind parameters. 9076 */ 9077 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 9078 sqlite3_stmt *pStmt = 0; 9079 int rx; 9080 int len = 0; 9081 rx = sqlite3_prepare_v2(p->db, 9082 "SELECT max(length(key)) " 9083 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9084 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9085 len = sqlite3_column_int(pStmt, 0); 9086 if( len>40 ) len = 40; 9087 } 9088 sqlite3_finalize(pStmt); 9089 pStmt = 0; 9090 if( len ){ 9091 rx = sqlite3_prepare_v2(p->db, 9092 "SELECT key, quote(value) " 9093 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9094 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9095 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 9096 sqlite3_column_text(pStmt,1)); 9097 } 9098 sqlite3_finalize(pStmt); 9099 } 9100 }else 9101 9102 /* .parameter init 9103 ** Make sure the TEMP table used to hold bind parameters exists. 9104 ** Create it if necessary. 9105 */ 9106 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 9107 bind_table_init(p); 9108 }else 9109 9110 /* .parameter set NAME VALUE 9111 ** Set or reset a bind parameter. NAME should be the full parameter 9112 ** name exactly as it appears in the query. (ex: $abc, @def). The 9113 ** VALUE can be in either SQL literal notation, or if not it will be 9114 ** understood to be a text string. 9115 */ 9116 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 9117 int rx; 9118 char *zSql; 9119 sqlite3_stmt *pStmt; 9120 const char *zKey = azArg[2]; 9121 const char *zValue = azArg[3]; 9122 bind_table_init(p); 9123 zSql = sqlite3_mprintf( 9124 "REPLACE INTO temp.sqlite_parameters(key,value)" 9125 "VALUES(%Q,%s);", zKey, zValue); 9126 if( zSql==0 ) shell_out_of_memory(); 9127 pStmt = 0; 9128 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9129 sqlite3_free(zSql); 9130 if( rx!=SQLITE_OK ){ 9131 sqlite3_finalize(pStmt); 9132 pStmt = 0; 9133 zSql = sqlite3_mprintf( 9134 "REPLACE INTO temp.sqlite_parameters(key,value)" 9135 "VALUES(%Q,%Q);", zKey, zValue); 9136 if( zSql==0 ) shell_out_of_memory(); 9137 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9138 sqlite3_free(zSql); 9139 if( rx!=SQLITE_OK ){ 9140 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 9141 sqlite3_finalize(pStmt); 9142 pStmt = 0; 9143 rc = 1; 9144 } 9145 } 9146 sqlite3_step(pStmt); 9147 sqlite3_finalize(pStmt); 9148 }else 9149 9150 /* .parameter unset NAME 9151 ** Remove the NAME binding from the parameter binding table, if it 9152 ** exists. 9153 */ 9154 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 9155 char *zSql = sqlite3_mprintf( 9156 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 9157 if( zSql==0 ) shell_out_of_memory(); 9158 sqlite3_exec(p->db, zSql, 0, 0, 0); 9159 sqlite3_free(zSql); 9160 }else 9161 /* If no command name matches, show a syntax error */ 9162 parameter_syntax_error: 9163 showHelp(p->out, "parameter"); 9164 }else 9165 9166 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 9167 int i; 9168 for(i=1; i<nArg; i++){ 9169 if( i>1 ) raw_printf(p->out, " "); 9170 utf8_printf(p->out, "%s", azArg[i]); 9171 } 9172 raw_printf(p->out, "\n"); 9173 }else 9174 9175#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 9176 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 9177 int i; 9178 int nn = 0; 9179 p->flgProgress = 0; 9180 p->mxProgress = 0; 9181 p->nProgress = 0; 9182 for(i=1; i<nArg; i++){ 9183 const char *z = azArg[i]; 9184 if( z[0]=='-' ){ 9185 z++; 9186 if( z[0]=='-' ) z++; 9187 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 9188 p->flgProgress |= SHELL_PROGRESS_QUIET; 9189 continue; 9190 } 9191 if( strcmp(z,"reset")==0 ){ 9192 p->flgProgress |= SHELL_PROGRESS_RESET; 9193 continue; 9194 } 9195 if( strcmp(z,"once")==0 ){ 9196 p->flgProgress |= SHELL_PROGRESS_ONCE; 9197 continue; 9198 } 9199 if( strcmp(z,"limit")==0 ){ 9200 if( i+1>=nArg ){ 9201 utf8_printf(stderr, "Error: missing argument on --limit\n"); 9202 rc = 1; 9203 goto meta_command_exit; 9204 }else{ 9205 p->mxProgress = (int)integerValue(azArg[++i]); 9206 } 9207 continue; 9208 } 9209 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 9210 rc = 1; 9211 goto meta_command_exit; 9212 }else{ 9213 nn = (int)integerValue(z); 9214 } 9215 } 9216 open_db(p, 0); 9217 sqlite3_progress_handler(p->db, nn, progress_handler, p); 9218 }else 9219#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 9220 9221 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 9222 if( nArg >= 2) { 9223 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 9224 } 9225 if( nArg >= 3) { 9226 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 9227 } 9228 }else 9229 9230 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 9231 rc = 2; 9232 }else 9233 9234 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 9235 FILE *inSaved = p->in; 9236 int savedLineno = p->lineno; 9237 failIfSafeMode(p, "cannot run .read in safe mode"); 9238 if( nArg!=2 ){ 9239 raw_printf(stderr, "Usage: .read FILE\n"); 9240 rc = 1; 9241 goto meta_command_exit; 9242 } 9243 if( azArg[1][0]=='|' ){ 9244#ifdef SQLITE_OMIT_POPEN 9245 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9246 rc = 1; 9247 p->out = stdout; 9248#else 9249 p->in = popen(azArg[1]+1, "r"); 9250 if( p->in==0 ){ 9251 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 9252 rc = 1; 9253 }else{ 9254 rc = process_input(p); 9255 pclose(p->in); 9256 } 9257#endif 9258 }else if( (p->in = openChrSource(azArg[1]))==0 ){ 9259 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 9260 rc = 1; 9261 }else{ 9262 rc = process_input(p); 9263 fclose(p->in); 9264 } 9265 p->in = inSaved; 9266 p->lineno = savedLineno; 9267 }else 9268 9269 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 9270 const char *zSrcFile; 9271 const char *zDb; 9272 sqlite3 *pSrc; 9273 sqlite3_backup *pBackup; 9274 int nTimeout = 0; 9275 9276 failIfSafeMode(p, "cannot run .restore in safe mode"); 9277 if( nArg==2 ){ 9278 zSrcFile = azArg[1]; 9279 zDb = "main"; 9280 }else if( nArg==3 ){ 9281 zSrcFile = azArg[2]; 9282 zDb = azArg[1]; 9283 }else{ 9284 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 9285 rc = 1; 9286 goto meta_command_exit; 9287 } 9288 rc = sqlite3_open(zSrcFile, &pSrc); 9289 if( rc!=SQLITE_OK ){ 9290 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 9291 close_db(pSrc); 9292 return 1; 9293 } 9294 open_db(p, 0); 9295 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 9296 if( pBackup==0 ){ 9297 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9298 close_db(pSrc); 9299 return 1; 9300 } 9301 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 9302 || rc==SQLITE_BUSY ){ 9303 if( rc==SQLITE_BUSY ){ 9304 if( nTimeout++ >= 3 ) break; 9305 sqlite3_sleep(100); 9306 } 9307 } 9308 sqlite3_backup_finish(pBackup); 9309 if( rc==SQLITE_DONE ){ 9310 rc = 0; 9311 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 9312 raw_printf(stderr, "Error: source database is busy\n"); 9313 rc = 1; 9314 }else{ 9315 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9316 rc = 1; 9317 } 9318 close_db(pSrc); 9319 }else 9320 9321 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 9322 if( nArg==2 ){ 9323 p->scanstatsOn = (u8)booleanValue(azArg[1]); 9324#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 9325 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 9326#endif 9327 }else{ 9328 raw_printf(stderr, "Usage: .scanstats on|off\n"); 9329 rc = 1; 9330 } 9331 }else 9332 9333 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 9334 ShellText sSelect; 9335 ShellState data; 9336 char *zErrMsg = 0; 9337 const char *zDiv = "("; 9338 const char *zName = 0; 9339 int iSchema = 0; 9340 int bDebug = 0; 9341 int bNoSystemTabs = 0; 9342 int ii; 9343 9344 open_db(p, 0); 9345 memcpy(&data, p, sizeof(data)); 9346 data.showHeader = 0; 9347 data.cMode = data.mode = MODE_Semi; 9348 initText(&sSelect); 9349 for(ii=1; ii<nArg; ii++){ 9350 if( optionMatch(azArg[ii],"indent") ){ 9351 data.cMode = data.mode = MODE_Pretty; 9352 }else if( optionMatch(azArg[ii],"debug") ){ 9353 bDebug = 1; 9354 }else if( optionMatch(azArg[ii],"nosys") ){ 9355 bNoSystemTabs = 1; 9356 }else if( azArg[ii][0]=='-' ){ 9357 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]); 9358 rc = 1; 9359 goto meta_command_exit; 9360 }else if( zName==0 ){ 9361 zName = azArg[ii]; 9362 }else{ 9363 raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); 9364 rc = 1; 9365 goto meta_command_exit; 9366 } 9367 } 9368 if( zName!=0 ){ 9369 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0 9370 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0 9371 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 9372 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0; 9373 if( isSchema ){ 9374 char *new_argv[2], *new_colv[2]; 9375 new_argv[0] = sqlite3_mprintf( 9376 "CREATE TABLE %s (\n" 9377 " type text,\n" 9378 " name text,\n" 9379 " tbl_name text,\n" 9380 " rootpage integer,\n" 9381 " sql text\n" 9382 ")", zName); 9383 new_argv[1] = 0; 9384 new_colv[0] = "sql"; 9385 new_colv[1] = 0; 9386 callback(&data, 1, new_argv, new_colv); 9387 sqlite3_free(new_argv[0]); 9388 } 9389 } 9390 if( zDiv ){ 9391 sqlite3_stmt *pStmt = 0; 9392 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 9393 -1, &pStmt, 0); 9394 if( rc ){ 9395 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9396 sqlite3_finalize(pStmt); 9397 rc = 1; 9398 goto meta_command_exit; 9399 } 9400 appendText(&sSelect, "SELECT sql FROM", 0); 9401 iSchema = 0; 9402 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9403 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 9404 char zScNum[30]; 9405 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 9406 appendText(&sSelect, zDiv, 0); 9407 zDiv = " UNION ALL "; 9408 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 9409 if( sqlite3_stricmp(zDb, "main")!=0 ){ 9410 appendText(&sSelect, zDb, '\''); 9411 }else{ 9412 appendText(&sSelect, "NULL", 0); 9413 } 9414 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 9415 appendText(&sSelect, zScNum, 0); 9416 appendText(&sSelect, " AS snum, ", 0); 9417 appendText(&sSelect, zDb, '\''); 9418 appendText(&sSelect, " AS sname FROM ", 0); 9419 appendText(&sSelect, zDb, quoteChar(zDb)); 9420 appendText(&sSelect, ".sqlite_schema", 0); 9421 } 9422 sqlite3_finalize(pStmt); 9423#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 9424 if( zName ){ 9425 appendText(&sSelect, 9426 " UNION ALL SELECT shell_module_schema(name)," 9427 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 9428 0); 9429 } 9430#endif 9431 appendText(&sSelect, ") WHERE ", 0); 9432 if( zName ){ 9433 char *zQarg = sqlite3_mprintf("%Q", zName); 9434 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 9435 strchr(zName, '[') != 0; 9436 if( strchr(zName, '.') ){ 9437 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 9438 }else{ 9439 appendText(&sSelect, "lower(tbl_name)", 0); 9440 } 9441 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 9442 appendText(&sSelect, zQarg, 0); 9443 if( !bGlob ){ 9444 appendText(&sSelect, " ESCAPE '\\' ", 0); 9445 } 9446 appendText(&sSelect, " AND ", 0); 9447 sqlite3_free(zQarg); 9448 } 9449 if( bNoSystemTabs ){ 9450 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0); 9451 } 9452 appendText(&sSelect, "sql IS NOT NULL" 9453 " ORDER BY snum, rowid", 0); 9454 if( bDebug ){ 9455 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 9456 }else{ 9457 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 9458 } 9459 freeText(&sSelect); 9460 } 9461 if( zErrMsg ){ 9462 utf8_printf(stderr,"Error: %s\n", zErrMsg); 9463 sqlite3_free(zErrMsg); 9464 rc = 1; 9465 }else if( rc != SQLITE_OK ){ 9466 raw_printf(stderr,"Error: querying schema information\n"); 9467 rc = 1; 9468 }else{ 9469 rc = 0; 9470 } 9471 }else 9472 9473 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 9474 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 9475 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x); 9476 }else 9477 9478#if defined(SQLITE_ENABLE_SESSION) 9479 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 9480 struct AuxDb *pAuxDb = p->pAuxDb; 9481 OpenSession *pSession = &pAuxDb->aSession[0]; 9482 char **azCmd = &azArg[1]; 9483 int iSes = 0; 9484 int nCmd = nArg - 1; 9485 int i; 9486 if( nArg<=1 ) goto session_syntax_error; 9487 open_db(p, 0); 9488 if( nArg>=3 ){ 9489 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ 9490 if( strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; 9491 } 9492 if( iSes<pAuxDb->nSession ){ 9493 pSession = &pAuxDb->aSession[iSes]; 9494 azCmd++; 9495 nCmd--; 9496 }else{ 9497 pSession = &pAuxDb->aSession[0]; 9498 iSes = 0; 9499 } 9500 } 9501 9502 /* .session attach TABLE 9503 ** Invoke the sqlite3session_attach() interface to attach a particular 9504 ** table so that it is never filtered. 9505 */ 9506 if( strcmp(azCmd[0],"attach")==0 ){ 9507 if( nCmd!=2 ) goto session_syntax_error; 9508 if( pSession->p==0 ){ 9509 session_not_open: 9510 raw_printf(stderr, "ERROR: No sessions are open\n"); 9511 }else{ 9512 rc = sqlite3session_attach(pSession->p, azCmd[1]); 9513 if( rc ){ 9514 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 9515 rc = 0; 9516 } 9517 } 9518 }else 9519 9520 /* .session changeset FILE 9521 ** .session patchset FILE 9522 ** Write a changeset or patchset into a file. The file is overwritten. 9523 */ 9524 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 9525 FILE *out = 0; 9526 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]); 9527 if( nCmd!=2 ) goto session_syntax_error; 9528 if( pSession->p==0 ) goto session_not_open; 9529 out = fopen(azCmd[1], "wb"); 9530 if( out==0 ){ 9531 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", 9532 azCmd[1]); 9533 }else{ 9534 int szChng; 9535 void *pChng; 9536 if( azCmd[0][0]=='c' ){ 9537 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 9538 }else{ 9539 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 9540 } 9541 if( rc ){ 9542 printf("Error: error code %d\n", rc); 9543 rc = 0; 9544 } 9545 if( pChng 9546 && fwrite(pChng, szChng, 1, out)!=1 ){ 9547 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 9548 szChng); 9549 } 9550 sqlite3_free(pChng); 9551 fclose(out); 9552 } 9553 }else 9554 9555 /* .session close 9556 ** Close the identified session 9557 */ 9558 if( strcmp(azCmd[0], "close")==0 ){ 9559 if( nCmd!=1 ) goto session_syntax_error; 9560 if( pAuxDb->nSession ){ 9561 session_close(pSession); 9562 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; 9563 } 9564 }else 9565 9566 /* .session enable ?BOOLEAN? 9567 ** Query or set the enable flag 9568 */ 9569 if( strcmp(azCmd[0], "enable")==0 ){ 9570 int ii; 9571 if( nCmd>2 ) goto session_syntax_error; 9572 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9573 if( pAuxDb->nSession ){ 9574 ii = sqlite3session_enable(pSession->p, ii); 9575 utf8_printf(p->out, "session %s enable flag = %d\n", 9576 pSession->zName, ii); 9577 } 9578 }else 9579 9580 /* .session filter GLOB .... 9581 ** Set a list of GLOB patterns of table names to be excluded. 9582 */ 9583 if( strcmp(azCmd[0], "filter")==0 ){ 9584 int ii, nByte; 9585 if( nCmd<2 ) goto session_syntax_error; 9586 if( pAuxDb->nSession ){ 9587 for(ii=0; ii<pSession->nFilter; ii++){ 9588 sqlite3_free(pSession->azFilter[ii]); 9589 } 9590 sqlite3_free(pSession->azFilter); 9591 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 9592 pSession->azFilter = sqlite3_malloc( nByte ); 9593 if( pSession->azFilter==0 ){ 9594 raw_printf(stderr, "Error: out or memory\n"); 9595 exit(1); 9596 } 9597 for(ii=1; ii<nCmd; ii++){ 9598 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 9599 } 9600 pSession->nFilter = ii-1; 9601 } 9602 }else 9603 9604 /* .session indirect ?BOOLEAN? 9605 ** Query or set the indirect flag 9606 */ 9607 if( strcmp(azCmd[0], "indirect")==0 ){ 9608 int ii; 9609 if( nCmd>2 ) goto session_syntax_error; 9610 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9611 if( pAuxDb->nSession ){ 9612 ii = sqlite3session_indirect(pSession->p, ii); 9613 utf8_printf(p->out, "session %s indirect flag = %d\n", 9614 pSession->zName, ii); 9615 } 9616 }else 9617 9618 /* .session isempty 9619 ** Determine if the session is empty 9620 */ 9621 if( strcmp(azCmd[0], "isempty")==0 ){ 9622 int ii; 9623 if( nCmd!=1 ) goto session_syntax_error; 9624 if( pAuxDb->nSession ){ 9625 ii = sqlite3session_isempty(pSession->p); 9626 utf8_printf(p->out, "session %s isempty flag = %d\n", 9627 pSession->zName, ii); 9628 } 9629 }else 9630 9631 /* .session list 9632 ** List all currently open sessions 9633 */ 9634 if( strcmp(azCmd[0],"list")==0 ){ 9635 for(i=0; i<pAuxDb->nSession; i++){ 9636 utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); 9637 } 9638 }else 9639 9640 /* .session open DB NAME 9641 ** Open a new session called NAME on the attached database DB. 9642 ** DB is normally "main". 9643 */ 9644 if( strcmp(azCmd[0],"open")==0 ){ 9645 char *zName; 9646 if( nCmd!=3 ) goto session_syntax_error; 9647 zName = azCmd[2]; 9648 if( zName[0]==0 ) goto session_syntax_error; 9649 for(i=0; i<pAuxDb->nSession; i++){ 9650 if( strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ 9651 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 9652 goto meta_command_exit; 9653 } 9654 } 9655 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ 9656 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); 9657 goto meta_command_exit; 9658 } 9659 pSession = &pAuxDb->aSession[pAuxDb->nSession]; 9660 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 9661 if( rc ){ 9662 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 9663 rc = 0; 9664 goto meta_command_exit; 9665 } 9666 pSession->nFilter = 0; 9667 sqlite3session_table_filter(pSession->p, session_filter, pSession); 9668 pAuxDb->nSession++; 9669 pSession->zName = sqlite3_mprintf("%s", zName); 9670 }else 9671 /* If no command name matches, show a syntax error */ 9672 session_syntax_error: 9673 showHelp(p->out, "session"); 9674 }else 9675#endif 9676 9677#ifdef SQLITE_DEBUG 9678 /* Undocumented commands for internal testing. Subject to change 9679 ** without notice. */ 9680 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 9681 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 9682 int i, v; 9683 for(i=1; i<nArg; i++){ 9684 v = booleanValue(azArg[i]); 9685 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 9686 } 9687 } 9688 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 9689 int i; sqlite3_int64 v; 9690 for(i=1; i<nArg; i++){ 9691 char zBuf[200]; 9692 v = integerValue(azArg[i]); 9693 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 9694 utf8_printf(p->out, "%s", zBuf); 9695 } 9696 } 9697 }else 9698#endif 9699 9700 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 9701 int bIsInit = 0; /* True to initialize the SELFTEST table */ 9702 int bVerbose = 0; /* Verbose output */ 9703 int bSelftestExists; /* True if SELFTEST already exists */ 9704 int i, k; /* Loop counters */ 9705 int nTest = 0; /* Number of tests runs */ 9706 int nErr = 0; /* Number of errors seen */ 9707 ShellText str; /* Answer for a query */ 9708 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 9709 9710 open_db(p,0); 9711 for(i=1; i<nArg; i++){ 9712 const char *z = azArg[i]; 9713 if( z[0]=='-' && z[1]=='-' ) z++; 9714 if( strcmp(z,"-init")==0 ){ 9715 bIsInit = 1; 9716 }else 9717 if( strcmp(z,"-v")==0 ){ 9718 bVerbose++; 9719 }else 9720 { 9721 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9722 azArg[i], azArg[0]); 9723 raw_printf(stderr, "Should be one of: --init -v\n"); 9724 rc = 1; 9725 goto meta_command_exit; 9726 } 9727 } 9728 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 9729 != SQLITE_OK ){ 9730 bSelftestExists = 0; 9731 }else{ 9732 bSelftestExists = 1; 9733 } 9734 if( bIsInit ){ 9735 createSelftestTable(p); 9736 bSelftestExists = 1; 9737 } 9738 initText(&str); 9739 appendText(&str, "x", 0); 9740 for(k=bSelftestExists; k>=0; k--){ 9741 if( k==1 ){ 9742 rc = sqlite3_prepare_v2(p->db, 9743 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 9744 -1, &pStmt, 0); 9745 }else{ 9746 rc = sqlite3_prepare_v2(p->db, 9747 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 9748 " (1,'run','PRAGMA integrity_check','ok')", 9749 -1, &pStmt, 0); 9750 } 9751 if( rc ){ 9752 raw_printf(stderr, "Error querying the selftest table\n"); 9753 rc = 1; 9754 sqlite3_finalize(pStmt); 9755 goto meta_command_exit; 9756 } 9757 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 9758 int tno = sqlite3_column_int(pStmt, 0); 9759 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 9760 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 9761 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 9762 9763 k = 0; 9764 if( bVerbose>0 ){ 9765 char *zQuote = sqlite3_mprintf("%q", zSql); 9766 printf("%d: %s %s\n", tno, zOp, zSql); 9767 sqlite3_free(zQuote); 9768 } 9769 if( strcmp(zOp,"memo")==0 ){ 9770 utf8_printf(p->out, "%s\n", zSql); 9771 }else 9772 if( strcmp(zOp,"run")==0 ){ 9773 char *zErrMsg = 0; 9774 str.n = 0; 9775 str.z[0] = 0; 9776 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 9777 nTest++; 9778 if( bVerbose ){ 9779 utf8_printf(p->out, "Result: %s\n", str.z); 9780 } 9781 if( rc || zErrMsg ){ 9782 nErr++; 9783 rc = 1; 9784 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 9785 sqlite3_free(zErrMsg); 9786 }else if( strcmp(zAns,str.z)!=0 ){ 9787 nErr++; 9788 rc = 1; 9789 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 9790 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 9791 } 9792 }else 9793 { 9794 utf8_printf(stderr, 9795 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 9796 rc = 1; 9797 break; 9798 } 9799 } /* End loop over rows of content from SELFTEST */ 9800 sqlite3_finalize(pStmt); 9801 } /* End loop over k */ 9802 freeText(&str); 9803 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 9804 }else 9805 9806 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 9807 if( nArg<2 || nArg>3 ){ 9808 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 9809 rc = 1; 9810 } 9811 if( nArg>=2 ){ 9812 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 9813 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 9814 } 9815 if( nArg>=3 ){ 9816 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 9817 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 9818 } 9819 }else 9820 9821 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 9822 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 9823 int i; /* Loop counter */ 9824 int bSchema = 0; /* Also hash the schema */ 9825 int bSeparate = 0; /* Hash each table separately */ 9826 int iSize = 224; /* Hash algorithm to use */ 9827 int bDebug = 0; /* Only show the query that would have run */ 9828 sqlite3_stmt *pStmt; /* For querying tables names */ 9829 char *zSql; /* SQL to be run */ 9830 char *zSep; /* Separator */ 9831 ShellText sSql; /* Complete SQL for the query to run the hash */ 9832 ShellText sQuery; /* Set of queries used to read all content */ 9833 open_db(p, 0); 9834 for(i=1; i<nArg; i++){ 9835 const char *z = azArg[i]; 9836 if( z[0]=='-' ){ 9837 z++; 9838 if( z[0]=='-' ) z++; 9839 if( strcmp(z,"schema")==0 ){ 9840 bSchema = 1; 9841 }else 9842 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 9843 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 9844 ){ 9845 iSize = atoi(&z[5]); 9846 }else 9847 if( strcmp(z,"debug")==0 ){ 9848 bDebug = 1; 9849 }else 9850 { 9851 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9852 azArg[i], azArg[0]); 9853 showHelp(p->out, azArg[0]); 9854 rc = 1; 9855 goto meta_command_exit; 9856 } 9857 }else if( zLike ){ 9858 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 9859 rc = 1; 9860 goto meta_command_exit; 9861 }else{ 9862 zLike = z; 9863 bSeparate = 1; 9864 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 9865 } 9866 } 9867 if( bSchema ){ 9868 zSql = "SELECT lower(name) FROM sqlite_schema" 9869 " WHERE type='table' AND coalesce(rootpage,0)>1" 9870 " UNION ALL SELECT 'sqlite_schema'" 9871 " ORDER BY 1 collate nocase"; 9872 }else{ 9873 zSql = "SELECT lower(name) FROM sqlite_schema" 9874 " WHERE type='table' AND coalesce(rootpage,0)>1" 9875 " AND name NOT LIKE 'sqlite_%'" 9876 " ORDER BY 1 collate nocase"; 9877 } 9878 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9879 initText(&sQuery); 9880 initText(&sSql); 9881 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 9882 zSep = "VALUES("; 9883 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 9884 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 9885 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 9886 if( strncmp(zTab, "sqlite_",7)!=0 ){ 9887 appendText(&sQuery,"SELECT * FROM ", 0); 9888 appendText(&sQuery,zTab,'"'); 9889 appendText(&sQuery," NOT INDEXED;", 0); 9890 }else if( strcmp(zTab, "sqlite_schema")==0 ){ 9891 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" 9892 " ORDER BY name;", 0); 9893 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 9894 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 9895 " ORDER BY name;", 0); 9896 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 9897 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 9898 " ORDER BY tbl,idx;", 0); 9899 }else if( strcmp(zTab, "sqlite_stat4")==0 ){ 9900 appendText(&sQuery, "SELECT * FROM ", 0); 9901 appendText(&sQuery, zTab, 0); 9902 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 9903 } 9904 appendText(&sSql, zSep, 0); 9905 appendText(&sSql, sQuery.z, '\''); 9906 sQuery.n = 0; 9907 appendText(&sSql, ",", 0); 9908 appendText(&sSql, zTab, '\''); 9909 zSep = "),("; 9910 } 9911 sqlite3_finalize(pStmt); 9912 if( bSeparate ){ 9913 zSql = sqlite3_mprintf( 9914 "%s))" 9915 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 9916 " FROM [sha3sum$query]", 9917 sSql.z, iSize); 9918 }else{ 9919 zSql = sqlite3_mprintf( 9920 "%s))" 9921 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 9922 " FROM [sha3sum$query]", 9923 sSql.z, iSize); 9924 } 9925 freeText(&sQuery); 9926 freeText(&sSql); 9927 if( bDebug ){ 9928 utf8_printf(p->out, "%s\n", zSql); 9929 }else{ 9930 shell_exec(p, zSql, 0); 9931 } 9932 sqlite3_free(zSql); 9933 }else 9934 9935#ifndef SQLITE_NOHAVE_SYSTEM 9936 if( c=='s' 9937 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 9938 ){ 9939 char *zCmd; 9940 int i, x; 9941 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 9942 if( nArg<2 ){ 9943 raw_printf(stderr, "Usage: .system COMMAND\n"); 9944 rc = 1; 9945 goto meta_command_exit; 9946 } 9947 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 9948 for(i=2; i<nArg; i++){ 9949 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 9950 zCmd, azArg[i]); 9951 } 9952 x = system(zCmd); 9953 sqlite3_free(zCmd); 9954 if( x ) raw_printf(stderr, "System command returns %d\n", x); 9955 }else 9956#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 9957 9958 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 9959 static const char *azBool[] = { "off", "on", "trigger", "full"}; 9960 const char *zOut; 9961 int i; 9962 if( nArg!=1 ){ 9963 raw_printf(stderr, "Usage: .show\n"); 9964 rc = 1; 9965 goto meta_command_exit; 9966 } 9967 utf8_printf(p->out, "%12.12s: %s\n","echo", 9968 azBool[ShellHasFlag(p, SHFLG_Echo)]); 9969 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 9970 utf8_printf(p->out, "%12.12s: %s\n","explain", 9971 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 9972 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 9973 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 9974 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 9975 output_c_string(p->out, p->nullValue); 9976 raw_printf(p->out, "\n"); 9977 utf8_printf(p->out,"%12.12s: %s\n","output", 9978 strlen30(p->outfile) ? p->outfile : "stdout"); 9979 utf8_printf(p->out,"%12.12s: ", "colseparator"); 9980 output_c_string(p->out, p->colSeparator); 9981 raw_printf(p->out, "\n"); 9982 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 9983 output_c_string(p->out, p->rowSeparator); 9984 raw_printf(p->out, "\n"); 9985 switch( p->statsOn ){ 9986 case 0: zOut = "off"; break; 9987 default: zOut = "on"; break; 9988 case 2: zOut = "stmt"; break; 9989 case 3: zOut = "vmstep"; break; 9990 } 9991 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut); 9992 utf8_printf(p->out, "%12.12s: ", "width"); 9993 for (i=0;i<p->nWidth;i++) { 9994 raw_printf(p->out, "%d ", p->colWidth[i]); 9995 } 9996 raw_printf(p->out, "\n"); 9997 utf8_printf(p->out, "%12.12s: %s\n", "filename", 9998 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); 9999 }else 10000 10001 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 10002 if( nArg==2 ){ 10003 if( strcmp(azArg[1],"stmt")==0 ){ 10004 p->statsOn = 2; 10005 }else if( strcmp(azArg[1],"vmstep")==0 ){ 10006 p->statsOn = 3; 10007 }else{ 10008 p->statsOn = (u8)booleanValue(azArg[1]); 10009 } 10010 }else if( nArg==1 ){ 10011 display_stats(p->db, p, 0); 10012 }else{ 10013 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n"); 10014 rc = 1; 10015 } 10016 }else 10017 10018 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 10019 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 10020 || strncmp(azArg[0], "indexes", n)==0) ) 10021 ){ 10022 sqlite3_stmt *pStmt; 10023 char **azResult; 10024 int nRow, nAlloc; 10025 int ii; 10026 ShellText s; 10027 initText(&s); 10028 open_db(p, 0); 10029 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 10030 if( rc ){ 10031 sqlite3_finalize(pStmt); 10032 return shellDatabaseError(p->db); 10033 } 10034 10035 if( nArg>2 && c=='i' ){ 10036 /* It is an historical accident that the .indexes command shows an error 10037 ** when called with the wrong number of arguments whereas the .tables 10038 ** command does not. */ 10039 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 10040 rc = 1; 10041 sqlite3_finalize(pStmt); 10042 goto meta_command_exit; 10043 } 10044 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 10045 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 10046 if( zDbName==0 ) continue; 10047 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 10048 if( sqlite3_stricmp(zDbName, "main")==0 ){ 10049 appendText(&s, "SELECT name FROM ", 0); 10050 }else{ 10051 appendText(&s, "SELECT ", 0); 10052 appendText(&s, zDbName, '\''); 10053 appendText(&s, "||'.'||name FROM ", 0); 10054 } 10055 appendText(&s, zDbName, '"'); 10056 appendText(&s, ".sqlite_schema ", 0); 10057 if( c=='t' ){ 10058 appendText(&s," WHERE type IN ('table','view')" 10059 " AND name NOT LIKE 'sqlite_%'" 10060 " AND name LIKE ?1", 0); 10061 }else{ 10062 appendText(&s," WHERE type='index'" 10063 " AND tbl_name LIKE ?1", 0); 10064 } 10065 } 10066 rc = sqlite3_finalize(pStmt); 10067 if( rc==SQLITE_OK ){ 10068 appendText(&s, " ORDER BY 1", 0); 10069 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 10070 } 10071 freeText(&s); 10072 if( rc ) return shellDatabaseError(p->db); 10073 10074 /* Run the SQL statement prepared by the above block. Store the results 10075 ** as an array of nul-terminated strings in azResult[]. */ 10076 nRow = nAlloc = 0; 10077 azResult = 0; 10078 if( nArg>1 ){ 10079 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 10080 }else{ 10081 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 10082 } 10083 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 10084 if( nRow>=nAlloc ){ 10085 char **azNew; 10086 int n2 = nAlloc*2 + 10; 10087 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 10088 if( azNew==0 ) shell_out_of_memory(); 10089 nAlloc = n2; 10090 azResult = azNew; 10091 } 10092 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 10093 if( 0==azResult[nRow] ) shell_out_of_memory(); 10094 nRow++; 10095 } 10096 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 10097 rc = shellDatabaseError(p->db); 10098 } 10099 10100 /* Pretty-print the contents of array azResult[] to the output */ 10101 if( rc==0 && nRow>0 ){ 10102 int len, maxlen = 0; 10103 int i, j; 10104 int nPrintCol, nPrintRow; 10105 for(i=0; i<nRow; i++){ 10106 len = strlen30(azResult[i]); 10107 if( len>maxlen ) maxlen = len; 10108 } 10109 nPrintCol = 80/(maxlen+2); 10110 if( nPrintCol<1 ) nPrintCol = 1; 10111 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 10112 for(i=0; i<nPrintRow; i++){ 10113 for(j=i; j<nRow; j+=nPrintRow){ 10114 char *zSp = j<nPrintRow ? "" : " "; 10115 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 10116 azResult[j] ? azResult[j]:""); 10117 } 10118 raw_printf(p->out, "\n"); 10119 } 10120 } 10121 10122 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 10123 sqlite3_free(azResult); 10124 }else 10125 10126 /* Begin redirecting output to the file "testcase-out.txt" */ 10127 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 10128 output_reset(p); 10129 p->out = output_file_open("testcase-out.txt", 0); 10130 if( p->out==0 ){ 10131 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 10132 } 10133 if( nArg>=2 ){ 10134 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 10135 }else{ 10136 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 10137 } 10138 }else 10139 10140#ifndef SQLITE_UNTESTABLE 10141 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 10142 static const struct { 10143 const char *zCtrlName; /* Name of a test-control option */ 10144 int ctrlCode; /* Integer code for that option */ 10145 const char *zUsage; /* Usage notes */ 10146 } aCtrl[] = { 10147 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, 10148 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, 10149 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ 10150 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ 10151 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, 10152 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" }, 10153 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/ 10154 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, 10155 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" }, 10156 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, 10157 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, 10158 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, 10159#ifdef YYCOVERAGE 10160 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, 10161#endif 10162 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, 10163 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, 10164 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, 10165 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" }, 10166 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, "" }, 10167 { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, "NMAX" }, 10168 { "tune", SQLITE_TESTCTRL_TUNE, "ID VALUE" }, 10169 }; 10170 int testctrl = -1; 10171 int iCtrl = -1; 10172 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 10173 int isOk = 0; 10174 int i, n2; 10175 const char *zCmd = 0; 10176 10177 open_db(p, 0); 10178 zCmd = nArg>=2 ? azArg[1] : "help"; 10179 10180 /* The argument can optionally begin with "-" or "--" */ 10181 if( zCmd[0]=='-' && zCmd[1] ){ 10182 zCmd++; 10183 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 10184 } 10185 10186 /* --help lists all test-controls */ 10187 if( strcmp(zCmd,"help")==0 ){ 10188 utf8_printf(p->out, "Available test-controls:\n"); 10189 for(i=0; i<ArraySize(aCtrl); i++){ 10190 utf8_printf(p->out, " .testctrl %s %s\n", 10191 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 10192 } 10193 rc = 1; 10194 goto meta_command_exit; 10195 } 10196 10197 /* convert testctrl text option to value. allow any unique prefix 10198 ** of the option name, or a numerical value. */ 10199 n2 = strlen30(zCmd); 10200 for(i=0; i<ArraySize(aCtrl); i++){ 10201 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 10202 if( testctrl<0 ){ 10203 testctrl = aCtrl[i].ctrlCode; 10204 iCtrl = i; 10205 }else{ 10206 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 10207 "Use \".testctrl --help\" for help\n", zCmd); 10208 rc = 1; 10209 goto meta_command_exit; 10210 } 10211 } 10212 } 10213 if( testctrl<0 ){ 10214 utf8_printf(stderr,"Error: unknown test-control: %s\n" 10215 "Use \".testctrl --help\" for help\n", zCmd); 10216 }else{ 10217 switch(testctrl){ 10218 10219 /* sqlite3_test_control(int, db, int) */ 10220 case SQLITE_TESTCTRL_OPTIMIZATIONS: 10221 if( nArg==3 ){ 10222 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0); 10223 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10224 isOk = 3; 10225 } 10226 break; 10227 10228 /* sqlite3_test_control(int) */ 10229 case SQLITE_TESTCTRL_PRNG_SAVE: 10230 case SQLITE_TESTCTRL_PRNG_RESTORE: 10231 case SQLITE_TESTCTRL_BYTEORDER: 10232 if( nArg==2 ){ 10233 rc2 = sqlite3_test_control(testctrl); 10234 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 10235 } 10236 break; 10237 10238 /* sqlite3_test_control(int, uint) */ 10239 case SQLITE_TESTCTRL_PENDING_BYTE: 10240 if( nArg==3 ){ 10241 unsigned int opt = (unsigned int)integerValue(azArg[2]); 10242 rc2 = sqlite3_test_control(testctrl, opt); 10243 isOk = 3; 10244 } 10245 break; 10246 10247 /* sqlite3_test_control(int, int, sqlite3*) */ 10248 case SQLITE_TESTCTRL_PRNG_SEED: 10249 if( nArg==3 || nArg==4 ){ 10250 int ii = (int)integerValue(azArg[2]); 10251 sqlite3 *db; 10252 if( ii==0 && strcmp(azArg[2],"random")==0 ){ 10253 sqlite3_randomness(sizeof(ii),&ii); 10254 printf("-- random seed: %d\n", ii); 10255 } 10256 if( nArg==3 ){ 10257 db = 0; 10258 }else{ 10259 db = p->db; 10260 /* Make sure the schema has been loaded */ 10261 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 10262 } 10263 rc2 = sqlite3_test_control(testctrl, ii, db); 10264 isOk = 3; 10265 } 10266 break; 10267 10268 /* sqlite3_test_control(int, int) */ 10269 case SQLITE_TESTCTRL_ASSERT: 10270 case SQLITE_TESTCTRL_ALWAYS: 10271 if( nArg==3 ){ 10272 int opt = booleanValue(azArg[2]); 10273 rc2 = sqlite3_test_control(testctrl, opt); 10274 isOk = 1; 10275 } 10276 break; 10277 10278 /* sqlite3_test_control(int, int) */ 10279 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 10280 case SQLITE_TESTCTRL_NEVER_CORRUPT: 10281 if( nArg==3 ){ 10282 int opt = booleanValue(azArg[2]); 10283 rc2 = sqlite3_test_control(testctrl, opt); 10284 isOk = 3; 10285 } 10286 break; 10287 10288 /* sqlite3_test_control(sqlite3*) */ 10289 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 10290 rc2 = sqlite3_test_control(testctrl, p->db); 10291 isOk = 3; 10292 break; 10293 10294 case SQLITE_TESTCTRL_IMPOSTER: 10295 if( nArg==5 ){ 10296 rc2 = sqlite3_test_control(testctrl, p->db, 10297 azArg[2], 10298 integerValue(azArg[3]), 10299 integerValue(azArg[4])); 10300 isOk = 3; 10301 } 10302 break; 10303 10304 case SQLITE_TESTCTRL_SEEK_COUNT: { 10305 u64 x = 0; 10306 rc2 = sqlite3_test_control(testctrl, p->db, &x); 10307 utf8_printf(p->out, "%llu\n", x); 10308 isOk = 3; 10309 break; 10310 } 10311 10312#ifdef YYCOVERAGE 10313 case SQLITE_TESTCTRL_PARSER_COVERAGE: { 10314 if( nArg==2 ){ 10315 sqlite3_test_control(testctrl, p->out); 10316 isOk = 3; 10317 } 10318 break; 10319 } 10320#endif 10321#ifdef SQLITE_DEBUG 10322 case SQLITE_TESTCTRL_TUNE: { 10323 if( nArg==4 ){ 10324 int id = (int)integerValue(azArg[2]); 10325 int val = (int)integerValue(azArg[3]); 10326 sqlite3_test_control(testctrl, id, &val); 10327 isOk = 3; 10328 }else if( nArg==3 ){ 10329 int id = (int)integerValue(azArg[2]); 10330 sqlite3_test_control(testctrl, -id, &rc2); 10331 isOk = 1; 10332 }else if( nArg==2 ){ 10333 int id = 1; 10334 while(1){ 10335 int val = 0; 10336 rc2 = sqlite3_test_control(testctrl, -id, &val); 10337 if( rc2!=SQLITE_OK ) break; 10338 if( id>1 ) utf8_printf(p->out, " "); 10339 utf8_printf(p->out, "%d: %d", id, val); 10340 id++; 10341 } 10342 if( id>1 ) utf8_printf(p->out, "\n"); 10343 isOk = 3; 10344 } 10345 break; 10346 } 10347#endif 10348 case SQLITE_TESTCTRL_SORTER_MMAP: 10349 if( nArg==3 ){ 10350 int opt = (unsigned int)integerValue(azArg[2]); 10351 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10352 isOk = 3; 10353 } 10354 break; 10355 } 10356 } 10357 if( isOk==0 && iCtrl>=0 ){ 10358 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 10359 rc = 1; 10360 }else if( isOk==1 ){ 10361 raw_printf(p->out, "%d\n", rc2); 10362 }else if( isOk==2 ){ 10363 raw_printf(p->out, "0x%08x\n", rc2); 10364 } 10365 }else 10366#endif /* !defined(SQLITE_UNTESTABLE) */ 10367 10368 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 10369 open_db(p, 0); 10370 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 10371 }else 10372 10373 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 10374 if( nArg==2 ){ 10375 enableTimer = booleanValue(azArg[1]); 10376 if( enableTimer && !HAS_TIMER ){ 10377 raw_printf(stderr, "Error: timer not available on this system.\n"); 10378 enableTimer = 0; 10379 } 10380 }else{ 10381 raw_printf(stderr, "Usage: .timer on|off\n"); 10382 rc = 1; 10383 } 10384 }else 10385 10386#ifndef SQLITE_OMIT_TRACE 10387 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 10388 int mType = 0; 10389 int jj; 10390 open_db(p, 0); 10391 for(jj=1; jj<nArg; jj++){ 10392 const char *z = azArg[jj]; 10393 if( z[0]=='-' ){ 10394 if( optionMatch(z, "expanded") ){ 10395 p->eTraceType = SHELL_TRACE_EXPANDED; 10396 } 10397#ifdef SQLITE_ENABLE_NORMALIZE 10398 else if( optionMatch(z, "normalized") ){ 10399 p->eTraceType = SHELL_TRACE_NORMALIZED; 10400 } 10401#endif 10402 else if( optionMatch(z, "plain") ){ 10403 p->eTraceType = SHELL_TRACE_PLAIN; 10404 } 10405 else if( optionMatch(z, "profile") ){ 10406 mType |= SQLITE_TRACE_PROFILE; 10407 } 10408 else if( optionMatch(z, "row") ){ 10409 mType |= SQLITE_TRACE_ROW; 10410 } 10411 else if( optionMatch(z, "stmt") ){ 10412 mType |= SQLITE_TRACE_STMT; 10413 } 10414 else if( optionMatch(z, "close") ){ 10415 mType |= SQLITE_TRACE_CLOSE; 10416 } 10417 else { 10418 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 10419 rc = 1; 10420 goto meta_command_exit; 10421 } 10422 }else{ 10423 output_file_close(p->traceOut); 10424 p->traceOut = output_file_open(azArg[1], 0); 10425 } 10426 } 10427 if( p->traceOut==0 ){ 10428 sqlite3_trace_v2(p->db, 0, 0, 0); 10429 }else{ 10430 if( mType==0 ) mType = SQLITE_TRACE_STMT; 10431 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 10432 } 10433 }else 10434#endif /* !defined(SQLITE_OMIT_TRACE) */ 10435 10436#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) 10437 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){ 10438 int ii; 10439 int lenOpt; 10440 char *zOpt; 10441 if( nArg<2 ){ 10442 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n"); 10443 rc = 1; 10444 goto meta_command_exit; 10445 } 10446 open_db(p, 0); 10447 zOpt = azArg[1]; 10448 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; 10449 lenOpt = (int)strlen(zOpt); 10450 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){ 10451 assert( azArg[nArg]==0 ); 10452 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); 10453 }else{ 10454 for(ii=1; ii<nArg; ii++){ 10455 sqlite3_create_module(p->db, azArg[ii], 0, 0); 10456 } 10457 } 10458 }else 10459#endif 10460 10461#if SQLITE_USER_AUTHENTICATION 10462 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 10463 if( nArg<2 ){ 10464 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 10465 rc = 1; 10466 goto meta_command_exit; 10467 } 10468 open_db(p, 0); 10469 if( strcmp(azArg[1],"login")==0 ){ 10470 if( nArg!=4 ){ 10471 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 10472 rc = 1; 10473 goto meta_command_exit; 10474 } 10475 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], 10476 strlen30(azArg[3])); 10477 if( rc ){ 10478 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 10479 rc = 1; 10480 } 10481 }else if( strcmp(azArg[1],"add")==0 ){ 10482 if( nArg!=5 ){ 10483 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 10484 rc = 1; 10485 goto meta_command_exit; 10486 } 10487 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10488 booleanValue(azArg[4])); 10489 if( rc ){ 10490 raw_printf(stderr, "User-Add failed: %d\n", rc); 10491 rc = 1; 10492 } 10493 }else if( strcmp(azArg[1],"edit")==0 ){ 10494 if( nArg!=5 ){ 10495 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 10496 rc = 1; 10497 goto meta_command_exit; 10498 } 10499 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10500 booleanValue(azArg[4])); 10501 if( rc ){ 10502 raw_printf(stderr, "User-Edit failed: %d\n", rc); 10503 rc = 1; 10504 } 10505 }else if( strcmp(azArg[1],"delete")==0 ){ 10506 if( nArg!=3 ){ 10507 raw_printf(stderr, "Usage: .user delete USER\n"); 10508 rc = 1; 10509 goto meta_command_exit; 10510 } 10511 rc = sqlite3_user_delete(p->db, azArg[2]); 10512 if( rc ){ 10513 raw_printf(stderr, "User-Delete failed: %d\n", rc); 10514 rc = 1; 10515 } 10516 }else{ 10517 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 10518 rc = 1; 10519 goto meta_command_exit; 10520 } 10521 }else 10522#endif /* SQLITE_USER_AUTHENTICATION */ 10523 10524 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 10525 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 10526 sqlite3_libversion(), sqlite3_sourceid()); 10527#if SQLITE_HAVE_ZLIB 10528 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 10529#endif 10530#define CTIMEOPT_VAL_(opt) #opt 10531#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 10532#if defined(__clang__) && defined(__clang_major__) 10533 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 10534 CTIMEOPT_VAL(__clang_minor__) "." 10535 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 10536#elif defined(_MSC_VER) 10537 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 10538#elif defined(__GNUC__) && defined(__VERSION__) 10539 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 10540#endif 10541 }else 10542 10543 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 10544 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10545 sqlite3_vfs *pVfs = 0; 10546 if( p->db ){ 10547 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 10548 if( pVfs ){ 10549 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 10550 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10551 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10552 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10553 } 10554 } 10555 }else 10556 10557 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 10558 sqlite3_vfs *pVfs; 10559 sqlite3_vfs *pCurrent = 0; 10560 if( p->db ){ 10561 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 10562 } 10563 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 10564 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 10565 pVfs==pCurrent ? " <--- CURRENT" : ""); 10566 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10567 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10568 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10569 if( pVfs->pNext ){ 10570 raw_printf(p->out, "-----------------------------------\n"); 10571 } 10572 } 10573 }else 10574 10575 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 10576 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10577 char *zVfsName = 0; 10578 if( p->db ){ 10579 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 10580 if( zVfsName ){ 10581 utf8_printf(p->out, "%s\n", zVfsName); 10582 sqlite3_free(zVfsName); 10583 } 10584 } 10585 }else 10586 10587 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 10588 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 10589 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x); 10590 }else 10591 10592 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 10593 int j; 10594 assert( nArg<=ArraySize(azArg) ); 10595 p->nWidth = nArg-1; 10596 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); 10597 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); 10598 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; 10599 for(j=1; j<nArg; j++){ 10600 p->colWidth[j-1] = (int)integerValue(azArg[j]); 10601 } 10602 }else 10603 10604 { 10605 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 10606 " \"%s\". Enter \".help\" for help\n", azArg[0]); 10607 rc = 1; 10608 } 10609 10610meta_command_exit: 10611 if( p->outCount ){ 10612 p->outCount--; 10613 if( p->outCount==0 ) output_reset(p); 10614 } 10615 p->bSafeMode = p->bSafeModePersist; 10616 return rc; 10617} 10618 10619/* Line scan result and intermediate states (supporting scan resumption) 10620*/ 10621#ifndef CHAR_BIT 10622# define CHAR_BIT 8 10623#endif 10624typedef enum { 10625 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT, 10626 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT, 10627 QSS_Start = 0 10628} QuickScanState; 10629#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask)) 10630#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start) 10631#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start) 10632#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark) 10633#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi) 10634 10635/* 10636** Scan line for classification to guide shell's handling. 10637** The scan is resumable for subsequent lines when prior 10638** return values are passed as the 2nd argument. 10639*/ 10640static QuickScanState quickscan(char *zLine, QuickScanState qss){ 10641 char cin; 10642 char cWait = (char)qss; /* intentional narrowing loss */ 10643 if( cWait==0 ){ 10644 PlainScan: 10645 assert( cWait==0 ); 10646 while( (cin = *zLine++)!=0 ){ 10647 if( IsSpace(cin) ) 10648 continue; 10649 switch (cin){ 10650 case '-': 10651 if( *zLine!='-' ) 10652 break; 10653 while((cin = *++zLine)!=0 ) 10654 if( cin=='\n') 10655 goto PlainScan; 10656 return qss; 10657 case ';': 10658 qss |= QSS_EndingSemi; 10659 continue; 10660 case '/': 10661 if( *zLine=='*' ){ 10662 ++zLine; 10663 cWait = '*'; 10664 qss = QSS_SETV(qss, cWait); 10665 goto TermScan; 10666 } 10667 break; 10668 case '[': 10669 cin = ']'; 10670 /* fall thru */ 10671 case '`': case '\'': case '"': 10672 cWait = cin; 10673 qss = QSS_HasDark | cWait; 10674 goto TermScan; 10675 default: 10676 break; 10677 } 10678 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark; 10679 } 10680 }else{ 10681 TermScan: 10682 while( (cin = *zLine++)!=0 ){ 10683 if( cin==cWait ){ 10684 switch( cWait ){ 10685 case '*': 10686 if( *zLine != '/' ) 10687 continue; 10688 ++zLine; 10689 cWait = 0; 10690 qss = QSS_SETV(qss, 0); 10691 goto PlainScan; 10692 case '`': case '\'': case '"': 10693 if(*zLine==cWait){ 10694 ++zLine; 10695 continue; 10696 } 10697 /* fall thru */ 10698 case ']': 10699 cWait = 0; 10700 qss = QSS_SETV(qss, 0); 10701 goto PlainScan; 10702 default: assert(0); 10703 } 10704 } 10705 } 10706 } 10707 return qss; 10708} 10709 10710/* 10711** Return TRUE if the line typed in is an SQL command terminator other 10712** than a semi-colon. The SQL Server style "go" command is understood 10713** as is the Oracle "/". 10714*/ 10715static int line_is_command_terminator(char *zLine){ 10716 while( IsSpace(zLine[0]) ){ zLine++; }; 10717 if( zLine[0]=='/' ) 10718 zLine += 1; /* Oracle */ 10719 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' ) 10720 zLine += 2; /* SQL Server */ 10721 else 10722 return 0; 10723 return quickscan(zLine,QSS_Start)==QSS_Start; 10724} 10725 10726/* 10727** We need a default sqlite3_complete() implementation to use in case 10728** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 10729** any arbitrary text is a complete SQL statement. This is not very 10730** user-friendly, but it does seem to work. 10731*/ 10732#ifdef SQLITE_OMIT_COMPLETE 10733#define sqlite3_complete(x) 1 10734#endif 10735 10736/* 10737** Return true if zSql is a complete SQL statement. Return false if it 10738** ends in the middle of a string literal or C-style comment. 10739*/ 10740static int line_is_complete(char *zSql, int nSql){ 10741 int rc; 10742 if( zSql==0 ) return 1; 10743 zSql[nSql] = ';'; 10744 zSql[nSql+1] = 0; 10745 rc = sqlite3_complete(zSql); 10746 zSql[nSql] = 0; 10747 return rc; 10748} 10749 10750/* 10751** Run a single line of SQL. Return the number of errors. 10752*/ 10753static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 10754 int rc; 10755 char *zErrMsg = 0; 10756 10757 open_db(p, 0); 10758 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 10759 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 10760 BEGIN_TIMER; 10761 rc = shell_exec(p, zSql, &zErrMsg); 10762 END_TIMER; 10763 if( rc || zErrMsg ){ 10764 char zPrefix[100]; 10765 if( in!=0 || !stdin_is_interactive ){ 10766 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 10767 "Error: near line %d:", startline); 10768 }else{ 10769 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 10770 } 10771 if( zErrMsg!=0 ){ 10772 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 10773 sqlite3_free(zErrMsg); 10774 zErrMsg = 0; 10775 }else{ 10776 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 10777 } 10778 return 1; 10779 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 10780 char zLineBuf[2000]; 10781 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf, 10782 "changes: %lld total_changes: %lld", 10783 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); 10784 raw_printf(p->out, "%s\n", zLineBuf); 10785 } 10786 return 0; 10787} 10788 10789 10790/* 10791** Read input from *in and process it. If *in==0 then input 10792** is interactive - the user is typing it it. Otherwise, input 10793** is coming from a file or device. A prompt is issued and history 10794** is saved only if input is interactive. An interrupt signal will 10795** cause this routine to exit immediately, unless input is interactive. 10796** 10797** Return the number of errors. 10798*/ 10799static int process_input(ShellState *p){ 10800 char *zLine = 0; /* A single input line */ 10801 char *zSql = 0; /* Accumulated SQL text */ 10802 int nLine; /* Length of current line */ 10803 int nSql = 0; /* Bytes of zSql[] used */ 10804 int nAlloc = 0; /* Allocated zSql[] space */ 10805 int rc; /* Error code */ 10806 int errCnt = 0; /* Number of errors seen */ 10807 int startline = 0; /* Line number for start of current input */ 10808 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */ 10809 10810 p->lineno = 0; 10811 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 10812 fflush(p->out); 10813 zLine = one_input_line(p->in, zLine, nSql>0); 10814 if( zLine==0 ){ 10815 /* End of input */ 10816 if( p->in==0 && stdin_is_interactive ) printf("\n"); 10817 break; 10818 } 10819 if( seenInterrupt ){ 10820 if( p->in!=0 ) break; 10821 seenInterrupt = 0; 10822 } 10823 p->lineno++; 10824 if( QSS_INPLAIN(qss) 10825 && line_is_command_terminator(zLine) 10826 && line_is_complete(zSql, nSql) ){ 10827 memcpy(zLine,";",2); 10828 } 10829 qss = quickscan(zLine, qss); 10830 if( QSS_PLAINWHITE(qss) && nSql==0 ){ 10831 if( ShellHasFlag(p, SHFLG_Echo) ) 10832 printf("%s\n", zLine); 10833 /* Just swallow single-line whitespace */ 10834 qss = QSS_Start; 10835 continue; 10836 } 10837 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 10838 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 10839 if( zLine[0]=='.' ){ 10840 rc = do_meta_command(zLine, p); 10841 if( rc==2 ){ /* exit requested */ 10842 break; 10843 }else if( rc ){ 10844 errCnt++; 10845 } 10846 } 10847 qss = QSS_Start; 10848 continue; 10849 } 10850 /* No single-line dispositions remain; accumulate line(s). */ 10851 nLine = strlen30(zLine); 10852 if( nSql+nLine+2>=nAlloc ){ 10853 /* Grow buffer by half-again increments when big. */ 10854 nAlloc = nSql+(nSql>>1)+nLine+100; 10855 zSql = realloc(zSql, nAlloc); 10856 if( zSql==0 ) shell_out_of_memory(); 10857 } 10858 if( nSql==0 ){ 10859 int i; 10860 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 10861 assert( nAlloc>0 && zSql!=0 ); 10862 memcpy(zSql, zLine+i, nLine+1-i); 10863 startline = p->lineno; 10864 nSql = nLine-i; 10865 }else{ 10866 zSql[nSql++] = '\n'; 10867 memcpy(zSql+nSql, zLine, nLine+1); 10868 nSql += nLine; 10869 } 10870 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){ 10871 errCnt += runOneSqlLine(p, zSql, p->in, startline); 10872 nSql = 0; 10873 if( p->outCount ){ 10874 output_reset(p); 10875 p->outCount = 0; 10876 }else{ 10877 clearTempFile(p); 10878 } 10879 p->bSafeMode = p->bSafeModePersist; 10880 qss = QSS_Start; 10881 }else if( nSql && QSS_PLAINWHITE(qss) ){ 10882 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 10883 nSql = 0; 10884 qss = QSS_Start; 10885 } 10886 } 10887 if( nSql && QSS_PLAINDARK(qss) ){ 10888 errCnt += runOneSqlLine(p, zSql, p->in, startline); 10889 } 10890 free(zSql); 10891 free(zLine); 10892 return errCnt>0; 10893} 10894 10895/* 10896** Return a pathname which is the user's home directory. A 10897** 0 return indicates an error of some kind. 10898*/ 10899static char *find_home_dir(int clearFlag){ 10900 static char *home_dir = NULL; 10901 if( clearFlag ){ 10902 free(home_dir); 10903 home_dir = 0; 10904 return 0; 10905 } 10906 if( home_dir ) return home_dir; 10907 10908#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 10909 && !defined(__RTP__) && !defined(_WRS_KERNEL) 10910 { 10911 struct passwd *pwent; 10912 uid_t uid = getuid(); 10913 if( (pwent=getpwuid(uid)) != NULL) { 10914 home_dir = pwent->pw_dir; 10915 } 10916 } 10917#endif 10918 10919#if defined(_WIN32_WCE) 10920 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 10921 */ 10922 home_dir = "/"; 10923#else 10924 10925#if defined(_WIN32) || defined(WIN32) 10926 if (!home_dir) { 10927 home_dir = getenv("USERPROFILE"); 10928 } 10929#endif 10930 10931 if (!home_dir) { 10932 home_dir = getenv("HOME"); 10933 } 10934 10935#if defined(_WIN32) || defined(WIN32) 10936 if (!home_dir) { 10937 char *zDrive, *zPath; 10938 int n; 10939 zDrive = getenv("HOMEDRIVE"); 10940 zPath = getenv("HOMEPATH"); 10941 if( zDrive && zPath ){ 10942 n = strlen30(zDrive) + strlen30(zPath) + 1; 10943 home_dir = malloc( n ); 10944 if( home_dir==0 ) return 0; 10945 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 10946 return home_dir; 10947 } 10948 home_dir = "c:\\"; 10949 } 10950#endif 10951 10952#endif /* !_WIN32_WCE */ 10953 10954 if( home_dir ){ 10955 int n = strlen30(home_dir) + 1; 10956 char *z = malloc( n ); 10957 if( z ) memcpy(z, home_dir, n); 10958 home_dir = z; 10959 } 10960 10961 return home_dir; 10962} 10963 10964/* 10965** Read input from the file given by sqliterc_override. Or if that 10966** parameter is NULL, take input from ~/.sqliterc 10967** 10968** Returns the number of errors. 10969*/ 10970static void process_sqliterc( 10971 ShellState *p, /* Configuration data */ 10972 const char *sqliterc_override /* Name of config file. NULL to use default */ 10973){ 10974 char *home_dir = NULL; 10975 const char *sqliterc = sqliterc_override; 10976 char *zBuf = 0; 10977 FILE *inSaved = p->in; 10978 int savedLineno = p->lineno; 10979 10980 if (sqliterc == NULL) { 10981 home_dir = find_home_dir(0); 10982 if( home_dir==0 ){ 10983 raw_printf(stderr, "-- warning: cannot find home directory;" 10984 " cannot read ~/.sqliterc\n"); 10985 return; 10986 } 10987 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 10988 sqliterc = zBuf; 10989 } 10990 p->in = fopen(sqliterc,"rb"); 10991 if( p->in ){ 10992 if( stdin_is_interactive ){ 10993 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 10994 } 10995 if( process_input(p) && bail_on_error ) exit(1); 10996 fclose(p->in); 10997 }else if( sqliterc_override!=0 ){ 10998 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc); 10999 if( bail_on_error ) exit(1); 11000 } 11001 p->in = inSaved; 11002 p->lineno = savedLineno; 11003 sqlite3_free(zBuf); 11004} 11005 11006/* 11007** Show available command line options 11008*/ 11009static const char zOptions[] = 11010#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 11011 " -A ARGS... run \".archive ARGS\" and exit\n" 11012#endif 11013 " -append append the database to the end of the file\n" 11014 " -ascii set output mode to 'ascii'\n" 11015 " -bail stop after hitting an error\n" 11016 " -batch force batch I/O\n" 11017 " -box set output mode to 'box'\n" 11018 " -column set output mode to 'column'\n" 11019 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 11020 " -csv set output mode to 'csv'\n" 11021#if !defined(SQLITE_OMIT_DESERIALIZE) 11022 " -deserialize open the database using sqlite3_deserialize()\n" 11023#endif 11024 " -echo print commands before execution\n" 11025 " -init FILENAME read/process named file\n" 11026 " -[no]header turn headers on or off\n" 11027#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11028 " -heap SIZE Size of heap for memsys3 or memsys5\n" 11029#endif 11030 " -help show this message\n" 11031 " -html set output mode to HTML\n" 11032 " -interactive force interactive I/O\n" 11033 " -json set output mode to 'json'\n" 11034 " -line set output mode to 'line'\n" 11035 " -list set output mode to 'list'\n" 11036 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 11037 " -markdown set output mode to 'markdown'\n" 11038#if !defined(SQLITE_OMIT_DESERIALIZE) 11039 " -maxsize N maximum size for a --deserialize database\n" 11040#endif 11041 " -memtrace trace all memory allocations and deallocations\n" 11042 " -mmap N default mmap size set to N\n" 11043#ifdef SQLITE_ENABLE_MULTIPLEX 11044 " -multiplex enable the multiplexor VFS\n" 11045#endif 11046 " -newline SEP set output row separator. Default: '\\n'\n" 11047 " -nofollow refuse to open symbolic links to database files\n" 11048 " -nonce STRING set the safe-mode escape nonce\n" 11049 " -nullvalue TEXT set text string for NULL values. Default ''\n" 11050 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 11051 " -quote set output mode to 'quote'\n" 11052 " -readonly open the database read-only\n" 11053 " -safe enable safe-mode\n" 11054 " -separator SEP set output column separator. Default: '|'\n" 11055#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11056 " -sorterref SIZE sorter references threshold size\n" 11057#endif 11058 " -stats print memory stats before each finalize\n" 11059 " -table set output mode to 'table'\n" 11060 " -tabs set output mode to 'tabs'\n" 11061 " -version show SQLite version\n" 11062 " -vfs NAME use NAME as the default VFS\n" 11063#ifdef SQLITE_ENABLE_VFSTRACE 11064 " -vfstrace enable tracing of all VFS calls\n" 11065#endif 11066#ifdef SQLITE_HAVE_ZLIB 11067 " -zip open the file as a ZIP Archive\n" 11068#endif 11069; 11070static void usage(int showDetail){ 11071 utf8_printf(stderr, 11072 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 11073 "FILENAME is the name of an SQLite database. A new database is created\n" 11074 "if the file does not previously exist.\n", Argv0); 11075 if( showDetail ){ 11076 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 11077 }else{ 11078 raw_printf(stderr, "Use the -help option for additional information\n"); 11079 } 11080 exit(1); 11081} 11082 11083/* 11084** Internal check: Verify that the SQLite is uninitialized. Print a 11085** error message if it is initialized. 11086*/ 11087static void verify_uninitialized(void){ 11088 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 11089 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 11090 " initialization.\n"); 11091 } 11092} 11093 11094/* 11095** Initialize the state information in data 11096*/ 11097static void main_init(ShellState *data) { 11098 memset(data, 0, sizeof(*data)); 11099 data->normalMode = data->cMode = data->mode = MODE_List; 11100 data->autoExplain = 1; 11101 data->pAuxDb = &data->aAuxDb[0]; 11102 memcpy(data->colSeparator,SEP_Column, 2); 11103 memcpy(data->rowSeparator,SEP_Row, 2); 11104 data->showHeader = 0; 11105 data->shellFlgs = SHFLG_Lookaside; 11106 verify_uninitialized(); 11107 sqlite3_config(SQLITE_CONFIG_URI, 1); 11108 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 11109 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 11110 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 11111 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 11112} 11113 11114/* 11115** Output text to the console in a font that attracts extra attention. 11116*/ 11117#ifdef _WIN32 11118static void printBold(const char *zText){ 11119#if !SQLITE_OS_WINRT 11120 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 11121 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 11122 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 11123 SetConsoleTextAttribute(out, 11124 FOREGROUND_RED|FOREGROUND_INTENSITY 11125 ); 11126#endif 11127 printf("%s", zText); 11128#if !SQLITE_OS_WINRT 11129 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 11130#endif 11131} 11132#else 11133static void printBold(const char *zText){ 11134 printf("\033[1m%s\033[0m", zText); 11135} 11136#endif 11137 11138/* 11139** Get the argument to an --option. Throw an error and die if no argument 11140** is available. 11141*/ 11142static char *cmdline_option_value(int argc, char **argv, int i){ 11143 if( i==argc ){ 11144 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 11145 argv[0], argv[argc-1]); 11146 exit(1); 11147 } 11148 return argv[i]; 11149} 11150 11151#ifndef SQLITE_SHELL_IS_UTF8 11152# if (defined(_WIN32) || defined(WIN32)) \ 11153 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__))) 11154# define SQLITE_SHELL_IS_UTF8 (0) 11155# else 11156# define SQLITE_SHELL_IS_UTF8 (1) 11157# endif 11158#endif 11159 11160#if SQLITE_SHELL_IS_UTF8 11161int SQLITE_CDECL main(int argc, char **argv){ 11162#else 11163int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 11164 char **argv; 11165#endif 11166 char *zErrMsg = 0; 11167 ShellState data; 11168 const char *zInitFile = 0; 11169 int i; 11170 int rc = 0; 11171 int warnInmemoryDb = 0; 11172 int readStdin = 1; 11173 int nCmd = 0; 11174 char **azCmd = 0; 11175 const char *zVfs = 0; /* Value of -vfs command-line option */ 11176#if !SQLITE_SHELL_IS_UTF8 11177 char **argvToFree = 0; 11178 int argcToFree = 0; 11179#endif 11180 11181 setBinaryMode(stdin, 0); 11182 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 11183 stdin_is_interactive = isatty(0); 11184 stdout_is_console = isatty(1); 11185 11186#ifdef SQLITE_DEBUG 11187 registerOomSimulator(); 11188#endif 11189 11190#if !defined(_WIN32_WCE) 11191 if( getenv("SQLITE_DEBUG_BREAK") ){ 11192 if( isatty(0) && isatty(2) ){ 11193 fprintf(stderr, 11194 "attach debugger to process %d and press any key to continue.\n", 11195 GETPID()); 11196 fgetc(stdin); 11197 }else{ 11198#if defined(_WIN32) || defined(WIN32) 11199#if SQLITE_OS_WINRT 11200 __debugbreak(); 11201#else 11202 DebugBreak(); 11203#endif 11204#elif defined(SIGTRAP) 11205 raise(SIGTRAP); 11206#endif 11207 } 11208 } 11209#endif 11210 11211#if USE_SYSTEM_SQLITE+0!=1 11212 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 11213 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 11214 sqlite3_sourceid(), SQLITE_SOURCE_ID); 11215 exit(1); 11216 } 11217#endif 11218 main_init(&data); 11219 11220 /* On Windows, we must translate command-line arguments into UTF-8. 11221 ** The SQLite memory allocator subsystem has to be enabled in order to 11222 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 11223 ** subsequent sqlite3_config() calls will work. So copy all results into 11224 ** memory that does not come from the SQLite memory allocator. 11225 */ 11226#if !SQLITE_SHELL_IS_UTF8 11227 sqlite3_initialize(); 11228 argvToFree = malloc(sizeof(argv[0])*argc*2); 11229 argcToFree = argc; 11230 argv = argvToFree + argc; 11231 if( argv==0 ) shell_out_of_memory(); 11232 for(i=0; i<argc; i++){ 11233 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 11234 int n; 11235 if( z==0 ) shell_out_of_memory(); 11236 n = (int)strlen(z); 11237 argv[i] = malloc( n+1 ); 11238 if( argv[i]==0 ) shell_out_of_memory(); 11239 memcpy(argv[i], z, n+1); 11240 argvToFree[i] = argv[i]; 11241 sqlite3_free(z); 11242 } 11243 sqlite3_shutdown(); 11244#endif 11245 11246 assert( argc>=1 && argv && argv[0] ); 11247 Argv0 = argv[0]; 11248 11249 /* Make sure we have a valid signal handler early, before anything 11250 ** else is done. 11251 */ 11252#ifdef SIGINT 11253 signal(SIGINT, interrupt_handler); 11254#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 11255 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 11256#endif 11257 11258#ifdef SQLITE_SHELL_DBNAME_PROC 11259 { 11260 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 11261 ** of a C-function that will provide the name of the database file. Use 11262 ** this compile-time option to embed this shell program in larger 11263 ** applications. */ 11264 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 11265 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename); 11266 warnInmemoryDb = 0; 11267 } 11268#endif 11269 11270 /* Do an initial pass through the command-line argument to locate 11271 ** the name of the database file, the name of the initialization file, 11272 ** the size of the alternative malloc heap, 11273 ** and the first command to execute. 11274 */ 11275 verify_uninitialized(); 11276 for(i=1; i<argc; i++){ 11277 char *z; 11278 z = argv[i]; 11279 if( z[0]!='-' ){ 11280 if( data.aAuxDb->zDbFilename==0 ){ 11281 data.aAuxDb->zDbFilename = z; 11282 }else{ 11283 /* Excesss arguments are interpreted as SQL (or dot-commands) and 11284 ** mean that nothing is read from stdin */ 11285 readStdin = 0; 11286 nCmd++; 11287 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 11288 if( azCmd==0 ) shell_out_of_memory(); 11289 azCmd[nCmd-1] = z; 11290 } 11291 } 11292 if( z[1]=='-' ) z++; 11293 if( strcmp(z,"-separator")==0 11294 || strcmp(z,"-nullvalue")==0 11295 || strcmp(z,"-newline")==0 11296 || strcmp(z,"-cmd")==0 11297 ){ 11298 (void)cmdline_option_value(argc, argv, ++i); 11299 }else if( strcmp(z,"-init")==0 ){ 11300 zInitFile = cmdline_option_value(argc, argv, ++i); 11301 }else if( strcmp(z,"-batch")==0 ){ 11302 /* Need to check for batch mode here to so we can avoid printing 11303 ** informational messages (like from process_sqliterc) before 11304 ** we do the actual processing of arguments later in a second pass. 11305 */ 11306 stdin_is_interactive = 0; 11307 }else if( strcmp(z,"-heap")==0 ){ 11308#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11309 const char *zSize; 11310 sqlite3_int64 szHeap; 11311 11312 zSize = cmdline_option_value(argc, argv, ++i); 11313 szHeap = integerValue(zSize); 11314 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 11315 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 11316#else 11317 (void)cmdline_option_value(argc, argv, ++i); 11318#endif 11319 }else if( strcmp(z,"-pagecache")==0 ){ 11320 sqlite3_int64 n, sz; 11321 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11322 if( sz>70000 ) sz = 70000; 11323 if( sz<0 ) sz = 0; 11324 n = integerValue(cmdline_option_value(argc,argv,++i)); 11325 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){ 11326 n = 0xffffffffffffLL/sz; 11327 } 11328 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 11329 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 11330 data.shellFlgs |= SHFLG_Pagecache; 11331 }else if( strcmp(z,"-lookaside")==0 ){ 11332 int n, sz; 11333 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11334 if( sz<0 ) sz = 0; 11335 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11336 if( n<0 ) n = 0; 11337 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 11338 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 11339 }else if( strcmp(z,"-threadsafe")==0 ){ 11340 int n; 11341 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11342 switch( n ){ 11343 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break; 11344 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break; 11345 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break; 11346 } 11347#ifdef SQLITE_ENABLE_VFSTRACE 11348 }else if( strcmp(z,"-vfstrace")==0 ){ 11349 extern int vfstrace_register( 11350 const char *zTraceName, 11351 const char *zOldVfsName, 11352 int (*xOut)(const char*,void*), 11353 void *pOutArg, 11354 int makeDefault 11355 ); 11356 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 11357#endif 11358#ifdef SQLITE_ENABLE_MULTIPLEX 11359 }else if( strcmp(z,"-multiplex")==0 ){ 11360 extern int sqlite3_multiple_initialize(const char*,int); 11361 sqlite3_multiplex_initialize(0, 1); 11362#endif 11363 }else if( strcmp(z,"-mmap")==0 ){ 11364 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11365 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 11366#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11367 }else if( strcmp(z,"-sorterref")==0 ){ 11368 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11369 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 11370#endif 11371 }else if( strcmp(z,"-vfs")==0 ){ 11372 zVfs = cmdline_option_value(argc, argv, ++i); 11373#ifdef SQLITE_HAVE_ZLIB 11374 }else if( strcmp(z,"-zip")==0 ){ 11375 data.openMode = SHELL_OPEN_ZIPFILE; 11376#endif 11377 }else if( strcmp(z,"-append")==0 ){ 11378 data.openMode = SHELL_OPEN_APPENDVFS; 11379#ifndef SQLITE_OMIT_DESERIALIZE 11380 }else if( strcmp(z,"-deserialize")==0 ){ 11381 data.openMode = SHELL_OPEN_DESERIALIZE; 11382 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 11383 data.szMax = integerValue(argv[++i]); 11384#endif 11385 }else if( strcmp(z,"-readonly")==0 ){ 11386 data.openMode = SHELL_OPEN_READONLY; 11387 }else if( strcmp(z,"-nofollow")==0 ){ 11388 data.openFlags = SQLITE_OPEN_NOFOLLOW; 11389#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11390 }else if( strncmp(z, "-A",2)==0 ){ 11391 /* All remaining command-line arguments are passed to the ".archive" 11392 ** command, so ignore them */ 11393 break; 11394#endif 11395 }else if( strcmp(z, "-memtrace")==0 ){ 11396 sqlite3MemTraceActivate(stderr); 11397 }else if( strcmp(z,"-bail")==0 ){ 11398 bail_on_error = 1; 11399 }else if( strcmp(z,"-nonce")==0 ){ 11400 free(data.zNonce); 11401 data.zNonce = strdup(argv[++i]); 11402 }else if( strcmp(z,"-safe")==0 ){ 11403 /* no-op - catch this on the second pass */ 11404 } 11405 } 11406 verify_uninitialized(); 11407 11408 11409#ifdef SQLITE_SHELL_INIT_PROC 11410 { 11411 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 11412 ** of a C-function that will perform initialization actions on SQLite that 11413 ** occur just before or after sqlite3_initialize(). Use this compile-time 11414 ** option to embed this shell program in larger applications. */ 11415 extern void SQLITE_SHELL_INIT_PROC(void); 11416 SQLITE_SHELL_INIT_PROC(); 11417 } 11418#else 11419 /* All the sqlite3_config() calls have now been made. So it is safe 11420 ** to call sqlite3_initialize() and process any command line -vfs option. */ 11421 sqlite3_initialize(); 11422#endif 11423 11424 if( zVfs ){ 11425 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 11426 if( pVfs ){ 11427 sqlite3_vfs_register(pVfs, 1); 11428 }else{ 11429 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 11430 exit(1); 11431 } 11432 } 11433 11434 if( data.pAuxDb->zDbFilename==0 ){ 11435#ifndef SQLITE_OMIT_MEMORYDB 11436 data.pAuxDb->zDbFilename = ":memory:"; 11437 warnInmemoryDb = argc==1; 11438#else 11439 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 11440 return 1; 11441#endif 11442 } 11443 data.out = stdout; 11444 sqlite3_appendvfs_init(0,0,0); 11445 11446 /* Go ahead and open the database file if it already exists. If the 11447 ** file does not exist, delay opening it. This prevents empty database 11448 ** files from being created if a user mistypes the database name argument 11449 ** to the sqlite command-line tool. 11450 */ 11451 if( access(data.pAuxDb->zDbFilename, 0)==0 ){ 11452 open_db(&data, 0); 11453 } 11454 11455 /* Process the initialization file if there is one. If no -init option 11456 ** is given on the command line, look for a file named ~/.sqliterc and 11457 ** try to process it. 11458 */ 11459 process_sqliterc(&data,zInitFile); 11460 11461 /* Make a second pass through the command-line argument and set 11462 ** options. This second pass is delayed until after the initialization 11463 ** file is processed so that the command-line arguments will override 11464 ** settings in the initialization file. 11465 */ 11466 for(i=1; i<argc; i++){ 11467 char *z = argv[i]; 11468 if( z[0]!='-' ) continue; 11469 if( z[1]=='-' ){ z++; } 11470 if( strcmp(z,"-init")==0 ){ 11471 i++; 11472 }else if( strcmp(z,"-html")==0 ){ 11473 data.mode = MODE_Html; 11474 }else if( strcmp(z,"-list")==0 ){ 11475 data.mode = MODE_List; 11476 }else if( strcmp(z,"-quote")==0 ){ 11477 data.mode = MODE_Quote; 11478 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma); 11479 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11480 }else if( strcmp(z,"-line")==0 ){ 11481 data.mode = MODE_Line; 11482 }else if( strcmp(z,"-column")==0 ){ 11483 data.mode = MODE_Column; 11484 }else if( strcmp(z,"-json")==0 ){ 11485 data.mode = MODE_Json; 11486 }else if( strcmp(z,"-markdown")==0 ){ 11487 data.mode = MODE_Markdown; 11488 }else if( strcmp(z,"-table")==0 ){ 11489 data.mode = MODE_Table; 11490 }else if( strcmp(z,"-box")==0 ){ 11491 data.mode = MODE_Box; 11492 }else if( strcmp(z,"-csv")==0 ){ 11493 data.mode = MODE_Csv; 11494 memcpy(data.colSeparator,",",2); 11495#ifdef SQLITE_HAVE_ZLIB 11496 }else if( strcmp(z,"-zip")==0 ){ 11497 data.openMode = SHELL_OPEN_ZIPFILE; 11498#endif 11499 }else if( strcmp(z,"-append")==0 ){ 11500 data.openMode = SHELL_OPEN_APPENDVFS; 11501#ifndef SQLITE_OMIT_DESERIALIZE 11502 }else if( strcmp(z,"-deserialize")==0 ){ 11503 data.openMode = SHELL_OPEN_DESERIALIZE; 11504 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 11505 data.szMax = integerValue(argv[++i]); 11506#endif 11507 }else if( strcmp(z,"-readonly")==0 ){ 11508 data.openMode = SHELL_OPEN_READONLY; 11509 }else if( strcmp(z,"-nofollow")==0 ){ 11510 data.openFlags |= SQLITE_OPEN_NOFOLLOW; 11511 }else if( strcmp(z,"-ascii")==0 ){ 11512 data.mode = MODE_Ascii; 11513 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit); 11514 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record); 11515 }else if( strcmp(z,"-tabs")==0 ){ 11516 data.mode = MODE_List; 11517 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab); 11518 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11519 }else if( strcmp(z,"-separator")==0 ){ 11520 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 11521 "%s",cmdline_option_value(argc,argv,++i)); 11522 }else if( strcmp(z,"-newline")==0 ){ 11523 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 11524 "%s",cmdline_option_value(argc,argv,++i)); 11525 }else if( strcmp(z,"-nullvalue")==0 ){ 11526 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 11527 "%s",cmdline_option_value(argc,argv,++i)); 11528 }else if( strcmp(z,"-header")==0 ){ 11529 data.showHeader = 1; 11530 ShellSetFlag(&data, SHFLG_HeaderSet); 11531 }else if( strcmp(z,"-noheader")==0 ){ 11532 data.showHeader = 0; 11533 ShellSetFlag(&data, SHFLG_HeaderSet); 11534 }else if( strcmp(z,"-echo")==0 ){ 11535 ShellSetFlag(&data, SHFLG_Echo); 11536 }else if( strcmp(z,"-eqp")==0 ){ 11537 data.autoEQP = AUTOEQP_on; 11538 }else if( strcmp(z,"-eqpfull")==0 ){ 11539 data.autoEQP = AUTOEQP_full; 11540 }else if( strcmp(z,"-stats")==0 ){ 11541 data.statsOn = 1; 11542 }else if( strcmp(z,"-scanstats")==0 ){ 11543 data.scanstatsOn = 1; 11544 }else if( strcmp(z,"-backslash")==0 ){ 11545 /* Undocumented command-line option: -backslash 11546 ** Causes C-style backslash escapes to be evaluated in SQL statements 11547 ** prior to sending the SQL into SQLite. Useful for injecting 11548 ** crazy bytes in the middle of SQL statements for testing and debugging. 11549 */ 11550 ShellSetFlag(&data, SHFLG_Backslash); 11551 }else if( strcmp(z,"-bail")==0 ){ 11552 /* No-op. The bail_on_error flag should already be set. */ 11553 }else if( strcmp(z,"-version")==0 ){ 11554 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 11555 return 0; 11556 }else if( strcmp(z,"-interactive")==0 ){ 11557 stdin_is_interactive = 1; 11558 }else if( strcmp(z,"-batch")==0 ){ 11559 stdin_is_interactive = 0; 11560 }else if( strcmp(z,"-heap")==0 ){ 11561 i++; 11562 }else if( strcmp(z,"-pagecache")==0 ){ 11563 i+=2; 11564 }else if( strcmp(z,"-lookaside")==0 ){ 11565 i+=2; 11566 }else if( strcmp(z,"-threadsafe")==0 ){ 11567 i+=2; 11568 }else if( strcmp(z,"-nonce")==0 ){ 11569 i += 2; 11570 }else if( strcmp(z,"-mmap")==0 ){ 11571 i++; 11572 }else if( strcmp(z,"-memtrace")==0 ){ 11573 i++; 11574#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11575 }else if( strcmp(z,"-sorterref")==0 ){ 11576 i++; 11577#endif 11578 }else if( strcmp(z,"-vfs")==0 ){ 11579 i++; 11580#ifdef SQLITE_ENABLE_VFSTRACE 11581 }else if( strcmp(z,"-vfstrace")==0 ){ 11582 i++; 11583#endif 11584#ifdef SQLITE_ENABLE_MULTIPLEX 11585 }else if( strcmp(z,"-multiplex")==0 ){ 11586 i++; 11587#endif 11588 }else if( strcmp(z,"-help")==0 ){ 11589 usage(1); 11590 }else if( strcmp(z,"-cmd")==0 ){ 11591 /* Run commands that follow -cmd first and separately from commands 11592 ** that simply appear on the command-line. This seems goofy. It would 11593 ** be better if all commands ran in the order that they appear. But 11594 ** we retain the goofy behavior for historical compatibility. */ 11595 if( i==argc-1 ) break; 11596 z = cmdline_option_value(argc,argv,++i); 11597 if( z[0]=='.' ){ 11598 rc = do_meta_command(z, &data); 11599 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 11600 }else{ 11601 open_db(&data, 0); 11602 rc = shell_exec(&data, z, &zErrMsg); 11603 if( zErrMsg!=0 ){ 11604 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11605 if( bail_on_error ) return rc!=0 ? rc : 1; 11606 }else if( rc!=0 ){ 11607 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 11608 if( bail_on_error ) return rc; 11609 } 11610 } 11611#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11612 }else if( strncmp(z, "-A", 2)==0 ){ 11613 if( nCmd>0 ){ 11614 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 11615 " with \"%s\"\n", z); 11616 return 1; 11617 } 11618 open_db(&data, OPEN_DB_ZIPFILE); 11619 if( z[2] ){ 11620 argv[i] = &z[2]; 11621 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 11622 }else{ 11623 arDotCommand(&data, 1, argv+i, argc-i); 11624 } 11625 readStdin = 0; 11626 break; 11627#endif 11628 }else if( strcmp(z,"-safe")==0 ){ 11629 data.bSafeMode = data.bSafeModePersist = 1; 11630 }else{ 11631 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 11632 raw_printf(stderr,"Use -help for a list of options.\n"); 11633 return 1; 11634 } 11635 data.cMode = data.mode; 11636 } 11637 11638 if( !readStdin ){ 11639 /* Run all arguments that do not begin with '-' as if they were separate 11640 ** command-line inputs, except for the argToSkip argument which contains 11641 ** the database filename. 11642 */ 11643 for(i=0; i<nCmd; i++){ 11644 if( azCmd[i][0]=='.' ){ 11645 rc = do_meta_command(azCmd[i], &data); 11646 if( rc ){ 11647 free(azCmd); 11648 return rc==2 ? 0 : rc; 11649 } 11650 }else{ 11651 open_db(&data, 0); 11652 rc = shell_exec(&data, azCmd[i], &zErrMsg); 11653 if( zErrMsg || rc ){ 11654 if( zErrMsg!=0 ){ 11655 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11656 }else{ 11657 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 11658 } 11659 sqlite3_free(zErrMsg); 11660 free(azCmd); 11661 return rc!=0 ? rc : 1; 11662 } 11663 } 11664 } 11665 }else{ 11666 /* Run commands received from standard input 11667 */ 11668 if( stdin_is_interactive ){ 11669 char *zHome; 11670 char *zHistory; 11671 int nHistory; 11672 printf( 11673 "SQLite version %s %.19s\n" /*extra-version-info*/ 11674 "Enter \".help\" for usage hints.\n", 11675 sqlite3_libversion(), sqlite3_sourceid() 11676 ); 11677 if( warnInmemoryDb ){ 11678 printf("Connected to a "); 11679 printBold("transient in-memory database"); 11680 printf(".\nUse \".open FILENAME\" to reopen on a " 11681 "persistent database.\n"); 11682 } 11683 zHistory = getenv("SQLITE_HISTORY"); 11684 if( zHistory ){ 11685 zHistory = strdup(zHistory); 11686 }else if( (zHome = find_home_dir(0))!=0 ){ 11687 nHistory = strlen30(zHome) + 20; 11688 if( (zHistory = malloc(nHistory))!=0 ){ 11689 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 11690 } 11691 } 11692 if( zHistory ){ shell_read_history(zHistory); } 11693#if HAVE_READLINE || HAVE_EDITLINE 11694 rl_attempted_completion_function = readline_completion; 11695#elif HAVE_LINENOISE 11696 linenoiseSetCompletionCallback(linenoise_completion); 11697#endif 11698 data.in = 0; 11699 rc = process_input(&data); 11700 if( zHistory ){ 11701 shell_stifle_history(2000); 11702 shell_write_history(zHistory); 11703 free(zHistory); 11704 } 11705 }else{ 11706 data.in = stdin; 11707 rc = process_input(&data); 11708 } 11709 } 11710 free(azCmd); 11711 set_table_name(&data, 0); 11712 if( data.db ){ 11713 session_close_all(&data, -1); 11714 close_db(data.db); 11715 } 11716 for(i=0; i<ArraySize(data.aAuxDb); i++){ 11717 sqlite3_free(data.aAuxDb[i].zFreeOnClose); 11718 if( data.aAuxDb[i].db ){ 11719 session_close_all(&data, i); 11720 close_db(data.aAuxDb[i].db); 11721 } 11722 } 11723 find_home_dir(1); 11724 output_reset(&data); 11725 data.doXdgOpen = 0; 11726 clearTempFile(&data); 11727#if !SQLITE_SHELL_IS_UTF8 11728 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 11729 free(argvToFree); 11730#endif 11731 free(data.colWidth); 11732 free(data.zNonce); 11733 /* Clear the global data structure so that valgrind will detect memory 11734 ** leaks */ 11735 memset(&data, 0, sizeof(data)); 11736 return rc; 11737} 11738