1/* 2** 2001 September 15 3** 4** The author disclaims copyright to this source code. In place of 5** a legal notice, here is a blessing: 6** 7** May you do good and not evil. 8** May you find forgiveness for yourself and forgive others. 9** May you share freely, never taking more than you give. 10** 11************************************************************************* 12** This file contains code to implement the "sqlite" command line 13** utility for accessing SQLite databases. 14*/ 15#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) 16/* This needs to come before any includes for MSVC compiler */ 17#define _CRT_SECURE_NO_WARNINGS 18#endif 19 20/* 21** Warning pragmas copied from msvc.h in the core. 22*/ 23#if defined(_MSC_VER) 24#pragma warning(disable : 4054) 25#pragma warning(disable : 4055) 26#pragma warning(disable : 4100) 27#pragma warning(disable : 4127) 28#pragma warning(disable : 4130) 29#pragma warning(disable : 4152) 30#pragma warning(disable : 4189) 31#pragma warning(disable : 4206) 32#pragma warning(disable : 4210) 33#pragma warning(disable : 4232) 34#pragma warning(disable : 4244) 35#pragma warning(disable : 4305) 36#pragma warning(disable : 4306) 37#pragma warning(disable : 4702) 38#pragma warning(disable : 4706) 39#endif /* defined(_MSC_VER) */ 40 41/* 42** No support for loadable extensions in VxWorks. 43*/ 44#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION 45# define SQLITE_OMIT_LOAD_EXTENSION 1 46#endif 47 48/* 49** Enable large-file support for fopen() and friends on unix. 50*/ 51#ifndef SQLITE_DISABLE_LFS 52# define _LARGE_FILE 1 53# ifndef _FILE_OFFSET_BITS 54# define _FILE_OFFSET_BITS 64 55# endif 56# define _LARGEFILE_SOURCE 1 57#endif 58 59#include <stdlib.h> 60#include <string.h> 61#include <stdio.h> 62#include <assert.h> 63#include "sqlite3.h" 64typedef sqlite3_int64 i64; 65typedef sqlite3_uint64 u64; 66typedef unsigned char u8; 67#if SQLITE_USER_AUTHENTICATION 68# include "sqlite3userauth.h" 69#endif 70#include <ctype.h> 71#include <stdarg.h> 72 73#if !defined(_WIN32) && !defined(WIN32) 74# include <signal.h> 75# if !defined(__RTP__) && !defined(_WRS_KERNEL) 76# include <pwd.h> 77# endif 78#endif 79#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) 80# include <unistd.h> 81# include <dirent.h> 82# define GETPID getpid 83# if defined(__MINGW32__) 84# define DIRENT dirent 85# ifndef S_ISLNK 86# define S_ISLNK(mode) (0) 87# endif 88# endif 89#else 90# define GETPID (int)GetCurrentProcessId 91#endif 92#include <sys/types.h> 93#include <sys/stat.h> 94 95#if HAVE_READLINE 96# include <readline/readline.h> 97# include <readline/history.h> 98#endif 99 100#if HAVE_EDITLINE 101# include <editline/readline.h> 102#endif 103 104#if HAVE_EDITLINE || HAVE_READLINE 105 106# define shell_add_history(X) add_history(X) 107# define shell_read_history(X) read_history(X) 108# define shell_write_history(X) write_history(X) 109# define shell_stifle_history(X) stifle_history(X) 110# define shell_readline(X) readline(X) 111 112#elif HAVE_LINENOISE 113 114# include "linenoise.h" 115# define shell_add_history(X) linenoiseHistoryAdd(X) 116# define shell_read_history(X) linenoiseHistoryLoad(X) 117# define shell_write_history(X) linenoiseHistorySave(X) 118# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) 119# define shell_readline(X) linenoise(X) 120 121#else 122 123# define shell_read_history(X) 124# define shell_write_history(X) 125# define shell_stifle_history(X) 126 127# define SHELL_USE_LOCAL_GETLINE 1 128#endif 129 130 131#if defined(_WIN32) || defined(WIN32) 132# include <io.h> 133# include <fcntl.h> 134# define isatty(h) _isatty(h) 135# ifndef access 136# define access(f,m) _access((f),(m)) 137# endif 138# ifndef unlink 139# define unlink _unlink 140# endif 141# ifndef strdup 142# define strdup _strdup 143# endif 144# undef popen 145# define popen _popen 146# undef pclose 147# define pclose _pclose 148#else 149 /* Make sure isatty() has a prototype. */ 150 extern int isatty(int); 151 152# if !defined(__RTP__) && !defined(_WRS_KERNEL) 153 /* popen and pclose are not C89 functions and so are 154 ** sometimes omitted from the <stdio.h> header */ 155 extern FILE *popen(const char*,const char*); 156 extern int pclose(FILE*); 157# else 158# define SQLITE_OMIT_POPEN 1 159# endif 160#endif 161 162#if defined(_WIN32_WCE) 163/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() 164 * thus we always assume that we have a console. That can be 165 * overridden with the -batch command line option. 166 */ 167#define isatty(x) 1 168#endif 169 170/* ctype macros that work with signed characters */ 171#define IsSpace(X) isspace((unsigned char)X) 172#define IsDigit(X) isdigit((unsigned char)X) 173#define ToLower(X) (char)tolower((unsigned char)X) 174 175#if defined(_WIN32) || defined(WIN32) 176#include <windows.h> 177 178/* string conversion routines only needed on Win32 */ 179extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); 180extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); 181extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); 182extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); 183#endif 184 185/* On Windows, we normally run with output mode of TEXT so that \n characters 186** are automatically translated into \r\n. However, this behavior needs 187** to be disabled in some cases (ex: when generating CSV output and when 188** rendering quoted strings that contain \n characters). The following 189** routines take care of that. 190*/ 191#if defined(_WIN32) || defined(WIN32) 192static void setBinaryMode(FILE *file, int isOutput){ 193 if( isOutput ) fflush(file); 194 _setmode(_fileno(file), _O_BINARY); 195} 196static void setTextMode(FILE *file, int isOutput){ 197 if( isOutput ) fflush(file); 198 _setmode(_fileno(file), _O_TEXT); 199} 200#else 201# define setBinaryMode(X,Y) 202# define setTextMode(X,Y) 203#endif 204 205 206/* True if the timer is enabled */ 207static int enableTimer = 0; 208 209/* Return the current wall-clock time */ 210static sqlite3_int64 timeOfDay(void){ 211 static sqlite3_vfs *clockVfs = 0; 212 sqlite3_int64 t; 213 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); 214 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ 215 clockVfs->xCurrentTimeInt64(clockVfs, &t); 216 }else{ 217 double r; 218 clockVfs->xCurrentTime(clockVfs, &r); 219 t = (sqlite3_int64)(r*86400000.0); 220 } 221 return t; 222} 223 224#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) 225#include <sys/time.h> 226#include <sys/resource.h> 227 228/* VxWorks does not support getrusage() as far as we can determine */ 229#if defined(_WRS_KERNEL) || defined(__RTP__) 230struct rusage { 231 struct timeval ru_utime; /* user CPU time used */ 232 struct timeval ru_stime; /* system CPU time used */ 233}; 234#define getrusage(A,B) memset(B,0,sizeof(*B)) 235#endif 236 237/* Saved resource information for the beginning of an operation */ 238static struct rusage sBegin; /* CPU time at start */ 239static sqlite3_int64 iBegin; /* Wall-clock time at start */ 240 241/* 242** Begin timing an operation 243*/ 244static void beginTimer(void){ 245 if( enableTimer ){ 246 getrusage(RUSAGE_SELF, &sBegin); 247 iBegin = timeOfDay(); 248 } 249} 250 251/* Return the difference of two time_structs in seconds */ 252static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ 253 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 254 (double)(pEnd->tv_sec - pStart->tv_sec); 255} 256 257/* 258** Print the timing results. 259*/ 260static void endTimer(void){ 261 if( enableTimer ){ 262 sqlite3_int64 iEnd = timeOfDay(); 263 struct rusage sEnd; 264 getrusage(RUSAGE_SELF, &sEnd); 265 printf("Run Time: real %.3f user %f sys %f\n", 266 (iEnd - iBegin)*0.001, 267 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), 268 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); 269 } 270} 271 272#define BEGIN_TIMER beginTimer() 273#define END_TIMER endTimer() 274#define HAS_TIMER 1 275 276#elif (defined(_WIN32) || defined(WIN32)) 277 278/* Saved resource information for the beginning of an operation */ 279static HANDLE hProcess; 280static FILETIME ftKernelBegin; 281static FILETIME ftUserBegin; 282static sqlite3_int64 ftWallBegin; 283typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, 284 LPFILETIME, LPFILETIME); 285static GETPROCTIMES getProcessTimesAddr = NULL; 286 287/* 288** Check to see if we have timer support. Return 1 if necessary 289** support found (or found previously). 290*/ 291static int hasTimer(void){ 292 if( getProcessTimesAddr ){ 293 return 1; 294 } else { 295 /* GetProcessTimes() isn't supported in WIN95 and some other Windows 296 ** versions. See if the version we are running on has it, and if it 297 ** does, save off a pointer to it and the current process handle. 298 */ 299 hProcess = GetCurrentProcess(); 300 if( hProcess ){ 301 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); 302 if( NULL != hinstLib ){ 303 getProcessTimesAddr = 304 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); 305 if( NULL != getProcessTimesAddr ){ 306 return 1; 307 } 308 FreeLibrary(hinstLib); 309 } 310 } 311 } 312 return 0; 313} 314 315/* 316** Begin timing an operation 317*/ 318static void beginTimer(void){ 319 if( enableTimer && getProcessTimesAddr ){ 320 FILETIME ftCreation, ftExit; 321 getProcessTimesAddr(hProcess,&ftCreation,&ftExit, 322 &ftKernelBegin,&ftUserBegin); 323 ftWallBegin = timeOfDay(); 324 } 325} 326 327/* Return the difference of two FILETIME structs in seconds */ 328static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ 329 sqlite_int64 i64Start = *((sqlite_int64 *) pStart); 330 sqlite_int64 i64End = *((sqlite_int64 *) pEnd); 331 return (double) ((i64End - i64Start) / 10000000.0); 332} 333 334/* 335** Print the timing results. 336*/ 337static void endTimer(void){ 338 if( enableTimer && getProcessTimesAddr){ 339 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; 340 sqlite3_int64 ftWallEnd = timeOfDay(); 341 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); 342 printf("Run Time: real %.3f user %f sys %f\n", 343 (ftWallEnd - ftWallBegin)*0.001, 344 timeDiff(&ftUserBegin, &ftUserEnd), 345 timeDiff(&ftKernelBegin, &ftKernelEnd)); 346 } 347} 348 349#define BEGIN_TIMER beginTimer() 350#define END_TIMER endTimer() 351#define HAS_TIMER hasTimer() 352 353#else 354#define BEGIN_TIMER 355#define END_TIMER 356#define HAS_TIMER 0 357#endif 358 359/* 360** Used to prevent warnings about unused parameters 361*/ 362#define UNUSED_PARAMETER(x) (void)(x) 363 364/* 365** Number of elements in an array 366*/ 367#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) 368 369/* 370** If the following flag is set, then command execution stops 371** at an error if we are not interactive. 372*/ 373static int bail_on_error = 0; 374 375/* 376** Threat stdin as an interactive input if the following variable 377** is true. Otherwise, assume stdin is connected to a file or pipe. 378*/ 379static int stdin_is_interactive = 1; 380 381/* 382** On Windows systems we have to know if standard output is a console 383** in order to translate UTF-8 into MBCS. The following variable is 384** true if translation is required. 385*/ 386static int stdout_is_console = 1; 387 388/* 389** The following is the open SQLite database. We make a pointer 390** to this database a static variable so that it can be accessed 391** by the SIGINT handler to interrupt database processing. 392*/ 393static sqlite3 *globalDb = 0; 394 395/* 396** True if an interrupt (Control-C) has been received. 397*/ 398static volatile int seenInterrupt = 0; 399 400#ifdef SQLITE_DEBUG 401/* 402** Out-of-memory simulator variables 403*/ 404static unsigned int oomCounter = 0; /* Simulate OOM when equals 1 */ 405static unsigned int oomRepeat = 0; /* Number of OOMs in a row */ 406static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */ 407#endif /* SQLITE_DEBUG */ 408 409/* 410** This is the name of our program. It is set in main(), used 411** in a number of other places, mostly for error messages. 412*/ 413static char *Argv0; 414 415/* 416** Prompt strings. Initialized in main. Settable with 417** .prompt main continue 418*/ 419static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 420static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 421 422/* 423** Render output like fprintf(). Except, if the output is going to the 424** console and if this is running on a Windows machine, translate the 425** output from UTF-8 into MBCS. 426*/ 427#if defined(_WIN32) || defined(WIN32) 428void utf8_printf(FILE *out, const char *zFormat, ...){ 429 va_list ap; 430 va_start(ap, zFormat); 431 if( stdout_is_console && (out==stdout || out==stderr) ){ 432 char *z1 = sqlite3_vmprintf(zFormat, ap); 433 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 434 sqlite3_free(z1); 435 fputs(z2, out); 436 sqlite3_free(z2); 437 }else{ 438 vfprintf(out, zFormat, ap); 439 } 440 va_end(ap); 441} 442#elif !defined(utf8_printf) 443# define utf8_printf fprintf 444#endif 445 446/* 447** Render output like fprintf(). This should not be used on anything that 448** includes string formatting (e.g. "%s"). 449*/ 450#if !defined(raw_printf) 451# define raw_printf fprintf 452#endif 453 454/* Indicate out-of-memory and exit. */ 455static void shell_out_of_memory(void){ 456 raw_printf(stderr,"Error: out of memory\n"); 457 exit(1); 458} 459 460#ifdef SQLITE_DEBUG 461/* This routine is called when a simulated OOM occurs. It is broken 462** out as a separate routine to make it easy to set a breakpoint on 463** the OOM 464*/ 465void shellOomFault(void){ 466 if( oomRepeat>0 ){ 467 oomRepeat--; 468 }else{ 469 oomCounter--; 470 } 471} 472#endif /* SQLITE_DEBUG */ 473 474#ifdef SQLITE_DEBUG 475/* This routine is a replacement malloc() that is used to simulate 476** Out-Of-Memory (OOM) errors for testing purposes. 477*/ 478static void *oomMalloc(int nByte){ 479 if( oomCounter ){ 480 if( oomCounter==1 ){ 481 shellOomFault(); 482 return 0; 483 }else{ 484 oomCounter--; 485 } 486 } 487 return defaultMalloc(nByte); 488} 489#endif /* SQLITE_DEBUG */ 490 491#ifdef SQLITE_DEBUG 492/* Register the OOM simulator. This must occur before any memory 493** allocations */ 494static void registerOomSimulator(void){ 495 sqlite3_mem_methods mem; 496 sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem); 497 defaultMalloc = mem.xMalloc; 498 mem.xMalloc = oomMalloc; 499 sqlite3_config(SQLITE_CONFIG_MALLOC, &mem); 500} 501#endif 502 503/* 504** Write I/O traces to the following stream. 505*/ 506#ifdef SQLITE_ENABLE_IOTRACE 507static FILE *iotrace = 0; 508#endif 509 510/* 511** This routine works like printf in that its first argument is a 512** format string and subsequent arguments are values to be substituted 513** in place of % fields. The result of formatting this string 514** is written to iotrace. 515*/ 516#ifdef SQLITE_ENABLE_IOTRACE 517static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 518 va_list ap; 519 char *z; 520 if( iotrace==0 ) return; 521 va_start(ap, zFormat); 522 z = sqlite3_vmprintf(zFormat, ap); 523 va_end(ap); 524 utf8_printf(iotrace, "%s", z); 525 sqlite3_free(z); 526} 527#endif 528 529/* 530** Output string zUtf to stream pOut as w characters. If w is negative, 531** then right-justify the text. W is the width in UTF-8 characters, not 532** in bytes. This is different from the %*.*s specification in printf 533** since with %*.*s the width is measured in bytes, not characters. 534*/ 535static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 536 int i; 537 int n; 538 int aw = w<0 ? -w : w; 539 char zBuf[1000]; 540 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3; 541 for(i=n=0; zUtf[i]; i++){ 542 if( (zUtf[i]&0xc0)!=0x80 ){ 543 n++; 544 if( n==aw ){ 545 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 546 break; 547 } 548 } 549 } 550 if( n>=aw ){ 551 utf8_printf(pOut, "%.*s", i, zUtf); 552 }else if( w<0 ){ 553 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 554 }else{ 555 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 556 } 557} 558 559 560/* 561** Determines if a string is a number of not. 562*/ 563static int isNumber(const char *z, int *realnum){ 564 if( *z=='-' || *z=='+' ) z++; 565 if( !IsDigit(*z) ){ 566 return 0; 567 } 568 z++; 569 if( realnum ) *realnum = 0; 570 while( IsDigit(*z) ){ z++; } 571 if( *z=='.' ){ 572 z++; 573 if( !IsDigit(*z) ) return 0; 574 while( IsDigit(*z) ){ z++; } 575 if( realnum ) *realnum = 1; 576 } 577 if( *z=='e' || *z=='E' ){ 578 z++; 579 if( *z=='+' || *z=='-' ) z++; 580 if( !IsDigit(*z) ) return 0; 581 while( IsDigit(*z) ){ z++; } 582 if( realnum ) *realnum = 1; 583 } 584 return *z==0; 585} 586 587/* 588** Compute a string length that is limited to what can be stored in 589** lower 30 bits of a 32-bit signed integer. 590*/ 591static int strlen30(const char *z){ 592 const char *z2 = z; 593 while( *z2 ){ z2++; } 594 return 0x3fffffff & (int)(z2 - z); 595} 596 597/* 598** Return the length of a string in characters. Multibyte UTF8 characters 599** count as a single character. 600*/ 601static int strlenChar(const char *z){ 602 int n = 0; 603 while( *z ){ 604 if( (0xc0&*(z++))!=0x80 ) n++; 605 } 606 return n; 607} 608 609/* 610** This routine reads a line of text from FILE in, stores 611** the text in memory obtained from malloc() and returns a pointer 612** to the text. NULL is returned at end of file, or if malloc() 613** fails. 614** 615** If zLine is not NULL then it is a malloced buffer returned from 616** a previous call to this routine that may be reused. 617*/ 618static char *local_getline(char *zLine, FILE *in){ 619 int nLine = zLine==0 ? 0 : 100; 620 int n = 0; 621 622 while( 1 ){ 623 if( n+100>nLine ){ 624 nLine = nLine*2 + 100; 625 zLine = realloc(zLine, nLine); 626 if( zLine==0 ) shell_out_of_memory(); 627 } 628 if( fgets(&zLine[n], nLine - n, in)==0 ){ 629 if( n==0 ){ 630 free(zLine); 631 return 0; 632 } 633 zLine[n] = 0; 634 break; 635 } 636 while( zLine[n] ) n++; 637 if( n>0 && zLine[n-1]=='\n' ){ 638 n--; 639 if( n>0 && zLine[n-1]=='\r' ) n--; 640 zLine[n] = 0; 641 break; 642 } 643 } 644#if defined(_WIN32) || defined(WIN32) 645 /* For interactive input on Windows systems, translate the 646 ** multi-byte characterset characters into UTF-8. */ 647 if( stdin_is_interactive && in==stdin ){ 648 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 649 if( zTrans ){ 650 int nTrans = strlen30(zTrans)+1; 651 if( nTrans>nLine ){ 652 zLine = realloc(zLine, nTrans); 653 if( zLine==0 ) shell_out_of_memory(); 654 } 655 memcpy(zLine, zTrans, nTrans); 656 sqlite3_free(zTrans); 657 } 658 } 659#endif /* defined(_WIN32) || defined(WIN32) */ 660 return zLine; 661} 662 663/* 664** Retrieve a single line of input text. 665** 666** If in==0 then read from standard input and prompt before each line. 667** If isContinuation is true, then a continuation prompt is appropriate. 668** If isContinuation is zero, then the main prompt should be used. 669** 670** If zPrior is not NULL then it is a buffer from a prior call to this 671** routine that can be reused. 672** 673** The result is stored in space obtained from malloc() and must either 674** be freed by the caller or else passed back into this routine via the 675** zPrior argument for reuse. 676*/ 677static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 678 char *zPrompt; 679 char *zResult; 680 if( in!=0 ){ 681 zResult = local_getline(zPrior, in); 682 }else{ 683 zPrompt = isContinuation ? continuePrompt : mainPrompt; 684#if SHELL_USE_LOCAL_GETLINE 685 printf("%s", zPrompt); 686 fflush(stdout); 687 zResult = local_getline(zPrior, stdin); 688#else 689 free(zPrior); 690 zResult = shell_readline(zPrompt); 691 if( zResult && *zResult ) shell_add_history(zResult); 692#endif 693 } 694 return zResult; 695} 696 697 698/* 699** Return the value of a hexadecimal digit. Return -1 if the input 700** is not a hex digit. 701*/ 702static int hexDigitValue(char c){ 703 if( c>='0' && c<='9' ) return c - '0'; 704 if( c>='a' && c<='f' ) return c - 'a' + 10; 705 if( c>='A' && c<='F' ) return c - 'A' + 10; 706 return -1; 707} 708 709/* 710** Interpret zArg as an integer value, possibly with suffixes. 711*/ 712static sqlite3_int64 integerValue(const char *zArg){ 713 sqlite3_int64 v = 0; 714 static const struct { char *zSuffix; int iMult; } aMult[] = { 715 { "KiB", 1024 }, 716 { "MiB", 1024*1024 }, 717 { "GiB", 1024*1024*1024 }, 718 { "KB", 1000 }, 719 { "MB", 1000000 }, 720 { "GB", 1000000000 }, 721 { "K", 1000 }, 722 { "M", 1000000 }, 723 { "G", 1000000000 }, 724 }; 725 int i; 726 int isNeg = 0; 727 if( zArg[0]=='-' ){ 728 isNeg = 1; 729 zArg++; 730 }else if( zArg[0]=='+' ){ 731 zArg++; 732 } 733 if( zArg[0]=='0' && zArg[1]=='x' ){ 734 int x; 735 zArg += 2; 736 while( (x = hexDigitValue(zArg[0]))>=0 ){ 737 v = (v<<4) + x; 738 zArg++; 739 } 740 }else{ 741 while( IsDigit(zArg[0]) ){ 742 v = v*10 + zArg[0] - '0'; 743 zArg++; 744 } 745 } 746 for(i=0; i<ArraySize(aMult); i++){ 747 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 748 v *= aMult[i].iMult; 749 break; 750 } 751 } 752 return isNeg? -v : v; 753} 754 755/* 756** A variable length string to which one can append text. 757*/ 758typedef struct ShellText ShellText; 759struct ShellText { 760 char *z; 761 int n; 762 int nAlloc; 763}; 764 765/* 766** Initialize and destroy a ShellText object 767*/ 768static void initText(ShellText *p){ 769 memset(p, 0, sizeof(*p)); 770} 771static void freeText(ShellText *p){ 772 free(p->z); 773 initText(p); 774} 775 776/* zIn is either a pointer to a NULL-terminated string in memory obtained 777** from malloc(), or a NULL pointer. The string pointed to by zAppend is 778** added to zIn, and the result returned in memory obtained from malloc(). 779** zIn, if it was not NULL, is freed. 780** 781** If the third argument, quote, is not '\0', then it is used as a 782** quote character for zAppend. 783*/ 784static void appendText(ShellText *p, char const *zAppend, char quote){ 785 int len; 786 int i; 787 int nAppend = strlen30(zAppend); 788 789 len = nAppend+p->n+1; 790 if( quote ){ 791 len += 2; 792 for(i=0; i<nAppend; i++){ 793 if( zAppend[i]==quote ) len++; 794 } 795 } 796 797 if( p->n+len>=p->nAlloc ){ 798 p->nAlloc = p->nAlloc*2 + len + 20; 799 p->z = realloc(p->z, p->nAlloc); 800 if( p->z==0 ) shell_out_of_memory(); 801 } 802 803 if( quote ){ 804 char *zCsr = p->z+p->n; 805 *zCsr++ = quote; 806 for(i=0; i<nAppend; i++){ 807 *zCsr++ = zAppend[i]; 808 if( zAppend[i]==quote ) *zCsr++ = quote; 809 } 810 *zCsr++ = quote; 811 p->n = (int)(zCsr - p->z); 812 *zCsr = '\0'; 813 }else{ 814 memcpy(p->z+p->n, zAppend, nAppend); 815 p->n += nAppend; 816 p->z[p->n] = '\0'; 817 } 818} 819 820/* 821** Attempt to determine if identifier zName needs to be quoted, either 822** because it contains non-alphanumeric characters, or because it is an 823** SQLite keyword. Be conservative in this estimate: When in doubt assume 824** that quoting is required. 825** 826** Return '"' if quoting is required. Return 0 if no quoting is required. 827*/ 828static char quoteChar(const char *zName){ 829 int i; 830 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 831 for(i=0; zName[i]; i++){ 832 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 833 } 834 return sqlite3_keyword_check(zName, i) ? '"' : 0; 835} 836 837/* 838** Construct a fake object name and column list to describe the structure 839** of the view, virtual table, or table valued function zSchema.zName. 840*/ 841static char *shellFakeSchema( 842 sqlite3 *db, /* The database connection containing the vtab */ 843 const char *zSchema, /* Schema of the database holding the vtab */ 844 const char *zName /* The name of the virtual table */ 845){ 846 sqlite3_stmt *pStmt = 0; 847 char *zSql; 848 ShellText s; 849 char cQuote; 850 char *zDiv = "("; 851 int nRow = 0; 852 853 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 854 zSchema ? zSchema : "main", zName); 855 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 856 sqlite3_free(zSql); 857 initText(&s); 858 if( zSchema ){ 859 cQuote = quoteChar(zSchema); 860 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 861 appendText(&s, zSchema, cQuote); 862 appendText(&s, ".", 0); 863 } 864 cQuote = quoteChar(zName); 865 appendText(&s, zName, cQuote); 866 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 867 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 868 nRow++; 869 appendText(&s, zDiv, 0); 870 zDiv = ","; 871 cQuote = quoteChar(zCol); 872 appendText(&s, zCol, cQuote); 873 } 874 appendText(&s, ")", 0); 875 sqlite3_finalize(pStmt); 876 if( nRow==0 ){ 877 freeText(&s); 878 s.z = 0; 879 } 880 return s.z; 881} 882 883/* 884** SQL function: shell_module_schema(X) 885** 886** Return a fake schema for the table-valued function or eponymous virtual 887** table X. 888*/ 889static void shellModuleSchema( 890 sqlite3_context *pCtx, 891 int nVal, 892 sqlite3_value **apVal 893){ 894 const char *zName = (const char*)sqlite3_value_text(apVal[0]); 895 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); 896 UNUSED_PARAMETER(nVal); 897 if( zFake ){ 898 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 899 -1, sqlite3_free); 900 free(zFake); 901 } 902} 903 904/* 905** SQL function: shell_add_schema(S,X) 906** 907** Add the schema name X to the CREATE statement in S and return the result. 908** Examples: 909** 910** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 911** 912** Also works on 913** 914** CREATE INDEX 915** CREATE UNIQUE INDEX 916** CREATE VIEW 917** CREATE TRIGGER 918** CREATE VIRTUAL TABLE 919** 920** This UDF is used by the .schema command to insert the schema name of 921** attached databases into the middle of the sqlite_master.sql field. 922*/ 923static void shellAddSchemaName( 924 sqlite3_context *pCtx, 925 int nVal, 926 sqlite3_value **apVal 927){ 928 static const char *aPrefix[] = { 929 "TABLE", 930 "INDEX", 931 "UNIQUE INDEX", 932 "VIEW", 933 "TRIGGER", 934 "VIRTUAL TABLE" 935 }; 936 int i = 0; 937 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 938 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 939 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 940 sqlite3 *db = sqlite3_context_db_handle(pCtx); 941 UNUSED_PARAMETER(nVal); 942 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ 943 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){ 944 int n = strlen30(aPrefix[i]); 945 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 946 char *z = 0; 947 char *zFake = 0; 948 if( zSchema ){ 949 char cQuote = quoteChar(zSchema); 950 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 951 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 952 }else{ 953 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 954 } 955 } 956 if( zName 957 && aPrefix[i][0]=='V' 958 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 959 ){ 960 if( z==0 ){ 961 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 962 }else{ 963 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 964 } 965 free(zFake); 966 } 967 if( z ){ 968 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 969 return; 970 } 971 } 972 } 973 } 974 sqlite3_result_value(pCtx, apVal[0]); 975} 976 977/* 978** The source code for several run-time loadable extensions is inserted 979** below by the ../tool/mkshellc.tcl script. Before processing that included 980** code, we need to override some macros to make the included program code 981** work here in the middle of this regular program. 982*/ 983#define SQLITE_EXTENSION_INIT1 984#define SQLITE_EXTENSION_INIT2(X) (void)(X) 985 986#if defined(_WIN32) && defined(_MSC_VER) 987INCLUDE test_windirent.h 988INCLUDE test_windirent.c 989#define dirent DIRENT 990#endif 991INCLUDE ../ext/misc/shathree.c 992INCLUDE ../ext/misc/fileio.c 993INCLUDE ../ext/misc/completion.c 994INCLUDE ../ext/misc/appendvfs.c 995INCLUDE ../ext/misc/memtrace.c 996#ifdef SQLITE_HAVE_ZLIB 997INCLUDE ../ext/misc/zipfile.c 998INCLUDE ../ext/misc/sqlar.c 999#endif 1000INCLUDE ../ext/expert/sqlite3expert.h 1001INCLUDE ../ext/expert/sqlite3expert.c 1002 1003#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 1004INCLUDE ../ext/misc/dbdata.c 1005#endif 1006 1007#if defined(SQLITE_ENABLE_SESSION) 1008/* 1009** State information for a single open session 1010*/ 1011typedef struct OpenSession OpenSession; 1012struct OpenSession { 1013 char *zName; /* Symbolic name for this session */ 1014 int nFilter; /* Number of xFilter rejection GLOB patterns */ 1015 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 1016 sqlite3_session *p; /* The open session */ 1017}; 1018#endif 1019 1020/* 1021** Shell output mode information from before ".explain on", 1022** saved so that it can be restored by ".explain off" 1023*/ 1024typedef struct SavedModeInfo SavedModeInfo; 1025struct SavedModeInfo { 1026 int valid; /* Is there legit data in here? */ 1027 int mode; /* Mode prior to ".explain on" */ 1028 int showHeader; /* The ".header" setting prior to ".explain on" */ 1029 int colWidth[100]; /* Column widths prior to ".explain on" */ 1030}; 1031 1032typedef struct ExpertInfo ExpertInfo; 1033struct ExpertInfo { 1034 sqlite3expert *pExpert; 1035 int bVerbose; 1036}; 1037 1038/* A single line in the EQP output */ 1039typedef struct EQPGraphRow EQPGraphRow; 1040struct EQPGraphRow { 1041 int iEqpId; /* ID for this row */ 1042 int iParentId; /* ID of the parent row */ 1043 EQPGraphRow *pNext; /* Next row in sequence */ 1044 char zText[1]; /* Text to display for this row */ 1045}; 1046 1047/* All EQP output is collected into an instance of the following */ 1048typedef struct EQPGraph EQPGraph; 1049struct EQPGraph { 1050 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 1051 EQPGraphRow *pLast; /* Last element of the pRow list */ 1052 char zPrefix[100]; /* Graph prefix */ 1053}; 1054 1055/* 1056** State information about the database connection is contained in an 1057** instance of the following structure. 1058*/ 1059typedef struct ShellState ShellState; 1060struct ShellState { 1061 sqlite3 *db; /* The database */ 1062 u8 autoExplain; /* Automatically turn on .explain mode */ 1063 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1064 u8 autoEQPtest; /* autoEQP is in test mode */ 1065 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1066 u8 statsOn; /* True to display memory stats before each finalize */ 1067 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1068 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1069 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1070 u8 nEqpLevel; /* Depth of the EQP output graph */ 1071 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1072 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1073 int outCount; /* Revert to stdout when reaching zero */ 1074 int cnt; /* Number of records displayed so far */ 1075 int lineno; /* Line number of last line read from in */ 1076 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ 1077 FILE *in; /* Read commands from this stream */ 1078 FILE *out; /* Write results here */ 1079 FILE *traceOut; /* Output for sqlite3_trace() */ 1080 int nErr; /* Number of errors seen */ 1081 int mode; /* An output mode setting */ 1082 int modePrior; /* Saved mode */ 1083 int cMode; /* temporary output mode for the current query */ 1084 int normalMode; /* Output mode before ".explain on" */ 1085 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1086 int showHeader; /* True to show column names in List or Column mode */ 1087 int nCheck; /* Number of ".check" commands run */ 1088 unsigned nProgress; /* Number of progress callbacks encountered */ 1089 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1090 unsigned flgProgress; /* Flags for the progress callback */ 1091 unsigned shellFlgs; /* Various flags */ 1092 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1093 char *zDestTable; /* Name of destination table when MODE_Insert */ 1094 char *zTempFile; /* Temporary file that might need deleting */ 1095 char zTestcase[30]; /* Name of current test case */ 1096 char colSeparator[20]; /* Column separator character for several modes */ 1097 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1098 char colSepPrior[20]; /* Saved column separator */ 1099 char rowSepPrior[20]; /* Saved row separator */ 1100 int colWidth[100]; /* Requested width of each column when in column mode*/ 1101 int actualWidth[100]; /* Actual width of each column */ 1102 char nullValue[20]; /* The text to print when a NULL comes back from 1103 ** the database */ 1104 char outfile[FILENAME_MAX]; /* Filename for *out */ 1105 const char *zDbFilename; /* name of the database file */ 1106 char *zFreeOnClose; /* Filename to free when closing */ 1107 const char *zVfs; /* Name of VFS to use */ 1108 sqlite3_stmt *pStmt; /* Current statement if any. */ 1109 FILE *pLog; /* Write log output here */ 1110 int *aiIndent; /* Array of indents used in MODE_Explain */ 1111 int nIndent; /* Size of array aiIndent[] */ 1112 int iIndent; /* Index of current op in aiIndent[] */ 1113 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1114#if defined(SQLITE_ENABLE_SESSION) 1115 int nSession; /* Number of active sessions */ 1116 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1117#endif 1118 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1119}; 1120 1121 1122/* Allowed values for ShellState.autoEQP 1123*/ 1124#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1125#define AUTOEQP_on 1 /* Automatic EQP is on */ 1126#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1127#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1128 1129/* Allowed values for ShellState.openMode 1130*/ 1131#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1132#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1133#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1134#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1135#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1136#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1137#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1138 1139/* Allowed values for ShellState.eTraceType 1140*/ 1141#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1142#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1143#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1144 1145/* Bits in the ShellState.flgProgress variable */ 1146#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1147#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1148 ** callback limit is reached, and for each 1149 ** top-level SQL statement */ 1150#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1151 1152/* 1153** These are the allowed shellFlgs values 1154*/ 1155#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1156#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1157#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1158#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1159#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1160#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1161#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1162 1163/* 1164** Macros for testing and setting shellFlgs 1165*/ 1166#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1167#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1168#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1169 1170/* 1171** These are the allowed modes. 1172*/ 1173#define MODE_Line 0 /* One column per line. Blank line between records */ 1174#define MODE_Column 1 /* One record per line in neat columns */ 1175#define MODE_List 2 /* One record per line with a separator */ 1176#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1177#define MODE_Html 4 /* Generate an XHTML table */ 1178#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1179#define MODE_Quote 6 /* Quote values as for SQL */ 1180#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1181#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1182#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1183#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1184#define MODE_Pretty 11 /* Pretty-print schemas */ 1185#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1186 1187static const char *modeDescr[] = { 1188 "line", 1189 "column", 1190 "list", 1191 "semi", 1192 "html", 1193 "insert", 1194 "quote", 1195 "tcl", 1196 "csv", 1197 "explain", 1198 "ascii", 1199 "prettyprint", 1200 "eqp" 1201}; 1202 1203/* 1204** These are the column/row/line separators used by the various 1205** import/export modes. 1206*/ 1207#define SEP_Column "|" 1208#define SEP_Row "\n" 1209#define SEP_Tab "\t" 1210#define SEP_Space " " 1211#define SEP_Comma "," 1212#define SEP_CrLf "\r\n" 1213#define SEP_Unit "\x1F" 1214#define SEP_Record "\x1E" 1215 1216/* 1217** A callback for the sqlite3_log() interface. 1218*/ 1219static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1220 ShellState *p = (ShellState*)pArg; 1221 if( p->pLog==0 ) return; 1222 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1223 fflush(p->pLog); 1224} 1225 1226/* 1227** SQL function: shell_putsnl(X) 1228** 1229** Write the text X to the screen (or whatever output is being directed) 1230** adding a newline at the end, and then return X. 1231*/ 1232static void shellPutsFunc( 1233 sqlite3_context *pCtx, 1234 int nVal, 1235 sqlite3_value **apVal 1236){ 1237 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1238 (void)nVal; 1239 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1240 sqlite3_result_value(pCtx, apVal[0]); 1241} 1242 1243/* 1244** SQL function: edit(VALUE) 1245** edit(VALUE,EDITOR) 1246** 1247** These steps: 1248** 1249** (1) Write VALUE into a temporary file. 1250** (2) Run program EDITOR on that temporary file. 1251** (3) Read the temporary file back and return its content as the result. 1252** (4) Delete the temporary file 1253** 1254** If the EDITOR argument is omitted, use the value in the VISUAL 1255** environment variable. If still there is no EDITOR, through an error. 1256** 1257** Also throw an error if the EDITOR program returns a non-zero exit code. 1258*/ 1259#ifndef SQLITE_NOHAVE_SYSTEM 1260static void editFunc( 1261 sqlite3_context *context, 1262 int argc, 1263 sqlite3_value **argv 1264){ 1265 const char *zEditor; 1266 char *zTempFile = 0; 1267 sqlite3 *db; 1268 char *zCmd = 0; 1269 int bBin; 1270 int rc; 1271 int hasCRNL = 0; 1272 FILE *f = 0; 1273 sqlite3_int64 sz; 1274 sqlite3_int64 x; 1275 unsigned char *p = 0; 1276 1277 if( argc==2 ){ 1278 zEditor = (const char*)sqlite3_value_text(argv[1]); 1279 }else{ 1280 zEditor = getenv("VISUAL"); 1281 } 1282 if( zEditor==0 ){ 1283 sqlite3_result_error(context, "no editor for edit()", -1); 1284 return; 1285 } 1286 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1287 sqlite3_result_error(context, "NULL input to edit()", -1); 1288 return; 1289 } 1290 db = sqlite3_context_db_handle(context); 1291 zTempFile = 0; 1292 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1293 if( zTempFile==0 ){ 1294 sqlite3_uint64 r = 0; 1295 sqlite3_randomness(sizeof(r), &r); 1296 zTempFile = sqlite3_mprintf("temp%llx", r); 1297 if( zTempFile==0 ){ 1298 sqlite3_result_error_nomem(context); 1299 return; 1300 } 1301 } 1302 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1303 /* When writing the file to be edited, do \n to \r\n conversions on systems 1304 ** that want \r\n line endings */ 1305 f = fopen(zTempFile, bBin ? "wb" : "w"); 1306 if( f==0 ){ 1307 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1308 goto edit_func_end; 1309 } 1310 sz = sqlite3_value_bytes(argv[0]); 1311 if( bBin ){ 1312 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); 1313 }else{ 1314 const char *z = (const char*)sqlite3_value_text(argv[0]); 1315 /* Remember whether or not the value originally contained \r\n */ 1316 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1317 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); 1318 } 1319 fclose(f); 1320 f = 0; 1321 if( x!=sz ){ 1322 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1323 goto edit_func_end; 1324 } 1325 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1326 if( zCmd==0 ){ 1327 sqlite3_result_error_nomem(context); 1328 goto edit_func_end; 1329 } 1330 rc = system(zCmd); 1331 sqlite3_free(zCmd); 1332 if( rc ){ 1333 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1334 goto edit_func_end; 1335 } 1336 f = fopen(zTempFile, "rb"); 1337 if( f==0 ){ 1338 sqlite3_result_error(context, 1339 "edit() cannot reopen temp file after edit", -1); 1340 goto edit_func_end; 1341 } 1342 fseek(f, 0, SEEK_END); 1343 sz = ftell(f); 1344 rewind(f); 1345 p = sqlite3_malloc64( sz+1 ); 1346 if( p==0 ){ 1347 sqlite3_result_error_nomem(context); 1348 goto edit_func_end; 1349 } 1350 x = fread(p, 1, (size_t)sz, f); 1351 fclose(f); 1352 f = 0; 1353 if( x!=sz ){ 1354 sqlite3_result_error(context, "could not read back the whole file", -1); 1355 goto edit_func_end; 1356 } 1357 if( bBin ){ 1358 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1359 }else{ 1360 sqlite3_int64 i, j; 1361 if( hasCRNL ){ 1362 /* If the original contains \r\n then do no conversions back to \n */ 1363 j = sz; 1364 }else{ 1365 /* If the file did not originally contain \r\n then convert any new 1366 ** \r\n back into \n */ 1367 for(i=j=0; i<sz; i++){ 1368 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1369 p[j++] = p[i]; 1370 } 1371 sz = j; 1372 p[sz] = 0; 1373 } 1374 sqlite3_result_text64(context, (const char*)p, sz, 1375 sqlite3_free, SQLITE_UTF8); 1376 } 1377 p = 0; 1378 1379edit_func_end: 1380 if( f ) fclose(f); 1381 unlink(zTempFile); 1382 sqlite3_free(zTempFile); 1383 sqlite3_free(p); 1384} 1385#endif /* SQLITE_NOHAVE_SYSTEM */ 1386 1387/* 1388** Save or restore the current output mode 1389*/ 1390static void outputModePush(ShellState *p){ 1391 p->modePrior = p->mode; 1392 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1393 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1394} 1395static void outputModePop(ShellState *p){ 1396 p->mode = p->modePrior; 1397 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1398 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1399} 1400 1401/* 1402** Output the given string as a hex-encoded blob (eg. X'1234' ) 1403*/ 1404static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1405 int i; 1406 char *zBlob = (char *)pBlob; 1407 raw_printf(out,"X'"); 1408 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1409 raw_printf(out,"'"); 1410} 1411 1412/* 1413** Find a string that is not found anywhere in z[]. Return a pointer 1414** to that string. 1415** 1416** Try to use zA and zB first. If both of those are already found in z[] 1417** then make up some string and store it in the buffer zBuf. 1418*/ 1419static const char *unused_string( 1420 const char *z, /* Result must not appear anywhere in z */ 1421 const char *zA, const char *zB, /* Try these first */ 1422 char *zBuf /* Space to store a generated string */ 1423){ 1424 unsigned i = 0; 1425 if( strstr(z, zA)==0 ) return zA; 1426 if( strstr(z, zB)==0 ) return zB; 1427 do{ 1428 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1429 }while( strstr(z,zBuf)!=0 ); 1430 return zBuf; 1431} 1432 1433/* 1434** Output the given string as a quoted string using SQL quoting conventions. 1435** 1436** See also: output_quoted_escaped_string() 1437*/ 1438static void output_quoted_string(FILE *out, const char *z){ 1439 int i; 1440 char c; 1441 setBinaryMode(out, 1); 1442 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1443 if( c==0 ){ 1444 utf8_printf(out,"'%s'",z); 1445 }else{ 1446 raw_printf(out, "'"); 1447 while( *z ){ 1448 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1449 if( c=='\'' ) i++; 1450 if( i ){ 1451 utf8_printf(out, "%.*s", i, z); 1452 z += i; 1453 } 1454 if( c=='\'' ){ 1455 raw_printf(out, "'"); 1456 continue; 1457 } 1458 if( c==0 ){ 1459 break; 1460 } 1461 z++; 1462 } 1463 raw_printf(out, "'"); 1464 } 1465 setTextMode(out, 1); 1466} 1467 1468/* 1469** Output the given string as a quoted string using SQL quoting conventions. 1470** Additionallly , escape the "\n" and "\r" characters so that they do not 1471** get corrupted by end-of-line translation facilities in some operating 1472** systems. 1473** 1474** This is like output_quoted_string() but with the addition of the \r\n 1475** escape mechanism. 1476*/ 1477static void output_quoted_escaped_string(FILE *out, const char *z){ 1478 int i; 1479 char c; 1480 setBinaryMode(out, 1); 1481 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1482 if( c==0 ){ 1483 utf8_printf(out,"'%s'",z); 1484 }else{ 1485 const char *zNL = 0; 1486 const char *zCR = 0; 1487 int nNL = 0; 1488 int nCR = 0; 1489 char zBuf1[20], zBuf2[20]; 1490 for(i=0; z[i]; i++){ 1491 if( z[i]=='\n' ) nNL++; 1492 if( z[i]=='\r' ) nCR++; 1493 } 1494 if( nNL ){ 1495 raw_printf(out, "replace("); 1496 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1497 } 1498 if( nCR ){ 1499 raw_printf(out, "replace("); 1500 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1501 } 1502 raw_printf(out, "'"); 1503 while( *z ){ 1504 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1505 if( c=='\'' ) i++; 1506 if( i ){ 1507 utf8_printf(out, "%.*s", i, z); 1508 z += i; 1509 } 1510 if( c=='\'' ){ 1511 raw_printf(out, "'"); 1512 continue; 1513 } 1514 if( c==0 ){ 1515 break; 1516 } 1517 z++; 1518 if( c=='\n' ){ 1519 raw_printf(out, "%s", zNL); 1520 continue; 1521 } 1522 raw_printf(out, "%s", zCR); 1523 } 1524 raw_printf(out, "'"); 1525 if( nCR ){ 1526 raw_printf(out, ",'%s',char(13))", zCR); 1527 } 1528 if( nNL ){ 1529 raw_printf(out, ",'%s',char(10))", zNL); 1530 } 1531 } 1532 setTextMode(out, 1); 1533} 1534 1535/* 1536** Output the given string as a quoted according to C or TCL quoting rules. 1537*/ 1538static void output_c_string(FILE *out, const char *z){ 1539 unsigned int c; 1540 fputc('"', out); 1541 while( (c = *(z++))!=0 ){ 1542 if( c=='\\' ){ 1543 fputc(c, out); 1544 fputc(c, out); 1545 }else if( c=='"' ){ 1546 fputc('\\', out); 1547 fputc('"', out); 1548 }else if( c=='\t' ){ 1549 fputc('\\', out); 1550 fputc('t', out); 1551 }else if( c=='\n' ){ 1552 fputc('\\', out); 1553 fputc('n', out); 1554 }else if( c=='\r' ){ 1555 fputc('\\', out); 1556 fputc('r', out); 1557 }else if( !isprint(c&0xff) ){ 1558 raw_printf(out, "\\%03o", c&0xff); 1559 }else{ 1560 fputc(c, out); 1561 } 1562 } 1563 fputc('"', out); 1564} 1565 1566/* 1567** Output the given string with characters that are special to 1568** HTML escaped. 1569*/ 1570static void output_html_string(FILE *out, const char *z){ 1571 int i; 1572 if( z==0 ) z = ""; 1573 while( *z ){ 1574 for(i=0; z[i] 1575 && z[i]!='<' 1576 && z[i]!='&' 1577 && z[i]!='>' 1578 && z[i]!='\"' 1579 && z[i]!='\''; 1580 i++){} 1581 if( i>0 ){ 1582 utf8_printf(out,"%.*s",i,z); 1583 } 1584 if( z[i]=='<' ){ 1585 raw_printf(out,"<"); 1586 }else if( z[i]=='&' ){ 1587 raw_printf(out,"&"); 1588 }else if( z[i]=='>' ){ 1589 raw_printf(out,">"); 1590 }else if( z[i]=='\"' ){ 1591 raw_printf(out,"""); 1592 }else if( z[i]=='\'' ){ 1593 raw_printf(out,"'"); 1594 }else{ 1595 break; 1596 } 1597 z += i + 1; 1598 } 1599} 1600 1601/* 1602** If a field contains any character identified by a 1 in the following 1603** array, then the string must be quoted for CSV. 1604*/ 1605static const char needCsvQuote[] = { 1606 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1607 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1608 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1609 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1610 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1611 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1612 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1613 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1614 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1615 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1616 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1617 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1618 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1619 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1620 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1621 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1622}; 1623 1624/* 1625** Output a single term of CSV. Actually, p->colSeparator is used for 1626** the separator, which may or may not be a comma. p->nullValue is 1627** the null value. Strings are quoted if necessary. The separator 1628** is only issued if bSep is true. 1629*/ 1630static void output_csv(ShellState *p, const char *z, int bSep){ 1631 FILE *out = p->out; 1632 if( z==0 ){ 1633 utf8_printf(out,"%s",p->nullValue); 1634 }else{ 1635 int i; 1636 int nSep = strlen30(p->colSeparator); 1637 for(i=0; z[i]; i++){ 1638 if( needCsvQuote[((unsigned char*)z)[i]] 1639 || (z[i]==p->colSeparator[0] && 1640 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ 1641 i = 0; 1642 break; 1643 } 1644 } 1645 if( i==0 ){ 1646 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1647 utf8_printf(out, "%s", zQuoted); 1648 sqlite3_free(zQuoted); 1649 }else{ 1650 utf8_printf(out, "%s", z); 1651 } 1652 } 1653 if( bSep ){ 1654 utf8_printf(p->out, "%s", p->colSeparator); 1655 } 1656} 1657 1658/* 1659** This routine runs when the user presses Ctrl-C 1660*/ 1661static void interrupt_handler(int NotUsed){ 1662 UNUSED_PARAMETER(NotUsed); 1663 seenInterrupt++; 1664 if( seenInterrupt>2 ) exit(1); 1665 if( globalDb ) sqlite3_interrupt(globalDb); 1666} 1667 1668#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1669/* 1670** This routine runs for console events (e.g. Ctrl-C) on Win32 1671*/ 1672static BOOL WINAPI ConsoleCtrlHandler( 1673 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1674){ 1675 if( dwCtrlType==CTRL_C_EVENT ){ 1676 interrupt_handler(0); 1677 return TRUE; 1678 } 1679 return FALSE; 1680} 1681#endif 1682 1683#ifndef SQLITE_OMIT_AUTHORIZATION 1684/* 1685** When the ".auth ON" is set, the following authorizer callback is 1686** invoked. It always returns SQLITE_OK. 1687*/ 1688static int shellAuth( 1689 void *pClientData, 1690 int op, 1691 const char *zA1, 1692 const char *zA2, 1693 const char *zA3, 1694 const char *zA4 1695){ 1696 ShellState *p = (ShellState*)pClientData; 1697 static const char *azAction[] = { 0, 1698 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1699 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1700 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1701 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1702 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1703 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1704 "PRAGMA", "READ", "SELECT", 1705 "TRANSACTION", "UPDATE", "ATTACH", 1706 "DETACH", "ALTER_TABLE", "REINDEX", 1707 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1708 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1709 }; 1710 int i; 1711 const char *az[4]; 1712 az[0] = zA1; 1713 az[1] = zA2; 1714 az[2] = zA3; 1715 az[3] = zA4; 1716 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1717 for(i=0; i<4; i++){ 1718 raw_printf(p->out, " "); 1719 if( az[i] ){ 1720 output_c_string(p->out, az[i]); 1721 }else{ 1722 raw_printf(p->out, "NULL"); 1723 } 1724 } 1725 raw_printf(p->out, "\n"); 1726 return SQLITE_OK; 1727} 1728#endif 1729 1730/* 1731** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1732** 1733** This routine converts some CREATE TABLE statements for shadow tables 1734** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1735*/ 1736static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1737 if( z==0 ) return; 1738 if( zTail==0 ) return; 1739 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1740 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1741 }else{ 1742 utf8_printf(out, "%s%s", z, zTail); 1743 } 1744} 1745static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1746 char c = z[n]; 1747 z[n] = 0; 1748 printSchemaLine(out, z, zTail); 1749 z[n] = c; 1750} 1751 1752/* 1753** Return true if string z[] has nothing but whitespace and comments to the 1754** end of the first line. 1755*/ 1756static int wsToEol(const char *z){ 1757 int i; 1758 for(i=0; z[i]; i++){ 1759 if( z[i]=='\n' ) return 1; 1760 if( IsSpace(z[i]) ) continue; 1761 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1762 return 0; 1763 } 1764 return 1; 1765} 1766 1767/* 1768** Add a new entry to the EXPLAIN QUERY PLAN data 1769*/ 1770static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1771 EQPGraphRow *pNew; 1772 int nText = strlen30(zText); 1773 if( p->autoEQPtest ){ 1774 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1775 } 1776 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1777 if( pNew==0 ) shell_out_of_memory(); 1778 pNew->iEqpId = iEqpId; 1779 pNew->iParentId = p2; 1780 memcpy(pNew->zText, zText, nText+1); 1781 pNew->pNext = 0; 1782 if( p->sGraph.pLast ){ 1783 p->sGraph.pLast->pNext = pNew; 1784 }else{ 1785 p->sGraph.pRow = pNew; 1786 } 1787 p->sGraph.pLast = pNew; 1788} 1789 1790/* 1791** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1792** in p->sGraph. 1793*/ 1794static void eqp_reset(ShellState *p){ 1795 EQPGraphRow *pRow, *pNext; 1796 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1797 pNext = pRow->pNext; 1798 sqlite3_free(pRow); 1799 } 1800 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1801} 1802 1803/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1804** pOld, or return the first such line if pOld is NULL 1805*/ 1806static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1807 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1808 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1809 return pRow; 1810} 1811 1812/* Render a single level of the graph that has iEqpId as its parent. Called 1813** recursively to render sublevels. 1814*/ 1815static void eqp_render_level(ShellState *p, int iEqpId){ 1816 EQPGraphRow *pRow, *pNext; 1817 int n = strlen30(p->sGraph.zPrefix); 1818 char *z; 1819 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1820 pNext = eqp_next_row(p, iEqpId, pRow); 1821 z = pRow->zText; 1822 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, 1823 pNext ? "|--" : "`--", z); 1824 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1825 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 1826 eqp_render_level(p, pRow->iEqpId); 1827 p->sGraph.zPrefix[n] = 0; 1828 } 1829 } 1830} 1831 1832/* 1833** Display and reset the EXPLAIN QUERY PLAN data 1834*/ 1835static void eqp_render(ShellState *p){ 1836 EQPGraphRow *pRow = p->sGraph.pRow; 1837 if( pRow ){ 1838 if( pRow->zText[0]=='-' ){ 1839 if( pRow->pNext==0 ){ 1840 eqp_reset(p); 1841 return; 1842 } 1843 utf8_printf(p->out, "%s\n", pRow->zText+3); 1844 p->sGraph.pRow = pRow->pNext; 1845 sqlite3_free(pRow); 1846 }else{ 1847 utf8_printf(p->out, "QUERY PLAN\n"); 1848 } 1849 p->sGraph.zPrefix[0] = 0; 1850 eqp_render_level(p, 0); 1851 eqp_reset(p); 1852 } 1853} 1854 1855#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1856/* 1857** Progress handler callback. 1858*/ 1859static int progress_handler(void *pClientData) { 1860 ShellState *p = (ShellState*)pClientData; 1861 p->nProgress++; 1862 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 1863 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 1864 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 1865 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 1866 return 1; 1867 } 1868 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 1869 raw_printf(p->out, "Progress %u\n", p->nProgress); 1870 } 1871 return 0; 1872} 1873#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 1874 1875/* 1876** This is the callback routine that the shell 1877** invokes for each row of a query result. 1878*/ 1879static int shell_callback( 1880 void *pArg, 1881 int nArg, /* Number of result columns */ 1882 char **azArg, /* Text of each result column */ 1883 char **azCol, /* Column names */ 1884 int *aiType /* Column types */ 1885){ 1886 int i; 1887 ShellState *p = (ShellState*)pArg; 1888 1889 if( azArg==0 ) return 0; 1890 switch( p->cMode ){ 1891 case MODE_Line: { 1892 int w = 5; 1893 if( azArg==0 ) break; 1894 for(i=0; i<nArg; i++){ 1895 int len = strlen30(azCol[i] ? azCol[i] : ""); 1896 if( len>w ) w = len; 1897 } 1898 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 1899 for(i=0; i<nArg; i++){ 1900 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 1901 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 1902 } 1903 break; 1904 } 1905 case MODE_Explain: 1906 case MODE_Column: { 1907 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13}; 1908 const int *colWidth; 1909 int showHdr; 1910 char *rowSep; 1911 int nWidth; 1912 if( p->cMode==MODE_Column ){ 1913 colWidth = p->colWidth; 1914 nWidth = ArraySize(p->colWidth); 1915 showHdr = p->showHeader; 1916 rowSep = p->rowSeparator; 1917 }else{ 1918 colWidth = aExplainWidths; 1919 nWidth = ArraySize(aExplainWidths); 1920 showHdr = 1; 1921 rowSep = SEP_Row; 1922 } 1923 if( p->cnt++==0 ){ 1924 for(i=0; i<nArg; i++){ 1925 int w, n; 1926 if( i<nWidth ){ 1927 w = colWidth[i]; 1928 }else{ 1929 w = 0; 1930 } 1931 if( w==0 ){ 1932 w = strlenChar(azCol[i] ? azCol[i] : ""); 1933 if( w<10 ) w = 10; 1934 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue); 1935 if( w<n ) w = n; 1936 } 1937 if( i<ArraySize(p->actualWidth) ){ 1938 p->actualWidth[i] = w; 1939 } 1940 if( showHdr ){ 1941 utf8_width_print(p->out, w, azCol[i]); 1942 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1943 } 1944 } 1945 if( showHdr ){ 1946 for(i=0; i<nArg; i++){ 1947 int w; 1948 if( i<ArraySize(p->actualWidth) ){ 1949 w = p->actualWidth[i]; 1950 if( w<0 ) w = -w; 1951 }else{ 1952 w = 10; 1953 } 1954 utf8_printf(p->out,"%-*.*s%s",w,w, 1955 "----------------------------------------------------------" 1956 "----------------------------------------------------------", 1957 i==nArg-1 ? rowSep : " "); 1958 } 1959 } 1960 } 1961 if( azArg==0 ) break; 1962 for(i=0; i<nArg; i++){ 1963 int w; 1964 if( i<ArraySize(p->actualWidth) ){ 1965 w = p->actualWidth[i]; 1966 }else{ 1967 w = 10; 1968 } 1969 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){ 1970 w = strlenChar(azArg[i]); 1971 } 1972 if( i==1 && p->aiIndent && p->pStmt ){ 1973 if( p->iIndent<p->nIndent ){ 1974 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 1975 } 1976 p->iIndent++; 1977 } 1978 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 1979 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1980 } 1981 break; 1982 } 1983 case MODE_Semi: { /* .schema and .fullschema output */ 1984 printSchemaLine(p->out, azArg[0], ";\n"); 1985 break; 1986 } 1987 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 1988 char *z; 1989 int j; 1990 int nParen = 0; 1991 char cEnd = 0; 1992 char c; 1993 int nLine = 0; 1994 assert( nArg==1 ); 1995 if( azArg[0]==0 ) break; 1996 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 1997 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 1998 ){ 1999 utf8_printf(p->out, "%s;\n", azArg[0]); 2000 break; 2001 } 2002 z = sqlite3_mprintf("%s", azArg[0]); 2003 j = 0; 2004 for(i=0; IsSpace(z[i]); i++){} 2005 for(; (c = z[i])!=0; i++){ 2006 if( IsSpace(c) ){ 2007 if( z[j-1]=='\r' ) z[j-1] = '\n'; 2008 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 2009 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 2010 j--; 2011 } 2012 z[j++] = c; 2013 } 2014 while( j>0 && IsSpace(z[j-1]) ){ j--; } 2015 z[j] = 0; 2016 if( strlen30(z)>=79 ){ 2017 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ 2018 if( c==cEnd ){ 2019 cEnd = 0; 2020 }else if( c=='"' || c=='\'' || c=='`' ){ 2021 cEnd = c; 2022 }else if( c=='[' ){ 2023 cEnd = ']'; 2024 }else if( c=='-' && z[i+1]=='-' ){ 2025 cEnd = '\n'; 2026 }else if( c=='(' ){ 2027 nParen++; 2028 }else if( c==')' ){ 2029 nParen--; 2030 if( nLine>0 && nParen==0 && j>0 ){ 2031 printSchemaLineN(p->out, z, j, "\n"); 2032 j = 0; 2033 } 2034 } 2035 z[j++] = c; 2036 if( nParen==1 && cEnd==0 2037 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 2038 ){ 2039 if( c=='\n' ) j--; 2040 printSchemaLineN(p->out, z, j, "\n "); 2041 j = 0; 2042 nLine++; 2043 while( IsSpace(z[i+1]) ){ i++; } 2044 } 2045 } 2046 z[j] = 0; 2047 } 2048 printSchemaLine(p->out, z, ";\n"); 2049 sqlite3_free(z); 2050 break; 2051 } 2052 case MODE_List: { 2053 if( p->cnt++==0 && p->showHeader ){ 2054 for(i=0; i<nArg; i++){ 2055 utf8_printf(p->out,"%s%s",azCol[i], 2056 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2057 } 2058 } 2059 if( azArg==0 ) break; 2060 for(i=0; i<nArg; i++){ 2061 char *z = azArg[i]; 2062 if( z==0 ) z = p->nullValue; 2063 utf8_printf(p->out, "%s", z); 2064 if( i<nArg-1 ){ 2065 utf8_printf(p->out, "%s", p->colSeparator); 2066 }else{ 2067 utf8_printf(p->out, "%s", p->rowSeparator); 2068 } 2069 } 2070 break; 2071 } 2072 case MODE_Html: { 2073 if( p->cnt++==0 && p->showHeader ){ 2074 raw_printf(p->out,"<TR>"); 2075 for(i=0; i<nArg; i++){ 2076 raw_printf(p->out,"<TH>"); 2077 output_html_string(p->out, azCol[i]); 2078 raw_printf(p->out,"</TH>\n"); 2079 } 2080 raw_printf(p->out,"</TR>\n"); 2081 } 2082 if( azArg==0 ) break; 2083 raw_printf(p->out,"<TR>"); 2084 for(i=0; i<nArg; i++){ 2085 raw_printf(p->out,"<TD>"); 2086 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2087 raw_printf(p->out,"</TD>\n"); 2088 } 2089 raw_printf(p->out,"</TR>\n"); 2090 break; 2091 } 2092 case MODE_Tcl: { 2093 if( p->cnt++==0 && p->showHeader ){ 2094 for(i=0; i<nArg; i++){ 2095 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2096 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2097 } 2098 utf8_printf(p->out, "%s", p->rowSeparator); 2099 } 2100 if( azArg==0 ) break; 2101 for(i=0; i<nArg; i++){ 2102 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2103 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2104 } 2105 utf8_printf(p->out, "%s", p->rowSeparator); 2106 break; 2107 } 2108 case MODE_Csv: { 2109 setBinaryMode(p->out, 1); 2110 if( p->cnt++==0 && p->showHeader ){ 2111 for(i=0; i<nArg; i++){ 2112 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2113 } 2114 utf8_printf(p->out, "%s", p->rowSeparator); 2115 } 2116 if( nArg>0 ){ 2117 for(i=0; i<nArg; i++){ 2118 output_csv(p, azArg[i], i<nArg-1); 2119 } 2120 utf8_printf(p->out, "%s", p->rowSeparator); 2121 } 2122 setTextMode(p->out, 1); 2123 break; 2124 } 2125 case MODE_Insert: { 2126 if( azArg==0 ) break; 2127 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2128 if( p->showHeader ){ 2129 raw_printf(p->out,"("); 2130 for(i=0; i<nArg; i++){ 2131 if( i>0 ) raw_printf(p->out, ","); 2132 if( quoteChar(azCol[i]) ){ 2133 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2134 utf8_printf(p->out, "%s", z); 2135 sqlite3_free(z); 2136 }else{ 2137 raw_printf(p->out, "%s", azCol[i]); 2138 } 2139 } 2140 raw_printf(p->out,")"); 2141 } 2142 p->cnt++; 2143 for(i=0; i<nArg; i++){ 2144 raw_printf(p->out, i>0 ? "," : " VALUES("); 2145 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2146 utf8_printf(p->out,"NULL"); 2147 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2148 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2149 output_quoted_string(p->out, azArg[i]); 2150 }else{ 2151 output_quoted_escaped_string(p->out, azArg[i]); 2152 } 2153 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2154 utf8_printf(p->out,"%s", azArg[i]); 2155 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2156 char z[50]; 2157 double r = sqlite3_column_double(p->pStmt, i); 2158 sqlite3_uint64 ur; 2159 memcpy(&ur,&r,sizeof(r)); 2160 if( ur==0x7ff0000000000000LL ){ 2161 raw_printf(p->out, "1e999"); 2162 }else if( ur==0xfff0000000000000LL ){ 2163 raw_printf(p->out, "-1e999"); 2164 }else{ 2165 sqlite3_snprintf(50,z,"%!.20g", r); 2166 raw_printf(p->out, "%s", z); 2167 } 2168 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2169 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2170 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2171 output_hex_blob(p->out, pBlob, nBlob); 2172 }else if( isNumber(azArg[i], 0) ){ 2173 utf8_printf(p->out,"%s", azArg[i]); 2174 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2175 output_quoted_string(p->out, azArg[i]); 2176 }else{ 2177 output_quoted_escaped_string(p->out, azArg[i]); 2178 } 2179 } 2180 raw_printf(p->out,");\n"); 2181 break; 2182 } 2183 case MODE_Quote: { 2184 if( azArg==0 ) break; 2185 if( p->cnt==0 && p->showHeader ){ 2186 for(i=0; i<nArg; i++){ 2187 if( i>0 ) raw_printf(p->out, ","); 2188 output_quoted_string(p->out, azCol[i]); 2189 } 2190 raw_printf(p->out,"\n"); 2191 } 2192 p->cnt++; 2193 for(i=0; i<nArg; i++){ 2194 if( i>0 ) raw_printf(p->out, ","); 2195 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2196 utf8_printf(p->out,"NULL"); 2197 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2198 output_quoted_string(p->out, azArg[i]); 2199 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2200 utf8_printf(p->out,"%s", azArg[i]); 2201 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2202 char z[50]; 2203 double r = sqlite3_column_double(p->pStmt, i); 2204 sqlite3_snprintf(50,z,"%!.20g", r); 2205 raw_printf(p->out, "%s", z); 2206 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2207 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2208 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2209 output_hex_blob(p->out, pBlob, nBlob); 2210 }else if( isNumber(azArg[i], 0) ){ 2211 utf8_printf(p->out,"%s", azArg[i]); 2212 }else{ 2213 output_quoted_string(p->out, azArg[i]); 2214 } 2215 } 2216 raw_printf(p->out,"\n"); 2217 break; 2218 } 2219 case MODE_Ascii: { 2220 if( p->cnt++==0 && p->showHeader ){ 2221 for(i=0; i<nArg; i++){ 2222 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2223 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2224 } 2225 utf8_printf(p->out, "%s", p->rowSeparator); 2226 } 2227 if( azArg==0 ) break; 2228 for(i=0; i<nArg; i++){ 2229 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2230 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2231 } 2232 utf8_printf(p->out, "%s", p->rowSeparator); 2233 break; 2234 } 2235 case MODE_EQP: { 2236 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2237 break; 2238 } 2239 } 2240 return 0; 2241} 2242 2243/* 2244** This is the callback routine that the SQLite library 2245** invokes for each row of a query result. 2246*/ 2247static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2248 /* since we don't have type info, call the shell_callback with a NULL value */ 2249 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2250} 2251 2252/* 2253** This is the callback routine from sqlite3_exec() that appends all 2254** output onto the end of a ShellText object. 2255*/ 2256static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2257 ShellText *p = (ShellText*)pArg; 2258 int i; 2259 UNUSED_PARAMETER(az); 2260 if( azArg==0 ) return 0; 2261 if( p->n ) appendText(p, "|", 0); 2262 for(i=0; i<nArg; i++){ 2263 if( i ) appendText(p, ",", 0); 2264 if( azArg[i] ) appendText(p, azArg[i], 0); 2265 } 2266 return 0; 2267} 2268 2269/* 2270** Generate an appropriate SELFTEST table in the main database. 2271*/ 2272static void createSelftestTable(ShellState *p){ 2273 char *zErrMsg = 0; 2274 sqlite3_exec(p->db, 2275 "SAVEPOINT selftest_init;\n" 2276 "CREATE TABLE IF NOT EXISTS selftest(\n" 2277 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2278 " op TEXT,\n" /* Operator: memo run */ 2279 " cmd TEXT,\n" /* Command text */ 2280 " ans TEXT\n" /* Desired answer */ 2281 ");" 2282 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2283 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2284 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2285 " 'memo','Tests generated by --init');\n" 2286 "INSERT INTO [_shell$self]\n" 2287 " SELECT 'run',\n" 2288 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2289 "FROM sqlite_master ORDER BY 2'',224))',\n" 2290 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2291 "FROM sqlite_master ORDER BY 2',224));\n" 2292 "INSERT INTO [_shell$self]\n" 2293 " SELECT 'run'," 2294 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2295 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2296 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2297 " FROM (\n" 2298 " SELECT name FROM sqlite_master\n" 2299 " WHERE type='table'\n" 2300 " AND name<>'selftest'\n" 2301 " AND coalesce(rootpage,0)>0\n" 2302 " )\n" 2303 " ORDER BY name;\n" 2304 "INSERT INTO [_shell$self]\n" 2305 " VALUES('run','PRAGMA integrity_check','ok');\n" 2306 "INSERT INTO selftest(tno,op,cmd,ans)" 2307 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2308 "DROP TABLE [_shell$self];" 2309 ,0,0,&zErrMsg); 2310 if( zErrMsg ){ 2311 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2312 sqlite3_free(zErrMsg); 2313 } 2314 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2315} 2316 2317 2318/* 2319** Set the destination table field of the ShellState structure to 2320** the name of the table given. Escape any quote characters in the 2321** table name. 2322*/ 2323static void set_table_name(ShellState *p, const char *zName){ 2324 int i, n; 2325 char cQuote; 2326 char *z; 2327 2328 if( p->zDestTable ){ 2329 free(p->zDestTable); 2330 p->zDestTable = 0; 2331 } 2332 if( zName==0 ) return; 2333 cQuote = quoteChar(zName); 2334 n = strlen30(zName); 2335 if( cQuote ) n += n+2; 2336 z = p->zDestTable = malloc( n+1 ); 2337 if( z==0 ) shell_out_of_memory(); 2338 n = 0; 2339 if( cQuote ) z[n++] = cQuote; 2340 for(i=0; zName[i]; i++){ 2341 z[n++] = zName[i]; 2342 if( zName[i]==cQuote ) z[n++] = cQuote; 2343 } 2344 if( cQuote ) z[n++] = cQuote; 2345 z[n] = 0; 2346} 2347 2348 2349/* 2350** Execute a query statement that will generate SQL output. Print 2351** the result columns, comma-separated, on a line and then add a 2352** semicolon terminator to the end of that line. 2353** 2354** If the number of columns is 1 and that column contains text "--" 2355** then write the semicolon on a separate line. That way, if a 2356** "--" comment occurs at the end of the statement, the comment 2357** won't consume the semicolon terminator. 2358*/ 2359static int run_table_dump_query( 2360 ShellState *p, /* Query context */ 2361 const char *zSelect, /* SELECT statement to extract content */ 2362 const char *zFirstRow /* Print before first row, if not NULL */ 2363){ 2364 sqlite3_stmt *pSelect; 2365 int rc; 2366 int nResult; 2367 int i; 2368 const char *z; 2369 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2370 if( rc!=SQLITE_OK || !pSelect ){ 2371 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2372 sqlite3_errmsg(p->db)); 2373 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2374 return rc; 2375 } 2376 rc = sqlite3_step(pSelect); 2377 nResult = sqlite3_column_count(pSelect); 2378 while( rc==SQLITE_ROW ){ 2379 if( zFirstRow ){ 2380 utf8_printf(p->out, "%s", zFirstRow); 2381 zFirstRow = 0; 2382 } 2383 z = (const char*)sqlite3_column_text(pSelect, 0); 2384 utf8_printf(p->out, "%s", z); 2385 for(i=1; i<nResult; i++){ 2386 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2387 } 2388 if( z==0 ) z = ""; 2389 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2390 if( z[0] ){ 2391 raw_printf(p->out, "\n;\n"); 2392 }else{ 2393 raw_printf(p->out, ";\n"); 2394 } 2395 rc = sqlite3_step(pSelect); 2396 } 2397 rc = sqlite3_finalize(pSelect); 2398 if( rc!=SQLITE_OK ){ 2399 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2400 sqlite3_errmsg(p->db)); 2401 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2402 } 2403 return rc; 2404} 2405 2406/* 2407** Allocate space and save off current error string. 2408*/ 2409static char *save_err_msg( 2410 sqlite3 *db /* Database to query */ 2411){ 2412 int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); 2413 char *zErrMsg = sqlite3_malloc64(nErrMsg); 2414 if( zErrMsg ){ 2415 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); 2416 } 2417 return zErrMsg; 2418} 2419 2420#ifdef __linux__ 2421/* 2422** Attempt to display I/O stats on Linux using /proc/PID/io 2423*/ 2424static void displayLinuxIoStats(FILE *out){ 2425 FILE *in; 2426 char z[200]; 2427 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2428 in = fopen(z, "rb"); 2429 if( in==0 ) return; 2430 while( fgets(z, sizeof(z), in)!=0 ){ 2431 static const struct { 2432 const char *zPattern; 2433 const char *zDesc; 2434 } aTrans[] = { 2435 { "rchar: ", "Bytes received by read():" }, 2436 { "wchar: ", "Bytes sent to write():" }, 2437 { "syscr: ", "Read() system calls:" }, 2438 { "syscw: ", "Write() system calls:" }, 2439 { "read_bytes: ", "Bytes read from storage:" }, 2440 { "write_bytes: ", "Bytes written to storage:" }, 2441 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2442 }; 2443 int i; 2444 for(i=0; i<ArraySize(aTrans); i++){ 2445 int n = strlen30(aTrans[i].zPattern); 2446 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2447 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2448 break; 2449 } 2450 } 2451 } 2452 fclose(in); 2453} 2454#endif 2455 2456/* 2457** Display a single line of status using 64-bit values. 2458*/ 2459static void displayStatLine( 2460 ShellState *p, /* The shell context */ 2461 char *zLabel, /* Label for this one line */ 2462 char *zFormat, /* Format for the result */ 2463 int iStatusCtrl, /* Which status to display */ 2464 int bReset /* True to reset the stats */ 2465){ 2466 sqlite3_int64 iCur = -1; 2467 sqlite3_int64 iHiwtr = -1; 2468 int i, nPercent; 2469 char zLine[200]; 2470 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2471 for(i=0, nPercent=0; zFormat[i]; i++){ 2472 if( zFormat[i]=='%' ) nPercent++; 2473 } 2474 if( nPercent>1 ){ 2475 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2476 }else{ 2477 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2478 } 2479 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2480} 2481 2482/* 2483** Display memory stats. 2484*/ 2485static int display_stats( 2486 sqlite3 *db, /* Database to query */ 2487 ShellState *pArg, /* Pointer to ShellState */ 2488 int bReset /* True to reset the stats */ 2489){ 2490 int iCur; 2491 int iHiwtr; 2492 FILE *out; 2493 if( pArg==0 || pArg->out==0 ) return 0; 2494 out = pArg->out; 2495 2496 if( pArg->pStmt && (pArg->statsOn & 2) ){ 2497 int nCol, i, x; 2498 sqlite3_stmt *pStmt = pArg->pStmt; 2499 char z[100]; 2500 nCol = sqlite3_column_count(pStmt); 2501 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2502 for(i=0; i<nCol; i++){ 2503 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2504 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2505#ifndef SQLITE_OMIT_DECLTYPE 2506 sqlite3_snprintf(30, z+x, "declared type:"); 2507 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2508#endif 2509#ifdef SQLITE_ENABLE_COLUMN_METADATA 2510 sqlite3_snprintf(30, z+x, "database name:"); 2511 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2512 sqlite3_snprintf(30, z+x, "table name:"); 2513 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2514 sqlite3_snprintf(30, z+x, "origin name:"); 2515 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2516#endif 2517 } 2518 } 2519 2520 displayStatLine(pArg, "Memory Used:", 2521 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2522 displayStatLine(pArg, "Number of Outstanding Allocations:", 2523 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2524 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2525 displayStatLine(pArg, "Number of Pcache Pages Used:", 2526 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2527 } 2528 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2529 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2530 displayStatLine(pArg, "Largest Allocation:", 2531 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2532 displayStatLine(pArg, "Largest Pcache Allocation:", 2533 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2534#ifdef YYTRACKMAXSTACKDEPTH 2535 displayStatLine(pArg, "Deepest Parser Stack:", 2536 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2537#endif 2538 2539 if( db ){ 2540 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2541 iHiwtr = iCur = -1; 2542 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2543 &iCur, &iHiwtr, bReset); 2544 raw_printf(pArg->out, 2545 "Lookaside Slots Used: %d (max %d)\n", 2546 iCur, iHiwtr); 2547 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2548 &iCur, &iHiwtr, bReset); 2549 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2550 iHiwtr); 2551 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2552 &iCur, &iHiwtr, bReset); 2553 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2554 iHiwtr); 2555 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2556 &iCur, &iHiwtr, bReset); 2557 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2558 iHiwtr); 2559 } 2560 iHiwtr = iCur = -1; 2561 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2562 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2563 iCur); 2564 iHiwtr = iCur = -1; 2565 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2566 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2567 iHiwtr = iCur = -1; 2568 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2569 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2570 iHiwtr = iCur = -1; 2571 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2572 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2573 iHiwtr = iCur = -1; 2574 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2575 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2576 iHiwtr = iCur = -1; 2577 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2578 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2579 iCur); 2580 iHiwtr = iCur = -1; 2581 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2582 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2583 iCur); 2584 } 2585 2586 if( pArg->pStmt ){ 2587 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2588 bReset); 2589 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2590 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2591 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2592 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2593 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2594 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2595 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2596 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); 2597 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2598 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2599 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2600 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2601 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2602 } 2603 2604#ifdef __linux__ 2605 displayLinuxIoStats(pArg->out); 2606#endif 2607 2608 /* Do not remove this machine readable comment: extra-stats-output-here */ 2609 2610 return 0; 2611} 2612 2613/* 2614** Display scan stats. 2615*/ 2616static void display_scanstats( 2617 sqlite3 *db, /* Database to query */ 2618 ShellState *pArg /* Pointer to ShellState */ 2619){ 2620#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2621 UNUSED_PARAMETER(db); 2622 UNUSED_PARAMETER(pArg); 2623#else 2624 int i, k, n, mx; 2625 raw_printf(pArg->out, "-------- scanstats --------\n"); 2626 mx = 0; 2627 for(k=0; k<=mx; k++){ 2628 double rEstLoop = 1.0; 2629 for(i=n=0; 1; i++){ 2630 sqlite3_stmt *p = pArg->pStmt; 2631 sqlite3_int64 nLoop, nVisit; 2632 double rEst; 2633 int iSid; 2634 const char *zExplain; 2635 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2636 break; 2637 } 2638 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2639 if( iSid>mx ) mx = iSid; 2640 if( iSid!=k ) continue; 2641 if( n==0 ){ 2642 rEstLoop = (double)nLoop; 2643 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2644 } 2645 n++; 2646 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2647 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2648 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2649 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2650 rEstLoop *= rEst; 2651 raw_printf(pArg->out, 2652 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2653 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2654 ); 2655 } 2656 } 2657 raw_printf(pArg->out, "---------------------------\n"); 2658#endif 2659} 2660 2661/* 2662** Parameter azArray points to a zero-terminated array of strings. zStr 2663** points to a single nul-terminated string. Return non-zero if zStr 2664** is equal, according to strcmp(), to any of the strings in the array. 2665** Otherwise, return zero. 2666*/ 2667static int str_in_array(const char *zStr, const char **azArray){ 2668 int i; 2669 for(i=0; azArray[i]; i++){ 2670 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2671 } 2672 return 0; 2673} 2674 2675/* 2676** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2677** and populate the ShellState.aiIndent[] array with the number of 2678** spaces each opcode should be indented before it is output. 2679** 2680** The indenting rules are: 2681** 2682** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2683** all opcodes that occur between the p2 jump destination and the opcode 2684** itself by 2 spaces. 2685** 2686** * For each "Goto", if the jump destination is earlier in the program 2687** and ends on one of: 2688** Yield SeekGt SeekLt RowSetRead Rewind 2689** or if the P1 parameter is one instead of zero, 2690** then indent all opcodes between the earlier instruction 2691** and "Goto" by 2 spaces. 2692*/ 2693static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2694 const char *zSql; /* The text of the SQL statement */ 2695 const char *z; /* Used to check if this is an EXPLAIN */ 2696 int *abYield = 0; /* True if op is an OP_Yield */ 2697 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2698 int iOp; /* Index of operation in p->aiIndent[] */ 2699 2700 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2701 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2702 "Rewind", 0 }; 2703 const char *azGoto[] = { "Goto", 0 }; 2704 2705 /* Try to figure out if this is really an EXPLAIN statement. If this 2706 ** cannot be verified, return early. */ 2707 if( sqlite3_column_count(pSql)!=8 ){ 2708 p->cMode = p->mode; 2709 return; 2710 } 2711 zSql = sqlite3_sql(pSql); 2712 if( zSql==0 ) return; 2713 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2714 if( sqlite3_strnicmp(z, "explain", 7) ){ 2715 p->cMode = p->mode; 2716 return; 2717 } 2718 2719 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2720 int i; 2721 int iAddr = sqlite3_column_int(pSql, 0); 2722 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2723 2724 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2725 ** p2 is an instruction address, set variable p2op to the index of that 2726 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2727 ** the current instruction is part of a sub-program generated by an 2728 ** SQL trigger or foreign key. */ 2729 int p2 = sqlite3_column_int(pSql, 3); 2730 int p2op = (p2 + (iOp-iAddr)); 2731 2732 /* Grow the p->aiIndent array as required */ 2733 if( iOp>=nAlloc ){ 2734 if( iOp==0 ){ 2735 /* Do further verfication that this is explain output. Abort if 2736 ** it is not */ 2737 static const char *explainCols[] = { 2738 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2739 int jj; 2740 for(jj=0; jj<ArraySize(explainCols); jj++){ 2741 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2742 p->cMode = p->mode; 2743 sqlite3_reset(pSql); 2744 return; 2745 } 2746 } 2747 } 2748 nAlloc += 100; 2749 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2750 if( p->aiIndent==0 ) shell_out_of_memory(); 2751 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2752 if( abYield==0 ) shell_out_of_memory(); 2753 } 2754 abYield[iOp] = str_in_array(zOp, azYield); 2755 p->aiIndent[iOp] = 0; 2756 p->nIndent = iOp+1; 2757 2758 if( str_in_array(zOp, azNext) ){ 2759 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2760 } 2761 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 2762 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 2763 ){ 2764 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2765 } 2766 } 2767 2768 p->iIndent = 0; 2769 sqlite3_free(abYield); 2770 sqlite3_reset(pSql); 2771} 2772 2773/* 2774** Free the array allocated by explain_data_prepare(). 2775*/ 2776static void explain_data_delete(ShellState *p){ 2777 sqlite3_free(p->aiIndent); 2778 p->aiIndent = 0; 2779 p->nIndent = 0; 2780 p->iIndent = 0; 2781} 2782 2783/* 2784** Disable and restore .wheretrace and .selecttrace settings. 2785*/ 2786#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2787extern int sqlite3SelectTrace; 2788static int savedSelectTrace; 2789#endif 2790#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2791extern int sqlite3WhereTrace; 2792static int savedWhereTrace; 2793#endif 2794static void disable_debug_trace_modes(void){ 2795#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2796 savedSelectTrace = sqlite3SelectTrace; 2797 sqlite3SelectTrace = 0; 2798#endif 2799#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2800 savedWhereTrace = sqlite3WhereTrace; 2801 sqlite3WhereTrace = 0; 2802#endif 2803} 2804static void restore_debug_trace_modes(void){ 2805#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2806 sqlite3SelectTrace = savedSelectTrace; 2807#endif 2808#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2809 sqlite3WhereTrace = savedWhereTrace; 2810#endif 2811} 2812 2813/* Create the TEMP table used to store parameter bindings */ 2814static void bind_table_init(ShellState *p){ 2815 int wrSchema = 0; 2816 int defensiveMode = 0; 2817 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); 2818 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); 2819 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 2820 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 2821 sqlite3_exec(p->db, 2822 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 2823 " key TEXT PRIMARY KEY,\n" 2824 " value ANY\n" 2825 ") WITHOUT ROWID;", 2826 0, 0, 0); 2827 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 2828 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); 2829} 2830 2831/* 2832** Bind parameters on a prepared statement. 2833** 2834** Parameter bindings are taken from a TEMP table of the form: 2835** 2836** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 2837** WITHOUT ROWID; 2838** 2839** No bindings occur if this table does not exist. The special character '$' 2840** is included in the table name to help prevent collisions with actual tables. 2841** The table must be in the TEMP schema. 2842*/ 2843static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 2844 int nVar; 2845 int i; 2846 int rc; 2847 sqlite3_stmt *pQ = 0; 2848 2849 nVar = sqlite3_bind_parameter_count(pStmt); 2850 if( nVar==0 ) return; /* Nothing to do */ 2851 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 2852 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 2853 return; /* Parameter table does not exist */ 2854 } 2855 rc = sqlite3_prepare_v2(pArg->db, 2856 "SELECT value FROM temp.sqlite_parameters" 2857 " WHERE key=?1", -1, &pQ, 0); 2858 if( rc || pQ==0 ) return; 2859 for(i=1; i<=nVar; i++){ 2860 char zNum[30]; 2861 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 2862 if( zVar==0 ){ 2863 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 2864 zVar = zNum; 2865 } 2866 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 2867 if( sqlite3_step(pQ)==SQLITE_ROW ){ 2868 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 2869 }else{ 2870 sqlite3_bind_null(pStmt, i); 2871 } 2872 sqlite3_reset(pQ); 2873 } 2874 sqlite3_finalize(pQ); 2875} 2876 2877/* 2878** Run a prepared statement 2879*/ 2880static void exec_prepared_stmt( 2881 ShellState *pArg, /* Pointer to ShellState */ 2882 sqlite3_stmt *pStmt /* Statment to run */ 2883){ 2884 int rc; 2885 2886 /* perform the first step. this will tell us if we 2887 ** have a result set or not and how wide it is. 2888 */ 2889 rc = sqlite3_step(pStmt); 2890 /* if we have a result set... */ 2891 if( SQLITE_ROW == rc ){ 2892 /* allocate space for col name ptr, value ptr, and type */ 2893 int nCol = sqlite3_column_count(pStmt); 2894 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 2895 if( !pData ){ 2896 rc = SQLITE_NOMEM; 2897 }else{ 2898 char **azCols = (char **)pData; /* Names of result columns */ 2899 char **azVals = &azCols[nCol]; /* Results */ 2900 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 2901 int i, x; 2902 assert(sizeof(int) <= sizeof(char *)); 2903 /* save off ptrs to column names */ 2904 for(i=0; i<nCol; i++){ 2905 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 2906 } 2907 do{ 2908 /* extract the data and data types */ 2909 for(i=0; i<nCol; i++){ 2910 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 2911 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ 2912 azVals[i] = ""; 2913 }else{ 2914 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 2915 } 2916 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 2917 rc = SQLITE_NOMEM; 2918 break; /* from for */ 2919 } 2920 } /* end for */ 2921 2922 /* if data and types extracted successfully... */ 2923 if( SQLITE_ROW == rc ){ 2924 /* call the supplied callback with the result row data */ 2925 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 2926 rc = SQLITE_ABORT; 2927 }else{ 2928 rc = sqlite3_step(pStmt); 2929 } 2930 } 2931 } while( SQLITE_ROW == rc ); 2932 sqlite3_free(pData); 2933 } 2934 } 2935} 2936 2937#ifndef SQLITE_OMIT_VIRTUALTABLE 2938/* 2939** This function is called to process SQL if the previous shell command 2940** was ".expert". It passes the SQL in the second argument directly to 2941** the sqlite3expert object. 2942** 2943** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2944** code. In this case, (*pzErr) may be set to point to a buffer containing 2945** an English language error message. It is the responsibility of the 2946** caller to eventually free this buffer using sqlite3_free(). 2947*/ 2948static int expertHandleSQL( 2949 ShellState *pState, 2950 const char *zSql, 2951 char **pzErr 2952){ 2953 assert( pState->expert.pExpert ); 2954 assert( pzErr==0 || *pzErr==0 ); 2955 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 2956} 2957 2958/* 2959** This function is called either to silently clean up the object 2960** created by the ".expert" command (if bCancel==1), or to generate a 2961** report from it and then clean it up (if bCancel==0). 2962** 2963** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2964** code. In this case, (*pzErr) may be set to point to a buffer containing 2965** an English language error message. It is the responsibility of the 2966** caller to eventually free this buffer using sqlite3_free(). 2967*/ 2968static int expertFinish( 2969 ShellState *pState, 2970 int bCancel, 2971 char **pzErr 2972){ 2973 int rc = SQLITE_OK; 2974 sqlite3expert *p = pState->expert.pExpert; 2975 assert( p ); 2976 assert( bCancel || pzErr==0 || *pzErr==0 ); 2977 if( bCancel==0 ){ 2978 FILE *out = pState->out; 2979 int bVerbose = pState->expert.bVerbose; 2980 2981 rc = sqlite3_expert_analyze(p, pzErr); 2982 if( rc==SQLITE_OK ){ 2983 int nQuery = sqlite3_expert_count(p); 2984 int i; 2985 2986 if( bVerbose ){ 2987 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 2988 raw_printf(out, "-- Candidates -----------------------------\n"); 2989 raw_printf(out, "%s\n", zCand); 2990 } 2991 for(i=0; i<nQuery; i++){ 2992 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 2993 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 2994 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 2995 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 2996 if( bVerbose ){ 2997 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 2998 raw_printf(out, "%s\n\n", zSql); 2999 } 3000 raw_printf(out, "%s\n", zIdx); 3001 raw_printf(out, "%s\n", zEQP); 3002 } 3003 } 3004 } 3005 sqlite3_expert_destroy(p); 3006 pState->expert.pExpert = 0; 3007 return rc; 3008} 3009 3010/* 3011** Implementation of ".expert" dot command. 3012*/ 3013static int expertDotCommand( 3014 ShellState *pState, /* Current shell tool state */ 3015 char **azArg, /* Array of arguments passed to dot command */ 3016 int nArg /* Number of entries in azArg[] */ 3017){ 3018 int rc = SQLITE_OK; 3019 char *zErr = 0; 3020 int i; 3021 int iSample = 0; 3022 3023 assert( pState->expert.pExpert==0 ); 3024 memset(&pState->expert, 0, sizeof(ExpertInfo)); 3025 3026 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 3027 char *z = azArg[i]; 3028 int n; 3029 if( z[0]=='-' && z[1]=='-' ) z++; 3030 n = strlen30(z); 3031 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 3032 pState->expert.bVerbose = 1; 3033 } 3034 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 3035 if( i==(nArg-1) ){ 3036 raw_printf(stderr, "option requires an argument: %s\n", z); 3037 rc = SQLITE_ERROR; 3038 }else{ 3039 iSample = (int)integerValue(azArg[++i]); 3040 if( iSample<0 || iSample>100 ){ 3041 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 3042 rc = SQLITE_ERROR; 3043 } 3044 } 3045 } 3046 else{ 3047 raw_printf(stderr, "unknown option: %s\n", z); 3048 rc = SQLITE_ERROR; 3049 } 3050 } 3051 3052 if( rc==SQLITE_OK ){ 3053 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 3054 if( pState->expert.pExpert==0 ){ 3055 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); 3056 rc = SQLITE_ERROR; 3057 }else{ 3058 sqlite3_expert_config( 3059 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 3060 ); 3061 } 3062 } 3063 3064 return rc; 3065} 3066#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3067 3068/* 3069** Execute a statement or set of statements. Print 3070** any result rows/columns depending on the current mode 3071** set via the supplied callback. 3072** 3073** This is very similar to SQLite's built-in sqlite3_exec() 3074** function except it takes a slightly different callback 3075** and callback data argument. 3076*/ 3077static int shell_exec( 3078 ShellState *pArg, /* Pointer to ShellState */ 3079 const char *zSql, /* SQL to be evaluated */ 3080 char **pzErrMsg /* Error msg written here */ 3081){ 3082 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3083 int rc = SQLITE_OK; /* Return Code */ 3084 int rc2; 3085 const char *zLeftover; /* Tail of unprocessed SQL */ 3086 sqlite3 *db = pArg->db; 3087 3088 if( pzErrMsg ){ 3089 *pzErrMsg = NULL; 3090 } 3091 3092#ifndef SQLITE_OMIT_VIRTUALTABLE 3093 if( pArg->expert.pExpert ){ 3094 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3095 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3096 } 3097#endif 3098 3099 while( zSql[0] && (SQLITE_OK == rc) ){ 3100 static const char *zStmtSql; 3101 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3102 if( SQLITE_OK != rc ){ 3103 if( pzErrMsg ){ 3104 *pzErrMsg = save_err_msg(db); 3105 } 3106 }else{ 3107 if( !pStmt ){ 3108 /* this happens for a comment or white-space */ 3109 zSql = zLeftover; 3110 while( IsSpace(zSql[0]) ) zSql++; 3111 continue; 3112 } 3113 zStmtSql = sqlite3_sql(pStmt); 3114 if( zStmtSql==0 ) zStmtSql = ""; 3115 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3116 3117 /* save off the prepared statment handle and reset row count */ 3118 if( pArg ){ 3119 pArg->pStmt = pStmt; 3120 pArg->cnt = 0; 3121 } 3122 3123 /* echo the sql statement if echo on */ 3124 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3125 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3126 } 3127 3128 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3129 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3130 sqlite3_stmt *pExplain; 3131 char *zEQP; 3132 int triggerEQP = 0; 3133 disable_debug_trace_modes(); 3134 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3135 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3136 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3137 } 3138 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3139 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3140 if( rc==SQLITE_OK ){ 3141 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3142 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3143 int iEqpId = sqlite3_column_int(pExplain, 0); 3144 int iParentId = sqlite3_column_int(pExplain, 1); 3145 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3146 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3147 } 3148 eqp_render(pArg); 3149 } 3150 sqlite3_finalize(pExplain); 3151 sqlite3_free(zEQP); 3152 if( pArg->autoEQP>=AUTOEQP_full ){ 3153 /* Also do an EXPLAIN for ".eqp full" mode */ 3154 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3155 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3156 if( rc==SQLITE_OK ){ 3157 pArg->cMode = MODE_Explain; 3158 explain_data_prepare(pArg, pExplain); 3159 exec_prepared_stmt(pArg, pExplain); 3160 explain_data_delete(pArg); 3161 } 3162 sqlite3_finalize(pExplain); 3163 sqlite3_free(zEQP); 3164 } 3165 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3166 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3167 /* Reprepare pStmt before reactiving trace modes */ 3168 sqlite3_finalize(pStmt); 3169 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3170 if( pArg ) pArg->pStmt = pStmt; 3171 } 3172 restore_debug_trace_modes(); 3173 } 3174 3175 if( pArg ){ 3176 pArg->cMode = pArg->mode; 3177 if( pArg->autoExplain ){ 3178 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3179 pArg->cMode = MODE_Explain; 3180 } 3181 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3182 pArg->cMode = MODE_EQP; 3183 } 3184 } 3185 3186 /* If the shell is currently in ".explain" mode, gather the extra 3187 ** data required to add indents to the output.*/ 3188 if( pArg->cMode==MODE_Explain ){ 3189 explain_data_prepare(pArg, pStmt); 3190 } 3191 } 3192 3193 bind_prepared_stmt(pArg, pStmt); 3194 exec_prepared_stmt(pArg, pStmt); 3195 explain_data_delete(pArg); 3196 eqp_render(pArg); 3197 3198 /* print usage stats if stats on */ 3199 if( pArg && pArg->statsOn ){ 3200 display_stats(db, pArg, 0); 3201 } 3202 3203 /* print loop-counters if required */ 3204 if( pArg && pArg->scanstatsOn ){ 3205 display_scanstats(db, pArg); 3206 } 3207 3208 /* Finalize the statement just executed. If this fails, save a 3209 ** copy of the error message. Otherwise, set zSql to point to the 3210 ** next statement to execute. */ 3211 rc2 = sqlite3_finalize(pStmt); 3212 if( rc!=SQLITE_NOMEM ) rc = rc2; 3213 if( rc==SQLITE_OK ){ 3214 zSql = zLeftover; 3215 while( IsSpace(zSql[0]) ) zSql++; 3216 }else if( pzErrMsg ){ 3217 *pzErrMsg = save_err_msg(db); 3218 } 3219 3220 /* clear saved stmt handle */ 3221 if( pArg ){ 3222 pArg->pStmt = NULL; 3223 } 3224 } 3225 } /* end while */ 3226 3227 return rc; 3228} 3229 3230/* 3231** Release memory previously allocated by tableColumnList(). 3232*/ 3233static void freeColumnList(char **azCol){ 3234 int i; 3235 for(i=1; azCol[i]; i++){ 3236 sqlite3_free(azCol[i]); 3237 } 3238 /* azCol[0] is a static string */ 3239 sqlite3_free(azCol); 3240} 3241 3242/* 3243** Return a list of pointers to strings which are the names of all 3244** columns in table zTab. The memory to hold the names is dynamically 3245** allocated and must be released by the caller using a subsequent call 3246** to freeColumnList(). 3247** 3248** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3249** value that needs to be preserved, then azCol[0] is filled in with the 3250** name of the rowid column. 3251** 3252** The first regular column in the table is azCol[1]. The list is terminated 3253** by an entry with azCol[i]==0. 3254*/ 3255static char **tableColumnList(ShellState *p, const char *zTab){ 3256 char **azCol = 0; 3257 sqlite3_stmt *pStmt; 3258 char *zSql; 3259 int nCol = 0; 3260 int nAlloc = 0; 3261 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3262 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3263 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3264 int rc; 3265 3266 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3267 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3268 sqlite3_free(zSql); 3269 if( rc ) return 0; 3270 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3271 if( nCol>=nAlloc-2 ){ 3272 nAlloc = nAlloc*2 + nCol + 10; 3273 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3274 if( azCol==0 ) shell_out_of_memory(); 3275 } 3276 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3277 if( sqlite3_column_int(pStmt, 5) ){ 3278 nPK++; 3279 if( nPK==1 3280 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3281 "INTEGER")==0 3282 ){ 3283 isIPK = 1; 3284 }else{ 3285 isIPK = 0; 3286 } 3287 } 3288 } 3289 sqlite3_finalize(pStmt); 3290 if( azCol==0 ) return 0; 3291 azCol[0] = 0; 3292 azCol[nCol+1] = 0; 3293 3294 /* The decision of whether or not a rowid really needs to be preserved 3295 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3296 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3297 ** rowids on tables where the rowid is inaccessible because there are other 3298 ** columns in the table named "rowid", "_rowid_", and "oid". 3299 */ 3300 if( preserveRowid && isIPK ){ 3301 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3302 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3303 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3304 ** ROWID aliases. To distinguish these cases, check to see if 3305 ** there is a "pk" entry in "PRAGMA index_list". There will be 3306 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3307 */ 3308 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3309 " WHERE origin='pk'", zTab); 3310 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3311 sqlite3_free(zSql); 3312 if( rc ){ 3313 freeColumnList(azCol); 3314 return 0; 3315 } 3316 rc = sqlite3_step(pStmt); 3317 sqlite3_finalize(pStmt); 3318 preserveRowid = rc==SQLITE_ROW; 3319 } 3320 if( preserveRowid ){ 3321 /* Only preserve the rowid if we can find a name to use for the 3322 ** rowid */ 3323 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3324 int i, j; 3325 for(j=0; j<3; j++){ 3326 for(i=1; i<=nCol; i++){ 3327 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3328 } 3329 if( i>nCol ){ 3330 /* At this point, we know that azRowid[j] is not the name of any 3331 ** ordinary column in the table. Verify that azRowid[j] is a valid 3332 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3333 ** tables will fail this last check */ 3334 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3335 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3336 break; 3337 } 3338 } 3339 } 3340 return azCol; 3341} 3342 3343/* 3344** Toggle the reverse_unordered_selects setting. 3345*/ 3346static void toggleSelectOrder(sqlite3 *db){ 3347 sqlite3_stmt *pStmt = 0; 3348 int iSetting = 0; 3349 char zStmt[100]; 3350 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3351 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3352 iSetting = sqlite3_column_int(pStmt, 0); 3353 } 3354 sqlite3_finalize(pStmt); 3355 sqlite3_snprintf(sizeof(zStmt), zStmt, 3356 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3357 sqlite3_exec(db, zStmt, 0, 0, 0); 3358} 3359 3360/* 3361** This is a different callback routine used for dumping the database. 3362** Each row received by this callback consists of a table name, 3363** the table type ("index" or "table") and SQL to create the table. 3364** This routine should print text sufficient to recreate the table. 3365*/ 3366static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3367 int rc; 3368 const char *zTable; 3369 const char *zType; 3370 const char *zSql; 3371 ShellState *p = (ShellState *)pArg; 3372 3373 UNUSED_PARAMETER(azNotUsed); 3374 if( nArg!=3 || azArg==0 ) return 0; 3375 zTable = azArg[0]; 3376 zType = azArg[1]; 3377 zSql = azArg[2]; 3378 3379 if( strcmp(zTable, "sqlite_sequence")==0 ){ 3380 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3381 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ 3382 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 3383 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3384 return 0; 3385 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3386 char *zIns; 3387 if( !p->writableSchema ){ 3388 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3389 p->writableSchema = 1; 3390 } 3391 zIns = sqlite3_mprintf( 3392 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" 3393 "VALUES('table','%q','%q',0,'%q');", 3394 zTable, zTable, zSql); 3395 utf8_printf(p->out, "%s\n", zIns); 3396 sqlite3_free(zIns); 3397 return 0; 3398 }else{ 3399 printSchemaLine(p->out, zSql, ";\n"); 3400 } 3401 3402 if( strcmp(zType, "table")==0 ){ 3403 ShellText sSelect; 3404 ShellText sTable; 3405 char **azCol; 3406 int i; 3407 char *savedDestTable; 3408 int savedMode; 3409 3410 azCol = tableColumnList(p, zTable); 3411 if( azCol==0 ){ 3412 p->nErr++; 3413 return 0; 3414 } 3415 3416 /* Always quote the table name, even if it appears to be pure ascii, 3417 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3418 initText(&sTable); 3419 appendText(&sTable, zTable, quoteChar(zTable)); 3420 /* If preserving the rowid, add a column list after the table name. 3421 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3422 ** instead of the usual "INSERT INTO tab VALUES(...)". 3423 */ 3424 if( azCol[0] ){ 3425 appendText(&sTable, "(", 0); 3426 appendText(&sTable, azCol[0], 0); 3427 for(i=1; azCol[i]; i++){ 3428 appendText(&sTable, ",", 0); 3429 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3430 } 3431 appendText(&sTable, ")", 0); 3432 } 3433 3434 /* Build an appropriate SELECT statement */ 3435 initText(&sSelect); 3436 appendText(&sSelect, "SELECT ", 0); 3437 if( azCol[0] ){ 3438 appendText(&sSelect, azCol[0], 0); 3439 appendText(&sSelect, ",", 0); 3440 } 3441 for(i=1; azCol[i]; i++){ 3442 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3443 if( azCol[i+1] ){ 3444 appendText(&sSelect, ",", 0); 3445 } 3446 } 3447 freeColumnList(azCol); 3448 appendText(&sSelect, " FROM ", 0); 3449 appendText(&sSelect, zTable, quoteChar(zTable)); 3450 3451 savedDestTable = p->zDestTable; 3452 savedMode = p->mode; 3453 p->zDestTable = sTable.z; 3454 p->mode = p->cMode = MODE_Insert; 3455 rc = shell_exec(p, sSelect.z, 0); 3456 if( (rc&0xff)==SQLITE_CORRUPT ){ 3457 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3458 toggleSelectOrder(p->db); 3459 shell_exec(p, sSelect.z, 0); 3460 toggleSelectOrder(p->db); 3461 } 3462 p->zDestTable = savedDestTable; 3463 p->mode = savedMode; 3464 freeText(&sTable); 3465 freeText(&sSelect); 3466 if( rc ) p->nErr++; 3467 } 3468 return 0; 3469} 3470 3471/* 3472** Run zQuery. Use dump_callback() as the callback routine so that 3473** the contents of the query are output as SQL statements. 3474** 3475** If we get a SQLITE_CORRUPT error, rerun the query after appending 3476** "ORDER BY rowid DESC" to the end. 3477*/ 3478static int run_schema_dump_query( 3479 ShellState *p, 3480 const char *zQuery 3481){ 3482 int rc; 3483 char *zErr = 0; 3484 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3485 if( rc==SQLITE_CORRUPT ){ 3486 char *zQ2; 3487 int len = strlen30(zQuery); 3488 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3489 if( zErr ){ 3490 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3491 sqlite3_free(zErr); 3492 zErr = 0; 3493 } 3494 zQ2 = malloc( len+100 ); 3495 if( zQ2==0 ) return rc; 3496 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3497 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3498 if( rc ){ 3499 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3500 }else{ 3501 rc = SQLITE_CORRUPT; 3502 } 3503 sqlite3_free(zErr); 3504 free(zQ2); 3505 } 3506 return rc; 3507} 3508 3509/* 3510** Text of help messages. 3511** 3512** The help text for each individual command begins with a line that starts 3513** with ".". Subsequent lines are supplimental information. 3514** 3515** There must be two or more spaces between the end of the command and the 3516** start of the description of what that command does. 3517*/ 3518static const char *(azHelp[]) = { 3519#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 3520 ".archive ... Manage SQL archives", 3521 " Each command must have exactly one of the following options:", 3522 " -c, --create Create a new archive", 3523 " -u, --update Add or update files with changed mtime", 3524 " -i, --insert Like -u but always add even if unchanged", 3525 " -t, --list List contents of archive", 3526 " -x, --extract Extract files from archive", 3527 " Optional arguments:", 3528 " -v, --verbose Print each filename as it is processed", 3529 " -f FILE, --file FILE Use archive FILE (default is current db)", 3530 " -a FILE, --append FILE Open FILE using the apndvfs VFS", 3531 " -C DIR, --directory DIR Read/extract files from directory DIR", 3532 " -n, --dryrun Show the SQL that would have occurred", 3533 " Examples:", 3534 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", 3535 " .ar -tf ARCHIVE # List members of ARCHIVE", 3536 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", 3537 " See also:", 3538 " http://sqlite.org/cli.html#sqlar_archive_support", 3539#endif 3540#ifndef SQLITE_OMIT_AUTHORIZATION 3541 ".auth ON|OFF Show authorizer callbacks", 3542#endif 3543 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 3544 " --append Use the appendvfs", 3545 " --async Write to FILE without journal and fsync()", 3546 ".bail on|off Stop after hitting an error. Default OFF", 3547 ".binary on|off Turn binary output on or off. Default OFF", 3548 ".cd DIRECTORY Change the working directory to DIRECTORY", 3549 ".changes on|off Show number of rows changed by SQL", 3550 ".check GLOB Fail if output since .testcase does not match", 3551 ".clone NEWDB Clone data into NEWDB from the existing database", 3552 ".databases List names and files of attached databases", 3553 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 3554 ".dbinfo ?DB? Show status information about the database", 3555 ".dump ?TABLE? ... Render all database content as SQL", 3556 " Options:", 3557 " --preserve-rowids Include ROWID values in the output", 3558 " --newlines Allow unescaped newline characters in output", 3559 " TABLE is a LIKE pattern for the tables to dump", 3560 ".echo on|off Turn command echo on or off", 3561 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 3562 " Other Modes:", 3563#ifdef SQLITE_DEBUG 3564 " test Show raw EXPLAIN QUERY PLAN output", 3565 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", 3566#endif 3567 " trigger Like \"full\" but also show trigger bytecode", 3568 ".excel Display the output of next command in spreadsheet", 3569 ".exit ?CODE? Exit this program with return-code CODE", 3570 ".expert EXPERIMENTAL. Suggest indexes for queries", 3571 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", 3572 ".filectrl CMD ... Run various sqlite3_file_control() operations", 3573 " Run \".filectrl\" with no arguments for details", 3574 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 3575 ".headers on|off Turn display of headers on or off", 3576 ".help ?-all? ?PATTERN? Show help text for PATTERN", 3577 ".import FILE TABLE Import data from FILE into TABLE", 3578 " Options:", 3579 " --ascii Use \\037 and \\036 as column and row separators", 3580 " --csv Use , and \\n as column and row separators", 3581 " --skip N Skip the first N rows of input", 3582 " -v \"Verbose\" - increase auxiliary output", 3583 " Notes:", 3584 " * If TABLE does not exist, it is created. The first row of input", 3585 " determines the column names.", 3586 " * If neither --csv or --ascii are used, the input mode is derived", 3587 " from the \".mode\" output mode", 3588 " * If FILE begins with \"|\" then it is a command that generates the", 3589 " input text.", 3590#ifndef SQLITE_OMIT_TEST_CONTROL 3591 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 3592#endif 3593 ".indexes ?TABLE? Show names of indexes", 3594 " If TABLE is specified, only show indexes for", 3595 " tables matching TABLE using the LIKE operator.", 3596#ifdef SQLITE_ENABLE_IOTRACE 3597 ".iotrace FILE Enable I/O diagnostic logging to FILE", 3598#endif 3599 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 3600 ".lint OPTIONS Report potential schema issues.", 3601 " Options:", 3602 " fkey-indexes Find missing foreign key indexes", 3603#ifndef SQLITE_OMIT_LOAD_EXTENSION 3604 ".load FILE ?ENTRY? Load an extension library", 3605#endif 3606 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 3607 ".mode MODE ?TABLE? Set output mode", 3608 " MODE is one of:", 3609 " ascii Columns/rows delimited by 0x1F and 0x1E", 3610 " csv Comma-separated values", 3611 " column Left-aligned columns. (See .width)", 3612 " html HTML <table> code", 3613 " insert SQL insert statements for TABLE", 3614 " line One value per line", 3615 " list Values delimited by \"|\"", 3616 " quote Escape answers as for SQL", 3617 " tabs Tab-separated values", 3618 " tcl TCL list elements", 3619 ".nullvalue STRING Use STRING in place of NULL values", 3620 ".once (-e|-x|FILE) Output for the next SQL command only to FILE", 3621 " If FILE begins with '|' then open as a pipe", 3622 " Other options:", 3623 " -e Invoke system text editor", 3624 " -x Open in a spreadsheet", 3625#ifdef SQLITE_DEBUG 3626 ".oom [--repeat M] [N] Simulate an OOM error on the N-th allocation", 3627#endif 3628 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 3629 " Options:", 3630 " --append Use appendvfs to append database to the end of FILE", 3631#ifdef SQLITE_ENABLE_DESERIALIZE 3632 " --deserialize Load into memory useing sqlite3_deserialize()", 3633 " --hexdb Load the output of \"dbtotxt\" as an in-memory db", 3634 " --maxsize N Maximum size for --hexdb or --deserialized database", 3635#endif 3636 " --new Initialize FILE to an empty database", 3637 " --nofollow Do not follow symbolic links", 3638 " --readonly Open FILE readonly", 3639 " --zip FILE is a ZIP archive", 3640 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 3641 " If FILE begins with '|' then open it as a pipe.", 3642 ".parameter CMD ... Manage SQL parameter bindings", 3643 " clear Erase all bindings", 3644 " init Initialize the TEMP table that holds bindings", 3645 " list List the current parameter bindings", 3646 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 3647 " PARAMETER should start with one of: $ : @ ?", 3648 " unset PARAMETER Remove PARAMETER from the binding table", 3649 ".print STRING... Print literal STRING", 3650#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 3651 ".progress N Invoke progress handler after every N opcodes", 3652 " --limit N Interrupt after N progress callbacks", 3653 " --once Do no more than one progress interrupt", 3654 " --quiet|-q No output except at interrupts", 3655 " --reset Reset the count for each input and interrupt", 3656#endif 3657 ".prompt MAIN CONTINUE Replace the standard prompts", 3658 ".quit Exit this program", 3659 ".read FILE Read input from FILE", 3660#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 3661 ".recover Recover as much data as possible from corrupt db.", 3662 " --freelist-corrupt Assume the freelist is corrupt", 3663 " --recovery-db NAME Store recovery metadata in database file NAME", 3664 " --lost-and-found TABLE Alternative name for the lost-and-found table", 3665 " --no-rowids Do not attempt to recover rowid values", 3666 " that are not also INTEGER PRIMARY KEYs", 3667#endif 3668 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 3669 ".save FILE Write in-memory database into FILE", 3670 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 3671 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 3672 " Options:", 3673 " --indent Try to pretty-print the schema", 3674 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 3675 " Options:", 3676 " --init Create a new SELFTEST table", 3677 " -v Verbose output", 3678 ".separator COL ?ROW? Change the column and row separators", 3679#if defined(SQLITE_ENABLE_SESSION) 3680 ".session ?NAME? CMD ... Create or control sessions", 3681 " Subcommands:", 3682 " attach TABLE Attach TABLE", 3683 " changeset FILE Write a changeset into FILE", 3684 " close Close one session", 3685 " enable ?BOOLEAN? Set or query the enable bit", 3686 " filter GLOB... Reject tables matching GLOBs", 3687 " indirect ?BOOLEAN? Mark or query the indirect status", 3688 " isempty Query whether the session is empty", 3689 " list List currently open session names", 3690 " open DB NAME Open a new session on DB", 3691 " patchset FILE Write a patchset into FILE", 3692 " If ?NAME? is omitted, the first defined session is used.", 3693#endif 3694 ".sha3sum ... Compute a SHA3 hash of database content", 3695 " Options:", 3696 " --schema Also hash the sqlite_master table", 3697 " --sha3-224 Use the sha3-224 algorithm", 3698 " --sha3-256 Use the sha3-256 algorithm (default)", 3699 " --sha3-384 Use the sha3-384 algorithm", 3700 " --sha3-512 Use the sha3-512 algorithm", 3701 " Any other argument is a LIKE pattern for tables to hash", 3702#ifndef SQLITE_NOHAVE_SYSTEM 3703 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 3704#endif 3705 ".show Show the current values for various settings", 3706 ".stats ?on|off? Show stats or turn stats on or off", 3707#ifndef SQLITE_NOHAVE_SYSTEM 3708 ".system CMD ARGS... Run CMD ARGS... in a system shell", 3709#endif 3710 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 3711 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 3712 ".testctrl CMD ... Run various sqlite3_test_control() operations", 3713 " Run \".testctrl\" with no arguments for details", 3714 ".timeout MS Try opening locked tables for MS milliseconds", 3715 ".timer on|off Turn SQL timer on or off", 3716#ifndef SQLITE_OMIT_TRACE 3717 ".trace ?OPTIONS? Output each SQL statement as it is run", 3718 " FILE Send output to FILE", 3719 " stdout Send output to stdout", 3720 " stderr Send output to stderr", 3721 " off Disable tracing", 3722 " --expanded Expand query parameters", 3723#ifdef SQLITE_ENABLE_NORMALIZE 3724 " --normalized Normal the SQL statements", 3725#endif 3726 " --plain Show SQL as it is input", 3727 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 3728 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 3729 " --row Trace each row (SQLITE_TRACE_ROW)", 3730 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 3731#endif /* SQLITE_OMIT_TRACE */ 3732#ifdef SQLITE_DEBUG 3733 ".unmodule NAME ... Unregister virtual table modules", 3734 " --allexcept Unregister everything except those named", 3735#endif 3736 ".vfsinfo ?AUX? Information about the top-level VFS", 3737 ".vfslist List all available VFSes", 3738 ".vfsname ?AUX? Print the name of the VFS stack", 3739 ".width NUM1 NUM2 ... Set column widths for \"column\" mode", 3740 " Negative values right-justify", 3741}; 3742 3743/* 3744** Output help text. 3745** 3746** zPattern describes the set of commands for which help text is provided. 3747** If zPattern is NULL, then show all commands, but only give a one-line 3748** description of each. 3749** 3750** Return the number of matches. 3751*/ 3752static int showHelp(FILE *out, const char *zPattern){ 3753 int i = 0; 3754 int j = 0; 3755 int n = 0; 3756 char *zPat; 3757 if( zPattern==0 3758 || zPattern[0]=='0' 3759 || strcmp(zPattern,"-a")==0 3760 || strcmp(zPattern,"-all")==0 3761 ){ 3762 /* Show all commands, but only one line per command */ 3763 if( zPattern==0 ) zPattern = ""; 3764 for(i=0; i<ArraySize(azHelp); i++){ 3765 if( azHelp[i][0]=='.' || zPattern[0] ){ 3766 utf8_printf(out, "%s\n", azHelp[i]); 3767 n++; 3768 } 3769 } 3770 }else{ 3771 /* Look for commands that for which zPattern is an exact prefix */ 3772 zPat = sqlite3_mprintf(".%s*", zPattern); 3773 for(i=0; i<ArraySize(azHelp); i++){ 3774 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 3775 utf8_printf(out, "%s\n", azHelp[i]); 3776 j = i+1; 3777 n++; 3778 } 3779 } 3780 sqlite3_free(zPat); 3781 if( n ){ 3782 if( n==1 ){ 3783 /* when zPattern is a prefix of exactly one command, then include the 3784 ** details of that command, which should begin at offset j */ 3785 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 3786 utf8_printf(out, "%s\n", azHelp[j]); 3787 j++; 3788 } 3789 } 3790 return n; 3791 } 3792 /* Look for commands that contain zPattern anywhere. Show the complete 3793 ** text of all commands that match. */ 3794 zPat = sqlite3_mprintf("%%%s%%", zPattern); 3795 for(i=0; i<ArraySize(azHelp); i++){ 3796 if( azHelp[i][0]=='.' ) j = i; 3797 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 3798 utf8_printf(out, "%s\n", azHelp[j]); 3799 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 3800 j++; 3801 utf8_printf(out, "%s\n", azHelp[j]); 3802 } 3803 i = j; 3804 n++; 3805 } 3806 } 3807 sqlite3_free(zPat); 3808 } 3809 return n; 3810} 3811 3812/* Forward reference */ 3813static int process_input(ShellState *p); 3814 3815/* 3816** Read the content of file zName into memory obtained from sqlite3_malloc64() 3817** and return a pointer to the buffer. The caller is responsible for freeing 3818** the memory. 3819** 3820** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 3821** read. 3822** 3823** For convenience, a nul-terminator byte is always appended to the data read 3824** from the file before the buffer is returned. This byte is not included in 3825** the final value of (*pnByte), if applicable. 3826** 3827** NULL is returned if any error is encountered. The final value of *pnByte 3828** is undefined in this case. 3829*/ 3830static char *readFile(const char *zName, int *pnByte){ 3831 FILE *in = fopen(zName, "rb"); 3832 long nIn; 3833 size_t nRead; 3834 char *pBuf; 3835 if( in==0 ) return 0; 3836 fseek(in, 0, SEEK_END); 3837 nIn = ftell(in); 3838 rewind(in); 3839 pBuf = sqlite3_malloc64( nIn+1 ); 3840 if( pBuf==0 ){ fclose(in); return 0; } 3841 nRead = fread(pBuf, nIn, 1, in); 3842 fclose(in); 3843 if( nRead!=1 ){ 3844 sqlite3_free(pBuf); 3845 return 0; 3846 } 3847 pBuf[nIn] = 0; 3848 if( pnByte ) *pnByte = nIn; 3849 return pBuf; 3850} 3851 3852#if defined(SQLITE_ENABLE_SESSION) 3853/* 3854** Close a single OpenSession object and release all of its associated 3855** resources. 3856*/ 3857static void session_close(OpenSession *pSession){ 3858 int i; 3859 sqlite3session_delete(pSession->p); 3860 sqlite3_free(pSession->zName); 3861 for(i=0; i<pSession->nFilter; i++){ 3862 sqlite3_free(pSession->azFilter[i]); 3863 } 3864 sqlite3_free(pSession->azFilter); 3865 memset(pSession, 0, sizeof(OpenSession)); 3866} 3867#endif 3868 3869/* 3870** Close all OpenSession objects and release all associated resources. 3871*/ 3872#if defined(SQLITE_ENABLE_SESSION) 3873static void session_close_all(ShellState *p){ 3874 int i; 3875 for(i=0; i<p->nSession; i++){ 3876 session_close(&p->aSession[i]); 3877 } 3878 p->nSession = 0; 3879} 3880#else 3881# define session_close_all(X) 3882#endif 3883 3884/* 3885** Implementation of the xFilter function for an open session. Omit 3886** any tables named by ".session filter" but let all other table through. 3887*/ 3888#if defined(SQLITE_ENABLE_SESSION) 3889static int session_filter(void *pCtx, const char *zTab){ 3890 OpenSession *pSession = (OpenSession*)pCtx; 3891 int i; 3892 for(i=0; i<pSession->nFilter; i++){ 3893 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 3894 } 3895 return 1; 3896} 3897#endif 3898 3899/* 3900** Try to deduce the type of file for zName based on its content. Return 3901** one of the SHELL_OPEN_* constants. 3902** 3903** If the file does not exist or is empty but its name looks like a ZIP 3904** archive and the dfltZip flag is true, then assume it is a ZIP archive. 3905** Otherwise, assume an ordinary database regardless of the filename if 3906** the type cannot be determined from content. 3907*/ 3908int deduceDatabaseType(const char *zName, int dfltZip){ 3909 FILE *f = fopen(zName, "rb"); 3910 size_t n; 3911 int rc = SHELL_OPEN_UNSPEC; 3912 char zBuf[100]; 3913 if( f==0 ){ 3914 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3915 return SHELL_OPEN_ZIPFILE; 3916 }else{ 3917 return SHELL_OPEN_NORMAL; 3918 } 3919 } 3920 n = fread(zBuf, 16, 1, f); 3921 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 3922 fclose(f); 3923 return SHELL_OPEN_NORMAL; 3924 } 3925 fseek(f, -25, SEEK_END); 3926 n = fread(zBuf, 25, 1, f); 3927 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 3928 rc = SHELL_OPEN_APPENDVFS; 3929 }else{ 3930 fseek(f, -22, SEEK_END); 3931 n = fread(zBuf, 22, 1, f); 3932 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 3933 && zBuf[3]==0x06 ){ 3934 rc = SHELL_OPEN_ZIPFILE; 3935 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3936 rc = SHELL_OPEN_ZIPFILE; 3937 } 3938 } 3939 fclose(f); 3940 return rc; 3941} 3942 3943#ifdef SQLITE_ENABLE_DESERIALIZE 3944/* 3945** Reconstruct an in-memory database using the output from the "dbtotxt" 3946** program. Read content from the file in p->zDbFilename. If p->zDbFilename 3947** is 0, then read from standard input. 3948*/ 3949static unsigned char *readHexDb(ShellState *p, int *pnData){ 3950 unsigned char *a = 0; 3951 int nLine; 3952 int n = 0; 3953 int pgsz = 0; 3954 int iOffset = 0; 3955 int j, k; 3956 int rc; 3957 FILE *in; 3958 unsigned int x[16]; 3959 char zLine[1000]; 3960 if( p->zDbFilename ){ 3961 in = fopen(p->zDbFilename, "r"); 3962 if( in==0 ){ 3963 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename); 3964 return 0; 3965 } 3966 nLine = 0; 3967 }else{ 3968 in = p->in; 3969 nLine = p->lineno; 3970 if( in==0 ) in = stdin; 3971 } 3972 *pnData = 0; 3973 nLine++; 3974 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 3975 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 3976 if( rc!=2 ) goto readHexDb_error; 3977 if( n<0 ) goto readHexDb_error; 3978 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 3979 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 3980 a = sqlite3_malloc( n ? n : 1 ); 3981 if( a==0 ){ 3982 utf8_printf(stderr, "Out of memory!\n"); 3983 goto readHexDb_error; 3984 } 3985 memset(a, 0, n); 3986 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 3987 utf8_printf(stderr, "invalid pagesize\n"); 3988 goto readHexDb_error; 3989 } 3990 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 3991 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 3992 if( rc==2 ){ 3993 iOffset = k; 3994 continue; 3995 } 3996 if( strncmp(zLine, "| end ", 6)==0 ){ 3997 break; 3998 } 3999 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 4000 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 4001 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 4002 if( rc==17 ){ 4003 k = iOffset+j; 4004 if( k+16<=n ){ 4005 int ii; 4006 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 4007 } 4008 } 4009 } 4010 *pnData = n; 4011 if( in!=p->in ){ 4012 fclose(in); 4013 }else{ 4014 p->lineno = nLine; 4015 } 4016 return a; 4017 4018readHexDb_error: 4019 if( in!=p->in ){ 4020 fclose(in); 4021 }else{ 4022 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 4023 nLine++; 4024 if(strncmp(zLine, "| end ", 6)==0 ) break; 4025 } 4026 p->lineno = nLine; 4027 } 4028 sqlite3_free(a); 4029 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 4030 return 0; 4031} 4032#endif /* SQLITE_ENABLE_DESERIALIZE */ 4033 4034/* 4035** Scalar function "shell_int32". The first argument to this function 4036** must be a blob. The second a non-negative integer. This function 4037** reads and returns a 32-bit big-endian integer from byte 4038** offset (4*<arg2>) of the blob. 4039*/ 4040static void shellInt32( 4041 sqlite3_context *context, 4042 int argc, 4043 sqlite3_value **argv 4044){ 4045 const unsigned char *pBlob; 4046 int nBlob; 4047 int iInt; 4048 4049 UNUSED_PARAMETER(argc); 4050 nBlob = sqlite3_value_bytes(argv[0]); 4051 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 4052 iInt = sqlite3_value_int(argv[1]); 4053 4054 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 4055 const unsigned char *a = &pBlob[iInt*4]; 4056 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 4057 + ((sqlite3_int64)a[1]<<16) 4058 + ((sqlite3_int64)a[2]<< 8) 4059 + ((sqlite3_int64)a[3]<< 0); 4060 sqlite3_result_int64(context, iVal); 4061 } 4062} 4063 4064/* 4065** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 4066** using "..." with internal double-quote characters doubled. 4067*/ 4068static void shellIdQuote( 4069 sqlite3_context *context, 4070 int argc, 4071 sqlite3_value **argv 4072){ 4073 const char *zName = (const char*)sqlite3_value_text(argv[0]); 4074 UNUSED_PARAMETER(argc); 4075 if( zName ){ 4076 char *z = sqlite3_mprintf("\"%w\"", zName); 4077 sqlite3_result_text(context, z, -1, sqlite3_free); 4078 } 4079} 4080 4081/* 4082** Scalar function "shell_escape_crnl" used by the .recover command. 4083** The argument passed to this function is the output of built-in 4084** function quote(). If the first character of the input is "'", 4085** indicating that the value passed to quote() was a text value, 4086** then this function searches the input for "\n" and "\r" characters 4087** and adds a wrapper similar to the following: 4088** 4089** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4090** 4091** Or, if the first character of the input is not "'", then a copy 4092** of the input is returned. 4093*/ 4094static void shellEscapeCrnl( 4095 sqlite3_context *context, 4096 int argc, 4097 sqlite3_value **argv 4098){ 4099 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4100 UNUSED_PARAMETER(argc); 4101 if( zText[0]=='\'' ){ 4102 int nText = sqlite3_value_bytes(argv[0]); 4103 int i; 4104 char zBuf1[20]; 4105 char zBuf2[20]; 4106 const char *zNL = 0; 4107 const char *zCR = 0; 4108 int nCR = 0; 4109 int nNL = 0; 4110 4111 for(i=0; zText[i]; i++){ 4112 if( zNL==0 && zText[i]=='\n' ){ 4113 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4114 nNL = (int)strlen(zNL); 4115 } 4116 if( zCR==0 && zText[i]=='\r' ){ 4117 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4118 nCR = (int)strlen(zCR); 4119 } 4120 } 4121 4122 if( zNL || zCR ){ 4123 int iOut = 0; 4124 i64 nMax = (nNL > nCR) ? nNL : nCR; 4125 i64 nAlloc = nMax * nText + (nMax+64)*2; 4126 char *zOut = (char*)sqlite3_malloc64(nAlloc); 4127 if( zOut==0 ){ 4128 sqlite3_result_error_nomem(context); 4129 return; 4130 } 4131 4132 if( zNL && zCR ){ 4133 memcpy(&zOut[iOut], "replace(replace(", 16); 4134 iOut += 16; 4135 }else{ 4136 memcpy(&zOut[iOut], "replace(", 8); 4137 iOut += 8; 4138 } 4139 for(i=0; zText[i]; i++){ 4140 if( zText[i]=='\n' ){ 4141 memcpy(&zOut[iOut], zNL, nNL); 4142 iOut += nNL; 4143 }else if( zText[i]=='\r' ){ 4144 memcpy(&zOut[iOut], zCR, nCR); 4145 iOut += nCR; 4146 }else{ 4147 zOut[iOut] = zText[i]; 4148 iOut++; 4149 } 4150 } 4151 4152 if( zNL ){ 4153 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4154 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 4155 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 4156 } 4157 if( zCR ){ 4158 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 4159 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 4160 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 4161 } 4162 4163 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 4164 sqlite3_free(zOut); 4165 return; 4166 } 4167 } 4168 4169 sqlite3_result_value(context, argv[0]); 4170} 4171 4172/* Flags for open_db(). 4173** 4174** The default behavior of open_db() is to exit(1) if the database fails to 4175** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 4176** but still returns without calling exit. 4177** 4178** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 4179** ZIP archive if the file does not exist or is empty and its name matches 4180** the *.zip pattern. 4181*/ 4182#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 4183#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 4184 4185/* 4186** Make sure the database is open. If it is not, then open it. If 4187** the database fails to open, print an error message and exit. 4188*/ 4189static void open_db(ShellState *p, int openFlags){ 4190 if( p->db==0 ){ 4191 if( p->openMode==SHELL_OPEN_UNSPEC ){ 4192 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){ 4193 p->openMode = SHELL_OPEN_NORMAL; 4194 }else{ 4195 p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 4196 (openFlags & OPEN_DB_ZIPFILE)!=0); 4197 } 4198 } 4199 switch( p->openMode ){ 4200 case SHELL_OPEN_APPENDVFS: { 4201 sqlite3_open_v2(p->zDbFilename, &p->db, 4202 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); 4203 break; 4204 } 4205 case SHELL_OPEN_HEXDB: 4206 case SHELL_OPEN_DESERIALIZE: { 4207 sqlite3_open(0, &p->db); 4208 break; 4209 } 4210 case SHELL_OPEN_ZIPFILE: { 4211 sqlite3_open(":memory:", &p->db); 4212 break; 4213 } 4214 case SHELL_OPEN_READONLY: { 4215 sqlite3_open_v2(p->zDbFilename, &p->db, 4216 SQLITE_OPEN_READONLY|p->openFlags, 0); 4217 break; 4218 } 4219 case SHELL_OPEN_UNSPEC: 4220 case SHELL_OPEN_NORMAL: { 4221 sqlite3_open_v2(p->zDbFilename, &p->db, 4222 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); 4223 break; 4224 } 4225 } 4226 globalDb = p->db; 4227 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 4228 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 4229 p->zDbFilename, sqlite3_errmsg(p->db)); 4230 if( openFlags & OPEN_DB_KEEPALIVE ){ 4231 sqlite3_open(":memory:", &p->db); 4232 return; 4233 } 4234 exit(1); 4235 } 4236#ifndef SQLITE_OMIT_LOAD_EXTENSION 4237 sqlite3_enable_load_extension(p->db, 1); 4238#endif 4239 sqlite3_fileio_init(p->db, 0, 0); 4240 sqlite3_shathree_init(p->db, 0, 0); 4241 sqlite3_completion_init(p->db, 0, 0); 4242#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 4243 sqlite3_dbdata_init(p->db, 0, 0); 4244#endif 4245#ifdef SQLITE_HAVE_ZLIB 4246 sqlite3_zipfile_init(p->db, 0, 0); 4247 sqlite3_sqlar_init(p->db, 0, 0); 4248#endif 4249 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4250 shellAddSchemaName, 0, 0); 4251 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4252 shellModuleSchema, 0, 0); 4253 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4254 shellPutsFunc, 0, 0); 4255 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 4256 shellEscapeCrnl, 0, 0); 4257 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 4258 shellInt32, 0, 0); 4259 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 4260 shellIdQuote, 0, 0); 4261#ifndef SQLITE_NOHAVE_SYSTEM 4262 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4263 editFunc, 0, 0); 4264 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4265 editFunc, 0, 0); 4266#endif 4267 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4268 char *zSql = sqlite3_mprintf( 4269 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); 4270 sqlite3_exec(p->db, zSql, 0, 0, 0); 4271 sqlite3_free(zSql); 4272 } 4273#ifdef SQLITE_ENABLE_DESERIALIZE 4274 else 4275 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4276 int rc; 4277 int nData = 0; 4278 unsigned char *aData; 4279 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4280 aData = (unsigned char*)readFile(p->zDbFilename, &nData); 4281 }else{ 4282 aData = readHexDb(p, &nData); 4283 if( aData==0 ){ 4284 return; 4285 } 4286 } 4287 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4288 SQLITE_DESERIALIZE_RESIZEABLE | 4289 SQLITE_DESERIALIZE_FREEONCLOSE); 4290 if( rc ){ 4291 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4292 } 4293 if( p->szMax>0 ){ 4294 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4295 } 4296 } 4297#endif 4298 } 4299} 4300 4301/* 4302** Attempt to close the databaes connection. Report errors. 4303*/ 4304void close_db(sqlite3 *db){ 4305 int rc = sqlite3_close(db); 4306 if( rc ){ 4307 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4308 rc, sqlite3_errmsg(db)); 4309 } 4310} 4311 4312#if HAVE_READLINE || HAVE_EDITLINE 4313/* 4314** Readline completion callbacks 4315*/ 4316static char *readline_completion_generator(const char *text, int state){ 4317 static sqlite3_stmt *pStmt = 0; 4318 char *zRet; 4319 if( state==0 ){ 4320 char *zSql; 4321 sqlite3_finalize(pStmt); 4322 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4323 " FROM completion(%Q) ORDER BY 1", text); 4324 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4325 sqlite3_free(zSql); 4326 } 4327 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4328 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); 4329 }else{ 4330 sqlite3_finalize(pStmt); 4331 pStmt = 0; 4332 zRet = 0; 4333 } 4334 return zRet; 4335} 4336static char **readline_completion(const char *zText, int iStart, int iEnd){ 4337 rl_attempted_completion_over = 1; 4338 return rl_completion_matches(zText, readline_completion_generator); 4339} 4340 4341#elif HAVE_LINENOISE 4342/* 4343** Linenoise completion callback 4344*/ 4345static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4346 int nLine = strlen30(zLine); 4347 int i, iStart; 4348 sqlite3_stmt *pStmt = 0; 4349 char *zSql; 4350 char zBuf[1000]; 4351 4352 if( nLine>sizeof(zBuf)-30 ) return; 4353 if( zLine[0]=='.' || zLine[0]=='#') return; 4354 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4355 if( i==nLine-1 ) return; 4356 iStart = i+1; 4357 memcpy(zBuf, zLine, iStart); 4358 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4359 " FROM completion(%Q,%Q) ORDER BY 1", 4360 &zLine[iStart], zLine); 4361 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4362 sqlite3_free(zSql); 4363 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4364 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4365 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4366 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4367 if( iStart+nCompletion < sizeof(zBuf)-1 ){ 4368 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4369 linenoiseAddCompletion(lc, zBuf); 4370 } 4371 } 4372 sqlite3_finalize(pStmt); 4373} 4374#endif 4375 4376/* 4377** Do C-language style dequoting. 4378** 4379** \a -> alarm 4380** \b -> backspace 4381** \t -> tab 4382** \n -> newline 4383** \v -> vertical tab 4384** \f -> form feed 4385** \r -> carriage return 4386** \s -> space 4387** \" -> " 4388** \' -> ' 4389** \\ -> backslash 4390** \NNN -> ascii character NNN in octal 4391*/ 4392static void resolve_backslashes(char *z){ 4393 int i, j; 4394 char c; 4395 while( *z && *z!='\\' ) z++; 4396 for(i=j=0; (c = z[i])!=0; i++, j++){ 4397 if( c=='\\' && z[i+1]!=0 ){ 4398 c = z[++i]; 4399 if( c=='a' ){ 4400 c = '\a'; 4401 }else if( c=='b' ){ 4402 c = '\b'; 4403 }else if( c=='t' ){ 4404 c = '\t'; 4405 }else if( c=='n' ){ 4406 c = '\n'; 4407 }else if( c=='v' ){ 4408 c = '\v'; 4409 }else if( c=='f' ){ 4410 c = '\f'; 4411 }else if( c=='r' ){ 4412 c = '\r'; 4413 }else if( c=='"' ){ 4414 c = '"'; 4415 }else if( c=='\'' ){ 4416 c = '\''; 4417 }else if( c=='\\' ){ 4418 c = '\\'; 4419 }else if( c>='0' && c<='7' ){ 4420 c -= '0'; 4421 if( z[i+1]>='0' && z[i+1]<='7' ){ 4422 i++; 4423 c = (c<<3) + z[i] - '0'; 4424 if( z[i+1]>='0' && z[i+1]<='7' ){ 4425 i++; 4426 c = (c<<3) + z[i] - '0'; 4427 } 4428 } 4429 } 4430 } 4431 z[j] = c; 4432 } 4433 if( j<i ) z[j] = 0; 4434} 4435 4436/* 4437** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4438** for TRUE and FALSE. Return the integer value if appropriate. 4439*/ 4440static int booleanValue(const char *zArg){ 4441 int i; 4442 if( zArg[0]=='0' && zArg[1]=='x' ){ 4443 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4444 }else{ 4445 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4446 } 4447 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4448 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4449 return 1; 4450 } 4451 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4452 return 0; 4453 } 4454 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4455 zArg); 4456 return 0; 4457} 4458 4459/* 4460** Set or clear a shell flag according to a boolean value. 4461*/ 4462static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4463 if( booleanValue(zArg) ){ 4464 ShellSetFlag(p, mFlag); 4465 }else{ 4466 ShellClearFlag(p, mFlag); 4467 } 4468} 4469 4470/* 4471** Close an output file, assuming it is not stderr or stdout 4472*/ 4473static void output_file_close(FILE *f){ 4474 if( f && f!=stdout && f!=stderr ) fclose(f); 4475} 4476 4477/* 4478** Try to open an output file. The names "stdout" and "stderr" are 4479** recognized and do the right thing. NULL is returned if the output 4480** filename is "off". 4481*/ 4482static FILE *output_file_open(const char *zFile, int bTextMode){ 4483 FILE *f; 4484 if( strcmp(zFile,"stdout")==0 ){ 4485 f = stdout; 4486 }else if( strcmp(zFile, "stderr")==0 ){ 4487 f = stderr; 4488 }else if( strcmp(zFile, "off")==0 ){ 4489 f = 0; 4490 }else{ 4491 f = fopen(zFile, bTextMode ? "w" : "wb"); 4492 if( f==0 ){ 4493 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 4494 } 4495 } 4496 return f; 4497} 4498 4499#ifndef SQLITE_OMIT_TRACE 4500/* 4501** A routine for handling output from sqlite3_trace(). 4502*/ 4503static int sql_trace_callback( 4504 unsigned mType, /* The trace type */ 4505 void *pArg, /* The ShellState pointer */ 4506 void *pP, /* Usually a pointer to sqlite_stmt */ 4507 void *pX /* Auxiliary output */ 4508){ 4509 ShellState *p = (ShellState*)pArg; 4510 sqlite3_stmt *pStmt; 4511 const char *zSql; 4512 int nSql; 4513 if( p->traceOut==0 ) return 0; 4514 if( mType==SQLITE_TRACE_CLOSE ){ 4515 utf8_printf(p->traceOut, "-- closing database connection\n"); 4516 return 0; 4517 } 4518 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 4519 zSql = (const char*)pX; 4520 }else{ 4521 pStmt = (sqlite3_stmt*)pP; 4522 switch( p->eTraceType ){ 4523 case SHELL_TRACE_EXPANDED: { 4524 zSql = sqlite3_expanded_sql(pStmt); 4525 break; 4526 } 4527#ifdef SQLITE_ENABLE_NORMALIZE 4528 case SHELL_TRACE_NORMALIZED: { 4529 zSql = sqlite3_normalized_sql(pStmt); 4530 break; 4531 } 4532#endif 4533 default: { 4534 zSql = sqlite3_sql(pStmt); 4535 break; 4536 } 4537 } 4538 } 4539 if( zSql==0 ) return 0; 4540 nSql = strlen30(zSql); 4541 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 4542 switch( mType ){ 4543 case SQLITE_TRACE_ROW: 4544 case SQLITE_TRACE_STMT: { 4545 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 4546 break; 4547 } 4548 case SQLITE_TRACE_PROFILE: { 4549 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 4550 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 4551 break; 4552 } 4553 } 4554 return 0; 4555} 4556#endif 4557 4558/* 4559** A no-op routine that runs with the ".breakpoint" doc-command. This is 4560** a useful spot to set a debugger breakpoint. 4561*/ 4562static void test_breakpoint(void){ 4563 static int nCall = 0; 4564 nCall++; 4565} 4566 4567/* 4568** An object used to read a CSV and other files for import. 4569*/ 4570typedef struct ImportCtx ImportCtx; 4571struct ImportCtx { 4572 const char *zFile; /* Name of the input file */ 4573 FILE *in; /* Read the CSV text from this input stream */ 4574 char *z; /* Accumulated text for a field */ 4575 int n; /* Number of bytes in z */ 4576 int nAlloc; /* Space allocated for z[] */ 4577 int nLine; /* Current line number */ 4578 int nRow; /* Number of rows imported */ 4579 int nErr; /* Number of errors encountered */ 4580 int bNotFirst; /* True if one or more bytes already read */ 4581 int cTerm; /* Character that terminated the most recent field */ 4582 int cColSep; /* The column separator character. (Usually ",") */ 4583 int cRowSep; /* The row separator character. (Usually "\n") */ 4584}; 4585 4586/* Append a single byte to z[] */ 4587static void import_append_char(ImportCtx *p, int c){ 4588 if( p->n+1>=p->nAlloc ){ 4589 p->nAlloc += p->nAlloc + 100; 4590 p->z = sqlite3_realloc64(p->z, p->nAlloc); 4591 if( p->z==0 ) shell_out_of_memory(); 4592 } 4593 p->z[p->n++] = (char)c; 4594} 4595 4596/* Read a single field of CSV text. Compatible with rfc4180 and extended 4597** with the option of having a separator other than ",". 4598** 4599** + Input comes from p->in. 4600** + Store results in p->z of length p->n. Space to hold p->z comes 4601** from sqlite3_malloc64(). 4602** + Use p->cSep as the column separator. The default is ",". 4603** + Use p->rSep as the row separator. The default is "\n". 4604** + Keep track of the line number in p->nLine. 4605** + Store the character that terminates the field in p->cTerm. Store 4606** EOF on end-of-file. 4607** + Report syntax errors on stderr 4608*/ 4609static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 4610 int c; 4611 int cSep = p->cColSep; 4612 int rSep = p->cRowSep; 4613 p->n = 0; 4614 c = fgetc(p->in); 4615 if( c==EOF || seenInterrupt ){ 4616 p->cTerm = EOF; 4617 return 0; 4618 } 4619 if( c=='"' ){ 4620 int pc, ppc; 4621 int startLine = p->nLine; 4622 int cQuote = c; 4623 pc = ppc = 0; 4624 while( 1 ){ 4625 c = fgetc(p->in); 4626 if( c==rSep ) p->nLine++; 4627 if( c==cQuote ){ 4628 if( pc==cQuote ){ 4629 pc = 0; 4630 continue; 4631 } 4632 } 4633 if( (c==cSep && pc==cQuote) 4634 || (c==rSep && pc==cQuote) 4635 || (c==rSep && pc=='\r' && ppc==cQuote) 4636 || (c==EOF && pc==cQuote) 4637 ){ 4638 do{ p->n--; }while( p->z[p->n]!=cQuote ); 4639 p->cTerm = c; 4640 break; 4641 } 4642 if( pc==cQuote && c!='\r' ){ 4643 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 4644 p->zFile, p->nLine, cQuote); 4645 } 4646 if( c==EOF ){ 4647 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 4648 p->zFile, startLine, cQuote); 4649 p->cTerm = c; 4650 break; 4651 } 4652 import_append_char(p, c); 4653 ppc = pc; 4654 pc = c; 4655 } 4656 }else{ 4657 /* If this is the first field being parsed and it begins with the 4658 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 4659 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 4660 import_append_char(p, c); 4661 c = fgetc(p->in); 4662 if( (c&0xff)==0xbb ){ 4663 import_append_char(p, c); 4664 c = fgetc(p->in); 4665 if( (c&0xff)==0xbf ){ 4666 p->bNotFirst = 1; 4667 p->n = 0; 4668 return csv_read_one_field(p); 4669 } 4670 } 4671 } 4672 while( c!=EOF && c!=cSep && c!=rSep ){ 4673 import_append_char(p, c); 4674 c = fgetc(p->in); 4675 } 4676 if( c==rSep ){ 4677 p->nLine++; 4678 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 4679 } 4680 p->cTerm = c; 4681 } 4682 if( p->z ) p->z[p->n] = 0; 4683 p->bNotFirst = 1; 4684 return p->z; 4685} 4686 4687/* Read a single field of ASCII delimited text. 4688** 4689** + Input comes from p->in. 4690** + Store results in p->z of length p->n. Space to hold p->z comes 4691** from sqlite3_malloc64(). 4692** + Use p->cSep as the column separator. The default is "\x1F". 4693** + Use p->rSep as the row separator. The default is "\x1E". 4694** + Keep track of the row number in p->nLine. 4695** + Store the character that terminates the field in p->cTerm. Store 4696** EOF on end-of-file. 4697** + Report syntax errors on stderr 4698*/ 4699static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 4700 int c; 4701 int cSep = p->cColSep; 4702 int rSep = p->cRowSep; 4703 p->n = 0; 4704 c = fgetc(p->in); 4705 if( c==EOF || seenInterrupt ){ 4706 p->cTerm = EOF; 4707 return 0; 4708 } 4709 while( c!=EOF && c!=cSep && c!=rSep ){ 4710 import_append_char(p, c); 4711 c = fgetc(p->in); 4712 } 4713 if( c==rSep ){ 4714 p->nLine++; 4715 } 4716 p->cTerm = c; 4717 if( p->z ) p->z[p->n] = 0; 4718 return p->z; 4719} 4720 4721/* 4722** Try to transfer data for table zTable. If an error is seen while 4723** moving forward, try to go backwards. The backwards movement won't 4724** work for WITHOUT ROWID tables. 4725*/ 4726static void tryToCloneData( 4727 ShellState *p, 4728 sqlite3 *newDb, 4729 const char *zTable 4730){ 4731 sqlite3_stmt *pQuery = 0; 4732 sqlite3_stmt *pInsert = 0; 4733 char *zQuery = 0; 4734 char *zInsert = 0; 4735 int rc; 4736 int i, j, n; 4737 int nTable = strlen30(zTable); 4738 int k = 0; 4739 int cnt = 0; 4740 const int spinRate = 10000; 4741 4742 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 4743 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4744 if( rc ){ 4745 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4746 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4747 zQuery); 4748 goto end_data_xfer; 4749 } 4750 n = sqlite3_column_count(pQuery); 4751 zInsert = sqlite3_malloc64(200 + nTable + n*3); 4752 if( zInsert==0 ) shell_out_of_memory(); 4753 sqlite3_snprintf(200+nTable,zInsert, 4754 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 4755 i = strlen30(zInsert); 4756 for(j=1; j<n; j++){ 4757 memcpy(zInsert+i, ",?", 2); 4758 i += 2; 4759 } 4760 memcpy(zInsert+i, ");", 3); 4761 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 4762 if( rc ){ 4763 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4764 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 4765 zQuery); 4766 goto end_data_xfer; 4767 } 4768 for(k=0; k<2; k++){ 4769 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4770 for(i=0; i<n; i++){ 4771 switch( sqlite3_column_type(pQuery, i) ){ 4772 case SQLITE_NULL: { 4773 sqlite3_bind_null(pInsert, i+1); 4774 break; 4775 } 4776 case SQLITE_INTEGER: { 4777 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 4778 break; 4779 } 4780 case SQLITE_FLOAT: { 4781 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 4782 break; 4783 } 4784 case SQLITE_TEXT: { 4785 sqlite3_bind_text(pInsert, i+1, 4786 (const char*)sqlite3_column_text(pQuery,i), 4787 -1, SQLITE_STATIC); 4788 break; 4789 } 4790 case SQLITE_BLOB: { 4791 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 4792 sqlite3_column_bytes(pQuery,i), 4793 SQLITE_STATIC); 4794 break; 4795 } 4796 } 4797 } /* End for */ 4798 rc = sqlite3_step(pInsert); 4799 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 4800 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 4801 sqlite3_errmsg(newDb)); 4802 } 4803 sqlite3_reset(pInsert); 4804 cnt++; 4805 if( (cnt%spinRate)==0 ){ 4806 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 4807 fflush(stdout); 4808 } 4809 } /* End while */ 4810 if( rc==SQLITE_DONE ) break; 4811 sqlite3_finalize(pQuery); 4812 sqlite3_free(zQuery); 4813 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 4814 zTable); 4815 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4816 if( rc ){ 4817 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 4818 break; 4819 } 4820 } /* End for(k=0...) */ 4821 4822end_data_xfer: 4823 sqlite3_finalize(pQuery); 4824 sqlite3_finalize(pInsert); 4825 sqlite3_free(zQuery); 4826 sqlite3_free(zInsert); 4827} 4828 4829 4830/* 4831** Try to transfer all rows of the schema that match zWhere. For 4832** each row, invoke xForEach() on the object defined by that row. 4833** If an error is encountered while moving forward through the 4834** sqlite_master table, try again moving backwards. 4835*/ 4836static void tryToCloneSchema( 4837 ShellState *p, 4838 sqlite3 *newDb, 4839 const char *zWhere, 4840 void (*xForEach)(ShellState*,sqlite3*,const char*) 4841){ 4842 sqlite3_stmt *pQuery = 0; 4843 char *zQuery = 0; 4844 int rc; 4845 const unsigned char *zName; 4846 const unsigned char *zSql; 4847 char *zErrMsg = 0; 4848 4849 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4850 " WHERE %s", zWhere); 4851 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4852 if( rc ){ 4853 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4854 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4855 zQuery); 4856 goto end_schema_xfer; 4857 } 4858 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4859 zName = sqlite3_column_text(pQuery, 0); 4860 zSql = sqlite3_column_text(pQuery, 1); 4861 printf("%s... ", zName); fflush(stdout); 4862 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4863 if( zErrMsg ){ 4864 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4865 sqlite3_free(zErrMsg); 4866 zErrMsg = 0; 4867 } 4868 if( xForEach ){ 4869 xForEach(p, newDb, (const char*)zName); 4870 } 4871 printf("done\n"); 4872 } 4873 if( rc!=SQLITE_DONE ){ 4874 sqlite3_finalize(pQuery); 4875 sqlite3_free(zQuery); 4876 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4877 " WHERE %s ORDER BY rowid DESC", zWhere); 4878 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4879 if( rc ){ 4880 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4881 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4882 zQuery); 4883 goto end_schema_xfer; 4884 } 4885 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4886 zName = sqlite3_column_text(pQuery, 0); 4887 zSql = sqlite3_column_text(pQuery, 1); 4888 printf("%s... ", zName); fflush(stdout); 4889 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4890 if( zErrMsg ){ 4891 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4892 sqlite3_free(zErrMsg); 4893 zErrMsg = 0; 4894 } 4895 if( xForEach ){ 4896 xForEach(p, newDb, (const char*)zName); 4897 } 4898 printf("done\n"); 4899 } 4900 } 4901end_schema_xfer: 4902 sqlite3_finalize(pQuery); 4903 sqlite3_free(zQuery); 4904} 4905 4906/* 4907** Open a new database file named "zNewDb". Try to recover as much information 4908** as possible out of the main database (which might be corrupt) and write it 4909** into zNewDb. 4910*/ 4911static void tryToClone(ShellState *p, const char *zNewDb){ 4912 int rc; 4913 sqlite3 *newDb = 0; 4914 if( access(zNewDb,0)==0 ){ 4915 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 4916 return; 4917 } 4918 rc = sqlite3_open(zNewDb, &newDb); 4919 if( rc ){ 4920 utf8_printf(stderr, "Cannot create output database: %s\n", 4921 sqlite3_errmsg(newDb)); 4922 }else{ 4923 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 4924 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 4925 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 4926 tryToCloneSchema(p, newDb, "type!='table'", 0); 4927 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 4928 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 4929 } 4930 close_db(newDb); 4931} 4932 4933/* 4934** Change the output file back to stdout. 4935** 4936** If the p->doXdgOpen flag is set, that means the output was being 4937** redirected to a temporary file named by p->zTempFile. In that case, 4938** launch start/open/xdg-open on that temporary file. 4939*/ 4940static void output_reset(ShellState *p){ 4941 if( p->outfile[0]=='|' ){ 4942#ifndef SQLITE_OMIT_POPEN 4943 pclose(p->out); 4944#endif 4945 }else{ 4946 output_file_close(p->out); 4947#ifndef SQLITE_NOHAVE_SYSTEM 4948 if( p->doXdgOpen ){ 4949 const char *zXdgOpenCmd = 4950#if defined(_WIN32) 4951 "start"; 4952#elif defined(__APPLE__) 4953 "open"; 4954#else 4955 "xdg-open"; 4956#endif 4957 char *zCmd; 4958 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 4959 if( system(zCmd) ){ 4960 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 4961 } 4962 sqlite3_free(zCmd); 4963 outputModePop(p); 4964 p->doXdgOpen = 0; 4965 sqlite3_sleep(100); 4966 } 4967#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 4968 } 4969 p->outfile[0] = 0; 4970 p->out = stdout; 4971} 4972 4973/* 4974** Run an SQL command and return the single integer result. 4975*/ 4976static int db_int(ShellState *p, const char *zSql){ 4977 sqlite3_stmt *pStmt; 4978 int res = 0; 4979 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4980 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 4981 res = sqlite3_column_int(pStmt,0); 4982 } 4983 sqlite3_finalize(pStmt); 4984 return res; 4985} 4986 4987/* 4988** Convert a 2-byte or 4-byte big-endian integer into a native integer 4989*/ 4990static unsigned int get2byteInt(unsigned char *a){ 4991 return (a[0]<<8) + a[1]; 4992} 4993static unsigned int get4byteInt(unsigned char *a){ 4994 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 4995} 4996 4997/* 4998** Implementation of the ".dbinfo" command. 4999** 5000** Return 1 on error, 2 to exit, and 0 otherwise. 5001*/ 5002static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 5003 static const struct { const char *zName; int ofst; } aField[] = { 5004 { "file change counter:", 24 }, 5005 { "database page count:", 28 }, 5006 { "freelist page count:", 36 }, 5007 { "schema cookie:", 40 }, 5008 { "schema format:", 44 }, 5009 { "default cache size:", 48 }, 5010 { "autovacuum top root:", 52 }, 5011 { "incremental vacuum:", 64 }, 5012 { "text encoding:", 56 }, 5013 { "user version:", 60 }, 5014 { "application id:", 68 }, 5015 { "software version:", 96 }, 5016 }; 5017 static const struct { const char *zName; const char *zSql; } aQuery[] = { 5018 { "number of tables:", 5019 "SELECT count(*) FROM %s WHERE type='table'" }, 5020 { "number of indexes:", 5021 "SELECT count(*) FROM %s WHERE type='index'" }, 5022 { "number of triggers:", 5023 "SELECT count(*) FROM %s WHERE type='trigger'" }, 5024 { "number of views:", 5025 "SELECT count(*) FROM %s WHERE type='view'" }, 5026 { "schema size:", 5027 "SELECT total(length(sql)) FROM %s" }, 5028 }; 5029 int i, rc; 5030 unsigned iDataVersion; 5031 char *zSchemaTab; 5032 char *zDb = nArg>=2 ? azArg[1] : "main"; 5033 sqlite3_stmt *pStmt = 0; 5034 unsigned char aHdr[100]; 5035 open_db(p, 0); 5036 if( p->db==0 ) return 1; 5037 rc = sqlite3_prepare_v2(p->db, 5038 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 5039 -1, &pStmt, 0); 5040 if( rc ){ 5041 if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){ 5042 utf8_printf(stderr, "the \".dbinfo\" command requires the " 5043 "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n"); 5044 }else{ 5045 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 5046 } 5047 sqlite3_finalize(pStmt); 5048 return 1; 5049 } 5050 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 5051 if( sqlite3_step(pStmt)==SQLITE_ROW 5052 && sqlite3_column_bytes(pStmt,0)>100 5053 ){ 5054 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 5055 sqlite3_finalize(pStmt); 5056 }else{ 5057 raw_printf(stderr, "unable to read database header\n"); 5058 sqlite3_finalize(pStmt); 5059 return 1; 5060 } 5061 i = get2byteInt(aHdr+16); 5062 if( i==1 ) i = 65536; 5063 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 5064 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 5065 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 5066 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 5067 for(i=0; i<ArraySize(aField); i++){ 5068 int ofst = aField[i].ofst; 5069 unsigned int val = get4byteInt(aHdr + ofst); 5070 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 5071 switch( ofst ){ 5072 case 56: { 5073 if( val==1 ) raw_printf(p->out, " (utf8)"); 5074 if( val==2 ) raw_printf(p->out, " (utf16le)"); 5075 if( val==3 ) raw_printf(p->out, " (utf16be)"); 5076 } 5077 } 5078 raw_printf(p->out, "\n"); 5079 } 5080 if( zDb==0 ){ 5081 zSchemaTab = sqlite3_mprintf("main.sqlite_master"); 5082 }else if( strcmp(zDb,"temp")==0 ){ 5083 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); 5084 }else{ 5085 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); 5086 } 5087 for(i=0; i<ArraySize(aQuery); i++){ 5088 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 5089 int val = db_int(p, zSql); 5090 sqlite3_free(zSql); 5091 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 5092 } 5093 sqlite3_free(zSchemaTab); 5094 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 5095 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 5096 return 0; 5097} 5098 5099/* 5100** Print the current sqlite3_errmsg() value to stderr and return 1. 5101*/ 5102static int shellDatabaseError(sqlite3 *db){ 5103 const char *zErr = sqlite3_errmsg(db); 5104 utf8_printf(stderr, "Error: %s\n", zErr); 5105 return 1; 5106} 5107 5108/* 5109** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 5110** if they match and FALSE (0) if they do not match. 5111** 5112** Globbing rules: 5113** 5114** '*' Matches any sequence of zero or more characters. 5115** 5116** '?' Matches exactly one character. 5117** 5118** [...] Matches one character from the enclosed list of 5119** characters. 5120** 5121** [^...] Matches one character not in the enclosed list. 5122** 5123** '#' Matches any sequence of one or more digits with an 5124** optional + or - sign in front 5125** 5126** ' ' Any span of whitespace matches any other span of 5127** whitespace. 5128** 5129** Extra whitespace at the end of z[] is ignored. 5130*/ 5131static int testcase_glob(const char *zGlob, const char *z){ 5132 int c, c2; 5133 int invert; 5134 int seen; 5135 5136 while( (c = (*(zGlob++)))!=0 ){ 5137 if( IsSpace(c) ){ 5138 if( !IsSpace(*z) ) return 0; 5139 while( IsSpace(*zGlob) ) zGlob++; 5140 while( IsSpace(*z) ) z++; 5141 }else if( c=='*' ){ 5142 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 5143 if( c=='?' && (*(z++))==0 ) return 0; 5144 } 5145 if( c==0 ){ 5146 return 1; 5147 }else if( c=='[' ){ 5148 while( *z && testcase_glob(zGlob-1,z)==0 ){ 5149 z++; 5150 } 5151 return (*z)!=0; 5152 } 5153 while( (c2 = (*(z++)))!=0 ){ 5154 while( c2!=c ){ 5155 c2 = *(z++); 5156 if( c2==0 ) return 0; 5157 } 5158 if( testcase_glob(zGlob,z) ) return 1; 5159 } 5160 return 0; 5161 }else if( c=='?' ){ 5162 if( (*(z++))==0 ) return 0; 5163 }else if( c=='[' ){ 5164 int prior_c = 0; 5165 seen = 0; 5166 invert = 0; 5167 c = *(z++); 5168 if( c==0 ) return 0; 5169 c2 = *(zGlob++); 5170 if( c2=='^' ){ 5171 invert = 1; 5172 c2 = *(zGlob++); 5173 } 5174 if( c2==']' ){ 5175 if( c==']' ) seen = 1; 5176 c2 = *(zGlob++); 5177 } 5178 while( c2 && c2!=']' ){ 5179 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 5180 c2 = *(zGlob++); 5181 if( c>=prior_c && c<=c2 ) seen = 1; 5182 prior_c = 0; 5183 }else{ 5184 if( c==c2 ){ 5185 seen = 1; 5186 } 5187 prior_c = c2; 5188 } 5189 c2 = *(zGlob++); 5190 } 5191 if( c2==0 || (seen ^ invert)==0 ) return 0; 5192 }else if( c=='#' ){ 5193 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 5194 if( !IsDigit(z[0]) ) return 0; 5195 z++; 5196 while( IsDigit(z[0]) ){ z++; } 5197 }else{ 5198 if( c!=(*(z++)) ) return 0; 5199 } 5200 } 5201 while( IsSpace(*z) ){ z++; } 5202 return *z==0; 5203} 5204 5205 5206/* 5207** Compare the string as a command-line option with either one or two 5208** initial "-" characters. 5209*/ 5210static int optionMatch(const char *zStr, const char *zOpt){ 5211 if( zStr[0]!='-' ) return 0; 5212 zStr++; 5213 if( zStr[0]=='-' ) zStr++; 5214 return strcmp(zStr, zOpt)==0; 5215} 5216 5217/* 5218** Delete a file. 5219*/ 5220int shellDeleteFile(const char *zFilename){ 5221 int rc; 5222#ifdef _WIN32 5223 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 5224 rc = _wunlink(z); 5225 sqlite3_free(z); 5226#else 5227 rc = unlink(zFilename); 5228#endif 5229 return rc; 5230} 5231 5232/* 5233** Try to delete the temporary file (if there is one) and free the 5234** memory used to hold the name of the temp file. 5235*/ 5236static void clearTempFile(ShellState *p){ 5237 if( p->zTempFile==0 ) return; 5238 if( p->doXdgOpen ) return; 5239 if( shellDeleteFile(p->zTempFile) ) return; 5240 sqlite3_free(p->zTempFile); 5241 p->zTempFile = 0; 5242} 5243 5244/* 5245** Create a new temp file name with the given suffix. 5246*/ 5247static void newTempFile(ShellState *p, const char *zSuffix){ 5248 clearTempFile(p); 5249 sqlite3_free(p->zTempFile); 5250 p->zTempFile = 0; 5251 if( p->db ){ 5252 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 5253 } 5254 if( p->zTempFile==0 ){ 5255 sqlite3_uint64 r; 5256 sqlite3_randomness(sizeof(r), &r); 5257 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix); 5258 }else{ 5259 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 5260 } 5261 if( p->zTempFile==0 ){ 5262 raw_printf(stderr, "out of memory\n"); 5263 exit(1); 5264 } 5265} 5266 5267 5268/* 5269** The implementation of SQL scalar function fkey_collate_clause(), used 5270** by the ".lint fkey-indexes" command. This scalar function is always 5271** called with four arguments - the parent table name, the parent column name, 5272** the child table name and the child column name. 5273** 5274** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5275** 5276** If either of the named tables or columns do not exist, this function 5277** returns an empty string. An empty string is also returned if both tables 5278** and columns exist but have the same default collation sequence. Or, 5279** if both exist but the default collation sequences are different, this 5280** function returns the string " COLLATE <parent-collation>", where 5281** <parent-collation> is the default collation sequence of the parent column. 5282*/ 5283static void shellFkeyCollateClause( 5284 sqlite3_context *pCtx, 5285 int nVal, 5286 sqlite3_value **apVal 5287){ 5288 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5289 const char *zParent; 5290 const char *zParentCol; 5291 const char *zParentSeq; 5292 const char *zChild; 5293 const char *zChildCol; 5294 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5295 int rc; 5296 5297 assert( nVal==4 ); 5298 zParent = (const char*)sqlite3_value_text(apVal[0]); 5299 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5300 zChild = (const char*)sqlite3_value_text(apVal[2]); 5301 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5302 5303 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5304 rc = sqlite3_table_column_metadata( 5305 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5306 ); 5307 if( rc==SQLITE_OK ){ 5308 rc = sqlite3_table_column_metadata( 5309 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5310 ); 5311 } 5312 5313 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5314 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5315 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5316 sqlite3_free(z); 5317 } 5318} 5319 5320 5321/* 5322** The implementation of dot-command ".lint fkey-indexes". 5323*/ 5324static int lintFkeyIndexes( 5325 ShellState *pState, /* Current shell tool state */ 5326 char **azArg, /* Array of arguments passed to dot command */ 5327 int nArg /* Number of entries in azArg[] */ 5328){ 5329 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5330 FILE *out = pState->out; /* Stream to write non-error output to */ 5331 int bVerbose = 0; /* If -verbose is present */ 5332 int bGroupByParent = 0; /* If -groupbyparent is present */ 5333 int i; /* To iterate through azArg[] */ 5334 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5335 int rc; /* Return code */ 5336 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5337 5338 /* 5339 ** This SELECT statement returns one row for each foreign key constraint 5340 ** in the schema of the main database. The column values are: 5341 ** 5342 ** 0. The text of an SQL statement similar to: 5343 ** 5344 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5345 ** 5346 ** This SELECT is similar to the one that the foreign keys implementation 5347 ** needs to run internally on child tables. If there is an index that can 5348 ** be used to optimize this query, then it can also be used by the FK 5349 ** implementation to optimize DELETE or UPDATE statements on the parent 5350 ** table. 5351 ** 5352 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5353 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5354 ** contains an index that can be used to optimize the query. 5355 ** 5356 ** 2. Human readable text that describes the child table and columns. e.g. 5357 ** 5358 ** "child_table(child_key1, child_key2)" 5359 ** 5360 ** 3. Human readable text that describes the parent table and columns. e.g. 5361 ** 5362 ** "parent_table(parent_key1, parent_key2)" 5363 ** 5364 ** 4. A full CREATE INDEX statement for an index that could be used to 5365 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5366 ** 5367 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5368 ** 5369 ** 5. The name of the parent table. 5370 ** 5371 ** These six values are used by the C logic below to generate the report. 5372 */ 5373 const char *zSql = 5374 "SELECT " 5375 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5376 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5377 " || fkey_collate_clause(" 5378 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5379 ", " 5380 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" 5381 " || group_concat('*=?', ' AND ') || ')'" 5382 ", " 5383 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5384 ", " 5385 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5386 ", " 5387 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5388 " || ' ON ' || quote(s.name) || '('" 5389 " || group_concat(quote(f.[from]) ||" 5390 " fkey_collate_clause(" 5391 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5392 " || ');'" 5393 ", " 5394 " f.[table] " 5395 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f " 5396 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5397 "GROUP BY s.name, f.id " 5398 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5399 ; 5400 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; 5401 5402 for(i=2; i<nArg; i++){ 5403 int n = strlen30(azArg[i]); 5404 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5405 bVerbose = 1; 5406 } 5407 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5408 bGroupByParent = 1; 5409 zIndent = " "; 5410 } 5411 else{ 5412 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5413 azArg[0], azArg[1] 5414 ); 5415 return SQLITE_ERROR; 5416 } 5417 } 5418 5419 /* Register the fkey_collate_clause() SQL function */ 5420 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5421 0, shellFkeyCollateClause, 0, 0 5422 ); 5423 5424 5425 if( rc==SQLITE_OK ){ 5426 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5427 } 5428 if( rc==SQLITE_OK ){ 5429 sqlite3_bind_int(pSql, 1, bGroupByParent); 5430 } 5431 5432 if( rc==SQLITE_OK ){ 5433 int rc2; 5434 char *zPrev = 0; 5435 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5436 int res = -1; 5437 sqlite3_stmt *pExplain = 0; 5438 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5439 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 5440 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 5441 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 5442 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 5443 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 5444 5445 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 5446 if( rc!=SQLITE_OK ) break; 5447 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 5448 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 5449 res = ( 5450 0==sqlite3_strglob(zGlob, zPlan) 5451 || 0==sqlite3_strglob(zGlobIPK, zPlan) 5452 ); 5453 } 5454 rc = sqlite3_finalize(pExplain); 5455 if( rc!=SQLITE_OK ) break; 5456 5457 if( res<0 ){ 5458 raw_printf(stderr, "Error: internal error"); 5459 break; 5460 }else{ 5461 if( bGroupByParent 5462 && (bVerbose || res==0) 5463 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 5464 ){ 5465 raw_printf(out, "-- Parent table %s\n", zParent); 5466 sqlite3_free(zPrev); 5467 zPrev = sqlite3_mprintf("%s", zParent); 5468 } 5469 5470 if( res==0 ){ 5471 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 5472 }else if( bVerbose ){ 5473 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 5474 zIndent, zFrom, zTarget 5475 ); 5476 } 5477 } 5478 } 5479 sqlite3_free(zPrev); 5480 5481 if( rc!=SQLITE_OK ){ 5482 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5483 } 5484 5485 rc2 = sqlite3_finalize(pSql); 5486 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 5487 rc = rc2; 5488 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5489 } 5490 }else{ 5491 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5492 } 5493 5494 return rc; 5495} 5496 5497/* 5498** Implementation of ".lint" dot command. 5499*/ 5500static int lintDotCommand( 5501 ShellState *pState, /* Current shell tool state */ 5502 char **azArg, /* Array of arguments passed to dot command */ 5503 int nArg /* Number of entries in azArg[] */ 5504){ 5505 int n; 5506 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 5507 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 5508 return lintFkeyIndexes(pState, azArg, nArg); 5509 5510 usage: 5511 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 5512 raw_printf(stderr, "Where sub-commands are:\n"); 5513 raw_printf(stderr, " fkey-indexes\n"); 5514 return SQLITE_ERROR; 5515} 5516 5517#if !defined SQLITE_OMIT_VIRTUALTABLE 5518static void shellPrepare( 5519 sqlite3 *db, 5520 int *pRc, 5521 const char *zSql, 5522 sqlite3_stmt **ppStmt 5523){ 5524 *ppStmt = 0; 5525 if( *pRc==SQLITE_OK ){ 5526 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 5527 if( rc!=SQLITE_OK ){ 5528 raw_printf(stderr, "sql error: %s (%d)\n", 5529 sqlite3_errmsg(db), sqlite3_errcode(db) 5530 ); 5531 *pRc = rc; 5532 } 5533 } 5534} 5535 5536/* 5537** Create a prepared statement using printf-style arguments for the SQL. 5538** 5539** This routine is could be marked "static". But it is not always used, 5540** depending on compile-time options. By omitting the "static", we avoid 5541** nuisance compiler warnings about "defined but not used". 5542*/ 5543void shellPreparePrintf( 5544 sqlite3 *db, 5545 int *pRc, 5546 sqlite3_stmt **ppStmt, 5547 const char *zFmt, 5548 ... 5549){ 5550 *ppStmt = 0; 5551 if( *pRc==SQLITE_OK ){ 5552 va_list ap; 5553 char *z; 5554 va_start(ap, zFmt); 5555 z = sqlite3_vmprintf(zFmt, ap); 5556 va_end(ap); 5557 if( z==0 ){ 5558 *pRc = SQLITE_NOMEM; 5559 }else{ 5560 shellPrepare(db, pRc, z, ppStmt); 5561 sqlite3_free(z); 5562 } 5563 } 5564} 5565 5566/* Finalize the prepared statement created using shellPreparePrintf(). 5567** 5568** This routine is could be marked "static". But it is not always used, 5569** depending on compile-time options. By omitting the "static", we avoid 5570** nuisance compiler warnings about "defined but not used". 5571*/ 5572void shellFinalize( 5573 int *pRc, 5574 sqlite3_stmt *pStmt 5575){ 5576 if( pStmt ){ 5577 sqlite3 *db = sqlite3_db_handle(pStmt); 5578 int rc = sqlite3_finalize(pStmt); 5579 if( *pRc==SQLITE_OK ){ 5580 if( rc!=SQLITE_OK ){ 5581 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5582 } 5583 *pRc = rc; 5584 } 5585 } 5586} 5587 5588/* Reset the prepared statement created using shellPreparePrintf(). 5589** 5590** This routine is could be marked "static". But it is not always used, 5591** depending on compile-time options. By omitting the "static", we avoid 5592** nuisance compiler warnings about "defined but not used". 5593*/ 5594void shellReset( 5595 int *pRc, 5596 sqlite3_stmt *pStmt 5597){ 5598 int rc = sqlite3_reset(pStmt); 5599 if( *pRc==SQLITE_OK ){ 5600 if( rc!=SQLITE_OK ){ 5601 sqlite3 *db = sqlite3_db_handle(pStmt); 5602 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5603 } 5604 *pRc = rc; 5605 } 5606} 5607#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 5608 5609#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 5610/****************************************************************************** 5611** The ".archive" or ".ar" command. 5612*/ 5613/* 5614** Structure representing a single ".ar" command. 5615*/ 5616typedef struct ArCommand ArCommand; 5617struct ArCommand { 5618 u8 eCmd; /* An AR_CMD_* value */ 5619 u8 bVerbose; /* True if --verbose */ 5620 u8 bZip; /* True if the archive is a ZIP */ 5621 u8 bDryRun; /* True if --dry-run */ 5622 u8 bAppend; /* True if --append */ 5623 u8 fromCmdLine; /* Run from -A instead of .archive */ 5624 int nArg; /* Number of command arguments */ 5625 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 5626 const char *zFile; /* --file argument, or NULL */ 5627 const char *zDir; /* --directory argument, or NULL */ 5628 char **azArg; /* Array of command arguments */ 5629 ShellState *p; /* Shell state */ 5630 sqlite3 *db; /* Database containing the archive */ 5631}; 5632 5633/* 5634** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 5635*/ 5636static int arUsage(FILE *f){ 5637 showHelp(f,"archive"); 5638 return SQLITE_ERROR; 5639} 5640 5641/* 5642** Print an error message for the .ar command to stderr and return 5643** SQLITE_ERROR. 5644*/ 5645static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 5646 va_list ap; 5647 char *z; 5648 va_start(ap, zFmt); 5649 z = sqlite3_vmprintf(zFmt, ap); 5650 va_end(ap); 5651 utf8_printf(stderr, "Error: %s\n", z); 5652 if( pAr->fromCmdLine ){ 5653 utf8_printf(stderr, "Use \"-A\" for more help\n"); 5654 }else{ 5655 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 5656 } 5657 sqlite3_free(z); 5658 return SQLITE_ERROR; 5659} 5660 5661/* 5662** Values for ArCommand.eCmd. 5663*/ 5664#define AR_CMD_CREATE 1 5665#define AR_CMD_UPDATE 2 5666#define AR_CMD_INSERT 3 5667#define AR_CMD_EXTRACT 4 5668#define AR_CMD_LIST 5 5669#define AR_CMD_HELP 6 5670 5671/* 5672** Other (non-command) switches. 5673*/ 5674#define AR_SWITCH_VERBOSE 7 5675#define AR_SWITCH_FILE 8 5676#define AR_SWITCH_DIRECTORY 9 5677#define AR_SWITCH_APPEND 10 5678#define AR_SWITCH_DRYRUN 11 5679 5680static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 5681 switch( eSwitch ){ 5682 case AR_CMD_CREATE: 5683 case AR_CMD_EXTRACT: 5684 case AR_CMD_LIST: 5685 case AR_CMD_UPDATE: 5686 case AR_CMD_INSERT: 5687 case AR_CMD_HELP: 5688 if( pAr->eCmd ){ 5689 return arErrorMsg(pAr, "multiple command options"); 5690 } 5691 pAr->eCmd = eSwitch; 5692 break; 5693 5694 case AR_SWITCH_DRYRUN: 5695 pAr->bDryRun = 1; 5696 break; 5697 case AR_SWITCH_VERBOSE: 5698 pAr->bVerbose = 1; 5699 break; 5700 case AR_SWITCH_APPEND: 5701 pAr->bAppend = 1; 5702 /* Fall thru into --file */ 5703 case AR_SWITCH_FILE: 5704 pAr->zFile = zArg; 5705 break; 5706 case AR_SWITCH_DIRECTORY: 5707 pAr->zDir = zArg; 5708 break; 5709 } 5710 5711 return SQLITE_OK; 5712} 5713 5714/* 5715** Parse the command line for an ".ar" command. The results are written into 5716** structure (*pAr). SQLITE_OK is returned if the command line is parsed 5717** successfully, otherwise an error message is written to stderr and 5718** SQLITE_ERROR returned. 5719*/ 5720static int arParseCommand( 5721 char **azArg, /* Array of arguments passed to dot command */ 5722 int nArg, /* Number of entries in azArg[] */ 5723 ArCommand *pAr /* Populate this object */ 5724){ 5725 struct ArSwitch { 5726 const char *zLong; 5727 char cShort; 5728 u8 eSwitch; 5729 u8 bArg; 5730 } aSwitch[] = { 5731 { "create", 'c', AR_CMD_CREATE, 0 }, 5732 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 5733 { "insert", 'i', AR_CMD_INSERT, 0 }, 5734 { "list", 't', AR_CMD_LIST, 0 }, 5735 { "update", 'u', AR_CMD_UPDATE, 0 }, 5736 { "help", 'h', AR_CMD_HELP, 0 }, 5737 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 5738 { "file", 'f', AR_SWITCH_FILE, 1 }, 5739 { "append", 'a', AR_SWITCH_APPEND, 1 }, 5740 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 5741 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 5742 }; 5743 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 5744 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 5745 5746 if( nArg<=1 ){ 5747 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 5748 return arUsage(stderr); 5749 }else{ 5750 char *z = azArg[1]; 5751 if( z[0]!='-' ){ 5752 /* Traditional style [tar] invocation */ 5753 int i; 5754 int iArg = 2; 5755 for(i=0; z[i]; i++){ 5756 const char *zArg = 0; 5757 struct ArSwitch *pOpt; 5758 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5759 if( z[i]==pOpt->cShort ) break; 5760 } 5761 if( pOpt==pEnd ){ 5762 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5763 } 5764 if( pOpt->bArg ){ 5765 if( iArg>=nArg ){ 5766 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5767 } 5768 zArg = azArg[iArg++]; 5769 } 5770 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5771 } 5772 pAr->nArg = nArg-iArg; 5773 if( pAr->nArg>0 ){ 5774 pAr->azArg = &azArg[iArg]; 5775 } 5776 }else{ 5777 /* Non-traditional invocation */ 5778 int iArg; 5779 for(iArg=1; iArg<nArg; iArg++){ 5780 int n; 5781 z = azArg[iArg]; 5782 if( z[0]!='-' ){ 5783 /* All remaining command line words are command arguments. */ 5784 pAr->azArg = &azArg[iArg]; 5785 pAr->nArg = nArg-iArg; 5786 break; 5787 } 5788 n = strlen30(z); 5789 5790 if( z[1]!='-' ){ 5791 int i; 5792 /* One or more short options */ 5793 for(i=1; i<n; i++){ 5794 const char *zArg = 0; 5795 struct ArSwitch *pOpt; 5796 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5797 if( z[i]==pOpt->cShort ) break; 5798 } 5799 if( pOpt==pEnd ){ 5800 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5801 } 5802 if( pOpt->bArg ){ 5803 if( i<(n-1) ){ 5804 zArg = &z[i+1]; 5805 i = n; 5806 }else{ 5807 if( iArg>=(nArg-1) ){ 5808 return arErrorMsg(pAr, "option requires an argument: %c", 5809 z[i]); 5810 } 5811 zArg = azArg[++iArg]; 5812 } 5813 } 5814 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5815 } 5816 }else if( z[2]=='\0' ){ 5817 /* A -- option, indicating that all remaining command line words 5818 ** are command arguments. */ 5819 pAr->azArg = &azArg[iArg+1]; 5820 pAr->nArg = nArg-iArg-1; 5821 break; 5822 }else{ 5823 /* A long option */ 5824 const char *zArg = 0; /* Argument for option, if any */ 5825 struct ArSwitch *pMatch = 0; /* Matching option */ 5826 struct ArSwitch *pOpt; /* Iterator */ 5827 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5828 const char *zLong = pOpt->zLong; 5829 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 5830 if( pMatch ){ 5831 return arErrorMsg(pAr, "ambiguous option: %s",z); 5832 }else{ 5833 pMatch = pOpt; 5834 } 5835 } 5836 } 5837 5838 if( pMatch==0 ){ 5839 return arErrorMsg(pAr, "unrecognized option: %s", z); 5840 } 5841 if( pMatch->bArg ){ 5842 if( iArg>=(nArg-1) ){ 5843 return arErrorMsg(pAr, "option requires an argument: %s", z); 5844 } 5845 zArg = azArg[++iArg]; 5846 } 5847 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 5848 } 5849 } 5850 } 5851 } 5852 5853 return SQLITE_OK; 5854} 5855 5856/* 5857** This function assumes that all arguments within the ArCommand.azArg[] 5858** array refer to archive members, as for the --extract or --list commands. 5859** It checks that each of them are present. If any specified file is not 5860** present in the archive, an error is printed to stderr and an error 5861** code returned. Otherwise, if all specified arguments are present in 5862** the archive, SQLITE_OK is returned. 5863** 5864** This function strips any trailing '/' characters from each argument. 5865** This is consistent with the way the [tar] command seems to work on 5866** Linux. 5867*/ 5868static int arCheckEntries(ArCommand *pAr){ 5869 int rc = SQLITE_OK; 5870 if( pAr->nArg ){ 5871 int i, j; 5872 sqlite3_stmt *pTest = 0; 5873 5874 shellPreparePrintf(pAr->db, &rc, &pTest, 5875 "SELECT name FROM %s WHERE name=$name", 5876 pAr->zSrcTable 5877 ); 5878 j = sqlite3_bind_parameter_index(pTest, "$name"); 5879 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 5880 char *z = pAr->azArg[i]; 5881 int n = strlen30(z); 5882 int bOk = 0; 5883 while( n>0 && z[n-1]=='/' ) n--; 5884 z[n] = '\0'; 5885 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 5886 if( SQLITE_ROW==sqlite3_step(pTest) ){ 5887 bOk = 1; 5888 } 5889 shellReset(&rc, pTest); 5890 if( rc==SQLITE_OK && bOk==0 ){ 5891 utf8_printf(stderr, "not found in archive: %s\n", z); 5892 rc = SQLITE_ERROR; 5893 } 5894 } 5895 shellFinalize(&rc, pTest); 5896 } 5897 return rc; 5898} 5899 5900/* 5901** Format a WHERE clause that can be used against the "sqlar" table to 5902** identify all archive members that match the command arguments held 5903** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 5904** The caller is responsible for eventually calling sqlite3_free() on 5905** any non-NULL (*pzWhere) value. 5906*/ 5907static void arWhereClause( 5908 int *pRc, 5909 ArCommand *pAr, 5910 char **pzWhere /* OUT: New WHERE clause */ 5911){ 5912 char *zWhere = 0; 5913 if( *pRc==SQLITE_OK ){ 5914 if( pAr->nArg==0 ){ 5915 zWhere = sqlite3_mprintf("1"); 5916 }else{ 5917 int i; 5918 const char *zSep = ""; 5919 for(i=0; i<pAr->nArg; i++){ 5920 const char *z = pAr->azArg[i]; 5921 zWhere = sqlite3_mprintf( 5922 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 5923 zWhere, zSep, z, strlen30(z)+1, z 5924 ); 5925 if( zWhere==0 ){ 5926 *pRc = SQLITE_NOMEM; 5927 break; 5928 } 5929 zSep = " OR "; 5930 } 5931 } 5932 } 5933 *pzWhere = zWhere; 5934} 5935 5936/* 5937** Implementation of .ar "lisT" command. 5938*/ 5939static int arListCommand(ArCommand *pAr){ 5940 const char *zSql = "SELECT %s FROM %s WHERE %s"; 5941 const char *azCols[] = { 5942 "name", 5943 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 5944 }; 5945 5946 char *zWhere = 0; 5947 sqlite3_stmt *pSql = 0; 5948 int rc; 5949 5950 rc = arCheckEntries(pAr); 5951 arWhereClause(&rc, pAr, &zWhere); 5952 5953 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 5954 pAr->zSrcTable, zWhere); 5955 if( pAr->bDryRun ){ 5956 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5957 }else{ 5958 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5959 if( pAr->bVerbose ){ 5960 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 5961 sqlite3_column_text(pSql, 0), 5962 sqlite3_column_int(pSql, 1), 5963 sqlite3_column_text(pSql, 2), 5964 sqlite3_column_text(pSql, 3) 5965 ); 5966 }else{ 5967 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5968 } 5969 } 5970 } 5971 shellFinalize(&rc, pSql); 5972 sqlite3_free(zWhere); 5973 return rc; 5974} 5975 5976 5977/* 5978** Implementation of .ar "eXtract" command. 5979*/ 5980static int arExtractCommand(ArCommand *pAr){ 5981 const char *zSql1 = 5982 "SELECT " 5983 " ($dir || name)," 5984 " writefile(($dir || name), %s, mode, mtime) " 5985 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 5986 " AND name NOT GLOB '*..[/\\]*'"; 5987 5988 const char *azExtraArg[] = { 5989 "sqlar_uncompress(data, sz)", 5990 "data" 5991 }; 5992 5993 sqlite3_stmt *pSql = 0; 5994 int rc = SQLITE_OK; 5995 char *zDir = 0; 5996 char *zWhere = 0; 5997 int i, j; 5998 5999 /* If arguments are specified, check that they actually exist within 6000 ** the archive before proceeding. And formulate a WHERE clause to 6001 ** match them. */ 6002 rc = arCheckEntries(pAr); 6003 arWhereClause(&rc, pAr, &zWhere); 6004 6005 if( rc==SQLITE_OK ){ 6006 if( pAr->zDir ){ 6007 zDir = sqlite3_mprintf("%s/", pAr->zDir); 6008 }else{ 6009 zDir = sqlite3_mprintf(""); 6010 } 6011 if( zDir==0 ) rc = SQLITE_NOMEM; 6012 } 6013 6014 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 6015 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 6016 ); 6017 6018 if( rc==SQLITE_OK ){ 6019 j = sqlite3_bind_parameter_index(pSql, "$dir"); 6020 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 6021 6022 /* Run the SELECT statement twice. The first time, writefile() is called 6023 ** for all archive members that should be extracted. The second time, 6024 ** only for the directories. This is because the timestamps for 6025 ** extracted directories must be reset after they are populated (as 6026 ** populating them changes the timestamp). */ 6027 for(i=0; i<2; i++){ 6028 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 6029 sqlite3_bind_int(pSql, j, i); 6030 if( pAr->bDryRun ){ 6031 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6032 }else{ 6033 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6034 if( i==0 && pAr->bVerbose ){ 6035 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6036 } 6037 } 6038 } 6039 shellReset(&rc, pSql); 6040 } 6041 shellFinalize(&rc, pSql); 6042 } 6043 6044 sqlite3_free(zDir); 6045 sqlite3_free(zWhere); 6046 return rc; 6047} 6048 6049/* 6050** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 6051*/ 6052static int arExecSql(ArCommand *pAr, const char *zSql){ 6053 int rc; 6054 if( pAr->bDryRun ){ 6055 utf8_printf(pAr->p->out, "%s\n", zSql); 6056 rc = SQLITE_OK; 6057 }else{ 6058 char *zErr = 0; 6059 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6060 if( zErr ){ 6061 utf8_printf(stdout, "ERROR: %s\n", zErr); 6062 sqlite3_free(zErr); 6063 } 6064 } 6065 return rc; 6066} 6067 6068 6069/* 6070** Implementation of .ar "create", "insert", and "update" commands. 6071** 6072** create -> Create a new SQL archive 6073** insert -> Insert or reinsert all files listed 6074** update -> Insert files that have changed or that were not 6075** previously in the archive 6076** 6077** Create the "sqlar" table in the database if it does not already exist. 6078** Then add each file in the azFile[] array to the archive. Directories 6079** are added recursively. If argument bVerbose is non-zero, a message is 6080** printed on stdout for each file archived. 6081** 6082** The create command is the same as update, except that it drops 6083** any existing "sqlar" table before beginning. The "insert" command 6084** always overwrites every file named on the command-line, where as 6085** "update" only overwrites if the size or mtime or mode has changed. 6086*/ 6087static int arCreateOrUpdateCommand( 6088 ArCommand *pAr, /* Command arguments and options */ 6089 int bUpdate, /* true for a --create. */ 6090 int bOnlyIfChanged /* Only update if file has changed */ 6091){ 6092 const char *zCreate = 6093 "CREATE TABLE IF NOT EXISTS sqlar(\n" 6094 " name TEXT PRIMARY KEY, -- name of the file\n" 6095 " mode INT, -- access permissions\n" 6096 " mtime INT, -- last modification time\n" 6097 " sz INT, -- original file size\n" 6098 " data BLOB -- compressed content\n" 6099 ")"; 6100 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 6101 const char *zInsertFmt[2] = { 6102 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 6103 " SELECT\n" 6104 " %s,\n" 6105 " mode,\n" 6106 " mtime,\n" 6107 " CASE substr(lsmode(mode),1,1)\n" 6108 " WHEN '-' THEN length(data)\n" 6109 " WHEN 'd' THEN 0\n" 6110 " ELSE -1 END,\n" 6111 " sqlar_compress(data)\n" 6112 " FROM fsdir(%Q,%Q) AS disk\n" 6113 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6114 , 6115 "REPLACE INTO %s(name,mode,mtime,data)\n" 6116 " SELECT\n" 6117 " %s,\n" 6118 " mode,\n" 6119 " mtime,\n" 6120 " data\n" 6121 " FROM fsdir(%Q,%Q) AS disk\n" 6122 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 6123 }; 6124 int i; /* For iterating through azFile[] */ 6125 int rc; /* Return code */ 6126 const char *zTab = 0; /* SQL table into which to insert */ 6127 char *zSql; 6128 char zTemp[50]; 6129 char *zExists = 0; 6130 6131 arExecSql(pAr, "PRAGMA page_size=512"); 6132 rc = arExecSql(pAr, "SAVEPOINT ar;"); 6133 if( rc!=SQLITE_OK ) return rc; 6134 zTemp[0] = 0; 6135 if( pAr->bZip ){ 6136 /* Initialize the zipfile virtual table, if necessary */ 6137 if( pAr->zFile ){ 6138 sqlite3_uint64 r; 6139 sqlite3_randomness(sizeof(r),&r); 6140 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 6141 zTab = zTemp; 6142 zSql = sqlite3_mprintf( 6143 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 6144 zTab, pAr->zFile 6145 ); 6146 rc = arExecSql(pAr, zSql); 6147 sqlite3_free(zSql); 6148 }else{ 6149 zTab = "zip"; 6150 } 6151 }else{ 6152 /* Initialize the table for an SQLAR */ 6153 zTab = "sqlar"; 6154 if( bUpdate==0 ){ 6155 rc = arExecSql(pAr, zDrop); 6156 if( rc!=SQLITE_OK ) goto end_ar_transaction; 6157 } 6158 rc = arExecSql(pAr, zCreate); 6159 } 6160 if( bOnlyIfChanged ){ 6161 zExists = sqlite3_mprintf( 6162 " AND NOT EXISTS(" 6163 "SELECT 1 FROM %s AS mem" 6164 " WHERE mem.name=disk.name" 6165 " AND mem.mtime=disk.mtime" 6166 " AND mem.mode=disk.mode)", zTab); 6167 }else{ 6168 zExists = sqlite3_mprintf(""); 6169 } 6170 if( zExists==0 ) rc = SQLITE_NOMEM; 6171 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6172 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 6173 pAr->bVerbose ? "shell_putsnl(name)" : "name", 6174 pAr->azArg[i], pAr->zDir, zExists); 6175 rc = arExecSql(pAr, zSql2); 6176 sqlite3_free(zSql2); 6177 } 6178end_ar_transaction: 6179 if( rc!=SQLITE_OK ){ 6180 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6181 }else{ 6182 rc = arExecSql(pAr, "RELEASE ar;"); 6183 if( pAr->bZip && pAr->zFile ){ 6184 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 6185 arExecSql(pAr, zSql); 6186 sqlite3_free(zSql); 6187 } 6188 } 6189 sqlite3_free(zExists); 6190 return rc; 6191} 6192 6193/* 6194** Implementation of ".ar" dot command. 6195*/ 6196static int arDotCommand( 6197 ShellState *pState, /* Current shell tool state */ 6198 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 6199 char **azArg, /* Array of arguments passed to dot command */ 6200 int nArg /* Number of entries in azArg[] */ 6201){ 6202 ArCommand cmd; 6203 int rc; 6204 memset(&cmd, 0, sizeof(cmd)); 6205 cmd.fromCmdLine = fromCmdLine; 6206 rc = arParseCommand(azArg, nArg, &cmd); 6207 if( rc==SQLITE_OK ){ 6208 int eDbType = SHELL_OPEN_UNSPEC; 6209 cmd.p = pState; 6210 cmd.db = pState->db; 6211 if( cmd.zFile ){ 6212 eDbType = deduceDatabaseType(cmd.zFile, 1); 6213 }else{ 6214 eDbType = pState->openMode; 6215 } 6216 if( eDbType==SHELL_OPEN_ZIPFILE ){ 6217 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 6218 if( cmd.zFile==0 ){ 6219 cmd.zSrcTable = sqlite3_mprintf("zip"); 6220 }else{ 6221 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 6222 } 6223 } 6224 cmd.bZip = 1; 6225 }else if( cmd.zFile ){ 6226 int flags; 6227 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 6228 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 6229 || cmd.eCmd==AR_CMD_UPDATE ){ 6230 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 6231 }else{ 6232 flags = SQLITE_OPEN_READONLY; 6233 } 6234 cmd.db = 0; 6235 if( cmd.bDryRun ){ 6236 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 6237 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 6238 } 6239 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 6240 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 6241 if( rc!=SQLITE_OK ){ 6242 utf8_printf(stderr, "cannot open file: %s (%s)\n", 6243 cmd.zFile, sqlite3_errmsg(cmd.db) 6244 ); 6245 goto end_ar_command; 6246 } 6247 sqlite3_fileio_init(cmd.db, 0, 0); 6248 sqlite3_sqlar_init(cmd.db, 0, 0); 6249 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 6250 shellPutsFunc, 0, 0); 6251 6252 } 6253 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 6254 if( cmd.eCmd!=AR_CMD_CREATE 6255 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 6256 ){ 6257 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 6258 rc = SQLITE_ERROR; 6259 goto end_ar_command; 6260 } 6261 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 6262 } 6263 6264 switch( cmd.eCmd ){ 6265 case AR_CMD_CREATE: 6266 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 6267 break; 6268 6269 case AR_CMD_EXTRACT: 6270 rc = arExtractCommand(&cmd); 6271 break; 6272 6273 case AR_CMD_LIST: 6274 rc = arListCommand(&cmd); 6275 break; 6276 6277 case AR_CMD_HELP: 6278 arUsage(pState->out); 6279 break; 6280 6281 case AR_CMD_INSERT: 6282 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 6283 break; 6284 6285 default: 6286 assert( cmd.eCmd==AR_CMD_UPDATE ); 6287 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 6288 break; 6289 } 6290 } 6291end_ar_command: 6292 if( cmd.db!=pState->db ){ 6293 close_db(cmd.db); 6294 } 6295 sqlite3_free(cmd.zSrcTable); 6296 6297 return rc; 6298} 6299/* End of the ".archive" or ".ar" command logic 6300*******************************************************************************/ 6301#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 6302 6303#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 6304/* 6305** If (*pRc) is not SQLITE_OK when this function is called, it is a no-op. 6306** Otherwise, the SQL statement or statements in zSql are executed using 6307** database connection db and the error code written to *pRc before 6308** this function returns. 6309*/ 6310static void shellExec(sqlite3 *db, int *pRc, const char *zSql){ 6311 int rc = *pRc; 6312 if( rc==SQLITE_OK ){ 6313 char *zErr = 0; 6314 rc = sqlite3_exec(db, zSql, 0, 0, &zErr); 6315 if( rc!=SQLITE_OK ){ 6316 raw_printf(stderr, "SQL error: %s\n", zErr); 6317 } 6318 *pRc = rc; 6319 } 6320} 6321 6322/* 6323** Like shellExec(), except that zFmt is a printf() style format string. 6324*/ 6325static void shellExecPrintf(sqlite3 *db, int *pRc, const char *zFmt, ...){ 6326 char *z = 0; 6327 if( *pRc==SQLITE_OK ){ 6328 va_list ap; 6329 va_start(ap, zFmt); 6330 z = sqlite3_vmprintf(zFmt, ap); 6331 va_end(ap); 6332 if( z==0 ){ 6333 *pRc = SQLITE_NOMEM; 6334 }else{ 6335 shellExec(db, pRc, z); 6336 } 6337 sqlite3_free(z); 6338 } 6339} 6340 6341/* 6342** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6343** Otherwise, an attempt is made to allocate, zero and return a pointer 6344** to a buffer nByte bytes in size. If an OOM error occurs, *pRc is set 6345** to SQLITE_NOMEM and NULL returned. 6346*/ 6347static void *shellMalloc(int *pRc, sqlite3_int64 nByte){ 6348 void *pRet = 0; 6349 if( *pRc==SQLITE_OK ){ 6350 pRet = sqlite3_malloc64(nByte); 6351 if( pRet==0 ){ 6352 *pRc = SQLITE_NOMEM; 6353 }else{ 6354 memset(pRet, 0, nByte); 6355 } 6356 } 6357 return pRet; 6358} 6359 6360/* 6361** If *pRc is not SQLITE_OK when this function is called, it is a no-op. 6362** Otherwise, zFmt is treated as a printf() style string. The result of 6363** formatting it along with any trailing arguments is written into a 6364** buffer obtained from sqlite3_malloc(), and pointer to which is returned. 6365** It is the responsibility of the caller to eventually free this buffer 6366** using a call to sqlite3_free(). 6367** 6368** If an OOM error occurs, (*pRc) is set to SQLITE_NOMEM and a NULL 6369** pointer returned. 6370*/ 6371static char *shellMPrintf(int *pRc, const char *zFmt, ...){ 6372 char *z = 0; 6373 if( *pRc==SQLITE_OK ){ 6374 va_list ap; 6375 va_start(ap, zFmt); 6376 z = sqlite3_vmprintf(zFmt, ap); 6377 va_end(ap); 6378 if( z==0 ){ 6379 *pRc = SQLITE_NOMEM; 6380 } 6381 } 6382 return z; 6383} 6384 6385/* 6386** When running the ".recover" command, each output table, and the special 6387** orphaned row table if it is required, is represented by an instance 6388** of the following struct. 6389*/ 6390typedef struct RecoverTable RecoverTable; 6391struct RecoverTable { 6392 char *zQuoted; /* Quoted version of table name */ 6393 int nCol; /* Number of columns in table */ 6394 char **azlCol; /* Array of column lists */ 6395 int iPk; /* Index of IPK column */ 6396}; 6397 6398/* 6399** Free a RecoverTable object allocated by recoverFindTable() or 6400** recoverOrphanTable(). 6401*/ 6402static void recoverFreeTable(RecoverTable *pTab){ 6403 if( pTab ){ 6404 sqlite3_free(pTab->zQuoted); 6405 if( pTab->azlCol ){ 6406 int i; 6407 for(i=0; i<=pTab->nCol; i++){ 6408 sqlite3_free(pTab->azlCol[i]); 6409 } 6410 sqlite3_free(pTab->azlCol); 6411 } 6412 sqlite3_free(pTab); 6413 } 6414} 6415 6416/* 6417** This function is a no-op if (*pRc) is not SQLITE_OK when it is called. 6418** Otherwise, it allocates and returns a RecoverTable object based on the 6419** final four arguments passed to this function. It is the responsibility 6420** of the caller to eventually free the returned object using 6421** recoverFreeTable(). 6422*/ 6423static RecoverTable *recoverNewTable( 6424 int *pRc, /* IN/OUT: Error code */ 6425 const char *zName, /* Name of table */ 6426 const char *zSql, /* CREATE TABLE statement */ 6427 int bIntkey, 6428 int nCol 6429){ 6430 sqlite3 *dbtmp = 0; /* sqlite3 handle for testing CREATE TABLE */ 6431 int rc = *pRc; 6432 RecoverTable *pTab = 0; 6433 6434 pTab = (RecoverTable*)shellMalloc(&rc, sizeof(RecoverTable)); 6435 if( rc==SQLITE_OK ){ 6436 int nSqlCol = 0; 6437 int bSqlIntkey = 0; 6438 sqlite3_stmt *pStmt = 0; 6439 6440 rc = sqlite3_open("", &dbtmp); 6441 if( rc==SQLITE_OK ){ 6442 sqlite3_create_function(dbtmp, "shell_idquote", 1, SQLITE_UTF8, 0, 6443 shellIdQuote, 0, 0); 6444 } 6445 if( rc==SQLITE_OK ){ 6446 rc = sqlite3_exec(dbtmp, "PRAGMA writable_schema = on", 0, 0, 0); 6447 } 6448 if( rc==SQLITE_OK ){ 6449 rc = sqlite3_exec(dbtmp, zSql, 0, 0, 0); 6450 if( rc==SQLITE_ERROR ){ 6451 rc = SQLITE_OK; 6452 goto finished; 6453 } 6454 } 6455 shellPreparePrintf(dbtmp, &rc, &pStmt, 6456 "SELECT count(*) FROM pragma_table_info(%Q)", zName 6457 ); 6458 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6459 nSqlCol = sqlite3_column_int(pStmt, 0); 6460 } 6461 shellFinalize(&rc, pStmt); 6462 6463 if( rc!=SQLITE_OK || nSqlCol<nCol ){ 6464 goto finished; 6465 } 6466 6467 shellPreparePrintf(dbtmp, &rc, &pStmt, 6468 "SELECT (" 6469 " SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage" 6470 ") FROM sqlite_master WHERE name = %Q", zName 6471 ); 6472 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6473 bSqlIntkey = sqlite3_column_int(pStmt, 0); 6474 } 6475 shellFinalize(&rc, pStmt); 6476 6477 if( bIntkey==bSqlIntkey ){ 6478 int i; 6479 const char *zPk = "_rowid_"; 6480 sqlite3_stmt *pPkFinder = 0; 6481 6482 /* If this is an intkey table and there is an INTEGER PRIMARY KEY, 6483 ** set zPk to the name of the PK column, and pTab->iPk to the index 6484 ** of the column, where columns are 0-numbered from left to right. 6485 ** Or, if this is a WITHOUT ROWID table or if there is no IPK column, 6486 ** leave zPk as "_rowid_" and pTab->iPk at -2. */ 6487 pTab->iPk = -2; 6488 if( bIntkey ){ 6489 shellPreparePrintf(dbtmp, &rc, &pPkFinder, 6490 "SELECT cid, name FROM pragma_table_info(%Q) " 6491 " WHERE pk=1 AND type='integer' COLLATE nocase" 6492 " AND NOT EXISTS (SELECT cid FROM pragma_table_info(%Q) WHERE pk=2)" 6493 , zName, zName 6494 ); 6495 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPkFinder) ){ 6496 pTab->iPk = sqlite3_column_int(pPkFinder, 0); 6497 zPk = (const char*)sqlite3_column_text(pPkFinder, 1); 6498 } 6499 } 6500 6501 pTab->zQuoted = shellMPrintf(&rc, "\"%w\"", zName); 6502 pTab->azlCol = (char**)shellMalloc(&rc, sizeof(char*) * (nSqlCol+1)); 6503 pTab->nCol = nSqlCol; 6504 6505 if( bIntkey ){ 6506 pTab->azlCol[0] = shellMPrintf(&rc, "\"%w\"", zPk); 6507 }else{ 6508 pTab->azlCol[0] = shellMPrintf(&rc, ""); 6509 } 6510 i = 1; 6511 shellPreparePrintf(dbtmp, &rc, &pStmt, 6512 "SELECT %Q || group_concat(shell_idquote(name), ', ') " 6513 " FILTER (WHERE cid!=%d) OVER (ORDER BY %s cid) " 6514 "FROM pragma_table_info(%Q)", 6515 bIntkey ? ", " : "", pTab->iPk, 6516 bIntkey ? "" : "(CASE WHEN pk=0 THEN 1000000 ELSE pk END), ", 6517 zName 6518 ); 6519 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6520 const char *zText = (const char*)sqlite3_column_text(pStmt, 0); 6521 pTab->azlCol[i] = shellMPrintf(&rc, "%s%s", pTab->azlCol[0], zText); 6522 i++; 6523 } 6524 shellFinalize(&rc, pStmt); 6525 6526 shellFinalize(&rc, pPkFinder); 6527 } 6528 } 6529 6530 finished: 6531 sqlite3_close(dbtmp); 6532 *pRc = rc; 6533 if( rc!=SQLITE_OK || (pTab && pTab->zQuoted==0) ){ 6534 recoverFreeTable(pTab); 6535 pTab = 0; 6536 } 6537 return pTab; 6538} 6539 6540/* 6541** This function is called to search the schema recovered from the 6542** sqlite_master table of the (possibly) corrupt database as part 6543** of a ".recover" command. Specifically, for a table with root page 6544** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the 6545** table must be a WITHOUT ROWID table, or if non-zero, not one of 6546** those. 6547** 6548** If a table is found, a (RecoverTable*) object is returned. Or, if 6549** no such table is found, but bIntkey is false and iRoot is the 6550** root page of an index in the recovered schema, then (*pbNoop) is 6551** set to true and NULL returned. Or, if there is no such table or 6552** index, NULL is returned and (*pbNoop) set to 0, indicating that 6553** the caller should write data to the orphans table. 6554*/ 6555static RecoverTable *recoverFindTable( 6556 ShellState *pState, /* Shell state object */ 6557 int *pRc, /* IN/OUT: Error code */ 6558 int iRoot, /* Root page of table */ 6559 int bIntkey, /* True for an intkey table */ 6560 int nCol, /* Number of columns in table */ 6561 int *pbNoop /* OUT: True if iRoot is root of index */ 6562){ 6563 sqlite3_stmt *pStmt = 0; 6564 RecoverTable *pRet = 0; 6565 int bNoop = 0; 6566 const char *zSql = 0; 6567 const char *zName = 0; 6568 6569 /* Search the recovered schema for an object with root page iRoot. */ 6570 shellPreparePrintf(pState->db, pRc, &pStmt, 6571 "SELECT type, name, sql FROM recovery.schema WHERE rootpage=%d", iRoot 6572 ); 6573 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6574 const char *zType = (const char*)sqlite3_column_text(pStmt, 0); 6575 if( bIntkey==0 && sqlite3_stricmp(zType, "index")==0 ){ 6576 bNoop = 1; 6577 break; 6578 } 6579 if( sqlite3_stricmp(zType, "table")==0 ){ 6580 zName = (const char*)sqlite3_column_text(pStmt, 1); 6581 zSql = (const char*)sqlite3_column_text(pStmt, 2); 6582 pRet = recoverNewTable(pRc, zName, zSql, bIntkey, nCol); 6583 break; 6584 } 6585 } 6586 6587 shellFinalize(pRc, pStmt); 6588 *pbNoop = bNoop; 6589 return pRet; 6590} 6591 6592/* 6593** Return a RecoverTable object representing the orphans table. 6594*/ 6595static RecoverTable *recoverOrphanTable( 6596 ShellState *pState, /* Shell state object */ 6597 int *pRc, /* IN/OUT: Error code */ 6598 const char *zLostAndFound, /* Base name for orphans table */ 6599 int nCol /* Number of user data columns */ 6600){ 6601 RecoverTable *pTab = 0; 6602 if( nCol>=0 && *pRc==SQLITE_OK ){ 6603 int i; 6604 6605 /* This block determines the name of the orphan table. The prefered 6606 ** name is zLostAndFound. But if that clashes with another name 6607 ** in the recovered schema, try zLostAndFound_0, zLostAndFound_1 6608 ** and so on until a non-clashing name is found. */ 6609 int iTab = 0; 6610 char *zTab = shellMPrintf(pRc, "%s", zLostAndFound); 6611 sqlite3_stmt *pTest = 0; 6612 shellPrepare(pState->db, pRc, 6613 "SELECT 1 FROM recovery.schema WHERE name=?", &pTest 6614 ); 6615 if( pTest ) sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6616 while( *pRc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pTest) ){ 6617 shellReset(pRc, pTest); 6618 sqlite3_free(zTab); 6619 zTab = shellMPrintf(pRc, "%s_%d", zLostAndFound, iTab++); 6620 sqlite3_bind_text(pTest, 1, zTab, -1, SQLITE_TRANSIENT); 6621 } 6622 shellFinalize(pRc, pTest); 6623 6624 pTab = (RecoverTable*)shellMalloc(pRc, sizeof(RecoverTable)); 6625 if( pTab ){ 6626 pTab->zQuoted = shellMPrintf(pRc, "\"%w\"", zTab); 6627 pTab->nCol = nCol; 6628 pTab->iPk = -2; 6629 if( nCol>0 ){ 6630 pTab->azlCol = (char**)shellMalloc(pRc, sizeof(char*) * (nCol+1)); 6631 if( pTab->azlCol ){ 6632 pTab->azlCol[nCol] = shellMPrintf(pRc, ""); 6633 for(i=nCol-1; i>=0; i--){ 6634 pTab->azlCol[i] = shellMPrintf(pRc, "%s, NULL", pTab->azlCol[i+1]); 6635 } 6636 } 6637 } 6638 6639 if( *pRc!=SQLITE_OK ){ 6640 recoverFreeTable(pTab); 6641 pTab = 0; 6642 }else{ 6643 raw_printf(pState->out, 6644 "CREATE TABLE %s(rootpgno INTEGER, " 6645 "pgno INTEGER, nfield INTEGER, id INTEGER", pTab->zQuoted 6646 ); 6647 for(i=0; i<nCol; i++){ 6648 raw_printf(pState->out, ", c%d", i); 6649 } 6650 raw_printf(pState->out, ");\n"); 6651 } 6652 } 6653 sqlite3_free(zTab); 6654 } 6655 return pTab; 6656} 6657 6658/* 6659** This function is called to recover data from the database. A script 6660** to construct a new database containing all recovered data is output 6661** on stream pState->out. 6662*/ 6663static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 6664 int rc = SQLITE_OK; 6665 sqlite3_stmt *pLoop = 0; /* Loop through all root pages */ 6666 sqlite3_stmt *pPages = 0; /* Loop through all pages in a group */ 6667 sqlite3_stmt *pCells = 0; /* Loop through all cells in a page */ 6668 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 6669 const char *zLostAndFound = "lost_and_found"; 6670 int i; 6671 int nOrphan = -1; 6672 RecoverTable *pOrphan = 0; 6673 6674 int bFreelist = 1; /* 0 if --freelist-corrupt is specified */ 6675 int bRowids = 1; /* 0 if --no-rowids */ 6676 for(i=1; i<nArg; i++){ 6677 char *z = azArg[i]; 6678 int n; 6679 if( z[0]=='-' && z[1]=='-' ) z++; 6680 n = strlen30(z); 6681 if( n<=17 && memcmp("-freelist-corrupt", z, n)==0 ){ 6682 bFreelist = 0; 6683 }else 6684 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 6685 i++; 6686 zRecoveryDb = azArg[i]; 6687 }else 6688 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 6689 i++; 6690 zLostAndFound = azArg[i]; 6691 }else 6692 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ 6693 bRowids = 0; 6694 } 6695 else{ 6696 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 6697 showHelp(pState->out, azArg[0]); 6698 return 1; 6699 } 6700 } 6701 6702 shellExecPrintf(pState->db, &rc, 6703 /* Attach an in-memory database named 'recovery'. Create an indexed 6704 ** cache of the sqlite_dbptr virtual table. */ 6705 "PRAGMA writable_schema = on;" 6706 "ATTACH %Q AS recovery;" 6707 "DROP TABLE IF EXISTS recovery.dbptr;" 6708 "DROP TABLE IF EXISTS recovery.freelist;" 6709 "DROP TABLE IF EXISTS recovery.map;" 6710 "DROP TABLE IF EXISTS recovery.schema;" 6711 "CREATE TABLE recovery.freelist(pgno INTEGER PRIMARY KEY);", zRecoveryDb 6712 ); 6713 6714 if( bFreelist ){ 6715 shellExec(pState->db, &rc, 6716 "WITH trunk(pgno) AS (" 6717 " SELECT shell_int32(" 6718 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 8) AS x " 6719 " WHERE x>0" 6720 " UNION" 6721 " SELECT shell_int32(" 6722 " (SELECT data FROM sqlite_dbpage WHERE pgno=trunk.pgno), 0) AS x " 6723 " FROM trunk WHERE x>0" 6724 ")," 6725 "freelist(data, n, freepgno) AS (" 6726 " SELECT data, min(16384, shell_int32(data, 1)-1), t.pgno " 6727 " FROM trunk t, sqlite_dbpage s WHERE s.pgno=t.pgno" 6728 " UNION ALL" 6729 " SELECT data, n-1, shell_int32(data, 2+n) " 6730 " FROM freelist WHERE n>=0" 6731 ")" 6732 "REPLACE INTO recovery.freelist SELECT freepgno FROM freelist;" 6733 ); 6734 } 6735 6736 /* If this is an auto-vacuum database, add all pointer-map pages to 6737 ** the freelist table. Do this regardless of whether or not 6738 ** --freelist-corrupt was specified. */ 6739 shellExec(pState->db, &rc, 6740 "WITH ptrmap(pgno) AS (" 6741 " SELECT 2 WHERE shell_int32(" 6742 " (SELECT data FROM sqlite_dbpage WHERE pgno=1), 13" 6743 " )" 6744 " UNION ALL " 6745 " SELECT pgno+1+(SELECT page_size FROM pragma_page_size)/5 AS pp " 6746 " FROM ptrmap WHERE pp<=(SELECT page_count FROM pragma_page_count)" 6747 ")" 6748 "REPLACE INTO recovery.freelist SELECT pgno FROM ptrmap" 6749 ); 6750 6751 shellExec(pState->db, &rc, 6752 "CREATE TABLE recovery.dbptr(" 6753 " pgno, child, PRIMARY KEY(child, pgno)" 6754 ") WITHOUT ROWID;" 6755 "INSERT OR IGNORE INTO recovery.dbptr(pgno, child) " 6756 " SELECT * FROM sqlite_dbptr" 6757 " WHERE pgno NOT IN freelist AND child NOT IN freelist;" 6758 6759 /* Delete any pointer to page 1. This ensures that page 1 is considered 6760 ** a root page, regardless of how corrupt the db is. */ 6761 "DELETE FROM recovery.dbptr WHERE child = 1;" 6762 6763 /* Delete all pointers to any pages that have more than one pointer 6764 ** to them. Such pages will be treated as root pages when recovering 6765 ** data. */ 6766 "DELETE FROM recovery.dbptr WHERE child IN (" 6767 " SELECT child FROM recovery.dbptr GROUP BY child HAVING count(*)>1" 6768 ");" 6769 6770 /* Create the "map" table that will (eventually) contain instructions 6771 ** for dealing with each page in the db that contains one or more 6772 ** records. */ 6773 "CREATE TABLE recovery.map(" 6774 "pgno INTEGER PRIMARY KEY, maxlen INT, intkey, root INT" 6775 ");" 6776 6777 /* Populate table [map]. If there are circular loops of pages in the 6778 ** database, the following adds all pages in such a loop to the map 6779 ** as individual root pages. This could be handled better. */ 6780 "WITH pages(i, maxlen) AS (" 6781 " SELECT page_count, (" 6782 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=page_count" 6783 " ) FROM pragma_page_count WHERE page_count>0" 6784 " UNION ALL" 6785 " SELECT i-1, (" 6786 " SELECT max(field+1) FROM sqlite_dbdata WHERE pgno=i-1" 6787 " ) FROM pages WHERE i>=2" 6788 ")" 6789 "INSERT INTO recovery.map(pgno, maxlen, intkey, root) " 6790 " SELECT i, maxlen, NULL, (" 6791 " WITH p(orig, pgno, parent) AS (" 6792 " SELECT 0, i, (SELECT pgno FROM recovery.dbptr WHERE child=i)" 6793 " UNION " 6794 " SELECT i, p.parent, " 6795 " (SELECT pgno FROM recovery.dbptr WHERE child=p.parent) FROM p" 6796 " )" 6797 " SELECT pgno FROM p WHERE (parent IS NULL OR pgno = orig)" 6798 ") " 6799 "FROM pages WHERE maxlen IS NOT NULL AND i NOT IN freelist;" 6800 "UPDATE recovery.map AS o SET intkey = (" 6801 " SELECT substr(data, 1, 1)==X'0D' FROM sqlite_dbpage WHERE pgno=o.pgno" 6802 ");" 6803 6804 /* Extract data from page 1 and any linked pages into table 6805 ** recovery.schema. With the same schema as an sqlite_master table. */ 6806 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" 6807 "INSERT INTO recovery.schema SELECT " 6808 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 6809 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 6810 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 6811 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 6812 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 6813 "FROM sqlite_dbdata WHERE pgno IN (" 6814 " SELECT pgno FROM recovery.map WHERE root=1" 6815 ")" 6816 "GROUP BY pgno, cell;" 6817 "CREATE INDEX recovery.schema_rootpage ON schema(rootpage);" 6818 ); 6819 6820 /* Open a transaction, then print out all non-virtual, non-"sqlite_%" 6821 ** CREATE TABLE statements that extracted from the existing schema. */ 6822 if( rc==SQLITE_OK ){ 6823 sqlite3_stmt *pStmt = 0; 6824 /* ".recover" might output content in an order which causes immediate 6825 ** foreign key constraints to be violated. So disable foreign-key 6826 ** constraint enforcement to prevent problems when running the output 6827 ** script. */ 6828 raw_printf(pState->out, "PRAGMA foreign_keys=OFF;\n"); 6829 raw_printf(pState->out, "BEGIN;\n"); 6830 raw_printf(pState->out, "PRAGMA writable_schema = on;\n"); 6831 shellPrepare(pState->db, &rc, 6832 "SELECT sql FROM recovery.schema " 6833 "WHERE type='table' AND sql LIKE 'create table%'", &pStmt 6834 ); 6835 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6836 const char *zCreateTable = (const char*)sqlite3_column_text(pStmt, 0); 6837 raw_printf(pState->out, "CREATE TABLE IF NOT EXISTS %s;\n", 6838 &zCreateTable[12] 6839 ); 6840 } 6841 shellFinalize(&rc, pStmt); 6842 } 6843 6844 /* Figure out if an orphan table will be required. And if so, how many 6845 ** user columns it should contain */ 6846 shellPrepare(pState->db, &rc, 6847 "SELECT coalesce(max(maxlen), -2) FROM recovery.map WHERE root>1" 6848 , &pLoop 6849 ); 6850 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6851 nOrphan = sqlite3_column_int(pLoop, 0); 6852 } 6853 shellFinalize(&rc, pLoop); 6854 pLoop = 0; 6855 6856 shellPrepare(pState->db, &rc, 6857 "SELECT pgno FROM recovery.map WHERE root=?", &pPages 6858 ); 6859 6860 shellPrepare(pState->db, &rc, 6861 "SELECT max(field), group_concat(shell_escape_crnl(quote" 6862 "(case when (? AND field<0) then NULL else value end)" 6863 "), ', ')" 6864 ", min(field) " 6865 "FROM sqlite_dbdata WHERE pgno = ? AND field != ?" 6866 "GROUP BY cell", &pCells 6867 ); 6868 6869 /* Loop through each root page. */ 6870 shellPrepare(pState->db, &rc, 6871 "SELECT root, intkey, max(maxlen) FROM recovery.map" 6872 " WHERE root>1 GROUP BY root, intkey ORDER BY root=(" 6873 " SELECT rootpage FROM recovery.schema WHERE name='sqlite_sequence'" 6874 ")", &pLoop 6875 ); 6876 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pLoop) ){ 6877 int iRoot = sqlite3_column_int(pLoop, 0); 6878 int bIntkey = sqlite3_column_int(pLoop, 1); 6879 int nCol = sqlite3_column_int(pLoop, 2); 6880 int bNoop = 0; 6881 RecoverTable *pTab; 6882 6883 assert( bIntkey==0 || bIntkey==1 ); 6884 pTab = recoverFindTable(pState, &rc, iRoot, bIntkey, nCol, &bNoop); 6885 if( bNoop || rc ) continue; 6886 if( pTab==0 ){ 6887 if( pOrphan==0 ){ 6888 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6889 } 6890 pTab = pOrphan; 6891 if( pTab==0 ) break; 6892 } 6893 6894 if( 0==sqlite3_stricmp(pTab->zQuoted, "\"sqlite_sequence\"") ){ 6895 raw_printf(pState->out, "DELETE FROM sqlite_sequence;\n"); 6896 } 6897 sqlite3_bind_int(pPages, 1, iRoot); 6898 if( bRowids==0 && pTab->iPk<0 ){ 6899 sqlite3_bind_int(pCells, 1, 1); 6900 }else{ 6901 sqlite3_bind_int(pCells, 1, 0); 6902 } 6903 sqlite3_bind_int(pCells, 3, pTab->iPk); 6904 6905 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPages) ){ 6906 int iPgno = sqlite3_column_int(pPages, 0); 6907 sqlite3_bind_int(pCells, 2, iPgno); 6908 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pCells) ){ 6909 int nField = sqlite3_column_int(pCells, 0); 6910 int iMin = sqlite3_column_int(pCells, 2); 6911 const char *zVal = (const char*)sqlite3_column_text(pCells, 1); 6912 6913 RecoverTable *pTab2 = pTab; 6914 if( pTab!=pOrphan && (iMin<0)!=bIntkey ){ 6915 if( pOrphan==0 ){ 6916 pOrphan = recoverOrphanTable(pState, &rc, zLostAndFound, nOrphan); 6917 } 6918 pTab2 = pOrphan; 6919 if( pTab2==0 ) break; 6920 } 6921 6922 nField = nField+1; 6923 if( pTab2==pOrphan ){ 6924 raw_printf(pState->out, 6925 "INSERT INTO %s VALUES(%d, %d, %d, %s%s%s);\n", 6926 pTab2->zQuoted, iRoot, iPgno, nField, 6927 iMin<0 ? "" : "NULL, ", zVal, pTab2->azlCol[nField] 6928 ); 6929 }else{ 6930 raw_printf(pState->out, "INSERT INTO %s(%s) VALUES( %s );\n", 6931 pTab2->zQuoted, pTab2->azlCol[nField], zVal 6932 ); 6933 } 6934 } 6935 shellReset(&rc, pCells); 6936 } 6937 shellReset(&rc, pPages); 6938 if( pTab!=pOrphan ) recoverFreeTable(pTab); 6939 } 6940 shellFinalize(&rc, pLoop); 6941 shellFinalize(&rc, pPages); 6942 shellFinalize(&rc, pCells); 6943 recoverFreeTable(pOrphan); 6944 6945 /* The rest of the schema */ 6946 if( rc==SQLITE_OK ){ 6947 sqlite3_stmt *pStmt = 0; 6948 shellPrepare(pState->db, &rc, 6949 "SELECT sql, name FROM recovery.schema " 6950 "WHERE sql NOT LIKE 'create table%'", &pStmt 6951 ); 6952 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ 6953 const char *zSql = (const char*)sqlite3_column_text(pStmt, 0); 6954 if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){ 6955 const char *zName = (const char*)sqlite3_column_text(pStmt, 1); 6956 char *zPrint = shellMPrintf(&rc, 6957 "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)", 6958 zName, zName, zSql 6959 ); 6960 raw_printf(pState->out, "%s;\n", zPrint); 6961 sqlite3_free(zPrint); 6962 }else{ 6963 raw_printf(pState->out, "%s;\n", zSql); 6964 } 6965 } 6966 shellFinalize(&rc, pStmt); 6967 } 6968 6969 if( rc==SQLITE_OK ){ 6970 raw_printf(pState->out, "PRAGMA writable_schema = off;\n"); 6971 raw_printf(pState->out, "COMMIT;\n"); 6972 } 6973 sqlite3_exec(pState->db, "DETACH recovery", 0, 0, 0); 6974 return rc; 6975} 6976#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 6977 6978 6979/* 6980** If an input line begins with "." then invoke this routine to 6981** process that line. 6982** 6983** Return 1 on error, 2 to exit, and 0 otherwise. 6984*/ 6985static int do_meta_command(char *zLine, ShellState *p){ 6986 int h = 1; 6987 int nArg = 0; 6988 int n, c; 6989 int rc = 0; 6990 char *azArg[52]; 6991 6992#ifndef SQLITE_OMIT_VIRTUALTABLE 6993 if( p->expert.pExpert ){ 6994 expertFinish(p, 1, 0); 6995 } 6996#endif 6997 6998 /* Parse the input line into tokens. 6999 */ 7000 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ 7001 while( IsSpace(zLine[h]) ){ h++; } 7002 if( zLine[h]==0 ) break; 7003 if( zLine[h]=='\'' || zLine[h]=='"' ){ 7004 int delim = zLine[h++]; 7005 azArg[nArg++] = &zLine[h]; 7006 while( zLine[h] && zLine[h]!=delim ){ 7007 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 7008 h++; 7009 } 7010 if( zLine[h]==delim ){ 7011 zLine[h++] = 0; 7012 } 7013 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 7014 }else{ 7015 azArg[nArg++] = &zLine[h]; 7016 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 7017 if( zLine[h] ) zLine[h++] = 0; 7018 resolve_backslashes(azArg[nArg-1]); 7019 } 7020 } 7021 azArg[nArg] = 0; 7022 7023 /* Process the input line. 7024 */ 7025 if( nArg==0 ) return 0; /* no tokens, no error */ 7026 n = strlen30(azArg[0]); 7027 c = azArg[0][0]; 7028 clearTempFile(p); 7029 7030#ifndef SQLITE_OMIT_AUTHORIZATION 7031 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 7032 if( nArg!=2 ){ 7033 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 7034 rc = 1; 7035 goto meta_command_exit; 7036 } 7037 open_db(p, 0); 7038 if( booleanValue(azArg[1]) ){ 7039 sqlite3_set_authorizer(p->db, shellAuth, p); 7040 }else{ 7041 sqlite3_set_authorizer(p->db, 0, 0); 7042 } 7043 }else 7044#endif 7045 7046#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 7047 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 7048 open_db(p, 0); 7049 rc = arDotCommand(p, 0, azArg, nArg); 7050 }else 7051#endif 7052 7053 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 7054 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 7055 ){ 7056 const char *zDestFile = 0; 7057 const char *zDb = 0; 7058 sqlite3 *pDest; 7059 sqlite3_backup *pBackup; 7060 int j; 7061 int bAsync = 0; 7062 const char *zVfs = 0; 7063 for(j=1; j<nArg; j++){ 7064 const char *z = azArg[j]; 7065 if( z[0]=='-' ){ 7066 if( z[1]=='-' ) z++; 7067 if( strcmp(z, "-append")==0 ){ 7068 zVfs = "apndvfs"; 7069 }else 7070 if( strcmp(z, "-async")==0 ){ 7071 bAsync = 1; 7072 }else 7073 { 7074 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 7075 return 1; 7076 } 7077 }else if( zDestFile==0 ){ 7078 zDestFile = azArg[j]; 7079 }else if( zDb==0 ){ 7080 zDb = zDestFile; 7081 zDestFile = azArg[j]; 7082 }else{ 7083 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 7084 return 1; 7085 } 7086 } 7087 if( zDestFile==0 ){ 7088 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 7089 return 1; 7090 } 7091 if( zDb==0 ) zDb = "main"; 7092 rc = sqlite3_open_v2(zDestFile, &pDest, 7093 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 7094 if( rc!=SQLITE_OK ){ 7095 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 7096 close_db(pDest); 7097 return 1; 7098 } 7099 if( bAsync ){ 7100 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7101 0, 0, 0); 7102 } 7103 open_db(p, 0); 7104 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7105 if( pBackup==0 ){ 7106 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7107 close_db(pDest); 7108 return 1; 7109 } 7110 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7111 sqlite3_backup_finish(pBackup); 7112 if( rc==SQLITE_DONE ){ 7113 rc = 0; 7114 }else{ 7115 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7116 rc = 1; 7117 } 7118 close_db(pDest); 7119 }else 7120 7121 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 7122 if( nArg==2 ){ 7123 bail_on_error = booleanValue(azArg[1]); 7124 }else{ 7125 raw_printf(stderr, "Usage: .bail on|off\n"); 7126 rc = 1; 7127 } 7128 }else 7129 7130 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 7131 if( nArg==2 ){ 7132 if( booleanValue(azArg[1]) ){ 7133 setBinaryMode(p->out, 1); 7134 }else{ 7135 setTextMode(p->out, 1); 7136 } 7137 }else{ 7138 raw_printf(stderr, "Usage: .binary on|off\n"); 7139 rc = 1; 7140 } 7141 }else 7142 7143 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 7144 if( nArg==2 ){ 7145#if defined(_WIN32) || defined(WIN32) 7146 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7147 rc = !SetCurrentDirectoryW(z); 7148 sqlite3_free(z); 7149#else 7150 rc = chdir(azArg[1]); 7151#endif 7152 if( rc ){ 7153 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7154 rc = 1; 7155 } 7156 }else{ 7157 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7158 rc = 1; 7159 } 7160 }else 7161 7162 /* The undocumented ".breakpoint" command causes a call to the no-op 7163 ** routine named test_breakpoint(). 7164 */ 7165 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 7166 test_breakpoint(); 7167 }else 7168 7169 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 7170 if( nArg==2 ){ 7171 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7172 }else{ 7173 raw_printf(stderr, "Usage: .changes on|off\n"); 7174 rc = 1; 7175 } 7176 }else 7177 7178 /* Cancel output redirection, if it is currently set (by .testcase) 7179 ** Then read the content of the testcase-out.txt file and compare against 7180 ** azArg[1]. If there are differences, report an error and exit. 7181 */ 7182 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 7183 char *zRes = 0; 7184 output_reset(p); 7185 if( nArg!=2 ){ 7186 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7187 rc = 2; 7188 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7189 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7190 rc = 2; 7191 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7192 utf8_printf(stderr, 7193 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7194 p->zTestcase, azArg[1], zRes); 7195 rc = 1; 7196 }else{ 7197 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7198 p->nCheck++; 7199 } 7200 sqlite3_free(zRes); 7201 }else 7202 7203 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 7204 if( nArg==2 ){ 7205 tryToClone(p, azArg[1]); 7206 }else{ 7207 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7208 rc = 1; 7209 } 7210 }else 7211 7212 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 7213 ShellState data; 7214 char *zErrMsg = 0; 7215 open_db(p, 0); 7216 memcpy(&data, p, sizeof(data)); 7217 data.showHeader = 0; 7218 data.cMode = data.mode = MODE_List; 7219 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); 7220 data.cnt = 0; 7221 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", 7222 callback, &data, &zErrMsg); 7223 if( zErrMsg ){ 7224 utf8_printf(stderr,"Error: %s\n", zErrMsg); 7225 sqlite3_free(zErrMsg); 7226 rc = 1; 7227 } 7228 }else 7229 7230 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 7231 static const struct DbConfigChoices { 7232 const char *zName; 7233 int op; 7234 } aDbConfig[] = { 7235 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7236 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7237 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7238 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7239 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7240 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7241 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, 7242 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7243 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7244 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, 7245 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7246 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7247 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7248 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7249 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, 7250 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7251 }; 7252 int ii, v; 7253 open_db(p, 0); 7254 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7255 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7256 if( nArg>=3 ){ 7257 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7258 } 7259 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7260 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7261 if( nArg>1 ) break; 7262 } 7263 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7264 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7265 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7266 } 7267 }else 7268 7269 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 7270 rc = shell_dbinfo_command(p, nArg, azArg); 7271 }else 7272 7273#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 7274 if( c=='r' && strncmp(azArg[0], "recover", n)==0 ){ 7275 open_db(p, 0); 7276 rc = recoverDatabaseCmd(p, nArg, azArg); 7277 }else 7278#endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */ 7279 7280 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 7281 const char *zLike = 0; 7282 int i; 7283 int savedShowHeader = p->showHeader; 7284 int savedShellFlags = p->shellFlgs; 7285 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo); 7286 for(i=1; i<nArg; i++){ 7287 if( azArg[i][0]=='-' ){ 7288 const char *z = azArg[i]+1; 7289 if( z[0]=='-' ) z++; 7290 if( strcmp(z,"preserve-rowids")==0 ){ 7291#ifdef SQLITE_OMIT_VIRTUALTABLE 7292 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7293 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7294 rc = 1; 7295 goto meta_command_exit; 7296#else 7297 ShellSetFlag(p, SHFLG_PreserveRowid); 7298#endif 7299 }else 7300 if( strcmp(z,"newlines")==0 ){ 7301 ShellSetFlag(p, SHFLG_Newlines); 7302 }else 7303 { 7304 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 7305 rc = 1; 7306 goto meta_command_exit; 7307 } 7308 }else if( zLike ){ 7309 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? " 7310 "?--newlines? ?LIKE-PATTERN?\n"); 7311 rc = 1; 7312 goto meta_command_exit; 7313 }else{ 7314 zLike = azArg[i]; 7315 } 7316 } 7317 7318 open_db(p, 0); 7319 7320 /* When playing back a "dump", the content might appear in an order 7321 ** which causes immediate foreign key constraints to be violated. 7322 ** So disable foreign-key constraint enforcement to prevent problems. */ 7323 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 7324 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 7325 p->writableSchema = 0; 7326 p->showHeader = 0; 7327 /* Set writable_schema=ON since doing so forces SQLite to initialize 7328 ** as much of the schema as it can even if the sqlite_master table is 7329 ** corrupt. */ 7330 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 7331 p->nErr = 0; 7332 if( zLike==0 ){ 7333 run_schema_dump_query(p, 7334 "SELECT name, type, sql FROM sqlite_master " 7335 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" 7336 ); 7337 run_schema_dump_query(p, 7338 "SELECT name, type, sql FROM sqlite_master " 7339 "WHERE name=='sqlite_sequence'" 7340 ); 7341 run_table_dump_query(p, 7342 "SELECT sql FROM sqlite_master " 7343 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 7344 ); 7345 }else{ 7346 char *zSql; 7347 zSql = sqlite3_mprintf( 7348 "SELECT name, type, sql FROM sqlite_master " 7349 "WHERE tbl_name LIKE %Q AND type=='table'" 7350 " AND sql NOT NULL", zLike); 7351 run_schema_dump_query(p,zSql); 7352 sqlite3_free(zSql); 7353 zSql = sqlite3_mprintf( 7354 "SELECT sql FROM sqlite_master " 7355 "WHERE sql NOT NULL" 7356 " AND type IN ('index','trigger','view')" 7357 " AND tbl_name LIKE %Q", zLike); 7358 run_table_dump_query(p, zSql, 0); 7359 sqlite3_free(zSql); 7360 } 7361 if( p->writableSchema ){ 7362 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 7363 p->writableSchema = 0; 7364 } 7365 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 7366 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 7367 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 7368 p->showHeader = savedShowHeader; 7369 p->shellFlgs = savedShellFlags; 7370 }else 7371 7372 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 7373 if( nArg==2 ){ 7374 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 7375 }else{ 7376 raw_printf(stderr, "Usage: .echo on|off\n"); 7377 rc = 1; 7378 } 7379 }else 7380 7381 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 7382 if( nArg==2 ){ 7383 p->autoEQPtest = 0; 7384 if( p->autoEQPtrace ){ 7385 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 7386 p->autoEQPtrace = 0; 7387 } 7388 if( strcmp(azArg[1],"full")==0 ){ 7389 p->autoEQP = AUTOEQP_full; 7390 }else if( strcmp(azArg[1],"trigger")==0 ){ 7391 p->autoEQP = AUTOEQP_trigger; 7392#ifdef SQLITE_DEBUG 7393 }else if( strcmp(azArg[1],"test")==0 ){ 7394 p->autoEQP = AUTOEQP_on; 7395 p->autoEQPtest = 1; 7396 }else if( strcmp(azArg[1],"trace")==0 ){ 7397 p->autoEQP = AUTOEQP_full; 7398 p->autoEQPtrace = 1; 7399 open_db(p, 0); 7400 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0); 7401 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 7402#endif 7403 }else{ 7404 p->autoEQP = (u8)booleanValue(azArg[1]); 7405 } 7406 }else{ 7407 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 7408 rc = 1; 7409 } 7410 }else 7411 7412 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 7413 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 7414 rc = 2; 7415 }else 7416 7417 /* The ".explain" command is automatic now. It is largely pointless. It 7418 ** retained purely for backwards compatibility */ 7419 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 7420 int val = 1; 7421 if( nArg>=2 ){ 7422 if( strcmp(azArg[1],"auto")==0 ){ 7423 val = 99; 7424 }else{ 7425 val = booleanValue(azArg[1]); 7426 } 7427 } 7428 if( val==1 && p->mode!=MODE_Explain ){ 7429 p->normalMode = p->mode; 7430 p->mode = MODE_Explain; 7431 p->autoExplain = 0; 7432 }else if( val==0 ){ 7433 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7434 p->autoExplain = 0; 7435 }else if( val==99 ){ 7436 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 7437 p->autoExplain = 1; 7438 } 7439 }else 7440 7441#ifndef SQLITE_OMIT_VIRTUALTABLE 7442 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 7443 open_db(p, 0); 7444 expertDotCommand(p, azArg, nArg); 7445 }else 7446#endif 7447 7448 if( c=='f' && strncmp(azArg[0], "filectrl", n)==0 ){ 7449 static const struct { 7450 const char *zCtrlName; /* Name of a test-control option */ 7451 int ctrlCode; /* Integer code for that option */ 7452 const char *zUsage; /* Usage notes */ 7453 } aCtrl[] = { 7454 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 7455 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 7456 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 7457 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 7458 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 7459 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 7460 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 7461 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 7462 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 7463 }; 7464 int filectrl = -1; 7465 int iCtrl = -1; 7466 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 7467 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 7468 int n2, i; 7469 const char *zCmd = 0; 7470 7471 open_db(p, 0); 7472 zCmd = nArg>=2 ? azArg[1] : "help"; 7473 7474 /* The argument can optionally begin with "-" or "--" */ 7475 if( zCmd[0]=='-' && zCmd[1] ){ 7476 zCmd++; 7477 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 7478 } 7479 7480 /* --help lists all file-controls */ 7481 if( strcmp(zCmd,"help")==0 ){ 7482 utf8_printf(p->out, "Available file-controls:\n"); 7483 for(i=0; i<ArraySize(aCtrl); i++){ 7484 utf8_printf(p->out, " .filectrl %s %s\n", 7485 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 7486 } 7487 rc = 1; 7488 goto meta_command_exit; 7489 } 7490 7491 /* convert filectrl text option to value. allow any unique prefix 7492 ** of the option name, or a numerical value. */ 7493 n2 = strlen30(zCmd); 7494 for(i=0; i<ArraySize(aCtrl); i++){ 7495 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 7496 if( filectrl<0 ){ 7497 filectrl = aCtrl[i].ctrlCode; 7498 iCtrl = i; 7499 }else{ 7500 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 7501 "Use \".filectrl --help\" for help\n", zCmd); 7502 rc = 1; 7503 goto meta_command_exit; 7504 } 7505 } 7506 } 7507 if( filectrl<0 ){ 7508 utf8_printf(stderr,"Error: unknown file-control: %s\n" 7509 "Use \".filectrl --help\" for help\n", zCmd); 7510 }else{ 7511 switch(filectrl){ 7512 case SQLITE_FCNTL_SIZE_LIMIT: { 7513 if( nArg!=2 && nArg!=3 ) break; 7514 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 7515 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 7516 isOk = 1; 7517 break; 7518 } 7519 case SQLITE_FCNTL_LOCK_TIMEOUT: 7520 case SQLITE_FCNTL_CHUNK_SIZE: { 7521 int x; 7522 if( nArg!=3 ) break; 7523 x = (int)integerValue(azArg[2]); 7524 sqlite3_file_control(p->db, 0, filectrl, &x); 7525 isOk = 2; 7526 break; 7527 } 7528 case SQLITE_FCNTL_PERSIST_WAL: 7529 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 7530 int x; 7531 if( nArg!=2 && nArg!=3 ) break; 7532 x = nArg==3 ? booleanValue(azArg[2]) : -1; 7533 sqlite3_file_control(p->db, 0, filectrl, &x); 7534 iRes = x; 7535 isOk = 1; 7536 break; 7537 } 7538 case SQLITE_FCNTL_HAS_MOVED: { 7539 int x; 7540 if( nArg!=2 ) break; 7541 sqlite3_file_control(p->db, 0, filectrl, &x); 7542 iRes = x; 7543 isOk = 1; 7544 break; 7545 } 7546 case SQLITE_FCNTL_TEMPFILENAME: { 7547 char *z = 0; 7548 if( nArg!=2 ) break; 7549 sqlite3_file_control(p->db, 0, filectrl, &z); 7550 if( z ){ 7551 utf8_printf(p->out, "%s\n", z); 7552 sqlite3_free(z); 7553 } 7554 isOk = 2; 7555 break; 7556 } 7557 } 7558 } 7559 if( isOk==0 && iCtrl>=0 ){ 7560 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 7561 rc = 1; 7562 }else if( isOk==1 ){ 7563 char zBuf[100]; 7564 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 7565 raw_printf(p->out, "%s\n", zBuf); 7566 } 7567 }else 7568 7569 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 7570 ShellState data; 7571 char *zErrMsg = 0; 7572 int doStats = 0; 7573 memcpy(&data, p, sizeof(data)); 7574 data.showHeader = 0; 7575 data.cMode = data.mode = MODE_Semi; 7576 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 7577 data.cMode = data.mode = MODE_Pretty; 7578 nArg = 1; 7579 } 7580 if( nArg!=1 ){ 7581 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 7582 rc = 1; 7583 goto meta_command_exit; 7584 } 7585 open_db(p, 0); 7586 rc = sqlite3_exec(p->db, 7587 "SELECT sql FROM" 7588 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 7589 " FROM sqlite_master UNION ALL" 7590 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " 7591 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 7592 "ORDER BY rowid", 7593 callback, &data, &zErrMsg 7594 ); 7595 if( rc==SQLITE_OK ){ 7596 sqlite3_stmt *pStmt; 7597 rc = sqlite3_prepare_v2(p->db, 7598 "SELECT rowid FROM sqlite_master" 7599 " WHERE name GLOB 'sqlite_stat[134]'", 7600 -1, &pStmt, 0); 7601 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 7602 sqlite3_finalize(pStmt); 7603 } 7604 if( doStats==0 ){ 7605 raw_printf(p->out, "/* No STAT tables available */\n"); 7606 }else{ 7607 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7608 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", 7609 callback, &data, &zErrMsg); 7610 data.cMode = data.mode = MODE_Insert; 7611 data.zDestTable = "sqlite_stat1"; 7612 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg); 7613 data.zDestTable = "sqlite_stat4"; 7614 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg); 7615 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 7616 } 7617 }else 7618 7619 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 7620 if( nArg==2 ){ 7621 p->showHeader = booleanValue(azArg[1]); 7622 }else{ 7623 raw_printf(stderr, "Usage: .headers on|off\n"); 7624 rc = 1; 7625 } 7626 }else 7627 7628 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 7629 if( nArg>=2 ){ 7630 n = showHelp(p->out, azArg[1]); 7631 if( n==0 ){ 7632 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 7633 } 7634 }else{ 7635 showHelp(p->out, 0); 7636 } 7637 }else 7638 7639 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 7640 char *zTable = 0; /* Insert data into this table */ 7641 char *zFile = 0; /* Name of file to extra content from */ 7642 sqlite3_stmt *pStmt = NULL; /* A statement */ 7643 int nCol; /* Number of columns in the table */ 7644 int nByte; /* Number of bytes in an SQL string */ 7645 int i, j; /* Loop counters */ 7646 int needCommit; /* True to COMMIT or ROLLBACK at end */ 7647 int nSep; /* Number of bytes in p->colSeparator[] */ 7648 char *zSql; /* An SQL statement */ 7649 ImportCtx sCtx; /* Reader context */ 7650 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 7651 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ 7652 int eVerbose = 0; /* Larger for more console output */ 7653 int nSkip = 0; /* Initial lines to skip */ 7654 int useOutputMode = 1; /* Use output mode to determine separators */ 7655 7656 memset(&sCtx, 0, sizeof(sCtx)); 7657 if( p->mode==MODE_Ascii ){ 7658 xRead = ascii_read_one_field; 7659 }else{ 7660 xRead = csv_read_one_field; 7661 } 7662 for(i=1; i<nArg; i++){ 7663 char *z = azArg[i]; 7664 if( z[0]=='-' && z[1]=='-' ) z++; 7665 if( z[0]!='-' ){ 7666 if( zFile==0 ){ 7667 zFile = z; 7668 }else if( zTable==0 ){ 7669 zTable = z; 7670 }else{ 7671 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z); 7672 showHelp(p->out, "import"); 7673 rc = 1; 7674 goto meta_command_exit; 7675 } 7676 }else if( strcmp(z,"-v")==0 ){ 7677 eVerbose++; 7678 }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){ 7679 nSkip = integerValue(azArg[++i]); 7680 }else if( strcmp(z,"-ascii")==0 ){ 7681 sCtx.cColSep = SEP_Unit[0]; 7682 sCtx.cRowSep = SEP_Record[0]; 7683 xRead = ascii_read_one_field; 7684 useOutputMode = 0; 7685 }else if( strcmp(z,"-csv")==0 ){ 7686 sCtx.cColSep = ','; 7687 sCtx.cRowSep = '\n'; 7688 xRead = csv_read_one_field; 7689 useOutputMode = 0; 7690 }else{ 7691 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z); 7692 showHelp(p->out, "import"); 7693 rc = 1; 7694 goto meta_command_exit; 7695 } 7696 } 7697 if( zTable==0 ){ 7698 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n", 7699 zFile==0 ? "FILE" : "TABLE"); 7700 showHelp(p->out, "import"); 7701 rc = 1; 7702 goto meta_command_exit; 7703 } 7704 seenInterrupt = 0; 7705 open_db(p, 0); 7706 if( useOutputMode ){ 7707 /* If neither the --csv or --ascii options are specified, then set 7708 ** the column and row separator characters from the output mode. */ 7709 nSep = strlen30(p->colSeparator); 7710 if( nSep==0 ){ 7711 raw_printf(stderr, 7712 "Error: non-null column separator required for import\n"); 7713 rc = 1; 7714 goto meta_command_exit; 7715 } 7716 if( nSep>1 ){ 7717 raw_printf(stderr, 7718 "Error: multi-character column separators not allowed" 7719 " for import\n"); 7720 rc = 1; 7721 goto meta_command_exit; 7722 } 7723 nSep = strlen30(p->rowSeparator); 7724 if( nSep==0 ){ 7725 raw_printf(stderr, 7726 "Error: non-null row separator required for import\n"); 7727 rc = 1; 7728 goto meta_command_exit; 7729 } 7730 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){ 7731 /* When importing CSV (only), if the row separator is set to the 7732 ** default output row separator, change it to the default input 7733 ** row separator. This avoids having to maintain different input 7734 ** and output row separators. */ 7735 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 7736 nSep = strlen30(p->rowSeparator); 7737 } 7738 if( nSep>1 ){ 7739 raw_printf(stderr, "Error: multi-character row separators not allowed" 7740 " for import\n"); 7741 rc = 1; 7742 goto meta_command_exit; 7743 } 7744 sCtx.cColSep = p->colSeparator[0]; 7745 sCtx.cRowSep = p->rowSeparator[0]; 7746 } 7747 sCtx.zFile = zFile; 7748 sCtx.nLine = 1; 7749 if( sCtx.zFile[0]=='|' ){ 7750#ifdef SQLITE_OMIT_POPEN 7751 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 7752 rc = 1; 7753 goto meta_command_exit; 7754#else 7755 sCtx.in = popen(sCtx.zFile+1, "r"); 7756 sCtx.zFile = "<pipe>"; 7757 xCloser = pclose; 7758#endif 7759 }else{ 7760 sCtx.in = fopen(sCtx.zFile, "rb"); 7761 xCloser = fclose; 7762 } 7763 if( sCtx.in==0 ){ 7764 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 7765 rc = 1; 7766 goto meta_command_exit; 7767 } 7768 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ 7769 char zSep[2]; 7770 zSep[1] = 0; 7771 zSep[0] = sCtx.cColSep; 7772 utf8_printf(p->out, "Column separator "); 7773 output_c_string(p->out, zSep); 7774 utf8_printf(p->out, ", row separator "); 7775 zSep[0] = sCtx.cRowSep; 7776 output_c_string(p->out, zSep); 7777 utf8_printf(p->out, "\n"); 7778 } 7779 while( (nSkip--)>0 ){ 7780 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} 7781 sCtx.nLine++; 7782 } 7783 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); 7784 if( zSql==0 ){ 7785 xCloser(sCtx.in); 7786 shell_out_of_memory(); 7787 } 7788 nByte = strlen30(zSql); 7789 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7790 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 7791 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 7792 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); 7793 char cSep = '('; 7794 while( xRead(&sCtx) ){ 7795 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 7796 cSep = ','; 7797 if( sCtx.cTerm!=sCtx.cColSep ) break; 7798 } 7799 if( cSep=='(' ){ 7800 sqlite3_free(zCreate); 7801 sqlite3_free(sCtx.z); 7802 xCloser(sCtx.in); 7803 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 7804 rc = 1; 7805 goto meta_command_exit; 7806 } 7807 zCreate = sqlite3_mprintf("%z\n)", zCreate); 7808 if( eVerbose>=1 ){ 7809 utf8_printf(p->out, "%s\n", zCreate); 7810 } 7811 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 7812 sqlite3_free(zCreate); 7813 if( rc ){ 7814 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, 7815 sqlite3_errmsg(p->db)); 7816 sqlite3_free(sCtx.z); 7817 xCloser(sCtx.in); 7818 rc = 1; 7819 goto meta_command_exit; 7820 } 7821 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7822 } 7823 sqlite3_free(zSql); 7824 if( rc ){ 7825 if (pStmt) sqlite3_finalize(pStmt); 7826 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 7827 xCloser(sCtx.in); 7828 rc = 1; 7829 goto meta_command_exit; 7830 } 7831 nCol = sqlite3_column_count(pStmt); 7832 sqlite3_finalize(pStmt); 7833 pStmt = 0; 7834 if( nCol==0 ) return 0; /* no columns, no error */ 7835 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 7836 if( zSql==0 ){ 7837 xCloser(sCtx.in); 7838 shell_out_of_memory(); 7839 } 7840 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); 7841 j = strlen30(zSql); 7842 for(i=1; i<nCol; i++){ 7843 zSql[j++] = ','; 7844 zSql[j++] = '?'; 7845 } 7846 zSql[j++] = ')'; 7847 zSql[j] = 0; 7848 if( eVerbose>=2 ){ 7849 utf8_printf(p->out, "Insert using: %s\n", zSql); 7850 } 7851 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7852 sqlite3_free(zSql); 7853 if( rc ){ 7854 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7855 if (pStmt) sqlite3_finalize(pStmt); 7856 xCloser(sCtx.in); 7857 rc = 1; 7858 goto meta_command_exit; 7859 } 7860 needCommit = sqlite3_get_autocommit(p->db); 7861 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 7862 do{ 7863 int startLine = sCtx.nLine; 7864 for(i=0; i<nCol; i++){ 7865 char *z = xRead(&sCtx); 7866 /* 7867 ** Did we reach end-of-file before finding any columns? 7868 ** If so, stop instead of NULL filling the remaining columns. 7869 */ 7870 if( z==0 && i==0 ) break; 7871 /* 7872 ** Did we reach end-of-file OR end-of-line before finding any 7873 ** columns in ASCII mode? If so, stop instead of NULL filling 7874 ** the remaining columns. 7875 */ 7876 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 7877 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 7878 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 7879 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7880 "filling the rest with NULL\n", 7881 sCtx.zFile, startLine, nCol, i+1); 7882 i += 2; 7883 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 7884 } 7885 } 7886 if( sCtx.cTerm==sCtx.cColSep ){ 7887 do{ 7888 xRead(&sCtx); 7889 i++; 7890 }while( sCtx.cTerm==sCtx.cColSep ); 7891 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 7892 "extras ignored\n", 7893 sCtx.zFile, startLine, nCol, i); 7894 } 7895 if( i>=nCol ){ 7896 sqlite3_step(pStmt); 7897 rc = sqlite3_reset(pStmt); 7898 if( rc!=SQLITE_OK ){ 7899 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 7900 startLine, sqlite3_errmsg(p->db)); 7901 sCtx.nErr++; 7902 }else{ 7903 sCtx.nRow++; 7904 } 7905 } 7906 }while( sCtx.cTerm!=EOF ); 7907 7908 xCloser(sCtx.in); 7909 sqlite3_free(sCtx.z); 7910 sqlite3_finalize(pStmt); 7911 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 7912 if( eVerbose>0 ){ 7913 utf8_printf(p->out, 7914 "Added %d rows with %d errors using %d lines of input\n", 7915 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); 7916 } 7917 }else 7918 7919#ifndef SQLITE_UNTESTABLE 7920 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 7921 char *zSql; 7922 char *zCollist = 0; 7923 sqlite3_stmt *pStmt; 7924 int tnum = 0; 7925 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ 7926 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ 7927 int i; 7928 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 7929 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 7930 " .imposter off\n"); 7931 /* Also allowed, but not documented: 7932 ** 7933 ** .imposter TABLE IMPOSTER 7934 ** 7935 ** where TABLE is a WITHOUT ROWID table. In that case, the 7936 ** imposter is another WITHOUT ROWID table with the columns in 7937 ** storage order. */ 7938 rc = 1; 7939 goto meta_command_exit; 7940 } 7941 open_db(p, 0); 7942 if( nArg==2 ){ 7943 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 7944 goto meta_command_exit; 7945 } 7946 zSql = sqlite3_mprintf( 7947 "SELECT rootpage, 0 FROM sqlite_master" 7948 " WHERE name='%q' AND type='index'" 7949 "UNION ALL " 7950 "SELECT rootpage, 1 FROM sqlite_master" 7951 " WHERE name='%q' AND type='table'" 7952 " AND sql LIKE '%%without%%rowid%%'", 7953 azArg[1], azArg[1] 7954 ); 7955 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7956 sqlite3_free(zSql); 7957 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 7958 tnum = sqlite3_column_int(pStmt, 0); 7959 isWO = sqlite3_column_int(pStmt, 1); 7960 } 7961 sqlite3_finalize(pStmt); 7962 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 7963 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7964 sqlite3_free(zSql); 7965 i = 0; 7966 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7967 char zLabel[20]; 7968 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 7969 i++; 7970 if( zCol==0 ){ 7971 if( sqlite3_column_int(pStmt,1)==-1 ){ 7972 zCol = "_ROWID_"; 7973 }else{ 7974 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 7975 zCol = zLabel; 7976 } 7977 } 7978 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ 7979 lenPK = (int)strlen(zCollist); 7980 } 7981 if( zCollist==0 ){ 7982 zCollist = sqlite3_mprintf("\"%w\"", zCol); 7983 }else{ 7984 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 7985 } 7986 } 7987 sqlite3_finalize(pStmt); 7988 if( i==0 || tnum==0 ){ 7989 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 7990 rc = 1; 7991 sqlite3_free(zCollist); 7992 goto meta_command_exit; 7993 } 7994 if( lenPK==0 ) lenPK = 100000; 7995 zSql = sqlite3_mprintf( 7996 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", 7997 azArg[2], zCollist, lenPK, zCollist); 7998 sqlite3_free(zCollist); 7999 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 8000 if( rc==SQLITE_OK ){ 8001 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 8002 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 8003 if( rc ){ 8004 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 8005 }else{ 8006 utf8_printf(stdout, "%s;\n", zSql); 8007 raw_printf(stdout, 8008 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n", 8009 azArg[1], isWO ? "table" : "index" 8010 ); 8011 } 8012 }else{ 8013 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 8014 rc = 1; 8015 } 8016 sqlite3_free(zSql); 8017 }else 8018#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 8019 8020#ifdef SQLITE_ENABLE_IOTRACE 8021 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 8022 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 8023 if( iotrace && iotrace!=stdout ) fclose(iotrace); 8024 iotrace = 0; 8025 if( nArg<2 ){ 8026 sqlite3IoTrace = 0; 8027 }else if( strcmp(azArg[1], "-")==0 ){ 8028 sqlite3IoTrace = iotracePrintf; 8029 iotrace = stdout; 8030 }else{ 8031 iotrace = fopen(azArg[1], "w"); 8032 if( iotrace==0 ){ 8033 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 8034 sqlite3IoTrace = 0; 8035 rc = 1; 8036 }else{ 8037 sqlite3IoTrace = iotracePrintf; 8038 } 8039 } 8040 }else 8041#endif 8042 8043 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 8044 static const struct { 8045 const char *zLimitName; /* Name of a limit */ 8046 int limitCode; /* Integer code for that limit */ 8047 } aLimit[] = { 8048 { "length", SQLITE_LIMIT_LENGTH }, 8049 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 8050 { "column", SQLITE_LIMIT_COLUMN }, 8051 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 8052 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 8053 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 8054 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 8055 { "attached", SQLITE_LIMIT_ATTACHED }, 8056 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 8057 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 8058 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 8059 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 8060 }; 8061 int i, n2; 8062 open_db(p, 0); 8063 if( nArg==1 ){ 8064 for(i=0; i<ArraySize(aLimit); i++){ 8065 printf("%20s %d\n", aLimit[i].zLimitName, 8066 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 8067 } 8068 }else if( nArg>3 ){ 8069 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 8070 rc = 1; 8071 goto meta_command_exit; 8072 }else{ 8073 int iLimit = -1; 8074 n2 = strlen30(azArg[1]); 8075 for(i=0; i<ArraySize(aLimit); i++){ 8076 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 8077 if( iLimit<0 ){ 8078 iLimit = i; 8079 }else{ 8080 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 8081 rc = 1; 8082 goto meta_command_exit; 8083 } 8084 } 8085 } 8086 if( iLimit<0 ){ 8087 utf8_printf(stderr, "unknown limit: \"%s\"\n" 8088 "enter \".limits\" with no arguments for a list.\n", 8089 azArg[1]); 8090 rc = 1; 8091 goto meta_command_exit; 8092 } 8093 if( nArg==3 ){ 8094 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 8095 (int)integerValue(azArg[2])); 8096 } 8097 printf("%20s %d\n", aLimit[iLimit].zLimitName, 8098 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 8099 } 8100 }else 8101 8102 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 8103 open_db(p, 0); 8104 lintDotCommand(p, azArg, nArg); 8105 }else 8106 8107#ifndef SQLITE_OMIT_LOAD_EXTENSION 8108 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 8109 const char *zFile, *zProc; 8110 char *zErrMsg = 0; 8111 if( nArg<2 ){ 8112 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 8113 rc = 1; 8114 goto meta_command_exit; 8115 } 8116 zFile = azArg[1]; 8117 zProc = nArg>=3 ? azArg[2] : 0; 8118 open_db(p, 0); 8119 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 8120 if( rc!=SQLITE_OK ){ 8121 utf8_printf(stderr, "Error: %s\n", zErrMsg); 8122 sqlite3_free(zErrMsg); 8123 rc = 1; 8124 } 8125 }else 8126#endif 8127 8128 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 8129 if( nArg!=2 ){ 8130 raw_printf(stderr, "Usage: .log FILENAME\n"); 8131 rc = 1; 8132 }else{ 8133 const char *zFile = azArg[1]; 8134 output_file_close(p->pLog); 8135 p->pLog = output_file_open(zFile, 0); 8136 } 8137 }else 8138 8139 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 8140 const char *zMode = nArg>=2 ? azArg[1] : ""; 8141 int n2 = strlen30(zMode); 8142 int c2 = zMode[0]; 8143 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 8144 p->mode = MODE_Line; 8145 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8146 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 8147 p->mode = MODE_Column; 8148 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8149 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 8150 p->mode = MODE_List; 8151 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 8152 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8153 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 8154 p->mode = MODE_Html; 8155 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 8156 p->mode = MODE_Tcl; 8157 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 8158 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8159 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 8160 p->mode = MODE_Csv; 8161 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8162 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8163 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 8164 p->mode = MODE_List; 8165 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 8166 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 8167 p->mode = MODE_Insert; 8168 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 8169 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 8170 p->mode = MODE_Quote; 8171 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 8172 p->mode = MODE_Ascii; 8173 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 8174 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 8175 }else if( nArg==1 ){ 8176 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 8177 }else{ 8178 raw_printf(stderr, "Error: mode should be one of: " 8179 "ascii column csv html insert line list quote tabs tcl\n"); 8180 rc = 1; 8181 } 8182 p->cMode = p->mode; 8183 }else 8184 8185 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 8186 if( nArg==2 ){ 8187 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 8188 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 8189 }else{ 8190 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 8191 rc = 1; 8192 } 8193 }else 8194 8195#ifdef SQLITE_DEBUG 8196 if( c=='o' && strcmp(azArg[0],"oom")==0 ){ 8197 int i; 8198 for(i=1; i<nArg; i++){ 8199 const char *z = azArg[i]; 8200 if( z[0]=='-' && z[1]=='-' ) z++; 8201 if( strcmp(z,"-repeat")==0 ){ 8202 if( i==nArg-1 ){ 8203 raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]); 8204 rc = 1; 8205 }else{ 8206 oomRepeat = (int)integerValue(azArg[++i]); 8207 } 8208 }else if( IsDigit(z[0]) ){ 8209 oomCounter = (int)integerValue(azArg[i]); 8210 }else{ 8211 raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]); 8212 raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n"); 8213 rc = 1; 8214 } 8215 } 8216 if( rc==0 ){ 8217 raw_printf(p->out, "oomCounter = %d\n", oomCounter); 8218 raw_printf(p->out, "oomRepeat = %d\n", oomRepeat); 8219 } 8220 }else 8221#endif /* SQLITE_DEBUG */ 8222 8223 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 8224 char *zNewFilename; /* Name of the database file to open */ 8225 int iName = 1; /* Index in azArg[] of the filename */ 8226 int newFlag = 0; /* True to delete file before opening */ 8227 /* Close the existing database */ 8228 session_close_all(p); 8229 close_db(p->db); 8230 p->db = 0; 8231 p->zDbFilename = 0; 8232 sqlite3_free(p->zFreeOnClose); 8233 p->zFreeOnClose = 0; 8234 p->openMode = SHELL_OPEN_UNSPEC; 8235 p->openFlags = 0; 8236 p->szMax = 0; 8237 /* Check for command-line arguments */ 8238 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){ 8239 const char *z = azArg[iName]; 8240 if( optionMatch(z,"new") ){ 8241 newFlag = 1; 8242#ifdef SQLITE_HAVE_ZLIB 8243 }else if( optionMatch(z, "zip") ){ 8244 p->openMode = SHELL_OPEN_ZIPFILE; 8245#endif 8246 }else if( optionMatch(z, "append") ){ 8247 p->openMode = SHELL_OPEN_APPENDVFS; 8248 }else if( optionMatch(z, "readonly") ){ 8249 p->openMode = SHELL_OPEN_READONLY; 8250 }else if( optionMatch(z, "nofollow") ){ 8251 p->openFlags |= SQLITE_OPEN_NOFOLLOW; 8252#ifdef SQLITE_ENABLE_DESERIALIZE 8253 }else if( optionMatch(z, "deserialize") ){ 8254 p->openMode = SHELL_OPEN_DESERIALIZE; 8255 }else if( optionMatch(z, "hexdb") ){ 8256 p->openMode = SHELL_OPEN_HEXDB; 8257 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 8258 p->szMax = integerValue(azArg[++iName]); 8259#endif /* SQLITE_ENABLE_DESERIALIZE */ 8260 }else if( z[0]=='-' ){ 8261 utf8_printf(stderr, "unknown option: %s\n", z); 8262 rc = 1; 8263 goto meta_command_exit; 8264 } 8265 } 8266 /* If a filename is specified, try to open it first */ 8267 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; 8268 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ 8269 if( newFlag ) shellDeleteFile(zNewFilename); 8270 p->zDbFilename = zNewFilename; 8271 open_db(p, OPEN_DB_KEEPALIVE); 8272 if( p->db==0 ){ 8273 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 8274 sqlite3_free(zNewFilename); 8275 }else{ 8276 p->zFreeOnClose = zNewFilename; 8277 } 8278 } 8279 if( p->db==0 ){ 8280 /* As a fall-back open a TEMP database */ 8281 p->zDbFilename = 0; 8282 open_db(p, 0); 8283 } 8284 }else 8285 8286 if( (c=='o' 8287 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 8288 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 8289 ){ 8290 const char *zFile = nArg>=2 ? azArg[1] : "stdout"; 8291 int bTxtMode = 0; 8292 if( azArg[0][0]=='e' ){ 8293 /* Transform the ".excel" command into ".once -x" */ 8294 nArg = 2; 8295 azArg[0] = "once"; 8296 zFile = azArg[1] = "-x"; 8297 n = 4; 8298 } 8299 if( nArg>2 ){ 8300 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]); 8301 rc = 1; 8302 goto meta_command_exit; 8303 } 8304 if( n>1 && strncmp(azArg[0], "once", n)==0 ){ 8305 if( nArg<2 ){ 8306 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n"); 8307 rc = 1; 8308 goto meta_command_exit; 8309 } 8310 p->outCount = 2; 8311 }else{ 8312 p->outCount = 0; 8313 } 8314 output_reset(p); 8315 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++; 8316#ifndef SQLITE_NOHAVE_SYSTEM 8317 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){ 8318 p->doXdgOpen = 1; 8319 outputModePush(p); 8320 if( zFile[1]=='x' ){ 8321 newTempFile(p, "csv"); 8322 p->mode = MODE_Csv; 8323 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8324 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8325 }else{ 8326 newTempFile(p, "txt"); 8327 bTxtMode = 1; 8328 } 8329 zFile = p->zTempFile; 8330 } 8331#endif /* SQLITE_NOHAVE_SYSTEM */ 8332 if( zFile[0]=='|' ){ 8333#ifdef SQLITE_OMIT_POPEN 8334 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8335 rc = 1; 8336 p->out = stdout; 8337#else 8338 p->out = popen(zFile + 1, "w"); 8339 if( p->out==0 ){ 8340 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 8341 p->out = stdout; 8342 rc = 1; 8343 }else{ 8344 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 8345 } 8346#endif 8347 }else{ 8348 p->out = output_file_open(zFile, bTxtMode); 8349 if( p->out==0 ){ 8350 if( strcmp(zFile,"off")!=0 ){ 8351 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 8352 } 8353 p->out = stdout; 8354 rc = 1; 8355 } else { 8356 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 8357 } 8358 } 8359 }else 8360 8361 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 8362 open_db(p,0); 8363 if( nArg<=1 ) goto parameter_syntax_error; 8364 8365 /* .parameter clear 8366 ** Clear all bind parameters by dropping the TEMP table that holds them. 8367 */ 8368 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 8369 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 8370 0, 0, 0); 8371 }else 8372 8373 /* .parameter list 8374 ** List all bind parameters. 8375 */ 8376 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 8377 sqlite3_stmt *pStmt = 0; 8378 int rx; 8379 int len = 0; 8380 rx = sqlite3_prepare_v2(p->db, 8381 "SELECT max(length(key)) " 8382 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 8383 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8384 len = sqlite3_column_int(pStmt, 0); 8385 if( len>40 ) len = 40; 8386 } 8387 sqlite3_finalize(pStmt); 8388 pStmt = 0; 8389 if( len ){ 8390 rx = sqlite3_prepare_v2(p->db, 8391 "SELECT key, quote(value) " 8392 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 8393 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8394 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 8395 sqlite3_column_text(pStmt,1)); 8396 } 8397 sqlite3_finalize(pStmt); 8398 } 8399 }else 8400 8401 /* .parameter init 8402 ** Make sure the TEMP table used to hold bind parameters exists. 8403 ** Create it if necessary. 8404 */ 8405 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 8406 bind_table_init(p); 8407 }else 8408 8409 /* .parameter set NAME VALUE 8410 ** Set or reset a bind parameter. NAME should be the full parameter 8411 ** name exactly as it appears in the query. (ex: $abc, @def). The 8412 ** VALUE can be in either SQL literal notation, or if not it will be 8413 ** understood to be a text string. 8414 */ 8415 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 8416 int rx; 8417 char *zSql; 8418 sqlite3_stmt *pStmt; 8419 const char *zKey = azArg[2]; 8420 const char *zValue = azArg[3]; 8421 bind_table_init(p); 8422 zSql = sqlite3_mprintf( 8423 "REPLACE INTO temp.sqlite_parameters(key,value)" 8424 "VALUES(%Q,%s);", zKey, zValue); 8425 if( zSql==0 ) shell_out_of_memory(); 8426 pStmt = 0; 8427 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8428 sqlite3_free(zSql); 8429 if( rx!=SQLITE_OK ){ 8430 sqlite3_finalize(pStmt); 8431 pStmt = 0; 8432 zSql = sqlite3_mprintf( 8433 "REPLACE INTO temp.sqlite_parameters(key,value)" 8434 "VALUES(%Q,%Q);", zKey, zValue); 8435 if( zSql==0 ) shell_out_of_memory(); 8436 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8437 sqlite3_free(zSql); 8438 if( rx!=SQLITE_OK ){ 8439 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 8440 sqlite3_finalize(pStmt); 8441 pStmt = 0; 8442 rc = 1; 8443 } 8444 } 8445 sqlite3_step(pStmt); 8446 sqlite3_finalize(pStmt); 8447 }else 8448 8449 /* .parameter unset NAME 8450 ** Remove the NAME binding from the parameter binding table, if it 8451 ** exists. 8452 */ 8453 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 8454 char *zSql = sqlite3_mprintf( 8455 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 8456 if( zSql==0 ) shell_out_of_memory(); 8457 sqlite3_exec(p->db, zSql, 0, 0, 0); 8458 sqlite3_free(zSql); 8459 }else 8460 /* If no command name matches, show a syntax error */ 8461 parameter_syntax_error: 8462 showHelp(p->out, "parameter"); 8463 }else 8464 8465 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 8466 int i; 8467 for(i=1; i<nArg; i++){ 8468 if( i>1 ) raw_printf(p->out, " "); 8469 utf8_printf(p->out, "%s", azArg[i]); 8470 } 8471 raw_printf(p->out, "\n"); 8472 }else 8473 8474#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 8475 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 8476 int i; 8477 int nn = 0; 8478 p->flgProgress = 0; 8479 p->mxProgress = 0; 8480 p->nProgress = 0; 8481 for(i=1; i<nArg; i++){ 8482 const char *z = azArg[i]; 8483 if( z[0]=='-' ){ 8484 z++; 8485 if( z[0]=='-' ) z++; 8486 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 8487 p->flgProgress |= SHELL_PROGRESS_QUIET; 8488 continue; 8489 } 8490 if( strcmp(z,"reset")==0 ){ 8491 p->flgProgress |= SHELL_PROGRESS_RESET; 8492 continue; 8493 } 8494 if( strcmp(z,"once")==0 ){ 8495 p->flgProgress |= SHELL_PROGRESS_ONCE; 8496 continue; 8497 } 8498 if( strcmp(z,"limit")==0 ){ 8499 if( i+1>=nArg ){ 8500 utf8_printf(stderr, "Error: missing argument on --limit\n"); 8501 rc = 1; 8502 goto meta_command_exit; 8503 }else{ 8504 p->mxProgress = (int)integerValue(azArg[++i]); 8505 } 8506 continue; 8507 } 8508 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 8509 rc = 1; 8510 goto meta_command_exit; 8511 }else{ 8512 nn = (int)integerValue(z); 8513 } 8514 } 8515 open_db(p, 0); 8516 sqlite3_progress_handler(p->db, nn, progress_handler, p); 8517 }else 8518#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 8519 8520 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 8521 if( nArg >= 2) { 8522 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 8523 } 8524 if( nArg >= 3) { 8525 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 8526 } 8527 }else 8528 8529 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 8530 rc = 2; 8531 }else 8532 8533 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 8534 FILE *inSaved = p->in; 8535 int savedLineno = p->lineno; 8536 if( nArg!=2 ){ 8537 raw_printf(stderr, "Usage: .read FILE\n"); 8538 rc = 1; 8539 goto meta_command_exit; 8540 } 8541 p->in = fopen(azArg[1], "rb"); 8542 if( p->in==0 ){ 8543 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 8544 rc = 1; 8545 }else{ 8546 rc = process_input(p); 8547 fclose(p->in); 8548 } 8549 p->in = inSaved; 8550 p->lineno = savedLineno; 8551 }else 8552 8553 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 8554 const char *zSrcFile; 8555 const char *zDb; 8556 sqlite3 *pSrc; 8557 sqlite3_backup *pBackup; 8558 int nTimeout = 0; 8559 8560 if( nArg==2 ){ 8561 zSrcFile = azArg[1]; 8562 zDb = "main"; 8563 }else if( nArg==3 ){ 8564 zSrcFile = azArg[2]; 8565 zDb = azArg[1]; 8566 }else{ 8567 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 8568 rc = 1; 8569 goto meta_command_exit; 8570 } 8571 rc = sqlite3_open(zSrcFile, &pSrc); 8572 if( rc!=SQLITE_OK ){ 8573 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 8574 close_db(pSrc); 8575 return 1; 8576 } 8577 open_db(p, 0); 8578 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 8579 if( pBackup==0 ){ 8580 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8581 close_db(pSrc); 8582 return 1; 8583 } 8584 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 8585 || rc==SQLITE_BUSY ){ 8586 if( rc==SQLITE_BUSY ){ 8587 if( nTimeout++ >= 3 ) break; 8588 sqlite3_sleep(100); 8589 } 8590 } 8591 sqlite3_backup_finish(pBackup); 8592 if( rc==SQLITE_DONE ){ 8593 rc = 0; 8594 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 8595 raw_printf(stderr, "Error: source database is busy\n"); 8596 rc = 1; 8597 }else{ 8598 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8599 rc = 1; 8600 } 8601 close_db(pSrc); 8602 }else 8603 8604 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 8605 if( nArg==2 ){ 8606 p->scanstatsOn = (u8)booleanValue(azArg[1]); 8607#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 8608 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 8609#endif 8610 }else{ 8611 raw_printf(stderr, "Usage: .scanstats on|off\n"); 8612 rc = 1; 8613 } 8614 }else 8615 8616 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 8617 ShellText sSelect; 8618 ShellState data; 8619 char *zErrMsg = 0; 8620 const char *zDiv = "("; 8621 const char *zName = 0; 8622 int iSchema = 0; 8623 int bDebug = 0; 8624 int ii; 8625 8626 open_db(p, 0); 8627 memcpy(&data, p, sizeof(data)); 8628 data.showHeader = 0; 8629 data.cMode = data.mode = MODE_Semi; 8630 initText(&sSelect); 8631 for(ii=1; ii<nArg; ii++){ 8632 if( optionMatch(azArg[ii],"indent") ){ 8633 data.cMode = data.mode = MODE_Pretty; 8634 }else if( optionMatch(azArg[ii],"debug") ){ 8635 bDebug = 1; 8636 }else if( zName==0 ){ 8637 zName = azArg[ii]; 8638 }else{ 8639 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); 8640 rc = 1; 8641 goto meta_command_exit; 8642 } 8643 } 8644 if( zName!=0 ){ 8645 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0; 8646 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){ 8647 char *new_argv[2], *new_colv[2]; 8648 new_argv[0] = sqlite3_mprintf( 8649 "CREATE TABLE %s (\n" 8650 " type text,\n" 8651 " name text,\n" 8652 " tbl_name text,\n" 8653 " rootpage integer,\n" 8654 " sql text\n" 8655 ")", isMaster ? "sqlite_master" : "sqlite_temp_master"); 8656 new_argv[1] = 0; 8657 new_colv[0] = "sql"; 8658 new_colv[1] = 0; 8659 callback(&data, 1, new_argv, new_colv); 8660 sqlite3_free(new_argv[0]); 8661 } 8662 } 8663 if( zDiv ){ 8664 sqlite3_stmt *pStmt = 0; 8665 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 8666 -1, &pStmt, 0); 8667 if( rc ){ 8668 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8669 sqlite3_finalize(pStmt); 8670 rc = 1; 8671 goto meta_command_exit; 8672 } 8673 appendText(&sSelect, "SELECT sql FROM", 0); 8674 iSchema = 0; 8675 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8676 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 8677 char zScNum[30]; 8678 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 8679 appendText(&sSelect, zDiv, 0); 8680 zDiv = " UNION ALL "; 8681 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 8682 if( sqlite3_stricmp(zDb, "main")!=0 ){ 8683 appendText(&sSelect, zDb, '\''); 8684 }else{ 8685 appendText(&sSelect, "NULL", 0); 8686 } 8687 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 8688 appendText(&sSelect, zScNum, 0); 8689 appendText(&sSelect, " AS snum, ", 0); 8690 appendText(&sSelect, zDb, '\''); 8691 appendText(&sSelect, " AS sname FROM ", 0); 8692 appendText(&sSelect, zDb, quoteChar(zDb)); 8693 appendText(&sSelect, ".sqlite_master", 0); 8694 } 8695 sqlite3_finalize(pStmt); 8696#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 8697 if( zName ){ 8698 appendText(&sSelect, 8699 " UNION ALL SELECT shell_module_schema(name)," 8700 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 8701 0); 8702 } 8703#endif 8704 appendText(&sSelect, ") WHERE ", 0); 8705 if( zName ){ 8706 char *zQarg = sqlite3_mprintf("%Q", zName); 8707 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 8708 strchr(zName, '[') != 0; 8709 if( strchr(zName, '.') ){ 8710 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 8711 }else{ 8712 appendText(&sSelect, "lower(tbl_name)", 0); 8713 } 8714 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 8715 appendText(&sSelect, zQarg, 0); 8716 if( !bGlob ){ 8717 appendText(&sSelect, " ESCAPE '\\' ", 0); 8718 } 8719 appendText(&sSelect, " AND ", 0); 8720 sqlite3_free(zQarg); 8721 } 8722 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" 8723 " ORDER BY snum, rowid", 0); 8724 if( bDebug ){ 8725 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 8726 }else{ 8727 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 8728 } 8729 freeText(&sSelect); 8730 } 8731 if( zErrMsg ){ 8732 utf8_printf(stderr,"Error: %s\n", zErrMsg); 8733 sqlite3_free(zErrMsg); 8734 rc = 1; 8735 }else if( rc != SQLITE_OK ){ 8736 raw_printf(stderr,"Error: querying schema information\n"); 8737 rc = 1; 8738 }else{ 8739 rc = 0; 8740 } 8741 }else 8742 8743#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 8744 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 8745 sqlite3SelectTrace = (int)integerValue(azArg[1]); 8746 }else 8747#endif 8748 8749#if defined(SQLITE_ENABLE_SESSION) 8750 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 8751 OpenSession *pSession = &p->aSession[0]; 8752 char **azCmd = &azArg[1]; 8753 int iSes = 0; 8754 int nCmd = nArg - 1; 8755 int i; 8756 if( nArg<=1 ) goto session_syntax_error; 8757 open_db(p, 0); 8758 if( nArg>=3 ){ 8759 for(iSes=0; iSes<p->nSession; iSes++){ 8760 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; 8761 } 8762 if( iSes<p->nSession ){ 8763 pSession = &p->aSession[iSes]; 8764 azCmd++; 8765 nCmd--; 8766 }else{ 8767 pSession = &p->aSession[0]; 8768 iSes = 0; 8769 } 8770 } 8771 8772 /* .session attach TABLE 8773 ** Invoke the sqlite3session_attach() interface to attach a particular 8774 ** table so that it is never filtered. 8775 */ 8776 if( strcmp(azCmd[0],"attach")==0 ){ 8777 if( nCmd!=2 ) goto session_syntax_error; 8778 if( pSession->p==0 ){ 8779 session_not_open: 8780 raw_printf(stderr, "ERROR: No sessions are open\n"); 8781 }else{ 8782 rc = sqlite3session_attach(pSession->p, azCmd[1]); 8783 if( rc ){ 8784 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 8785 rc = 0; 8786 } 8787 } 8788 }else 8789 8790 /* .session changeset FILE 8791 ** .session patchset FILE 8792 ** Write a changeset or patchset into a file. The file is overwritten. 8793 */ 8794 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 8795 FILE *out = 0; 8796 if( nCmd!=2 ) goto session_syntax_error; 8797 if( pSession->p==0 ) goto session_not_open; 8798 out = fopen(azCmd[1], "wb"); 8799 if( out==0 ){ 8800 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", 8801 azCmd[1]); 8802 }else{ 8803 int szChng; 8804 void *pChng; 8805 if( azCmd[0][0]=='c' ){ 8806 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 8807 }else{ 8808 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 8809 } 8810 if( rc ){ 8811 printf("Error: error code %d\n", rc); 8812 rc = 0; 8813 } 8814 if( pChng 8815 && fwrite(pChng, szChng, 1, out)!=1 ){ 8816 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 8817 szChng); 8818 } 8819 sqlite3_free(pChng); 8820 fclose(out); 8821 } 8822 }else 8823 8824 /* .session close 8825 ** Close the identified session 8826 */ 8827 if( strcmp(azCmd[0], "close")==0 ){ 8828 if( nCmd!=1 ) goto session_syntax_error; 8829 if( p->nSession ){ 8830 session_close(pSession); 8831 p->aSession[iSes] = p->aSession[--p->nSession]; 8832 } 8833 }else 8834 8835 /* .session enable ?BOOLEAN? 8836 ** Query or set the enable flag 8837 */ 8838 if( strcmp(azCmd[0], "enable")==0 ){ 8839 int ii; 8840 if( nCmd>2 ) goto session_syntax_error; 8841 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8842 if( p->nSession ){ 8843 ii = sqlite3session_enable(pSession->p, ii); 8844 utf8_printf(p->out, "session %s enable flag = %d\n", 8845 pSession->zName, ii); 8846 } 8847 }else 8848 8849 /* .session filter GLOB .... 8850 ** Set a list of GLOB patterns of table names to be excluded. 8851 */ 8852 if( strcmp(azCmd[0], "filter")==0 ){ 8853 int ii, nByte; 8854 if( nCmd<2 ) goto session_syntax_error; 8855 if( p->nSession ){ 8856 for(ii=0; ii<pSession->nFilter; ii++){ 8857 sqlite3_free(pSession->azFilter[ii]); 8858 } 8859 sqlite3_free(pSession->azFilter); 8860 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 8861 pSession->azFilter = sqlite3_malloc( nByte ); 8862 if( pSession->azFilter==0 ){ 8863 raw_printf(stderr, "Error: out or memory\n"); 8864 exit(1); 8865 } 8866 for(ii=1; ii<nCmd; ii++){ 8867 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 8868 } 8869 pSession->nFilter = ii-1; 8870 } 8871 }else 8872 8873 /* .session indirect ?BOOLEAN? 8874 ** Query or set the indirect flag 8875 */ 8876 if( strcmp(azCmd[0], "indirect")==0 ){ 8877 int ii; 8878 if( nCmd>2 ) goto session_syntax_error; 8879 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 8880 if( p->nSession ){ 8881 ii = sqlite3session_indirect(pSession->p, ii); 8882 utf8_printf(p->out, "session %s indirect flag = %d\n", 8883 pSession->zName, ii); 8884 } 8885 }else 8886 8887 /* .session isempty 8888 ** Determine if the session is empty 8889 */ 8890 if( strcmp(azCmd[0], "isempty")==0 ){ 8891 int ii; 8892 if( nCmd!=1 ) goto session_syntax_error; 8893 if( p->nSession ){ 8894 ii = sqlite3session_isempty(pSession->p); 8895 utf8_printf(p->out, "session %s isempty flag = %d\n", 8896 pSession->zName, ii); 8897 } 8898 }else 8899 8900 /* .session list 8901 ** List all currently open sessions 8902 */ 8903 if( strcmp(azCmd[0],"list")==0 ){ 8904 for(i=0; i<p->nSession; i++){ 8905 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); 8906 } 8907 }else 8908 8909 /* .session open DB NAME 8910 ** Open a new session called NAME on the attached database DB. 8911 ** DB is normally "main". 8912 */ 8913 if( strcmp(azCmd[0],"open")==0 ){ 8914 char *zName; 8915 if( nCmd!=3 ) goto session_syntax_error; 8916 zName = azCmd[2]; 8917 if( zName[0]==0 ) goto session_syntax_error; 8918 for(i=0; i<p->nSession; i++){ 8919 if( strcmp(p->aSession[i].zName,zName)==0 ){ 8920 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 8921 goto meta_command_exit; 8922 } 8923 } 8924 if( p->nSession>=ArraySize(p->aSession) ){ 8925 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); 8926 goto meta_command_exit; 8927 } 8928 pSession = &p->aSession[p->nSession]; 8929 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 8930 if( rc ){ 8931 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 8932 rc = 0; 8933 goto meta_command_exit; 8934 } 8935 pSession->nFilter = 0; 8936 sqlite3session_table_filter(pSession->p, session_filter, pSession); 8937 p->nSession++; 8938 pSession->zName = sqlite3_mprintf("%s", zName); 8939 }else 8940 /* If no command name matches, show a syntax error */ 8941 session_syntax_error: 8942 showHelp(p->out, "session"); 8943 }else 8944#endif 8945 8946#ifdef SQLITE_DEBUG 8947 /* Undocumented commands for internal testing. Subject to change 8948 ** without notice. */ 8949 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 8950 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 8951 int i, v; 8952 for(i=1; i<nArg; i++){ 8953 v = booleanValue(azArg[i]); 8954 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 8955 } 8956 } 8957 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 8958 int i; sqlite3_int64 v; 8959 for(i=1; i<nArg; i++){ 8960 char zBuf[200]; 8961 v = integerValue(azArg[i]); 8962 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 8963 utf8_printf(p->out, "%s", zBuf); 8964 } 8965 } 8966 }else 8967#endif 8968 8969 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 8970 int bIsInit = 0; /* True to initialize the SELFTEST table */ 8971 int bVerbose = 0; /* Verbose output */ 8972 int bSelftestExists; /* True if SELFTEST already exists */ 8973 int i, k; /* Loop counters */ 8974 int nTest = 0; /* Number of tests runs */ 8975 int nErr = 0; /* Number of errors seen */ 8976 ShellText str; /* Answer for a query */ 8977 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 8978 8979 open_db(p,0); 8980 for(i=1; i<nArg; i++){ 8981 const char *z = azArg[i]; 8982 if( z[0]=='-' && z[1]=='-' ) z++; 8983 if( strcmp(z,"-init")==0 ){ 8984 bIsInit = 1; 8985 }else 8986 if( strcmp(z,"-v")==0 ){ 8987 bVerbose++; 8988 }else 8989 { 8990 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 8991 azArg[i], azArg[0]); 8992 raw_printf(stderr, "Should be one of: --init -v\n"); 8993 rc = 1; 8994 goto meta_command_exit; 8995 } 8996 } 8997 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 8998 != SQLITE_OK ){ 8999 bSelftestExists = 0; 9000 }else{ 9001 bSelftestExists = 1; 9002 } 9003 if( bIsInit ){ 9004 createSelftestTable(p); 9005 bSelftestExists = 1; 9006 } 9007 initText(&str); 9008 appendText(&str, "x", 0); 9009 for(k=bSelftestExists; k>=0; k--){ 9010 if( k==1 ){ 9011 rc = sqlite3_prepare_v2(p->db, 9012 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 9013 -1, &pStmt, 0); 9014 }else{ 9015 rc = sqlite3_prepare_v2(p->db, 9016 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 9017 " (1,'run','PRAGMA integrity_check','ok')", 9018 -1, &pStmt, 0); 9019 } 9020 if( rc ){ 9021 raw_printf(stderr, "Error querying the selftest table\n"); 9022 rc = 1; 9023 sqlite3_finalize(pStmt); 9024 goto meta_command_exit; 9025 } 9026 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 9027 int tno = sqlite3_column_int(pStmt, 0); 9028 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 9029 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 9030 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 9031 9032 k = 0; 9033 if( bVerbose>0 ){ 9034 char *zQuote = sqlite3_mprintf("%q", zSql); 9035 printf("%d: %s %s\n", tno, zOp, zSql); 9036 sqlite3_free(zQuote); 9037 } 9038 if( strcmp(zOp,"memo")==0 ){ 9039 utf8_printf(p->out, "%s\n", zSql); 9040 }else 9041 if( strcmp(zOp,"run")==0 ){ 9042 char *zErrMsg = 0; 9043 str.n = 0; 9044 str.z[0] = 0; 9045 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 9046 nTest++; 9047 if( bVerbose ){ 9048 utf8_printf(p->out, "Result: %s\n", str.z); 9049 } 9050 if( rc || zErrMsg ){ 9051 nErr++; 9052 rc = 1; 9053 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 9054 sqlite3_free(zErrMsg); 9055 }else if( strcmp(zAns,str.z)!=0 ){ 9056 nErr++; 9057 rc = 1; 9058 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 9059 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 9060 } 9061 }else 9062 { 9063 utf8_printf(stderr, 9064 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 9065 rc = 1; 9066 break; 9067 } 9068 } /* End loop over rows of content from SELFTEST */ 9069 sqlite3_finalize(pStmt); 9070 } /* End loop over k */ 9071 freeText(&str); 9072 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 9073 }else 9074 9075 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 9076 if( nArg<2 || nArg>3 ){ 9077 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 9078 rc = 1; 9079 } 9080 if( nArg>=2 ){ 9081 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 9082 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 9083 } 9084 if( nArg>=3 ){ 9085 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 9086 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 9087 } 9088 }else 9089 9090 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 9091 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 9092 int i; /* Loop counter */ 9093 int bSchema = 0; /* Also hash the schema */ 9094 int bSeparate = 0; /* Hash each table separately */ 9095 int iSize = 224; /* Hash algorithm to use */ 9096 int bDebug = 0; /* Only show the query that would have run */ 9097 sqlite3_stmt *pStmt; /* For querying tables names */ 9098 char *zSql; /* SQL to be run */ 9099 char *zSep; /* Separator */ 9100 ShellText sSql; /* Complete SQL for the query to run the hash */ 9101 ShellText sQuery; /* Set of queries used to read all content */ 9102 open_db(p, 0); 9103 for(i=1; i<nArg; i++){ 9104 const char *z = azArg[i]; 9105 if( z[0]=='-' ){ 9106 z++; 9107 if( z[0]=='-' ) z++; 9108 if( strcmp(z,"schema")==0 ){ 9109 bSchema = 1; 9110 }else 9111 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 9112 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 9113 ){ 9114 iSize = atoi(&z[5]); 9115 }else 9116 if( strcmp(z,"debug")==0 ){ 9117 bDebug = 1; 9118 }else 9119 { 9120 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9121 azArg[i], azArg[0]); 9122 showHelp(p->out, azArg[0]); 9123 rc = 1; 9124 goto meta_command_exit; 9125 } 9126 }else if( zLike ){ 9127 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 9128 rc = 1; 9129 goto meta_command_exit; 9130 }else{ 9131 zLike = z; 9132 bSeparate = 1; 9133 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 9134 } 9135 } 9136 if( bSchema ){ 9137 zSql = "SELECT lower(name) FROM sqlite_master" 9138 " WHERE type='table' AND coalesce(rootpage,0)>1" 9139 " UNION ALL SELECT 'sqlite_master'" 9140 " ORDER BY 1 collate nocase"; 9141 }else{ 9142 zSql = "SELECT lower(name) FROM sqlite_master" 9143 " WHERE type='table' AND coalesce(rootpage,0)>1" 9144 " AND name NOT LIKE 'sqlite_%'" 9145 " ORDER BY 1 collate nocase"; 9146 } 9147 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9148 initText(&sQuery); 9149 initText(&sSql); 9150 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 9151 zSep = "VALUES("; 9152 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 9153 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 9154 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 9155 if( strncmp(zTab, "sqlite_",7)!=0 ){ 9156 appendText(&sQuery,"SELECT * FROM ", 0); 9157 appendText(&sQuery,zTab,'"'); 9158 appendText(&sQuery," NOT INDEXED;", 0); 9159 }else if( strcmp(zTab, "sqlite_master")==0 ){ 9160 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master" 9161 " ORDER BY name;", 0); 9162 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 9163 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 9164 " ORDER BY name;", 0); 9165 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 9166 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 9167 " ORDER BY tbl,idx;", 0); 9168 }else if( strcmp(zTab, "sqlite_stat4")==0 ){ 9169 appendText(&sQuery, "SELECT * FROM ", 0); 9170 appendText(&sQuery, zTab, 0); 9171 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 9172 } 9173 appendText(&sSql, zSep, 0); 9174 appendText(&sSql, sQuery.z, '\''); 9175 sQuery.n = 0; 9176 appendText(&sSql, ",", 0); 9177 appendText(&sSql, zTab, '\''); 9178 zSep = "),("; 9179 } 9180 sqlite3_finalize(pStmt); 9181 if( bSeparate ){ 9182 zSql = sqlite3_mprintf( 9183 "%s))" 9184 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 9185 " FROM [sha3sum$query]", 9186 sSql.z, iSize); 9187 }else{ 9188 zSql = sqlite3_mprintf( 9189 "%s))" 9190 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 9191 " FROM [sha3sum$query]", 9192 sSql.z, iSize); 9193 } 9194 freeText(&sQuery); 9195 freeText(&sSql); 9196 if( bDebug ){ 9197 utf8_printf(p->out, "%s\n", zSql); 9198 }else{ 9199 shell_exec(p, zSql, 0); 9200 } 9201 sqlite3_free(zSql); 9202 }else 9203 9204#ifndef SQLITE_NOHAVE_SYSTEM 9205 if( c=='s' 9206 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 9207 ){ 9208 char *zCmd; 9209 int i, x; 9210 if( nArg<2 ){ 9211 raw_printf(stderr, "Usage: .system COMMAND\n"); 9212 rc = 1; 9213 goto meta_command_exit; 9214 } 9215 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 9216 for(i=2; i<nArg; i++){ 9217 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 9218 zCmd, azArg[i]); 9219 } 9220 x = system(zCmd); 9221 sqlite3_free(zCmd); 9222 if( x ) raw_printf(stderr, "System command returns %d\n", x); 9223 }else 9224#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 9225 9226 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 9227 static const char *azBool[] = { "off", "on", "trigger", "full"}; 9228 int i; 9229 if( nArg!=1 ){ 9230 raw_printf(stderr, "Usage: .show\n"); 9231 rc = 1; 9232 goto meta_command_exit; 9233 } 9234 utf8_printf(p->out, "%12.12s: %s\n","echo", 9235 azBool[ShellHasFlag(p, SHFLG_Echo)]); 9236 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 9237 utf8_printf(p->out, "%12.12s: %s\n","explain", 9238 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 9239 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 9240 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 9241 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 9242 output_c_string(p->out, p->nullValue); 9243 raw_printf(p->out, "\n"); 9244 utf8_printf(p->out,"%12.12s: %s\n","output", 9245 strlen30(p->outfile) ? p->outfile : "stdout"); 9246 utf8_printf(p->out,"%12.12s: ", "colseparator"); 9247 output_c_string(p->out, p->colSeparator); 9248 raw_printf(p->out, "\n"); 9249 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 9250 output_c_string(p->out, p->rowSeparator); 9251 raw_printf(p->out, "\n"); 9252 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); 9253 utf8_printf(p->out, "%12.12s: ", "width"); 9254 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { 9255 raw_printf(p->out, "%d ", p->colWidth[i]); 9256 } 9257 raw_printf(p->out, "\n"); 9258 utf8_printf(p->out, "%12.12s: %s\n", "filename", 9259 p->zDbFilename ? p->zDbFilename : ""); 9260 }else 9261 9262 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 9263 if( nArg==2 ){ 9264 p->statsOn = (u8)booleanValue(azArg[1]); 9265 }else if( nArg==1 ){ 9266 display_stats(p->db, p, 0); 9267 }else{ 9268 raw_printf(stderr, "Usage: .stats ?on|off?\n"); 9269 rc = 1; 9270 } 9271 }else 9272 9273 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 9274 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 9275 || strncmp(azArg[0], "indexes", n)==0) ) 9276 ){ 9277 sqlite3_stmt *pStmt; 9278 char **azResult; 9279 int nRow, nAlloc; 9280 int ii; 9281 ShellText s; 9282 initText(&s); 9283 open_db(p, 0); 9284 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 9285 if( rc ){ 9286 sqlite3_finalize(pStmt); 9287 return shellDatabaseError(p->db); 9288 } 9289 9290 if( nArg>2 && c=='i' ){ 9291 /* It is an historical accident that the .indexes command shows an error 9292 ** when called with the wrong number of arguments whereas the .tables 9293 ** command does not. */ 9294 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 9295 rc = 1; 9296 sqlite3_finalize(pStmt); 9297 goto meta_command_exit; 9298 } 9299 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 9300 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 9301 if( zDbName==0 ) continue; 9302 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 9303 if( sqlite3_stricmp(zDbName, "main")==0 ){ 9304 appendText(&s, "SELECT name FROM ", 0); 9305 }else{ 9306 appendText(&s, "SELECT ", 0); 9307 appendText(&s, zDbName, '\''); 9308 appendText(&s, "||'.'||name FROM ", 0); 9309 } 9310 appendText(&s, zDbName, '"'); 9311 appendText(&s, ".sqlite_master ", 0); 9312 if( c=='t' ){ 9313 appendText(&s," WHERE type IN ('table','view')" 9314 " AND name NOT LIKE 'sqlite_%'" 9315 " AND name LIKE ?1", 0); 9316 }else{ 9317 appendText(&s," WHERE type='index'" 9318 " AND tbl_name LIKE ?1", 0); 9319 } 9320 } 9321 rc = sqlite3_finalize(pStmt); 9322 appendText(&s, " ORDER BY 1", 0); 9323 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 9324 freeText(&s); 9325 if( rc ) return shellDatabaseError(p->db); 9326 9327 /* Run the SQL statement prepared by the above block. Store the results 9328 ** as an array of nul-terminated strings in azResult[]. */ 9329 nRow = nAlloc = 0; 9330 azResult = 0; 9331 if( nArg>1 ){ 9332 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 9333 }else{ 9334 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 9335 } 9336 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9337 if( nRow>=nAlloc ){ 9338 char **azNew; 9339 int n2 = nAlloc*2 + 10; 9340 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 9341 if( azNew==0 ) shell_out_of_memory(); 9342 nAlloc = n2; 9343 azResult = azNew; 9344 } 9345 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 9346 if( 0==azResult[nRow] ) shell_out_of_memory(); 9347 nRow++; 9348 } 9349 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 9350 rc = shellDatabaseError(p->db); 9351 } 9352 9353 /* Pretty-print the contents of array azResult[] to the output */ 9354 if( rc==0 && nRow>0 ){ 9355 int len, maxlen = 0; 9356 int i, j; 9357 int nPrintCol, nPrintRow; 9358 for(i=0; i<nRow; i++){ 9359 len = strlen30(azResult[i]); 9360 if( len>maxlen ) maxlen = len; 9361 } 9362 nPrintCol = 80/(maxlen+2); 9363 if( nPrintCol<1 ) nPrintCol = 1; 9364 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 9365 for(i=0; i<nPrintRow; i++){ 9366 for(j=i; j<nRow; j+=nPrintRow){ 9367 char *zSp = j<nPrintRow ? "" : " "; 9368 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 9369 azResult[j] ? azResult[j]:""); 9370 } 9371 raw_printf(p->out, "\n"); 9372 } 9373 } 9374 9375 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 9376 sqlite3_free(azResult); 9377 }else 9378 9379 /* Begin redirecting output to the file "testcase-out.txt" */ 9380 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 9381 output_reset(p); 9382 p->out = output_file_open("testcase-out.txt", 0); 9383 if( p->out==0 ){ 9384 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 9385 } 9386 if( nArg>=2 ){ 9387 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 9388 }else{ 9389 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 9390 } 9391 }else 9392 9393#ifndef SQLITE_UNTESTABLE 9394 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 9395 static const struct { 9396 const char *zCtrlName; /* Name of a test-control option */ 9397 int ctrlCode; /* Integer code for that option */ 9398 const char *zUsage; /* Usage notes */ 9399 } aCtrl[] = { 9400 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, 9401 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, 9402 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ 9403 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ 9404 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, 9405 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN" }, 9406 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" },*/ 9407 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, 9408 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" }, 9409 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, 9410 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, 9411 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, 9412#ifdef YYCOVERAGE 9413 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, 9414#endif 9415 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, 9416 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, 9417 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, 9418 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, "SEED ?db?" }, 9419 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE"}, 9420 }; 9421 int testctrl = -1; 9422 int iCtrl = -1; 9423 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 9424 int isOk = 0; 9425 int i, n2; 9426 const char *zCmd = 0; 9427 9428 open_db(p, 0); 9429 zCmd = nArg>=2 ? azArg[1] : "help"; 9430 9431 /* The argument can optionally begin with "-" or "--" */ 9432 if( zCmd[0]=='-' && zCmd[1] ){ 9433 zCmd++; 9434 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 9435 } 9436 9437 /* --help lists all test-controls */ 9438 if( strcmp(zCmd,"help")==0 ){ 9439 utf8_printf(p->out, "Available test-controls:\n"); 9440 for(i=0; i<ArraySize(aCtrl); i++){ 9441 utf8_printf(p->out, " .testctrl %s %s\n", 9442 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 9443 } 9444 rc = 1; 9445 goto meta_command_exit; 9446 } 9447 9448 /* convert testctrl text option to value. allow any unique prefix 9449 ** of the option name, or a numerical value. */ 9450 n2 = strlen30(zCmd); 9451 for(i=0; i<ArraySize(aCtrl); i++){ 9452 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 9453 if( testctrl<0 ){ 9454 testctrl = aCtrl[i].ctrlCode; 9455 iCtrl = i; 9456 }else{ 9457 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 9458 "Use \".testctrl --help\" for help\n", zCmd); 9459 rc = 1; 9460 goto meta_command_exit; 9461 } 9462 } 9463 } 9464 if( testctrl<0 ){ 9465 utf8_printf(stderr,"Error: unknown test-control: %s\n" 9466 "Use \".testctrl --help\" for help\n", zCmd); 9467 }else{ 9468 switch(testctrl){ 9469 9470 /* sqlite3_test_control(int, db, int) */ 9471 case SQLITE_TESTCTRL_OPTIMIZATIONS: 9472 case SQLITE_TESTCTRL_RESERVE: 9473 if( nArg==3 ){ 9474 int opt = (int)strtol(azArg[2], 0, 0); 9475 rc2 = sqlite3_test_control(testctrl, p->db, opt); 9476 isOk = 3; 9477 } 9478 break; 9479 9480 /* sqlite3_test_control(int) */ 9481 case SQLITE_TESTCTRL_PRNG_SAVE: 9482 case SQLITE_TESTCTRL_PRNG_RESTORE: 9483 case SQLITE_TESTCTRL_PRNG_RESET: 9484 case SQLITE_TESTCTRL_BYTEORDER: 9485 if( nArg==2 ){ 9486 rc2 = sqlite3_test_control(testctrl); 9487 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 9488 } 9489 break; 9490 9491 /* sqlite3_test_control(int, uint) */ 9492 case SQLITE_TESTCTRL_PENDING_BYTE: 9493 if( nArg==3 ){ 9494 unsigned int opt = (unsigned int)integerValue(azArg[2]); 9495 rc2 = sqlite3_test_control(testctrl, opt); 9496 isOk = 3; 9497 } 9498 break; 9499 9500 /* sqlite3_test_control(int, int, sqlite3*) */ 9501 case SQLITE_TESTCTRL_PRNG_SEED: 9502 if( nArg==3 || nArg==4 ){ 9503 int ii = (int)integerValue(azArg[2]); 9504 sqlite3 *db; 9505 if( ii==0 && strcmp(azArg[2],"random")==0 ){ 9506 sqlite3_randomness(sizeof(ii),&ii); 9507 printf("-- random seed: %d\n", ii); 9508 } 9509 if( nArg==3 ){ 9510 db = 0; 9511 }else{ 9512 db = p->db; 9513 /* Make sure the schema has been loaded */ 9514 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 9515 } 9516 rc2 = sqlite3_test_control(testctrl, ii, db); 9517 isOk = 3; 9518 } 9519 break; 9520 9521 /* sqlite3_test_control(int, int) */ 9522 case SQLITE_TESTCTRL_ASSERT: 9523 case SQLITE_TESTCTRL_ALWAYS: 9524 if( nArg==3 ){ 9525 int opt = booleanValue(azArg[2]); 9526 rc2 = sqlite3_test_control(testctrl, opt); 9527 isOk = 1; 9528 } 9529 break; 9530 9531 /* sqlite3_test_control(int, int) */ 9532 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 9533 case SQLITE_TESTCTRL_NEVER_CORRUPT: 9534 if( nArg==3 ){ 9535 int opt = booleanValue(azArg[2]); 9536 rc2 = sqlite3_test_control(testctrl, opt); 9537 isOk = 3; 9538 } 9539 break; 9540 9541 /* sqlite3_test_control(sqlite3*) */ 9542 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 9543 rc2 = sqlite3_test_control(testctrl, p->db); 9544 isOk = 3; 9545 break; 9546 9547 case SQLITE_TESTCTRL_IMPOSTER: 9548 if( nArg==5 ){ 9549 rc2 = sqlite3_test_control(testctrl, p->db, 9550 azArg[2], 9551 integerValue(azArg[3]), 9552 integerValue(azArg[4])); 9553 isOk = 3; 9554 } 9555 break; 9556 9557#ifdef YYCOVERAGE 9558 case SQLITE_TESTCTRL_PARSER_COVERAGE: 9559 if( nArg==2 ){ 9560 sqlite3_test_control(testctrl, p->out); 9561 isOk = 3; 9562 } 9563#endif 9564 } 9565 } 9566 if( isOk==0 && iCtrl>=0 ){ 9567 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 9568 rc = 1; 9569 }else if( isOk==1 ){ 9570 raw_printf(p->out, "%d\n", rc2); 9571 }else if( isOk==2 ){ 9572 raw_printf(p->out, "0x%08x\n", rc2); 9573 } 9574 }else 9575#endif /* !defined(SQLITE_UNTESTABLE) */ 9576 9577 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 9578 open_db(p, 0); 9579 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 9580 }else 9581 9582 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 9583 if( nArg==2 ){ 9584 enableTimer = booleanValue(azArg[1]); 9585 if( enableTimer && !HAS_TIMER ){ 9586 raw_printf(stderr, "Error: timer not available on this system.\n"); 9587 enableTimer = 0; 9588 } 9589 }else{ 9590 raw_printf(stderr, "Usage: .timer on|off\n"); 9591 rc = 1; 9592 } 9593 }else 9594 9595#ifndef SQLITE_OMIT_TRACE 9596 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 9597 int mType = 0; 9598 int jj; 9599 open_db(p, 0); 9600 for(jj=1; jj<nArg; jj++){ 9601 const char *z = azArg[jj]; 9602 if( z[0]=='-' ){ 9603 if( optionMatch(z, "expanded") ){ 9604 p->eTraceType = SHELL_TRACE_EXPANDED; 9605 } 9606#ifdef SQLITE_ENABLE_NORMALIZE 9607 else if( optionMatch(z, "normalized") ){ 9608 p->eTraceType = SHELL_TRACE_NORMALIZED; 9609 } 9610#endif 9611 else if( optionMatch(z, "plain") ){ 9612 p->eTraceType = SHELL_TRACE_PLAIN; 9613 } 9614 else if( optionMatch(z, "profile") ){ 9615 mType |= SQLITE_TRACE_PROFILE; 9616 } 9617 else if( optionMatch(z, "row") ){ 9618 mType |= SQLITE_TRACE_ROW; 9619 } 9620 else if( optionMatch(z, "stmt") ){ 9621 mType |= SQLITE_TRACE_STMT; 9622 } 9623 else if( optionMatch(z, "close") ){ 9624 mType |= SQLITE_TRACE_CLOSE; 9625 } 9626 else { 9627 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 9628 rc = 1; 9629 goto meta_command_exit; 9630 } 9631 }else{ 9632 output_file_close(p->traceOut); 9633 p->traceOut = output_file_open(azArg[1], 0); 9634 } 9635 } 9636 if( p->traceOut==0 ){ 9637 sqlite3_trace_v2(p->db, 0, 0, 0); 9638 }else{ 9639 if( mType==0 ) mType = SQLITE_TRACE_STMT; 9640 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 9641 } 9642 }else 9643#endif /* !defined(SQLITE_OMIT_TRACE) */ 9644 9645#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) 9646 if( c=='u' && strncmp(azArg[0], "unmodule", n)==0 ){ 9647 int ii; 9648 int lenOpt; 9649 char *zOpt; 9650 if( nArg<2 ){ 9651 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n"); 9652 rc = 1; 9653 goto meta_command_exit; 9654 } 9655 open_db(p, 0); 9656 zOpt = azArg[1]; 9657 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; 9658 lenOpt = (int)strlen(zOpt); 9659 if( lenOpt>=3 && strncmp(zOpt, "-allexcept",lenOpt)==0 ){ 9660 assert( azArg[nArg]==0 ); 9661 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); 9662 }else{ 9663 for(ii=1; ii<nArg; ii++){ 9664 sqlite3_create_module(p->db, azArg[ii], 0, 0); 9665 } 9666 } 9667 }else 9668#endif 9669 9670#if SQLITE_USER_AUTHENTICATION 9671 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 9672 if( nArg<2 ){ 9673 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 9674 rc = 1; 9675 goto meta_command_exit; 9676 } 9677 open_db(p, 0); 9678 if( strcmp(azArg[1],"login")==0 ){ 9679 if( nArg!=4 ){ 9680 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 9681 rc = 1; 9682 goto meta_command_exit; 9683 } 9684 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], 9685 strlen30(azArg[3])); 9686 if( rc ){ 9687 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 9688 rc = 1; 9689 } 9690 }else if( strcmp(azArg[1],"add")==0 ){ 9691 if( nArg!=5 ){ 9692 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 9693 rc = 1; 9694 goto meta_command_exit; 9695 } 9696 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9697 booleanValue(azArg[4])); 9698 if( rc ){ 9699 raw_printf(stderr, "User-Add failed: %d\n", rc); 9700 rc = 1; 9701 } 9702 }else if( strcmp(azArg[1],"edit")==0 ){ 9703 if( nArg!=5 ){ 9704 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 9705 rc = 1; 9706 goto meta_command_exit; 9707 } 9708 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 9709 booleanValue(azArg[4])); 9710 if( rc ){ 9711 raw_printf(stderr, "User-Edit failed: %d\n", rc); 9712 rc = 1; 9713 } 9714 }else if( strcmp(azArg[1],"delete")==0 ){ 9715 if( nArg!=3 ){ 9716 raw_printf(stderr, "Usage: .user delete USER\n"); 9717 rc = 1; 9718 goto meta_command_exit; 9719 } 9720 rc = sqlite3_user_delete(p->db, azArg[2]); 9721 if( rc ){ 9722 raw_printf(stderr, "User-Delete failed: %d\n", rc); 9723 rc = 1; 9724 } 9725 }else{ 9726 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 9727 rc = 1; 9728 goto meta_command_exit; 9729 } 9730 }else 9731#endif /* SQLITE_USER_AUTHENTICATION */ 9732 9733 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 9734 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 9735 sqlite3_libversion(), sqlite3_sourceid()); 9736#if SQLITE_HAVE_ZLIB 9737 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 9738#endif 9739#define CTIMEOPT_VAL_(opt) #opt 9740#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 9741#if defined(__clang__) && defined(__clang_major__) 9742 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 9743 CTIMEOPT_VAL(__clang_minor__) "." 9744 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 9745#elif defined(_MSC_VER) 9746 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 9747#elif defined(__GNUC__) && defined(__VERSION__) 9748 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 9749#endif 9750 }else 9751 9752 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 9753 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9754 sqlite3_vfs *pVfs = 0; 9755 if( p->db ){ 9756 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 9757 if( pVfs ){ 9758 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 9759 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9760 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9761 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9762 } 9763 } 9764 }else 9765 9766 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 9767 sqlite3_vfs *pVfs; 9768 sqlite3_vfs *pCurrent = 0; 9769 if( p->db ){ 9770 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 9771 } 9772 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 9773 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 9774 pVfs==pCurrent ? " <--- CURRENT" : ""); 9775 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 9776 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 9777 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 9778 if( pVfs->pNext ){ 9779 raw_printf(p->out, "-----------------------------------\n"); 9780 } 9781 } 9782 }else 9783 9784 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 9785 const char *zDbName = nArg==2 ? azArg[1] : "main"; 9786 char *zVfsName = 0; 9787 if( p->db ){ 9788 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 9789 if( zVfsName ){ 9790 utf8_printf(p->out, "%s\n", zVfsName); 9791 sqlite3_free(zVfsName); 9792 } 9793 } 9794 }else 9795 9796#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 9797 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 9798 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; 9799 }else 9800#endif 9801 9802 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 9803 int j; 9804 assert( nArg<=ArraySize(azArg) ); 9805 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ 9806 p->colWidth[j-1] = (int)integerValue(azArg[j]); 9807 } 9808 }else 9809 9810 { 9811 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 9812 " \"%s\". Enter \".help\" for help\n", azArg[0]); 9813 rc = 1; 9814 } 9815 9816meta_command_exit: 9817 if( p->outCount ){ 9818 p->outCount--; 9819 if( p->outCount==0 ) output_reset(p); 9820 } 9821 return rc; 9822} 9823 9824/* 9825** Return TRUE if a semicolon occurs anywhere in the first N characters 9826** of string z[]. 9827*/ 9828static int line_contains_semicolon(const char *z, int N){ 9829 int i; 9830 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } 9831 return 0; 9832} 9833 9834/* 9835** Test to see if a line consists entirely of whitespace. 9836*/ 9837static int _all_whitespace(const char *z){ 9838 for(; *z; z++){ 9839 if( IsSpace(z[0]) ) continue; 9840 if( *z=='/' && z[1]=='*' ){ 9841 z += 2; 9842 while( *z && (*z!='*' || z[1]!='/') ){ z++; } 9843 if( *z==0 ) return 0; 9844 z++; 9845 continue; 9846 } 9847 if( *z=='-' && z[1]=='-' ){ 9848 z += 2; 9849 while( *z && *z!='\n' ){ z++; } 9850 if( *z==0 ) return 1; 9851 continue; 9852 } 9853 return 0; 9854 } 9855 return 1; 9856} 9857 9858/* 9859** Return TRUE if the line typed in is an SQL command terminator other 9860** than a semi-colon. The SQL Server style "go" command is understood 9861** as is the Oracle "/". 9862*/ 9863static int line_is_command_terminator(const char *zLine){ 9864 while( IsSpace(zLine[0]) ){ zLine++; }; 9865 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ 9866 return 1; /* Oracle */ 9867 } 9868 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' 9869 && _all_whitespace(&zLine[2]) ){ 9870 return 1; /* SQL Server */ 9871 } 9872 return 0; 9873} 9874 9875/* 9876** We need a default sqlite3_complete() implementation to use in case 9877** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 9878** any arbitrary text is a complete SQL statement. This is not very 9879** user-friendly, but it does seem to work. 9880*/ 9881#ifdef SQLITE_OMIT_COMPLETE 9882#define sqlite3_complete(x) 1 9883#endif 9884 9885/* 9886** Return true if zSql is a complete SQL statement. Return false if it 9887** ends in the middle of a string literal or C-style comment. 9888*/ 9889static int line_is_complete(char *zSql, int nSql){ 9890 int rc; 9891 if( zSql==0 ) return 1; 9892 zSql[nSql] = ';'; 9893 zSql[nSql+1] = 0; 9894 rc = sqlite3_complete(zSql); 9895 zSql[nSql] = 0; 9896 return rc; 9897} 9898 9899/* 9900** Run a single line of SQL. Return the number of errors. 9901*/ 9902static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 9903 int rc; 9904 char *zErrMsg = 0; 9905 9906 open_db(p, 0); 9907 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 9908 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 9909 BEGIN_TIMER; 9910 rc = shell_exec(p, zSql, &zErrMsg); 9911 END_TIMER; 9912 if( rc || zErrMsg ){ 9913 char zPrefix[100]; 9914 if( in!=0 || !stdin_is_interactive ){ 9915 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 9916 "Error: near line %d:", startline); 9917 }else{ 9918 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 9919 } 9920 if( zErrMsg!=0 ){ 9921 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 9922 sqlite3_free(zErrMsg); 9923 zErrMsg = 0; 9924 }else{ 9925 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 9926 } 9927 return 1; 9928 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 9929 raw_printf(p->out, "changes: %3d total_changes: %d\n", 9930 sqlite3_changes(p->db), sqlite3_total_changes(p->db)); 9931 } 9932 return 0; 9933} 9934 9935 9936/* 9937** Read input from *in and process it. If *in==0 then input 9938** is interactive - the user is typing it it. Otherwise, input 9939** is coming from a file or device. A prompt is issued and history 9940** is saved only if input is interactive. An interrupt signal will 9941** cause this routine to exit immediately, unless input is interactive. 9942** 9943** Return the number of errors. 9944*/ 9945static int process_input(ShellState *p){ 9946 char *zLine = 0; /* A single input line */ 9947 char *zSql = 0; /* Accumulated SQL text */ 9948 int nLine; /* Length of current line */ 9949 int nSql = 0; /* Bytes of zSql[] used */ 9950 int nAlloc = 0; /* Allocated zSql[] space */ 9951 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ 9952 int rc; /* Error code */ 9953 int errCnt = 0; /* Number of errors seen */ 9954 int startline = 0; /* Line number for start of current input */ 9955 9956 p->lineno = 0; 9957 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 9958 fflush(p->out); 9959 zLine = one_input_line(p->in, zLine, nSql>0); 9960 if( zLine==0 ){ 9961 /* End of input */ 9962 if( p->in==0 && stdin_is_interactive ) printf("\n"); 9963 break; 9964 } 9965 if( seenInterrupt ){ 9966 if( p->in!=0 ) break; 9967 seenInterrupt = 0; 9968 } 9969 p->lineno++; 9970 if( nSql==0 && _all_whitespace(zLine) ){ 9971 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9972 continue; 9973 } 9974 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 9975 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 9976 if( zLine[0]=='.' ){ 9977 rc = do_meta_command(zLine, p); 9978 if( rc==2 ){ /* exit requested */ 9979 break; 9980 }else if( rc ){ 9981 errCnt++; 9982 } 9983 } 9984 continue; 9985 } 9986 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ 9987 memcpy(zLine,";",2); 9988 } 9989 nLine = strlen30(zLine); 9990 if( nSql+nLine+2>=nAlloc ){ 9991 nAlloc = nSql+nLine+100; 9992 zSql = realloc(zSql, nAlloc); 9993 if( zSql==0 ) shell_out_of_memory(); 9994 } 9995 nSqlPrior = nSql; 9996 if( nSql==0 ){ 9997 int i; 9998 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 9999 assert( nAlloc>0 && zSql!=0 ); 10000 memcpy(zSql, zLine+i, nLine+1-i); 10001 startline = p->lineno; 10002 nSql = nLine-i; 10003 }else{ 10004 zSql[nSql++] = '\n'; 10005 memcpy(zSql+nSql, zLine, nLine+1); 10006 nSql += nLine; 10007 } 10008 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) 10009 && sqlite3_complete(zSql) ){ 10010 errCnt += runOneSqlLine(p, zSql, p->in, startline); 10011 nSql = 0; 10012 if( p->outCount ){ 10013 output_reset(p); 10014 p->outCount = 0; 10015 }else{ 10016 clearTempFile(p); 10017 } 10018 }else if( nSql && _all_whitespace(zSql) ){ 10019 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 10020 nSql = 0; 10021 } 10022 } 10023 if( nSql && !_all_whitespace(zSql) ){ 10024 errCnt += runOneSqlLine(p, zSql, p->in, startline); 10025 } 10026 free(zSql); 10027 free(zLine); 10028 return errCnt>0; 10029} 10030 10031/* 10032** Return a pathname which is the user's home directory. A 10033** 0 return indicates an error of some kind. 10034*/ 10035static char *find_home_dir(int clearFlag){ 10036 static char *home_dir = NULL; 10037 if( clearFlag ){ 10038 free(home_dir); 10039 home_dir = 0; 10040 return 0; 10041 } 10042 if( home_dir ) return home_dir; 10043 10044#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 10045 && !defined(__RTP__) && !defined(_WRS_KERNEL) 10046 { 10047 struct passwd *pwent; 10048 uid_t uid = getuid(); 10049 if( (pwent=getpwuid(uid)) != NULL) { 10050 home_dir = pwent->pw_dir; 10051 } 10052 } 10053#endif 10054 10055#if defined(_WIN32_WCE) 10056 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 10057 */ 10058 home_dir = "/"; 10059#else 10060 10061#if defined(_WIN32) || defined(WIN32) 10062 if (!home_dir) { 10063 home_dir = getenv("USERPROFILE"); 10064 } 10065#endif 10066 10067 if (!home_dir) { 10068 home_dir = getenv("HOME"); 10069 } 10070 10071#if defined(_WIN32) || defined(WIN32) 10072 if (!home_dir) { 10073 char *zDrive, *zPath; 10074 int n; 10075 zDrive = getenv("HOMEDRIVE"); 10076 zPath = getenv("HOMEPATH"); 10077 if( zDrive && zPath ){ 10078 n = strlen30(zDrive) + strlen30(zPath) + 1; 10079 home_dir = malloc( n ); 10080 if( home_dir==0 ) return 0; 10081 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 10082 return home_dir; 10083 } 10084 home_dir = "c:\\"; 10085 } 10086#endif 10087 10088#endif /* !_WIN32_WCE */ 10089 10090 if( home_dir ){ 10091 int n = strlen30(home_dir) + 1; 10092 char *z = malloc( n ); 10093 if( z ) memcpy(z, home_dir, n); 10094 home_dir = z; 10095 } 10096 10097 return home_dir; 10098} 10099 10100/* 10101** Read input from the file given by sqliterc_override. Or if that 10102** parameter is NULL, take input from ~/.sqliterc 10103** 10104** Returns the number of errors. 10105*/ 10106static void process_sqliterc( 10107 ShellState *p, /* Configuration data */ 10108 const char *sqliterc_override /* Name of config file. NULL to use default */ 10109){ 10110 char *home_dir = NULL; 10111 const char *sqliterc = sqliterc_override; 10112 char *zBuf = 0; 10113 FILE *inSaved = p->in; 10114 int savedLineno = p->lineno; 10115 10116 if (sqliterc == NULL) { 10117 home_dir = find_home_dir(0); 10118 if( home_dir==0 ){ 10119 raw_printf(stderr, "-- warning: cannot find home directory;" 10120 " cannot read ~/.sqliterc\n"); 10121 return; 10122 } 10123 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 10124 sqliterc = zBuf; 10125 } 10126 p->in = fopen(sqliterc,"rb"); 10127 if( p->in ){ 10128 if( stdin_is_interactive ){ 10129 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 10130 } 10131 process_input(p); 10132 fclose(p->in); 10133 } 10134 p->in = inSaved; 10135 p->lineno = savedLineno; 10136 sqlite3_free(zBuf); 10137} 10138 10139/* 10140** Show available command line options 10141*/ 10142static const char zOptions[] = 10143#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 10144 " -A ARGS... run \".archive ARGS\" and exit\n" 10145#endif 10146 " -append append the database to the end of the file\n" 10147 " -ascii set output mode to 'ascii'\n" 10148 " -bail stop after hitting an error\n" 10149 " -batch force batch I/O\n" 10150 " -column set output mode to 'column'\n" 10151 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 10152 " -csv set output mode to 'csv'\n" 10153#if defined(SQLITE_ENABLE_DESERIALIZE) 10154 " -deserialize open the database using sqlite3_deserialize()\n" 10155#endif 10156 " -echo print commands before execution\n" 10157 " -init FILENAME read/process named file\n" 10158 " -[no]header turn headers on or off\n" 10159#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 10160 " -heap SIZE Size of heap for memsys3 or memsys5\n" 10161#endif 10162 " -help show this message\n" 10163 " -html set output mode to HTML\n" 10164 " -interactive force interactive I/O\n" 10165 " -line set output mode to 'line'\n" 10166 " -list set output mode to 'list'\n" 10167 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 10168#if defined(SQLITE_ENABLE_DESERIALIZE) 10169 " -maxsize N maximum size for a --deserialize database\n" 10170#endif 10171 " -memtrace trace all memory allocations and deallocations\n" 10172 " -mmap N default mmap size set to N\n" 10173#ifdef SQLITE_ENABLE_MULTIPLEX 10174 " -multiplex enable the multiplexor VFS\n" 10175#endif 10176 " -newline SEP set output row separator. Default: '\\n'\n" 10177 " -nofollow refuse to open symbolic links to database files\n" 10178 " -nullvalue TEXT set text string for NULL values. Default ''\n" 10179 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 10180 " -quote set output mode to 'quote'\n" 10181 " -readonly open the database read-only\n" 10182 " -separator SEP set output column separator. Default: '|'\n" 10183#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10184 " -sorterref SIZE sorter references threshold size\n" 10185#endif 10186 " -stats print memory stats before each finalize\n" 10187 " -version show SQLite version\n" 10188 " -vfs NAME use NAME as the default VFS\n" 10189#ifdef SQLITE_ENABLE_VFSTRACE 10190 " -vfstrace enable tracing of all VFS calls\n" 10191#endif 10192#ifdef SQLITE_HAVE_ZLIB 10193 " -zip open the file as a ZIP Archive\n" 10194#endif 10195; 10196static void usage(int showDetail){ 10197 utf8_printf(stderr, 10198 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 10199 "FILENAME is the name of an SQLite database. A new database is created\n" 10200 "if the file does not previously exist.\n", Argv0); 10201 if( showDetail ){ 10202 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 10203 }else{ 10204 raw_printf(stderr, "Use the -help option for additional information\n"); 10205 } 10206 exit(1); 10207} 10208 10209/* 10210** Internal check: Verify that the SQLite is uninitialized. Print a 10211** error message if it is initialized. 10212*/ 10213static void verify_uninitialized(void){ 10214 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 10215 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 10216 " initialization.\n"); 10217 } 10218} 10219 10220/* 10221** Initialize the state information in data 10222*/ 10223static void main_init(ShellState *data) { 10224 memset(data, 0, sizeof(*data)); 10225 data->normalMode = data->cMode = data->mode = MODE_List; 10226 data->autoExplain = 1; 10227 memcpy(data->colSeparator,SEP_Column, 2); 10228 memcpy(data->rowSeparator,SEP_Row, 2); 10229 data->showHeader = 0; 10230 data->shellFlgs = SHFLG_Lookaside; 10231 verify_uninitialized(); 10232 sqlite3_config(SQLITE_CONFIG_URI, 1); 10233 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 10234 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 10235 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 10236 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 10237} 10238 10239/* 10240** Output text to the console in a font that attracts extra attention. 10241*/ 10242#ifdef _WIN32 10243static void printBold(const char *zText){ 10244 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 10245 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 10246 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 10247 SetConsoleTextAttribute(out, 10248 FOREGROUND_RED|FOREGROUND_INTENSITY 10249 ); 10250 printf("%s", zText); 10251 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 10252} 10253#else 10254static void printBold(const char *zText){ 10255 printf("\033[1m%s\033[0m", zText); 10256} 10257#endif 10258 10259/* 10260** Get the argument to an --option. Throw an error and die if no argument 10261** is available. 10262*/ 10263static char *cmdline_option_value(int argc, char **argv, int i){ 10264 if( i==argc ){ 10265 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 10266 argv[0], argv[argc-1]); 10267 exit(1); 10268 } 10269 return argv[i]; 10270} 10271 10272#ifndef SQLITE_SHELL_IS_UTF8 10273# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) 10274# define SQLITE_SHELL_IS_UTF8 (0) 10275# else 10276# define SQLITE_SHELL_IS_UTF8 (1) 10277# endif 10278#endif 10279 10280#if SQLITE_SHELL_IS_UTF8 10281int SQLITE_CDECL main(int argc, char **argv){ 10282#else 10283int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 10284 char **argv; 10285#endif 10286 char *zErrMsg = 0; 10287 ShellState data; 10288 const char *zInitFile = 0; 10289 int i; 10290 int rc = 0; 10291 int warnInmemoryDb = 0; 10292 int readStdin = 1; 10293 int nCmd = 0; 10294 char **azCmd = 0; 10295 const char *zVfs = 0; /* Value of -vfs command-line option */ 10296#if !SQLITE_SHELL_IS_UTF8 10297 char **argvToFree = 0; 10298 int argcToFree = 0; 10299#endif 10300 10301 setBinaryMode(stdin, 0); 10302 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 10303 stdin_is_interactive = isatty(0); 10304 stdout_is_console = isatty(1); 10305 10306#ifdef SQLITE_DEBUG 10307 registerOomSimulator(); 10308#endif 10309 10310#if !defined(_WIN32_WCE) 10311 if( getenv("SQLITE_DEBUG_BREAK") ){ 10312 if( isatty(0) && isatty(2) ){ 10313 fprintf(stderr, 10314 "attach debugger to process %d and press any key to continue.\n", 10315 GETPID()); 10316 fgetc(stdin); 10317 }else{ 10318#if defined(_WIN32) || defined(WIN32) 10319 DebugBreak(); 10320#elif defined(SIGTRAP) 10321 raise(SIGTRAP); 10322#endif 10323 } 10324 } 10325#endif 10326 10327#if USE_SYSTEM_SQLITE+0!=1 10328 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 10329 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 10330 sqlite3_sourceid(), SQLITE_SOURCE_ID); 10331 exit(1); 10332 } 10333#endif 10334 main_init(&data); 10335 10336 /* On Windows, we must translate command-line arguments into UTF-8. 10337 ** The SQLite memory allocator subsystem has to be enabled in order to 10338 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 10339 ** subsequent sqlite3_config() calls will work. So copy all results into 10340 ** memory that does not come from the SQLite memory allocator. 10341 */ 10342#if !SQLITE_SHELL_IS_UTF8 10343 sqlite3_initialize(); 10344 argvToFree = malloc(sizeof(argv[0])*argc*2); 10345 argcToFree = argc; 10346 argv = argvToFree + argc; 10347 if( argv==0 ) shell_out_of_memory(); 10348 for(i=0; i<argc; i++){ 10349 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 10350 int n; 10351 if( z==0 ) shell_out_of_memory(); 10352 n = (int)strlen(z); 10353 argv[i] = malloc( n+1 ); 10354 if( argv[i]==0 ) shell_out_of_memory(); 10355 memcpy(argv[i], z, n+1); 10356 argvToFree[i] = argv[i]; 10357 sqlite3_free(z); 10358 } 10359 sqlite3_shutdown(); 10360#endif 10361 10362 assert( argc>=1 && argv && argv[0] ); 10363 Argv0 = argv[0]; 10364 10365 /* Make sure we have a valid signal handler early, before anything 10366 ** else is done. 10367 */ 10368#ifdef SIGINT 10369 signal(SIGINT, interrupt_handler); 10370#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 10371 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 10372#endif 10373 10374#ifdef SQLITE_SHELL_DBNAME_PROC 10375 { 10376 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 10377 ** of a C-function that will provide the name of the database file. Use 10378 ** this compile-time option to embed this shell program in larger 10379 ** applications. */ 10380 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 10381 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); 10382 warnInmemoryDb = 0; 10383 } 10384#endif 10385 10386 /* Do an initial pass through the command-line argument to locate 10387 ** the name of the database file, the name of the initialization file, 10388 ** the size of the alternative malloc heap, 10389 ** and the first command to execute. 10390 */ 10391 verify_uninitialized(); 10392 for(i=1; i<argc; i++){ 10393 char *z; 10394 z = argv[i]; 10395 if( z[0]!='-' ){ 10396 if( data.zDbFilename==0 ){ 10397 data.zDbFilename = z; 10398 }else{ 10399 /* Excesss arguments are interpreted as SQL (or dot-commands) and 10400 ** mean that nothing is read from stdin */ 10401 readStdin = 0; 10402 nCmd++; 10403 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 10404 if( azCmd==0 ) shell_out_of_memory(); 10405 azCmd[nCmd-1] = z; 10406 } 10407 } 10408 if( z[1]=='-' ) z++; 10409 if( strcmp(z,"-separator")==0 10410 || strcmp(z,"-nullvalue")==0 10411 || strcmp(z,"-newline")==0 10412 || strcmp(z,"-cmd")==0 10413 ){ 10414 (void)cmdline_option_value(argc, argv, ++i); 10415 }else if( strcmp(z,"-init")==0 ){ 10416 zInitFile = cmdline_option_value(argc, argv, ++i); 10417 }else if( strcmp(z,"-batch")==0 ){ 10418 /* Need to check for batch mode here to so we can avoid printing 10419 ** informational messages (like from process_sqliterc) before 10420 ** we do the actual processing of arguments later in a second pass. 10421 */ 10422 stdin_is_interactive = 0; 10423 }else if( strcmp(z,"-heap")==0 ){ 10424#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 10425 const char *zSize; 10426 sqlite3_int64 szHeap; 10427 10428 zSize = cmdline_option_value(argc, argv, ++i); 10429 szHeap = integerValue(zSize); 10430 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 10431 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 10432#else 10433 (void)cmdline_option_value(argc, argv, ++i); 10434#endif 10435 }else if( strcmp(z,"-pagecache")==0 ){ 10436 int n, sz; 10437 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10438 if( sz>70000 ) sz = 70000; 10439 if( sz<0 ) sz = 0; 10440 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10441 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 10442 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 10443 data.shellFlgs |= SHFLG_Pagecache; 10444 }else if( strcmp(z,"-lookaside")==0 ){ 10445 int n, sz; 10446 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10447 if( sz<0 ) sz = 0; 10448 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 10449 if( n<0 ) n = 0; 10450 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 10451 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 10452#ifdef SQLITE_ENABLE_VFSTRACE 10453 }else if( strcmp(z,"-vfstrace")==0 ){ 10454 extern int vfstrace_register( 10455 const char *zTraceName, 10456 const char *zOldVfsName, 10457 int (*xOut)(const char*,void*), 10458 void *pOutArg, 10459 int makeDefault 10460 ); 10461 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 10462#endif 10463#ifdef SQLITE_ENABLE_MULTIPLEX 10464 }else if( strcmp(z,"-multiplex")==0 ){ 10465 extern int sqlite3_multiple_initialize(const char*,int); 10466 sqlite3_multiplex_initialize(0, 1); 10467#endif 10468 }else if( strcmp(z,"-mmap")==0 ){ 10469 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 10470 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 10471#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10472 }else if( strcmp(z,"-sorterref")==0 ){ 10473 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 10474 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 10475#endif 10476 }else if( strcmp(z,"-vfs")==0 ){ 10477 zVfs = cmdline_option_value(argc, argv, ++i); 10478#ifdef SQLITE_HAVE_ZLIB 10479 }else if( strcmp(z,"-zip")==0 ){ 10480 data.openMode = SHELL_OPEN_ZIPFILE; 10481#endif 10482 }else if( strcmp(z,"-append")==0 ){ 10483 data.openMode = SHELL_OPEN_APPENDVFS; 10484#ifdef SQLITE_ENABLE_DESERIALIZE 10485 }else if( strcmp(z,"-deserialize")==0 ){ 10486 data.openMode = SHELL_OPEN_DESERIALIZE; 10487 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10488 data.szMax = integerValue(argv[++i]); 10489#endif 10490 }else if( strcmp(z,"-readonly")==0 ){ 10491 data.openMode = SHELL_OPEN_READONLY; 10492 }else if( strcmp(z,"-nofollow")==0 ){ 10493 data.openFlags = SQLITE_OPEN_NOFOLLOW; 10494#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10495 }else if( strncmp(z, "-A",2)==0 ){ 10496 /* All remaining command-line arguments are passed to the ".archive" 10497 ** command, so ignore them */ 10498 break; 10499#endif 10500 }else if( strcmp(z, "-memtrace")==0 ){ 10501 sqlite3MemTraceActivate(stderr); 10502 } 10503 } 10504 verify_uninitialized(); 10505 10506 10507#ifdef SQLITE_SHELL_INIT_PROC 10508 { 10509 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 10510 ** of a C-function that will perform initialization actions on SQLite that 10511 ** occur just before or after sqlite3_initialize(). Use this compile-time 10512 ** option to embed this shell program in larger applications. */ 10513 extern void SQLITE_SHELL_INIT_PROC(void); 10514 SQLITE_SHELL_INIT_PROC(); 10515 } 10516#else 10517 /* All the sqlite3_config() calls have now been made. So it is safe 10518 ** to call sqlite3_initialize() and process any command line -vfs option. */ 10519 sqlite3_initialize(); 10520#endif 10521 10522 if( zVfs ){ 10523 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 10524 if( pVfs ){ 10525 sqlite3_vfs_register(pVfs, 1); 10526 }else{ 10527 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 10528 exit(1); 10529 } 10530 } 10531 10532 if( data.zDbFilename==0 ){ 10533#ifndef SQLITE_OMIT_MEMORYDB 10534 data.zDbFilename = ":memory:"; 10535 warnInmemoryDb = argc==1; 10536#else 10537 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 10538 return 1; 10539#endif 10540 } 10541 data.out = stdout; 10542 sqlite3_appendvfs_init(0,0,0); 10543 10544 /* Go ahead and open the database file if it already exists. If the 10545 ** file does not exist, delay opening it. This prevents empty database 10546 ** files from being created if a user mistypes the database name argument 10547 ** to the sqlite command-line tool. 10548 */ 10549 if( access(data.zDbFilename, 0)==0 ){ 10550 open_db(&data, 0); 10551 } 10552 10553 /* Process the initialization file if there is one. If no -init option 10554 ** is given on the command line, look for a file named ~/.sqliterc and 10555 ** try to process it. 10556 */ 10557 process_sqliterc(&data,zInitFile); 10558 10559 /* Make a second pass through the command-line argument and set 10560 ** options. This second pass is delayed until after the initialization 10561 ** file is processed so that the command-line arguments will override 10562 ** settings in the initialization file. 10563 */ 10564 for(i=1; i<argc; i++){ 10565 char *z = argv[i]; 10566 if( z[0]!='-' ) continue; 10567 if( z[1]=='-' ){ z++; } 10568 if( strcmp(z,"-init")==0 ){ 10569 i++; 10570 }else if( strcmp(z,"-html")==0 ){ 10571 data.mode = MODE_Html; 10572 }else if( strcmp(z,"-list")==0 ){ 10573 data.mode = MODE_List; 10574 }else if( strcmp(z,"-quote")==0 ){ 10575 data.mode = MODE_Quote; 10576 }else if( strcmp(z,"-line")==0 ){ 10577 data.mode = MODE_Line; 10578 }else if( strcmp(z,"-column")==0 ){ 10579 data.mode = MODE_Column; 10580 }else if( strcmp(z,"-csv")==0 ){ 10581 data.mode = MODE_Csv; 10582 memcpy(data.colSeparator,",",2); 10583#ifdef SQLITE_HAVE_ZLIB 10584 }else if( strcmp(z,"-zip")==0 ){ 10585 data.openMode = SHELL_OPEN_ZIPFILE; 10586#endif 10587 }else if( strcmp(z,"-append")==0 ){ 10588 data.openMode = SHELL_OPEN_APPENDVFS; 10589#ifdef SQLITE_ENABLE_DESERIALIZE 10590 }else if( strcmp(z,"-deserialize")==0 ){ 10591 data.openMode = SHELL_OPEN_DESERIALIZE; 10592 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 10593 data.szMax = integerValue(argv[++i]); 10594#endif 10595 }else if( strcmp(z,"-readonly")==0 ){ 10596 data.openMode = SHELL_OPEN_READONLY; 10597 }else if( strcmp(z,"-nofollow")==0 ){ 10598 data.openFlags |= SQLITE_OPEN_NOFOLLOW; 10599 }else if( strcmp(z,"-ascii")==0 ){ 10600 data.mode = MODE_Ascii; 10601 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10602 SEP_Unit); 10603 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10604 SEP_Record); 10605 }else if( strcmp(z,"-separator")==0 ){ 10606 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 10607 "%s",cmdline_option_value(argc,argv,++i)); 10608 }else if( strcmp(z,"-newline")==0 ){ 10609 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 10610 "%s",cmdline_option_value(argc,argv,++i)); 10611 }else if( strcmp(z,"-nullvalue")==0 ){ 10612 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 10613 "%s",cmdline_option_value(argc,argv,++i)); 10614 }else if( strcmp(z,"-header")==0 ){ 10615 data.showHeader = 1; 10616 }else if( strcmp(z,"-noheader")==0 ){ 10617 data.showHeader = 0; 10618 }else if( strcmp(z,"-echo")==0 ){ 10619 ShellSetFlag(&data, SHFLG_Echo); 10620 }else if( strcmp(z,"-eqp")==0 ){ 10621 data.autoEQP = AUTOEQP_on; 10622 }else if( strcmp(z,"-eqpfull")==0 ){ 10623 data.autoEQP = AUTOEQP_full; 10624 }else if( strcmp(z,"-stats")==0 ){ 10625 data.statsOn = 1; 10626 }else if( strcmp(z,"-scanstats")==0 ){ 10627 data.scanstatsOn = 1; 10628 }else if( strcmp(z,"-backslash")==0 ){ 10629 /* Undocumented command-line option: -backslash 10630 ** Causes C-style backslash escapes to be evaluated in SQL statements 10631 ** prior to sending the SQL into SQLite. Useful for injecting 10632 ** crazy bytes in the middle of SQL statements for testing and debugging. 10633 */ 10634 ShellSetFlag(&data, SHFLG_Backslash); 10635 }else if( strcmp(z,"-bail")==0 ){ 10636 bail_on_error = 1; 10637 }else if( strcmp(z,"-version")==0 ){ 10638 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 10639 return 0; 10640 }else if( strcmp(z,"-interactive")==0 ){ 10641 stdin_is_interactive = 1; 10642 }else if( strcmp(z,"-batch")==0 ){ 10643 stdin_is_interactive = 0; 10644 }else if( strcmp(z,"-heap")==0 ){ 10645 i++; 10646 }else if( strcmp(z,"-pagecache")==0 ){ 10647 i+=2; 10648 }else if( strcmp(z,"-lookaside")==0 ){ 10649 i+=2; 10650 }else if( strcmp(z,"-mmap")==0 ){ 10651 i++; 10652 }else if( strcmp(z,"-memtrace")==0 ){ 10653 i++; 10654#ifdef SQLITE_ENABLE_SORTER_REFERENCES 10655 }else if( strcmp(z,"-sorterref")==0 ){ 10656 i++; 10657#endif 10658 }else if( strcmp(z,"-vfs")==0 ){ 10659 i++; 10660#ifdef SQLITE_ENABLE_VFSTRACE 10661 }else if( strcmp(z,"-vfstrace")==0 ){ 10662 i++; 10663#endif 10664#ifdef SQLITE_ENABLE_MULTIPLEX 10665 }else if( strcmp(z,"-multiplex")==0 ){ 10666 i++; 10667#endif 10668 }else if( strcmp(z,"-help")==0 ){ 10669 usage(1); 10670 }else if( strcmp(z,"-cmd")==0 ){ 10671 /* Run commands that follow -cmd first and separately from commands 10672 ** that simply appear on the command-line. This seems goofy. It would 10673 ** be better if all commands ran in the order that they appear. But 10674 ** we retain the goofy behavior for historical compatibility. */ 10675 if( i==argc-1 ) break; 10676 z = cmdline_option_value(argc,argv,++i); 10677 if( z[0]=='.' ){ 10678 rc = do_meta_command(z, &data); 10679 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 10680 }else{ 10681 open_db(&data, 0); 10682 rc = shell_exec(&data, z, &zErrMsg); 10683 if( zErrMsg!=0 ){ 10684 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10685 if( bail_on_error ) return rc!=0 ? rc : 1; 10686 }else if( rc!=0 ){ 10687 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 10688 if( bail_on_error ) return rc; 10689 } 10690 } 10691#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 10692 }else if( strncmp(z, "-A", 2)==0 ){ 10693 if( nCmd>0 ){ 10694 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 10695 " with \"%s\"\n", z); 10696 return 1; 10697 } 10698 open_db(&data, OPEN_DB_ZIPFILE); 10699 if( z[2] ){ 10700 argv[i] = &z[2]; 10701 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 10702 }else{ 10703 arDotCommand(&data, 1, argv+i, argc-i); 10704 } 10705 readStdin = 0; 10706 break; 10707#endif 10708 }else{ 10709 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 10710 raw_printf(stderr,"Use -help for a list of options.\n"); 10711 return 1; 10712 } 10713 data.cMode = data.mode; 10714 } 10715 10716 if( !readStdin ){ 10717 /* Run all arguments that do not begin with '-' as if they were separate 10718 ** command-line inputs, except for the argToSkip argument which contains 10719 ** the database filename. 10720 */ 10721 for(i=0; i<nCmd; i++){ 10722 if( azCmd[i][0]=='.' ){ 10723 rc = do_meta_command(azCmd[i], &data); 10724 if( rc ) return rc==2 ? 0 : rc; 10725 }else{ 10726 open_db(&data, 0); 10727 rc = shell_exec(&data, azCmd[i], &zErrMsg); 10728 if( zErrMsg!=0 ){ 10729 utf8_printf(stderr,"Error: %s\n", zErrMsg); 10730 return rc!=0 ? rc : 1; 10731 }else if( rc!=0 ){ 10732 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 10733 return rc; 10734 } 10735 } 10736 } 10737 free(azCmd); 10738 }else{ 10739 /* Run commands received from standard input 10740 */ 10741 if( stdin_is_interactive ){ 10742 char *zHome; 10743 char *zHistory; 10744 int nHistory; 10745 printf( 10746 "SQLite version %s %.19s\n" /*extra-version-info*/ 10747 "Enter \".help\" for usage hints.\n", 10748 sqlite3_libversion(), sqlite3_sourceid() 10749 ); 10750 if( warnInmemoryDb ){ 10751 printf("Connected to a "); 10752 printBold("transient in-memory database"); 10753 printf(".\nUse \".open FILENAME\" to reopen on a " 10754 "persistent database.\n"); 10755 } 10756 zHistory = getenv("SQLITE_HISTORY"); 10757 if( zHistory ){ 10758 zHistory = strdup(zHistory); 10759 }else if( (zHome = find_home_dir(0))!=0 ){ 10760 nHistory = strlen30(zHome) + 20; 10761 if( (zHistory = malloc(nHistory))!=0 ){ 10762 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 10763 } 10764 } 10765 if( zHistory ){ shell_read_history(zHistory); } 10766#if HAVE_READLINE || HAVE_EDITLINE 10767 rl_attempted_completion_function = readline_completion; 10768#elif HAVE_LINENOISE 10769 linenoiseSetCompletionCallback(linenoise_completion); 10770#endif 10771 data.in = 0; 10772 rc = process_input(&data); 10773 if( zHistory ){ 10774 shell_stifle_history(2000); 10775 shell_write_history(zHistory); 10776 free(zHistory); 10777 } 10778 }else{ 10779 data.in = stdin; 10780 rc = process_input(&data); 10781 } 10782 } 10783 set_table_name(&data, 0); 10784 if( data.db ){ 10785 session_close_all(&data); 10786 close_db(data.db); 10787 } 10788 sqlite3_free(data.zFreeOnClose); 10789 find_home_dir(1); 10790 output_reset(&data); 10791 data.doXdgOpen = 0; 10792 clearTempFile(&data); 10793#if !SQLITE_SHELL_IS_UTF8 10794 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 10795 free(argvToFree); 10796#endif 10797 /* Clear the global data structure so that valgrind will detect memory 10798 ** leaks */ 10799 memset(&data, 0, sizeof(data)); 10800 return rc; 10801} 10802