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/* 401** This is the name of our program. It is set in main(), used 402** in a number of other places, mostly for error messages. 403*/ 404static char *Argv0; 405 406/* 407** Prompt strings. Initialized in main. Settable with 408** .prompt main continue 409*/ 410static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 411static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 412 413/* 414** Render output like fprintf(). Except, if the output is going to the 415** console and if this is running on a Windows machine, translate the 416** output from UTF-8 into MBCS. 417*/ 418#if defined(_WIN32) || defined(WIN32) 419void utf8_printf(FILE *out, const char *zFormat, ...){ 420 va_list ap; 421 va_start(ap, zFormat); 422 if( stdout_is_console && (out==stdout || out==stderr) ){ 423 char *z1 = sqlite3_vmprintf(zFormat, ap); 424 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 425 sqlite3_free(z1); 426 fputs(z2, out); 427 sqlite3_free(z2); 428 }else{ 429 vfprintf(out, zFormat, ap); 430 } 431 va_end(ap); 432} 433#elif !defined(utf8_printf) 434# define utf8_printf fprintf 435#endif 436 437/* 438** Render output like fprintf(). This should not be used on anything that 439** includes string formatting (e.g. "%s"). 440*/ 441#if !defined(raw_printf) 442# define raw_printf fprintf 443#endif 444 445/* Indicate out-of-memory and exit. */ 446static void shell_out_of_memory(void){ 447 raw_printf(stderr,"Error: out of memory\n"); 448 exit(1); 449} 450 451/* 452** Write I/O traces to the following stream. 453*/ 454#ifdef SQLITE_ENABLE_IOTRACE 455static FILE *iotrace = 0; 456#endif 457 458/* 459** This routine works like printf in that its first argument is a 460** format string and subsequent arguments are values to be substituted 461** in place of % fields. The result of formatting this string 462** is written to iotrace. 463*/ 464#ifdef SQLITE_ENABLE_IOTRACE 465static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 466 va_list ap; 467 char *z; 468 if( iotrace==0 ) return; 469 va_start(ap, zFormat); 470 z = sqlite3_vmprintf(zFormat, ap); 471 va_end(ap); 472 utf8_printf(iotrace, "%s", z); 473 sqlite3_free(z); 474} 475#endif 476 477/* 478** Output string zUtf to stream pOut as w characters. If w is negative, 479** then right-justify the text. W is the width in UTF-8 characters, not 480** in bytes. This is different from the %*.*s specification in printf 481** since with %*.*s the width is measured in bytes, not characters. 482*/ 483static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 484 int i; 485 int n; 486 int aw = w<0 ? -w : w; 487 char zBuf[1000]; 488 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3; 489 for(i=n=0; zUtf[i]; i++){ 490 if( (zUtf[i]&0xc0)!=0x80 ){ 491 n++; 492 if( n==aw ){ 493 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 494 break; 495 } 496 } 497 } 498 if( n>=aw ){ 499 utf8_printf(pOut, "%.*s", i, zUtf); 500 }else if( w<0 ){ 501 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 502 }else{ 503 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 504 } 505} 506 507 508/* 509** Determines if a string is a number of not. 510*/ 511static int isNumber(const char *z, int *realnum){ 512 if( *z=='-' || *z=='+' ) z++; 513 if( !IsDigit(*z) ){ 514 return 0; 515 } 516 z++; 517 if( realnum ) *realnum = 0; 518 while( IsDigit(*z) ){ z++; } 519 if( *z=='.' ){ 520 z++; 521 if( !IsDigit(*z) ) return 0; 522 while( IsDigit(*z) ){ z++; } 523 if( realnum ) *realnum = 1; 524 } 525 if( *z=='e' || *z=='E' ){ 526 z++; 527 if( *z=='+' || *z=='-' ) z++; 528 if( !IsDigit(*z) ) return 0; 529 while( IsDigit(*z) ){ z++; } 530 if( realnum ) *realnum = 1; 531 } 532 return *z==0; 533} 534 535/* 536** Compute a string length that is limited to what can be stored in 537** lower 30 bits of a 32-bit signed integer. 538*/ 539static int strlen30(const char *z){ 540 const char *z2 = z; 541 while( *z2 ){ z2++; } 542 return 0x3fffffff & (int)(z2 - z); 543} 544 545/* 546** Return the length of a string in characters. Multibyte UTF8 characters 547** count as a single character. 548*/ 549static int strlenChar(const char *z){ 550 int n = 0; 551 while( *z ){ 552 if( (0xc0&*(z++))!=0x80 ) n++; 553 } 554 return n; 555} 556 557/* 558** This routine reads a line of text from FILE in, stores 559** the text in memory obtained from malloc() and returns a pointer 560** to the text. NULL is returned at end of file, or if malloc() 561** fails. 562** 563** If zLine is not NULL then it is a malloced buffer returned from 564** a previous call to this routine that may be reused. 565*/ 566static char *local_getline(char *zLine, FILE *in){ 567 int nLine = zLine==0 ? 0 : 100; 568 int n = 0; 569 570 while( 1 ){ 571 if( n+100>nLine ){ 572 nLine = nLine*2 + 100; 573 zLine = realloc(zLine, nLine); 574 if( zLine==0 ) shell_out_of_memory(); 575 } 576 if( fgets(&zLine[n], nLine - n, in)==0 ){ 577 if( n==0 ){ 578 free(zLine); 579 return 0; 580 } 581 zLine[n] = 0; 582 break; 583 } 584 while( zLine[n] ) n++; 585 if( n>0 && zLine[n-1]=='\n' ){ 586 n--; 587 if( n>0 && zLine[n-1]=='\r' ) n--; 588 zLine[n] = 0; 589 break; 590 } 591 } 592#if defined(_WIN32) || defined(WIN32) 593 /* For interactive input on Windows systems, translate the 594 ** multi-byte characterset characters into UTF-8. */ 595 if( stdin_is_interactive && in==stdin ){ 596 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 597 if( zTrans ){ 598 int nTrans = strlen30(zTrans)+1; 599 if( nTrans>nLine ){ 600 zLine = realloc(zLine, nTrans); 601 if( zLine==0 ) shell_out_of_memory(); 602 } 603 memcpy(zLine, zTrans, nTrans); 604 sqlite3_free(zTrans); 605 } 606 } 607#endif /* defined(_WIN32) || defined(WIN32) */ 608 return zLine; 609} 610 611/* 612** Retrieve a single line of input text. 613** 614** If in==0 then read from standard input and prompt before each line. 615** If isContinuation is true, then a continuation prompt is appropriate. 616** If isContinuation is zero, then the main prompt should be used. 617** 618** If zPrior is not NULL then it is a buffer from a prior call to this 619** routine that can be reused. 620** 621** The result is stored in space obtained from malloc() and must either 622** be freed by the caller or else passed back into this routine via the 623** zPrior argument for reuse. 624*/ 625static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 626 char *zPrompt; 627 char *zResult; 628 if( in!=0 ){ 629 zResult = local_getline(zPrior, in); 630 }else{ 631 zPrompt = isContinuation ? continuePrompt : mainPrompt; 632#if SHELL_USE_LOCAL_GETLINE 633 printf("%s", zPrompt); 634 fflush(stdout); 635 zResult = local_getline(zPrior, stdin); 636#else 637 free(zPrior); 638 zResult = shell_readline(zPrompt); 639 if( zResult && *zResult ) shell_add_history(zResult); 640#endif 641 } 642 return zResult; 643} 644 645 646/* 647** Return the value of a hexadecimal digit. Return -1 if the input 648** is not a hex digit. 649*/ 650static int hexDigitValue(char c){ 651 if( c>='0' && c<='9' ) return c - '0'; 652 if( c>='a' && c<='f' ) return c - 'a' + 10; 653 if( c>='A' && c<='F' ) return c - 'A' + 10; 654 return -1; 655} 656 657/* 658** Interpret zArg as an integer value, possibly with suffixes. 659*/ 660static sqlite3_int64 integerValue(const char *zArg){ 661 sqlite3_int64 v = 0; 662 static const struct { char *zSuffix; int iMult; } aMult[] = { 663 { "KiB", 1024 }, 664 { "MiB", 1024*1024 }, 665 { "GiB", 1024*1024*1024 }, 666 { "KB", 1000 }, 667 { "MB", 1000000 }, 668 { "GB", 1000000000 }, 669 { "K", 1000 }, 670 { "M", 1000000 }, 671 { "G", 1000000000 }, 672 }; 673 int i; 674 int isNeg = 0; 675 if( zArg[0]=='-' ){ 676 isNeg = 1; 677 zArg++; 678 }else if( zArg[0]=='+' ){ 679 zArg++; 680 } 681 if( zArg[0]=='0' && zArg[1]=='x' ){ 682 int x; 683 zArg += 2; 684 while( (x = hexDigitValue(zArg[0]))>=0 ){ 685 v = (v<<4) + x; 686 zArg++; 687 } 688 }else{ 689 while( IsDigit(zArg[0]) ){ 690 v = v*10 + zArg[0] - '0'; 691 zArg++; 692 } 693 } 694 for(i=0; i<ArraySize(aMult); i++){ 695 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 696 v *= aMult[i].iMult; 697 break; 698 } 699 } 700 return isNeg? -v : v; 701} 702 703/* 704** A variable length string to which one can append text. 705*/ 706typedef struct ShellText ShellText; 707struct ShellText { 708 char *z; 709 int n; 710 int nAlloc; 711}; 712 713/* 714** Initialize and destroy a ShellText object 715*/ 716static void initText(ShellText *p){ 717 memset(p, 0, sizeof(*p)); 718} 719static void freeText(ShellText *p){ 720 free(p->z); 721 initText(p); 722} 723 724/* zIn is either a pointer to a NULL-terminated string in memory obtained 725** from malloc(), or a NULL pointer. The string pointed to by zAppend is 726** added to zIn, and the result returned in memory obtained from malloc(). 727** zIn, if it was not NULL, is freed. 728** 729** If the third argument, quote, is not '\0', then it is used as a 730** quote character for zAppend. 731*/ 732static void appendText(ShellText *p, char const *zAppend, char quote){ 733 int len; 734 int i; 735 int nAppend = strlen30(zAppend); 736 737 len = nAppend+p->n+1; 738 if( quote ){ 739 len += 2; 740 for(i=0; i<nAppend; i++){ 741 if( zAppend[i]==quote ) len++; 742 } 743 } 744 745 if( p->n+len>=p->nAlloc ){ 746 p->nAlloc = p->nAlloc*2 + len + 20; 747 p->z = realloc(p->z, p->nAlloc); 748 if( p->z==0 ) shell_out_of_memory(); 749 } 750 751 if( quote ){ 752 char *zCsr = p->z+p->n; 753 *zCsr++ = quote; 754 for(i=0; i<nAppend; i++){ 755 *zCsr++ = zAppend[i]; 756 if( zAppend[i]==quote ) *zCsr++ = quote; 757 } 758 *zCsr++ = quote; 759 p->n = (int)(zCsr - p->z); 760 *zCsr = '\0'; 761 }else{ 762 memcpy(p->z+p->n, zAppend, nAppend); 763 p->n += nAppend; 764 p->z[p->n] = '\0'; 765 } 766} 767 768/* 769** Attempt to determine if identifier zName needs to be quoted, either 770** because it contains non-alphanumeric characters, or because it is an 771** SQLite keyword. Be conservative in this estimate: When in doubt assume 772** that quoting is required. 773** 774** Return '"' if quoting is required. Return 0 if no quoting is required. 775*/ 776static char quoteChar(const char *zName){ 777 int i; 778 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 779 for(i=0; zName[i]; i++){ 780 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 781 } 782 return sqlite3_keyword_check(zName, i) ? '"' : 0; 783} 784 785/* 786** Construct a fake object name and column list to describe the structure 787** of the view, virtual table, or table valued function zSchema.zName. 788*/ 789static char *shellFakeSchema( 790 sqlite3 *db, /* The database connection containing the vtab */ 791 const char *zSchema, /* Schema of the database holding the vtab */ 792 const char *zName /* The name of the virtual table */ 793){ 794 sqlite3_stmt *pStmt = 0; 795 char *zSql; 796 ShellText s; 797 char cQuote; 798 char *zDiv = "("; 799 int nRow = 0; 800 801 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 802 zSchema ? zSchema : "main", zName); 803 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 804 sqlite3_free(zSql); 805 initText(&s); 806 if( zSchema ){ 807 cQuote = quoteChar(zSchema); 808 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 809 appendText(&s, zSchema, cQuote); 810 appendText(&s, ".", 0); 811 } 812 cQuote = quoteChar(zName); 813 appendText(&s, zName, cQuote); 814 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 815 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 816 nRow++; 817 appendText(&s, zDiv, 0); 818 zDiv = ","; 819 cQuote = quoteChar(zCol); 820 appendText(&s, zCol, cQuote); 821 } 822 appendText(&s, ")", 0); 823 sqlite3_finalize(pStmt); 824 if( nRow==0 ){ 825 freeText(&s); 826 s.z = 0; 827 } 828 return s.z; 829} 830 831/* 832** SQL function: shell_module_schema(X) 833** 834** Return a fake schema for the table-valued function or eponymous virtual 835** table X. 836*/ 837static void shellModuleSchema( 838 sqlite3_context *pCtx, 839 int nVal, 840 sqlite3_value **apVal 841){ 842 const char *zName = (const char*)sqlite3_value_text(apVal[0]); 843 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName); 844 UNUSED_PARAMETER(nVal); 845 if( zFake ){ 846 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 847 -1, sqlite3_free); 848 free(zFake); 849 } 850} 851 852/* 853** SQL function: shell_add_schema(S,X) 854** 855** Add the schema name X to the CREATE statement in S and return the result. 856** Examples: 857** 858** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 859** 860** Also works on 861** 862** CREATE INDEX 863** CREATE UNIQUE INDEX 864** CREATE VIEW 865** CREATE TRIGGER 866** CREATE VIRTUAL TABLE 867** 868** This UDF is used by the .schema command to insert the schema name of 869** attached databases into the middle of the sqlite_master.sql field. 870*/ 871static void shellAddSchemaName( 872 sqlite3_context *pCtx, 873 int nVal, 874 sqlite3_value **apVal 875){ 876 static const char *aPrefix[] = { 877 "TABLE", 878 "INDEX", 879 "UNIQUE INDEX", 880 "VIEW", 881 "TRIGGER", 882 "VIRTUAL TABLE" 883 }; 884 int i = 0; 885 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 886 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 887 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 888 sqlite3 *db = sqlite3_context_db_handle(pCtx); 889 UNUSED_PARAMETER(nVal); 890 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){ 891 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){ 892 int n = strlen30(aPrefix[i]); 893 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 894 char *z = 0; 895 char *zFake = 0; 896 if( zSchema ){ 897 char cQuote = quoteChar(zSchema); 898 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 899 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 900 }else{ 901 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 902 } 903 } 904 if( zName 905 && aPrefix[i][0]=='V' 906 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 907 ){ 908 if( z==0 ){ 909 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 910 }else{ 911 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 912 } 913 free(zFake); 914 } 915 if( z ){ 916 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 917 return; 918 } 919 } 920 } 921 } 922 sqlite3_result_value(pCtx, apVal[0]); 923} 924 925/* 926** The source code for several run-time loadable extensions is inserted 927** below by the ../tool/mkshellc.tcl script. Before processing that included 928** code, we need to override some macros to make the included program code 929** work here in the middle of this regular program. 930*/ 931#define SQLITE_EXTENSION_INIT1 932#define SQLITE_EXTENSION_INIT2(X) (void)(X) 933 934#if defined(_WIN32) && defined(_MSC_VER) 935INCLUDE test_windirent.h 936INCLUDE test_windirent.c 937#define dirent DIRENT 938#endif 939INCLUDE ../ext/misc/shathree.c 940INCLUDE ../ext/misc/fileio.c 941INCLUDE ../ext/misc/completion.c 942INCLUDE ../ext/misc/appendvfs.c 943INCLUDE ../ext/misc/memtrace.c 944#ifdef SQLITE_HAVE_ZLIB 945INCLUDE ../ext/misc/zipfile.c 946INCLUDE ../ext/misc/sqlar.c 947#endif 948INCLUDE ../ext/expert/sqlite3expert.h 949INCLUDE ../ext/expert/sqlite3expert.c 950 951#if defined(SQLITE_ENABLE_SESSION) 952/* 953** State information for a single open session 954*/ 955typedef struct OpenSession OpenSession; 956struct OpenSession { 957 char *zName; /* Symbolic name for this session */ 958 int nFilter; /* Number of xFilter rejection GLOB patterns */ 959 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 960 sqlite3_session *p; /* The open session */ 961}; 962#endif 963 964/* 965** Shell output mode information from before ".explain on", 966** saved so that it can be restored by ".explain off" 967*/ 968typedef struct SavedModeInfo SavedModeInfo; 969struct SavedModeInfo { 970 int valid; /* Is there legit data in here? */ 971 int mode; /* Mode prior to ".explain on" */ 972 int showHeader; /* The ".header" setting prior to ".explain on" */ 973 int colWidth[100]; /* Column widths prior to ".explain on" */ 974}; 975 976typedef struct ExpertInfo ExpertInfo; 977struct ExpertInfo { 978 sqlite3expert *pExpert; 979 int bVerbose; 980}; 981 982/* A single line in the EQP output */ 983typedef struct EQPGraphRow EQPGraphRow; 984struct EQPGraphRow { 985 int iEqpId; /* ID for this row */ 986 int iParentId; /* ID of the parent row */ 987 EQPGraphRow *pNext; /* Next row in sequence */ 988 char zText[1]; /* Text to display for this row */ 989}; 990 991/* All EQP output is collected into an instance of the following */ 992typedef struct EQPGraph EQPGraph; 993struct EQPGraph { 994 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 995 EQPGraphRow *pLast; /* Last element of the pRow list */ 996 char zPrefix[100]; /* Graph prefix */ 997}; 998 999/* 1000** State information about the database connection is contained in an 1001** instance of the following structure. 1002*/ 1003typedef struct ShellState ShellState; 1004struct ShellState { 1005 sqlite3 *db; /* The database */ 1006 u8 autoExplain; /* Automatically turn on .explain mode */ 1007 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1008 u8 autoEQPtest; /* autoEQP is in test mode */ 1009 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1010 u8 statsOn; /* True to display memory stats before each finalize */ 1011 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1012 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1013 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1014 u8 nEqpLevel; /* Depth of the EQP output graph */ 1015 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1016 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1017 int outCount; /* Revert to stdout when reaching zero */ 1018 int cnt; /* Number of records displayed so far */ 1019 int lineno; /* Line number of last line read from in */ 1020 FILE *in; /* Read commands from this stream */ 1021 FILE *out; /* Write results here */ 1022 FILE *traceOut; /* Output for sqlite3_trace() */ 1023 int nErr; /* Number of errors seen */ 1024 int mode; /* An output mode setting */ 1025 int modePrior; /* Saved mode */ 1026 int cMode; /* temporary output mode for the current query */ 1027 int normalMode; /* Output mode before ".explain on" */ 1028 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1029 int showHeader; /* True to show column names in List or Column mode */ 1030 int nCheck; /* Number of ".check" commands run */ 1031 unsigned nProgress; /* Number of progress callbacks encountered */ 1032 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1033 unsigned flgProgress; /* Flags for the progress callback */ 1034 unsigned shellFlgs; /* Various flags */ 1035 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1036 char *zDestTable; /* Name of destination table when MODE_Insert */ 1037 char *zTempFile; /* Temporary file that might need deleting */ 1038 char zTestcase[30]; /* Name of current test case */ 1039 char colSeparator[20]; /* Column separator character for several modes */ 1040 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1041 char colSepPrior[20]; /* Saved column separator */ 1042 char rowSepPrior[20]; /* Saved row separator */ 1043 int colWidth[100]; /* Requested width of each column when in column mode*/ 1044 int actualWidth[100]; /* Actual width of each column */ 1045 char nullValue[20]; /* The text to print when a NULL comes back from 1046 ** the database */ 1047 char outfile[FILENAME_MAX]; /* Filename for *out */ 1048 const char *zDbFilename; /* name of the database file */ 1049 char *zFreeOnClose; /* Filename to free when closing */ 1050 const char *zVfs; /* Name of VFS to use */ 1051 sqlite3_stmt *pStmt; /* Current statement if any. */ 1052 FILE *pLog; /* Write log output here */ 1053 int *aiIndent; /* Array of indents used in MODE_Explain */ 1054 int nIndent; /* Size of array aiIndent[] */ 1055 int iIndent; /* Index of current op in aiIndent[] */ 1056 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1057#if defined(SQLITE_ENABLE_SESSION) 1058 int nSession; /* Number of active sessions */ 1059 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1060#endif 1061 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1062}; 1063 1064 1065/* Allowed values for ShellState.autoEQP 1066*/ 1067#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1068#define AUTOEQP_on 1 /* Automatic EQP is on */ 1069#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1070#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1071 1072/* Allowed values for ShellState.openMode 1073*/ 1074#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1075#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1076#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1077#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1078#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1079#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1080#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1081 1082/* Allowed values for ShellState.eTraceType 1083*/ 1084#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1085#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1086#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1087 1088/* Bits in the ShellState.flgProgress variable */ 1089#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1090#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1091 ** callback limit is reached, and for each 1092 ** top-level SQL statement */ 1093#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1094 1095/* 1096** These are the allowed shellFlgs values 1097*/ 1098#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1099#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1100#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1101#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1102#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1103#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1104#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */ 1105 1106/* 1107** Macros for testing and setting shellFlgs 1108*/ 1109#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1110#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1111#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1112 1113/* 1114** These are the allowed modes. 1115*/ 1116#define MODE_Line 0 /* One column per line. Blank line between records */ 1117#define MODE_Column 1 /* One record per line in neat columns */ 1118#define MODE_List 2 /* One record per line with a separator */ 1119#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1120#define MODE_Html 4 /* Generate an XHTML table */ 1121#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1122#define MODE_Quote 6 /* Quote values as for SQL */ 1123#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1124#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1125#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1126#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1127#define MODE_Pretty 11 /* Pretty-print schemas */ 1128#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1129 1130static const char *modeDescr[] = { 1131 "line", 1132 "column", 1133 "list", 1134 "semi", 1135 "html", 1136 "insert", 1137 "quote", 1138 "tcl", 1139 "csv", 1140 "explain", 1141 "ascii", 1142 "prettyprint", 1143 "eqp" 1144}; 1145 1146/* 1147** These are the column/row/line separators used by the various 1148** import/export modes. 1149*/ 1150#define SEP_Column "|" 1151#define SEP_Row "\n" 1152#define SEP_Tab "\t" 1153#define SEP_Space " " 1154#define SEP_Comma "," 1155#define SEP_CrLf "\r\n" 1156#define SEP_Unit "\x1F" 1157#define SEP_Record "\x1E" 1158 1159/* 1160** A callback for the sqlite3_log() interface. 1161*/ 1162static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1163 ShellState *p = (ShellState*)pArg; 1164 if( p->pLog==0 ) return; 1165 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1166 fflush(p->pLog); 1167} 1168 1169/* 1170** SQL function: shell_putsnl(X) 1171** 1172** Write the text X to the screen (or whatever output is being directed) 1173** adding a newline at the end, and then return X. 1174*/ 1175static void shellPutsFunc( 1176 sqlite3_context *pCtx, 1177 int nVal, 1178 sqlite3_value **apVal 1179){ 1180 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1181 (void)nVal; 1182 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1183 sqlite3_result_value(pCtx, apVal[0]); 1184} 1185 1186/* 1187** SQL function: edit(VALUE) 1188** edit(VALUE,EDITOR) 1189** 1190** These steps: 1191** 1192** (1) Write VALUE into a temporary file. 1193** (2) Run program EDITOR on that temporary file. 1194** (3) Read the temporary file back and return its content as the result. 1195** (4) Delete the temporary file 1196** 1197** If the EDITOR argument is omitted, use the value in the VISUAL 1198** environment variable. If still there is no EDITOR, through an error. 1199** 1200** Also throw an error if the EDITOR program returns a non-zero exit code. 1201*/ 1202#ifndef SQLITE_NOHAVE_SYSTEM 1203static void editFunc( 1204 sqlite3_context *context, 1205 int argc, 1206 sqlite3_value **argv 1207){ 1208 const char *zEditor; 1209 char *zTempFile = 0; 1210 sqlite3 *db; 1211 char *zCmd = 0; 1212 int bBin; 1213 int rc; 1214 int hasCRNL = 0; 1215 FILE *f = 0; 1216 sqlite3_int64 sz; 1217 sqlite3_int64 x; 1218 unsigned char *p = 0; 1219 1220 if( argc==2 ){ 1221 zEditor = (const char*)sqlite3_value_text(argv[1]); 1222 }else{ 1223 zEditor = getenv("VISUAL"); 1224 } 1225 if( zEditor==0 ){ 1226 sqlite3_result_error(context, "no editor for edit()", -1); 1227 return; 1228 } 1229 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1230 sqlite3_result_error(context, "NULL input to edit()", -1); 1231 return; 1232 } 1233 db = sqlite3_context_db_handle(context); 1234 zTempFile = 0; 1235 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1236 if( zTempFile==0 ){ 1237 sqlite3_uint64 r = 0; 1238 sqlite3_randomness(sizeof(r), &r); 1239 zTempFile = sqlite3_mprintf("temp%llx", r); 1240 if( zTempFile==0 ){ 1241 sqlite3_result_error_nomem(context); 1242 return; 1243 } 1244 } 1245 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1246 /* When writing the file to be edited, do \n to \r\n conversions on systems 1247 ** that want \r\n line endings */ 1248 f = fopen(zTempFile, bBin ? "wb" : "w"); 1249 if( f==0 ){ 1250 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1251 goto edit_func_end; 1252 } 1253 sz = sqlite3_value_bytes(argv[0]); 1254 if( bBin ){ 1255 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f); 1256 }else{ 1257 const char *z = (const char*)sqlite3_value_text(argv[0]); 1258 /* Remember whether or not the value originally contained \r\n */ 1259 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1260 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f); 1261 } 1262 fclose(f); 1263 f = 0; 1264 if( x!=sz ){ 1265 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1266 goto edit_func_end; 1267 } 1268 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1269 if( zCmd==0 ){ 1270 sqlite3_result_error_nomem(context); 1271 goto edit_func_end; 1272 } 1273 rc = system(zCmd); 1274 sqlite3_free(zCmd); 1275 if( rc ){ 1276 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1277 goto edit_func_end; 1278 } 1279 f = fopen(zTempFile, "rb"); 1280 if( f==0 ){ 1281 sqlite3_result_error(context, 1282 "edit() cannot reopen temp file after edit", -1); 1283 goto edit_func_end; 1284 } 1285 fseek(f, 0, SEEK_END); 1286 sz = ftell(f); 1287 rewind(f); 1288 p = sqlite3_malloc64( sz+(bBin==0) ); 1289 if( p==0 ){ 1290 sqlite3_result_error_nomem(context); 1291 goto edit_func_end; 1292 } 1293 x = fread(p, 1, sz, f); 1294 fclose(f); 1295 f = 0; 1296 if( x!=sz ){ 1297 sqlite3_result_error(context, "could not read back the whole file", -1); 1298 goto edit_func_end; 1299 } 1300 if( bBin ){ 1301 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1302 }else{ 1303 sqlite3_int64 i, j; 1304 if( hasCRNL ){ 1305 /* If the original contains \r\n then do no conversions back to \n */ 1306 j = sz; 1307 }else{ 1308 /* If the file did not originally contain \r\n then convert any new 1309 ** \r\n back into \n */ 1310 for(i=j=0; i<sz; i++){ 1311 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1312 p[j++] = p[i]; 1313 } 1314 sz = j; 1315 p[sz] = 0; 1316 } 1317 sqlite3_result_text64(context, (const char*)p, sz, 1318 sqlite3_free, SQLITE_UTF8); 1319 } 1320 p = 0; 1321 1322edit_func_end: 1323 if( f ) fclose(f); 1324 unlink(zTempFile); 1325 sqlite3_free(zTempFile); 1326 sqlite3_free(p); 1327} 1328#endif /* SQLITE_NOHAVE_SYSTEM */ 1329 1330/* 1331** Save or restore the current output mode 1332*/ 1333static void outputModePush(ShellState *p){ 1334 p->modePrior = p->mode; 1335 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1336 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1337} 1338static void outputModePop(ShellState *p){ 1339 p->mode = p->modePrior; 1340 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1341 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1342} 1343 1344/* 1345** Output the given string as a hex-encoded blob (eg. X'1234' ) 1346*/ 1347static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1348 int i; 1349 char *zBlob = (char *)pBlob; 1350 raw_printf(out,"X'"); 1351 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } 1352 raw_printf(out,"'"); 1353} 1354 1355/* 1356** Find a string that is not found anywhere in z[]. Return a pointer 1357** to that string. 1358** 1359** Try to use zA and zB first. If both of those are already found in z[] 1360** then make up some string and store it in the buffer zBuf. 1361*/ 1362static const char *unused_string( 1363 const char *z, /* Result must not appear anywhere in z */ 1364 const char *zA, const char *zB, /* Try these first */ 1365 char *zBuf /* Space to store a generated string */ 1366){ 1367 unsigned i = 0; 1368 if( strstr(z, zA)==0 ) return zA; 1369 if( strstr(z, zB)==0 ) return zB; 1370 do{ 1371 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1372 }while( strstr(z,zBuf)!=0 ); 1373 return zBuf; 1374} 1375 1376/* 1377** Output the given string as a quoted string using SQL quoting conventions. 1378** 1379** See also: output_quoted_escaped_string() 1380*/ 1381static void output_quoted_string(FILE *out, const char *z){ 1382 int i; 1383 char c; 1384 setBinaryMode(out, 1); 1385 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1386 if( c==0 ){ 1387 utf8_printf(out,"'%s'",z); 1388 }else{ 1389 raw_printf(out, "'"); 1390 while( *z ){ 1391 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1392 if( c=='\'' ) i++; 1393 if( i ){ 1394 utf8_printf(out, "%.*s", i, z); 1395 z += i; 1396 } 1397 if( c=='\'' ){ 1398 raw_printf(out, "'"); 1399 continue; 1400 } 1401 if( c==0 ){ 1402 break; 1403 } 1404 z++; 1405 } 1406 raw_printf(out, "'"); 1407 } 1408 setTextMode(out, 1); 1409} 1410 1411/* 1412** Output the given string as a quoted string using SQL quoting conventions. 1413** Additionallly , escape the "\n" and "\r" characters so that they do not 1414** get corrupted by end-of-line translation facilities in some operating 1415** systems. 1416** 1417** This is like output_quoted_string() but with the addition of the \r\n 1418** escape mechanism. 1419*/ 1420static void output_quoted_escaped_string(FILE *out, const char *z){ 1421 int i; 1422 char c; 1423 setBinaryMode(out, 1); 1424 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1425 if( c==0 ){ 1426 utf8_printf(out,"'%s'",z); 1427 }else{ 1428 const char *zNL = 0; 1429 const char *zCR = 0; 1430 int nNL = 0; 1431 int nCR = 0; 1432 char zBuf1[20], zBuf2[20]; 1433 for(i=0; z[i]; i++){ 1434 if( z[i]=='\n' ) nNL++; 1435 if( z[i]=='\r' ) nCR++; 1436 } 1437 if( nNL ){ 1438 raw_printf(out, "replace("); 1439 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1440 } 1441 if( nCR ){ 1442 raw_printf(out, "replace("); 1443 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1444 } 1445 raw_printf(out, "'"); 1446 while( *z ){ 1447 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1448 if( c=='\'' ) i++; 1449 if( i ){ 1450 utf8_printf(out, "%.*s", i, z); 1451 z += i; 1452 } 1453 if( c=='\'' ){ 1454 raw_printf(out, "'"); 1455 continue; 1456 } 1457 if( c==0 ){ 1458 break; 1459 } 1460 z++; 1461 if( c=='\n' ){ 1462 raw_printf(out, "%s", zNL); 1463 continue; 1464 } 1465 raw_printf(out, "%s", zCR); 1466 } 1467 raw_printf(out, "'"); 1468 if( nCR ){ 1469 raw_printf(out, ",'%s',char(13))", zCR); 1470 } 1471 if( nNL ){ 1472 raw_printf(out, ",'%s',char(10))", zNL); 1473 } 1474 } 1475 setTextMode(out, 1); 1476} 1477 1478/* 1479** Output the given string as a quoted according to C or TCL quoting rules. 1480*/ 1481static void output_c_string(FILE *out, const char *z){ 1482 unsigned int c; 1483 fputc('"', out); 1484 while( (c = *(z++))!=0 ){ 1485 if( c=='\\' ){ 1486 fputc(c, out); 1487 fputc(c, out); 1488 }else if( c=='"' ){ 1489 fputc('\\', out); 1490 fputc('"', out); 1491 }else if( c=='\t' ){ 1492 fputc('\\', out); 1493 fputc('t', out); 1494 }else if( c=='\n' ){ 1495 fputc('\\', out); 1496 fputc('n', out); 1497 }else if( c=='\r' ){ 1498 fputc('\\', out); 1499 fputc('r', out); 1500 }else if( !isprint(c&0xff) ){ 1501 raw_printf(out, "\\%03o", c&0xff); 1502 }else{ 1503 fputc(c, out); 1504 } 1505 } 1506 fputc('"', out); 1507} 1508 1509/* 1510** Output the given string with characters that are special to 1511** HTML escaped. 1512*/ 1513static void output_html_string(FILE *out, const char *z){ 1514 int i; 1515 if( z==0 ) z = ""; 1516 while( *z ){ 1517 for(i=0; z[i] 1518 && z[i]!='<' 1519 && z[i]!='&' 1520 && z[i]!='>' 1521 && z[i]!='\"' 1522 && z[i]!='\''; 1523 i++){} 1524 if( i>0 ){ 1525 utf8_printf(out,"%.*s",i,z); 1526 } 1527 if( z[i]=='<' ){ 1528 raw_printf(out,"<"); 1529 }else if( z[i]=='&' ){ 1530 raw_printf(out,"&"); 1531 }else if( z[i]=='>' ){ 1532 raw_printf(out,">"); 1533 }else if( z[i]=='\"' ){ 1534 raw_printf(out,"""); 1535 }else if( z[i]=='\'' ){ 1536 raw_printf(out,"'"); 1537 }else{ 1538 break; 1539 } 1540 z += i + 1; 1541 } 1542} 1543 1544/* 1545** If a field contains any character identified by a 1 in the following 1546** array, then the string must be quoted for CSV. 1547*/ 1548static const char needCsvQuote[] = { 1549 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1550 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1551 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1552 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1553 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1554 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1555 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1556 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1557 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1558 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1559 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1560 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1561 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1562 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1563 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1564 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1565}; 1566 1567/* 1568** Output a single term of CSV. Actually, p->colSeparator is used for 1569** the separator, which may or may not be a comma. p->nullValue is 1570** the null value. Strings are quoted if necessary. The separator 1571** is only issued if bSep is true. 1572*/ 1573static void output_csv(ShellState *p, const char *z, int bSep){ 1574 FILE *out = p->out; 1575 if( z==0 ){ 1576 utf8_printf(out,"%s",p->nullValue); 1577 }else{ 1578 int i; 1579 int nSep = strlen30(p->colSeparator); 1580 for(i=0; z[i]; i++){ 1581 if( needCsvQuote[((unsigned char*)z)[i]] 1582 || (z[i]==p->colSeparator[0] && 1583 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ 1584 i = 0; 1585 break; 1586 } 1587 } 1588 if( i==0 ){ 1589 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1590 utf8_printf(out, "%s", zQuoted); 1591 sqlite3_free(zQuoted); 1592 }else{ 1593 utf8_printf(out, "%s", z); 1594 } 1595 } 1596 if( bSep ){ 1597 utf8_printf(p->out, "%s", p->colSeparator); 1598 } 1599} 1600 1601/* 1602** This routine runs when the user presses Ctrl-C 1603*/ 1604static void interrupt_handler(int NotUsed){ 1605 UNUSED_PARAMETER(NotUsed); 1606 seenInterrupt++; 1607 if( seenInterrupt>2 ) exit(1); 1608 if( globalDb ) sqlite3_interrupt(globalDb); 1609} 1610 1611#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1612/* 1613** This routine runs for console events (e.g. Ctrl-C) on Win32 1614*/ 1615static BOOL WINAPI ConsoleCtrlHandler( 1616 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1617){ 1618 if( dwCtrlType==CTRL_C_EVENT ){ 1619 interrupt_handler(0); 1620 return TRUE; 1621 } 1622 return FALSE; 1623} 1624#endif 1625 1626#ifndef SQLITE_OMIT_AUTHORIZATION 1627/* 1628** When the ".auth ON" is set, the following authorizer callback is 1629** invoked. It always returns SQLITE_OK. 1630*/ 1631static int shellAuth( 1632 void *pClientData, 1633 int op, 1634 const char *zA1, 1635 const char *zA2, 1636 const char *zA3, 1637 const char *zA4 1638){ 1639 ShellState *p = (ShellState*)pClientData; 1640 static const char *azAction[] = { 0, 1641 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1642 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1643 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1644 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1645 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1646 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1647 "PRAGMA", "READ", "SELECT", 1648 "TRANSACTION", "UPDATE", "ATTACH", 1649 "DETACH", "ALTER_TABLE", "REINDEX", 1650 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1651 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1652 }; 1653 int i; 1654 const char *az[4]; 1655 az[0] = zA1; 1656 az[1] = zA2; 1657 az[2] = zA3; 1658 az[3] = zA4; 1659 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1660 for(i=0; i<4; i++){ 1661 raw_printf(p->out, " "); 1662 if( az[i] ){ 1663 output_c_string(p->out, az[i]); 1664 }else{ 1665 raw_printf(p->out, "NULL"); 1666 } 1667 } 1668 raw_printf(p->out, "\n"); 1669 return SQLITE_OK; 1670} 1671#endif 1672 1673/* 1674** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1675** 1676** This routine converts some CREATE TABLE statements for shadow tables 1677** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1678*/ 1679static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1680 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1681 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1682 }else{ 1683 utf8_printf(out, "%s%s", z, zTail); 1684 } 1685} 1686static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1687 char c = z[n]; 1688 z[n] = 0; 1689 printSchemaLine(out, z, zTail); 1690 z[n] = c; 1691} 1692 1693/* 1694** Return true if string z[] has nothing but whitespace and comments to the 1695** end of the first line. 1696*/ 1697static int wsToEol(const char *z){ 1698 int i; 1699 for(i=0; z[i]; i++){ 1700 if( z[i]=='\n' ) return 1; 1701 if( IsSpace(z[i]) ) continue; 1702 if( z[i]=='-' && z[i+1]=='-' ) return 1; 1703 return 0; 1704 } 1705 return 1; 1706} 1707 1708/* 1709** Add a new entry to the EXPLAIN QUERY PLAN data 1710*/ 1711static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 1712 EQPGraphRow *pNew; 1713 int nText = strlen30(zText); 1714 if( p->autoEQPtest ){ 1715 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 1716 } 1717 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 1718 if( pNew==0 ) shell_out_of_memory(); 1719 pNew->iEqpId = iEqpId; 1720 pNew->iParentId = p2; 1721 memcpy(pNew->zText, zText, nText+1); 1722 pNew->pNext = 0; 1723 if( p->sGraph.pLast ){ 1724 p->sGraph.pLast->pNext = pNew; 1725 }else{ 1726 p->sGraph.pRow = pNew; 1727 } 1728 p->sGraph.pLast = pNew; 1729} 1730 1731/* 1732** Free and reset the EXPLAIN QUERY PLAN data that has been collected 1733** in p->sGraph. 1734*/ 1735static void eqp_reset(ShellState *p){ 1736 EQPGraphRow *pRow, *pNext; 1737 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 1738 pNext = pRow->pNext; 1739 sqlite3_free(pRow); 1740 } 1741 memset(&p->sGraph, 0, sizeof(p->sGraph)); 1742} 1743 1744/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 1745** pOld, or return the first such line if pOld is NULL 1746*/ 1747static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 1748 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 1749 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 1750 return pRow; 1751} 1752 1753/* Render a single level of the graph that has iEqpId as its parent. Called 1754** recursively to render sublevels. 1755*/ 1756static void eqp_render_level(ShellState *p, int iEqpId){ 1757 EQPGraphRow *pRow, *pNext; 1758 int n = strlen30(p->sGraph.zPrefix); 1759 char *z; 1760 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 1761 pNext = eqp_next_row(p, iEqpId, pRow); 1762 z = pRow->zText; 1763 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z); 1764 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){ 1765 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 1766 eqp_render_level(p, pRow->iEqpId); 1767 p->sGraph.zPrefix[n] = 0; 1768 } 1769 } 1770} 1771 1772/* 1773** Display and reset the EXPLAIN QUERY PLAN data 1774*/ 1775static void eqp_render(ShellState *p){ 1776 EQPGraphRow *pRow = p->sGraph.pRow; 1777 if( pRow ){ 1778 if( pRow->zText[0]=='-' ){ 1779 if( pRow->pNext==0 ){ 1780 eqp_reset(p); 1781 return; 1782 } 1783 utf8_printf(p->out, "%s\n", pRow->zText+3); 1784 p->sGraph.pRow = pRow->pNext; 1785 sqlite3_free(pRow); 1786 }else{ 1787 utf8_printf(p->out, "QUERY PLAN\n"); 1788 } 1789 p->sGraph.zPrefix[0] = 0; 1790 eqp_render_level(p, 0); 1791 eqp_reset(p); 1792 } 1793} 1794 1795#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 1796/* 1797** Progress handler callback. 1798*/ 1799static int progress_handler(void *pClientData) { 1800 ShellState *p = (ShellState*)pClientData; 1801 p->nProgress++; 1802 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 1803 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 1804 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 1805 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 1806 return 1; 1807 } 1808 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 1809 raw_printf(p->out, "Progress %u\n", p->nProgress); 1810 } 1811 return 0; 1812} 1813#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 1814 1815/* 1816** This is the callback routine that the shell 1817** invokes for each row of a query result. 1818*/ 1819static int shell_callback( 1820 void *pArg, 1821 int nArg, /* Number of result columns */ 1822 char **azArg, /* Text of each result column */ 1823 char **azCol, /* Column names */ 1824 int *aiType /* Column types */ 1825){ 1826 int i; 1827 ShellState *p = (ShellState*)pArg; 1828 1829 if( azArg==0 ) return 0; 1830 switch( p->cMode ){ 1831 case MODE_Line: { 1832 int w = 5; 1833 if( azArg==0 ) break; 1834 for(i=0; i<nArg; i++){ 1835 int len = strlen30(azCol[i] ? azCol[i] : ""); 1836 if( len>w ) w = len; 1837 } 1838 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 1839 for(i=0; i<nArg; i++){ 1840 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 1841 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 1842 } 1843 break; 1844 } 1845 case MODE_Explain: 1846 case MODE_Column: { 1847 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13}; 1848 const int *colWidth; 1849 int showHdr; 1850 char *rowSep; 1851 if( p->cMode==MODE_Column ){ 1852 colWidth = p->colWidth; 1853 showHdr = p->showHeader; 1854 rowSep = p->rowSeparator; 1855 }else{ 1856 colWidth = aExplainWidths; 1857 showHdr = 1; 1858 rowSep = SEP_Row; 1859 } 1860 if( p->cnt++==0 ){ 1861 for(i=0; i<nArg; i++){ 1862 int w, n; 1863 if( i<ArraySize(p->colWidth) ){ 1864 w = colWidth[i]; 1865 }else{ 1866 w = 0; 1867 } 1868 if( w==0 ){ 1869 w = strlenChar(azCol[i] ? azCol[i] : ""); 1870 if( w<10 ) w = 10; 1871 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue); 1872 if( w<n ) w = n; 1873 } 1874 if( i<ArraySize(p->actualWidth) ){ 1875 p->actualWidth[i] = w; 1876 } 1877 if( showHdr ){ 1878 utf8_width_print(p->out, w, azCol[i]); 1879 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1880 } 1881 } 1882 if( showHdr ){ 1883 for(i=0; i<nArg; i++){ 1884 int w; 1885 if( i<ArraySize(p->actualWidth) ){ 1886 w = p->actualWidth[i]; 1887 if( w<0 ) w = -w; 1888 }else{ 1889 w = 10; 1890 } 1891 utf8_printf(p->out,"%-*.*s%s",w,w, 1892 "----------------------------------------------------------" 1893 "----------------------------------------------------------", 1894 i==nArg-1 ? rowSep : " "); 1895 } 1896 } 1897 } 1898 if( azArg==0 ) break; 1899 for(i=0; i<nArg; i++){ 1900 int w; 1901 if( i<ArraySize(p->actualWidth) ){ 1902 w = p->actualWidth[i]; 1903 }else{ 1904 w = 10; 1905 } 1906 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){ 1907 w = strlenChar(azArg[i]); 1908 } 1909 if( i==1 && p->aiIndent && p->pStmt ){ 1910 if( p->iIndent<p->nIndent ){ 1911 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 1912 } 1913 p->iIndent++; 1914 } 1915 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 1916 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " "); 1917 } 1918 break; 1919 } 1920 case MODE_Semi: { /* .schema and .fullschema output */ 1921 printSchemaLine(p->out, azArg[0], ";\n"); 1922 break; 1923 } 1924 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 1925 char *z; 1926 int j; 1927 int nParen = 0; 1928 char cEnd = 0; 1929 char c; 1930 int nLine = 0; 1931 assert( nArg==1 ); 1932 if( azArg[0]==0 ) break; 1933 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 1934 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 1935 ){ 1936 utf8_printf(p->out, "%s;\n", azArg[0]); 1937 break; 1938 } 1939 z = sqlite3_mprintf("%s", azArg[0]); 1940 j = 0; 1941 for(i=0; IsSpace(z[i]); i++){} 1942 for(; (c = z[i])!=0; i++){ 1943 if( IsSpace(c) ){ 1944 if( z[j-1]=='\r' ) z[j-1] = '\n'; 1945 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 1946 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 1947 j--; 1948 } 1949 z[j++] = c; 1950 } 1951 while( j>0 && IsSpace(z[j-1]) ){ j--; } 1952 z[j] = 0; 1953 if( strlen30(z)>=79 ){ 1954 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */ 1955 if( c==cEnd ){ 1956 cEnd = 0; 1957 }else if( c=='"' || c=='\'' || c=='`' ){ 1958 cEnd = c; 1959 }else if( c=='[' ){ 1960 cEnd = ']'; 1961 }else if( c=='-' && z[i+1]=='-' ){ 1962 cEnd = '\n'; 1963 }else if( c=='(' ){ 1964 nParen++; 1965 }else if( c==')' ){ 1966 nParen--; 1967 if( nLine>0 && nParen==0 && j>0 ){ 1968 printSchemaLineN(p->out, z, j, "\n"); 1969 j = 0; 1970 } 1971 } 1972 z[j++] = c; 1973 if( nParen==1 && cEnd==0 1974 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 1975 ){ 1976 if( c=='\n' ) j--; 1977 printSchemaLineN(p->out, z, j, "\n "); 1978 j = 0; 1979 nLine++; 1980 while( IsSpace(z[i+1]) ){ i++; } 1981 } 1982 } 1983 z[j] = 0; 1984 } 1985 printSchemaLine(p->out, z, ";\n"); 1986 sqlite3_free(z); 1987 break; 1988 } 1989 case MODE_List: { 1990 if( p->cnt++==0 && p->showHeader ){ 1991 for(i=0; i<nArg; i++){ 1992 utf8_printf(p->out,"%s%s",azCol[i], 1993 i==nArg-1 ? p->rowSeparator : p->colSeparator); 1994 } 1995 } 1996 if( azArg==0 ) break; 1997 for(i=0; i<nArg; i++){ 1998 char *z = azArg[i]; 1999 if( z==0 ) z = p->nullValue; 2000 utf8_printf(p->out, "%s", z); 2001 if( i<nArg-1 ){ 2002 utf8_printf(p->out, "%s", p->colSeparator); 2003 }else{ 2004 utf8_printf(p->out, "%s", p->rowSeparator); 2005 } 2006 } 2007 break; 2008 } 2009 case MODE_Html: { 2010 if( p->cnt++==0 && p->showHeader ){ 2011 raw_printf(p->out,"<TR>"); 2012 for(i=0; i<nArg; i++){ 2013 raw_printf(p->out,"<TH>"); 2014 output_html_string(p->out, azCol[i]); 2015 raw_printf(p->out,"</TH>\n"); 2016 } 2017 raw_printf(p->out,"</TR>\n"); 2018 } 2019 if( azArg==0 ) break; 2020 raw_printf(p->out,"<TR>"); 2021 for(i=0; i<nArg; i++){ 2022 raw_printf(p->out,"<TD>"); 2023 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2024 raw_printf(p->out,"</TD>\n"); 2025 } 2026 raw_printf(p->out,"</TR>\n"); 2027 break; 2028 } 2029 case MODE_Tcl: { 2030 if( p->cnt++==0 && p->showHeader ){ 2031 for(i=0; i<nArg; i++){ 2032 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2033 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2034 } 2035 utf8_printf(p->out, "%s", p->rowSeparator); 2036 } 2037 if( azArg==0 ) break; 2038 for(i=0; i<nArg; i++){ 2039 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2040 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2041 } 2042 utf8_printf(p->out, "%s", p->rowSeparator); 2043 break; 2044 } 2045 case MODE_Csv: { 2046 setBinaryMode(p->out, 1); 2047 if( p->cnt++==0 && p->showHeader ){ 2048 for(i=0; i<nArg; i++){ 2049 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2050 } 2051 utf8_printf(p->out, "%s", p->rowSeparator); 2052 } 2053 if( nArg>0 ){ 2054 for(i=0; i<nArg; i++){ 2055 output_csv(p, azArg[i], i<nArg-1); 2056 } 2057 utf8_printf(p->out, "%s", p->rowSeparator); 2058 } 2059 setTextMode(p->out, 1); 2060 break; 2061 } 2062 case MODE_Insert: { 2063 if( azArg==0 ) break; 2064 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2065 if( p->showHeader ){ 2066 raw_printf(p->out,"("); 2067 for(i=0; i<nArg; i++){ 2068 if( i>0 ) raw_printf(p->out, ","); 2069 if( quoteChar(azCol[i]) ){ 2070 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2071 utf8_printf(p->out, "%s", z); 2072 sqlite3_free(z); 2073 }else{ 2074 raw_printf(p->out, "%s", azCol[i]); 2075 } 2076 } 2077 raw_printf(p->out,")"); 2078 } 2079 p->cnt++; 2080 for(i=0; i<nArg; i++){ 2081 raw_printf(p->out, i>0 ? "," : " VALUES("); 2082 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2083 utf8_printf(p->out,"NULL"); 2084 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2085 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2086 output_quoted_string(p->out, azArg[i]); 2087 }else{ 2088 output_quoted_escaped_string(p->out, azArg[i]); 2089 } 2090 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2091 utf8_printf(p->out,"%s", azArg[i]); 2092 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2093 char z[50]; 2094 double r = sqlite3_column_double(p->pStmt, i); 2095 sqlite3_uint64 ur; 2096 memcpy(&ur,&r,sizeof(r)); 2097 if( ur==0x7ff0000000000000LL ){ 2098 raw_printf(p->out, "1e999"); 2099 }else if( ur==0xfff0000000000000LL ){ 2100 raw_printf(p->out, "-1e999"); 2101 }else{ 2102 sqlite3_snprintf(50,z,"%!.20g", r); 2103 raw_printf(p->out, "%s", z); 2104 } 2105 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2106 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2107 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2108 output_hex_blob(p->out, pBlob, nBlob); 2109 }else if( isNumber(azArg[i], 0) ){ 2110 utf8_printf(p->out,"%s", azArg[i]); 2111 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2112 output_quoted_string(p->out, azArg[i]); 2113 }else{ 2114 output_quoted_escaped_string(p->out, azArg[i]); 2115 } 2116 } 2117 raw_printf(p->out,");\n"); 2118 break; 2119 } 2120 case MODE_Quote: { 2121 if( azArg==0 ) break; 2122 if( p->cnt==0 && p->showHeader ){ 2123 for(i=0; i<nArg; i++){ 2124 if( i>0 ) raw_printf(p->out, ","); 2125 output_quoted_string(p->out, azCol[i]); 2126 } 2127 raw_printf(p->out,"\n"); 2128 } 2129 p->cnt++; 2130 for(i=0; i<nArg; i++){ 2131 if( i>0 ) raw_printf(p->out, ","); 2132 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2133 utf8_printf(p->out,"NULL"); 2134 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2135 output_quoted_string(p->out, azArg[i]); 2136 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2137 utf8_printf(p->out,"%s", azArg[i]); 2138 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2139 char z[50]; 2140 double r = sqlite3_column_double(p->pStmt, i); 2141 sqlite3_snprintf(50,z,"%!.20g", r); 2142 raw_printf(p->out, "%s", z); 2143 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2144 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2145 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2146 output_hex_blob(p->out, pBlob, nBlob); 2147 }else if( isNumber(azArg[i], 0) ){ 2148 utf8_printf(p->out,"%s", azArg[i]); 2149 }else{ 2150 output_quoted_string(p->out, azArg[i]); 2151 } 2152 } 2153 raw_printf(p->out,"\n"); 2154 break; 2155 } 2156 case MODE_Ascii: { 2157 if( p->cnt++==0 && p->showHeader ){ 2158 for(i=0; i<nArg; i++){ 2159 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2160 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2161 } 2162 utf8_printf(p->out, "%s", p->rowSeparator); 2163 } 2164 if( azArg==0 ) break; 2165 for(i=0; i<nArg; i++){ 2166 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2167 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2168 } 2169 utf8_printf(p->out, "%s", p->rowSeparator); 2170 break; 2171 } 2172 case MODE_EQP: { 2173 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2174 break; 2175 } 2176 } 2177 return 0; 2178} 2179 2180/* 2181** This is the callback routine that the SQLite library 2182** invokes for each row of a query result. 2183*/ 2184static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2185 /* since we don't have type info, call the shell_callback with a NULL value */ 2186 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2187} 2188 2189/* 2190** This is the callback routine from sqlite3_exec() that appends all 2191** output onto the end of a ShellText object. 2192*/ 2193static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2194 ShellText *p = (ShellText*)pArg; 2195 int i; 2196 UNUSED_PARAMETER(az); 2197 if( azArg==0 ) return 0; 2198 if( p->n ) appendText(p, "|", 0); 2199 for(i=0; i<nArg; i++){ 2200 if( i ) appendText(p, ",", 0); 2201 if( azArg[i] ) appendText(p, azArg[i], 0); 2202 } 2203 return 0; 2204} 2205 2206/* 2207** Generate an appropriate SELFTEST table in the main database. 2208*/ 2209static void createSelftestTable(ShellState *p){ 2210 char *zErrMsg = 0; 2211 sqlite3_exec(p->db, 2212 "SAVEPOINT selftest_init;\n" 2213 "CREATE TABLE IF NOT EXISTS selftest(\n" 2214 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2215 " op TEXT,\n" /* Operator: memo run */ 2216 " cmd TEXT,\n" /* Command text */ 2217 " ans TEXT\n" /* Desired answer */ 2218 ");" 2219 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2220 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2221 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2222 " 'memo','Tests generated by --init');\n" 2223 "INSERT INTO [_shell$self]\n" 2224 " SELECT 'run',\n" 2225 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2226 "FROM sqlite_master ORDER BY 2'',224))',\n" 2227 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2228 "FROM sqlite_master ORDER BY 2',224));\n" 2229 "INSERT INTO [_shell$self]\n" 2230 " SELECT 'run'," 2231 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2232 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2233 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2234 " FROM (\n" 2235 " SELECT name FROM sqlite_master\n" 2236 " WHERE type='table'\n" 2237 " AND name<>'selftest'\n" 2238 " AND coalesce(rootpage,0)>0\n" 2239 " )\n" 2240 " ORDER BY name;\n" 2241 "INSERT INTO [_shell$self]\n" 2242 " VALUES('run','PRAGMA integrity_check','ok');\n" 2243 "INSERT INTO selftest(tno,op,cmd,ans)" 2244 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2245 "DROP TABLE [_shell$self];" 2246 ,0,0,&zErrMsg); 2247 if( zErrMsg ){ 2248 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2249 sqlite3_free(zErrMsg); 2250 } 2251 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2252} 2253 2254 2255/* 2256** Set the destination table field of the ShellState structure to 2257** the name of the table given. Escape any quote characters in the 2258** table name. 2259*/ 2260static void set_table_name(ShellState *p, const char *zName){ 2261 int i, n; 2262 char cQuote; 2263 char *z; 2264 2265 if( p->zDestTable ){ 2266 free(p->zDestTable); 2267 p->zDestTable = 0; 2268 } 2269 if( zName==0 ) return; 2270 cQuote = quoteChar(zName); 2271 n = strlen30(zName); 2272 if( cQuote ) n += n+2; 2273 z = p->zDestTable = malloc( n+1 ); 2274 if( z==0 ) shell_out_of_memory(); 2275 n = 0; 2276 if( cQuote ) z[n++] = cQuote; 2277 for(i=0; zName[i]; i++){ 2278 z[n++] = zName[i]; 2279 if( zName[i]==cQuote ) z[n++] = cQuote; 2280 } 2281 if( cQuote ) z[n++] = cQuote; 2282 z[n] = 0; 2283} 2284 2285 2286/* 2287** Execute a query statement that will generate SQL output. Print 2288** the result columns, comma-separated, on a line and then add a 2289** semicolon terminator to the end of that line. 2290** 2291** If the number of columns is 1 and that column contains text "--" 2292** then write the semicolon on a separate line. That way, if a 2293** "--" comment occurs at the end of the statement, the comment 2294** won't consume the semicolon terminator. 2295*/ 2296static int run_table_dump_query( 2297 ShellState *p, /* Query context */ 2298 const char *zSelect, /* SELECT statement to extract content */ 2299 const char *zFirstRow /* Print before first row, if not NULL */ 2300){ 2301 sqlite3_stmt *pSelect; 2302 int rc; 2303 int nResult; 2304 int i; 2305 const char *z; 2306 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2307 if( rc!=SQLITE_OK || !pSelect ){ 2308 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2309 sqlite3_errmsg(p->db)); 2310 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2311 return rc; 2312 } 2313 rc = sqlite3_step(pSelect); 2314 nResult = sqlite3_column_count(pSelect); 2315 while( rc==SQLITE_ROW ){ 2316 if( zFirstRow ){ 2317 utf8_printf(p->out, "%s", zFirstRow); 2318 zFirstRow = 0; 2319 } 2320 z = (const char*)sqlite3_column_text(pSelect, 0); 2321 utf8_printf(p->out, "%s", z); 2322 for(i=1; i<nResult; i++){ 2323 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2324 } 2325 if( z==0 ) z = ""; 2326 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2327 if( z[0] ){ 2328 raw_printf(p->out, "\n;\n"); 2329 }else{ 2330 raw_printf(p->out, ";\n"); 2331 } 2332 rc = sqlite3_step(pSelect); 2333 } 2334 rc = sqlite3_finalize(pSelect); 2335 if( rc!=SQLITE_OK ){ 2336 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2337 sqlite3_errmsg(p->db)); 2338 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2339 } 2340 return rc; 2341} 2342 2343/* 2344** Allocate space and save off current error string. 2345*/ 2346static char *save_err_msg( 2347 sqlite3 *db /* Database to query */ 2348){ 2349 int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); 2350 char *zErrMsg = sqlite3_malloc64(nErrMsg); 2351 if( zErrMsg ){ 2352 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); 2353 } 2354 return zErrMsg; 2355} 2356 2357#ifdef __linux__ 2358/* 2359** Attempt to display I/O stats on Linux using /proc/PID/io 2360*/ 2361static void displayLinuxIoStats(FILE *out){ 2362 FILE *in; 2363 char z[200]; 2364 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2365 in = fopen(z, "rb"); 2366 if( in==0 ) return; 2367 while( fgets(z, sizeof(z), in)!=0 ){ 2368 static const struct { 2369 const char *zPattern; 2370 const char *zDesc; 2371 } aTrans[] = { 2372 { "rchar: ", "Bytes received by read():" }, 2373 { "wchar: ", "Bytes sent to write():" }, 2374 { "syscr: ", "Read() system calls:" }, 2375 { "syscw: ", "Write() system calls:" }, 2376 { "read_bytes: ", "Bytes read from storage:" }, 2377 { "write_bytes: ", "Bytes written to storage:" }, 2378 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2379 }; 2380 int i; 2381 for(i=0; i<ArraySize(aTrans); i++){ 2382 int n = strlen30(aTrans[i].zPattern); 2383 if( strncmp(aTrans[i].zPattern, z, n)==0 ){ 2384 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2385 break; 2386 } 2387 } 2388 } 2389 fclose(in); 2390} 2391#endif 2392 2393/* 2394** Display a single line of status using 64-bit values. 2395*/ 2396static void displayStatLine( 2397 ShellState *p, /* The shell context */ 2398 char *zLabel, /* Label for this one line */ 2399 char *zFormat, /* Format for the result */ 2400 int iStatusCtrl, /* Which status to display */ 2401 int bReset /* True to reset the stats */ 2402){ 2403 sqlite3_int64 iCur = -1; 2404 sqlite3_int64 iHiwtr = -1; 2405 int i, nPercent; 2406 char zLine[200]; 2407 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2408 for(i=0, nPercent=0; zFormat[i]; i++){ 2409 if( zFormat[i]=='%' ) nPercent++; 2410 } 2411 if( nPercent>1 ){ 2412 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2413 }else{ 2414 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2415 } 2416 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2417} 2418 2419/* 2420** Display memory stats. 2421*/ 2422static int display_stats( 2423 sqlite3 *db, /* Database to query */ 2424 ShellState *pArg, /* Pointer to ShellState */ 2425 int bReset /* True to reset the stats */ 2426){ 2427 int iCur; 2428 int iHiwtr; 2429 FILE *out; 2430 if( pArg==0 || pArg->out==0 ) return 0; 2431 out = pArg->out; 2432 2433 if( pArg->pStmt && (pArg->statsOn & 2) ){ 2434 int nCol, i, x; 2435 sqlite3_stmt *pStmt = pArg->pStmt; 2436 char z[100]; 2437 nCol = sqlite3_column_count(pStmt); 2438 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2439 for(i=0; i<nCol; i++){ 2440 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2441 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2442#ifndef SQLITE_OMIT_DECLTYPE 2443 sqlite3_snprintf(30, z+x, "declared type:"); 2444 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2445#endif 2446#ifdef SQLITE_ENABLE_COLUMN_METADATA 2447 sqlite3_snprintf(30, z+x, "database name:"); 2448 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2449 sqlite3_snprintf(30, z+x, "table name:"); 2450 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2451 sqlite3_snprintf(30, z+x, "origin name:"); 2452 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2453#endif 2454 } 2455 } 2456 2457 displayStatLine(pArg, "Memory Used:", 2458 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2459 displayStatLine(pArg, "Number of Outstanding Allocations:", 2460 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2461 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2462 displayStatLine(pArg, "Number of Pcache Pages Used:", 2463 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2464 } 2465 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2466 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2467 displayStatLine(pArg, "Largest Allocation:", 2468 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2469 displayStatLine(pArg, "Largest Pcache Allocation:", 2470 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2471#ifdef YYTRACKMAXSTACKDEPTH 2472 displayStatLine(pArg, "Deepest Parser Stack:", 2473 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2474#endif 2475 2476 if( db ){ 2477 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2478 iHiwtr = iCur = -1; 2479 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2480 &iCur, &iHiwtr, bReset); 2481 raw_printf(pArg->out, 2482 "Lookaside Slots Used: %d (max %d)\n", 2483 iCur, iHiwtr); 2484 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2485 &iCur, &iHiwtr, bReset); 2486 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2487 iHiwtr); 2488 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2489 &iCur, &iHiwtr, bReset); 2490 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2491 iHiwtr); 2492 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2493 &iCur, &iHiwtr, bReset); 2494 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2495 iHiwtr); 2496 } 2497 iHiwtr = iCur = -1; 2498 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2499 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2500 iCur); 2501 iHiwtr = iCur = -1; 2502 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2503 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2504 iHiwtr = iCur = -1; 2505 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2506 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2507 iHiwtr = iCur = -1; 2508 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2509 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2510 iHiwtr = iCur = -1; 2511 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2512 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2513 iHiwtr = iCur = -1; 2514 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2515 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2516 iCur); 2517 iHiwtr = iCur = -1; 2518 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2519 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2520 iCur); 2521 } 2522 2523 if( pArg->pStmt ){ 2524 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2525 bReset); 2526 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2527 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2528 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2529 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2530 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2531 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2532 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2533 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset); 2534 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2535 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2536 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2537 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2538 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2539 } 2540 2541#ifdef __linux__ 2542 displayLinuxIoStats(pArg->out); 2543#endif 2544 2545 /* Do not remove this machine readable comment: extra-stats-output-here */ 2546 2547 return 0; 2548} 2549 2550/* 2551** Display scan stats. 2552*/ 2553static void display_scanstats( 2554 sqlite3 *db, /* Database to query */ 2555 ShellState *pArg /* Pointer to ShellState */ 2556){ 2557#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2558 UNUSED_PARAMETER(db); 2559 UNUSED_PARAMETER(pArg); 2560#else 2561 int i, k, n, mx; 2562 raw_printf(pArg->out, "-------- scanstats --------\n"); 2563 mx = 0; 2564 for(k=0; k<=mx; k++){ 2565 double rEstLoop = 1.0; 2566 for(i=n=0; 1; i++){ 2567 sqlite3_stmt *p = pArg->pStmt; 2568 sqlite3_int64 nLoop, nVisit; 2569 double rEst; 2570 int iSid; 2571 const char *zExplain; 2572 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2573 break; 2574 } 2575 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2576 if( iSid>mx ) mx = iSid; 2577 if( iSid!=k ) continue; 2578 if( n==0 ){ 2579 rEstLoop = (double)nLoop; 2580 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2581 } 2582 n++; 2583 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2584 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 2585 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 2586 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 2587 rEstLoop *= rEst; 2588 raw_printf(pArg->out, 2589 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 2590 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 2591 ); 2592 } 2593 } 2594 raw_printf(pArg->out, "---------------------------\n"); 2595#endif 2596} 2597 2598/* 2599** Parameter azArray points to a zero-terminated array of strings. zStr 2600** points to a single nul-terminated string. Return non-zero if zStr 2601** is equal, according to strcmp(), to any of the strings in the array. 2602** Otherwise, return zero. 2603*/ 2604static int str_in_array(const char *zStr, const char **azArray){ 2605 int i; 2606 for(i=0; azArray[i]; i++){ 2607 if( 0==strcmp(zStr, azArray[i]) ) return 1; 2608 } 2609 return 0; 2610} 2611 2612/* 2613** If compiled statement pSql appears to be an EXPLAIN statement, allocate 2614** and populate the ShellState.aiIndent[] array with the number of 2615** spaces each opcode should be indented before it is output. 2616** 2617** The indenting rules are: 2618** 2619** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 2620** all opcodes that occur between the p2 jump destination and the opcode 2621** itself by 2 spaces. 2622** 2623** * For each "Goto", if the jump destination is earlier in the program 2624** and ends on one of: 2625** Yield SeekGt SeekLt RowSetRead Rewind 2626** or if the P1 parameter is one instead of zero, 2627** then indent all opcodes between the earlier instruction 2628** and "Goto" by 2 spaces. 2629*/ 2630static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 2631 const char *zSql; /* The text of the SQL statement */ 2632 const char *z; /* Used to check if this is an EXPLAIN */ 2633 int *abYield = 0; /* True if op is an OP_Yield */ 2634 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 2635 int iOp; /* Index of operation in p->aiIndent[] */ 2636 2637 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 }; 2638 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 2639 "Rewind", 0 }; 2640 const char *azGoto[] = { "Goto", 0 }; 2641 2642 /* Try to figure out if this is really an EXPLAIN statement. If this 2643 ** cannot be verified, return early. */ 2644 if( sqlite3_column_count(pSql)!=8 ){ 2645 p->cMode = p->mode; 2646 return; 2647 } 2648 zSql = sqlite3_sql(pSql); 2649 if( zSql==0 ) return; 2650 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 2651 if( sqlite3_strnicmp(z, "explain", 7) ){ 2652 p->cMode = p->mode; 2653 return; 2654 } 2655 2656 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 2657 int i; 2658 int iAddr = sqlite3_column_int(pSql, 0); 2659 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 2660 2661 /* Set p2 to the P2 field of the current opcode. Then, assuming that 2662 ** p2 is an instruction address, set variable p2op to the index of that 2663 ** instruction in the aiIndent[] array. p2 and p2op may be different if 2664 ** the current instruction is part of a sub-program generated by an 2665 ** SQL trigger or foreign key. */ 2666 int p2 = sqlite3_column_int(pSql, 3); 2667 int p2op = (p2 + (iOp-iAddr)); 2668 2669 /* Grow the p->aiIndent array as required */ 2670 if( iOp>=nAlloc ){ 2671 if( iOp==0 ){ 2672 /* Do further verfication that this is explain output. Abort if 2673 ** it is not */ 2674 static const char *explainCols[] = { 2675 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 2676 int jj; 2677 for(jj=0; jj<ArraySize(explainCols); jj++){ 2678 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 2679 p->cMode = p->mode; 2680 sqlite3_reset(pSql); 2681 return; 2682 } 2683 } 2684 } 2685 nAlloc += 100; 2686 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 2687 if( p->aiIndent==0 ) shell_out_of_memory(); 2688 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 2689 if( abYield==0 ) shell_out_of_memory(); 2690 } 2691 abYield[iOp] = str_in_array(zOp, azYield); 2692 p->aiIndent[iOp] = 0; 2693 p->nIndent = iOp+1; 2694 2695 if( str_in_array(zOp, azNext) ){ 2696 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2697 } 2698 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 2699 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 2700 ){ 2701 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 2702 } 2703 } 2704 2705 p->iIndent = 0; 2706 sqlite3_free(abYield); 2707 sqlite3_reset(pSql); 2708} 2709 2710/* 2711** Free the array allocated by explain_data_prepare(). 2712*/ 2713static void explain_data_delete(ShellState *p){ 2714 sqlite3_free(p->aiIndent); 2715 p->aiIndent = 0; 2716 p->nIndent = 0; 2717 p->iIndent = 0; 2718} 2719 2720/* 2721** Disable and restore .wheretrace and .selecttrace settings. 2722*/ 2723#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2724extern int sqlite3SelectTrace; 2725static int savedSelectTrace; 2726#endif 2727#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2728extern int sqlite3WhereTrace; 2729static int savedWhereTrace; 2730#endif 2731static void disable_debug_trace_modes(void){ 2732#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2733 savedSelectTrace = sqlite3SelectTrace; 2734 sqlite3SelectTrace = 0; 2735#endif 2736#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2737 savedWhereTrace = sqlite3WhereTrace; 2738 sqlite3WhereTrace = 0; 2739#endif 2740} 2741static void restore_debug_trace_modes(void){ 2742#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 2743 sqlite3SelectTrace = savedSelectTrace; 2744#endif 2745#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 2746 sqlite3WhereTrace = savedWhereTrace; 2747#endif 2748} 2749 2750/* Name of the TEMP table that holds bind parameter values */ 2751#define BIND_PARAM_TABLE "$Parameters" 2752 2753/* Create the TEMP table used to store parameter bindings */ 2754static void bind_table_init(ShellState *p){ 2755 sqlite3_exec(p->db, 2756 "CREATE TABLE IF NOT EXISTS temp.[" BIND_PARAM_TABLE "](\n" 2757 " key TEXT PRIMARY KEY,\n" 2758 " value ANY\n" 2759 ") WITHOUT ROWID;", 2760 0, 0, 0); 2761} 2762 2763/* 2764** Bind parameters on a prepared statement. 2765** 2766** Parameter bindings are taken from a TEMP table of the form: 2767** 2768** CREATE TEMP TABLE "$Parameters"(key TEXT PRIMARY KEY, value) 2769** WITHOUT ROWID; 2770** 2771** No bindings occur if this table does not exist. The special character '$' 2772** is included in the table name to help prevent collisions with actual tables. 2773** The table must be in the TEMP schema. 2774*/ 2775static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 2776 int nVar; 2777 int i; 2778 int rc; 2779 sqlite3_stmt *pQ = 0; 2780 2781 nVar = sqlite3_bind_parameter_count(pStmt); 2782 if( nVar==0 ) return; /* Nothing to do */ 2783 if( sqlite3_table_column_metadata(pArg->db, "TEMP", BIND_PARAM_TABLE, 2784 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 2785 return; /* Parameter table does not exist */ 2786 } 2787 rc = sqlite3_prepare_v2(pArg->db, 2788 "SELECT value FROM temp.\"" BIND_PARAM_TABLE "\"" 2789 " WHERE key=?1", -1, &pQ, 0); 2790 if( rc || pQ==0 ) return; 2791 for(i=1; i<=nVar; i++){ 2792 char zNum[30]; 2793 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 2794 if( zVar==0 ){ 2795 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 2796 zVar = zNum; 2797 } 2798 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 2799 if( sqlite3_step(pQ)==SQLITE_ROW ){ 2800 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 2801 }else{ 2802 sqlite3_bind_null(pStmt, i); 2803 } 2804 sqlite3_reset(pQ); 2805 } 2806 sqlite3_finalize(pQ); 2807} 2808 2809/* 2810** Run a prepared statement 2811*/ 2812static void exec_prepared_stmt( 2813 ShellState *pArg, /* Pointer to ShellState */ 2814 sqlite3_stmt *pStmt /* Statment to run */ 2815){ 2816 int rc; 2817 2818 /* perform the first step. this will tell us if we 2819 ** have a result set or not and how wide it is. 2820 */ 2821 rc = sqlite3_step(pStmt); 2822 /* if we have a result set... */ 2823 if( SQLITE_ROW == rc ){ 2824 /* allocate space for col name ptr, value ptr, and type */ 2825 int nCol = sqlite3_column_count(pStmt); 2826 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 2827 if( !pData ){ 2828 rc = SQLITE_NOMEM; 2829 }else{ 2830 char **azCols = (char **)pData; /* Names of result columns */ 2831 char **azVals = &azCols[nCol]; /* Results */ 2832 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 2833 int i, x; 2834 assert(sizeof(int) <= sizeof(char *)); 2835 /* save off ptrs to column names */ 2836 for(i=0; i<nCol; i++){ 2837 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 2838 } 2839 do{ 2840 /* extract the data and data types */ 2841 for(i=0; i<nCol; i++){ 2842 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 2843 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ 2844 azVals[i] = ""; 2845 }else{ 2846 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 2847 } 2848 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 2849 rc = SQLITE_NOMEM; 2850 break; /* from for */ 2851 } 2852 } /* end for */ 2853 2854 /* if data and types extracted successfully... */ 2855 if( SQLITE_ROW == rc ){ 2856 /* call the supplied callback with the result row data */ 2857 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 2858 rc = SQLITE_ABORT; 2859 }else{ 2860 rc = sqlite3_step(pStmt); 2861 } 2862 } 2863 } while( SQLITE_ROW == rc ); 2864 sqlite3_free(pData); 2865 } 2866 } 2867} 2868 2869#ifndef SQLITE_OMIT_VIRTUALTABLE 2870/* 2871** This function is called to process SQL if the previous shell command 2872** was ".expert". It passes the SQL in the second argument directly to 2873** the sqlite3expert object. 2874** 2875** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2876** code. In this case, (*pzErr) may be set to point to a buffer containing 2877** an English language error message. It is the responsibility of the 2878** caller to eventually free this buffer using sqlite3_free(). 2879*/ 2880static int expertHandleSQL( 2881 ShellState *pState, 2882 const char *zSql, 2883 char **pzErr 2884){ 2885 assert( pState->expert.pExpert ); 2886 assert( pzErr==0 || *pzErr==0 ); 2887 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 2888} 2889 2890/* 2891** This function is called either to silently clean up the object 2892** created by the ".expert" command (if bCancel==1), or to generate a 2893** report from it and then clean it up (if bCancel==0). 2894** 2895** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 2896** code. In this case, (*pzErr) may be set to point to a buffer containing 2897** an English language error message. It is the responsibility of the 2898** caller to eventually free this buffer using sqlite3_free(). 2899*/ 2900static int expertFinish( 2901 ShellState *pState, 2902 int bCancel, 2903 char **pzErr 2904){ 2905 int rc = SQLITE_OK; 2906 sqlite3expert *p = pState->expert.pExpert; 2907 assert( p ); 2908 assert( bCancel || pzErr==0 || *pzErr==0 ); 2909 if( bCancel==0 ){ 2910 FILE *out = pState->out; 2911 int bVerbose = pState->expert.bVerbose; 2912 2913 rc = sqlite3_expert_analyze(p, pzErr); 2914 if( rc==SQLITE_OK ){ 2915 int nQuery = sqlite3_expert_count(p); 2916 int i; 2917 2918 if( bVerbose ){ 2919 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 2920 raw_printf(out, "-- Candidates -----------------------------\n"); 2921 raw_printf(out, "%s\n", zCand); 2922 } 2923 for(i=0; i<nQuery; i++){ 2924 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 2925 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 2926 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 2927 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 2928 if( bVerbose ){ 2929 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 2930 raw_printf(out, "%s\n\n", zSql); 2931 } 2932 raw_printf(out, "%s\n", zIdx); 2933 raw_printf(out, "%s\n", zEQP); 2934 } 2935 } 2936 } 2937 sqlite3_expert_destroy(p); 2938 pState->expert.pExpert = 0; 2939 return rc; 2940} 2941 2942/* 2943** Implementation of ".expert" dot command. 2944*/ 2945static int expertDotCommand( 2946 ShellState *pState, /* Current shell tool state */ 2947 char **azArg, /* Array of arguments passed to dot command */ 2948 int nArg /* Number of entries in azArg[] */ 2949){ 2950 int rc = SQLITE_OK; 2951 char *zErr = 0; 2952 int i; 2953 int iSample = 0; 2954 2955 assert( pState->expert.pExpert==0 ); 2956 memset(&pState->expert, 0, sizeof(ExpertInfo)); 2957 2958 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 2959 char *z = azArg[i]; 2960 int n; 2961 if( z[0]=='-' && z[1]=='-' ) z++; 2962 n = strlen30(z); 2963 if( n>=2 && 0==strncmp(z, "-verbose", n) ){ 2964 pState->expert.bVerbose = 1; 2965 } 2966 else if( n>=2 && 0==strncmp(z, "-sample", n) ){ 2967 if( i==(nArg-1) ){ 2968 raw_printf(stderr, "option requires an argument: %s\n", z); 2969 rc = SQLITE_ERROR; 2970 }else{ 2971 iSample = (int)integerValue(azArg[++i]); 2972 if( iSample<0 || iSample>100 ){ 2973 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 2974 rc = SQLITE_ERROR; 2975 } 2976 } 2977 } 2978 else{ 2979 raw_printf(stderr, "unknown option: %s\n", z); 2980 rc = SQLITE_ERROR; 2981 } 2982 } 2983 2984 if( rc==SQLITE_OK ){ 2985 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 2986 if( pState->expert.pExpert==0 ){ 2987 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr); 2988 rc = SQLITE_ERROR; 2989 }else{ 2990 sqlite3_expert_config( 2991 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 2992 ); 2993 } 2994 } 2995 2996 return rc; 2997} 2998#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 2999 3000/* 3001** Execute a statement or set of statements. Print 3002** any result rows/columns depending on the current mode 3003** set via the supplied callback. 3004** 3005** This is very similar to SQLite's built-in sqlite3_exec() 3006** function except it takes a slightly different callback 3007** and callback data argument. 3008*/ 3009static int shell_exec( 3010 ShellState *pArg, /* Pointer to ShellState */ 3011 const char *zSql, /* SQL to be evaluated */ 3012 char **pzErrMsg /* Error msg written here */ 3013){ 3014 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3015 int rc = SQLITE_OK; /* Return Code */ 3016 int rc2; 3017 const char *zLeftover; /* Tail of unprocessed SQL */ 3018 sqlite3 *db = pArg->db; 3019 3020 if( pzErrMsg ){ 3021 *pzErrMsg = NULL; 3022 } 3023 3024#ifndef SQLITE_OMIT_VIRTUALTABLE 3025 if( pArg->expert.pExpert ){ 3026 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3027 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3028 } 3029#endif 3030 3031 while( zSql[0] && (SQLITE_OK == rc) ){ 3032 static const char *zStmtSql; 3033 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3034 if( SQLITE_OK != rc ){ 3035 if( pzErrMsg ){ 3036 *pzErrMsg = save_err_msg(db); 3037 } 3038 }else{ 3039 if( !pStmt ){ 3040 /* this happens for a comment or white-space */ 3041 zSql = zLeftover; 3042 while( IsSpace(zSql[0]) ) zSql++; 3043 continue; 3044 } 3045 zStmtSql = sqlite3_sql(pStmt); 3046 if( zStmtSql==0 ) zStmtSql = ""; 3047 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3048 3049 /* save off the prepared statment handle and reset row count */ 3050 if( pArg ){ 3051 pArg->pStmt = pStmt; 3052 pArg->cnt = 0; 3053 } 3054 3055 /* echo the sql statement if echo on */ 3056 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){ 3057 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); 3058 } 3059 3060 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3061 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3062 sqlite3_stmt *pExplain; 3063 char *zEQP; 3064 int triggerEQP = 0; 3065 disable_debug_trace_modes(); 3066 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3067 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3068 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3069 } 3070 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3071 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3072 if( rc==SQLITE_OK ){ 3073 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3074 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3075 int iEqpId = sqlite3_column_int(pExplain, 0); 3076 int iParentId = sqlite3_column_int(pExplain, 1); 3077 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3078 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3079 } 3080 eqp_render(pArg); 3081 } 3082 sqlite3_finalize(pExplain); 3083 sqlite3_free(zEQP); 3084 if( pArg->autoEQP>=AUTOEQP_full ){ 3085 /* Also do an EXPLAIN for ".eqp full" mode */ 3086 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3087 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3088 if( rc==SQLITE_OK ){ 3089 pArg->cMode = MODE_Explain; 3090 explain_data_prepare(pArg, pExplain); 3091 exec_prepared_stmt(pArg, pExplain); 3092 explain_data_delete(pArg); 3093 } 3094 sqlite3_finalize(pExplain); 3095 sqlite3_free(zEQP); 3096 } 3097 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3098 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3099 /* Reprepare pStmt before reactiving trace modes */ 3100 sqlite3_finalize(pStmt); 3101 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3102 if( pArg ) pArg->pStmt = pStmt; 3103 } 3104 restore_debug_trace_modes(); 3105 } 3106 3107 if( pArg ){ 3108 pArg->cMode = pArg->mode; 3109 if( pArg->autoExplain ){ 3110 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3111 pArg->cMode = MODE_Explain; 3112 } 3113 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3114 pArg->cMode = MODE_EQP; 3115 } 3116 } 3117 3118 /* If the shell is currently in ".explain" mode, gather the extra 3119 ** data required to add indents to the output.*/ 3120 if( pArg->cMode==MODE_Explain ){ 3121 explain_data_prepare(pArg, pStmt); 3122 } 3123 } 3124 3125 bind_prepared_stmt(pArg, pStmt); 3126 exec_prepared_stmt(pArg, pStmt); 3127 explain_data_delete(pArg); 3128 eqp_render(pArg); 3129 3130 /* print usage stats if stats on */ 3131 if( pArg && pArg->statsOn ){ 3132 display_stats(db, pArg, 0); 3133 } 3134 3135 /* print loop-counters if required */ 3136 if( pArg && pArg->scanstatsOn ){ 3137 display_scanstats(db, pArg); 3138 } 3139 3140 /* Finalize the statement just executed. If this fails, save a 3141 ** copy of the error message. Otherwise, set zSql to point to the 3142 ** next statement to execute. */ 3143 rc2 = sqlite3_finalize(pStmt); 3144 if( rc!=SQLITE_NOMEM ) rc = rc2; 3145 if( rc==SQLITE_OK ){ 3146 zSql = zLeftover; 3147 while( IsSpace(zSql[0]) ) zSql++; 3148 }else if( pzErrMsg ){ 3149 *pzErrMsg = save_err_msg(db); 3150 } 3151 3152 /* clear saved stmt handle */ 3153 if( pArg ){ 3154 pArg->pStmt = NULL; 3155 } 3156 } 3157 } /* end while */ 3158 3159 return rc; 3160} 3161 3162/* 3163** Release memory previously allocated by tableColumnList(). 3164*/ 3165static void freeColumnList(char **azCol){ 3166 int i; 3167 for(i=1; azCol[i]; i++){ 3168 sqlite3_free(azCol[i]); 3169 } 3170 /* azCol[0] is a static string */ 3171 sqlite3_free(azCol); 3172} 3173 3174/* 3175** Return a list of pointers to strings which are the names of all 3176** columns in table zTab. The memory to hold the names is dynamically 3177** allocated and must be released by the caller using a subsequent call 3178** to freeColumnList(). 3179** 3180** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 3181** value that needs to be preserved, then azCol[0] is filled in with the 3182** name of the rowid column. 3183** 3184** The first regular column in the table is azCol[1]. The list is terminated 3185** by an entry with azCol[i]==0. 3186*/ 3187static char **tableColumnList(ShellState *p, const char *zTab){ 3188 char **azCol = 0; 3189 sqlite3_stmt *pStmt; 3190 char *zSql; 3191 int nCol = 0; 3192 int nAlloc = 0; 3193 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 3194 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 3195 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 3196 int rc; 3197 3198 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 3199 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3200 sqlite3_free(zSql); 3201 if( rc ) return 0; 3202 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 3203 if( nCol>=nAlloc-2 ){ 3204 nAlloc = nAlloc*2 + nCol + 10; 3205 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 3206 if( azCol==0 ) shell_out_of_memory(); 3207 } 3208 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 3209 if( sqlite3_column_int(pStmt, 5) ){ 3210 nPK++; 3211 if( nPK==1 3212 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 3213 "INTEGER")==0 3214 ){ 3215 isIPK = 1; 3216 }else{ 3217 isIPK = 0; 3218 } 3219 } 3220 } 3221 sqlite3_finalize(pStmt); 3222 if( azCol==0 ) return 0; 3223 azCol[0] = 0; 3224 azCol[nCol+1] = 0; 3225 3226 /* The decision of whether or not a rowid really needs to be preserved 3227 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 3228 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 3229 ** rowids on tables where the rowid is inaccessible because there are other 3230 ** columns in the table named "rowid", "_rowid_", and "oid". 3231 */ 3232 if( preserveRowid && isIPK ){ 3233 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 3234 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 3235 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 3236 ** ROWID aliases. To distinguish these cases, check to see if 3237 ** there is a "pk" entry in "PRAGMA index_list". There will be 3238 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 3239 */ 3240 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 3241 " WHERE origin='pk'", zTab); 3242 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 3243 sqlite3_free(zSql); 3244 if( rc ){ 3245 freeColumnList(azCol); 3246 return 0; 3247 } 3248 rc = sqlite3_step(pStmt); 3249 sqlite3_finalize(pStmt); 3250 preserveRowid = rc==SQLITE_ROW; 3251 } 3252 if( preserveRowid ){ 3253 /* Only preserve the rowid if we can find a name to use for the 3254 ** rowid */ 3255 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 3256 int i, j; 3257 for(j=0; j<3; j++){ 3258 for(i=1; i<=nCol; i++){ 3259 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 3260 } 3261 if( i>nCol ){ 3262 /* At this point, we know that azRowid[j] is not the name of any 3263 ** ordinary column in the table. Verify that azRowid[j] is a valid 3264 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 3265 ** tables will fail this last check */ 3266 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 3267 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 3268 break; 3269 } 3270 } 3271 } 3272 return azCol; 3273} 3274 3275/* 3276** Toggle the reverse_unordered_selects setting. 3277*/ 3278static void toggleSelectOrder(sqlite3 *db){ 3279 sqlite3_stmt *pStmt = 0; 3280 int iSetting = 0; 3281 char zStmt[100]; 3282 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 3283 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 3284 iSetting = sqlite3_column_int(pStmt, 0); 3285 } 3286 sqlite3_finalize(pStmt); 3287 sqlite3_snprintf(sizeof(zStmt), zStmt, 3288 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 3289 sqlite3_exec(db, zStmt, 0, 0, 0); 3290} 3291 3292/* 3293** This is a different callback routine used for dumping the database. 3294** Each row received by this callback consists of a table name, 3295** the table type ("index" or "table") and SQL to create the table. 3296** This routine should print text sufficient to recreate the table. 3297*/ 3298static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 3299 int rc; 3300 const char *zTable; 3301 const char *zType; 3302 const char *zSql; 3303 ShellState *p = (ShellState *)pArg; 3304 3305 UNUSED_PARAMETER(azNotUsed); 3306 if( nArg!=3 || azArg==0 ) return 0; 3307 zTable = azArg[0]; 3308 zType = azArg[1]; 3309 zSql = azArg[2]; 3310 3311 if( strcmp(zTable, "sqlite_sequence")==0 ){ 3312 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 3313 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ 3314 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 3315 }else if( strncmp(zTable, "sqlite_", 7)==0 ){ 3316 return 0; 3317 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 3318 char *zIns; 3319 if( !p->writableSchema ){ 3320 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 3321 p->writableSchema = 1; 3322 } 3323 zIns = sqlite3_mprintf( 3324 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" 3325 "VALUES('table','%q','%q',0,'%q');", 3326 zTable, zTable, zSql); 3327 utf8_printf(p->out, "%s\n", zIns); 3328 sqlite3_free(zIns); 3329 return 0; 3330 }else{ 3331 printSchemaLine(p->out, zSql, ";\n"); 3332 } 3333 3334 if( strcmp(zType, "table")==0 ){ 3335 ShellText sSelect; 3336 ShellText sTable; 3337 char **azCol; 3338 int i; 3339 char *savedDestTable; 3340 int savedMode; 3341 3342 azCol = tableColumnList(p, zTable); 3343 if( azCol==0 ){ 3344 p->nErr++; 3345 return 0; 3346 } 3347 3348 /* Always quote the table name, even if it appears to be pure ascii, 3349 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 3350 initText(&sTable); 3351 appendText(&sTable, zTable, quoteChar(zTable)); 3352 /* If preserving the rowid, add a column list after the table name. 3353 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 3354 ** instead of the usual "INSERT INTO tab VALUES(...)". 3355 */ 3356 if( azCol[0] ){ 3357 appendText(&sTable, "(", 0); 3358 appendText(&sTable, azCol[0], 0); 3359 for(i=1; azCol[i]; i++){ 3360 appendText(&sTable, ",", 0); 3361 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 3362 } 3363 appendText(&sTable, ")", 0); 3364 } 3365 3366 /* Build an appropriate SELECT statement */ 3367 initText(&sSelect); 3368 appendText(&sSelect, "SELECT ", 0); 3369 if( azCol[0] ){ 3370 appendText(&sSelect, azCol[0], 0); 3371 appendText(&sSelect, ",", 0); 3372 } 3373 for(i=1; azCol[i]; i++){ 3374 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 3375 if( azCol[i+1] ){ 3376 appendText(&sSelect, ",", 0); 3377 } 3378 } 3379 freeColumnList(azCol); 3380 appendText(&sSelect, " FROM ", 0); 3381 appendText(&sSelect, zTable, quoteChar(zTable)); 3382 3383 savedDestTable = p->zDestTable; 3384 savedMode = p->mode; 3385 p->zDestTable = sTable.z; 3386 p->mode = p->cMode = MODE_Insert; 3387 rc = shell_exec(p, sSelect.z, 0); 3388 if( (rc&0xff)==SQLITE_CORRUPT ){ 3389 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3390 toggleSelectOrder(p->db); 3391 shell_exec(p, sSelect.z, 0); 3392 toggleSelectOrder(p->db); 3393 } 3394 p->zDestTable = savedDestTable; 3395 p->mode = savedMode; 3396 freeText(&sTable); 3397 freeText(&sSelect); 3398 if( rc ) p->nErr++; 3399 } 3400 return 0; 3401} 3402 3403/* 3404** Run zQuery. Use dump_callback() as the callback routine so that 3405** the contents of the query are output as SQL statements. 3406** 3407** If we get a SQLITE_CORRUPT error, rerun the query after appending 3408** "ORDER BY rowid DESC" to the end. 3409*/ 3410static int run_schema_dump_query( 3411 ShellState *p, 3412 const char *zQuery 3413){ 3414 int rc; 3415 char *zErr = 0; 3416 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 3417 if( rc==SQLITE_CORRUPT ){ 3418 char *zQ2; 3419 int len = strlen30(zQuery); 3420 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 3421 if( zErr ){ 3422 utf8_printf(p->out, "/****** %s ******/\n", zErr); 3423 sqlite3_free(zErr); 3424 zErr = 0; 3425 } 3426 zQ2 = malloc( len+100 ); 3427 if( zQ2==0 ) return rc; 3428 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 3429 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 3430 if( rc ){ 3431 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 3432 }else{ 3433 rc = SQLITE_CORRUPT; 3434 } 3435 sqlite3_free(zErr); 3436 free(zQ2); 3437 } 3438 return rc; 3439} 3440 3441/* 3442** Text of help messages. 3443** 3444** The help text for each individual command begins with a line that starts 3445** with ".". Subsequent lines are supplimental information. 3446** 3447** There must be two or more spaces between the end of the command and the 3448** start of the description of what that command does. 3449*/ 3450static const char *(azHelp[]) = { 3451#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 3452 ".archive ... Manage SQL archives", 3453 " Each command must have exactly one of the following options:", 3454 " -c, --create Create a new archive", 3455 " -u, --update Update or add files to an existing archive", 3456 " -t, --list List contents of archive", 3457 " -x, --extract Extract files from archive", 3458 " Optional arguments:", 3459 " -v, --verbose Print each filename as it is processed", 3460 " -f FILE, --file FILE Operate on archive FILE (default is current db)", 3461 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS", 3462 " -C DIR, --directory DIR Change to directory DIR to read/extract files", 3463 " -n, --dryrun Show the SQL that would have occurred", 3464 " Examples:", 3465 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar", 3466 " .ar -tf archive.sar # List members of archive.sar", 3467 " .ar -xvf archive.sar # Verbosely extract files from archive.sar", 3468 " See also:", 3469 " http://sqlite.org/cli.html#sqlar_archive_support", 3470#endif 3471#ifndef SQLITE_OMIT_AUTHORIZATION 3472 ".auth ON|OFF Show authorizer callbacks", 3473#endif 3474 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 3475 " --append Use the appendvfs", 3476 " --async Write to FILE without a journal and without fsync()", 3477 ".bail on|off Stop after hitting an error. Default OFF", 3478 ".binary on|off Turn binary output on or off. Default OFF", 3479 ".cd DIRECTORY Change the working directory to DIRECTORY", 3480 ".changes on|off Show number of rows changed by SQL", 3481 ".check GLOB Fail if output since .testcase does not match", 3482 ".clone NEWDB Clone data into NEWDB from the existing database", 3483 ".databases List names and files of attached databases", 3484 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 3485 ".dbinfo ?DB? Show status information about the database", 3486 ".dump ?TABLE? ... Render all database content as SQL", 3487 " Options:", 3488 " --preserve-rowids Include ROWID values in the output", 3489 " --newlines Allow unescaped newline characters in output", 3490 " TABLE is LIKE pattern for the tables to dump", 3491 ".echo on|off Turn command echo on or off", 3492 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 3493 " Other Modes:", 3494#ifdef SQLITE_DEBUG 3495 " test Show raw EXPLAIN QUERY PLAN output", 3496 " trace Like \"full\" but also enable \"PRAGMA vdbe_trace\"", 3497#endif 3498 " trigger Like \"full\" but also show trigger bytecode", 3499 ".excel Display the output of next command in a spreadsheet", 3500 ".exit ?CODE? Exit this program with return-code CODE", 3501 ".expert EXPERIMENTAL. Suggest indexes for specified queries", 3502/* Because explain mode comes on automatically now, the ".explain" mode 3503** is removed from the help screen. It is still supported for legacy, however */ 3504/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/ 3505 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 3506 ".headers on|off Turn display of headers on or off", 3507 ".help ?-all? ?PATTERN? Show help text for PATTERN", 3508 ".import FILE TABLE Import data from FILE into TABLE", 3509#ifndef SQLITE_OMIT_TEST_CONTROL 3510 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 3511#endif 3512 ".indexes ?TABLE? Show names of indexes", 3513 " If TABLE is specified, only show indexes for", 3514 " tables matching TABLE using the LIKE operator.", 3515#ifdef SQLITE_ENABLE_IOTRACE 3516 ".iotrace FILE Enable I/O diagnostic logging to FILE", 3517#endif 3518 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 3519 ".lint OPTIONS Report potential schema issues.", 3520 " Options:", 3521 " fkey-indexes Find missing foreign key indexes", 3522#ifndef SQLITE_OMIT_LOAD_EXTENSION 3523 ".load FILE ?ENTRY? Load an extension library", 3524#endif 3525 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 3526 ".mode MODE ?TABLE? Set output mode", 3527 " MODE is one of:", 3528 " ascii Columns/rows delimited by 0x1F and 0x1E", 3529 " csv Comma-separated values", 3530 " column Left-aligned columns. (See .width)", 3531 " html HTML <table> code", 3532 " insert SQL insert statements for TABLE", 3533 " line One value per line", 3534 " list Values delimited by \"|\"", 3535 " quote Escape answers as for SQL", 3536 " tabs Tab-separated values", 3537 " tcl TCL list elements", 3538 ".nullvalue STRING Use STRING in place of NULL values", 3539 ".once (-e|-x|FILE) Output for the next SQL command only to FILE", 3540 " If FILE begins with '|' then open as a pipe", 3541 " Other options:", 3542 " -e Invoke system text editor", 3543 " -x Open in a spreadsheet", 3544 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 3545 " Options:", 3546 " --append Use appendvfs to append database to the end of FILE", 3547#ifdef SQLITE_ENABLE_DESERIALIZE 3548 " --deserialize Load into memory useing sqlite3_deserialize()", 3549 " --hexdb Load the output of \"dbtotxt\" as an in-memory database", 3550 " --maxsize N Maximum size for --hexdb or --deserialized database", 3551#endif 3552 " --new Initialize FILE to an empty database", 3553 " --readonly Open FILE readonly", 3554 " --zip FILE is a ZIP archive", 3555 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 3556 " If FILE begins with '|' then open it as a pipe.", 3557 ".parameter CMD ... Manage SQL parameter bindings", 3558 " clear Erase all bindings", 3559 " init Initialize the TEMP table that holds bindings", 3560 " list List the current parameter bindings", 3561 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 3562 " PARAMETER should start with '$', ':', '@', or '?'", 3563 " unset PARAMETER Remove PARAMETER from the binding table", 3564 ".print STRING... Print literal STRING", 3565#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 3566 ".progress N Invoke progress handler after every N opcodes", 3567 " --limit N Interrupt after N progress callbacks", 3568 " --once Do no more than one progress interrupt", 3569 " --quiet|-q No output except at interrupts", 3570 " --reset Reset the count for each input and interrupt", 3571#endif 3572 ".prompt MAIN CONTINUE Replace the standard prompts", 3573 ".quit Exit this program", 3574 ".read FILE Read input from FILE", 3575 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 3576 ".save FILE Write in-memory database into FILE", 3577 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 3578 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 3579 " Options:", 3580 " --indent Try to pretty-print the schema", 3581 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 3582 " Options:", 3583 " --init Create a new SELFTEST table", 3584 " -v Verbose output", 3585 ".separator COL ?ROW? Change the column and row separators", 3586#if defined(SQLITE_ENABLE_SESSION) 3587 ".session ?NAME? CMD ... Create or control sessions", 3588 " Subcommands:", 3589 " attach TABLE Attach TABLE", 3590 " changeset FILE Write a changeset into FILE", 3591 " close Close one session", 3592 " enable ?BOOLEAN? Set or query the enable bit", 3593 " filter GLOB... Reject tables matching GLOBs", 3594 " indirect ?BOOLEAN? Mark or query the indirect status", 3595 " isempty Query whether the session is empty", 3596 " list List currently open session names", 3597 " open DB NAME Open a new session on DB", 3598 " patchset FILE Write a patchset into FILE", 3599 " If ?NAME? is omitted, the first defined session is used.", 3600#endif 3601 ".sha3sum ... Compute a SHA3 hash of database content", 3602 " Options:", 3603 " --schema Also hash the sqlite_master table", 3604 " --sha3-224 Use the sha3-224 algorithm", 3605 " --sha3-256 Use the sha3-256 algorithm. This is the default.", 3606 " --sha3-384 Use the sha3-384 algorithm", 3607 " --sha3-512 Use the sha3-512 algorithm", 3608 " Any other argument is a LIKE pattern for tables to hash", 3609#ifndef SQLITE_NOHAVE_SYSTEM 3610 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 3611#endif 3612 ".show Show the current values for various settings", 3613 ".stats ?on|off? Show stats or turn stats on or off", 3614#ifndef SQLITE_NOHAVE_SYSTEM 3615 ".system CMD ARGS... Run CMD ARGS... in a system shell", 3616#endif 3617 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 3618 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 3619 ".timeout MS Try opening locked tables for MS milliseconds", 3620 ".timer on|off Turn SQL timer on or off", 3621#ifndef SQLITE_OMIT_TRACE 3622 ".trace ?OPTIONS? Output each SQL statement as it is run", 3623 " FILE Send output to FILE", 3624 " stdout Send output to stdout", 3625 " stderr Send output to stderr", 3626 " off Disable tracing", 3627 " --expanded Expand query parameters", 3628#ifdef SQLITE_ENABLE_NORMALIZE 3629 " --normalized Normal the SQL statements", 3630#endif 3631 " --plain Show SQL as it is input", 3632 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 3633 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 3634 " --row Trace each row (SQLITE_TRACE_ROW)", 3635 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 3636#endif /* SQLITE_OMIT_TRACE */ 3637 ".vfsinfo ?AUX? Information about the top-level VFS", 3638 ".vfslist List all available VFSes", 3639 ".vfsname ?AUX? Print the name of the VFS stack", 3640 ".width NUM1 NUM2 ... Set column widths for \"column\" mode", 3641 " Negative values right-justify", 3642}; 3643 3644/* 3645** Output help text. 3646** 3647** zPattern describes the set of commands for which help text is provided. 3648** If zPattern is NULL, then show all commands, but only give a one-line 3649** description of each. 3650** 3651** Return the number of matches. 3652*/ 3653static int showHelp(FILE *out, const char *zPattern){ 3654 int i = 0; 3655 int j = 0; 3656 int n = 0; 3657 char *zPat; 3658 if( zPattern==0 3659 || zPattern[0]=='0' 3660 || strcmp(zPattern,"-a")==0 3661 || strcmp(zPattern,"-all")==0 3662 ){ 3663 /* Show all commands, but only one line per command */ 3664 if( zPattern==0 ) zPattern = ""; 3665 for(i=0; i<ArraySize(azHelp); i++){ 3666 if( azHelp[i][0]=='.' || zPattern[0] ){ 3667 utf8_printf(out, "%s\n", azHelp[i]); 3668 n++; 3669 } 3670 } 3671 }else{ 3672 /* Look for commands that for which zPattern is an exact prefix */ 3673 zPat = sqlite3_mprintf(".%s*", zPattern); 3674 for(i=0; i<ArraySize(azHelp); i++){ 3675 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 3676 utf8_printf(out, "%s\n", azHelp[i]); 3677 j = i+1; 3678 n++; 3679 } 3680 } 3681 sqlite3_free(zPat); 3682 if( n ){ 3683 if( n==1 ){ 3684 /* when zPattern is a prefix of exactly one command, then include the 3685 ** details of that command, which should begin at offset j */ 3686 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 3687 utf8_printf(out, "%s\n", azHelp[j]); 3688 j++; 3689 } 3690 } 3691 return n; 3692 } 3693 /* Look for commands that contain zPattern anywhere. Show the complete 3694 ** text of all commands that match. */ 3695 zPat = sqlite3_mprintf("%%%s%%", zPattern); 3696 for(i=0; i<ArraySize(azHelp); i++){ 3697 if( azHelp[i][0]=='.' ) j = i; 3698 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 3699 utf8_printf(out, "%s\n", azHelp[j]); 3700 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 3701 j++; 3702 utf8_printf(out, "%s\n", azHelp[j]); 3703 } 3704 i = j; 3705 n++; 3706 } 3707 } 3708 sqlite3_free(zPat); 3709 } 3710 return n; 3711} 3712 3713/* Forward reference */ 3714static int process_input(ShellState *p); 3715 3716/* 3717** Read the content of file zName into memory obtained from sqlite3_malloc64() 3718** and return a pointer to the buffer. The caller is responsible for freeing 3719** the memory. 3720** 3721** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 3722** read. 3723** 3724** For convenience, a nul-terminator byte is always appended to the data read 3725** from the file before the buffer is returned. This byte is not included in 3726** the final value of (*pnByte), if applicable. 3727** 3728** NULL is returned if any error is encountered. The final value of *pnByte 3729** is undefined in this case. 3730*/ 3731static char *readFile(const char *zName, int *pnByte){ 3732 FILE *in = fopen(zName, "rb"); 3733 long nIn; 3734 size_t nRead; 3735 char *pBuf; 3736 if( in==0 ) return 0; 3737 fseek(in, 0, SEEK_END); 3738 nIn = ftell(in); 3739 rewind(in); 3740 pBuf = sqlite3_malloc64( nIn+1 ); 3741 if( pBuf==0 ){ fclose(in); return 0; } 3742 nRead = fread(pBuf, nIn, 1, in); 3743 fclose(in); 3744 if( nRead!=1 ){ 3745 sqlite3_free(pBuf); 3746 return 0; 3747 } 3748 pBuf[nIn] = 0; 3749 if( pnByte ) *pnByte = nIn; 3750 return pBuf; 3751} 3752 3753#if defined(SQLITE_ENABLE_SESSION) 3754/* 3755** Close a single OpenSession object and release all of its associated 3756** resources. 3757*/ 3758static void session_close(OpenSession *pSession){ 3759 int i; 3760 sqlite3session_delete(pSession->p); 3761 sqlite3_free(pSession->zName); 3762 for(i=0; i<pSession->nFilter; i++){ 3763 sqlite3_free(pSession->azFilter[i]); 3764 } 3765 sqlite3_free(pSession->azFilter); 3766 memset(pSession, 0, sizeof(OpenSession)); 3767} 3768#endif 3769 3770/* 3771** Close all OpenSession objects and release all associated resources. 3772*/ 3773#if defined(SQLITE_ENABLE_SESSION) 3774static void session_close_all(ShellState *p){ 3775 int i; 3776 for(i=0; i<p->nSession; i++){ 3777 session_close(&p->aSession[i]); 3778 } 3779 p->nSession = 0; 3780} 3781#else 3782# define session_close_all(X) 3783#endif 3784 3785/* 3786** Implementation of the xFilter function for an open session. Omit 3787** any tables named by ".session filter" but let all other table through. 3788*/ 3789#if defined(SQLITE_ENABLE_SESSION) 3790static int session_filter(void *pCtx, const char *zTab){ 3791 OpenSession *pSession = (OpenSession*)pCtx; 3792 int i; 3793 for(i=0; i<pSession->nFilter; i++){ 3794 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 3795 } 3796 return 1; 3797} 3798#endif 3799 3800/* 3801** Try to deduce the type of file for zName based on its content. Return 3802** one of the SHELL_OPEN_* constants. 3803** 3804** If the file does not exist or is empty but its name looks like a ZIP 3805** archive and the dfltZip flag is true, then assume it is a ZIP archive. 3806** Otherwise, assume an ordinary database regardless of the filename if 3807** the type cannot be determined from content. 3808*/ 3809int deduceDatabaseType(const char *zName, int dfltZip){ 3810 FILE *f = fopen(zName, "rb"); 3811 size_t n; 3812 int rc = SHELL_OPEN_UNSPEC; 3813 char zBuf[100]; 3814 if( f==0 ){ 3815 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3816 return SHELL_OPEN_ZIPFILE; 3817 }else{ 3818 return SHELL_OPEN_NORMAL; 3819 } 3820 } 3821 n = fread(zBuf, 16, 1, f); 3822 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 3823 fclose(f); 3824 return SHELL_OPEN_NORMAL; 3825 } 3826 fseek(f, -25, SEEK_END); 3827 n = fread(zBuf, 25, 1, f); 3828 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 3829 rc = SHELL_OPEN_APPENDVFS; 3830 }else{ 3831 fseek(f, -22, SEEK_END); 3832 n = fread(zBuf, 22, 1, f); 3833 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 3834 && zBuf[3]==0x06 ){ 3835 rc = SHELL_OPEN_ZIPFILE; 3836 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 3837 rc = SHELL_OPEN_ZIPFILE; 3838 } 3839 } 3840 fclose(f); 3841 return rc; 3842} 3843 3844#ifdef SQLITE_ENABLE_DESERIALIZE 3845/* 3846** Reconstruct an in-memory database using the output from the "dbtotxt" 3847** program. Read content from the file in p->zDbFilename. If p->zDbFilename 3848** is 0, then read from standard input. 3849*/ 3850static unsigned char *readHexDb(ShellState *p, int *pnData){ 3851 unsigned char *a = 0; 3852 int nLine; 3853 int n = 0; 3854 int pgsz = 0; 3855 int iOffset = 0; 3856 int j, k; 3857 int rc; 3858 FILE *in; 3859 unsigned char x[16]; 3860 char zLine[1000]; 3861 if( p->zDbFilename ){ 3862 in = fopen(p->zDbFilename, "r"); 3863 if( in==0 ){ 3864 utf8_printf(stderr, "cannot open \"%s\" for reading\n", p->zDbFilename); 3865 return 0; 3866 } 3867 nLine = 0; 3868 }else{ 3869 in = p->in; 3870 nLine = p->lineno; 3871 } 3872 *pnData = 0; 3873 nLine++; 3874 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 3875 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 3876 if( rc!=2 ) goto readHexDb_error; 3877 if( n<=0 ) goto readHexDb_error; 3878 a = sqlite3_malloc( n ); 3879 if( a==0 ){ 3880 utf8_printf(stderr, "Out of memory!\n"); 3881 goto readHexDb_error; 3882 } 3883 memset(a, 0, n); 3884 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 3885 utf8_printf(stderr, "invalid pagesize\n"); 3886 goto readHexDb_error; 3887 } 3888 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 3889 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 3890 if( rc==2 ){ 3891 iOffset = k; 3892 continue; 3893 } 3894 if( strncmp(zLine, "| end ", 6)==0 ){ 3895 break; 3896 } 3897 rc = sscanf(zLine,"| %d: %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx" 3898 " %hhx %hhx %hhx %hhx %hhx %hhx %hhx %hhx", 3899 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 3900 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 3901 if( rc==17 ){ 3902 k = iOffset+j; 3903 if( k+16<=n ){ 3904 memcpy(a+k, x, 16); 3905 } 3906 } 3907 } 3908 *pnData = n; 3909 if( in!=p->in ){ 3910 fclose(in); 3911 }else{ 3912 p->lineno = nLine; 3913 } 3914 return a; 3915 3916readHexDb_error: 3917 if( in!=stdin ){ 3918 fclose(in); 3919 }else{ 3920 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 3921 nLine++; 3922 if(strncmp(zLine, "| end ", 6)==0 ) break; 3923 } 3924 p->lineno = nLine; 3925 } 3926 sqlite3_free(a); 3927 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 3928 return 0; 3929} 3930#endif /* SQLITE_ENABLE_DESERIALIZE */ 3931 3932/* Flags for open_db(). 3933** 3934** The default behavior of open_db() is to exit(1) if the database fails to 3935** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 3936** but still returns without calling exit. 3937** 3938** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 3939** ZIP archive if the file does not exist or is empty and its name matches 3940** the *.zip pattern. 3941*/ 3942#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 3943#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 3944 3945/* 3946** Make sure the database is open. If it is not, then open it. If 3947** the database fails to open, print an error message and exit. 3948*/ 3949static void open_db(ShellState *p, int openFlags){ 3950 if( p->db==0 ){ 3951 if( p->openMode==SHELL_OPEN_UNSPEC ){ 3952 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){ 3953 p->openMode = SHELL_OPEN_NORMAL; 3954 }else{ 3955 p->openMode = (u8)deduceDatabaseType(p->zDbFilename, 3956 (openFlags & OPEN_DB_ZIPFILE)!=0); 3957 } 3958 } 3959 switch( p->openMode ){ 3960 case SHELL_OPEN_APPENDVFS: { 3961 sqlite3_open_v2(p->zDbFilename, &p->db, 3962 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs"); 3963 break; 3964 } 3965 case SHELL_OPEN_HEXDB: 3966 case SHELL_OPEN_DESERIALIZE: { 3967 sqlite3_open(0, &p->db); 3968 break; 3969 } 3970 case SHELL_OPEN_ZIPFILE: { 3971 sqlite3_open(":memory:", &p->db); 3972 break; 3973 } 3974 case SHELL_OPEN_READONLY: { 3975 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0); 3976 break; 3977 } 3978 case SHELL_OPEN_UNSPEC: 3979 case SHELL_OPEN_NORMAL: { 3980 sqlite3_open(p->zDbFilename, &p->db); 3981 break; 3982 } 3983 } 3984 globalDb = p->db; 3985 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 3986 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 3987 p->zDbFilename, sqlite3_errmsg(p->db)); 3988 if( openFlags & OPEN_DB_KEEPALIVE ){ 3989 sqlite3_open(":memory:", &p->db); 3990 return; 3991 } 3992 exit(1); 3993 } 3994#ifndef SQLITE_OMIT_LOAD_EXTENSION 3995 sqlite3_enable_load_extension(p->db, 1); 3996#endif 3997 sqlite3_fileio_init(p->db, 0, 0); 3998 sqlite3_shathree_init(p->db, 0, 0); 3999 sqlite3_completion_init(p->db, 0, 0); 4000#ifdef SQLITE_HAVE_ZLIB 4001 sqlite3_zipfile_init(p->db, 0, 0); 4002 sqlite3_sqlar_init(p->db, 0, 0); 4003#endif 4004 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 4005 shellAddSchemaName, 0, 0); 4006 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 4007 shellModuleSchema, 0, 0); 4008 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 4009 shellPutsFunc, 0, 0); 4010#ifndef SQLITE_NOHAVE_SYSTEM 4011 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 4012 editFunc, 0, 0); 4013 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 4014 editFunc, 0, 0); 4015#endif 4016 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 4017 char *zSql = sqlite3_mprintf( 4018 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename); 4019 sqlite3_exec(p->db, zSql, 0, 0, 0); 4020 sqlite3_free(zSql); 4021 } 4022#ifdef SQLITE_ENABLE_DESERIALIZE 4023 else 4024 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 4025 int rc; 4026 int nData = 0; 4027 unsigned char *aData; 4028 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 4029 aData = (unsigned char*)readFile(p->zDbFilename, &nData); 4030 }else{ 4031 aData = readHexDb(p, &nData); 4032 if( aData==0 ){ 4033 utf8_printf(stderr, "Error in hexdb input\n"); 4034 return; 4035 } 4036 } 4037 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 4038 SQLITE_DESERIALIZE_RESIZEABLE | 4039 SQLITE_DESERIALIZE_FREEONCLOSE); 4040 if( rc ){ 4041 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 4042 } 4043 if( p->szMax>0 ){ 4044 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 4045 } 4046 } 4047#endif 4048 } 4049} 4050 4051/* 4052** Attempt to close the databaes connection. Report errors. 4053*/ 4054void close_db(sqlite3 *db){ 4055 int rc = sqlite3_close(db); 4056 if( rc ){ 4057 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 4058 rc, sqlite3_errmsg(db)); 4059 } 4060} 4061 4062#if HAVE_READLINE || HAVE_EDITLINE 4063/* 4064** Readline completion callbacks 4065*/ 4066static char *readline_completion_generator(const char *text, int state){ 4067 static sqlite3_stmt *pStmt = 0; 4068 char *zRet; 4069 if( state==0 ){ 4070 char *zSql; 4071 sqlite3_finalize(pStmt); 4072 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4073 " FROM completion(%Q) ORDER BY 1", text); 4074 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4075 sqlite3_free(zSql); 4076 } 4077 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4078 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0)); 4079 }else{ 4080 sqlite3_finalize(pStmt); 4081 pStmt = 0; 4082 zRet = 0; 4083 } 4084 return zRet; 4085} 4086static char **readline_completion(const char *zText, int iStart, int iEnd){ 4087 rl_attempted_completion_over = 1; 4088 return rl_completion_matches(zText, readline_completion_generator); 4089} 4090 4091#elif HAVE_LINENOISE 4092/* 4093** Linenoise completion callback 4094*/ 4095static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 4096 int nLine = strlen30(zLine); 4097 int i, iStart; 4098 sqlite3_stmt *pStmt = 0; 4099 char *zSql; 4100 char zBuf[1000]; 4101 4102 if( nLine>sizeof(zBuf)-30 ) return; 4103 if( zLine[0]=='.' || zLine[0]=='#') return; 4104 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 4105 if( i==nLine-1 ) return; 4106 iStart = i+1; 4107 memcpy(zBuf, zLine, iStart); 4108 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 4109 " FROM completion(%Q,%Q) ORDER BY 1", 4110 &zLine[iStart], zLine); 4111 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 4112 sqlite3_free(zSql); 4113 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 4114 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4115 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 4116 int nCompletion = sqlite3_column_bytes(pStmt, 0); 4117 if( iStart+nCompletion < sizeof(zBuf)-1 ){ 4118 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 4119 linenoiseAddCompletion(lc, zBuf); 4120 } 4121 } 4122 sqlite3_finalize(pStmt); 4123} 4124#endif 4125 4126/* 4127** Do C-language style dequoting. 4128** 4129** \a -> alarm 4130** \b -> backspace 4131** \t -> tab 4132** \n -> newline 4133** \v -> vertical tab 4134** \f -> form feed 4135** \r -> carriage return 4136** \s -> space 4137** \" -> " 4138** \' -> ' 4139** \\ -> backslash 4140** \NNN -> ascii character NNN in octal 4141*/ 4142static void resolve_backslashes(char *z){ 4143 int i, j; 4144 char c; 4145 while( *z && *z!='\\' ) z++; 4146 for(i=j=0; (c = z[i])!=0; i++, j++){ 4147 if( c=='\\' && z[i+1]!=0 ){ 4148 c = z[++i]; 4149 if( c=='a' ){ 4150 c = '\a'; 4151 }else if( c=='b' ){ 4152 c = '\b'; 4153 }else if( c=='t' ){ 4154 c = '\t'; 4155 }else if( c=='n' ){ 4156 c = '\n'; 4157 }else if( c=='v' ){ 4158 c = '\v'; 4159 }else if( c=='f' ){ 4160 c = '\f'; 4161 }else if( c=='r' ){ 4162 c = '\r'; 4163 }else if( c=='"' ){ 4164 c = '"'; 4165 }else if( c=='\'' ){ 4166 c = '\''; 4167 }else if( c=='\\' ){ 4168 c = '\\'; 4169 }else if( c>='0' && c<='7' ){ 4170 c -= '0'; 4171 if( z[i+1]>='0' && z[i+1]<='7' ){ 4172 i++; 4173 c = (c<<3) + z[i] - '0'; 4174 if( z[i+1]>='0' && z[i+1]<='7' ){ 4175 i++; 4176 c = (c<<3) + z[i] - '0'; 4177 } 4178 } 4179 } 4180 } 4181 z[j] = c; 4182 } 4183 if( j<i ) z[j] = 0; 4184} 4185 4186/* 4187** Interpret zArg as either an integer or a boolean value. Return 1 or 0 4188** for TRUE and FALSE. Return the integer value if appropriate. 4189*/ 4190static int booleanValue(const char *zArg){ 4191 int i; 4192 if( zArg[0]=='0' && zArg[1]=='x' ){ 4193 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 4194 }else{ 4195 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 4196 } 4197 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 4198 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 4199 return 1; 4200 } 4201 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 4202 return 0; 4203 } 4204 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 4205 zArg); 4206 return 0; 4207} 4208 4209/* 4210** Set or clear a shell flag according to a boolean value. 4211*/ 4212static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 4213 if( booleanValue(zArg) ){ 4214 ShellSetFlag(p, mFlag); 4215 }else{ 4216 ShellClearFlag(p, mFlag); 4217 } 4218} 4219 4220/* 4221** Close an output file, assuming it is not stderr or stdout 4222*/ 4223static void output_file_close(FILE *f){ 4224 if( f && f!=stdout && f!=stderr ) fclose(f); 4225} 4226 4227/* 4228** Try to open an output file. The names "stdout" and "stderr" are 4229** recognized and do the right thing. NULL is returned if the output 4230** filename is "off". 4231*/ 4232static FILE *output_file_open(const char *zFile, int bTextMode){ 4233 FILE *f; 4234 if( strcmp(zFile,"stdout")==0 ){ 4235 f = stdout; 4236 }else if( strcmp(zFile, "stderr")==0 ){ 4237 f = stderr; 4238 }else if( strcmp(zFile, "off")==0 ){ 4239 f = 0; 4240 }else{ 4241 f = fopen(zFile, bTextMode ? "w" : "wb"); 4242 if( f==0 ){ 4243 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 4244 } 4245 } 4246 return f; 4247} 4248 4249#ifndef SQLITE_OMIT_TRACE 4250/* 4251** A routine for handling output from sqlite3_trace(). 4252*/ 4253static int sql_trace_callback( 4254 unsigned mType, /* The trace type */ 4255 void *pArg, /* The ShellState pointer */ 4256 void *pP, /* Usually a pointer to sqlite_stmt */ 4257 void *pX /* Auxiliary output */ 4258){ 4259 ShellState *p = (ShellState*)pArg; 4260 sqlite3_stmt *pStmt; 4261 const char *zSql; 4262 int nSql; 4263 if( p->traceOut==0 ) return 0; 4264 if( mType==SQLITE_TRACE_CLOSE ){ 4265 utf8_printf(p->traceOut, "-- closing database connection\n"); 4266 return 0; 4267 } 4268 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 4269 zSql = (const char*)pX; 4270 }else{ 4271 pStmt = (sqlite3_stmt*)pP; 4272 switch( p->eTraceType ){ 4273 case SHELL_TRACE_EXPANDED: { 4274 zSql = sqlite3_expanded_sql(pStmt); 4275 break; 4276 } 4277#ifdef SQLITE_ENABLE_NORMALIZE 4278 case SHELL_TRACE_NORMALIZED: { 4279 zSql = sqlite3_normalized_sql(pStmt); 4280 break; 4281 } 4282#endif 4283 default: { 4284 zSql = sqlite3_sql(pStmt); 4285 break; 4286 } 4287 } 4288 } 4289 if( zSql==0 ) return 0; 4290 nSql = strlen30(zSql); 4291 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 4292 switch( mType ){ 4293 case SQLITE_TRACE_ROW: 4294 case SQLITE_TRACE_STMT: { 4295 utf8_printf(p->traceOut, "%.*s;\n", nSql, zSql); 4296 break; 4297 } 4298 case SQLITE_TRACE_PROFILE: { 4299 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 4300 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", nSql, zSql, nNanosec); 4301 break; 4302 } 4303 } 4304 return 0; 4305} 4306#endif 4307 4308/* 4309** A no-op routine that runs with the ".breakpoint" doc-command. This is 4310** a useful spot to set a debugger breakpoint. 4311*/ 4312static void test_breakpoint(void){ 4313 static int nCall = 0; 4314 nCall++; 4315} 4316 4317/* 4318** An object used to read a CSV and other files for import. 4319*/ 4320typedef struct ImportCtx ImportCtx; 4321struct ImportCtx { 4322 const char *zFile; /* Name of the input file */ 4323 FILE *in; /* Read the CSV text from this input stream */ 4324 char *z; /* Accumulated text for a field */ 4325 int n; /* Number of bytes in z */ 4326 int nAlloc; /* Space allocated for z[] */ 4327 int nLine; /* Current line number */ 4328 int bNotFirst; /* True if one or more bytes already read */ 4329 int cTerm; /* Character that terminated the most recent field */ 4330 int cColSep; /* The column separator character. (Usually ",") */ 4331 int cRowSep; /* The row separator character. (Usually "\n") */ 4332}; 4333 4334/* Append a single byte to z[] */ 4335static void import_append_char(ImportCtx *p, int c){ 4336 if( p->n+1>=p->nAlloc ){ 4337 p->nAlloc += p->nAlloc + 100; 4338 p->z = sqlite3_realloc64(p->z, p->nAlloc); 4339 if( p->z==0 ) shell_out_of_memory(); 4340 } 4341 p->z[p->n++] = (char)c; 4342} 4343 4344/* Read a single field of CSV text. Compatible with rfc4180 and extended 4345** with the option of having a separator other than ",". 4346** 4347** + Input comes from p->in. 4348** + Store results in p->z of length p->n. Space to hold p->z comes 4349** from sqlite3_malloc64(). 4350** + Use p->cSep as the column separator. The default is ",". 4351** + Use p->rSep as the row separator. The default is "\n". 4352** + Keep track of the line number in p->nLine. 4353** + Store the character that terminates the field in p->cTerm. Store 4354** EOF on end-of-file. 4355** + Report syntax errors on stderr 4356*/ 4357static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 4358 int c; 4359 int cSep = p->cColSep; 4360 int rSep = p->cRowSep; 4361 p->n = 0; 4362 c = fgetc(p->in); 4363 if( c==EOF || seenInterrupt ){ 4364 p->cTerm = EOF; 4365 return 0; 4366 } 4367 if( c=='"' ){ 4368 int pc, ppc; 4369 int startLine = p->nLine; 4370 int cQuote = c; 4371 pc = ppc = 0; 4372 while( 1 ){ 4373 c = fgetc(p->in); 4374 if( c==rSep ) p->nLine++; 4375 if( c==cQuote ){ 4376 if( pc==cQuote ){ 4377 pc = 0; 4378 continue; 4379 } 4380 } 4381 if( (c==cSep && pc==cQuote) 4382 || (c==rSep && pc==cQuote) 4383 || (c==rSep && pc=='\r' && ppc==cQuote) 4384 || (c==EOF && pc==cQuote) 4385 ){ 4386 do{ p->n--; }while( p->z[p->n]!=cQuote ); 4387 p->cTerm = c; 4388 break; 4389 } 4390 if( pc==cQuote && c!='\r' ){ 4391 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 4392 p->zFile, p->nLine, cQuote); 4393 } 4394 if( c==EOF ){ 4395 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 4396 p->zFile, startLine, cQuote); 4397 p->cTerm = c; 4398 break; 4399 } 4400 import_append_char(p, c); 4401 ppc = pc; 4402 pc = c; 4403 } 4404 }else{ 4405 /* If this is the first field being parsed and it begins with the 4406 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 4407 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 4408 import_append_char(p, c); 4409 c = fgetc(p->in); 4410 if( (c&0xff)==0xbb ){ 4411 import_append_char(p, c); 4412 c = fgetc(p->in); 4413 if( (c&0xff)==0xbf ){ 4414 p->bNotFirst = 1; 4415 p->n = 0; 4416 return csv_read_one_field(p); 4417 } 4418 } 4419 } 4420 while( c!=EOF && c!=cSep && c!=rSep ){ 4421 import_append_char(p, c); 4422 c = fgetc(p->in); 4423 } 4424 if( c==rSep ){ 4425 p->nLine++; 4426 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 4427 } 4428 p->cTerm = c; 4429 } 4430 if( p->z ) p->z[p->n] = 0; 4431 p->bNotFirst = 1; 4432 return p->z; 4433} 4434 4435/* Read a single field of ASCII delimited text. 4436** 4437** + Input comes from p->in. 4438** + Store results in p->z of length p->n. Space to hold p->z comes 4439** from sqlite3_malloc64(). 4440** + Use p->cSep as the column separator. The default is "\x1F". 4441** + Use p->rSep as the row separator. The default is "\x1E". 4442** + Keep track of the row number in p->nLine. 4443** + Store the character that terminates the field in p->cTerm. Store 4444** EOF on end-of-file. 4445** + Report syntax errors on stderr 4446*/ 4447static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 4448 int c; 4449 int cSep = p->cColSep; 4450 int rSep = p->cRowSep; 4451 p->n = 0; 4452 c = fgetc(p->in); 4453 if( c==EOF || seenInterrupt ){ 4454 p->cTerm = EOF; 4455 return 0; 4456 } 4457 while( c!=EOF && c!=cSep && c!=rSep ){ 4458 import_append_char(p, c); 4459 c = fgetc(p->in); 4460 } 4461 if( c==rSep ){ 4462 p->nLine++; 4463 } 4464 p->cTerm = c; 4465 if( p->z ) p->z[p->n] = 0; 4466 return p->z; 4467} 4468 4469/* 4470** Try to transfer data for table zTable. If an error is seen while 4471** moving forward, try to go backwards. The backwards movement won't 4472** work for WITHOUT ROWID tables. 4473*/ 4474static void tryToCloneData( 4475 ShellState *p, 4476 sqlite3 *newDb, 4477 const char *zTable 4478){ 4479 sqlite3_stmt *pQuery = 0; 4480 sqlite3_stmt *pInsert = 0; 4481 char *zQuery = 0; 4482 char *zInsert = 0; 4483 int rc; 4484 int i, j, n; 4485 int nTable = strlen30(zTable); 4486 int k = 0; 4487 int cnt = 0; 4488 const int spinRate = 10000; 4489 4490 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 4491 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4492 if( rc ){ 4493 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4494 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4495 zQuery); 4496 goto end_data_xfer; 4497 } 4498 n = sqlite3_column_count(pQuery); 4499 zInsert = sqlite3_malloc64(200 + nTable + n*3); 4500 if( zInsert==0 ) shell_out_of_memory(); 4501 sqlite3_snprintf(200+nTable,zInsert, 4502 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 4503 i = strlen30(zInsert); 4504 for(j=1; j<n; j++){ 4505 memcpy(zInsert+i, ",?", 2); 4506 i += 2; 4507 } 4508 memcpy(zInsert+i, ");", 3); 4509 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 4510 if( rc ){ 4511 utf8_printf(stderr, "Error %d: %s on [%s]\n", 4512 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 4513 zQuery); 4514 goto end_data_xfer; 4515 } 4516 for(k=0; k<2; k++){ 4517 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4518 for(i=0; i<n; i++){ 4519 switch( sqlite3_column_type(pQuery, i) ){ 4520 case SQLITE_NULL: { 4521 sqlite3_bind_null(pInsert, i+1); 4522 break; 4523 } 4524 case SQLITE_INTEGER: { 4525 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 4526 break; 4527 } 4528 case SQLITE_FLOAT: { 4529 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 4530 break; 4531 } 4532 case SQLITE_TEXT: { 4533 sqlite3_bind_text(pInsert, i+1, 4534 (const char*)sqlite3_column_text(pQuery,i), 4535 -1, SQLITE_STATIC); 4536 break; 4537 } 4538 case SQLITE_BLOB: { 4539 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 4540 sqlite3_column_bytes(pQuery,i), 4541 SQLITE_STATIC); 4542 break; 4543 } 4544 } 4545 } /* End for */ 4546 rc = sqlite3_step(pInsert); 4547 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 4548 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 4549 sqlite3_errmsg(newDb)); 4550 } 4551 sqlite3_reset(pInsert); 4552 cnt++; 4553 if( (cnt%spinRate)==0 ){ 4554 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 4555 fflush(stdout); 4556 } 4557 } /* End while */ 4558 if( rc==SQLITE_DONE ) break; 4559 sqlite3_finalize(pQuery); 4560 sqlite3_free(zQuery); 4561 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 4562 zTable); 4563 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4564 if( rc ){ 4565 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 4566 break; 4567 } 4568 } /* End for(k=0...) */ 4569 4570end_data_xfer: 4571 sqlite3_finalize(pQuery); 4572 sqlite3_finalize(pInsert); 4573 sqlite3_free(zQuery); 4574 sqlite3_free(zInsert); 4575} 4576 4577 4578/* 4579** Try to transfer all rows of the schema that match zWhere. For 4580** each row, invoke xForEach() on the object defined by that row. 4581** If an error is encountered while moving forward through the 4582** sqlite_master table, try again moving backwards. 4583*/ 4584static void tryToCloneSchema( 4585 ShellState *p, 4586 sqlite3 *newDb, 4587 const char *zWhere, 4588 void (*xForEach)(ShellState*,sqlite3*,const char*) 4589){ 4590 sqlite3_stmt *pQuery = 0; 4591 char *zQuery = 0; 4592 int rc; 4593 const unsigned char *zName; 4594 const unsigned char *zSql; 4595 char *zErrMsg = 0; 4596 4597 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4598 " WHERE %s", zWhere); 4599 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4600 if( rc ){ 4601 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4602 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4603 zQuery); 4604 goto end_schema_xfer; 4605 } 4606 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4607 zName = sqlite3_column_text(pQuery, 0); 4608 zSql = sqlite3_column_text(pQuery, 1); 4609 printf("%s... ", zName); fflush(stdout); 4610 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4611 if( zErrMsg ){ 4612 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4613 sqlite3_free(zErrMsg); 4614 zErrMsg = 0; 4615 } 4616 if( xForEach ){ 4617 xForEach(p, newDb, (const char*)zName); 4618 } 4619 printf("done\n"); 4620 } 4621 if( rc!=SQLITE_DONE ){ 4622 sqlite3_finalize(pQuery); 4623 sqlite3_free(zQuery); 4624 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" 4625 " WHERE %s ORDER BY rowid DESC", zWhere); 4626 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 4627 if( rc ){ 4628 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 4629 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 4630 zQuery); 4631 goto end_schema_xfer; 4632 } 4633 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 4634 zName = sqlite3_column_text(pQuery, 0); 4635 zSql = sqlite3_column_text(pQuery, 1); 4636 printf("%s... ", zName); fflush(stdout); 4637 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 4638 if( zErrMsg ){ 4639 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 4640 sqlite3_free(zErrMsg); 4641 zErrMsg = 0; 4642 } 4643 if( xForEach ){ 4644 xForEach(p, newDb, (const char*)zName); 4645 } 4646 printf("done\n"); 4647 } 4648 } 4649end_schema_xfer: 4650 sqlite3_finalize(pQuery); 4651 sqlite3_free(zQuery); 4652} 4653 4654/* 4655** Open a new database file named "zNewDb". Try to recover as much information 4656** as possible out of the main database (which might be corrupt) and write it 4657** into zNewDb. 4658*/ 4659static void tryToClone(ShellState *p, const char *zNewDb){ 4660 int rc; 4661 sqlite3 *newDb = 0; 4662 if( access(zNewDb,0)==0 ){ 4663 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 4664 return; 4665 } 4666 rc = sqlite3_open(zNewDb, &newDb); 4667 if( rc ){ 4668 utf8_printf(stderr, "Cannot create output database: %s\n", 4669 sqlite3_errmsg(newDb)); 4670 }else{ 4671 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 4672 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 4673 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 4674 tryToCloneSchema(p, newDb, "type!='table'", 0); 4675 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 4676 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 4677 } 4678 close_db(newDb); 4679} 4680 4681/* 4682** Change the output file back to stdout. 4683** 4684** If the p->doXdgOpen flag is set, that means the output was being 4685** redirected to a temporary file named by p->zTempFile. In that case, 4686** launch start/open/xdg-open on that temporary file. 4687*/ 4688static void output_reset(ShellState *p){ 4689 if( p->outfile[0]=='|' ){ 4690#ifndef SQLITE_OMIT_POPEN 4691 pclose(p->out); 4692#endif 4693 }else{ 4694 output_file_close(p->out); 4695#ifndef SQLITE_NOHAVE_SYSTEM 4696 if( p->doXdgOpen ){ 4697 const char *zXdgOpenCmd = 4698#if defined(_WIN32) 4699 "start"; 4700#elif defined(__APPLE__) 4701 "open"; 4702#else 4703 "xdg-open"; 4704#endif 4705 char *zCmd; 4706 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 4707 if( system(zCmd) ){ 4708 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 4709 } 4710 sqlite3_free(zCmd); 4711 outputModePop(p); 4712 p->doXdgOpen = 0; 4713 } 4714#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 4715 } 4716 p->outfile[0] = 0; 4717 p->out = stdout; 4718} 4719 4720/* 4721** Run an SQL command and return the single integer result. 4722*/ 4723static int db_int(ShellState *p, const char *zSql){ 4724 sqlite3_stmt *pStmt; 4725 int res = 0; 4726 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4727 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 4728 res = sqlite3_column_int(pStmt,0); 4729 } 4730 sqlite3_finalize(pStmt); 4731 return res; 4732} 4733 4734/* 4735** Convert a 2-byte or 4-byte big-endian integer into a native integer 4736*/ 4737static unsigned int get2byteInt(unsigned char *a){ 4738 return (a[0]<<8) + a[1]; 4739} 4740static unsigned int get4byteInt(unsigned char *a){ 4741 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 4742} 4743 4744/* 4745** Implementation of the ".info" command. 4746** 4747** Return 1 on error, 2 to exit, and 0 otherwise. 4748*/ 4749static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 4750 static const struct { const char *zName; int ofst; } aField[] = { 4751 { "file change counter:", 24 }, 4752 { "database page count:", 28 }, 4753 { "freelist page count:", 36 }, 4754 { "schema cookie:", 40 }, 4755 { "schema format:", 44 }, 4756 { "default cache size:", 48 }, 4757 { "autovacuum top root:", 52 }, 4758 { "incremental vacuum:", 64 }, 4759 { "text encoding:", 56 }, 4760 { "user version:", 60 }, 4761 { "application id:", 68 }, 4762 { "software version:", 96 }, 4763 }; 4764 static const struct { const char *zName; const char *zSql; } aQuery[] = { 4765 { "number of tables:", 4766 "SELECT count(*) FROM %s WHERE type='table'" }, 4767 { "number of indexes:", 4768 "SELECT count(*) FROM %s WHERE type='index'" }, 4769 { "number of triggers:", 4770 "SELECT count(*) FROM %s WHERE type='trigger'" }, 4771 { "number of views:", 4772 "SELECT count(*) FROM %s WHERE type='view'" }, 4773 { "schema size:", 4774 "SELECT total(length(sql)) FROM %s" }, 4775 }; 4776 int i; 4777 unsigned iDataVersion; 4778 char *zSchemaTab; 4779 char *zDb = nArg>=2 ? azArg[1] : "main"; 4780 sqlite3_stmt *pStmt = 0; 4781 unsigned char aHdr[100]; 4782 open_db(p, 0); 4783 if( p->db==0 ) return 1; 4784 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 4785 -1, &pStmt, 0); 4786 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 4787 if( sqlite3_step(pStmt)==SQLITE_ROW 4788 && sqlite3_column_bytes(pStmt,0)>100 4789 ){ 4790 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 4791 sqlite3_finalize(pStmt); 4792 }else{ 4793 raw_printf(stderr, "unable to read database header\n"); 4794 sqlite3_finalize(pStmt); 4795 return 1; 4796 } 4797 i = get2byteInt(aHdr+16); 4798 if( i==1 ) i = 65536; 4799 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 4800 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 4801 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 4802 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 4803 for(i=0; i<ArraySize(aField); i++){ 4804 int ofst = aField[i].ofst; 4805 unsigned int val = get4byteInt(aHdr + ofst); 4806 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 4807 switch( ofst ){ 4808 case 56: { 4809 if( val==1 ) raw_printf(p->out, " (utf8)"); 4810 if( val==2 ) raw_printf(p->out, " (utf16le)"); 4811 if( val==3 ) raw_printf(p->out, " (utf16be)"); 4812 } 4813 } 4814 raw_printf(p->out, "\n"); 4815 } 4816 if( zDb==0 ){ 4817 zSchemaTab = sqlite3_mprintf("main.sqlite_master"); 4818 }else if( strcmp(zDb,"temp")==0 ){ 4819 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); 4820 }else{ 4821 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); 4822 } 4823 for(i=0; i<ArraySize(aQuery); i++){ 4824 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 4825 int val = db_int(p, zSql); 4826 sqlite3_free(zSql); 4827 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 4828 } 4829 sqlite3_free(zSchemaTab); 4830 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 4831 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 4832 return 0; 4833} 4834 4835/* 4836** Print the current sqlite3_errmsg() value to stderr and return 1. 4837*/ 4838static int shellDatabaseError(sqlite3 *db){ 4839 const char *zErr = sqlite3_errmsg(db); 4840 utf8_printf(stderr, "Error: %s\n", zErr); 4841 return 1; 4842} 4843 4844/* 4845** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 4846** if they match and FALSE (0) if they do not match. 4847** 4848** Globbing rules: 4849** 4850** '*' Matches any sequence of zero or more characters. 4851** 4852** '?' Matches exactly one character. 4853** 4854** [...] Matches one character from the enclosed list of 4855** characters. 4856** 4857** [^...] Matches one character not in the enclosed list. 4858** 4859** '#' Matches any sequence of one or more digits with an 4860** optional + or - sign in front 4861** 4862** ' ' Any span of whitespace matches any other span of 4863** whitespace. 4864** 4865** Extra whitespace at the end of z[] is ignored. 4866*/ 4867static int testcase_glob(const char *zGlob, const char *z){ 4868 int c, c2; 4869 int invert; 4870 int seen; 4871 4872 while( (c = (*(zGlob++)))!=0 ){ 4873 if( IsSpace(c) ){ 4874 if( !IsSpace(*z) ) return 0; 4875 while( IsSpace(*zGlob) ) zGlob++; 4876 while( IsSpace(*z) ) z++; 4877 }else if( c=='*' ){ 4878 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 4879 if( c=='?' && (*(z++))==0 ) return 0; 4880 } 4881 if( c==0 ){ 4882 return 1; 4883 }else if( c=='[' ){ 4884 while( *z && testcase_glob(zGlob-1,z)==0 ){ 4885 z++; 4886 } 4887 return (*z)!=0; 4888 } 4889 while( (c2 = (*(z++)))!=0 ){ 4890 while( c2!=c ){ 4891 c2 = *(z++); 4892 if( c2==0 ) return 0; 4893 } 4894 if( testcase_glob(zGlob,z) ) return 1; 4895 } 4896 return 0; 4897 }else if( c=='?' ){ 4898 if( (*(z++))==0 ) return 0; 4899 }else if( c=='[' ){ 4900 int prior_c = 0; 4901 seen = 0; 4902 invert = 0; 4903 c = *(z++); 4904 if( c==0 ) return 0; 4905 c2 = *(zGlob++); 4906 if( c2=='^' ){ 4907 invert = 1; 4908 c2 = *(zGlob++); 4909 } 4910 if( c2==']' ){ 4911 if( c==']' ) seen = 1; 4912 c2 = *(zGlob++); 4913 } 4914 while( c2 && c2!=']' ){ 4915 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 4916 c2 = *(zGlob++); 4917 if( c>=prior_c && c<=c2 ) seen = 1; 4918 prior_c = 0; 4919 }else{ 4920 if( c==c2 ){ 4921 seen = 1; 4922 } 4923 prior_c = c2; 4924 } 4925 c2 = *(zGlob++); 4926 } 4927 if( c2==0 || (seen ^ invert)==0 ) return 0; 4928 }else if( c=='#' ){ 4929 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 4930 if( !IsDigit(z[0]) ) return 0; 4931 z++; 4932 while( IsDigit(z[0]) ){ z++; } 4933 }else{ 4934 if( c!=(*(z++)) ) return 0; 4935 } 4936 } 4937 while( IsSpace(*z) ){ z++; } 4938 return *z==0; 4939} 4940 4941 4942/* 4943** Compare the string as a command-line option with either one or two 4944** initial "-" characters. 4945*/ 4946static int optionMatch(const char *zStr, const char *zOpt){ 4947 if( zStr[0]!='-' ) return 0; 4948 zStr++; 4949 if( zStr[0]=='-' ) zStr++; 4950 return strcmp(zStr, zOpt)==0; 4951} 4952 4953/* 4954** Delete a file. 4955*/ 4956int shellDeleteFile(const char *zFilename){ 4957 int rc; 4958#ifdef _WIN32 4959 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 4960 rc = _wunlink(z); 4961 sqlite3_free(z); 4962#else 4963 rc = unlink(zFilename); 4964#endif 4965 return rc; 4966} 4967 4968/* 4969** Try to delete the temporary file (if there is one) and free the 4970** memory used to hold the name of the temp file. 4971*/ 4972static void clearTempFile(ShellState *p){ 4973 if( p->zTempFile==0 ) return; 4974 if( p->doXdgOpen ) return; 4975 if( shellDeleteFile(p->zTempFile) ) return; 4976 sqlite3_free(p->zTempFile); 4977 p->zTempFile = 0; 4978} 4979 4980/* 4981** Create a new temp file name with the given suffix. 4982*/ 4983static void newTempFile(ShellState *p, const char *zSuffix){ 4984 clearTempFile(p); 4985 sqlite3_free(p->zTempFile); 4986 p->zTempFile = 0; 4987 if( p->db ){ 4988 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 4989 } 4990 if( p->zTempFile==0 ){ 4991 sqlite3_uint64 r; 4992 sqlite3_randomness(sizeof(r), &r); 4993 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix); 4994 }else{ 4995 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 4996 } 4997 if( p->zTempFile==0 ){ 4998 raw_printf(stderr, "out of memory\n"); 4999 exit(1); 5000 } 5001} 5002 5003 5004/* 5005** The implementation of SQL scalar function fkey_collate_clause(), used 5006** by the ".lint fkey-indexes" command. This scalar function is always 5007** called with four arguments - the parent table name, the parent column name, 5008** the child table name and the child column name. 5009** 5010** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 5011** 5012** If either of the named tables or columns do not exist, this function 5013** returns an empty string. An empty string is also returned if both tables 5014** and columns exist but have the same default collation sequence. Or, 5015** if both exist but the default collation sequences are different, this 5016** function returns the string " COLLATE <parent-collation>", where 5017** <parent-collation> is the default collation sequence of the parent column. 5018*/ 5019static void shellFkeyCollateClause( 5020 sqlite3_context *pCtx, 5021 int nVal, 5022 sqlite3_value **apVal 5023){ 5024 sqlite3 *db = sqlite3_context_db_handle(pCtx); 5025 const char *zParent; 5026 const char *zParentCol; 5027 const char *zParentSeq; 5028 const char *zChild; 5029 const char *zChildCol; 5030 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 5031 int rc; 5032 5033 assert( nVal==4 ); 5034 zParent = (const char*)sqlite3_value_text(apVal[0]); 5035 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 5036 zChild = (const char*)sqlite3_value_text(apVal[2]); 5037 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 5038 5039 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 5040 rc = sqlite3_table_column_metadata( 5041 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 5042 ); 5043 if( rc==SQLITE_OK ){ 5044 rc = sqlite3_table_column_metadata( 5045 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 5046 ); 5047 } 5048 5049 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 5050 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 5051 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 5052 sqlite3_free(z); 5053 } 5054} 5055 5056 5057/* 5058** The implementation of dot-command ".lint fkey-indexes". 5059*/ 5060static int lintFkeyIndexes( 5061 ShellState *pState, /* Current shell tool state */ 5062 char **azArg, /* Array of arguments passed to dot command */ 5063 int nArg /* Number of entries in azArg[] */ 5064){ 5065 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 5066 FILE *out = pState->out; /* Stream to write non-error output to */ 5067 int bVerbose = 0; /* If -verbose is present */ 5068 int bGroupByParent = 0; /* If -groupbyparent is present */ 5069 int i; /* To iterate through azArg[] */ 5070 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 5071 int rc; /* Return code */ 5072 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 5073 5074 /* 5075 ** This SELECT statement returns one row for each foreign key constraint 5076 ** in the schema of the main database. The column values are: 5077 ** 5078 ** 0. The text of an SQL statement similar to: 5079 ** 5080 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 5081 ** 5082 ** This SELECT is similar to the one that the foreign keys implementation 5083 ** needs to run internally on child tables. If there is an index that can 5084 ** be used to optimize this query, then it can also be used by the FK 5085 ** implementation to optimize DELETE or UPDATE statements on the parent 5086 ** table. 5087 ** 5088 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 5089 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 5090 ** contains an index that can be used to optimize the query. 5091 ** 5092 ** 2. Human readable text that describes the child table and columns. e.g. 5093 ** 5094 ** "child_table(child_key1, child_key2)" 5095 ** 5096 ** 3. Human readable text that describes the parent table and columns. e.g. 5097 ** 5098 ** "parent_table(parent_key1, parent_key2)" 5099 ** 5100 ** 4. A full CREATE INDEX statement for an index that could be used to 5101 ** optimize DELETE or UPDATE statements on the parent table. e.g. 5102 ** 5103 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 5104 ** 5105 ** 5. The name of the parent table. 5106 ** 5107 ** These six values are used by the C logic below to generate the report. 5108 */ 5109 const char *zSql = 5110 "SELECT " 5111 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 5112 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 5113 " || fkey_collate_clause(" 5114 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 5115 ", " 5116 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('" 5117 " || group_concat('*=?', ' AND ') || ')'" 5118 ", " 5119 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 5120 ", " 5121 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 5122 ", " 5123 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 5124 " || ' ON ' || quote(s.name) || '('" 5125 " || group_concat(quote(f.[from]) ||" 5126 " fkey_collate_clause(" 5127 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 5128 " || ');'" 5129 ", " 5130 " f.[table] " 5131 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f " 5132 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 5133 "GROUP BY s.name, f.id " 5134 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 5135 ; 5136 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)"; 5137 5138 for(i=2; i<nArg; i++){ 5139 int n = strlen30(azArg[i]); 5140 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 5141 bVerbose = 1; 5142 } 5143 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 5144 bGroupByParent = 1; 5145 zIndent = " "; 5146 } 5147 else{ 5148 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 5149 azArg[0], azArg[1] 5150 ); 5151 return SQLITE_ERROR; 5152 } 5153 } 5154 5155 /* Register the fkey_collate_clause() SQL function */ 5156 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 5157 0, shellFkeyCollateClause, 0, 0 5158 ); 5159 5160 5161 if( rc==SQLITE_OK ){ 5162 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 5163 } 5164 if( rc==SQLITE_OK ){ 5165 sqlite3_bind_int(pSql, 1, bGroupByParent); 5166 } 5167 5168 if( rc==SQLITE_OK ){ 5169 int rc2; 5170 char *zPrev = 0; 5171 while( SQLITE_ROW==sqlite3_step(pSql) ){ 5172 int res = -1; 5173 sqlite3_stmt *pExplain = 0; 5174 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 5175 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 5176 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 5177 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 5178 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 5179 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 5180 5181 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 5182 if( rc!=SQLITE_OK ) break; 5183 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 5184 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 5185 res = ( 5186 0==sqlite3_strglob(zGlob, zPlan) 5187 || 0==sqlite3_strglob(zGlobIPK, zPlan) 5188 ); 5189 } 5190 rc = sqlite3_finalize(pExplain); 5191 if( rc!=SQLITE_OK ) break; 5192 5193 if( res<0 ){ 5194 raw_printf(stderr, "Error: internal error"); 5195 break; 5196 }else{ 5197 if( bGroupByParent 5198 && (bVerbose || res==0) 5199 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 5200 ){ 5201 raw_printf(out, "-- Parent table %s\n", zParent); 5202 sqlite3_free(zPrev); 5203 zPrev = sqlite3_mprintf("%s", zParent); 5204 } 5205 5206 if( res==0 ){ 5207 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 5208 }else if( bVerbose ){ 5209 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 5210 zIndent, zFrom, zTarget 5211 ); 5212 } 5213 } 5214 } 5215 sqlite3_free(zPrev); 5216 5217 if( rc!=SQLITE_OK ){ 5218 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5219 } 5220 5221 rc2 = sqlite3_finalize(pSql); 5222 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 5223 rc = rc2; 5224 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5225 } 5226 }else{ 5227 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 5228 } 5229 5230 return rc; 5231} 5232 5233/* 5234** Implementation of ".lint" dot command. 5235*/ 5236static int lintDotCommand( 5237 ShellState *pState, /* Current shell tool state */ 5238 char **azArg, /* Array of arguments passed to dot command */ 5239 int nArg /* Number of entries in azArg[] */ 5240){ 5241 int n; 5242 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 5243 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 5244 return lintFkeyIndexes(pState, azArg, nArg); 5245 5246 usage: 5247 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 5248 raw_printf(stderr, "Where sub-commands are:\n"); 5249 raw_printf(stderr, " fkey-indexes\n"); 5250 return SQLITE_ERROR; 5251} 5252 5253#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 5254/********************************************************************************* 5255** The ".archive" or ".ar" command. 5256*/ 5257static void shellPrepare( 5258 sqlite3 *db, 5259 int *pRc, 5260 const char *zSql, 5261 sqlite3_stmt **ppStmt 5262){ 5263 *ppStmt = 0; 5264 if( *pRc==SQLITE_OK ){ 5265 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 5266 if( rc!=SQLITE_OK ){ 5267 raw_printf(stderr, "sql error: %s (%d)\n", 5268 sqlite3_errmsg(db), sqlite3_errcode(db) 5269 ); 5270 *pRc = rc; 5271 } 5272 } 5273} 5274 5275static void shellPreparePrintf( 5276 sqlite3 *db, 5277 int *pRc, 5278 sqlite3_stmt **ppStmt, 5279 const char *zFmt, 5280 ... 5281){ 5282 *ppStmt = 0; 5283 if( *pRc==SQLITE_OK ){ 5284 va_list ap; 5285 char *z; 5286 va_start(ap, zFmt); 5287 z = sqlite3_vmprintf(zFmt, ap); 5288 va_end(ap); 5289 if( z==0 ){ 5290 *pRc = SQLITE_NOMEM; 5291 }else{ 5292 shellPrepare(db, pRc, z, ppStmt); 5293 sqlite3_free(z); 5294 } 5295 } 5296} 5297 5298static void shellFinalize( 5299 int *pRc, 5300 sqlite3_stmt *pStmt 5301){ 5302 if( pStmt ){ 5303 sqlite3 *db = sqlite3_db_handle(pStmt); 5304 int rc = sqlite3_finalize(pStmt); 5305 if( *pRc==SQLITE_OK ){ 5306 if( rc!=SQLITE_OK ){ 5307 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5308 } 5309 *pRc = rc; 5310 } 5311 } 5312} 5313 5314static void shellReset( 5315 int *pRc, 5316 sqlite3_stmt *pStmt 5317){ 5318 int rc = sqlite3_reset(pStmt); 5319 if( *pRc==SQLITE_OK ){ 5320 if( rc!=SQLITE_OK ){ 5321 sqlite3 *db = sqlite3_db_handle(pStmt); 5322 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 5323 } 5324 *pRc = rc; 5325 } 5326} 5327/* 5328** Structure representing a single ".ar" command. 5329*/ 5330typedef struct ArCommand ArCommand; 5331struct ArCommand { 5332 u8 eCmd; /* An AR_CMD_* value */ 5333 u8 bVerbose; /* True if --verbose */ 5334 u8 bZip; /* True if the archive is a ZIP */ 5335 u8 bDryRun; /* True if --dry-run */ 5336 u8 bAppend; /* True if --append */ 5337 u8 fromCmdLine; /* Run from -A instead of .archive */ 5338 int nArg; /* Number of command arguments */ 5339 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 5340 const char *zFile; /* --file argument, or NULL */ 5341 const char *zDir; /* --directory argument, or NULL */ 5342 char **azArg; /* Array of command arguments */ 5343 ShellState *p; /* Shell state */ 5344 sqlite3 *db; /* Database containing the archive */ 5345}; 5346 5347/* 5348** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 5349*/ 5350static int arUsage(FILE *f){ 5351 showHelp(f,"archive"); 5352 return SQLITE_ERROR; 5353} 5354 5355/* 5356** Print an error message for the .ar command to stderr and return 5357** SQLITE_ERROR. 5358*/ 5359static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 5360 va_list ap; 5361 char *z; 5362 va_start(ap, zFmt); 5363 z = sqlite3_vmprintf(zFmt, ap); 5364 va_end(ap); 5365 utf8_printf(stderr, "Error: %s\n", z); 5366 if( pAr->fromCmdLine ){ 5367 utf8_printf(stderr, "Use \"-A\" for more help\n"); 5368 }else{ 5369 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 5370 } 5371 sqlite3_free(z); 5372 return SQLITE_ERROR; 5373} 5374 5375/* 5376** Values for ArCommand.eCmd. 5377*/ 5378#define AR_CMD_CREATE 1 5379#define AR_CMD_EXTRACT 2 5380#define AR_CMD_LIST 3 5381#define AR_CMD_UPDATE 4 5382#define AR_CMD_HELP 5 5383 5384/* 5385** Other (non-command) switches. 5386*/ 5387#define AR_SWITCH_VERBOSE 6 5388#define AR_SWITCH_FILE 7 5389#define AR_SWITCH_DIRECTORY 8 5390#define AR_SWITCH_APPEND 9 5391#define AR_SWITCH_DRYRUN 10 5392 5393static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 5394 switch( eSwitch ){ 5395 case AR_CMD_CREATE: 5396 case AR_CMD_EXTRACT: 5397 case AR_CMD_LIST: 5398 case AR_CMD_UPDATE: 5399 case AR_CMD_HELP: 5400 if( pAr->eCmd ){ 5401 return arErrorMsg(pAr, "multiple command options"); 5402 } 5403 pAr->eCmd = eSwitch; 5404 break; 5405 5406 case AR_SWITCH_DRYRUN: 5407 pAr->bDryRun = 1; 5408 break; 5409 case AR_SWITCH_VERBOSE: 5410 pAr->bVerbose = 1; 5411 break; 5412 case AR_SWITCH_APPEND: 5413 pAr->bAppend = 1; 5414 /* Fall thru into --file */ 5415 case AR_SWITCH_FILE: 5416 pAr->zFile = zArg; 5417 break; 5418 case AR_SWITCH_DIRECTORY: 5419 pAr->zDir = zArg; 5420 break; 5421 } 5422 5423 return SQLITE_OK; 5424} 5425 5426/* 5427** Parse the command line for an ".ar" command. The results are written into 5428** structure (*pAr). SQLITE_OK is returned if the command line is parsed 5429** successfully, otherwise an error message is written to stderr and 5430** SQLITE_ERROR returned. 5431*/ 5432static int arParseCommand( 5433 char **azArg, /* Array of arguments passed to dot command */ 5434 int nArg, /* Number of entries in azArg[] */ 5435 ArCommand *pAr /* Populate this object */ 5436){ 5437 struct ArSwitch { 5438 const char *zLong; 5439 char cShort; 5440 u8 eSwitch; 5441 u8 bArg; 5442 } aSwitch[] = { 5443 { "create", 'c', AR_CMD_CREATE, 0 }, 5444 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 5445 { "list", 't', AR_CMD_LIST, 0 }, 5446 { "update", 'u', AR_CMD_UPDATE, 0 }, 5447 { "help", 'h', AR_CMD_HELP, 0 }, 5448 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 5449 { "file", 'f', AR_SWITCH_FILE, 1 }, 5450 { "append", 'a', AR_SWITCH_APPEND, 1 }, 5451 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 5452 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 5453 }; 5454 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 5455 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 5456 5457 if( nArg<=1 ){ 5458 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 5459 return arUsage(stderr); 5460 }else{ 5461 char *z = azArg[1]; 5462 if( z[0]!='-' ){ 5463 /* Traditional style [tar] invocation */ 5464 int i; 5465 int iArg = 2; 5466 for(i=0; z[i]; i++){ 5467 const char *zArg = 0; 5468 struct ArSwitch *pOpt; 5469 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5470 if( z[i]==pOpt->cShort ) break; 5471 } 5472 if( pOpt==pEnd ){ 5473 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5474 } 5475 if( pOpt->bArg ){ 5476 if( iArg>=nArg ){ 5477 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5478 } 5479 zArg = azArg[iArg++]; 5480 } 5481 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5482 } 5483 pAr->nArg = nArg-iArg; 5484 if( pAr->nArg>0 ){ 5485 pAr->azArg = &azArg[iArg]; 5486 } 5487 }else{ 5488 /* Non-traditional invocation */ 5489 int iArg; 5490 for(iArg=1; iArg<nArg; iArg++){ 5491 int n; 5492 z = azArg[iArg]; 5493 if( z[0]!='-' ){ 5494 /* All remaining command line words are command arguments. */ 5495 pAr->azArg = &azArg[iArg]; 5496 pAr->nArg = nArg-iArg; 5497 break; 5498 } 5499 n = strlen30(z); 5500 5501 if( z[1]!='-' ){ 5502 int i; 5503 /* One or more short options */ 5504 for(i=1; i<n; i++){ 5505 const char *zArg = 0; 5506 struct ArSwitch *pOpt; 5507 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5508 if( z[i]==pOpt->cShort ) break; 5509 } 5510 if( pOpt==pEnd ){ 5511 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 5512 } 5513 if( pOpt->bArg ){ 5514 if( i<(n-1) ){ 5515 zArg = &z[i+1]; 5516 i = n; 5517 }else{ 5518 if( iArg>=(nArg-1) ){ 5519 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 5520 } 5521 zArg = azArg[++iArg]; 5522 } 5523 } 5524 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 5525 } 5526 }else if( z[2]=='\0' ){ 5527 /* A -- option, indicating that all remaining command line words 5528 ** are command arguments. */ 5529 pAr->azArg = &azArg[iArg+1]; 5530 pAr->nArg = nArg-iArg-1; 5531 break; 5532 }else{ 5533 /* A long option */ 5534 const char *zArg = 0; /* Argument for option, if any */ 5535 struct ArSwitch *pMatch = 0; /* Matching option */ 5536 struct ArSwitch *pOpt; /* Iterator */ 5537 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 5538 const char *zLong = pOpt->zLong; 5539 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 5540 if( pMatch ){ 5541 return arErrorMsg(pAr, "ambiguous option: %s",z); 5542 }else{ 5543 pMatch = pOpt; 5544 } 5545 } 5546 } 5547 5548 if( pMatch==0 ){ 5549 return arErrorMsg(pAr, "unrecognized option: %s", z); 5550 } 5551 if( pMatch->bArg ){ 5552 if( iArg>=(nArg-1) ){ 5553 return arErrorMsg(pAr, "option requires an argument: %s", z); 5554 } 5555 zArg = azArg[++iArg]; 5556 } 5557 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 5558 } 5559 } 5560 } 5561 } 5562 5563 return SQLITE_OK; 5564} 5565 5566/* 5567** This function assumes that all arguments within the ArCommand.azArg[] 5568** array refer to archive members, as for the --extract or --list commands. 5569** It checks that each of them are present. If any specified file is not 5570** present in the archive, an error is printed to stderr and an error 5571** code returned. Otherwise, if all specified arguments are present in 5572** the archive, SQLITE_OK is returned. 5573** 5574** This function strips any trailing '/' characters from each argument. 5575** This is consistent with the way the [tar] command seems to work on 5576** Linux. 5577*/ 5578static int arCheckEntries(ArCommand *pAr){ 5579 int rc = SQLITE_OK; 5580 if( pAr->nArg ){ 5581 int i, j; 5582 sqlite3_stmt *pTest = 0; 5583 5584 shellPreparePrintf(pAr->db, &rc, &pTest, 5585 "SELECT name FROM %s WHERE name=$name", 5586 pAr->zSrcTable 5587 ); 5588 j = sqlite3_bind_parameter_index(pTest, "$name"); 5589 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 5590 char *z = pAr->azArg[i]; 5591 int n = strlen30(z); 5592 int bOk = 0; 5593 while( n>0 && z[n-1]=='/' ) n--; 5594 z[n] = '\0'; 5595 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 5596 if( SQLITE_ROW==sqlite3_step(pTest) ){ 5597 bOk = 1; 5598 } 5599 shellReset(&rc, pTest); 5600 if( rc==SQLITE_OK && bOk==0 ){ 5601 utf8_printf(stderr, "not found in archive: %s\n", z); 5602 rc = SQLITE_ERROR; 5603 } 5604 } 5605 shellFinalize(&rc, pTest); 5606 } 5607 return rc; 5608} 5609 5610/* 5611** Format a WHERE clause that can be used against the "sqlar" table to 5612** identify all archive members that match the command arguments held 5613** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 5614** The caller is responsible for eventually calling sqlite3_free() on 5615** any non-NULL (*pzWhere) value. 5616*/ 5617static void arWhereClause( 5618 int *pRc, 5619 ArCommand *pAr, 5620 char **pzWhere /* OUT: New WHERE clause */ 5621){ 5622 char *zWhere = 0; 5623 if( *pRc==SQLITE_OK ){ 5624 if( pAr->nArg==0 ){ 5625 zWhere = sqlite3_mprintf("1"); 5626 }else{ 5627 int i; 5628 const char *zSep = ""; 5629 for(i=0; i<pAr->nArg; i++){ 5630 const char *z = pAr->azArg[i]; 5631 zWhere = sqlite3_mprintf( 5632 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'", 5633 zWhere, zSep, z, strlen30(z)+1, z 5634 ); 5635 if( zWhere==0 ){ 5636 *pRc = SQLITE_NOMEM; 5637 break; 5638 } 5639 zSep = " OR "; 5640 } 5641 } 5642 } 5643 *pzWhere = zWhere; 5644} 5645 5646/* 5647** Implementation of .ar "lisT" command. 5648*/ 5649static int arListCommand(ArCommand *pAr){ 5650 const char *zSql = "SELECT %s FROM %s WHERE %s"; 5651 const char *azCols[] = { 5652 "name", 5653 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 5654 }; 5655 5656 char *zWhere = 0; 5657 sqlite3_stmt *pSql = 0; 5658 int rc; 5659 5660 rc = arCheckEntries(pAr); 5661 arWhereClause(&rc, pAr, &zWhere); 5662 5663 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 5664 pAr->zSrcTable, zWhere); 5665 if( pAr->bDryRun ){ 5666 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5667 }else{ 5668 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5669 if( pAr->bVerbose ){ 5670 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 5671 sqlite3_column_text(pSql, 0), 5672 sqlite3_column_int(pSql, 1), 5673 sqlite3_column_text(pSql, 2), 5674 sqlite3_column_text(pSql, 3) 5675 ); 5676 }else{ 5677 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5678 } 5679 } 5680 } 5681 shellFinalize(&rc, pSql); 5682 sqlite3_free(zWhere); 5683 return rc; 5684} 5685 5686 5687/* 5688** Implementation of .ar "eXtract" command. 5689*/ 5690static int arExtractCommand(ArCommand *pAr){ 5691 const char *zSql1 = 5692 "SELECT " 5693 " ($dir || name)," 5694 " writefile(($dir || name), %s, mode, mtime) " 5695 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 5696 " AND name NOT GLOB '*..[/\\]*'"; 5697 5698 const char *azExtraArg[] = { 5699 "sqlar_uncompress(data, sz)", 5700 "data" 5701 }; 5702 5703 sqlite3_stmt *pSql = 0; 5704 int rc = SQLITE_OK; 5705 char *zDir = 0; 5706 char *zWhere = 0; 5707 int i, j; 5708 5709 /* If arguments are specified, check that they actually exist within 5710 ** the archive before proceeding. And formulate a WHERE clause to 5711 ** match them. */ 5712 rc = arCheckEntries(pAr); 5713 arWhereClause(&rc, pAr, &zWhere); 5714 5715 if( rc==SQLITE_OK ){ 5716 if( pAr->zDir ){ 5717 zDir = sqlite3_mprintf("%s/", pAr->zDir); 5718 }else{ 5719 zDir = sqlite3_mprintf(""); 5720 } 5721 if( zDir==0 ) rc = SQLITE_NOMEM; 5722 } 5723 5724 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 5725 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 5726 ); 5727 5728 if( rc==SQLITE_OK ){ 5729 j = sqlite3_bind_parameter_index(pSql, "$dir"); 5730 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 5731 5732 /* Run the SELECT statement twice. The first time, writefile() is called 5733 ** for all archive members that should be extracted. The second time, 5734 ** only for the directories. This is because the timestamps for 5735 ** extracted directories must be reset after they are populated (as 5736 ** populating them changes the timestamp). */ 5737 for(i=0; i<2; i++){ 5738 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 5739 sqlite3_bind_int(pSql, j, i); 5740 if( pAr->bDryRun ){ 5741 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 5742 }else{ 5743 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 5744 if( i==0 && pAr->bVerbose ){ 5745 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 5746 } 5747 } 5748 } 5749 shellReset(&rc, pSql); 5750 } 5751 shellFinalize(&rc, pSql); 5752 } 5753 5754 sqlite3_free(zDir); 5755 sqlite3_free(zWhere); 5756 return rc; 5757} 5758 5759/* 5760** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 5761*/ 5762static int arExecSql(ArCommand *pAr, const char *zSql){ 5763 int rc; 5764 if( pAr->bDryRun ){ 5765 utf8_printf(pAr->p->out, "%s\n", zSql); 5766 rc = SQLITE_OK; 5767 }else{ 5768 char *zErr = 0; 5769 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 5770 if( zErr ){ 5771 utf8_printf(stdout, "ERROR: %s\n", zErr); 5772 sqlite3_free(zErr); 5773 } 5774 } 5775 return rc; 5776} 5777 5778 5779/* 5780** Implementation of .ar "create" and "update" commands. 5781** 5782** Create the "sqlar" table in the database if it does not already exist. 5783** Then add each file in the azFile[] array to the archive. Directories 5784** are added recursively. If argument bVerbose is non-zero, a message is 5785** printed on stdout for each file archived. 5786** 5787** The create command is the same as update, except that it drops 5788** any existing "sqlar" table before beginning. 5789*/ 5790static int arCreateOrUpdateCommand( 5791 ArCommand *pAr, /* Command arguments and options */ 5792 int bUpdate /* true for a --create. false for --update */ 5793){ 5794 const char *zCreate = 5795 "CREATE TABLE IF NOT EXISTS sqlar(\n" 5796 " name TEXT PRIMARY KEY, -- name of the file\n" 5797 " mode INT, -- access permissions\n" 5798 " mtime INT, -- last modification time\n" 5799 " sz INT, -- original file size\n" 5800 " data BLOB -- compressed content\n" 5801 ")"; 5802 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 5803 const char *zInsertFmt[2] = { 5804 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 5805 " SELECT\n" 5806 " %s,\n" 5807 " mode,\n" 5808 " mtime,\n" 5809 " CASE substr(lsmode(mode),1,1)\n" 5810 " WHEN '-' THEN length(data)\n" 5811 " WHEN 'd' THEN 0\n" 5812 " ELSE -1 END,\n" 5813 " sqlar_compress(data)\n" 5814 " FROM fsdir(%Q,%Q)\n" 5815 " WHERE lsmode(mode) NOT LIKE '?%%';", 5816 "REPLACE INTO %s(name,mode,mtime,data)\n" 5817 " SELECT\n" 5818 " %s,\n" 5819 " mode,\n" 5820 " mtime,\n" 5821 " data\n" 5822 " FROM fsdir(%Q,%Q)\n" 5823 " WHERE lsmode(mode) NOT LIKE '?%%';" 5824 }; 5825 int i; /* For iterating through azFile[] */ 5826 int rc; /* Return code */ 5827 const char *zTab = 0; /* SQL table into which to insert */ 5828 char *zSql; 5829 char zTemp[50]; 5830 5831 arExecSql(pAr, "PRAGMA page_size=512"); 5832 rc = arExecSql(pAr, "SAVEPOINT ar;"); 5833 if( rc!=SQLITE_OK ) return rc; 5834 zTemp[0] = 0; 5835 if( pAr->bZip ){ 5836 /* Initialize the zipfile virtual table, if necessary */ 5837 if( pAr->zFile ){ 5838 sqlite3_uint64 r; 5839 sqlite3_randomness(sizeof(r),&r); 5840 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 5841 zTab = zTemp; 5842 zSql = sqlite3_mprintf( 5843 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 5844 zTab, pAr->zFile 5845 ); 5846 rc = arExecSql(pAr, zSql); 5847 sqlite3_free(zSql); 5848 }else{ 5849 zTab = "zip"; 5850 } 5851 }else{ 5852 /* Initialize the table for an SQLAR */ 5853 zTab = "sqlar"; 5854 if( bUpdate==0 ){ 5855 rc = arExecSql(pAr, zDrop); 5856 if( rc!=SQLITE_OK ) goto end_ar_transaction; 5857 } 5858 rc = arExecSql(pAr, zCreate); 5859 } 5860 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 5861 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 5862 pAr->bVerbose ? "shell_putsnl(name)" : "name", 5863 pAr->azArg[i], pAr->zDir); 5864 rc = arExecSql(pAr, zSql2); 5865 sqlite3_free(zSql2); 5866 } 5867end_ar_transaction: 5868 if( rc!=SQLITE_OK ){ 5869 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 5870 }else{ 5871 rc = arExecSql(pAr, "RELEASE ar;"); 5872 if( pAr->bZip && pAr->zFile ){ 5873 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 5874 arExecSql(pAr, zSql); 5875 sqlite3_free(zSql); 5876 } 5877 } 5878 return rc; 5879} 5880 5881/* 5882** Implementation of ".ar" dot command. 5883*/ 5884static int arDotCommand( 5885 ShellState *pState, /* Current shell tool state */ 5886 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 5887 char **azArg, /* Array of arguments passed to dot command */ 5888 int nArg /* Number of entries in azArg[] */ 5889){ 5890 ArCommand cmd; 5891 int rc; 5892 memset(&cmd, 0, sizeof(cmd)); 5893 cmd.fromCmdLine = fromCmdLine; 5894 rc = arParseCommand(azArg, nArg, &cmd); 5895 if( rc==SQLITE_OK ){ 5896 int eDbType = SHELL_OPEN_UNSPEC; 5897 cmd.p = pState; 5898 cmd.db = pState->db; 5899 if( cmd.zFile ){ 5900 eDbType = deduceDatabaseType(cmd.zFile, 1); 5901 }else{ 5902 eDbType = pState->openMode; 5903 } 5904 if( eDbType==SHELL_OPEN_ZIPFILE ){ 5905 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 5906 if( cmd.zFile==0 ){ 5907 cmd.zSrcTable = sqlite3_mprintf("zip"); 5908 }else{ 5909 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 5910 } 5911 } 5912 cmd.bZip = 1; 5913 }else if( cmd.zFile ){ 5914 int flags; 5915 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 5916 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){ 5917 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 5918 }else{ 5919 flags = SQLITE_OPEN_READONLY; 5920 } 5921 cmd.db = 0; 5922 if( cmd.bDryRun ){ 5923 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 5924 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 5925 } 5926 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 5927 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 5928 if( rc!=SQLITE_OK ){ 5929 utf8_printf(stderr, "cannot open file: %s (%s)\n", 5930 cmd.zFile, sqlite3_errmsg(cmd.db) 5931 ); 5932 goto end_ar_command; 5933 } 5934 sqlite3_fileio_init(cmd.db, 0, 0); 5935 sqlite3_sqlar_init(cmd.db, 0, 0); 5936 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 5937 shellPutsFunc, 0, 0); 5938 5939 } 5940 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 5941 if( cmd.eCmd!=AR_CMD_CREATE 5942 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 5943 ){ 5944 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 5945 rc = SQLITE_ERROR; 5946 goto end_ar_command; 5947 } 5948 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 5949 } 5950 5951 switch( cmd.eCmd ){ 5952 case AR_CMD_CREATE: 5953 rc = arCreateOrUpdateCommand(&cmd, 0); 5954 break; 5955 5956 case AR_CMD_EXTRACT: 5957 rc = arExtractCommand(&cmd); 5958 break; 5959 5960 case AR_CMD_LIST: 5961 rc = arListCommand(&cmd); 5962 break; 5963 5964 case AR_CMD_HELP: 5965 arUsage(pState->out); 5966 break; 5967 5968 default: 5969 assert( cmd.eCmd==AR_CMD_UPDATE ); 5970 rc = arCreateOrUpdateCommand(&cmd, 1); 5971 break; 5972 } 5973 } 5974end_ar_command: 5975 if( cmd.db!=pState->db ){ 5976 close_db(cmd.db); 5977 } 5978 sqlite3_free(cmd.zSrcTable); 5979 5980 return rc; 5981} 5982/* End of the ".archive" or ".ar" command logic 5983**********************************************************************************/ 5984#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 5985 5986 5987/* 5988** If an input line begins with "." then invoke this routine to 5989** process that line. 5990** 5991** Return 1 on error, 2 to exit, and 0 otherwise. 5992*/ 5993static int do_meta_command(char *zLine, ShellState *p){ 5994 int h = 1; 5995 int nArg = 0; 5996 int n, c; 5997 int rc = 0; 5998 char *azArg[50]; 5999 6000#ifndef SQLITE_OMIT_VIRTUALTABLE 6001 if( p->expert.pExpert ){ 6002 expertFinish(p, 1, 0); 6003 } 6004#endif 6005 6006 /* Parse the input line into tokens. 6007 */ 6008 while( zLine[h] && nArg<ArraySize(azArg) ){ 6009 while( IsSpace(zLine[h]) ){ h++; } 6010 if( zLine[h]==0 ) break; 6011 if( zLine[h]=='\'' || zLine[h]=='"' ){ 6012 int delim = zLine[h++]; 6013 azArg[nArg++] = &zLine[h]; 6014 while( zLine[h] && zLine[h]!=delim ){ 6015 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 6016 h++; 6017 } 6018 if( zLine[h]==delim ){ 6019 zLine[h++] = 0; 6020 } 6021 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 6022 }else{ 6023 azArg[nArg++] = &zLine[h]; 6024 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 6025 if( zLine[h] ) zLine[h++] = 0; 6026 resolve_backslashes(azArg[nArg-1]); 6027 } 6028 } 6029 6030 /* Process the input line. 6031 */ 6032 if( nArg==0 ) return 0; /* no tokens, no error */ 6033 n = strlen30(azArg[0]); 6034 c = azArg[0][0]; 6035 clearTempFile(p); 6036 6037#ifndef SQLITE_OMIT_AUTHORIZATION 6038 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ 6039 if( nArg!=2 ){ 6040 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 6041 rc = 1; 6042 goto meta_command_exit; 6043 } 6044 open_db(p, 0); 6045 if( booleanValue(azArg[1]) ){ 6046 sqlite3_set_authorizer(p->db, shellAuth, p); 6047 }else{ 6048 sqlite3_set_authorizer(p->db, 0, 0); 6049 } 6050 }else 6051#endif 6052 6053#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6054 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){ 6055 open_db(p, 0); 6056 rc = arDotCommand(p, 0, azArg, nArg); 6057 }else 6058#endif 6059 6060 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) 6061 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) 6062 ){ 6063 const char *zDestFile = 0; 6064 const char *zDb = 0; 6065 sqlite3 *pDest; 6066 sqlite3_backup *pBackup; 6067 int j; 6068 int bAsync = 0; 6069 const char *zVfs = 0; 6070 for(j=1; j<nArg; j++){ 6071 const char *z = azArg[j]; 6072 if( z[0]=='-' ){ 6073 if( z[1]=='-' ) z++; 6074 if( strcmp(z, "-append")==0 ){ 6075 zVfs = "apndvfs"; 6076 }else 6077 if( strcmp(z, "-async")==0 ){ 6078 bAsync = 1; 6079 }else 6080 { 6081 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 6082 return 1; 6083 } 6084 }else if( zDestFile==0 ){ 6085 zDestFile = azArg[j]; 6086 }else if( zDb==0 ){ 6087 zDb = zDestFile; 6088 zDestFile = azArg[j]; 6089 }else{ 6090 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 6091 return 1; 6092 } 6093 } 6094 if( zDestFile==0 ){ 6095 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 6096 return 1; 6097 } 6098 if( zDb==0 ) zDb = "main"; 6099 rc = sqlite3_open_v2(zDestFile, &pDest, 6100 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 6101 if( rc!=SQLITE_OK ){ 6102 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 6103 close_db(pDest); 6104 return 1; 6105 } 6106 if( bAsync ){ 6107 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 6108 0, 0, 0); 6109 } 6110 open_db(p, 0); 6111 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 6112 if( pBackup==0 ){ 6113 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 6114 close_db(pDest); 6115 return 1; 6116 } 6117 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 6118 sqlite3_backup_finish(pBackup); 6119 if( rc==SQLITE_DONE ){ 6120 rc = 0; 6121 }else{ 6122 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 6123 rc = 1; 6124 } 6125 close_db(pDest); 6126 }else 6127 6128 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ 6129 if( nArg==2 ){ 6130 bail_on_error = booleanValue(azArg[1]); 6131 }else{ 6132 raw_printf(stderr, "Usage: .bail on|off\n"); 6133 rc = 1; 6134 } 6135 }else 6136 6137 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ 6138 if( nArg==2 ){ 6139 if( booleanValue(azArg[1]) ){ 6140 setBinaryMode(p->out, 1); 6141 }else{ 6142 setTextMode(p->out, 1); 6143 } 6144 }else{ 6145 raw_printf(stderr, "Usage: .binary on|off\n"); 6146 rc = 1; 6147 } 6148 }else 6149 6150 if( c=='c' && strcmp(azArg[0],"cd")==0 ){ 6151 if( nArg==2 ){ 6152#if defined(_WIN32) || defined(WIN32) 6153 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 6154 rc = !SetCurrentDirectoryW(z); 6155 sqlite3_free(z); 6156#else 6157 rc = chdir(azArg[1]); 6158#endif 6159 if( rc ){ 6160 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 6161 rc = 1; 6162 } 6163 }else{ 6164 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 6165 rc = 1; 6166 } 6167 }else 6168 6169 /* The undocumented ".breakpoint" command causes a call to the no-op 6170 ** routine named test_breakpoint(). 6171 */ 6172 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ 6173 test_breakpoint(); 6174 }else 6175 6176 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ 6177 if( nArg==2 ){ 6178 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 6179 }else{ 6180 raw_printf(stderr, "Usage: .changes on|off\n"); 6181 rc = 1; 6182 } 6183 }else 6184 6185 /* Cancel output redirection, if it is currently set (by .testcase) 6186 ** Then read the content of the testcase-out.txt file and compare against 6187 ** azArg[1]. If there are differences, report an error and exit. 6188 */ 6189 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){ 6190 char *zRes = 0; 6191 output_reset(p); 6192 if( nArg!=2 ){ 6193 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 6194 rc = 2; 6195 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 6196 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 6197 rc = 2; 6198 }else if( testcase_glob(azArg[1],zRes)==0 ){ 6199 utf8_printf(stderr, 6200 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 6201 p->zTestcase, azArg[1], zRes); 6202 rc = 1; 6203 }else{ 6204 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 6205 p->nCheck++; 6206 } 6207 sqlite3_free(zRes); 6208 }else 6209 6210 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ 6211 if( nArg==2 ){ 6212 tryToClone(p, azArg[1]); 6213 }else{ 6214 raw_printf(stderr, "Usage: .clone FILENAME\n"); 6215 rc = 1; 6216 } 6217 }else 6218 6219 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ 6220 ShellState data; 6221 char *zErrMsg = 0; 6222 open_db(p, 0); 6223 memcpy(&data, p, sizeof(data)); 6224 data.showHeader = 0; 6225 data.cMode = data.mode = MODE_List; 6226 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": "); 6227 data.cnt = 0; 6228 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list", 6229 callback, &data, &zErrMsg); 6230 if( zErrMsg ){ 6231 utf8_printf(stderr,"Error: %s\n", zErrMsg); 6232 sqlite3_free(zErrMsg); 6233 rc = 1; 6234 } 6235 }else 6236 6237 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){ 6238 static const struct DbConfigChoices { 6239 const char *zName; 6240 int op; 6241 } aDbConfig[] = { 6242 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 6243 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 6244 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 6245 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 6246 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 6247 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 6248 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 6249 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 6250 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 6251 }; 6252 int ii, v; 6253 open_db(p, 0); 6254 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 6255 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 6256 if( nArg>=3 ){ 6257 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 6258 } 6259 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 6260 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 6261 if( nArg>1 ) break; 6262 } 6263 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 6264 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 6265 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 6266 } 6267 }else 6268 6269 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){ 6270 rc = shell_dbinfo_command(p, nArg, azArg); 6271 }else 6272 6273 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ 6274 const char *zLike = 0; 6275 int i; 6276 int savedShowHeader = p->showHeader; 6277 int savedShellFlags = p->shellFlgs; 6278 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo); 6279 for(i=1; i<nArg; i++){ 6280 if( azArg[i][0]=='-' ){ 6281 const char *z = azArg[i]+1; 6282 if( z[0]=='-' ) z++; 6283 if( strcmp(z,"preserve-rowids")==0 ){ 6284#ifdef SQLITE_OMIT_VIRTUALTABLE 6285 raw_printf(stderr, "The --preserve-rowids option is not compatible" 6286 " with SQLITE_OMIT_VIRTUALTABLE\n"); 6287 rc = 1; 6288 goto meta_command_exit; 6289#else 6290 ShellSetFlag(p, SHFLG_PreserveRowid); 6291#endif 6292 }else 6293 if( strcmp(z,"newlines")==0 ){ 6294 ShellSetFlag(p, SHFLG_Newlines); 6295 }else 6296 { 6297 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 6298 rc = 1; 6299 goto meta_command_exit; 6300 } 6301 }else if( zLike ){ 6302 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? " 6303 "?--newlines? ?LIKE-PATTERN?\n"); 6304 rc = 1; 6305 goto meta_command_exit; 6306 }else{ 6307 zLike = azArg[i]; 6308 } 6309 } 6310 open_db(p, 0); 6311 /* When playing back a "dump", the content might appear in an order 6312 ** which causes immediate foreign key constraints to be violated. 6313 ** So disable foreign-key constraint enforcement to prevent problems. */ 6314 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 6315 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 6316 p->writableSchema = 0; 6317 p->showHeader = 0; 6318 /* Set writable_schema=ON since doing so forces SQLite to initialize 6319 ** as much of the schema as it can even if the sqlite_master table is 6320 ** corrupt. */ 6321 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 6322 p->nErr = 0; 6323 if( zLike==0 ){ 6324 run_schema_dump_query(p, 6325 "SELECT name, type, sql FROM sqlite_master " 6326 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" 6327 ); 6328 run_schema_dump_query(p, 6329 "SELECT name, type, sql FROM sqlite_master " 6330 "WHERE name=='sqlite_sequence'" 6331 ); 6332 run_table_dump_query(p, 6333 "SELECT sql FROM sqlite_master " 6334 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 6335 ); 6336 }else{ 6337 char *zSql; 6338 zSql = sqlite3_mprintf( 6339 "SELECT name, type, sql FROM sqlite_master " 6340 "WHERE tbl_name LIKE %Q AND type=='table'" 6341 " AND sql NOT NULL", zLike); 6342 run_schema_dump_query(p,zSql); 6343 sqlite3_free(zSql); 6344 zSql = sqlite3_mprintf( 6345 "SELECT sql FROM sqlite_master " 6346 "WHERE sql NOT NULL" 6347 " AND type IN ('index','trigger','view')" 6348 " AND tbl_name LIKE %Q", zLike); 6349 run_table_dump_query(p, zSql, 0); 6350 sqlite3_free(zSql); 6351 } 6352 if( p->writableSchema ){ 6353 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 6354 p->writableSchema = 0; 6355 } 6356 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 6357 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 6358 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); 6359 p->showHeader = savedShowHeader; 6360 p->shellFlgs = savedShellFlags; 6361 }else 6362 6363 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ 6364 if( nArg==2 ){ 6365 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 6366 }else{ 6367 raw_printf(stderr, "Usage: .echo on|off\n"); 6368 rc = 1; 6369 } 6370 }else 6371 6372 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ 6373 if( nArg==2 ){ 6374 p->autoEQPtest = 0; 6375 if( p->autoEQPtrace ){ 6376 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 6377 p->autoEQPtrace = 0; 6378 } 6379 if( strcmp(azArg[1],"full")==0 ){ 6380 p->autoEQP = AUTOEQP_full; 6381 }else if( strcmp(azArg[1],"trigger")==0 ){ 6382 p->autoEQP = AUTOEQP_trigger; 6383#ifdef SQLITE_DEBUG 6384 }else if( strcmp(azArg[1],"test")==0 ){ 6385 p->autoEQP = AUTOEQP_on; 6386 p->autoEQPtest = 1; 6387 }else if( strcmp(azArg[1],"trace")==0 ){ 6388 p->autoEQP = AUTOEQP_full; 6389 p->autoEQPtrace = 1; 6390 open_db(p, 0); 6391 sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0); 6392 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 6393#endif 6394 }else{ 6395 p->autoEQP = (u8)booleanValue(azArg[1]); 6396 } 6397 }else{ 6398 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 6399 rc = 1; 6400 } 6401 }else 6402 6403 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ 6404 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 6405 rc = 2; 6406 }else 6407 6408 /* The ".explain" command is automatic now. It is largely pointless. It 6409 ** retained purely for backwards compatibility */ 6410 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ 6411 int val = 1; 6412 if( nArg>=2 ){ 6413 if( strcmp(azArg[1],"auto")==0 ){ 6414 val = 99; 6415 }else{ 6416 val = booleanValue(azArg[1]); 6417 } 6418 } 6419 if( val==1 && p->mode!=MODE_Explain ){ 6420 p->normalMode = p->mode; 6421 p->mode = MODE_Explain; 6422 p->autoExplain = 0; 6423 }else if( val==0 ){ 6424 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 6425 p->autoExplain = 0; 6426 }else if( val==99 ){ 6427 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 6428 p->autoExplain = 1; 6429 } 6430 }else 6431 6432#ifndef SQLITE_OMIT_VIRTUALTABLE 6433 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){ 6434 open_db(p, 0); 6435 expertDotCommand(p, azArg, nArg); 6436 }else 6437#endif 6438 6439 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ 6440 ShellState data; 6441 char *zErrMsg = 0; 6442 int doStats = 0; 6443 memcpy(&data, p, sizeof(data)); 6444 data.showHeader = 0; 6445 data.cMode = data.mode = MODE_Semi; 6446 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 6447 data.cMode = data.mode = MODE_Pretty; 6448 nArg = 1; 6449 } 6450 if( nArg!=1 ){ 6451 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 6452 rc = 1; 6453 goto meta_command_exit; 6454 } 6455 open_db(p, 0); 6456 rc = sqlite3_exec(p->db, 6457 "SELECT sql FROM" 6458 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 6459 " FROM sqlite_master UNION ALL" 6460 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " 6461 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 6462 "ORDER BY rowid", 6463 callback, &data, &zErrMsg 6464 ); 6465 if( rc==SQLITE_OK ){ 6466 sqlite3_stmt *pStmt; 6467 rc = sqlite3_prepare_v2(p->db, 6468 "SELECT rowid FROM sqlite_master" 6469 " WHERE name GLOB 'sqlite_stat[134]'", 6470 -1, &pStmt, 0); 6471 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 6472 sqlite3_finalize(pStmt); 6473 } 6474 if( doStats==0 ){ 6475 raw_printf(p->out, "/* No STAT tables available */\n"); 6476 }else{ 6477 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 6478 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", 6479 callback, &data, &zErrMsg); 6480 data.cMode = data.mode = MODE_Insert; 6481 data.zDestTable = "sqlite_stat1"; 6482 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg); 6483 data.zDestTable = "sqlite_stat3"; 6484 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg); 6485 data.zDestTable = "sqlite_stat4"; 6486 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg); 6487 raw_printf(p->out, "ANALYZE sqlite_master;\n"); 6488 } 6489 }else 6490 6491 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ 6492 if( nArg==2 ){ 6493 p->showHeader = booleanValue(azArg[1]); 6494 }else{ 6495 raw_printf(stderr, "Usage: .headers on|off\n"); 6496 rc = 1; 6497 } 6498 }else 6499 6500 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ 6501 if( nArg>=2 ){ 6502 n = showHelp(p->out, azArg[1]); 6503 if( n==0 ){ 6504 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 6505 } 6506 }else{ 6507 showHelp(p->out, 0); 6508 } 6509 }else 6510 6511 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ 6512 char *zTable; /* Insert data into this table */ 6513 char *zFile; /* Name of file to extra content from */ 6514 sqlite3_stmt *pStmt = NULL; /* A statement */ 6515 int nCol; /* Number of columns in the table */ 6516 int nByte; /* Number of bytes in an SQL string */ 6517 int i, j; /* Loop counters */ 6518 int needCommit; /* True to COMMIT or ROLLBACK at end */ 6519 int nSep; /* Number of bytes in p->colSeparator[] */ 6520 char *zSql; /* An SQL statement */ 6521 ImportCtx sCtx; /* Reader context */ 6522 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 6523 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ 6524 6525 if( nArg!=3 ){ 6526 raw_printf(stderr, "Usage: .import FILE TABLE\n"); 6527 goto meta_command_exit; 6528 } 6529 zFile = azArg[1]; 6530 zTable = azArg[2]; 6531 seenInterrupt = 0; 6532 memset(&sCtx, 0, sizeof(sCtx)); 6533 open_db(p, 0); 6534 nSep = strlen30(p->colSeparator); 6535 if( nSep==0 ){ 6536 raw_printf(stderr, 6537 "Error: non-null column separator required for import\n"); 6538 return 1; 6539 } 6540 if( nSep>1 ){ 6541 raw_printf(stderr, "Error: multi-character column separators not allowed" 6542 " for import\n"); 6543 return 1; 6544 } 6545 nSep = strlen30(p->rowSeparator); 6546 if( nSep==0 ){ 6547 raw_printf(stderr, "Error: non-null row separator required for import\n"); 6548 return 1; 6549 } 6550 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){ 6551 /* When importing CSV (only), if the row separator is set to the 6552 ** default output row separator, change it to the default input 6553 ** row separator. This avoids having to maintain different input 6554 ** and output row separators. */ 6555 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 6556 nSep = strlen30(p->rowSeparator); 6557 } 6558 if( nSep>1 ){ 6559 raw_printf(stderr, "Error: multi-character row separators not allowed" 6560 " for import\n"); 6561 return 1; 6562 } 6563 sCtx.zFile = zFile; 6564 sCtx.nLine = 1; 6565 if( sCtx.zFile[0]=='|' ){ 6566#ifdef SQLITE_OMIT_POPEN 6567 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 6568 return 1; 6569#else 6570 sCtx.in = popen(sCtx.zFile+1, "r"); 6571 sCtx.zFile = "<pipe>"; 6572 xCloser = pclose; 6573#endif 6574 }else{ 6575 sCtx.in = fopen(sCtx.zFile, "rb"); 6576 xCloser = fclose; 6577 } 6578 if( p->mode==MODE_Ascii ){ 6579 xRead = ascii_read_one_field; 6580 }else{ 6581 xRead = csv_read_one_field; 6582 } 6583 if( sCtx.in==0 ){ 6584 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 6585 return 1; 6586 } 6587 sCtx.cColSep = p->colSeparator[0]; 6588 sCtx.cRowSep = p->rowSeparator[0]; 6589 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); 6590 if( zSql==0 ){ 6591 xCloser(sCtx.in); 6592 shell_out_of_memory(); 6593 } 6594 nByte = strlen30(zSql); 6595 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 6596 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 6597 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 6598 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); 6599 char cSep = '('; 6600 while( xRead(&sCtx) ){ 6601 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); 6602 cSep = ','; 6603 if( sCtx.cTerm!=sCtx.cColSep ) break; 6604 } 6605 if( cSep=='(' ){ 6606 sqlite3_free(zCreate); 6607 sqlite3_free(sCtx.z); 6608 xCloser(sCtx.in); 6609 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 6610 return 1; 6611 } 6612 zCreate = sqlite3_mprintf("%z\n)", zCreate); 6613 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 6614 sqlite3_free(zCreate); 6615 if( rc ){ 6616 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, 6617 sqlite3_errmsg(p->db)); 6618 sqlite3_free(sCtx.z); 6619 xCloser(sCtx.in); 6620 return 1; 6621 } 6622 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 6623 } 6624 sqlite3_free(zSql); 6625 if( rc ){ 6626 if (pStmt) sqlite3_finalize(pStmt); 6627 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 6628 xCloser(sCtx.in); 6629 return 1; 6630 } 6631 nCol = sqlite3_column_count(pStmt); 6632 sqlite3_finalize(pStmt); 6633 pStmt = 0; 6634 if( nCol==0 ) return 0; /* no columns, no error */ 6635 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 6636 if( zSql==0 ){ 6637 xCloser(sCtx.in); 6638 shell_out_of_memory(); 6639 } 6640 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); 6641 j = strlen30(zSql); 6642 for(i=1; i<nCol; i++){ 6643 zSql[j++] = ','; 6644 zSql[j++] = '?'; 6645 } 6646 zSql[j++] = ')'; 6647 zSql[j] = 0; 6648 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 6649 sqlite3_free(zSql); 6650 if( rc ){ 6651 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 6652 if (pStmt) sqlite3_finalize(pStmt); 6653 xCloser(sCtx.in); 6654 return 1; 6655 } 6656 needCommit = sqlite3_get_autocommit(p->db); 6657 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 6658 do{ 6659 int startLine = sCtx.nLine; 6660 for(i=0; i<nCol; i++){ 6661 char *z = xRead(&sCtx); 6662 /* 6663 ** Did we reach end-of-file before finding any columns? 6664 ** If so, stop instead of NULL filling the remaining columns. 6665 */ 6666 if( z==0 && i==0 ) break; 6667 /* 6668 ** Did we reach end-of-file OR end-of-line before finding any 6669 ** columns in ASCII mode? If so, stop instead of NULL filling 6670 ** the remaining columns. 6671 */ 6672 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 6673 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 6674 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 6675 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 6676 "filling the rest with NULL\n", 6677 sCtx.zFile, startLine, nCol, i+1); 6678 i += 2; 6679 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 6680 } 6681 } 6682 if( sCtx.cTerm==sCtx.cColSep ){ 6683 do{ 6684 xRead(&sCtx); 6685 i++; 6686 }while( sCtx.cTerm==sCtx.cColSep ); 6687 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 6688 "extras ignored\n", 6689 sCtx.zFile, startLine, nCol, i); 6690 } 6691 if( i>=nCol ){ 6692 sqlite3_step(pStmt); 6693 rc = sqlite3_reset(pStmt); 6694 if( rc!=SQLITE_OK ){ 6695 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 6696 startLine, sqlite3_errmsg(p->db)); 6697 } 6698 } 6699 }while( sCtx.cTerm!=EOF ); 6700 6701 xCloser(sCtx.in); 6702 sqlite3_free(sCtx.z); 6703 sqlite3_finalize(pStmt); 6704 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 6705 }else 6706 6707#ifndef SQLITE_UNTESTABLE 6708 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){ 6709 char *zSql; 6710 char *zCollist = 0; 6711 sqlite3_stmt *pStmt; 6712 int tnum = 0; 6713 int i; 6714 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 6715 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 6716 " .imposter off\n"); 6717 rc = 1; 6718 goto meta_command_exit; 6719 } 6720 open_db(p, 0); 6721 if( nArg==2 ){ 6722 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 6723 goto meta_command_exit; 6724 } 6725 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master" 6726 " WHERE name='%q' AND type='index'", azArg[1]); 6727 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 6728 sqlite3_free(zSql); 6729 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 6730 tnum = sqlite3_column_int(pStmt, 0); 6731 } 6732 sqlite3_finalize(pStmt); 6733 if( tnum==0 ){ 6734 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 6735 rc = 1; 6736 goto meta_command_exit; 6737 } 6738 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 6739 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 6740 sqlite3_free(zSql); 6741 i = 0; 6742 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 6743 char zLabel[20]; 6744 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 6745 i++; 6746 if( zCol==0 ){ 6747 if( sqlite3_column_int(pStmt,1)==-1 ){ 6748 zCol = "_ROWID_"; 6749 }else{ 6750 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 6751 zCol = zLabel; 6752 } 6753 } 6754 if( zCollist==0 ){ 6755 zCollist = sqlite3_mprintf("\"%w\"", zCol); 6756 }else{ 6757 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 6758 } 6759 } 6760 sqlite3_finalize(pStmt); 6761 zSql = sqlite3_mprintf( 6762 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID", 6763 azArg[2], zCollist, zCollist); 6764 sqlite3_free(zCollist); 6765 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 6766 if( rc==SQLITE_OK ){ 6767 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 6768 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 6769 if( rc ){ 6770 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 6771 }else{ 6772 utf8_printf(stdout, "%s;\n", zSql); 6773 raw_printf(stdout, 6774 "WARNING: writing to an imposter table will corrupt the index!\n" 6775 ); 6776 } 6777 }else{ 6778 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 6779 rc = 1; 6780 } 6781 sqlite3_free(zSql); 6782 }else 6783#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 6784 6785#ifdef SQLITE_ENABLE_IOTRACE 6786 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ 6787 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 6788 if( iotrace && iotrace!=stdout ) fclose(iotrace); 6789 iotrace = 0; 6790 if( nArg<2 ){ 6791 sqlite3IoTrace = 0; 6792 }else if( strcmp(azArg[1], "-")==0 ){ 6793 sqlite3IoTrace = iotracePrintf; 6794 iotrace = stdout; 6795 }else{ 6796 iotrace = fopen(azArg[1], "w"); 6797 if( iotrace==0 ){ 6798 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 6799 sqlite3IoTrace = 0; 6800 rc = 1; 6801 }else{ 6802 sqlite3IoTrace = iotracePrintf; 6803 } 6804 } 6805 }else 6806#endif 6807 6808 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ 6809 static const struct { 6810 const char *zLimitName; /* Name of a limit */ 6811 int limitCode; /* Integer code for that limit */ 6812 } aLimit[] = { 6813 { "length", SQLITE_LIMIT_LENGTH }, 6814 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 6815 { "column", SQLITE_LIMIT_COLUMN }, 6816 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 6817 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 6818 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 6819 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 6820 { "attached", SQLITE_LIMIT_ATTACHED }, 6821 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 6822 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 6823 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 6824 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 6825 }; 6826 int i, n2; 6827 open_db(p, 0); 6828 if( nArg==1 ){ 6829 for(i=0; i<ArraySize(aLimit); i++){ 6830 printf("%20s %d\n", aLimit[i].zLimitName, 6831 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 6832 } 6833 }else if( nArg>3 ){ 6834 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 6835 rc = 1; 6836 goto meta_command_exit; 6837 }else{ 6838 int iLimit = -1; 6839 n2 = strlen30(azArg[1]); 6840 for(i=0; i<ArraySize(aLimit); i++){ 6841 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 6842 if( iLimit<0 ){ 6843 iLimit = i; 6844 }else{ 6845 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 6846 rc = 1; 6847 goto meta_command_exit; 6848 } 6849 } 6850 } 6851 if( iLimit<0 ){ 6852 utf8_printf(stderr, "unknown limit: \"%s\"\n" 6853 "enter \".limits\" with no arguments for a list.\n", 6854 azArg[1]); 6855 rc = 1; 6856 goto meta_command_exit; 6857 } 6858 if( nArg==3 ){ 6859 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 6860 (int)integerValue(azArg[2])); 6861 } 6862 printf("%20s %d\n", aLimit[iLimit].zLimitName, 6863 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 6864 } 6865 }else 6866 6867 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){ 6868 open_db(p, 0); 6869 lintDotCommand(p, azArg, nArg); 6870 }else 6871 6872#ifndef SQLITE_OMIT_LOAD_EXTENSION 6873 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ 6874 const char *zFile, *zProc; 6875 char *zErrMsg = 0; 6876 if( nArg<2 ){ 6877 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 6878 rc = 1; 6879 goto meta_command_exit; 6880 } 6881 zFile = azArg[1]; 6882 zProc = nArg>=3 ? azArg[2] : 0; 6883 open_db(p, 0); 6884 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 6885 if( rc!=SQLITE_OK ){ 6886 utf8_printf(stderr, "Error: %s\n", zErrMsg); 6887 sqlite3_free(zErrMsg); 6888 rc = 1; 6889 } 6890 }else 6891#endif 6892 6893 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ 6894 if( nArg!=2 ){ 6895 raw_printf(stderr, "Usage: .log FILENAME\n"); 6896 rc = 1; 6897 }else{ 6898 const char *zFile = azArg[1]; 6899 output_file_close(p->pLog); 6900 p->pLog = output_file_open(zFile, 0); 6901 } 6902 }else 6903 6904 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ 6905 const char *zMode = nArg>=2 ? azArg[1] : ""; 6906 int n2 = strlen30(zMode); 6907 int c2 = zMode[0]; 6908 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ 6909 p->mode = MODE_Line; 6910 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 6911 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ 6912 p->mode = MODE_Column; 6913 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 6914 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ 6915 p->mode = MODE_List; 6916 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 6917 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 6918 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ 6919 p->mode = MODE_Html; 6920 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ 6921 p->mode = MODE_Tcl; 6922 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 6923 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 6924 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ 6925 p->mode = MODE_Csv; 6926 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 6927 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 6928 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ 6929 p->mode = MODE_List; 6930 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 6931 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ 6932 p->mode = MODE_Insert; 6933 set_table_name(p, nArg>=3 ? azArg[2] : "table"); 6934 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){ 6935 p->mode = MODE_Quote; 6936 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ 6937 p->mode = MODE_Ascii; 6938 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 6939 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 6940 }else if( nArg==1 ){ 6941 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 6942 }else{ 6943 raw_printf(stderr, "Error: mode should be one of: " 6944 "ascii column csv html insert line list quote tabs tcl\n"); 6945 rc = 1; 6946 } 6947 p->cMode = p->mode; 6948 }else 6949 6950 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ 6951 if( nArg==2 ){ 6952 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 6953 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 6954 }else{ 6955 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 6956 rc = 1; 6957 } 6958 }else 6959 6960 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ 6961 char *zNewFilename; /* Name of the database file to open */ 6962 int iName = 1; /* Index in azArg[] of the filename */ 6963 int newFlag = 0; /* True to delete file before opening */ 6964 /* Close the existing database */ 6965 session_close_all(p); 6966 close_db(p->db); 6967 p->db = 0; 6968 p->zDbFilename = 0; 6969 sqlite3_free(p->zFreeOnClose); 6970 p->zFreeOnClose = 0; 6971 p->openMode = SHELL_OPEN_UNSPEC; 6972 p->szMax = 0; 6973 /* Check for command-line arguments */ 6974 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){ 6975 const char *z = azArg[iName]; 6976 if( optionMatch(z,"new") ){ 6977 newFlag = 1; 6978#ifdef SQLITE_HAVE_ZLIB 6979 }else if( optionMatch(z, "zip") ){ 6980 p->openMode = SHELL_OPEN_ZIPFILE; 6981#endif 6982 }else if( optionMatch(z, "append") ){ 6983 p->openMode = SHELL_OPEN_APPENDVFS; 6984 }else if( optionMatch(z, "readonly") ){ 6985 p->openMode = SHELL_OPEN_READONLY; 6986#ifdef SQLITE_ENABLE_DESERIALIZE 6987 }else if( optionMatch(z, "deserialize") ){ 6988 p->openMode = SHELL_OPEN_DESERIALIZE; 6989 }else if( optionMatch(z, "hexdb") ){ 6990 p->openMode = SHELL_OPEN_HEXDB; 6991 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 6992 p->szMax = integerValue(azArg[++iName]); 6993#endif /* SQLITE_ENABLE_DESERIALIZE */ 6994 }else if( z[0]=='-' ){ 6995 utf8_printf(stderr, "unknown option: %s\n", z); 6996 rc = 1; 6997 goto meta_command_exit; 6998 } 6999 } 7000 /* If a filename is specified, try to open it first */ 7001 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0; 7002 if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){ 7003 if( newFlag ) shellDeleteFile(zNewFilename); 7004 p->zDbFilename = zNewFilename; 7005 open_db(p, OPEN_DB_KEEPALIVE); 7006 if( p->db==0 ){ 7007 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 7008 sqlite3_free(zNewFilename); 7009 }else{ 7010 p->zFreeOnClose = zNewFilename; 7011 } 7012 } 7013 if( p->db==0 ){ 7014 /* As a fall-back open a TEMP database */ 7015 p->zDbFilename = 0; 7016 open_db(p, 0); 7017 } 7018 }else 7019 7020 if( (c=='o' 7021 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0)) 7022 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0) 7023 ){ 7024 const char *zFile = nArg>=2 ? azArg[1] : "stdout"; 7025 int bTxtMode = 0; 7026 if( azArg[0][0]=='e' ){ 7027 /* Transform the ".excel" command into ".once -x" */ 7028 nArg = 2; 7029 azArg[0] = "once"; 7030 zFile = azArg[1] = "-x"; 7031 n = 4; 7032 } 7033 if( nArg>2 ){ 7034 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]); 7035 rc = 1; 7036 goto meta_command_exit; 7037 } 7038 if( n>1 && strncmp(azArg[0], "once", n)==0 ){ 7039 if( nArg<2 ){ 7040 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n"); 7041 rc = 1; 7042 goto meta_command_exit; 7043 } 7044 p->outCount = 2; 7045 }else{ 7046 p->outCount = 0; 7047 } 7048 output_reset(p); 7049 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++; 7050#ifndef SQLITE_NOHAVE_SYSTEM 7051 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){ 7052 p->doXdgOpen = 1; 7053 outputModePush(p); 7054 if( zFile[1]=='x' ){ 7055 newTempFile(p, "csv"); 7056 p->mode = MODE_Csv; 7057 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 7058 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 7059 }else{ 7060 newTempFile(p, "txt"); 7061 bTxtMode = 1; 7062 } 7063 zFile = p->zTempFile; 7064 } 7065#endif /* SQLITE_NOHAVE_SYSTEM */ 7066 if( zFile[0]=='|' ){ 7067#ifdef SQLITE_OMIT_POPEN 7068 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 7069 rc = 1; 7070 p->out = stdout; 7071#else 7072 p->out = popen(zFile + 1, "w"); 7073 if( p->out==0 ){ 7074 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 7075 p->out = stdout; 7076 rc = 1; 7077 }else{ 7078 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 7079 } 7080#endif 7081 }else{ 7082 p->out = output_file_open(zFile, bTxtMode); 7083 if( p->out==0 ){ 7084 if( strcmp(zFile,"off")!=0 ){ 7085 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 7086 } 7087 p->out = stdout; 7088 rc = 1; 7089 } else { 7090 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 7091 } 7092 } 7093 }else 7094 7095 if( c=='p' && n>=3 && strncmp(azArg[0], "parameter", n)==0 ){ 7096 open_db(p,0); 7097 if( nArg<=1 ) goto parameter_syntax_error; 7098 7099 /* .parameter clear 7100 ** Clear all bind parameters by dropping the TEMP table that holds them. 7101 */ 7102 if( nArg==2 && strcmp(azArg[1],"clear")==0 ){ 7103 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.[" BIND_PARAM_TABLE "];", 7104 0, 0, 0); 7105 }else 7106 7107 /* .parameter list 7108 ** List all bind parameters. 7109 */ 7110 if( nArg==2 && strcmp(azArg[1],"list")==0 ){ 7111 sqlite3_stmt *pStmt = 0; 7112 int rx; 7113 int len = 0; 7114 rx = sqlite3_prepare_v2(p->db, 7115 "SELECT max(length(key)) " 7116 "FROM temp.[" BIND_PARAM_TABLE "];", -1, &pStmt, 0); 7117 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 7118 len = sqlite3_column_int(pStmt, 0); 7119 if( len>40 ) len = 40; 7120 } 7121 sqlite3_finalize(pStmt); 7122 pStmt = 0; 7123 if( len ){ 7124 rx = sqlite3_prepare_v2(p->db, 7125 "SELECT key, quote(value) " 7126 "FROM temp.[" BIND_PARAM_TABLE "];", -1, &pStmt, 0); 7127 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7128 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 7129 sqlite3_column_text(pStmt,1)); 7130 } 7131 sqlite3_finalize(pStmt); 7132 } 7133 }else 7134 7135 /* .parameter init 7136 ** Make sure the TEMP table used to hold bind parameters exists. 7137 ** Create it if necessary. 7138 */ 7139 if( nArg==2 && strcmp(azArg[1],"init")==0 ){ 7140 bind_table_init(p); 7141 }else 7142 7143 /* .parameter set NAME VALUE 7144 ** Set or reset a bind parameter. NAME should be the full parameter 7145 ** name exactly as it appears in the query. (ex: $abc, @def). The 7146 ** VALUE can be in either SQL literal notation, or if not it will be 7147 ** understood to be a text string. 7148 */ 7149 if( nArg==4 && strcmp(azArg[1],"set")==0 ){ 7150 int rx; 7151 char *zSql; 7152 sqlite3_stmt *pStmt; 7153 const char *zKey = azArg[2]; 7154 const char *zValue = azArg[3]; 7155 bind_table_init(p); 7156 zSql = sqlite3_mprintf( 7157 "REPLACE INTO temp.[" BIND_PARAM_TABLE "](key,value)" 7158 "VALUES(%Q,%s);", zKey, zValue); 7159 if( zSql==0 ) shell_out_of_memory(); 7160 pStmt = 0; 7161 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7162 sqlite3_free(zSql); 7163 if( rx!=SQLITE_OK ){ 7164 sqlite3_finalize(pStmt); 7165 pStmt = 0; 7166 zSql = sqlite3_mprintf( 7167 "REPLACE INTO temp.[" BIND_PARAM_TABLE "](key,value)" 7168 "VALUES(%Q,%Q);", zKey, zValue); 7169 if( zSql==0 ) shell_out_of_memory(); 7170 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7171 sqlite3_free(zSql); 7172 if( rx!=SQLITE_OK ){ 7173 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 7174 sqlite3_finalize(pStmt); 7175 pStmt = 0; 7176 rc = 1; 7177 } 7178 } 7179 sqlite3_step(pStmt); 7180 sqlite3_finalize(pStmt); 7181 }else 7182 7183 /* .parameter unset NAME 7184 ** Remove the NAME binding from the parameter binding table, if it 7185 ** exists. 7186 */ 7187 if( nArg==3 && strcmp(azArg[1],"unset")==0 ){ 7188 char *zSql = sqlite3_mprintf( 7189 "DELETE FROM temp.[" BIND_PARAM_TABLE "] WHERE key=%Q", azArg[2]); 7190 if( zSql==0 ) shell_out_of_memory(); 7191 sqlite3_exec(p->db, zSql, 0, 0, 0); 7192 sqlite3_free(zSql); 7193 }else 7194 /* If no command name matches, show a syntax error */ 7195 parameter_syntax_error: 7196 showHelp(p->out, "parameter"); 7197 }else 7198 7199 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ 7200 int i; 7201 for(i=1; i<nArg; i++){ 7202 if( i>1 ) raw_printf(p->out, " "); 7203 utf8_printf(p->out, "%s", azArg[i]); 7204 } 7205 raw_printf(p->out, "\n"); 7206 }else 7207 7208#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 7209 if( c=='p' && n>=3 && strncmp(azArg[0], "progress", n)==0 ){ 7210 int i; 7211 int nn = 0; 7212 p->flgProgress = 0; 7213 p->mxProgress = 0; 7214 p->nProgress = 0; 7215 for(i=1; i<nArg; i++){ 7216 const char *z = azArg[i]; 7217 if( z[0]=='-' ){ 7218 z++; 7219 if( z[0]=='-' ) z++; 7220 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){ 7221 p->flgProgress |= SHELL_PROGRESS_QUIET; 7222 continue; 7223 } 7224 if( strcmp(z,"reset")==0 ){ 7225 p->flgProgress |= SHELL_PROGRESS_RESET; 7226 continue; 7227 } 7228 if( strcmp(z,"once")==0 ){ 7229 p->flgProgress |= SHELL_PROGRESS_ONCE; 7230 continue; 7231 } 7232 if( strcmp(z,"limit")==0 ){ 7233 if( i+1>=nArg ){ 7234 utf8_printf(stderr, "Error: missing argument on --limit\n"); 7235 rc = 1; 7236 goto meta_command_exit; 7237 }else{ 7238 p->mxProgress = (int)integerValue(azArg[++i]); 7239 } 7240 continue; 7241 } 7242 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 7243 rc = 1; 7244 goto meta_command_exit; 7245 }else{ 7246 nn = (int)integerValue(z); 7247 } 7248 } 7249 open_db(p, 0); 7250 sqlite3_progress_handler(p->db, nn, progress_handler, p); 7251 }else 7252#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 7253 7254 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ 7255 if( nArg >= 2) { 7256 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 7257 } 7258 if( nArg >= 3) { 7259 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 7260 } 7261 }else 7262 7263 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ 7264 rc = 2; 7265 }else 7266 7267 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ 7268 FILE *inSaved = p->in; 7269 int savedLineno = p->lineno; 7270 if( nArg!=2 ){ 7271 raw_printf(stderr, "Usage: .read FILE\n"); 7272 rc = 1; 7273 goto meta_command_exit; 7274 } 7275 p->in = fopen(azArg[1], "rb"); 7276 if( p->in==0 ){ 7277 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 7278 rc = 1; 7279 }else{ 7280 rc = process_input(p); 7281 fclose(p->in); 7282 } 7283 p->in = inSaved; 7284 p->lineno = savedLineno; 7285 }else 7286 7287 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ 7288 const char *zSrcFile; 7289 const char *zDb; 7290 sqlite3 *pSrc; 7291 sqlite3_backup *pBackup; 7292 int nTimeout = 0; 7293 7294 if( nArg==2 ){ 7295 zSrcFile = azArg[1]; 7296 zDb = "main"; 7297 }else if( nArg==3 ){ 7298 zSrcFile = azArg[2]; 7299 zDb = azArg[1]; 7300 }else{ 7301 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 7302 rc = 1; 7303 goto meta_command_exit; 7304 } 7305 rc = sqlite3_open(zSrcFile, &pSrc); 7306 if( rc!=SQLITE_OK ){ 7307 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 7308 close_db(pSrc); 7309 return 1; 7310 } 7311 open_db(p, 0); 7312 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 7313 if( pBackup==0 ){ 7314 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7315 close_db(pSrc); 7316 return 1; 7317 } 7318 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 7319 || rc==SQLITE_BUSY ){ 7320 if( rc==SQLITE_BUSY ){ 7321 if( nTimeout++ >= 3 ) break; 7322 sqlite3_sleep(100); 7323 } 7324 } 7325 sqlite3_backup_finish(pBackup); 7326 if( rc==SQLITE_DONE ){ 7327 rc = 0; 7328 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 7329 raw_printf(stderr, "Error: source database is busy\n"); 7330 rc = 1; 7331 }else{ 7332 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7333 rc = 1; 7334 } 7335 close_db(pSrc); 7336 }else 7337 7338 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ 7339 if( nArg==2 ){ 7340 p->scanstatsOn = (u8)booleanValue(azArg[1]); 7341#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 7342 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 7343#endif 7344 }else{ 7345 raw_printf(stderr, "Usage: .scanstats on|off\n"); 7346 rc = 1; 7347 } 7348 }else 7349 7350 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ 7351 ShellText sSelect; 7352 ShellState data; 7353 char *zErrMsg = 0; 7354 const char *zDiv = "("; 7355 const char *zName = 0; 7356 int iSchema = 0; 7357 int bDebug = 0; 7358 int ii; 7359 7360 open_db(p, 0); 7361 memcpy(&data, p, sizeof(data)); 7362 data.showHeader = 0; 7363 data.cMode = data.mode = MODE_Semi; 7364 initText(&sSelect); 7365 for(ii=1; ii<nArg; ii++){ 7366 if( optionMatch(azArg[ii],"indent") ){ 7367 data.cMode = data.mode = MODE_Pretty; 7368 }else if( optionMatch(azArg[ii],"debug") ){ 7369 bDebug = 1; 7370 }else if( zName==0 ){ 7371 zName = azArg[ii]; 7372 }else{ 7373 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); 7374 rc = 1; 7375 goto meta_command_exit; 7376 } 7377 } 7378 if( zName!=0 ){ 7379 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0; 7380 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){ 7381 char *new_argv[2], *new_colv[2]; 7382 new_argv[0] = sqlite3_mprintf( 7383 "CREATE TABLE %s (\n" 7384 " type text,\n" 7385 " name text,\n" 7386 " tbl_name text,\n" 7387 " rootpage integer,\n" 7388 " sql text\n" 7389 ")", isMaster ? "sqlite_master" : "sqlite_temp_master"); 7390 new_argv[1] = 0; 7391 new_colv[0] = "sql"; 7392 new_colv[1] = 0; 7393 callback(&data, 1, new_argv, new_colv); 7394 sqlite3_free(new_argv[0]); 7395 } 7396 } 7397 if( zDiv ){ 7398 sqlite3_stmt *pStmt = 0; 7399 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 7400 -1, &pStmt, 0); 7401 if( rc ){ 7402 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7403 sqlite3_finalize(pStmt); 7404 rc = 1; 7405 goto meta_command_exit; 7406 } 7407 appendText(&sSelect, "SELECT sql FROM", 0); 7408 iSchema = 0; 7409 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7410 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 7411 char zScNum[30]; 7412 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 7413 appendText(&sSelect, zDiv, 0); 7414 zDiv = " UNION ALL "; 7415 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 7416 if( sqlite3_stricmp(zDb, "main")!=0 ){ 7417 appendText(&sSelect, zDb, '"'); 7418 }else{ 7419 appendText(&sSelect, "NULL", 0); 7420 } 7421 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 7422 appendText(&sSelect, zScNum, 0); 7423 appendText(&sSelect, " AS snum, ", 0); 7424 appendText(&sSelect, zDb, '\''); 7425 appendText(&sSelect, " AS sname FROM ", 0); 7426 appendText(&sSelect, zDb, '"'); 7427 appendText(&sSelect, ".sqlite_master", 0); 7428 } 7429 sqlite3_finalize(pStmt); 7430#ifdef SQLITE_INTROSPECTION_PRAGMAS 7431 if( zName ){ 7432 appendText(&sSelect, 7433 " UNION ALL SELECT shell_module_schema(name)," 7434 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0); 7435 } 7436#endif 7437 appendText(&sSelect, ") WHERE ", 0); 7438 if( zName ){ 7439 char *zQarg = sqlite3_mprintf("%Q", zName); 7440 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 7441 strchr(zName, '[') != 0; 7442 if( strchr(zName, '.') ){ 7443 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 7444 }else{ 7445 appendText(&sSelect, "lower(tbl_name)", 0); 7446 } 7447 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 7448 appendText(&sSelect, zQarg, 0); 7449 if( !bGlob ){ 7450 appendText(&sSelect, " ESCAPE '\\' ", 0); 7451 } 7452 appendText(&sSelect, " AND ", 0); 7453 sqlite3_free(zQarg); 7454 } 7455 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL" 7456 " ORDER BY snum, rowid", 0); 7457 if( bDebug ){ 7458 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 7459 }else{ 7460 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 7461 } 7462 freeText(&sSelect); 7463 } 7464 if( zErrMsg ){ 7465 utf8_printf(stderr,"Error: %s\n", zErrMsg); 7466 sqlite3_free(zErrMsg); 7467 rc = 1; 7468 }else if( rc != SQLITE_OK ){ 7469 raw_printf(stderr,"Error: querying schema information\n"); 7470 rc = 1; 7471 }else{ 7472 rc = 0; 7473 } 7474 }else 7475 7476#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) 7477 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ 7478 sqlite3SelectTrace = (int)integerValue(azArg[1]); 7479 }else 7480#endif 7481 7482#if defined(SQLITE_ENABLE_SESSION) 7483 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ 7484 OpenSession *pSession = &p->aSession[0]; 7485 char **azCmd = &azArg[1]; 7486 int iSes = 0; 7487 int nCmd = nArg - 1; 7488 int i; 7489 if( nArg<=1 ) goto session_syntax_error; 7490 open_db(p, 0); 7491 if( nArg>=3 ){ 7492 for(iSes=0; iSes<p->nSession; iSes++){ 7493 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; 7494 } 7495 if( iSes<p->nSession ){ 7496 pSession = &p->aSession[iSes]; 7497 azCmd++; 7498 nCmd--; 7499 }else{ 7500 pSession = &p->aSession[0]; 7501 iSes = 0; 7502 } 7503 } 7504 7505 /* .session attach TABLE 7506 ** Invoke the sqlite3session_attach() interface to attach a particular 7507 ** table so that it is never filtered. 7508 */ 7509 if( strcmp(azCmd[0],"attach")==0 ){ 7510 if( nCmd!=2 ) goto session_syntax_error; 7511 if( pSession->p==0 ){ 7512 session_not_open: 7513 raw_printf(stderr, "ERROR: No sessions are open\n"); 7514 }else{ 7515 rc = sqlite3session_attach(pSession->p, azCmd[1]); 7516 if( rc ){ 7517 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 7518 rc = 0; 7519 } 7520 } 7521 }else 7522 7523 /* .session changeset FILE 7524 ** .session patchset FILE 7525 ** Write a changeset or patchset into a file. The file is overwritten. 7526 */ 7527 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ 7528 FILE *out = 0; 7529 if( nCmd!=2 ) goto session_syntax_error; 7530 if( pSession->p==0 ) goto session_not_open; 7531 out = fopen(azCmd[1], "wb"); 7532 if( out==0 ){ 7533 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]); 7534 }else{ 7535 int szChng; 7536 void *pChng; 7537 if( azCmd[0][0]=='c' ){ 7538 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 7539 }else{ 7540 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 7541 } 7542 if( rc ){ 7543 printf("Error: error code %d\n", rc); 7544 rc = 0; 7545 } 7546 if( pChng 7547 && fwrite(pChng, szChng, 1, out)!=1 ){ 7548 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 7549 szChng); 7550 } 7551 sqlite3_free(pChng); 7552 fclose(out); 7553 } 7554 }else 7555 7556 /* .session close 7557 ** Close the identified session 7558 */ 7559 if( strcmp(azCmd[0], "close")==0 ){ 7560 if( nCmd!=1 ) goto session_syntax_error; 7561 if( p->nSession ){ 7562 session_close(pSession); 7563 p->aSession[iSes] = p->aSession[--p->nSession]; 7564 } 7565 }else 7566 7567 /* .session enable ?BOOLEAN? 7568 ** Query or set the enable flag 7569 */ 7570 if( strcmp(azCmd[0], "enable")==0 ){ 7571 int ii; 7572 if( nCmd>2 ) goto session_syntax_error; 7573 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 7574 if( p->nSession ){ 7575 ii = sqlite3session_enable(pSession->p, ii); 7576 utf8_printf(p->out, "session %s enable flag = %d\n", 7577 pSession->zName, ii); 7578 } 7579 }else 7580 7581 /* .session filter GLOB .... 7582 ** Set a list of GLOB patterns of table names to be excluded. 7583 */ 7584 if( strcmp(azCmd[0], "filter")==0 ){ 7585 int ii, nByte; 7586 if( nCmd<2 ) goto session_syntax_error; 7587 if( p->nSession ){ 7588 for(ii=0; ii<pSession->nFilter; ii++){ 7589 sqlite3_free(pSession->azFilter[ii]); 7590 } 7591 sqlite3_free(pSession->azFilter); 7592 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 7593 pSession->azFilter = sqlite3_malloc( nByte ); 7594 if( pSession->azFilter==0 ){ 7595 raw_printf(stderr, "Error: out or memory\n"); 7596 exit(1); 7597 } 7598 for(ii=1; ii<nCmd; ii++){ 7599 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 7600 } 7601 pSession->nFilter = ii-1; 7602 } 7603 }else 7604 7605 /* .session indirect ?BOOLEAN? 7606 ** Query or set the indirect flag 7607 */ 7608 if( strcmp(azCmd[0], "indirect")==0 ){ 7609 int ii; 7610 if( nCmd>2 ) goto session_syntax_error; 7611 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 7612 if( p->nSession ){ 7613 ii = sqlite3session_indirect(pSession->p, ii); 7614 utf8_printf(p->out, "session %s indirect flag = %d\n", 7615 pSession->zName, ii); 7616 } 7617 }else 7618 7619 /* .session isempty 7620 ** Determine if the session is empty 7621 */ 7622 if( strcmp(azCmd[0], "isempty")==0 ){ 7623 int ii; 7624 if( nCmd!=1 ) goto session_syntax_error; 7625 if( p->nSession ){ 7626 ii = sqlite3session_isempty(pSession->p); 7627 utf8_printf(p->out, "session %s isempty flag = %d\n", 7628 pSession->zName, ii); 7629 } 7630 }else 7631 7632 /* .session list 7633 ** List all currently open sessions 7634 */ 7635 if( strcmp(azCmd[0],"list")==0 ){ 7636 for(i=0; i<p->nSession; i++){ 7637 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); 7638 } 7639 }else 7640 7641 /* .session open DB NAME 7642 ** Open a new session called NAME on the attached database DB. 7643 ** DB is normally "main". 7644 */ 7645 if( strcmp(azCmd[0],"open")==0 ){ 7646 char *zName; 7647 if( nCmd!=3 ) goto session_syntax_error; 7648 zName = azCmd[2]; 7649 if( zName[0]==0 ) goto session_syntax_error; 7650 for(i=0; i<p->nSession; i++){ 7651 if( strcmp(p->aSession[i].zName,zName)==0 ){ 7652 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 7653 goto meta_command_exit; 7654 } 7655 } 7656 if( p->nSession>=ArraySize(p->aSession) ){ 7657 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); 7658 goto meta_command_exit; 7659 } 7660 pSession = &p->aSession[p->nSession]; 7661 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 7662 if( rc ){ 7663 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 7664 rc = 0; 7665 goto meta_command_exit; 7666 } 7667 pSession->nFilter = 0; 7668 sqlite3session_table_filter(pSession->p, session_filter, pSession); 7669 p->nSession++; 7670 pSession->zName = sqlite3_mprintf("%s", zName); 7671 }else 7672 /* If no command name matches, show a syntax error */ 7673 session_syntax_error: 7674 showHelp(p->out, "session"); 7675 }else 7676#endif 7677 7678#ifdef SQLITE_DEBUG 7679 /* Undocumented commands for internal testing. Subject to change 7680 ** without notice. */ 7681 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ 7682 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 7683 int i, v; 7684 for(i=1; i<nArg; i++){ 7685 v = booleanValue(azArg[i]); 7686 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 7687 } 7688 } 7689 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ 7690 int i; sqlite3_int64 v; 7691 for(i=1; i<nArg; i++){ 7692 char zBuf[200]; 7693 v = integerValue(azArg[i]); 7694 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 7695 utf8_printf(p->out, "%s", zBuf); 7696 } 7697 } 7698 }else 7699#endif 7700 7701 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){ 7702 int bIsInit = 0; /* True to initialize the SELFTEST table */ 7703 int bVerbose = 0; /* Verbose output */ 7704 int bSelftestExists; /* True if SELFTEST already exists */ 7705 int i, k; /* Loop counters */ 7706 int nTest = 0; /* Number of tests runs */ 7707 int nErr = 0; /* Number of errors seen */ 7708 ShellText str; /* Answer for a query */ 7709 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 7710 7711 open_db(p,0); 7712 for(i=1; i<nArg; i++){ 7713 const char *z = azArg[i]; 7714 if( z[0]=='-' && z[1]=='-' ) z++; 7715 if( strcmp(z,"-init")==0 ){ 7716 bIsInit = 1; 7717 }else 7718 if( strcmp(z,"-v")==0 ){ 7719 bVerbose++; 7720 }else 7721 { 7722 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 7723 azArg[i], azArg[0]); 7724 raw_printf(stderr, "Should be one of: --init -v\n"); 7725 rc = 1; 7726 goto meta_command_exit; 7727 } 7728 } 7729 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 7730 != SQLITE_OK ){ 7731 bSelftestExists = 0; 7732 }else{ 7733 bSelftestExists = 1; 7734 } 7735 if( bIsInit ){ 7736 createSelftestTable(p); 7737 bSelftestExists = 1; 7738 } 7739 initText(&str); 7740 appendText(&str, "x", 0); 7741 for(k=bSelftestExists; k>=0; k--){ 7742 if( k==1 ){ 7743 rc = sqlite3_prepare_v2(p->db, 7744 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 7745 -1, &pStmt, 0); 7746 }else{ 7747 rc = sqlite3_prepare_v2(p->db, 7748 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 7749 " (1,'run','PRAGMA integrity_check','ok')", 7750 -1, &pStmt, 0); 7751 } 7752 if( rc ){ 7753 raw_printf(stderr, "Error querying the selftest table\n"); 7754 rc = 1; 7755 sqlite3_finalize(pStmt); 7756 goto meta_command_exit; 7757 } 7758 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 7759 int tno = sqlite3_column_int(pStmt, 0); 7760 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 7761 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 7762 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 7763 7764 k = 0; 7765 if( bVerbose>0 ){ 7766 char *zQuote = sqlite3_mprintf("%q", zSql); 7767 printf("%d: %s %s\n", tno, zOp, zSql); 7768 sqlite3_free(zQuote); 7769 } 7770 if( strcmp(zOp,"memo")==0 ){ 7771 utf8_printf(p->out, "%s\n", zSql); 7772 }else 7773 if( strcmp(zOp,"run")==0 ){ 7774 char *zErrMsg = 0; 7775 str.n = 0; 7776 str.z[0] = 0; 7777 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 7778 nTest++; 7779 if( bVerbose ){ 7780 utf8_printf(p->out, "Result: %s\n", str.z); 7781 } 7782 if( rc || zErrMsg ){ 7783 nErr++; 7784 rc = 1; 7785 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 7786 sqlite3_free(zErrMsg); 7787 }else if( strcmp(zAns,str.z)!=0 ){ 7788 nErr++; 7789 rc = 1; 7790 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 7791 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 7792 } 7793 }else 7794 { 7795 utf8_printf(stderr, 7796 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 7797 rc = 1; 7798 break; 7799 } 7800 } /* End loop over rows of content from SELFTEST */ 7801 sqlite3_finalize(pStmt); 7802 } /* End loop over k */ 7803 freeText(&str); 7804 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 7805 }else 7806 7807 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ 7808 if( nArg<2 || nArg>3 ){ 7809 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 7810 rc = 1; 7811 } 7812 if( nArg>=2 ){ 7813 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 7814 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 7815 } 7816 if( nArg>=3 ){ 7817 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 7818 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 7819 } 7820 }else 7821 7822 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){ 7823 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 7824 int i; /* Loop counter */ 7825 int bSchema = 0; /* Also hash the schema */ 7826 int bSeparate = 0; /* Hash each table separately */ 7827 int iSize = 224; /* Hash algorithm to use */ 7828 int bDebug = 0; /* Only show the query that would have run */ 7829 sqlite3_stmt *pStmt; /* For querying tables names */ 7830 char *zSql; /* SQL to be run */ 7831 char *zSep; /* Separator */ 7832 ShellText sSql; /* Complete SQL for the query to run the hash */ 7833 ShellText sQuery; /* Set of queries used to read all content */ 7834 open_db(p, 0); 7835 for(i=1; i<nArg; i++){ 7836 const char *z = azArg[i]; 7837 if( z[0]=='-' ){ 7838 z++; 7839 if( z[0]=='-' ) z++; 7840 if( strcmp(z,"schema")==0 ){ 7841 bSchema = 1; 7842 }else 7843 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0 7844 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0 7845 ){ 7846 iSize = atoi(&z[5]); 7847 }else 7848 if( strcmp(z,"debug")==0 ){ 7849 bDebug = 1; 7850 }else 7851 { 7852 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 7853 azArg[i], azArg[0]); 7854 raw_printf(stderr, "Should be one of: --schema" 7855 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n"); 7856 rc = 1; 7857 goto meta_command_exit; 7858 } 7859 }else if( zLike ){ 7860 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 7861 rc = 1; 7862 goto meta_command_exit; 7863 }else{ 7864 zLike = z; 7865 bSeparate = 1; 7866 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 7867 } 7868 } 7869 if( bSchema ){ 7870 zSql = "SELECT lower(name) FROM sqlite_master" 7871 " WHERE type='table' AND coalesce(rootpage,0)>1" 7872 " UNION ALL SELECT 'sqlite_master'" 7873 " ORDER BY 1 collate nocase"; 7874 }else{ 7875 zSql = "SELECT lower(name) FROM sqlite_master" 7876 " WHERE type='table' AND coalesce(rootpage,0)>1" 7877 " AND name NOT LIKE 'sqlite_%'" 7878 " ORDER BY 1 collate nocase"; 7879 } 7880 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 7881 initText(&sQuery); 7882 initText(&sSql); 7883 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 7884 zSep = "VALUES("; 7885 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 7886 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 7887 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 7888 if( strncmp(zTab, "sqlite_",7)!=0 ){ 7889 appendText(&sQuery,"SELECT * FROM ", 0); 7890 appendText(&sQuery,zTab,'"'); 7891 appendText(&sQuery," NOT INDEXED;", 0); 7892 }else if( strcmp(zTab, "sqlite_master")==0 ){ 7893 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master" 7894 " ORDER BY name;", 0); 7895 }else if( strcmp(zTab, "sqlite_sequence")==0 ){ 7896 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 7897 " ORDER BY name;", 0); 7898 }else if( strcmp(zTab, "sqlite_stat1")==0 ){ 7899 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 7900 " ORDER BY tbl,idx;", 0); 7901 }else if( strcmp(zTab, "sqlite_stat3")==0 7902 || strcmp(zTab, "sqlite_stat4")==0 ){ 7903 appendText(&sQuery, "SELECT * FROM ", 0); 7904 appendText(&sQuery, zTab, 0); 7905 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 7906 } 7907 appendText(&sSql, zSep, 0); 7908 appendText(&sSql, sQuery.z, '\''); 7909 sQuery.n = 0; 7910 appendText(&sSql, ",", 0); 7911 appendText(&sSql, zTab, '\''); 7912 zSep = "),("; 7913 } 7914 sqlite3_finalize(pStmt); 7915 if( bSeparate ){ 7916 zSql = sqlite3_mprintf( 7917 "%s))" 7918 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 7919 " FROM [sha3sum$query]", 7920 sSql.z, iSize); 7921 }else{ 7922 zSql = sqlite3_mprintf( 7923 "%s))" 7924 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 7925 " FROM [sha3sum$query]", 7926 sSql.z, iSize); 7927 } 7928 freeText(&sQuery); 7929 freeText(&sSql); 7930 if( bDebug ){ 7931 utf8_printf(p->out, "%s\n", zSql); 7932 }else{ 7933 shell_exec(p, zSql, 0); 7934 } 7935 sqlite3_free(zSql); 7936 }else 7937 7938#ifndef SQLITE_NOHAVE_SYSTEM 7939 if( c=='s' 7940 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) 7941 ){ 7942 char *zCmd; 7943 int i, x; 7944 if( nArg<2 ){ 7945 raw_printf(stderr, "Usage: .system COMMAND\n"); 7946 rc = 1; 7947 goto meta_command_exit; 7948 } 7949 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 7950 for(i=2; i<nArg; i++){ 7951 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 7952 zCmd, azArg[i]); 7953 } 7954 x = system(zCmd); 7955 sqlite3_free(zCmd); 7956 if( x ) raw_printf(stderr, "System command returns %d\n", x); 7957 }else 7958#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 7959 7960 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ 7961 static const char *azBool[] = { "off", "on", "trigger", "full"}; 7962 int i; 7963 if( nArg!=1 ){ 7964 raw_printf(stderr, "Usage: .show\n"); 7965 rc = 1; 7966 goto meta_command_exit; 7967 } 7968 utf8_printf(p->out, "%12.12s: %s\n","echo", 7969 azBool[ShellHasFlag(p, SHFLG_Echo)]); 7970 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 7971 utf8_printf(p->out, "%12.12s: %s\n","explain", 7972 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 7973 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 7974 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 7975 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 7976 output_c_string(p->out, p->nullValue); 7977 raw_printf(p->out, "\n"); 7978 utf8_printf(p->out,"%12.12s: %s\n","output", 7979 strlen30(p->outfile) ? p->outfile : "stdout"); 7980 utf8_printf(p->out,"%12.12s: ", "colseparator"); 7981 output_c_string(p->out, p->colSeparator); 7982 raw_printf(p->out, "\n"); 7983 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 7984 output_c_string(p->out, p->rowSeparator); 7985 raw_printf(p->out, "\n"); 7986 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); 7987 utf8_printf(p->out, "%12.12s: ", "width"); 7988 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { 7989 raw_printf(p->out, "%d ", p->colWidth[i]); 7990 } 7991 raw_printf(p->out, "\n"); 7992 utf8_printf(p->out, "%12.12s: %s\n", "filename", 7993 p->zDbFilename ? p->zDbFilename : ""); 7994 }else 7995 7996 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ 7997 if( nArg==2 ){ 7998 p->statsOn = (u8)booleanValue(azArg[1]); 7999 }else if( nArg==1 ){ 8000 display_stats(p->db, p, 0); 8001 }else{ 8002 raw_printf(stderr, "Usage: .stats ?on|off?\n"); 8003 rc = 1; 8004 } 8005 }else 8006 8007 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0) 8008 || (c=='i' && (strncmp(azArg[0], "indices", n)==0 8009 || strncmp(azArg[0], "indexes", n)==0) ) 8010 ){ 8011 sqlite3_stmt *pStmt; 8012 char **azResult; 8013 int nRow, nAlloc; 8014 int ii; 8015 ShellText s; 8016 initText(&s); 8017 open_db(p, 0); 8018 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 8019 if( rc ){ 8020 sqlite3_finalize(pStmt); 8021 return shellDatabaseError(p->db); 8022 } 8023 8024 if( nArg>2 && c=='i' ){ 8025 /* It is an historical accident that the .indexes command shows an error 8026 ** when called with the wrong number of arguments whereas the .tables 8027 ** command does not. */ 8028 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 8029 rc = 1; 8030 sqlite3_finalize(pStmt); 8031 goto meta_command_exit; 8032 } 8033 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 8034 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 8035 if( zDbName==0 ) continue; 8036 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 8037 if( sqlite3_stricmp(zDbName, "main")==0 ){ 8038 appendText(&s, "SELECT name FROM ", 0); 8039 }else{ 8040 appendText(&s, "SELECT ", 0); 8041 appendText(&s, zDbName, '\''); 8042 appendText(&s, "||'.'||name FROM ", 0); 8043 } 8044 appendText(&s, zDbName, '"'); 8045 appendText(&s, ".sqlite_master ", 0); 8046 if( c=='t' ){ 8047 appendText(&s," WHERE type IN ('table','view')" 8048 " AND name NOT LIKE 'sqlite_%'" 8049 " AND name LIKE ?1", 0); 8050 }else{ 8051 appendText(&s," WHERE type='index'" 8052 " AND tbl_name LIKE ?1", 0); 8053 } 8054 } 8055 rc = sqlite3_finalize(pStmt); 8056 appendText(&s, " ORDER BY 1", 0); 8057 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 8058 freeText(&s); 8059 if( rc ) return shellDatabaseError(p->db); 8060 8061 /* Run the SQL statement prepared by the above block. Store the results 8062 ** as an array of nul-terminated strings in azResult[]. */ 8063 nRow = nAlloc = 0; 8064 azResult = 0; 8065 if( nArg>1 ){ 8066 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 8067 }else{ 8068 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 8069 } 8070 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 8071 if( nRow>=nAlloc ){ 8072 char **azNew; 8073 int n2 = nAlloc*2 + 10; 8074 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 8075 if( azNew==0 ) shell_out_of_memory(); 8076 nAlloc = n2; 8077 azResult = azNew; 8078 } 8079 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 8080 if( 0==azResult[nRow] ) shell_out_of_memory(); 8081 nRow++; 8082 } 8083 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 8084 rc = shellDatabaseError(p->db); 8085 } 8086 8087 /* Pretty-print the contents of array azResult[] to the output */ 8088 if( rc==0 && nRow>0 ){ 8089 int len, maxlen = 0; 8090 int i, j; 8091 int nPrintCol, nPrintRow; 8092 for(i=0; i<nRow; i++){ 8093 len = strlen30(azResult[i]); 8094 if( len>maxlen ) maxlen = len; 8095 } 8096 nPrintCol = 80/(maxlen+2); 8097 if( nPrintCol<1 ) nPrintCol = 1; 8098 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 8099 for(i=0; i<nPrintRow; i++){ 8100 for(j=i; j<nRow; j+=nPrintRow){ 8101 char *zSp = j<nPrintRow ? "" : " "; 8102 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 8103 azResult[j] ? azResult[j]:""); 8104 } 8105 raw_printf(p->out, "\n"); 8106 } 8107 } 8108 8109 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 8110 sqlite3_free(azResult); 8111 }else 8112 8113 /* Begin redirecting output to the file "testcase-out.txt" */ 8114 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){ 8115 output_reset(p); 8116 p->out = output_file_open("testcase-out.txt", 0); 8117 if( p->out==0 ){ 8118 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 8119 } 8120 if( nArg>=2 ){ 8121 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 8122 }else{ 8123 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 8124 } 8125 }else 8126 8127#ifndef SQLITE_UNTESTABLE 8128 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){ 8129 static const struct { 8130 const char *zCtrlName; /* Name of a test-control option */ 8131 int ctrlCode; /* Integer code for that option */ 8132 const char *zUsage; /* Usage notes */ 8133 } aCtrl[] = { 8134 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" }, 8135 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" }, 8136 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/ 8137 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/ 8138 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" }, 8139 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */ 8140 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"}, 8141 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN" }, 8142 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" }, 8143 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" }, 8144 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" }, 8145#ifdef YYCOVERAGE 8146 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" }, 8147#endif 8148 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " }, 8149 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" }, 8150 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" }, 8151 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" }, 8152 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" }, 8153 }; 8154 int testctrl = -1; 8155 int iCtrl = -1; 8156 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 8157 int isOk = 0; 8158 int i, n2; 8159 const char *zCmd = 0; 8160 8161 open_db(p, 0); 8162 zCmd = nArg>=2 ? azArg[1] : "help"; 8163 8164 /* The argument can optionally begin with "-" or "--" */ 8165 if( zCmd[0]=='-' && zCmd[1] ){ 8166 zCmd++; 8167 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 8168 } 8169 8170 /* --help lists all test-controls */ 8171 if( strcmp(zCmd,"help")==0 ){ 8172 utf8_printf(p->out, "Available test-controls:\n"); 8173 for(i=0; i<ArraySize(aCtrl); i++){ 8174 utf8_printf(p->out, " .testctrl %s %s\n", 8175 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 8176 } 8177 rc = 1; 8178 goto meta_command_exit; 8179 } 8180 8181 /* convert testctrl text option to value. allow any unique prefix 8182 ** of the option name, or a numerical value. */ 8183 n2 = strlen30(zCmd); 8184 for(i=0; i<ArraySize(aCtrl); i++){ 8185 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 8186 if( testctrl<0 ){ 8187 testctrl = aCtrl[i].ctrlCode; 8188 iCtrl = i; 8189 }else{ 8190 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 8191 "Use \".testctrl --help\" for help\n", zCmd); 8192 rc = 1; 8193 goto meta_command_exit; 8194 } 8195 } 8196 } 8197 if( testctrl<0 ){ 8198 utf8_printf(stderr,"Error: unknown test-control: %s\n" 8199 "Use \".testctrl --help\" for help\n", zCmd); 8200 }else{ 8201 switch(testctrl){ 8202 8203 /* sqlite3_test_control(int, db, int) */ 8204 case SQLITE_TESTCTRL_OPTIMIZATIONS: 8205 case SQLITE_TESTCTRL_RESERVE: 8206 if( nArg==3 ){ 8207 int opt = (int)strtol(azArg[2], 0, 0); 8208 rc2 = sqlite3_test_control(testctrl, p->db, opt); 8209 isOk = 3; 8210 } 8211 break; 8212 8213 /* sqlite3_test_control(int) */ 8214 case SQLITE_TESTCTRL_PRNG_SAVE: 8215 case SQLITE_TESTCTRL_PRNG_RESTORE: 8216 case SQLITE_TESTCTRL_PRNG_RESET: 8217 case SQLITE_TESTCTRL_BYTEORDER: 8218 if( nArg==2 ){ 8219 rc2 = sqlite3_test_control(testctrl); 8220 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 8221 } 8222 break; 8223 8224 /* sqlite3_test_control(int, uint) */ 8225 case SQLITE_TESTCTRL_PENDING_BYTE: 8226 if( nArg==3 ){ 8227 unsigned int opt = (unsigned int)integerValue(azArg[2]); 8228 rc2 = sqlite3_test_control(testctrl, opt); 8229 isOk = 3; 8230 } 8231 break; 8232 8233 /* sqlite3_test_control(int, int) */ 8234 case SQLITE_TESTCTRL_ASSERT: 8235 case SQLITE_TESTCTRL_ALWAYS: 8236 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 8237 if( nArg==3 ){ 8238 int opt = booleanValue(azArg[2]); 8239 rc2 = sqlite3_test_control(testctrl, opt); 8240 isOk = 1; 8241 } 8242 break; 8243 8244 /* sqlite3_test_control(int, int) */ 8245 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 8246 case SQLITE_TESTCTRL_NEVER_CORRUPT: 8247 if( nArg==3 ){ 8248 int opt = booleanValue(azArg[2]); 8249 rc2 = sqlite3_test_control(testctrl, opt); 8250 isOk = 3; 8251 } 8252 break; 8253 8254 case SQLITE_TESTCTRL_IMPOSTER: 8255 if( nArg==5 ){ 8256 rc2 = sqlite3_test_control(testctrl, p->db, 8257 azArg[2], 8258 integerValue(azArg[3]), 8259 integerValue(azArg[4])); 8260 isOk = 3; 8261 } 8262 break; 8263 8264#ifdef YYCOVERAGE 8265 case SQLITE_TESTCTRL_PARSER_COVERAGE: 8266 if( nArg==2 ){ 8267 sqlite3_test_control(testctrl, p->out); 8268 isOk = 3; 8269 } 8270#endif 8271 } 8272 } 8273 if( isOk==0 && iCtrl>=0 ){ 8274 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage); 8275 rc = 1; 8276 }else if( isOk==1 ){ 8277 raw_printf(p->out, "%d\n", rc2); 8278 }else if( isOk==2 ){ 8279 raw_printf(p->out, "0x%08x\n", rc2); 8280 } 8281 }else 8282#endif /* !defined(SQLITE_UNTESTABLE) */ 8283 8284 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ 8285 open_db(p, 0); 8286 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 8287 }else 8288 8289 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ 8290 if( nArg==2 ){ 8291 enableTimer = booleanValue(azArg[1]); 8292 if( enableTimer && !HAS_TIMER ){ 8293 raw_printf(stderr, "Error: timer not available on this system.\n"); 8294 enableTimer = 0; 8295 } 8296 }else{ 8297 raw_printf(stderr, "Usage: .timer on|off\n"); 8298 rc = 1; 8299 } 8300 }else 8301 8302#ifndef SQLITE_OMIT_TRACE 8303 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ 8304 int mType = 0; 8305 int jj; 8306 open_db(p, 0); 8307 for(jj=1; jj<nArg; jj++){ 8308 const char *z = azArg[jj]; 8309 if( z[0]=='-' ){ 8310 if( optionMatch(z, "expanded") ){ 8311 p->eTraceType = SHELL_TRACE_EXPANDED; 8312 } 8313#ifdef SQLITE_ENABLE_NORMALIZE 8314 else if( optionMatch(z, "normalized") ){ 8315 p->eTraceType = SHELL_TRACE_NORMALIZED; 8316 } 8317#endif 8318 else if( optionMatch(z, "plain") ){ 8319 p->eTraceType = SHELL_TRACE_PLAIN; 8320 } 8321 else if( optionMatch(z, "profile") ){ 8322 mType |= SQLITE_TRACE_PROFILE; 8323 } 8324 else if( optionMatch(z, "row") ){ 8325 mType |= SQLITE_TRACE_ROW; 8326 } 8327 else if( optionMatch(z, "stmt") ){ 8328 mType |= SQLITE_TRACE_STMT; 8329 } 8330 else if( optionMatch(z, "close") ){ 8331 mType |= SQLITE_TRACE_CLOSE; 8332 } 8333 else { 8334 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 8335 rc = 1; 8336 goto meta_command_exit; 8337 } 8338 }else{ 8339 output_file_close(p->traceOut); 8340 p->traceOut = output_file_open(azArg[1], 0); 8341 } 8342 } 8343 if( p->traceOut==0 ){ 8344 sqlite3_trace_v2(p->db, 0, 0, 0); 8345 }else{ 8346 if( mType==0 ) mType = SQLITE_TRACE_STMT; 8347 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 8348 } 8349 }else 8350#endif /* !defined(SQLITE_OMIT_TRACE) */ 8351 8352#if SQLITE_USER_AUTHENTICATION 8353 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ 8354 if( nArg<2 ){ 8355 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 8356 rc = 1; 8357 goto meta_command_exit; 8358 } 8359 open_db(p, 0); 8360 if( strcmp(azArg[1],"login")==0 ){ 8361 if( nArg!=4 ){ 8362 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 8363 rc = 1; 8364 goto meta_command_exit; 8365 } 8366 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3])); 8367 if( rc ){ 8368 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 8369 rc = 1; 8370 } 8371 }else if( strcmp(azArg[1],"add")==0 ){ 8372 if( nArg!=5 ){ 8373 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 8374 rc = 1; 8375 goto meta_command_exit; 8376 } 8377 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 8378 booleanValue(azArg[4])); 8379 if( rc ){ 8380 raw_printf(stderr, "User-Add failed: %d\n", rc); 8381 rc = 1; 8382 } 8383 }else if( strcmp(azArg[1],"edit")==0 ){ 8384 if( nArg!=5 ){ 8385 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 8386 rc = 1; 8387 goto meta_command_exit; 8388 } 8389 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 8390 booleanValue(azArg[4])); 8391 if( rc ){ 8392 raw_printf(stderr, "User-Edit failed: %d\n", rc); 8393 rc = 1; 8394 } 8395 }else if( strcmp(azArg[1],"delete")==0 ){ 8396 if( nArg!=3 ){ 8397 raw_printf(stderr, "Usage: .user delete USER\n"); 8398 rc = 1; 8399 goto meta_command_exit; 8400 } 8401 rc = sqlite3_user_delete(p->db, azArg[2]); 8402 if( rc ){ 8403 raw_printf(stderr, "User-Delete failed: %d\n", rc); 8404 rc = 1; 8405 } 8406 }else{ 8407 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 8408 rc = 1; 8409 goto meta_command_exit; 8410 } 8411 }else 8412#endif /* SQLITE_USER_AUTHENTICATION */ 8413 8414 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ 8415 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 8416 sqlite3_libversion(), sqlite3_sourceid()); 8417#if SQLITE_HAVE_ZLIB 8418 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 8419#endif 8420#define CTIMEOPT_VAL_(opt) #opt 8421#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 8422#if defined(__clang__) && defined(__clang_major__) 8423 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 8424 CTIMEOPT_VAL(__clang_minor__) "." 8425 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 8426#elif defined(_MSC_VER) 8427 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 8428#elif defined(__GNUC__) && defined(__VERSION__) 8429 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 8430#endif 8431 }else 8432 8433 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ 8434 const char *zDbName = nArg==2 ? azArg[1] : "main"; 8435 sqlite3_vfs *pVfs = 0; 8436 if( p->db ){ 8437 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 8438 if( pVfs ){ 8439 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 8440 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 8441 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 8442 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 8443 } 8444 } 8445 }else 8446 8447 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ 8448 sqlite3_vfs *pVfs; 8449 sqlite3_vfs *pCurrent = 0; 8450 if( p->db ){ 8451 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 8452 } 8453 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 8454 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 8455 pVfs==pCurrent ? " <--- CURRENT" : ""); 8456 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 8457 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 8458 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 8459 if( pVfs->pNext ){ 8460 raw_printf(p->out, "-----------------------------------\n"); 8461 } 8462 } 8463 }else 8464 8465 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ 8466 const char *zDbName = nArg==2 ? azArg[1] : "main"; 8467 char *zVfsName = 0; 8468 if( p->db ){ 8469 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 8470 if( zVfsName ){ 8471 utf8_printf(p->out, "%s\n", zVfsName); 8472 sqlite3_free(zVfsName); 8473 } 8474 } 8475 }else 8476 8477#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) 8478 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ 8479 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; 8480 }else 8481#endif 8482 8483 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ 8484 int j; 8485 assert( nArg<=ArraySize(azArg) ); 8486 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ 8487 p->colWidth[j-1] = (int)integerValue(azArg[j]); 8488 } 8489 }else 8490 8491 { 8492 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 8493 " \"%s\". Enter \".help\" for help\n", azArg[0]); 8494 rc = 1; 8495 } 8496 8497meta_command_exit: 8498 if( p->outCount ){ 8499 p->outCount--; 8500 if( p->outCount==0 ) output_reset(p); 8501 } 8502 return rc; 8503} 8504 8505/* 8506** Return TRUE if a semicolon occurs anywhere in the first N characters 8507** of string z[]. 8508*/ 8509static int line_contains_semicolon(const char *z, int N){ 8510 int i; 8511 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } 8512 return 0; 8513} 8514 8515/* 8516** Test to see if a line consists entirely of whitespace. 8517*/ 8518static int _all_whitespace(const char *z){ 8519 for(; *z; z++){ 8520 if( IsSpace(z[0]) ) continue; 8521 if( *z=='/' && z[1]=='*' ){ 8522 z += 2; 8523 while( *z && (*z!='*' || z[1]!='/') ){ z++; } 8524 if( *z==0 ) return 0; 8525 z++; 8526 continue; 8527 } 8528 if( *z=='-' && z[1]=='-' ){ 8529 z += 2; 8530 while( *z && *z!='\n' ){ z++; } 8531 if( *z==0 ) return 1; 8532 continue; 8533 } 8534 return 0; 8535 } 8536 return 1; 8537} 8538 8539/* 8540** Return TRUE if the line typed in is an SQL command terminator other 8541** than a semi-colon. The SQL Server style "go" command is understood 8542** as is the Oracle "/". 8543*/ 8544static int line_is_command_terminator(const char *zLine){ 8545 while( IsSpace(zLine[0]) ){ zLine++; }; 8546 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ 8547 return 1; /* Oracle */ 8548 } 8549 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' 8550 && _all_whitespace(&zLine[2]) ){ 8551 return 1; /* SQL Server */ 8552 } 8553 return 0; 8554} 8555 8556/* 8557** We need a default sqlite3_complete() implementation to use in case 8558** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 8559** any arbitrary text is a complete SQL statement. This is not very 8560** user-friendly, but it does seem to work. 8561*/ 8562#ifdef SQLITE_OMIT_COMPLETE 8563#define sqlite3_complete(x) 1 8564#endif 8565 8566/* 8567** Return true if zSql is a complete SQL statement. Return false if it 8568** ends in the middle of a string literal or C-style comment. 8569*/ 8570static int line_is_complete(char *zSql, int nSql){ 8571 int rc; 8572 if( zSql==0 ) return 1; 8573 zSql[nSql] = ';'; 8574 zSql[nSql+1] = 0; 8575 rc = sqlite3_complete(zSql); 8576 zSql[nSql] = 0; 8577 return rc; 8578} 8579 8580/* 8581** Run a single line of SQL. Return the number of errors. 8582*/ 8583static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 8584 int rc; 8585 char *zErrMsg = 0; 8586 8587 open_db(p, 0); 8588 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 8589 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 8590 BEGIN_TIMER; 8591 rc = shell_exec(p, zSql, &zErrMsg); 8592 END_TIMER; 8593 if( rc || zErrMsg ){ 8594 char zPrefix[100]; 8595 if( in!=0 || !stdin_is_interactive ){ 8596 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 8597 "Error: near line %d:", startline); 8598 }else{ 8599 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); 8600 } 8601 if( zErrMsg!=0 ){ 8602 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); 8603 sqlite3_free(zErrMsg); 8604 zErrMsg = 0; 8605 }else{ 8606 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); 8607 } 8608 return 1; 8609 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 8610 raw_printf(p->out, "changes: %3d total_changes: %d\n", 8611 sqlite3_changes(p->db), sqlite3_total_changes(p->db)); 8612 } 8613 return 0; 8614} 8615 8616 8617/* 8618** Read input from *in and process it. If *in==0 then input 8619** is interactive - the user is typing it it. Otherwise, input 8620** is coming from a file or device. A prompt is issued and history 8621** is saved only if input is interactive. An interrupt signal will 8622** cause this routine to exit immediately, unless input is interactive. 8623** 8624** Return the number of errors. 8625*/ 8626static int process_input(ShellState *p){ 8627 char *zLine = 0; /* A single input line */ 8628 char *zSql = 0; /* Accumulated SQL text */ 8629 int nLine; /* Length of current line */ 8630 int nSql = 0; /* Bytes of zSql[] used */ 8631 int nAlloc = 0; /* Allocated zSql[] space */ 8632 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ 8633 int rc; /* Error code */ 8634 int errCnt = 0; /* Number of errors seen */ 8635 int startline = 0; /* Line number for start of current input */ 8636 8637 p->lineno = 0; 8638 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 8639 fflush(p->out); 8640 zLine = one_input_line(p->in, zLine, nSql>0); 8641 if( zLine==0 ){ 8642 /* End of input */ 8643 if( p->in==0 && stdin_is_interactive ) printf("\n"); 8644 break; 8645 } 8646 if( seenInterrupt ){ 8647 if( p->in!=0 ) break; 8648 seenInterrupt = 0; 8649 } 8650 p->lineno++; 8651 if( nSql==0 && _all_whitespace(zLine) ){ 8652 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 8653 continue; 8654 } 8655 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 8656 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine); 8657 if( zLine[0]=='.' ){ 8658 rc = do_meta_command(zLine, p); 8659 if( rc==2 ){ /* exit requested */ 8660 break; 8661 }else if( rc ){ 8662 errCnt++; 8663 } 8664 } 8665 continue; 8666 } 8667 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ 8668 memcpy(zLine,";",2); 8669 } 8670 nLine = strlen30(zLine); 8671 if( nSql+nLine+2>=nAlloc ){ 8672 nAlloc = nSql+nLine+100; 8673 zSql = realloc(zSql, nAlloc); 8674 if( zSql==0 ) shell_out_of_memory(); 8675 } 8676 nSqlPrior = nSql; 8677 if( nSql==0 ){ 8678 int i; 8679 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 8680 assert( nAlloc>0 && zSql!=0 ); 8681 memcpy(zSql, zLine+i, nLine+1-i); 8682 startline = p->lineno; 8683 nSql = nLine-i; 8684 }else{ 8685 zSql[nSql++] = '\n'; 8686 memcpy(zSql+nSql, zLine, nLine+1); 8687 nSql += nLine; 8688 } 8689 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) 8690 && sqlite3_complete(zSql) ){ 8691 errCnt += runOneSqlLine(p, zSql, p->in, startline); 8692 nSql = 0; 8693 if( p->outCount ){ 8694 output_reset(p); 8695 p->outCount = 0; 8696 }else{ 8697 clearTempFile(p); 8698 } 8699 }else if( nSql && _all_whitespace(zSql) ){ 8700 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql); 8701 nSql = 0; 8702 } 8703 } 8704 if( nSql && !_all_whitespace(zSql) ){ 8705 errCnt += runOneSqlLine(p, zSql, p->in, startline); 8706 } 8707 free(zSql); 8708 free(zLine); 8709 return errCnt>0; 8710} 8711 8712/* 8713** Return a pathname which is the user's home directory. A 8714** 0 return indicates an error of some kind. 8715*/ 8716static char *find_home_dir(int clearFlag){ 8717 static char *home_dir = NULL; 8718 if( clearFlag ){ 8719 free(home_dir); 8720 home_dir = 0; 8721 return 0; 8722 } 8723 if( home_dir ) return home_dir; 8724 8725#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 8726 && !defined(__RTP__) && !defined(_WRS_KERNEL) 8727 { 8728 struct passwd *pwent; 8729 uid_t uid = getuid(); 8730 if( (pwent=getpwuid(uid)) != NULL) { 8731 home_dir = pwent->pw_dir; 8732 } 8733 } 8734#endif 8735 8736#if defined(_WIN32_WCE) 8737 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 8738 */ 8739 home_dir = "/"; 8740#else 8741 8742#if defined(_WIN32) || defined(WIN32) 8743 if (!home_dir) { 8744 home_dir = getenv("USERPROFILE"); 8745 } 8746#endif 8747 8748 if (!home_dir) { 8749 home_dir = getenv("HOME"); 8750 } 8751 8752#if defined(_WIN32) || defined(WIN32) 8753 if (!home_dir) { 8754 char *zDrive, *zPath; 8755 int n; 8756 zDrive = getenv("HOMEDRIVE"); 8757 zPath = getenv("HOMEPATH"); 8758 if( zDrive && zPath ){ 8759 n = strlen30(zDrive) + strlen30(zPath) + 1; 8760 home_dir = malloc( n ); 8761 if( home_dir==0 ) return 0; 8762 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 8763 return home_dir; 8764 } 8765 home_dir = "c:\\"; 8766 } 8767#endif 8768 8769#endif /* !_WIN32_WCE */ 8770 8771 if( home_dir ){ 8772 int n = strlen30(home_dir) + 1; 8773 char *z = malloc( n ); 8774 if( z ) memcpy(z, home_dir, n); 8775 home_dir = z; 8776 } 8777 8778 return home_dir; 8779} 8780 8781/* 8782** Read input from the file given by sqliterc_override. Or if that 8783** parameter is NULL, take input from ~/.sqliterc 8784** 8785** Returns the number of errors. 8786*/ 8787static void process_sqliterc( 8788 ShellState *p, /* Configuration data */ 8789 const char *sqliterc_override /* Name of config file. NULL to use default */ 8790){ 8791 char *home_dir = NULL; 8792 const char *sqliterc = sqliterc_override; 8793 char *zBuf = 0; 8794 FILE *inSaved = p->in; 8795 int savedLineno = p->lineno; 8796 8797 if (sqliterc == NULL) { 8798 home_dir = find_home_dir(0); 8799 if( home_dir==0 ){ 8800 raw_printf(stderr, "-- warning: cannot find home directory;" 8801 " cannot read ~/.sqliterc\n"); 8802 return; 8803 } 8804 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 8805 sqliterc = zBuf; 8806 } 8807 p->in = fopen(sqliterc,"rb"); 8808 if( p->in ){ 8809 if( stdin_is_interactive ){ 8810 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 8811 } 8812 process_input(p); 8813 fclose(p->in); 8814 } 8815 p->in = inSaved; 8816 p->lineno = savedLineno; 8817 sqlite3_free(zBuf); 8818} 8819 8820/* 8821** Show available command line options 8822*/ 8823static const char zOptions[] = 8824#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 8825 " -A ARGS... run \".archive ARGS\" and exit\n" 8826#endif 8827 " -append append the database to the end of the file\n" 8828 " -ascii set output mode to 'ascii'\n" 8829 " -bail stop after hitting an error\n" 8830 " -batch force batch I/O\n" 8831 " -column set output mode to 'column'\n" 8832 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 8833 " -csv set output mode to 'csv'\n" 8834#if defined(SQLITE_ENABLE_DESERIALIZE) 8835 " -deserialize open the database using sqlite3_deserialize()\n" 8836#endif 8837 " -echo print commands before execution\n" 8838 " -init FILENAME read/process named file\n" 8839 " -[no]header turn headers on or off\n" 8840#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 8841 " -heap SIZE Size of heap for memsys3 or memsys5\n" 8842#endif 8843 " -help show this message\n" 8844 " -html set output mode to HTML\n" 8845 " -interactive force interactive I/O\n" 8846 " -line set output mode to 'line'\n" 8847 " -list set output mode to 'list'\n" 8848 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 8849#if defined(SQLITE_ENABLE_DESERIALIZE) 8850 " -maxsize N maximum size for a --deserialize database\n" 8851#endif 8852 " -memtrace trace all memory allocations and deallocations\n" 8853 " -mmap N default mmap size set to N\n" 8854#ifdef SQLITE_ENABLE_MULTIPLEX 8855 " -multiplex enable the multiplexor VFS\n" 8856#endif 8857 " -newline SEP set output row separator. Default: '\\n'\n" 8858 " -nullvalue TEXT set text string for NULL values. Default ''\n" 8859 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 8860 " -quote set output mode to 'quote'\n" 8861 " -readonly open the database read-only\n" 8862 " -separator SEP set output column separator. Default: '|'\n" 8863#ifdef SQLITE_ENABLE_SORTER_REFERENCES 8864 " -sorterref SIZE sorter references threshold size\n" 8865#endif 8866 " -stats print memory stats before each finalize\n" 8867 " -version show SQLite version\n" 8868 " -vfs NAME use NAME as the default VFS\n" 8869#ifdef SQLITE_ENABLE_VFSTRACE 8870 " -vfstrace enable tracing of all VFS calls\n" 8871#endif 8872#ifdef SQLITE_HAVE_ZLIB 8873 " -zip open the file as a ZIP Archive\n" 8874#endif 8875; 8876static void usage(int showDetail){ 8877 utf8_printf(stderr, 8878 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 8879 "FILENAME is the name of an SQLite database. A new database is created\n" 8880 "if the file does not previously exist.\n", Argv0); 8881 if( showDetail ){ 8882 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 8883 }else{ 8884 raw_printf(stderr, "Use the -help option for additional information\n"); 8885 } 8886 exit(1); 8887} 8888 8889/* 8890** Internal check: Verify that the SQLite is uninitialized. Print a 8891** error message if it is initialized. 8892*/ 8893static void verify_uninitialized(void){ 8894 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 8895 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 8896 " initialization.\n"); 8897 } 8898} 8899 8900/* 8901** Initialize the state information in data 8902*/ 8903static void main_init(ShellState *data) { 8904 memset(data, 0, sizeof(*data)); 8905 data->normalMode = data->cMode = data->mode = MODE_List; 8906 data->autoExplain = 1; 8907 memcpy(data->colSeparator,SEP_Column, 2); 8908 memcpy(data->rowSeparator,SEP_Row, 2); 8909 data->showHeader = 0; 8910 data->shellFlgs = SHFLG_Lookaside; 8911 verify_uninitialized(); 8912 sqlite3_config(SQLITE_CONFIG_URI, 1); 8913 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 8914 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 8915 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 8916 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 8917} 8918 8919/* 8920** Output text to the console in a font that attracts extra attention. 8921*/ 8922#ifdef _WIN32 8923static void printBold(const char *zText){ 8924 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 8925 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 8926 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 8927 SetConsoleTextAttribute(out, 8928 FOREGROUND_RED|FOREGROUND_INTENSITY 8929 ); 8930 printf("%s", zText); 8931 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 8932} 8933#else 8934static void printBold(const char *zText){ 8935 printf("\033[1m%s\033[0m", zText); 8936} 8937#endif 8938 8939/* 8940** Get the argument to an --option. Throw an error and die if no argument 8941** is available. 8942*/ 8943static char *cmdline_option_value(int argc, char **argv, int i){ 8944 if( i==argc ){ 8945 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 8946 argv[0], argv[argc-1]); 8947 exit(1); 8948 } 8949 return argv[i]; 8950} 8951 8952#ifndef SQLITE_SHELL_IS_UTF8 8953# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) 8954# define SQLITE_SHELL_IS_UTF8 (0) 8955# else 8956# define SQLITE_SHELL_IS_UTF8 (1) 8957# endif 8958#endif 8959 8960#if SQLITE_SHELL_IS_UTF8 8961int SQLITE_CDECL main(int argc, char **argv){ 8962#else 8963int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 8964 char **argv; 8965#endif 8966 char *zErrMsg = 0; 8967 ShellState data; 8968 const char *zInitFile = 0; 8969 int i; 8970 int rc = 0; 8971 int warnInmemoryDb = 0; 8972 int readStdin = 1; 8973 int nCmd = 0; 8974 char **azCmd = 0; 8975 const char *zVfs = 0; /* Value of -vfs command-line option */ 8976#if !SQLITE_SHELL_IS_UTF8 8977 char **argvToFree = 0; 8978 int argcToFree = 0; 8979#endif 8980 8981 setBinaryMode(stdin, 0); 8982 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 8983 stdin_is_interactive = isatty(0); 8984 stdout_is_console = isatty(1); 8985 8986#if !defined(_WIN32_WCE) 8987 if( getenv("SQLITE_DEBUG_BREAK") ){ 8988 if( isatty(0) && isatty(2) ){ 8989 fprintf(stderr, 8990 "attach debugger to process %d and press any key to continue.\n", 8991 GETPID()); 8992 fgetc(stdin); 8993 }else{ 8994#if defined(_WIN32) || defined(WIN32) 8995 DebugBreak(); 8996#elif defined(SIGTRAP) 8997 raise(SIGTRAP); 8998#endif 8999 } 9000 } 9001#endif 9002 9003#if USE_SYSTEM_SQLITE+0!=1 9004 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 9005 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 9006 sqlite3_sourceid(), SQLITE_SOURCE_ID); 9007 exit(1); 9008 } 9009#endif 9010 main_init(&data); 9011 9012 /* On Windows, we must translate command-line arguments into UTF-8. 9013 ** The SQLite memory allocator subsystem has to be enabled in order to 9014 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 9015 ** subsequent sqlite3_config() calls will work. So copy all results into 9016 ** memory that does not come from the SQLite memory allocator. 9017 */ 9018#if !SQLITE_SHELL_IS_UTF8 9019 sqlite3_initialize(); 9020 argvToFree = malloc(sizeof(argv[0])*argc*2); 9021 argcToFree = argc; 9022 argv = argvToFree + argc; 9023 if( argv==0 ) shell_out_of_memory(); 9024 for(i=0; i<argc; i++){ 9025 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 9026 int n; 9027 if( z==0 ) shell_out_of_memory(); 9028 n = (int)strlen(z); 9029 argv[i] = malloc( n+1 ); 9030 if( argv[i]==0 ) shell_out_of_memory(); 9031 memcpy(argv[i], z, n+1); 9032 argvToFree[i] = argv[i]; 9033 sqlite3_free(z); 9034 } 9035 sqlite3_shutdown(); 9036#endif 9037 9038 assert( argc>=1 && argv && argv[0] ); 9039 Argv0 = argv[0]; 9040 9041 /* Make sure we have a valid signal handler early, before anything 9042 ** else is done. 9043 */ 9044#ifdef SIGINT 9045 signal(SIGINT, interrupt_handler); 9046#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 9047 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 9048#endif 9049 9050#ifdef SQLITE_SHELL_DBNAME_PROC 9051 { 9052 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 9053 ** of a C-function that will provide the name of the database file. Use 9054 ** this compile-time option to embed this shell program in larger 9055 ** applications. */ 9056 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 9057 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); 9058 warnInmemoryDb = 0; 9059 } 9060#endif 9061 9062 /* Do an initial pass through the command-line argument to locate 9063 ** the name of the database file, the name of the initialization file, 9064 ** the size of the alternative malloc heap, 9065 ** and the first command to execute. 9066 */ 9067 verify_uninitialized(); 9068 for(i=1; i<argc; i++){ 9069 char *z; 9070 z = argv[i]; 9071 if( z[0]!='-' ){ 9072 if( data.zDbFilename==0 ){ 9073 data.zDbFilename = z; 9074 }else{ 9075 /* Excesss arguments are interpreted as SQL (or dot-commands) and 9076 ** mean that nothing is read from stdin */ 9077 readStdin = 0; 9078 nCmd++; 9079 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 9080 if( azCmd==0 ) shell_out_of_memory(); 9081 azCmd[nCmd-1] = z; 9082 } 9083 } 9084 if( z[1]=='-' ) z++; 9085 if( strcmp(z,"-separator")==0 9086 || strcmp(z,"-nullvalue")==0 9087 || strcmp(z,"-newline")==0 9088 || strcmp(z,"-cmd")==0 9089 ){ 9090 (void)cmdline_option_value(argc, argv, ++i); 9091 }else if( strcmp(z,"-init")==0 ){ 9092 zInitFile = cmdline_option_value(argc, argv, ++i); 9093 }else if( strcmp(z,"-batch")==0 ){ 9094 /* Need to check for batch mode here to so we can avoid printing 9095 ** informational messages (like from process_sqliterc) before 9096 ** we do the actual processing of arguments later in a second pass. 9097 */ 9098 stdin_is_interactive = 0; 9099 }else if( strcmp(z,"-heap")==0 ){ 9100#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 9101 const char *zSize; 9102 sqlite3_int64 szHeap; 9103 9104 zSize = cmdline_option_value(argc, argv, ++i); 9105 szHeap = integerValue(zSize); 9106 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 9107 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 9108#else 9109 (void)cmdline_option_value(argc, argv, ++i); 9110#endif 9111 }else if( strcmp(z,"-pagecache")==0 ){ 9112 int n, sz; 9113 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9114 if( sz>70000 ) sz = 70000; 9115 if( sz<0 ) sz = 0; 9116 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9117 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 9118 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 9119 data.shellFlgs |= SHFLG_Pagecache; 9120 }else if( strcmp(z,"-lookaside")==0 ){ 9121 int n, sz; 9122 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9123 if( sz<0 ) sz = 0; 9124 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 9125 if( n<0 ) n = 0; 9126 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 9127 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 9128#ifdef SQLITE_ENABLE_VFSTRACE 9129 }else if( strcmp(z,"-vfstrace")==0 ){ 9130 extern int vfstrace_register( 9131 const char *zTraceName, 9132 const char *zOldVfsName, 9133 int (*xOut)(const char*,void*), 9134 void *pOutArg, 9135 int makeDefault 9136 ); 9137 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 9138#endif 9139#ifdef SQLITE_ENABLE_MULTIPLEX 9140 }else if( strcmp(z,"-multiplex")==0 ){ 9141 extern int sqlite3_multiple_initialize(const char*,int); 9142 sqlite3_multiplex_initialize(0, 1); 9143#endif 9144 }else if( strcmp(z,"-mmap")==0 ){ 9145 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 9146 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 9147#ifdef SQLITE_ENABLE_SORTER_REFERENCES 9148 }else if( strcmp(z,"-sorterref")==0 ){ 9149 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 9150 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 9151#endif 9152 }else if( strcmp(z,"-vfs")==0 ){ 9153 zVfs = cmdline_option_value(argc, argv, ++i); 9154#ifdef SQLITE_HAVE_ZLIB 9155 }else if( strcmp(z,"-zip")==0 ){ 9156 data.openMode = SHELL_OPEN_ZIPFILE; 9157#endif 9158 }else if( strcmp(z,"-append")==0 ){ 9159 data.openMode = SHELL_OPEN_APPENDVFS; 9160#ifdef SQLITE_ENABLE_DESERIALIZE 9161 }else if( strcmp(z,"-deserialize")==0 ){ 9162 data.openMode = SHELL_OPEN_DESERIALIZE; 9163 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 9164 data.szMax = integerValue(argv[++i]); 9165#endif 9166 }else if( strcmp(z,"-readonly")==0 ){ 9167 data.openMode = SHELL_OPEN_READONLY; 9168#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 9169 }else if( strncmp(z, "-A",2)==0 ){ 9170 /* All remaining command-line arguments are passed to the ".archive" 9171 ** command, so ignore them */ 9172 break; 9173#endif 9174 }else if( strcmp(z, "-memtrace")==0 ){ 9175 sqlite3MemTraceActivate(stderr); 9176 } 9177 } 9178 verify_uninitialized(); 9179 9180 9181#ifdef SQLITE_SHELL_INIT_PROC 9182 { 9183 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 9184 ** of a C-function that will perform initialization actions on SQLite that 9185 ** occur just before or after sqlite3_initialize(). Use this compile-time 9186 ** option to embed this shell program in larger applications. */ 9187 extern void SQLITE_SHELL_INIT_PROC(void); 9188 SQLITE_SHELL_INIT_PROC(); 9189 } 9190#else 9191 /* All the sqlite3_config() calls have now been made. So it is safe 9192 ** to call sqlite3_initialize() and process any command line -vfs option. */ 9193 sqlite3_initialize(); 9194#endif 9195 9196 if( zVfs ){ 9197 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 9198 if( pVfs ){ 9199 sqlite3_vfs_register(pVfs, 1); 9200 }else{ 9201 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 9202 exit(1); 9203 } 9204 } 9205 9206 if( data.zDbFilename==0 ){ 9207#ifndef SQLITE_OMIT_MEMORYDB 9208 data.zDbFilename = ":memory:"; 9209 warnInmemoryDb = argc==1; 9210#else 9211 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 9212 return 1; 9213#endif 9214 } 9215 data.out = stdout; 9216 sqlite3_appendvfs_init(0,0,0); 9217 9218 /* Go ahead and open the database file if it already exists. If the 9219 ** file does not exist, delay opening it. This prevents empty database 9220 ** files from being created if a user mistypes the database name argument 9221 ** to the sqlite command-line tool. 9222 */ 9223 if( access(data.zDbFilename, 0)==0 ){ 9224 open_db(&data, 0); 9225 } 9226 9227 /* Process the initialization file if there is one. If no -init option 9228 ** is given on the command line, look for a file named ~/.sqliterc and 9229 ** try to process it. 9230 */ 9231 process_sqliterc(&data,zInitFile); 9232 9233 /* Make a second pass through the command-line argument and set 9234 ** options. This second pass is delayed until after the initialization 9235 ** file is processed so that the command-line arguments will override 9236 ** settings in the initialization file. 9237 */ 9238 for(i=1; i<argc; i++){ 9239 char *z = argv[i]; 9240 if( z[0]!='-' ) continue; 9241 if( z[1]=='-' ){ z++; } 9242 if( strcmp(z,"-init")==0 ){ 9243 i++; 9244 }else if( strcmp(z,"-html")==0 ){ 9245 data.mode = MODE_Html; 9246 }else if( strcmp(z,"-list")==0 ){ 9247 data.mode = MODE_List; 9248 }else if( strcmp(z,"-quote")==0 ){ 9249 data.mode = MODE_Quote; 9250 }else if( strcmp(z,"-line")==0 ){ 9251 data.mode = MODE_Line; 9252 }else if( strcmp(z,"-column")==0 ){ 9253 data.mode = MODE_Column; 9254 }else if( strcmp(z,"-csv")==0 ){ 9255 data.mode = MODE_Csv; 9256 memcpy(data.colSeparator,",",2); 9257#ifdef SQLITE_HAVE_ZLIB 9258 }else if( strcmp(z,"-zip")==0 ){ 9259 data.openMode = SHELL_OPEN_ZIPFILE; 9260#endif 9261 }else if( strcmp(z,"-append")==0 ){ 9262 data.openMode = SHELL_OPEN_APPENDVFS; 9263#ifdef SQLITE_ENABLE_DESERIALIZE 9264 }else if( strcmp(z,"-deserialize")==0 ){ 9265 data.openMode = SHELL_OPEN_DESERIALIZE; 9266 }else if( strcmp(z,"-maxsize")==0 && i+1<argc ){ 9267 data.szMax = integerValue(argv[++i]); 9268#endif 9269 }else if( strcmp(z,"-readonly")==0 ){ 9270 data.openMode = SHELL_OPEN_READONLY; 9271 }else if( strcmp(z,"-ascii")==0 ){ 9272 data.mode = MODE_Ascii; 9273 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 9274 SEP_Unit); 9275 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 9276 SEP_Record); 9277 }else if( strcmp(z,"-separator")==0 ){ 9278 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 9279 "%s",cmdline_option_value(argc,argv,++i)); 9280 }else if( strcmp(z,"-newline")==0 ){ 9281 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 9282 "%s",cmdline_option_value(argc,argv,++i)); 9283 }else if( strcmp(z,"-nullvalue")==0 ){ 9284 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 9285 "%s",cmdline_option_value(argc,argv,++i)); 9286 }else if( strcmp(z,"-header")==0 ){ 9287 data.showHeader = 1; 9288 }else if( strcmp(z,"-noheader")==0 ){ 9289 data.showHeader = 0; 9290 }else if( strcmp(z,"-echo")==0 ){ 9291 ShellSetFlag(&data, SHFLG_Echo); 9292 }else if( strcmp(z,"-eqp")==0 ){ 9293 data.autoEQP = AUTOEQP_on; 9294 }else if( strcmp(z,"-eqpfull")==0 ){ 9295 data.autoEQP = AUTOEQP_full; 9296 }else if( strcmp(z,"-stats")==0 ){ 9297 data.statsOn = 1; 9298 }else if( strcmp(z,"-scanstats")==0 ){ 9299 data.scanstatsOn = 1; 9300 }else if( strcmp(z,"-backslash")==0 ){ 9301 /* Undocumented command-line option: -backslash 9302 ** Causes C-style backslash escapes to be evaluated in SQL statements 9303 ** prior to sending the SQL into SQLite. Useful for injecting 9304 ** crazy bytes in the middle of SQL statements for testing and debugging. 9305 */ 9306 ShellSetFlag(&data, SHFLG_Backslash); 9307 }else if( strcmp(z,"-bail")==0 ){ 9308 bail_on_error = 1; 9309 }else if( strcmp(z,"-version")==0 ){ 9310 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 9311 return 0; 9312 }else if( strcmp(z,"-interactive")==0 ){ 9313 stdin_is_interactive = 1; 9314 }else if( strcmp(z,"-batch")==0 ){ 9315 stdin_is_interactive = 0; 9316 }else if( strcmp(z,"-heap")==0 ){ 9317 i++; 9318 }else if( strcmp(z,"-pagecache")==0 ){ 9319 i+=2; 9320 }else if( strcmp(z,"-lookaside")==0 ){ 9321 i+=2; 9322 }else if( strcmp(z,"-mmap")==0 ){ 9323 i++; 9324 }else if( strcmp(z,"-memtrace")==0 ){ 9325 i++; 9326#ifdef SQLITE_ENABLE_SORTER_REFERENCES 9327 }else if( strcmp(z,"-sorterref")==0 ){ 9328 i++; 9329#endif 9330 }else if( strcmp(z,"-vfs")==0 ){ 9331 i++; 9332#ifdef SQLITE_ENABLE_VFSTRACE 9333 }else if( strcmp(z,"-vfstrace")==0 ){ 9334 i++; 9335#endif 9336#ifdef SQLITE_ENABLE_MULTIPLEX 9337 }else if( strcmp(z,"-multiplex")==0 ){ 9338 i++; 9339#endif 9340 }else if( strcmp(z,"-help")==0 ){ 9341 usage(1); 9342 }else if( strcmp(z,"-cmd")==0 ){ 9343 /* Run commands that follow -cmd first and separately from commands 9344 ** that simply appear on the command-line. This seems goofy. It would 9345 ** be better if all commands ran in the order that they appear. But 9346 ** we retain the goofy behavior for historical compatibility. */ 9347 if( i==argc-1 ) break; 9348 z = cmdline_option_value(argc,argv,++i); 9349 if( z[0]=='.' ){ 9350 rc = do_meta_command(z, &data); 9351 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 9352 }else{ 9353 open_db(&data, 0); 9354 rc = shell_exec(&data, z, &zErrMsg); 9355 if( zErrMsg!=0 ){ 9356 utf8_printf(stderr,"Error: %s\n", zErrMsg); 9357 if( bail_on_error ) return rc!=0 ? rc : 1; 9358 }else if( rc!=0 ){ 9359 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 9360 if( bail_on_error ) return rc; 9361 } 9362 } 9363#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 9364 }else if( strncmp(z, "-A", 2)==0 ){ 9365 if( nCmd>0 ){ 9366 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 9367 " with \"%s\"\n", z); 9368 return 1; 9369 } 9370 open_db(&data, OPEN_DB_ZIPFILE); 9371 if( z[2] ){ 9372 argv[i] = &z[2]; 9373 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 9374 }else{ 9375 arDotCommand(&data, 1, argv+i, argc-i); 9376 } 9377 readStdin = 0; 9378 break; 9379#endif 9380 }else{ 9381 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 9382 raw_printf(stderr,"Use -help for a list of options.\n"); 9383 return 1; 9384 } 9385 data.cMode = data.mode; 9386 } 9387 9388 if( !readStdin ){ 9389 /* Run all arguments that do not begin with '-' as if they were separate 9390 ** command-line inputs, except for the argToSkip argument which contains 9391 ** the database filename. 9392 */ 9393 for(i=0; i<nCmd; i++){ 9394 if( azCmd[i][0]=='.' ){ 9395 rc = do_meta_command(azCmd[i], &data); 9396 if( rc ) return rc==2 ? 0 : rc; 9397 }else{ 9398 open_db(&data, 0); 9399 rc = shell_exec(&data, azCmd[i], &zErrMsg); 9400 if( zErrMsg!=0 ){ 9401 utf8_printf(stderr,"Error: %s\n", zErrMsg); 9402 return rc!=0 ? rc : 1; 9403 }else if( rc!=0 ){ 9404 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 9405 return rc; 9406 } 9407 } 9408 } 9409 free(azCmd); 9410 }else{ 9411 /* Run commands received from standard input 9412 */ 9413 if( stdin_is_interactive ){ 9414 char *zHome; 9415 char *zHistory; 9416 int nHistory; 9417 printf( 9418 "SQLite version %s %.19s\n" /*extra-version-info*/ 9419 "Enter \".help\" for usage hints.\n", 9420 sqlite3_libversion(), sqlite3_sourceid() 9421 ); 9422 if( warnInmemoryDb ){ 9423 printf("Connected to a "); 9424 printBold("transient in-memory database"); 9425 printf(".\nUse \".open FILENAME\" to reopen on a " 9426 "persistent database.\n"); 9427 } 9428 zHistory = getenv("SQLITE_HISTORY"); 9429 if( zHistory ){ 9430 zHistory = strdup(zHistory); 9431 }else if( (zHome = find_home_dir(0))!=0 ){ 9432 nHistory = strlen30(zHome) + 20; 9433 if( (zHistory = malloc(nHistory))!=0 ){ 9434 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 9435 } 9436 } 9437 if( zHistory ){ shell_read_history(zHistory); } 9438#if HAVE_READLINE || HAVE_EDITLINE 9439 rl_attempted_completion_function = readline_completion; 9440#elif HAVE_LINENOISE 9441 linenoiseSetCompletionCallback(linenoise_completion); 9442#endif 9443 data.in = 0; 9444 rc = process_input(&data); 9445 if( zHistory ){ 9446 shell_stifle_history(2000); 9447 shell_write_history(zHistory); 9448 free(zHistory); 9449 } 9450 }else{ 9451 data.in = stdin; 9452 rc = process_input(&data); 9453 } 9454 } 9455 set_table_name(&data, 0); 9456 if( data.db ){ 9457 session_close_all(&data); 9458 close_db(data.db); 9459 } 9460 sqlite3_free(data.zFreeOnClose); 9461 find_home_dir(1); 9462 output_reset(&data); 9463 data.doXdgOpen = 0; 9464 clearTempFile(&data); 9465#if !SQLITE_SHELL_IS_UTF8 9466 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 9467 free(argvToFree); 9468#endif 9469 /* Clear the global data structure so that valgrind will detect memory 9470 ** leaks */ 9471 memset(&data, 0, sizeof(data)); 9472 return rc; 9473} 9474