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