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