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