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