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