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** Optionally #include a user-defined header, whereby compilation options 22** may be set prior to where they take effect, but after platform setup. 23** If SQLITE_CUSTOM_INCLUDE=? is defined, its value names the #include 24** file. Note that this macro has a like effect on sqlite3.c compilation. 25*/ 26# define SHELL_STRINGIFY_(f) #f 27# define SHELL_STRINGIFY(f) SHELL_STRINGIFY_(f) 28#ifdef SQLITE_CUSTOM_INCLUDE 29# include SHELL_STRINGIFY(SQLITE_CUSTOM_INCLUDE) 30#endif 31 32/* 33** Determine if we are dealing with WinRT, which provides only a subset of 34** the full Win32 API. 35*/ 36#if !defined(SQLITE_OS_WINRT) 37# define SQLITE_OS_WINRT 0 38#endif 39 40/* 41** If SQLITE_SHELL_FIDDLE is defined then the shell is modified 42** somewhat for use as a WASM module in a web browser. This flag 43** should only be used when building the "fiddle" web application, as 44** the browser-mode build has much different user input requirements 45** and this build mode rewires the user input subsystem to account for 46** that. 47*/ 48 49/* 50** Warning pragmas copied from msvc.h in the core. 51*/ 52#if defined(_MSC_VER) 53#pragma warning(disable : 4054) 54#pragma warning(disable : 4055) 55#pragma warning(disable : 4100) 56#pragma warning(disable : 4127) 57#pragma warning(disable : 4130) 58#pragma warning(disable : 4152) 59#pragma warning(disable : 4189) 60#pragma warning(disable : 4206) 61#pragma warning(disable : 4210) 62#pragma warning(disable : 4232) 63#pragma warning(disable : 4244) 64#pragma warning(disable : 4305) 65#pragma warning(disable : 4306) 66#pragma warning(disable : 4702) 67#pragma warning(disable : 4706) 68#endif /* defined(_MSC_VER) */ 69 70/* 71** No support for loadable extensions in VxWorks. 72*/ 73#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION 74# define SQLITE_OMIT_LOAD_EXTENSION 1 75#endif 76 77/* 78** Enable large-file support for fopen() and friends on unix. 79*/ 80#ifndef SQLITE_DISABLE_LFS 81# define _LARGE_FILE 1 82# ifndef _FILE_OFFSET_BITS 83# define _FILE_OFFSET_BITS 64 84# endif 85# define _LARGEFILE_SOURCE 1 86#endif 87 88#if defined(SQLITE_SHELL_FIDDLE) && !defined(_POSIX_SOURCE) 89/* 90** emcc requires _POSIX_SOURCE (or one of several similar defines) 91** to expose strdup(). 92*/ 93# define _POSIX_SOURCE 94#endif 95 96#include <stdlib.h> 97#include <string.h> 98#include <stdio.h> 99#include <assert.h> 100#include "sqlite3.h" 101typedef sqlite3_int64 i64; 102typedef sqlite3_uint64 u64; 103typedef unsigned char u8; 104#if SQLITE_USER_AUTHENTICATION 105# include "sqlite3userauth.h" 106#endif 107#include <ctype.h> 108#include <stdarg.h> 109 110#if !defined(_WIN32) && !defined(WIN32) 111# include <signal.h> 112# if !defined(__RTP__) && !defined(_WRS_KERNEL) 113# include <pwd.h> 114# endif 115#endif 116#if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__) 117# include <unistd.h> 118# include <dirent.h> 119# define GETPID getpid 120# if defined(__MINGW32__) 121# define DIRENT dirent 122# ifndef S_ISLNK 123# define S_ISLNK(mode) (0) 124# endif 125# endif 126#else 127# define GETPID (int)GetCurrentProcessId 128#endif 129#include <sys/types.h> 130#include <sys/stat.h> 131 132#if HAVE_READLINE 133# include <readline/readline.h> 134# include <readline/history.h> 135#endif 136 137#if HAVE_EDITLINE 138# include <editline/readline.h> 139#endif 140 141#if HAVE_EDITLINE || HAVE_READLINE 142 143# define shell_add_history(X) add_history(X) 144# define shell_read_history(X) read_history(X) 145# define shell_write_history(X) write_history(X) 146# define shell_stifle_history(X) stifle_history(X) 147# define shell_readline(X) readline(X) 148 149#elif HAVE_LINENOISE 150 151# include "linenoise.h" 152# define shell_add_history(X) linenoiseHistoryAdd(X) 153# define shell_read_history(X) linenoiseHistoryLoad(X) 154# define shell_write_history(X) linenoiseHistorySave(X) 155# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) 156# define shell_readline(X) linenoise(X) 157 158#else 159 160# define shell_read_history(X) 161# define shell_write_history(X) 162# define shell_stifle_history(X) 163 164# define SHELL_USE_LOCAL_GETLINE 1 165#endif 166 167 168#if defined(_WIN32) || defined(WIN32) 169# if SQLITE_OS_WINRT 170# define SQLITE_OMIT_POPEN 1 171# else 172# include <io.h> 173# include <fcntl.h> 174# define isatty(h) _isatty(h) 175# ifndef access 176# define access(f,m) _access((f),(m)) 177# endif 178# ifndef unlink 179# define unlink _unlink 180# endif 181# ifndef strdup 182# define strdup _strdup 183# endif 184# undef popen 185# define popen _popen 186# undef pclose 187# define pclose _pclose 188# endif 189#else 190 /* Make sure isatty() has a prototype. */ 191 extern int isatty(int); 192 193# if !defined(__RTP__) && !defined(_WRS_KERNEL) 194 /* popen and pclose are not C89 functions and so are 195 ** sometimes omitted from the <stdio.h> header */ 196 extern FILE *popen(const char*,const char*); 197 extern int pclose(FILE*); 198# else 199# define SQLITE_OMIT_POPEN 1 200# endif 201#endif 202 203#if defined(_WIN32_WCE) 204/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() 205 * thus we always assume that we have a console. That can be 206 * overridden with the -batch command line option. 207 */ 208#define isatty(x) 1 209#endif 210 211/* ctype macros that work with signed characters */ 212#define IsSpace(X) isspace((unsigned char)X) 213#define IsDigit(X) isdigit((unsigned char)X) 214#define ToLower(X) (char)tolower((unsigned char)X) 215 216#if defined(_WIN32) || defined(WIN32) 217#if SQLITE_OS_WINRT 218#include <intrin.h> 219#endif 220#include <windows.h> 221 222/* string conversion routines only needed on Win32 */ 223extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); 224extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); 225extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); 226extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText); 227#endif 228 229/* On Windows, we normally run with output mode of TEXT so that \n characters 230** are automatically translated into \r\n. However, this behavior needs 231** to be disabled in some cases (ex: when generating CSV output and when 232** rendering quoted strings that contain \n characters). The following 233** routines take care of that. 234*/ 235#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT 236static void setBinaryMode(FILE *file, int isOutput){ 237 if( isOutput ) fflush(file); 238 _setmode(_fileno(file), _O_BINARY); 239} 240static void setTextMode(FILE *file, int isOutput){ 241 if( isOutput ) fflush(file); 242 _setmode(_fileno(file), _O_TEXT); 243} 244#else 245# define setBinaryMode(X,Y) 246# define setTextMode(X,Y) 247#endif 248 249/* True if the timer is enabled */ 250static int enableTimer = 0; 251 252/* A version of strcmp() that works with NULL values */ 253static int cli_strcmp(const char *a, const char *b){ 254 if( a==0 ) a = ""; 255 if( b==0 ) b = ""; 256 return strcmp(a,b); 257} 258static int cli_strncmp(const char *a, const char *b, size_t n){ 259 if( a==0 ) a = ""; 260 if( b==0 ) b = ""; 261 return strncmp(a,b,n); 262} 263 264/* Return the current wall-clock time */ 265static sqlite3_int64 timeOfDay(void){ 266 static sqlite3_vfs *clockVfs = 0; 267 sqlite3_int64 t; 268 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); 269 if( clockVfs==0 ) return 0; /* Never actually happens */ 270 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ 271 clockVfs->xCurrentTimeInt64(clockVfs, &t); 272 }else{ 273 double r; 274 clockVfs->xCurrentTime(clockVfs, &r); 275 t = (sqlite3_int64)(r*86400000.0); 276 } 277 return t; 278} 279 280#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) 281#include <sys/time.h> 282#include <sys/resource.h> 283 284/* VxWorks does not support getrusage() as far as we can determine */ 285#if defined(_WRS_KERNEL) || defined(__RTP__) 286struct rusage { 287 struct timeval ru_utime; /* user CPU time used */ 288 struct timeval ru_stime; /* system CPU time used */ 289}; 290#define getrusage(A,B) memset(B,0,sizeof(*B)) 291#endif 292 293/* Saved resource information for the beginning of an operation */ 294static struct rusage sBegin; /* CPU time at start */ 295static sqlite3_int64 iBegin; /* Wall-clock time at start */ 296 297/* 298** Begin timing an operation 299*/ 300static void beginTimer(void){ 301 if( enableTimer ){ 302 getrusage(RUSAGE_SELF, &sBegin); 303 iBegin = timeOfDay(); 304 } 305} 306 307/* Return the difference of two time_structs in seconds */ 308static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ 309 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + 310 (double)(pEnd->tv_sec - pStart->tv_sec); 311} 312 313/* 314** Print the timing results. 315*/ 316static void endTimer(void){ 317 if( enableTimer ){ 318 sqlite3_int64 iEnd = timeOfDay(); 319 struct rusage sEnd; 320 getrusage(RUSAGE_SELF, &sEnd); 321 printf("Run Time: real %.3f user %f sys %f\n", 322 (iEnd - iBegin)*0.001, 323 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), 324 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); 325 } 326} 327 328#define BEGIN_TIMER beginTimer() 329#define END_TIMER endTimer() 330#define HAS_TIMER 1 331 332#elif (defined(_WIN32) || defined(WIN32)) 333 334/* Saved resource information for the beginning of an operation */ 335static HANDLE hProcess; 336static FILETIME ftKernelBegin; 337static FILETIME ftUserBegin; 338static sqlite3_int64 ftWallBegin; 339typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, 340 LPFILETIME, LPFILETIME); 341static GETPROCTIMES getProcessTimesAddr = NULL; 342 343/* 344** Check to see if we have timer support. Return 1 if necessary 345** support found (or found previously). 346*/ 347static int hasTimer(void){ 348 if( getProcessTimesAddr ){ 349 return 1; 350 } else { 351#if !SQLITE_OS_WINRT 352 /* GetProcessTimes() isn't supported in WIN95 and some other Windows 353 ** versions. See if the version we are running on has it, and if it 354 ** does, save off a pointer to it and the current process handle. 355 */ 356 hProcess = GetCurrentProcess(); 357 if( hProcess ){ 358 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); 359 if( NULL != hinstLib ){ 360 getProcessTimesAddr = 361 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); 362 if( NULL != getProcessTimesAddr ){ 363 return 1; 364 } 365 FreeLibrary(hinstLib); 366 } 367 } 368#endif 369 } 370 return 0; 371} 372 373/* 374** Begin timing an operation 375*/ 376static void beginTimer(void){ 377 if( enableTimer && getProcessTimesAddr ){ 378 FILETIME ftCreation, ftExit; 379 getProcessTimesAddr(hProcess,&ftCreation,&ftExit, 380 &ftKernelBegin,&ftUserBegin); 381 ftWallBegin = timeOfDay(); 382 } 383} 384 385/* Return the difference of two FILETIME structs in seconds */ 386static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ 387 sqlite_int64 i64Start = *((sqlite_int64 *) pStart); 388 sqlite_int64 i64End = *((sqlite_int64 *) pEnd); 389 return (double) ((i64End - i64Start) / 10000000.0); 390} 391 392/* 393** Print the timing results. 394*/ 395static void endTimer(void){ 396 if( enableTimer && getProcessTimesAddr){ 397 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; 398 sqlite3_int64 ftWallEnd = timeOfDay(); 399 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); 400 printf("Run Time: real %.3f user %f sys %f\n", 401 (ftWallEnd - ftWallBegin)*0.001, 402 timeDiff(&ftUserBegin, &ftUserEnd), 403 timeDiff(&ftKernelBegin, &ftKernelEnd)); 404 } 405} 406 407#define BEGIN_TIMER beginTimer() 408#define END_TIMER endTimer() 409#define HAS_TIMER hasTimer() 410 411#else 412#define BEGIN_TIMER 413#define END_TIMER 414#define HAS_TIMER 0 415#endif 416 417/* 418** Used to prevent warnings about unused parameters 419*/ 420#define UNUSED_PARAMETER(x) (void)(x) 421 422/* 423** Number of elements in an array 424*/ 425#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) 426 427/* 428** If the following flag is set, then command execution stops 429** at an error if we are not interactive. 430*/ 431static int bail_on_error = 0; 432 433/* 434** Threat stdin as an interactive input if the following variable 435** is true. Otherwise, assume stdin is connected to a file or pipe. 436*/ 437static int stdin_is_interactive = 1; 438 439/* 440** On Windows systems we have to know if standard output is a console 441** in order to translate UTF-8 into MBCS. The following variable is 442** true if translation is required. 443*/ 444static int stdout_is_console = 1; 445 446/* 447** The following is the open SQLite database. We make a pointer 448** to this database a static variable so that it can be accessed 449** by the SIGINT handler to interrupt database processing. 450*/ 451static sqlite3 *globalDb = 0; 452 453/* 454** True if an interrupt (Control-C) has been received. 455*/ 456static volatile int seenInterrupt = 0; 457 458/* 459** This is the name of our program. It is set in main(), used 460** in a number of other places, mostly for error messages. 461*/ 462static char *Argv0; 463 464/* 465** Prompt strings. Initialized in main. Settable with 466** .prompt main continue 467*/ 468static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ 469static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ 470 471/* 472** Render output like fprintf(). Except, if the output is going to the 473** console and if this is running on a Windows machine, translate the 474** output from UTF-8 into MBCS. 475*/ 476#if defined(_WIN32) || defined(WIN32) 477void utf8_printf(FILE *out, const char *zFormat, ...){ 478 va_list ap; 479 va_start(ap, zFormat); 480 if( stdout_is_console && (out==stdout || out==stderr) ){ 481 char *z1 = sqlite3_vmprintf(zFormat, ap); 482 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); 483 sqlite3_free(z1); 484 fputs(z2, out); 485 sqlite3_free(z2); 486 }else{ 487 vfprintf(out, zFormat, ap); 488 } 489 va_end(ap); 490} 491#elif !defined(utf8_printf) 492# define utf8_printf fprintf 493#endif 494 495/* 496** Render output like fprintf(). This should not be used on anything that 497** includes string formatting (e.g. "%s"). 498*/ 499#if !defined(raw_printf) 500# define raw_printf fprintf 501#endif 502 503/* Indicate out-of-memory and exit. */ 504static void shell_out_of_memory(void){ 505 raw_printf(stderr,"Error: out of memory\n"); 506 exit(1); 507} 508 509/* Check a pointer to see if it is NULL. If it is NULL, exit with an 510** out-of-memory error. 511*/ 512static void shell_check_oom(void *p){ 513 if( p==0 ) shell_out_of_memory(); 514} 515 516/* 517** Write I/O traces to the following stream. 518*/ 519#ifdef SQLITE_ENABLE_IOTRACE 520static FILE *iotrace = 0; 521#endif 522 523/* 524** This routine works like printf in that its first argument is a 525** format string and subsequent arguments are values to be substituted 526** in place of % fields. The result of formatting this string 527** is written to iotrace. 528*/ 529#ifdef SQLITE_ENABLE_IOTRACE 530static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ 531 va_list ap; 532 char *z; 533 if( iotrace==0 ) return; 534 va_start(ap, zFormat); 535 z = sqlite3_vmprintf(zFormat, ap); 536 va_end(ap); 537 utf8_printf(iotrace, "%s", z); 538 sqlite3_free(z); 539} 540#endif 541 542/* 543** Output string zUtf to stream pOut as w characters. If w is negative, 544** then right-justify the text. W is the width in UTF-8 characters, not 545** in bytes. This is different from the %*.*s specification in printf 546** since with %*.*s the width is measured in bytes, not characters. 547*/ 548static void utf8_width_print(FILE *pOut, int w, const char *zUtf){ 549 int i; 550 int n; 551 int aw = w<0 ? -w : w; 552 if( zUtf==0 ) zUtf = ""; 553 for(i=n=0; zUtf[i]; i++){ 554 if( (zUtf[i]&0xc0)!=0x80 ){ 555 n++; 556 if( n==aw ){ 557 do{ i++; }while( (zUtf[i]&0xc0)==0x80 ); 558 break; 559 } 560 } 561 } 562 if( n>=aw ){ 563 utf8_printf(pOut, "%.*s", i, zUtf); 564 }else if( w<0 ){ 565 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf); 566 }else{ 567 utf8_printf(pOut, "%s%*s", zUtf, aw-n, ""); 568 } 569} 570 571 572/* 573** Determines if a string is a number of not. 574*/ 575static int isNumber(const char *z, int *realnum){ 576 if( *z=='-' || *z=='+' ) z++; 577 if( !IsDigit(*z) ){ 578 return 0; 579 } 580 z++; 581 if( realnum ) *realnum = 0; 582 while( IsDigit(*z) ){ z++; } 583 if( *z=='.' ){ 584 z++; 585 if( !IsDigit(*z) ) return 0; 586 while( IsDigit(*z) ){ z++; } 587 if( realnum ) *realnum = 1; 588 } 589 if( *z=='e' || *z=='E' ){ 590 z++; 591 if( *z=='+' || *z=='-' ) z++; 592 if( !IsDigit(*z) ) return 0; 593 while( IsDigit(*z) ){ z++; } 594 if( realnum ) *realnum = 1; 595 } 596 return *z==0; 597} 598 599/* 600** Compute a string length that is limited to what can be stored in 601** lower 30 bits of a 32-bit signed integer. 602*/ 603static int strlen30(const char *z){ 604 const char *z2 = z; 605 while( *z2 ){ z2++; } 606 return 0x3fffffff & (int)(z2 - z); 607} 608 609/* 610** Return the length of a string in characters. Multibyte UTF8 characters 611** count as a single character. 612*/ 613static int strlenChar(const char *z){ 614 int n = 0; 615 while( *z ){ 616 if( (0xc0&*(z++))!=0x80 ) n++; 617 } 618 return n; 619} 620 621/* 622** Return open FILE * if zFile exists, can be opened for read 623** and is an ordinary file or a character stream source. 624** Otherwise return 0. 625*/ 626static FILE * openChrSource(const char *zFile){ 627#ifdef _WIN32 628 struct _stat x = {0}; 629# define STAT_CHR_SRC(mode) ((mode & (_S_IFCHR|_S_IFIFO|_S_IFREG))!=0) 630 /* On Windows, open first, then check the stream nature. This order 631 ** is necessary because _stat() and sibs, when checking a named pipe, 632 ** effectively break the pipe as its supplier sees it. */ 633 FILE *rv = fopen(zFile, "rb"); 634 if( rv==0 ) return 0; 635 if( _fstat(_fileno(rv), &x) != 0 636 || !STAT_CHR_SRC(x.st_mode)){ 637 fclose(rv); 638 rv = 0; 639 } 640 return rv; 641#else 642 struct stat x = {0}; 643 int rc = stat(zFile, &x); 644# define STAT_CHR_SRC(mode) (S_ISREG(mode)||S_ISFIFO(mode)||S_ISCHR(mode)) 645 if( rc!=0 ) return 0; 646 if( STAT_CHR_SRC(x.st_mode) ){ 647 return fopen(zFile, "rb"); 648 }else{ 649 return 0; 650 } 651#endif 652#undef STAT_CHR_SRC 653} 654 655/* 656** This routine reads a line of text from FILE in, stores 657** the text in memory obtained from malloc() and returns a pointer 658** to the text. NULL is returned at end of file, or if malloc() 659** fails. 660** 661** If zLine is not NULL then it is a malloced buffer returned from 662** a previous call to this routine that may be reused. 663*/ 664static char *local_getline(char *zLine, FILE *in){ 665 int nLine = zLine==0 ? 0 : 100; 666 int n = 0; 667 668 while( 1 ){ 669 if( n+100>nLine ){ 670 nLine = nLine*2 + 100; 671 zLine = realloc(zLine, nLine); 672 shell_check_oom(zLine); 673 } 674 if( fgets(&zLine[n], nLine - n, in)==0 ){ 675 if( n==0 ){ 676 free(zLine); 677 return 0; 678 } 679 zLine[n] = 0; 680 break; 681 } 682 while( zLine[n] ) n++; 683 if( n>0 && zLine[n-1]=='\n' ){ 684 n--; 685 if( n>0 && zLine[n-1]=='\r' ) n--; 686 zLine[n] = 0; 687 break; 688 } 689 } 690#if defined(_WIN32) || defined(WIN32) 691 /* For interactive input on Windows systems, translate the 692 ** multi-byte characterset characters into UTF-8. */ 693 if( stdin_is_interactive && in==stdin ){ 694 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); 695 if( zTrans ){ 696 i64 nTrans = strlen(zTrans)+1; 697 if( nTrans>nLine ){ 698 zLine = realloc(zLine, nTrans); 699 shell_check_oom(zLine); 700 } 701 memcpy(zLine, zTrans, nTrans); 702 sqlite3_free(zTrans); 703 } 704 } 705#endif /* defined(_WIN32) || defined(WIN32) */ 706 return zLine; 707} 708 709/* 710** Retrieve a single line of input text. 711** 712** If in==0 then read from standard input and prompt before each line. 713** If isContinuation is true, then a continuation prompt is appropriate. 714** If isContinuation is zero, then the main prompt should be used. 715** 716** If zPrior is not NULL then it is a buffer from a prior call to this 717** routine that can be reused. 718** 719** The result is stored in space obtained from malloc() and must either 720** be freed by the caller or else passed back into this routine via the 721** zPrior argument for reuse. 722*/ 723#ifndef SQLITE_SHELL_FIDDLE 724static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 725 char *zPrompt; 726 char *zResult; 727 if( in!=0 ){ 728 zResult = local_getline(zPrior, in); 729 }else{ 730 zPrompt = isContinuation ? continuePrompt : mainPrompt; 731#if SHELL_USE_LOCAL_GETLINE 732 printf("%s", zPrompt); 733 fflush(stdout); 734 zResult = local_getline(zPrior, stdin); 735#else 736 free(zPrior); 737 zResult = shell_readline(zPrompt); 738 if( zResult && *zResult ) shell_add_history(zResult); 739#endif 740 } 741 return zResult; 742} 743#endif /* !SQLITE_SHELL_FIDDLE */ 744 745/* 746** Return the value of a hexadecimal digit. Return -1 if the input 747** is not a hex digit. 748*/ 749static int hexDigitValue(char c){ 750 if( c>='0' && c<='9' ) return c - '0'; 751 if( c>='a' && c<='f' ) return c - 'a' + 10; 752 if( c>='A' && c<='F' ) return c - 'A' + 10; 753 return -1; 754} 755 756/* 757** Interpret zArg as an integer value, possibly with suffixes. 758*/ 759static sqlite3_int64 integerValue(const char *zArg){ 760 sqlite3_int64 v = 0; 761 static const struct { char *zSuffix; int iMult; } aMult[] = { 762 { "KiB", 1024 }, 763 { "MiB", 1024*1024 }, 764 { "GiB", 1024*1024*1024 }, 765 { "KB", 1000 }, 766 { "MB", 1000000 }, 767 { "GB", 1000000000 }, 768 { "K", 1000 }, 769 { "M", 1000000 }, 770 { "G", 1000000000 }, 771 }; 772 int i; 773 int isNeg = 0; 774 if( zArg[0]=='-' ){ 775 isNeg = 1; 776 zArg++; 777 }else if( zArg[0]=='+' ){ 778 zArg++; 779 } 780 if( zArg[0]=='0' && zArg[1]=='x' ){ 781 int x; 782 zArg += 2; 783 while( (x = hexDigitValue(zArg[0]))>=0 ){ 784 v = (v<<4) + x; 785 zArg++; 786 } 787 }else{ 788 while( IsDigit(zArg[0]) ){ 789 v = v*10 + zArg[0] - '0'; 790 zArg++; 791 } 792 } 793 for(i=0; i<ArraySize(aMult); i++){ 794 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ 795 v *= aMult[i].iMult; 796 break; 797 } 798 } 799 return isNeg? -v : v; 800} 801 802/* 803** A variable length string to which one can append text. 804*/ 805typedef struct ShellText ShellText; 806struct ShellText { 807 char *z; 808 int n; 809 int nAlloc; 810}; 811 812/* 813** Initialize and destroy a ShellText object 814*/ 815static void initText(ShellText *p){ 816 memset(p, 0, sizeof(*p)); 817} 818static void freeText(ShellText *p){ 819 free(p->z); 820 initText(p); 821} 822 823/* zIn is either a pointer to a NULL-terminated string in memory obtained 824** from malloc(), or a NULL pointer. The string pointed to by zAppend is 825** added to zIn, and the result returned in memory obtained from malloc(). 826** zIn, if it was not NULL, is freed. 827** 828** If the third argument, quote, is not '\0', then it is used as a 829** quote character for zAppend. 830*/ 831static void appendText(ShellText *p, const char *zAppend, char quote){ 832 i64 len; 833 i64 i; 834 i64 nAppend = strlen30(zAppend); 835 836 len = nAppend+p->n+1; 837 if( quote ){ 838 len += 2; 839 for(i=0; i<nAppend; i++){ 840 if( zAppend[i]==quote ) len++; 841 } 842 } 843 844 if( p->z==0 || p->n+len>=p->nAlloc ){ 845 p->nAlloc = p->nAlloc*2 + len + 20; 846 p->z = realloc(p->z, p->nAlloc); 847 shell_check_oom(p->z); 848 } 849 850 if( quote ){ 851 char *zCsr = p->z+p->n; 852 *zCsr++ = quote; 853 for(i=0; i<nAppend; i++){ 854 *zCsr++ = zAppend[i]; 855 if( zAppend[i]==quote ) *zCsr++ = quote; 856 } 857 *zCsr++ = quote; 858 p->n = (int)(zCsr - p->z); 859 *zCsr = '\0'; 860 }else{ 861 memcpy(p->z+p->n, zAppend, nAppend); 862 p->n += nAppend; 863 p->z[p->n] = '\0'; 864 } 865} 866 867/* 868** Attempt to determine if identifier zName needs to be quoted, either 869** because it contains non-alphanumeric characters, or because it is an 870** SQLite keyword. Be conservative in this estimate: When in doubt assume 871** that quoting is required. 872** 873** Return '"' if quoting is required. Return 0 if no quoting is required. 874*/ 875static char quoteChar(const char *zName){ 876 int i; 877 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; 878 for(i=0; zName[i]; i++){ 879 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; 880 } 881 return sqlite3_keyword_check(zName, i) ? '"' : 0; 882} 883 884/* 885** Construct a fake object name and column list to describe the structure 886** of the view, virtual table, or table valued function zSchema.zName. 887*/ 888static char *shellFakeSchema( 889 sqlite3 *db, /* The database connection containing the vtab */ 890 const char *zSchema, /* Schema of the database holding the vtab */ 891 const char *zName /* The name of the virtual table */ 892){ 893 sqlite3_stmt *pStmt = 0; 894 char *zSql; 895 ShellText s; 896 char cQuote; 897 char *zDiv = "("; 898 int nRow = 0; 899 900 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;", 901 zSchema ? zSchema : "main", zName); 902 shell_check_oom(zSql); 903 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 904 sqlite3_free(zSql); 905 initText(&s); 906 if( zSchema ){ 907 cQuote = quoteChar(zSchema); 908 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0; 909 appendText(&s, zSchema, cQuote); 910 appendText(&s, ".", 0); 911 } 912 cQuote = quoteChar(zName); 913 appendText(&s, zName, cQuote); 914 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 915 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1); 916 nRow++; 917 appendText(&s, zDiv, 0); 918 zDiv = ","; 919 if( zCol==0 ) zCol = ""; 920 cQuote = quoteChar(zCol); 921 appendText(&s, zCol, cQuote); 922 } 923 appendText(&s, ")", 0); 924 sqlite3_finalize(pStmt); 925 if( nRow==0 ){ 926 freeText(&s); 927 s.z = 0; 928 } 929 return s.z; 930} 931 932/* 933** SQL function: shell_module_schema(X) 934** 935** Return a fake schema for the table-valued function or eponymous virtual 936** table X. 937*/ 938static void shellModuleSchema( 939 sqlite3_context *pCtx, 940 int nVal, 941 sqlite3_value **apVal 942){ 943 const char *zName; 944 char *zFake; 945 UNUSED_PARAMETER(nVal); 946 zName = (const char*)sqlite3_value_text(apVal[0]); 947 zFake = zName ? shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName) : 0; 948 if( zFake ){ 949 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake), 950 -1, sqlite3_free); 951 free(zFake); 952 } 953} 954 955/* 956** SQL function: shell_add_schema(S,X) 957** 958** Add the schema name X to the CREATE statement in S and return the result. 959** Examples: 960** 961** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x); 962** 963** Also works on 964** 965** CREATE INDEX 966** CREATE UNIQUE INDEX 967** CREATE VIEW 968** CREATE TRIGGER 969** CREATE VIRTUAL TABLE 970** 971** This UDF is used by the .schema command to insert the schema name of 972** attached databases into the middle of the sqlite_schema.sql field. 973*/ 974static void shellAddSchemaName( 975 sqlite3_context *pCtx, 976 int nVal, 977 sqlite3_value **apVal 978){ 979 static const char *aPrefix[] = { 980 "TABLE", 981 "INDEX", 982 "UNIQUE INDEX", 983 "VIEW", 984 "TRIGGER", 985 "VIRTUAL TABLE" 986 }; 987 int i = 0; 988 const char *zIn = (const char*)sqlite3_value_text(apVal[0]); 989 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]); 990 const char *zName = (const char*)sqlite3_value_text(apVal[2]); 991 sqlite3 *db = sqlite3_context_db_handle(pCtx); 992 UNUSED_PARAMETER(nVal); 993 if( zIn!=0 && cli_strncmp(zIn, "CREATE ", 7)==0 ){ 994 for(i=0; i<ArraySize(aPrefix); i++){ 995 int n = strlen30(aPrefix[i]); 996 if( cli_strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){ 997 char *z = 0; 998 char *zFake = 0; 999 if( zSchema ){ 1000 char cQuote = quoteChar(zSchema); 1001 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){ 1002 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8); 1003 }else{ 1004 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8); 1005 } 1006 } 1007 if( zName 1008 && aPrefix[i][0]=='V' 1009 && (zFake = shellFakeSchema(db, zSchema, zName))!=0 1010 ){ 1011 if( z==0 ){ 1012 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake); 1013 }else{ 1014 z = sqlite3_mprintf("%z\n/* %s */", z, zFake); 1015 } 1016 free(zFake); 1017 } 1018 if( z ){ 1019 sqlite3_result_text(pCtx, z, -1, sqlite3_free); 1020 return; 1021 } 1022 } 1023 } 1024 } 1025 sqlite3_result_value(pCtx, apVal[0]); 1026} 1027 1028/* 1029** The source code for several run-time loadable extensions is inserted 1030** below by the ../tool/mkshellc.tcl script. Before processing that included 1031** code, we need to override some macros to make the included program code 1032** work here in the middle of this regular program. 1033*/ 1034#define SQLITE_EXTENSION_INIT1 1035#define SQLITE_EXTENSION_INIT2(X) (void)(X) 1036 1037#if defined(_WIN32) && defined(_MSC_VER) 1038INCLUDE test_windirent.h 1039INCLUDE test_windirent.c 1040#define dirent DIRENT 1041#endif 1042INCLUDE ../ext/misc/memtrace.c 1043INCLUDE ../ext/misc/shathree.c 1044INCLUDE ../ext/misc/uint.c 1045INCLUDE ../ext/misc/decimal.c 1046INCLUDE ../ext/misc/ieee754.c 1047INCLUDE ../ext/misc/series.c 1048INCLUDE ../ext/misc/regexp.c 1049#ifndef SQLITE_SHELL_FIDDLE 1050INCLUDE ../ext/misc/fileio.c 1051INCLUDE ../ext/misc/completion.c 1052INCLUDE ../ext/misc/appendvfs.c 1053#endif 1054#ifdef SQLITE_HAVE_ZLIB 1055INCLUDE ../ext/misc/zipfile.c 1056INCLUDE ../ext/misc/sqlar.c 1057#endif 1058INCLUDE ../ext/expert/sqlite3expert.h 1059INCLUDE ../ext/expert/sqlite3expert.c 1060 1061#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 1062#define SQLITE_SHELL_HAVE_RECOVER 1 1063#else 1064#define SQLITE_SHELL_HAVE_RECOVER 0 1065#endif 1066#if SQLITE_SHELL_HAVE_RECOVER 1067INCLUDE ../ext/recover/dbdata.c 1068INCLUDE ../ext/recover/sqlite3recover.h 1069INCLUDE ../ext/recover/sqlite3recover.c 1070#endif 1071 1072#if defined(SQLITE_ENABLE_SESSION) 1073/* 1074** State information for a single open session 1075*/ 1076typedef struct OpenSession OpenSession; 1077struct OpenSession { 1078 char *zName; /* Symbolic name for this session */ 1079 int nFilter; /* Number of xFilter rejection GLOB patterns */ 1080 char **azFilter; /* Array of xFilter rejection GLOB patterns */ 1081 sqlite3_session *p; /* The open session */ 1082}; 1083#endif 1084 1085typedef struct ExpertInfo ExpertInfo; 1086struct ExpertInfo { 1087 sqlite3expert *pExpert; 1088 int bVerbose; 1089}; 1090 1091/* A single line in the EQP output */ 1092typedef struct EQPGraphRow EQPGraphRow; 1093struct EQPGraphRow { 1094 int iEqpId; /* ID for this row */ 1095 int iParentId; /* ID of the parent row */ 1096 EQPGraphRow *pNext; /* Next row in sequence */ 1097 char zText[1]; /* Text to display for this row */ 1098}; 1099 1100/* All EQP output is collected into an instance of the following */ 1101typedef struct EQPGraph EQPGraph; 1102struct EQPGraph { 1103 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */ 1104 EQPGraphRow *pLast; /* Last element of the pRow list */ 1105 char zPrefix[100]; /* Graph prefix */ 1106}; 1107 1108/* Parameters affecting columnar mode result display (defaulting together) */ 1109typedef struct ColModeOpts { 1110 int iWrap; /* In columnar modes, wrap lines reaching this limit */ 1111 u8 bQuote; /* Quote results for .mode box and table */ 1112 u8 bWordWrap; /* In columnar modes, wrap at word boundaries */ 1113} ColModeOpts; 1114#define ColModeOpts_default { 60, 0, 0 } 1115#define ColModeOpts_default_qbox { 60, 1, 0 } 1116 1117/* 1118** State information about the database connection is contained in an 1119** instance of the following structure. 1120*/ 1121typedef struct ShellState ShellState; 1122struct ShellState { 1123 sqlite3 *db; /* The database */ 1124 u8 autoExplain; /* Automatically turn on .explain mode */ 1125 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ 1126 u8 autoEQPtest; /* autoEQP is in test mode */ 1127 u8 autoEQPtrace; /* autoEQP is in trace mode */ 1128 u8 scanstatsOn; /* True to display scan stats before each finalize */ 1129 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */ 1130 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */ 1131 u8 nEqpLevel; /* Depth of the EQP output graph */ 1132 u8 eTraceType; /* SHELL_TRACE_* value for type of trace */ 1133 u8 bSafeMode; /* True to prohibit unsafe operations */ 1134 u8 bSafeModePersist; /* The long-term value of bSafeMode */ 1135 ColModeOpts cmOpts; /* Option values affecting columnar mode output */ 1136 unsigned statsOn; /* True to display memory stats before each finalize */ 1137 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */ 1138 int inputNesting; /* Track nesting level of .read and other redirects */ 1139 int outCount; /* Revert to stdout when reaching zero */ 1140 int cnt; /* Number of records displayed so far */ 1141 int lineno; /* Line number of last line read from in */ 1142 int openFlags; /* Additional flags to open. (SQLITE_OPEN_NOFOLLOW) */ 1143 FILE *in; /* Read commands from this stream */ 1144 FILE *out; /* Write results here */ 1145 FILE *traceOut; /* Output for sqlite3_trace() */ 1146 int nErr; /* Number of errors seen */ 1147 int mode; /* An output mode setting */ 1148 int modePrior; /* Saved mode */ 1149 int cMode; /* temporary output mode for the current query */ 1150 int normalMode; /* Output mode before ".explain on" */ 1151 int writableSchema; /* True if PRAGMA writable_schema=ON */ 1152 int showHeader; /* True to show column names in List or Column mode */ 1153 int nCheck; /* Number of ".check" commands run */ 1154 unsigned nProgress; /* Number of progress callbacks encountered */ 1155 unsigned mxProgress; /* Maximum progress callbacks before failing */ 1156 unsigned flgProgress; /* Flags for the progress callback */ 1157 unsigned shellFlgs; /* Various flags */ 1158 unsigned priorShFlgs; /* Saved copy of flags */ 1159 sqlite3_int64 szMax; /* --maxsize argument to .open */ 1160 char *zDestTable; /* Name of destination table when MODE_Insert */ 1161 char *zTempFile; /* Temporary file that might need deleting */ 1162 char zTestcase[30]; /* Name of current test case */ 1163 char colSeparator[20]; /* Column separator character for several modes */ 1164 char rowSeparator[20]; /* Row separator character for MODE_Ascii */ 1165 char colSepPrior[20]; /* Saved column separator */ 1166 char rowSepPrior[20]; /* Saved row separator */ 1167 int *colWidth; /* Requested width of each column in columnar modes */ 1168 int *actualWidth; /* Actual width of each column */ 1169 int nWidth; /* Number of slots in colWidth[] and actualWidth[] */ 1170 char nullValue[20]; /* The text to print when a NULL comes back from 1171 ** the database */ 1172 char outfile[FILENAME_MAX]; /* Filename for *out */ 1173 sqlite3_stmt *pStmt; /* Current statement if any. */ 1174 FILE *pLog; /* Write log output here */ 1175 struct AuxDb { /* Storage space for auxiliary database connections */ 1176 sqlite3 *db; /* Connection pointer */ 1177 const char *zDbFilename; /* Filename used to open the connection */ 1178 char *zFreeOnClose; /* Free this memory allocation on close */ 1179#if defined(SQLITE_ENABLE_SESSION) 1180 int nSession; /* Number of active sessions */ 1181 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ 1182#endif 1183 } aAuxDb[5], /* Array of all database connections */ 1184 *pAuxDb; /* Currently active database connection */ 1185 int *aiIndent; /* Array of indents used in MODE_Explain */ 1186 int nIndent; /* Size of array aiIndent[] */ 1187 int iIndent; /* Index of current op in aiIndent[] */ 1188 char *zNonce; /* Nonce for temporary safe-mode excapes */ 1189 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */ 1190 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */ 1191#ifdef SQLITE_SHELL_FIDDLE 1192 struct { 1193 const char * zInput; /* Input string from wasm/JS proxy */ 1194 const char * zPos; /* Cursor pos into zInput */ 1195 const char * zDefaultDbName; /* Default name for db file */ 1196 } wasm; 1197#endif 1198}; 1199 1200#ifdef SQLITE_SHELL_FIDDLE 1201static ShellState shellState; 1202#endif 1203 1204 1205/* Allowed values for ShellState.autoEQP 1206*/ 1207#define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */ 1208#define AUTOEQP_on 1 /* Automatic EQP is on */ 1209#define AUTOEQP_trigger 2 /* On and also show plans for triggers */ 1210#define AUTOEQP_full 3 /* Show full EXPLAIN */ 1211 1212/* Allowed values for ShellState.openMode 1213*/ 1214#define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */ 1215#define SHELL_OPEN_NORMAL 1 /* Normal database file */ 1216#define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */ 1217#define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */ 1218#define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */ 1219#define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */ 1220#define SHELL_OPEN_HEXDB 6 /* Use "dbtotxt" output as data source */ 1221 1222/* Allowed values for ShellState.eTraceType 1223*/ 1224#define SHELL_TRACE_PLAIN 0 /* Show input SQL text */ 1225#define SHELL_TRACE_EXPANDED 1 /* Show expanded SQL text */ 1226#define SHELL_TRACE_NORMALIZED 2 /* Show normalized SQL text */ 1227 1228/* Bits in the ShellState.flgProgress variable */ 1229#define SHELL_PROGRESS_QUIET 0x01 /* Omit announcing every progress callback */ 1230#define SHELL_PROGRESS_RESET 0x02 /* Reset the count when the progres 1231 ** callback limit is reached, and for each 1232 ** top-level SQL statement */ 1233#define SHELL_PROGRESS_ONCE 0x04 /* Cancel the --limit after firing once */ 1234 1235/* 1236** These are the allowed shellFlgs values 1237*/ 1238#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */ 1239#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */ 1240#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */ 1241#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */ 1242#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */ 1243#define SHFLG_CountChanges 0x00000020 /* .changes setting */ 1244#define SHFLG_Echo 0x00000040 /* .echo on/off, or --echo setting */ 1245#define SHFLG_HeaderSet 0x00000080 /* showHeader has been specified */ 1246#define SHFLG_DumpDataOnly 0x00000100 /* .dump show data only */ 1247#define SHFLG_DumpNoSys 0x00000200 /* .dump omits system tables */ 1248 1249/* 1250** Macros for testing and setting shellFlgs 1251*/ 1252#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0) 1253#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X)) 1254#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X))) 1255 1256/* 1257** These are the allowed modes. 1258*/ 1259#define MODE_Line 0 /* One column per line. Blank line between records */ 1260#define MODE_Column 1 /* One record per line in neat columns */ 1261#define MODE_List 2 /* One record per line with a separator */ 1262#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ 1263#define MODE_Html 4 /* Generate an XHTML table */ 1264#define MODE_Insert 5 /* Generate SQL "insert" statements */ 1265#define MODE_Quote 6 /* Quote values as for SQL */ 1266#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */ 1267#define MODE_Csv 8 /* Quote strings, numbers are plain */ 1268#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */ 1269#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */ 1270#define MODE_Pretty 11 /* Pretty-print schemas */ 1271#define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */ 1272#define MODE_Json 13 /* Output JSON */ 1273#define MODE_Markdown 14 /* Markdown formatting */ 1274#define MODE_Table 15 /* MySQL-style table formatting */ 1275#define MODE_Box 16 /* Unicode box-drawing characters */ 1276#define MODE_Count 17 /* Output only a count of the rows of output */ 1277#define MODE_Off 18 /* No query output shown */ 1278 1279static const char *modeDescr[] = { 1280 "line", 1281 "column", 1282 "list", 1283 "semi", 1284 "html", 1285 "insert", 1286 "quote", 1287 "tcl", 1288 "csv", 1289 "explain", 1290 "ascii", 1291 "prettyprint", 1292 "eqp", 1293 "json", 1294 "markdown", 1295 "table", 1296 "box", 1297 "count", 1298 "off" 1299}; 1300 1301/* 1302** These are the column/row/line separators used by the various 1303** import/export modes. 1304*/ 1305#define SEP_Column "|" 1306#define SEP_Row "\n" 1307#define SEP_Tab "\t" 1308#define SEP_Space " " 1309#define SEP_Comma "," 1310#define SEP_CrLf "\r\n" 1311#define SEP_Unit "\x1F" 1312#define SEP_Record "\x1E" 1313 1314/* 1315** Limit input nesting via .read or any other input redirect. 1316** It's not too expensive, so a generous allowance can be made. 1317*/ 1318#define MAX_INPUT_NESTING 25 1319 1320/* 1321** A callback for the sqlite3_log() interface. 1322*/ 1323static void shellLog(void *pArg, int iErrCode, const char *zMsg){ 1324 ShellState *p = (ShellState*)pArg; 1325 if( p->pLog==0 ) return; 1326 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); 1327 fflush(p->pLog); 1328} 1329 1330/* 1331** SQL function: shell_putsnl(X) 1332** 1333** Write the text X to the screen (or whatever output is being directed) 1334** adding a newline at the end, and then return X. 1335*/ 1336static void shellPutsFunc( 1337 sqlite3_context *pCtx, 1338 int nVal, 1339 sqlite3_value **apVal 1340){ 1341 ShellState *p = (ShellState*)sqlite3_user_data(pCtx); 1342 (void)nVal; 1343 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0])); 1344 sqlite3_result_value(pCtx, apVal[0]); 1345} 1346 1347/* 1348** If in safe mode, print an error message described by the arguments 1349** and exit immediately. 1350*/ 1351static void failIfSafeMode( 1352 ShellState *p, 1353 const char *zErrMsg, 1354 ... 1355){ 1356 if( p->bSafeMode ){ 1357 va_list ap; 1358 char *zMsg; 1359 va_start(ap, zErrMsg); 1360 zMsg = sqlite3_vmprintf(zErrMsg, ap); 1361 va_end(ap); 1362 raw_printf(stderr, "line %d: ", p->lineno); 1363 utf8_printf(stderr, "%s\n", zMsg); 1364 exit(1); 1365 } 1366} 1367 1368/* 1369** SQL function: edit(VALUE) 1370** edit(VALUE,EDITOR) 1371** 1372** These steps: 1373** 1374** (1) Write VALUE into a temporary file. 1375** (2) Run program EDITOR on that temporary file. 1376** (3) Read the temporary file back and return its content as the result. 1377** (4) Delete the temporary file 1378** 1379** If the EDITOR argument is omitted, use the value in the VISUAL 1380** environment variable. If still there is no EDITOR, through an error. 1381** 1382** Also throw an error if the EDITOR program returns a non-zero exit code. 1383*/ 1384#ifndef SQLITE_NOHAVE_SYSTEM 1385static void editFunc( 1386 sqlite3_context *context, 1387 int argc, 1388 sqlite3_value **argv 1389){ 1390 const char *zEditor; 1391 char *zTempFile = 0; 1392 sqlite3 *db; 1393 char *zCmd = 0; 1394 int bBin; 1395 int rc; 1396 int hasCRNL = 0; 1397 FILE *f = 0; 1398 sqlite3_int64 sz; 1399 sqlite3_int64 x; 1400 unsigned char *p = 0; 1401 1402 if( argc==2 ){ 1403 zEditor = (const char*)sqlite3_value_text(argv[1]); 1404 }else{ 1405 zEditor = getenv("VISUAL"); 1406 } 1407 if( zEditor==0 ){ 1408 sqlite3_result_error(context, "no editor for edit()", -1); 1409 return; 1410 } 1411 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ 1412 sqlite3_result_error(context, "NULL input to edit()", -1); 1413 return; 1414 } 1415 db = sqlite3_context_db_handle(context); 1416 zTempFile = 0; 1417 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile); 1418 if( zTempFile==0 ){ 1419 sqlite3_uint64 r = 0; 1420 sqlite3_randomness(sizeof(r), &r); 1421 zTempFile = sqlite3_mprintf("temp%llx", r); 1422 if( zTempFile==0 ){ 1423 sqlite3_result_error_nomem(context); 1424 return; 1425 } 1426 } 1427 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB; 1428 /* When writing the file to be edited, do \n to \r\n conversions on systems 1429 ** that want \r\n line endings */ 1430 f = fopen(zTempFile, bBin ? "wb" : "w"); 1431 if( f==0 ){ 1432 sqlite3_result_error(context, "edit() cannot open temp file", -1); 1433 goto edit_func_end; 1434 } 1435 sz = sqlite3_value_bytes(argv[0]); 1436 if( bBin ){ 1437 x = fwrite(sqlite3_value_blob(argv[0]), 1, (size_t)sz, f); 1438 }else{ 1439 const char *z = (const char*)sqlite3_value_text(argv[0]); 1440 /* Remember whether or not the value originally contained \r\n */ 1441 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1; 1442 x = fwrite(sqlite3_value_text(argv[0]), 1, (size_t)sz, f); 1443 } 1444 fclose(f); 1445 f = 0; 1446 if( x!=sz ){ 1447 sqlite3_result_error(context, "edit() could not write the whole file", -1); 1448 goto edit_func_end; 1449 } 1450 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile); 1451 if( zCmd==0 ){ 1452 sqlite3_result_error_nomem(context); 1453 goto edit_func_end; 1454 } 1455 rc = system(zCmd); 1456 sqlite3_free(zCmd); 1457 if( rc ){ 1458 sqlite3_result_error(context, "EDITOR returned non-zero", -1); 1459 goto edit_func_end; 1460 } 1461 f = fopen(zTempFile, "rb"); 1462 if( f==0 ){ 1463 sqlite3_result_error(context, 1464 "edit() cannot reopen temp file after edit", -1); 1465 goto edit_func_end; 1466 } 1467 fseek(f, 0, SEEK_END); 1468 sz = ftell(f); 1469 rewind(f); 1470 p = sqlite3_malloc64( sz+1 ); 1471 if( p==0 ){ 1472 sqlite3_result_error_nomem(context); 1473 goto edit_func_end; 1474 } 1475 x = fread(p, 1, (size_t)sz, f); 1476 fclose(f); 1477 f = 0; 1478 if( x!=sz ){ 1479 sqlite3_result_error(context, "could not read back the whole file", -1); 1480 goto edit_func_end; 1481 } 1482 if( bBin ){ 1483 sqlite3_result_blob64(context, p, sz, sqlite3_free); 1484 }else{ 1485 sqlite3_int64 i, j; 1486 if( hasCRNL ){ 1487 /* If the original contains \r\n then do no conversions back to \n */ 1488 }else{ 1489 /* If the file did not originally contain \r\n then convert any new 1490 ** \r\n back into \n */ 1491 for(i=j=0; i<sz; i++){ 1492 if( p[i]=='\r' && p[i+1]=='\n' ) i++; 1493 p[j++] = p[i]; 1494 } 1495 sz = j; 1496 p[sz] = 0; 1497 } 1498 sqlite3_result_text64(context, (const char*)p, sz, 1499 sqlite3_free, SQLITE_UTF8); 1500 } 1501 p = 0; 1502 1503edit_func_end: 1504 if( f ) fclose(f); 1505 unlink(zTempFile); 1506 sqlite3_free(zTempFile); 1507 sqlite3_free(p); 1508} 1509#endif /* SQLITE_NOHAVE_SYSTEM */ 1510 1511/* 1512** Save or restore the current output mode 1513*/ 1514static void outputModePush(ShellState *p){ 1515 p->modePrior = p->mode; 1516 p->priorShFlgs = p->shellFlgs; 1517 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator)); 1518 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator)); 1519} 1520static void outputModePop(ShellState *p){ 1521 p->mode = p->modePrior; 1522 p->shellFlgs = p->priorShFlgs; 1523 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator)); 1524 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator)); 1525} 1526 1527/* 1528** Output the given string as a hex-encoded blob (eg. X'1234' ) 1529*/ 1530static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ 1531 int i; 1532 unsigned char *aBlob = (unsigned char*)pBlob; 1533 1534 char *zStr = sqlite3_malloc(nBlob*2 + 1); 1535 shell_check_oom(zStr); 1536 1537 for(i=0; i<nBlob; i++){ 1538 static const char aHex[] = { 1539 '0', '1', '2', '3', '4', '5', '6', '7', 1540 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 1541 }; 1542 zStr[i*2] = aHex[ (aBlob[i] >> 4) ]; 1543 zStr[i*2+1] = aHex[ (aBlob[i] & 0x0F) ]; 1544 } 1545 zStr[i*2] = '\0'; 1546 1547 raw_printf(out,"X'%s'", zStr); 1548 sqlite3_free(zStr); 1549} 1550 1551/* 1552** Find a string that is not found anywhere in z[]. Return a pointer 1553** to that string. 1554** 1555** Try to use zA and zB first. If both of those are already found in z[] 1556** then make up some string and store it in the buffer zBuf. 1557*/ 1558static const char *unused_string( 1559 const char *z, /* Result must not appear anywhere in z */ 1560 const char *zA, const char *zB, /* Try these first */ 1561 char *zBuf /* Space to store a generated string */ 1562){ 1563 unsigned i = 0; 1564 if( strstr(z, zA)==0 ) return zA; 1565 if( strstr(z, zB)==0 ) return zB; 1566 do{ 1567 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 1568 }while( strstr(z,zBuf)!=0 ); 1569 return zBuf; 1570} 1571 1572/* 1573** Output the given string as a quoted string using SQL quoting conventions. 1574** 1575** See also: output_quoted_escaped_string() 1576*/ 1577static void output_quoted_string(FILE *out, const char *z){ 1578 int i; 1579 char c; 1580 setBinaryMode(out, 1); 1581 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1582 if( c==0 ){ 1583 utf8_printf(out,"'%s'",z); 1584 }else{ 1585 raw_printf(out, "'"); 1586 while( *z ){ 1587 for(i=0; (c = z[i])!=0 && c!='\''; i++){} 1588 if( c=='\'' ) i++; 1589 if( i ){ 1590 utf8_printf(out, "%.*s", i, z); 1591 z += i; 1592 } 1593 if( c=='\'' ){ 1594 raw_printf(out, "'"); 1595 continue; 1596 } 1597 if( c==0 ){ 1598 break; 1599 } 1600 z++; 1601 } 1602 raw_printf(out, "'"); 1603 } 1604 setTextMode(out, 1); 1605} 1606 1607/* 1608** Output the given string as a quoted string using SQL quoting conventions. 1609** Additionallly , escape the "\n" and "\r" characters so that they do not 1610** get corrupted by end-of-line translation facilities in some operating 1611** systems. 1612** 1613** This is like output_quoted_string() but with the addition of the \r\n 1614** escape mechanism. 1615*/ 1616static void output_quoted_escaped_string(FILE *out, const char *z){ 1617 int i; 1618 char c; 1619 setBinaryMode(out, 1); 1620 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} 1621 if( c==0 ){ 1622 utf8_printf(out,"'%s'",z); 1623 }else{ 1624 const char *zNL = 0; 1625 const char *zCR = 0; 1626 int nNL = 0; 1627 int nCR = 0; 1628 char zBuf1[20], zBuf2[20]; 1629 for(i=0; z[i]; i++){ 1630 if( z[i]=='\n' ) nNL++; 1631 if( z[i]=='\r' ) nCR++; 1632 } 1633 if( nNL ){ 1634 raw_printf(out, "replace("); 1635 zNL = unused_string(z, "\\n", "\\012", zBuf1); 1636 } 1637 if( nCR ){ 1638 raw_printf(out, "replace("); 1639 zCR = unused_string(z, "\\r", "\\015", zBuf2); 1640 } 1641 raw_printf(out, "'"); 1642 while( *z ){ 1643 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} 1644 if( c=='\'' ) i++; 1645 if( i ){ 1646 utf8_printf(out, "%.*s", i, z); 1647 z += i; 1648 } 1649 if( c=='\'' ){ 1650 raw_printf(out, "'"); 1651 continue; 1652 } 1653 if( c==0 ){ 1654 break; 1655 } 1656 z++; 1657 if( c=='\n' ){ 1658 raw_printf(out, "%s", zNL); 1659 continue; 1660 } 1661 raw_printf(out, "%s", zCR); 1662 } 1663 raw_printf(out, "'"); 1664 if( nCR ){ 1665 raw_printf(out, ",'%s',char(13))", zCR); 1666 } 1667 if( nNL ){ 1668 raw_printf(out, ",'%s',char(10))", zNL); 1669 } 1670 } 1671 setTextMode(out, 1); 1672} 1673 1674/* 1675** Output the given string as a quoted according to C or TCL quoting rules. 1676*/ 1677static void output_c_string(FILE *out, const char *z){ 1678 unsigned int c; 1679 fputc('"', out); 1680 while( (c = *(z++))!=0 ){ 1681 if( c=='\\' ){ 1682 fputc(c, out); 1683 fputc(c, out); 1684 }else if( c=='"' ){ 1685 fputc('\\', out); 1686 fputc('"', out); 1687 }else if( c=='\t' ){ 1688 fputc('\\', out); 1689 fputc('t', out); 1690 }else if( c=='\n' ){ 1691 fputc('\\', out); 1692 fputc('n', out); 1693 }else if( c=='\r' ){ 1694 fputc('\\', out); 1695 fputc('r', out); 1696 }else if( !isprint(c&0xff) ){ 1697 raw_printf(out, "\\%03o", c&0xff); 1698 }else{ 1699 fputc(c, out); 1700 } 1701 } 1702 fputc('"', out); 1703} 1704 1705/* 1706** Output the given string as a quoted according to JSON quoting rules. 1707*/ 1708static void output_json_string(FILE *out, const char *z, i64 n){ 1709 unsigned int c; 1710 if( n<0 ) n = strlen(z); 1711 fputc('"', out); 1712 while( n-- ){ 1713 c = *(z++); 1714 if( c=='\\' || c=='"' ){ 1715 fputc('\\', out); 1716 fputc(c, out); 1717 }else if( c<=0x1f ){ 1718 fputc('\\', out); 1719 if( c=='\b' ){ 1720 fputc('b', out); 1721 }else if( c=='\f' ){ 1722 fputc('f', out); 1723 }else if( c=='\n' ){ 1724 fputc('n', out); 1725 }else if( c=='\r' ){ 1726 fputc('r', out); 1727 }else if( c=='\t' ){ 1728 fputc('t', out); 1729 }else{ 1730 raw_printf(out, "u%04x",c); 1731 } 1732 }else{ 1733 fputc(c, out); 1734 } 1735 } 1736 fputc('"', out); 1737} 1738 1739/* 1740** Output the given string with characters that are special to 1741** HTML escaped. 1742*/ 1743static void output_html_string(FILE *out, const char *z){ 1744 int i; 1745 if( z==0 ) z = ""; 1746 while( *z ){ 1747 for(i=0; z[i] 1748 && z[i]!='<' 1749 && z[i]!='&' 1750 && z[i]!='>' 1751 && z[i]!='\"' 1752 && z[i]!='\''; 1753 i++){} 1754 if( i>0 ){ 1755 utf8_printf(out,"%.*s",i,z); 1756 } 1757 if( z[i]=='<' ){ 1758 raw_printf(out,"<"); 1759 }else if( z[i]=='&' ){ 1760 raw_printf(out,"&"); 1761 }else if( z[i]=='>' ){ 1762 raw_printf(out,">"); 1763 }else if( z[i]=='\"' ){ 1764 raw_printf(out,"""); 1765 }else if( z[i]=='\'' ){ 1766 raw_printf(out,"'"); 1767 }else{ 1768 break; 1769 } 1770 z += i + 1; 1771 } 1772} 1773 1774/* 1775** If a field contains any character identified by a 1 in the following 1776** array, then the string must be quoted for CSV. 1777*/ 1778static const char needCsvQuote[] = { 1779 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1780 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1781 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1782 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1783 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1784 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1785 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1786 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1787 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1788 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1789 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1790 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1791 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1792 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1793 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1794 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1795}; 1796 1797/* 1798** Output a single term of CSV. Actually, p->colSeparator is used for 1799** the separator, which may or may not be a comma. p->nullValue is 1800** the null value. Strings are quoted if necessary. The separator 1801** is only issued if bSep is true. 1802*/ 1803static void output_csv(ShellState *p, const char *z, int bSep){ 1804 FILE *out = p->out; 1805 if( z==0 ){ 1806 utf8_printf(out,"%s",p->nullValue); 1807 }else{ 1808 unsigned i; 1809 for(i=0; z[i]; i++){ 1810 if( needCsvQuote[((unsigned char*)z)[i]] ){ 1811 i = 0; 1812 break; 1813 } 1814 } 1815 if( i==0 || strstr(z, p->colSeparator)!=0 ){ 1816 char *zQuoted = sqlite3_mprintf("\"%w\"", z); 1817 shell_check_oom(zQuoted); 1818 utf8_printf(out, "%s", zQuoted); 1819 sqlite3_free(zQuoted); 1820 }else{ 1821 utf8_printf(out, "%s", z); 1822 } 1823 } 1824 if( bSep ){ 1825 utf8_printf(p->out, "%s", p->colSeparator); 1826 } 1827} 1828 1829/* 1830** This routine runs when the user presses Ctrl-C 1831*/ 1832static void interrupt_handler(int NotUsed){ 1833 UNUSED_PARAMETER(NotUsed); 1834 seenInterrupt++; 1835 if( seenInterrupt>2 ) exit(1); 1836 if( globalDb ) sqlite3_interrupt(globalDb); 1837} 1838 1839#if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 1840/* 1841** This routine runs for console events (e.g. Ctrl-C) on Win32 1842*/ 1843static BOOL WINAPI ConsoleCtrlHandler( 1844 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */ 1845){ 1846 if( dwCtrlType==CTRL_C_EVENT ){ 1847 interrupt_handler(0); 1848 return TRUE; 1849 } 1850 return FALSE; 1851} 1852#endif 1853 1854#ifndef SQLITE_OMIT_AUTHORIZATION 1855/* 1856** This authorizer runs in safe mode. 1857*/ 1858static int safeModeAuth( 1859 void *pClientData, 1860 int op, 1861 const char *zA1, 1862 const char *zA2, 1863 const char *zA3, 1864 const char *zA4 1865){ 1866 ShellState *p = (ShellState*)pClientData; 1867 static const char *azProhibitedFunctions[] = { 1868 "edit", 1869 "fts3_tokenizer", 1870 "load_extension", 1871 "readfile", 1872 "writefile", 1873 "zipfile", 1874 "zipfile_cds", 1875 }; 1876 UNUSED_PARAMETER(zA2); 1877 UNUSED_PARAMETER(zA3); 1878 UNUSED_PARAMETER(zA4); 1879 switch( op ){ 1880 case SQLITE_ATTACH: { 1881#ifndef SQLITE_SHELL_FIDDLE 1882 /* In WASM builds the filesystem is a virtual sandbox, so 1883 ** there's no harm in using ATTACH. */ 1884 failIfSafeMode(p, "cannot run ATTACH in safe mode"); 1885#endif 1886 break; 1887 } 1888 case SQLITE_FUNCTION: { 1889 int i; 1890 for(i=0; i<ArraySize(azProhibitedFunctions); i++){ 1891 if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){ 1892 failIfSafeMode(p, "cannot use the %s() function in safe mode", 1893 azProhibitedFunctions[i]); 1894 } 1895 } 1896 break; 1897 } 1898 } 1899 return SQLITE_OK; 1900} 1901 1902/* 1903** When the ".auth ON" is set, the following authorizer callback is 1904** invoked. It always returns SQLITE_OK. 1905*/ 1906static int shellAuth( 1907 void *pClientData, 1908 int op, 1909 const char *zA1, 1910 const char *zA2, 1911 const char *zA3, 1912 const char *zA4 1913){ 1914 ShellState *p = (ShellState*)pClientData; 1915 static const char *azAction[] = { 0, 1916 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", 1917 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", 1918 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", 1919 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", 1920 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", 1921 "DROP_TRIGGER", "DROP_VIEW", "INSERT", 1922 "PRAGMA", "READ", "SELECT", 1923 "TRANSACTION", "UPDATE", "ATTACH", 1924 "DETACH", "ALTER_TABLE", "REINDEX", 1925 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", 1926 "FUNCTION", "SAVEPOINT", "RECURSIVE" 1927 }; 1928 int i; 1929 const char *az[4]; 1930 az[0] = zA1; 1931 az[1] = zA2; 1932 az[2] = zA3; 1933 az[3] = zA4; 1934 utf8_printf(p->out, "authorizer: %s", azAction[op]); 1935 for(i=0; i<4; i++){ 1936 raw_printf(p->out, " "); 1937 if( az[i] ){ 1938 output_c_string(p->out, az[i]); 1939 }else{ 1940 raw_printf(p->out, "NULL"); 1941 } 1942 } 1943 raw_printf(p->out, "\n"); 1944 if( p->bSafeMode ) (void)safeModeAuth(pClientData, op, zA1, zA2, zA3, zA4); 1945 return SQLITE_OK; 1946} 1947#endif 1948 1949/* 1950** Print a schema statement. Part of MODE_Semi and MODE_Pretty output. 1951** 1952** This routine converts some CREATE TABLE statements for shadow tables 1953** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements. 1954** 1955** If the schema statement in z[] contains a start-of-comment and if 1956** sqlite3_complete() returns false, try to terminate the comment before 1957** printing the result. https://sqlite.org/forum/forumpost/d7be961c5c 1958*/ 1959static void printSchemaLine(FILE *out, const char *z, const char *zTail){ 1960 char *zToFree = 0; 1961 if( z==0 ) return; 1962 if( zTail==0 ) return; 1963 if( zTail[0]==';' && (strstr(z, "/*")!=0 || strstr(z,"--")!=0) ){ 1964 const char *zOrig = z; 1965 static const char *azTerm[] = { "", "*/", "\n" }; 1966 int i; 1967 for(i=0; i<ArraySize(azTerm); i++){ 1968 char *zNew = sqlite3_mprintf("%s%s;", zOrig, azTerm[i]); 1969 if( sqlite3_complete(zNew) ){ 1970 size_t n = strlen(zNew); 1971 zNew[n-1] = 0; 1972 zToFree = zNew; 1973 z = zNew; 1974 break; 1975 } 1976 sqlite3_free(zNew); 1977 } 1978 } 1979 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){ 1980 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail); 1981 }else{ 1982 utf8_printf(out, "%s%s", z, zTail); 1983 } 1984 sqlite3_free(zToFree); 1985} 1986static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){ 1987 char c = z[n]; 1988 z[n] = 0; 1989 printSchemaLine(out, z, zTail); 1990 z[n] = c; 1991} 1992 1993/* 1994** Return true if string z[] has nothing but whitespace and comments to the 1995** end of the first line. 1996*/ 1997static int wsToEol(const char *z){ 1998 int i; 1999 for(i=0; z[i]; i++){ 2000 if( z[i]=='\n' ) return 1; 2001 if( IsSpace(z[i]) ) continue; 2002 if( z[i]=='-' && z[i+1]=='-' ) return 1; 2003 return 0; 2004 } 2005 return 1; 2006} 2007 2008/* 2009** Add a new entry to the EXPLAIN QUERY PLAN data 2010*/ 2011static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){ 2012 EQPGraphRow *pNew; 2013 i64 nText; 2014 if( zText==0 ) return; 2015 nText = strlen(zText); 2016 if( p->autoEQPtest ){ 2017 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText); 2018 } 2019 pNew = sqlite3_malloc64( sizeof(*pNew) + nText ); 2020 shell_check_oom(pNew); 2021 pNew->iEqpId = iEqpId; 2022 pNew->iParentId = p2; 2023 memcpy(pNew->zText, zText, nText+1); 2024 pNew->pNext = 0; 2025 if( p->sGraph.pLast ){ 2026 p->sGraph.pLast->pNext = pNew; 2027 }else{ 2028 p->sGraph.pRow = pNew; 2029 } 2030 p->sGraph.pLast = pNew; 2031} 2032 2033/* 2034** Free and reset the EXPLAIN QUERY PLAN data that has been collected 2035** in p->sGraph. 2036*/ 2037static void eqp_reset(ShellState *p){ 2038 EQPGraphRow *pRow, *pNext; 2039 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){ 2040 pNext = pRow->pNext; 2041 sqlite3_free(pRow); 2042 } 2043 memset(&p->sGraph, 0, sizeof(p->sGraph)); 2044} 2045 2046/* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after 2047** pOld, or return the first such line if pOld is NULL 2048*/ 2049static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){ 2050 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow; 2051 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext; 2052 return pRow; 2053} 2054 2055/* Render a single level of the graph that has iEqpId as its parent. Called 2056** recursively to render sublevels. 2057*/ 2058static void eqp_render_level(ShellState *p, int iEqpId){ 2059 EQPGraphRow *pRow, *pNext; 2060 i64 n = strlen(p->sGraph.zPrefix); 2061 char *z; 2062 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){ 2063 pNext = eqp_next_row(p, iEqpId, pRow); 2064 z = pRow->zText; 2065 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, 2066 pNext ? "|--" : "`--", z); 2067 if( n<(i64)sizeof(p->sGraph.zPrefix)-7 ){ 2068 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4); 2069 eqp_render_level(p, pRow->iEqpId); 2070 p->sGraph.zPrefix[n] = 0; 2071 } 2072 } 2073} 2074 2075/* 2076** Display and reset the EXPLAIN QUERY PLAN data 2077*/ 2078static void eqp_render(ShellState *p){ 2079 EQPGraphRow *pRow = p->sGraph.pRow; 2080 if( pRow ){ 2081 if( pRow->zText[0]=='-' ){ 2082 if( pRow->pNext==0 ){ 2083 eqp_reset(p); 2084 return; 2085 } 2086 utf8_printf(p->out, "%s\n", pRow->zText+3); 2087 p->sGraph.pRow = pRow->pNext; 2088 sqlite3_free(pRow); 2089 }else{ 2090 utf8_printf(p->out, "QUERY PLAN\n"); 2091 } 2092 p->sGraph.zPrefix[0] = 0; 2093 eqp_render_level(p, 0); 2094 eqp_reset(p); 2095 } 2096} 2097 2098#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 2099/* 2100** Progress handler callback. 2101*/ 2102static int progress_handler(void *pClientData) { 2103 ShellState *p = (ShellState*)pClientData; 2104 p->nProgress++; 2105 if( p->nProgress>=p->mxProgress && p->mxProgress>0 ){ 2106 raw_printf(p->out, "Progress limit reached (%u)\n", p->nProgress); 2107 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 2108 if( p->flgProgress & SHELL_PROGRESS_ONCE ) p->mxProgress = 0; 2109 return 1; 2110 } 2111 if( (p->flgProgress & SHELL_PROGRESS_QUIET)==0 ){ 2112 raw_printf(p->out, "Progress %u\n", p->nProgress); 2113 } 2114 return 0; 2115} 2116#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 2117 2118/* 2119** Print N dashes 2120*/ 2121static void print_dashes(FILE *out, int N){ 2122 const char zDash[] = "--------------------------------------------------"; 2123 const int nDash = sizeof(zDash) - 1; 2124 while( N>nDash ){ 2125 fputs(zDash, out); 2126 N -= nDash; 2127 } 2128 raw_printf(out, "%.*s", N, zDash); 2129} 2130 2131/* 2132** Print a markdown or table-style row separator using ascii-art 2133*/ 2134static void print_row_separator( 2135 ShellState *p, 2136 int nArg, 2137 const char *zSep 2138){ 2139 int i; 2140 if( nArg>0 ){ 2141 fputs(zSep, p->out); 2142 print_dashes(p->out, p->actualWidth[0]+2); 2143 for(i=1; i<nArg; i++){ 2144 fputs(zSep, p->out); 2145 print_dashes(p->out, p->actualWidth[i]+2); 2146 } 2147 fputs(zSep, p->out); 2148 } 2149 fputs("\n", p->out); 2150} 2151 2152/* 2153** This is the callback routine that the shell 2154** invokes for each row of a query result. 2155*/ 2156static int shell_callback( 2157 void *pArg, 2158 int nArg, /* Number of result columns */ 2159 char **azArg, /* Text of each result column */ 2160 char **azCol, /* Column names */ 2161 int *aiType /* Column types. Might be NULL */ 2162){ 2163 int i; 2164 ShellState *p = (ShellState*)pArg; 2165 2166 if( azArg==0 ) return 0; 2167 switch( p->cMode ){ 2168 case MODE_Count: 2169 case MODE_Off: { 2170 break; 2171 } 2172 case MODE_Line: { 2173 int w = 5; 2174 if( azArg==0 ) break; 2175 for(i=0; i<nArg; i++){ 2176 int len = strlen30(azCol[i] ? azCol[i] : ""); 2177 if( len>w ) w = len; 2178 } 2179 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); 2180 for(i=0; i<nArg; i++){ 2181 utf8_printf(p->out,"%*s = %s%s", w, azCol[i], 2182 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); 2183 } 2184 break; 2185 } 2186 case MODE_Explain: { 2187 static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13}; 2188 if( nArg>ArraySize(aExplainWidth) ){ 2189 nArg = ArraySize(aExplainWidth); 2190 } 2191 if( p->cnt++==0 ){ 2192 for(i=0; i<nArg; i++){ 2193 int w = aExplainWidth[i]; 2194 utf8_width_print(p->out, w, azCol[i]); 2195 fputs(i==nArg-1 ? "\n" : " ", p->out); 2196 } 2197 for(i=0; i<nArg; i++){ 2198 int w = aExplainWidth[i]; 2199 print_dashes(p->out, w); 2200 fputs(i==nArg-1 ? "\n" : " ", p->out); 2201 } 2202 } 2203 if( azArg==0 ) break; 2204 for(i=0; i<nArg; i++){ 2205 int w = aExplainWidth[i]; 2206 if( i==nArg-1 ) w = 0; 2207 if( azArg[i] && strlenChar(azArg[i])>w ){ 2208 w = strlenChar(azArg[i]); 2209 } 2210 if( i==1 && p->aiIndent && p->pStmt ){ 2211 if( p->iIndent<p->nIndent ){ 2212 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); 2213 } 2214 p->iIndent++; 2215 } 2216 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue); 2217 fputs(i==nArg-1 ? "\n" : " ", p->out); 2218 } 2219 break; 2220 } 2221 case MODE_Semi: { /* .schema and .fullschema output */ 2222 printSchemaLine(p->out, azArg[0], ";\n"); 2223 break; 2224 } 2225 case MODE_Pretty: { /* .schema and .fullschema with --indent */ 2226 char *z; 2227 int j; 2228 int nParen = 0; 2229 char cEnd = 0; 2230 char c; 2231 int nLine = 0; 2232 assert( nArg==1 ); 2233 if( azArg[0]==0 ) break; 2234 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 2235 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 2236 ){ 2237 utf8_printf(p->out, "%s;\n", azArg[0]); 2238 break; 2239 } 2240 z = sqlite3_mprintf("%s", azArg[0]); 2241 shell_check_oom(z); 2242 j = 0; 2243 for(i=0; IsSpace(z[i]); i++){} 2244 for(; (c = z[i])!=0; i++){ 2245 if( IsSpace(c) ){ 2246 if( z[j-1]=='\r' ) z[j-1] = '\n'; 2247 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; 2248 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ 2249 j--; 2250 } 2251 z[j++] = c; 2252 } 2253 while( j>0 && IsSpace(z[j-1]) ){ j--; } 2254 z[j] = 0; 2255 if( strlen30(z)>=79 ){ 2256 for(i=j=0; (c = z[i])!=0; i++){ /* Copy from z[i] back to z[j] */ 2257 if( c==cEnd ){ 2258 cEnd = 0; 2259 }else if( c=='"' || c=='\'' || c=='`' ){ 2260 cEnd = c; 2261 }else if( c=='[' ){ 2262 cEnd = ']'; 2263 }else if( c=='-' && z[i+1]=='-' ){ 2264 cEnd = '\n'; 2265 }else if( c=='(' ){ 2266 nParen++; 2267 }else if( c==')' ){ 2268 nParen--; 2269 if( nLine>0 && nParen==0 && j>0 ){ 2270 printSchemaLineN(p->out, z, j, "\n"); 2271 j = 0; 2272 } 2273 } 2274 z[j++] = c; 2275 if( nParen==1 && cEnd==0 2276 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1))) 2277 ){ 2278 if( c=='\n' ) j--; 2279 printSchemaLineN(p->out, z, j, "\n "); 2280 j = 0; 2281 nLine++; 2282 while( IsSpace(z[i+1]) ){ i++; } 2283 } 2284 } 2285 z[j] = 0; 2286 } 2287 printSchemaLine(p->out, z, ";\n"); 2288 sqlite3_free(z); 2289 break; 2290 } 2291 case MODE_List: { 2292 if( p->cnt++==0 && p->showHeader ){ 2293 for(i=0; i<nArg; i++){ 2294 utf8_printf(p->out,"%s%s",azCol[i], 2295 i==nArg-1 ? p->rowSeparator : p->colSeparator); 2296 } 2297 } 2298 if( azArg==0 ) break; 2299 for(i=0; i<nArg; i++){ 2300 char *z = azArg[i]; 2301 if( z==0 ) z = p->nullValue; 2302 utf8_printf(p->out, "%s", z); 2303 if( i<nArg-1 ){ 2304 utf8_printf(p->out, "%s", p->colSeparator); 2305 }else{ 2306 utf8_printf(p->out, "%s", p->rowSeparator); 2307 } 2308 } 2309 break; 2310 } 2311 case MODE_Html: { 2312 if( p->cnt++==0 && p->showHeader ){ 2313 raw_printf(p->out,"<TR>"); 2314 for(i=0; i<nArg; i++){ 2315 raw_printf(p->out,"<TH>"); 2316 output_html_string(p->out, azCol[i]); 2317 raw_printf(p->out,"</TH>\n"); 2318 } 2319 raw_printf(p->out,"</TR>\n"); 2320 } 2321 if( azArg==0 ) break; 2322 raw_printf(p->out,"<TR>"); 2323 for(i=0; i<nArg; i++){ 2324 raw_printf(p->out,"<TD>"); 2325 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2326 raw_printf(p->out,"</TD>\n"); 2327 } 2328 raw_printf(p->out,"</TR>\n"); 2329 break; 2330 } 2331 case MODE_Tcl: { 2332 if( p->cnt++==0 && p->showHeader ){ 2333 for(i=0; i<nArg; i++){ 2334 output_c_string(p->out,azCol[i] ? azCol[i] : ""); 2335 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2336 } 2337 utf8_printf(p->out, "%s", p->rowSeparator); 2338 } 2339 if( azArg==0 ) break; 2340 for(i=0; i<nArg; i++){ 2341 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); 2342 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); 2343 } 2344 utf8_printf(p->out, "%s", p->rowSeparator); 2345 break; 2346 } 2347 case MODE_Csv: { 2348 setBinaryMode(p->out, 1); 2349 if( p->cnt++==0 && p->showHeader ){ 2350 for(i=0; i<nArg; i++){ 2351 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); 2352 } 2353 utf8_printf(p->out, "%s", p->rowSeparator); 2354 } 2355 if( nArg>0 ){ 2356 for(i=0; i<nArg; i++){ 2357 output_csv(p, azArg[i], i<nArg-1); 2358 } 2359 utf8_printf(p->out, "%s", p->rowSeparator); 2360 } 2361 setTextMode(p->out, 1); 2362 break; 2363 } 2364 case MODE_Insert: { 2365 if( azArg==0 ) break; 2366 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); 2367 if( p->showHeader ){ 2368 raw_printf(p->out,"("); 2369 for(i=0; i<nArg; i++){ 2370 if( i>0 ) raw_printf(p->out, ","); 2371 if( quoteChar(azCol[i]) ){ 2372 char *z = sqlite3_mprintf("\"%w\"", azCol[i]); 2373 shell_check_oom(z); 2374 utf8_printf(p->out, "%s", z); 2375 sqlite3_free(z); 2376 }else{ 2377 raw_printf(p->out, "%s", azCol[i]); 2378 } 2379 } 2380 raw_printf(p->out,")"); 2381 } 2382 p->cnt++; 2383 for(i=0; i<nArg; i++){ 2384 raw_printf(p->out, i>0 ? "," : " VALUES("); 2385 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2386 utf8_printf(p->out,"NULL"); 2387 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2388 if( ShellHasFlag(p, SHFLG_Newlines) ){ 2389 output_quoted_string(p->out, azArg[i]); 2390 }else{ 2391 output_quoted_escaped_string(p->out, azArg[i]); 2392 } 2393 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2394 utf8_printf(p->out,"%s", azArg[i]); 2395 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2396 char z[50]; 2397 double r = sqlite3_column_double(p->pStmt, i); 2398 sqlite3_uint64 ur; 2399 memcpy(&ur,&r,sizeof(r)); 2400 if( ur==0x7ff0000000000000LL ){ 2401 raw_printf(p->out, "1e999"); 2402 }else if( ur==0xfff0000000000000LL ){ 2403 raw_printf(p->out, "-1e999"); 2404 }else{ 2405 sqlite3_int64 ir = (sqlite3_int64)r; 2406 if( r==(double)ir ){ 2407 sqlite3_snprintf(50,z,"%lld.0", ir); 2408 }else{ 2409 sqlite3_snprintf(50,z,"%!.20g", r); 2410 } 2411 raw_printf(p->out, "%s", z); 2412 } 2413 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2414 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2415 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2416 output_hex_blob(p->out, pBlob, nBlob); 2417 }else if( isNumber(azArg[i], 0) ){ 2418 utf8_printf(p->out,"%s", azArg[i]); 2419 }else if( ShellHasFlag(p, SHFLG_Newlines) ){ 2420 output_quoted_string(p->out, azArg[i]); 2421 }else{ 2422 output_quoted_escaped_string(p->out, azArg[i]); 2423 } 2424 } 2425 raw_printf(p->out,");\n"); 2426 break; 2427 } 2428 case MODE_Json: { 2429 if( azArg==0 ) break; 2430 if( p->cnt==0 ){ 2431 fputs("[{", p->out); 2432 }else{ 2433 fputs(",\n{", p->out); 2434 } 2435 p->cnt++; 2436 for(i=0; i<nArg; i++){ 2437 output_json_string(p->out, azCol[i], -1); 2438 putc(':', p->out); 2439 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2440 fputs("null",p->out); 2441 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2442 char z[50]; 2443 double r = sqlite3_column_double(p->pStmt, i); 2444 sqlite3_uint64 ur; 2445 memcpy(&ur,&r,sizeof(r)); 2446 if( ur==0x7ff0000000000000LL ){ 2447 raw_printf(p->out, "1e999"); 2448 }else if( ur==0xfff0000000000000LL ){ 2449 raw_printf(p->out, "-1e999"); 2450 }else{ 2451 sqlite3_snprintf(50,z,"%!.20g", r); 2452 raw_printf(p->out, "%s", z); 2453 } 2454 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2455 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2456 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2457 output_json_string(p->out, pBlob, nBlob); 2458 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2459 output_json_string(p->out, azArg[i], -1); 2460 }else{ 2461 utf8_printf(p->out,"%s", azArg[i]); 2462 } 2463 if( i<nArg-1 ){ 2464 putc(',', p->out); 2465 } 2466 } 2467 putc('}', p->out); 2468 break; 2469 } 2470 case MODE_Quote: { 2471 if( azArg==0 ) break; 2472 if( p->cnt==0 && p->showHeader ){ 2473 for(i=0; i<nArg; i++){ 2474 if( i>0 ) fputs(p->colSeparator, p->out); 2475 output_quoted_string(p->out, azCol[i]); 2476 } 2477 fputs(p->rowSeparator, p->out); 2478 } 2479 p->cnt++; 2480 for(i=0; i<nArg; i++){ 2481 if( i>0 ) fputs(p->colSeparator, p->out); 2482 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ 2483 utf8_printf(p->out,"NULL"); 2484 }else if( aiType && aiType[i]==SQLITE_TEXT ){ 2485 output_quoted_string(p->out, azArg[i]); 2486 }else if( aiType && aiType[i]==SQLITE_INTEGER ){ 2487 utf8_printf(p->out,"%s", azArg[i]); 2488 }else if( aiType && aiType[i]==SQLITE_FLOAT ){ 2489 char z[50]; 2490 double r = sqlite3_column_double(p->pStmt, i); 2491 sqlite3_snprintf(50,z,"%!.20g", r); 2492 raw_printf(p->out, "%s", z); 2493 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ 2494 const void *pBlob = sqlite3_column_blob(p->pStmt, i); 2495 int nBlob = sqlite3_column_bytes(p->pStmt, i); 2496 output_hex_blob(p->out, pBlob, nBlob); 2497 }else if( isNumber(azArg[i], 0) ){ 2498 utf8_printf(p->out,"%s", azArg[i]); 2499 }else{ 2500 output_quoted_string(p->out, azArg[i]); 2501 } 2502 } 2503 fputs(p->rowSeparator, p->out); 2504 break; 2505 } 2506 case MODE_Ascii: { 2507 if( p->cnt++==0 && p->showHeader ){ 2508 for(i=0; i<nArg; i++){ 2509 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2510 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); 2511 } 2512 utf8_printf(p->out, "%s", p->rowSeparator); 2513 } 2514 if( azArg==0 ) break; 2515 for(i=0; i<nArg; i++){ 2516 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); 2517 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); 2518 } 2519 utf8_printf(p->out, "%s", p->rowSeparator); 2520 break; 2521 } 2522 case MODE_EQP: { 2523 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]); 2524 break; 2525 } 2526 } 2527 return 0; 2528} 2529 2530/* 2531** This is the callback routine that the SQLite library 2532** invokes for each row of a query result. 2533*/ 2534static int callback(void *pArg, int nArg, char **azArg, char **azCol){ 2535 /* since we don't have type info, call the shell_callback with a NULL value */ 2536 return shell_callback(pArg, nArg, azArg, azCol, NULL); 2537} 2538 2539/* 2540** This is the callback routine from sqlite3_exec() that appends all 2541** output onto the end of a ShellText object. 2542*/ 2543static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){ 2544 ShellText *p = (ShellText*)pArg; 2545 int i; 2546 UNUSED_PARAMETER(az); 2547 if( azArg==0 ) return 0; 2548 if( p->n ) appendText(p, "|", 0); 2549 for(i=0; i<nArg; i++){ 2550 if( i ) appendText(p, ",", 0); 2551 if( azArg[i] ) appendText(p, azArg[i], 0); 2552 } 2553 return 0; 2554} 2555 2556/* 2557** Generate an appropriate SELFTEST table in the main database. 2558*/ 2559static void createSelftestTable(ShellState *p){ 2560 char *zErrMsg = 0; 2561 sqlite3_exec(p->db, 2562 "SAVEPOINT selftest_init;\n" 2563 "CREATE TABLE IF NOT EXISTS selftest(\n" 2564 " tno INTEGER PRIMARY KEY,\n" /* Test number */ 2565 " op TEXT,\n" /* Operator: memo run */ 2566 " cmd TEXT,\n" /* Command text */ 2567 " ans TEXT\n" /* Desired answer */ 2568 ");" 2569 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n" 2570 "INSERT INTO [_shell$self](rowid,op,cmd)\n" 2571 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n" 2572 " 'memo','Tests generated by --init');\n" 2573 "INSERT INTO [_shell$self]\n" 2574 " SELECT 'run',\n" 2575 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql " 2576 "FROM sqlite_schema ORDER BY 2'',224))',\n" 2577 " hex(sha3_query('SELECT type,name,tbl_name,sql " 2578 "FROM sqlite_schema ORDER BY 2',224));\n" 2579 "INSERT INTO [_shell$self]\n" 2580 " SELECT 'run'," 2581 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||" 2582 " printf('%w',name) || '\" NOT INDEXED'',224))',\n" 2583 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n" 2584 " FROM (\n" 2585 " SELECT name FROM sqlite_schema\n" 2586 " WHERE type='table'\n" 2587 " AND name<>'selftest'\n" 2588 " AND coalesce(rootpage,0)>0\n" 2589 " )\n" 2590 " ORDER BY name;\n" 2591 "INSERT INTO [_shell$self]\n" 2592 " VALUES('run','PRAGMA integrity_check','ok');\n" 2593 "INSERT INTO selftest(tno,op,cmd,ans)" 2594 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n" 2595 "DROP TABLE [_shell$self];" 2596 ,0,0,&zErrMsg); 2597 if( zErrMsg ){ 2598 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg); 2599 sqlite3_free(zErrMsg); 2600 } 2601 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0); 2602} 2603 2604 2605/* 2606** Set the destination table field of the ShellState structure to 2607** the name of the table given. Escape any quote characters in the 2608** table name. 2609*/ 2610static void set_table_name(ShellState *p, const char *zName){ 2611 int i, n; 2612 char cQuote; 2613 char *z; 2614 2615 if( p->zDestTable ){ 2616 free(p->zDestTable); 2617 p->zDestTable = 0; 2618 } 2619 if( zName==0 ) return; 2620 cQuote = quoteChar(zName); 2621 n = strlen30(zName); 2622 if( cQuote ) n += n+2; 2623 z = p->zDestTable = malloc( n+1 ); 2624 shell_check_oom(z); 2625 n = 0; 2626 if( cQuote ) z[n++] = cQuote; 2627 for(i=0; zName[i]; i++){ 2628 z[n++] = zName[i]; 2629 if( zName[i]==cQuote ) z[n++] = cQuote; 2630 } 2631 if( cQuote ) z[n++] = cQuote; 2632 z[n] = 0; 2633} 2634 2635/* 2636** Maybe construct two lines of text that point out the position of a 2637** syntax error. Return a pointer to the text, in memory obtained from 2638** sqlite3_malloc(). Or, if the most recent error does not involve a 2639** specific token that we can point to, return an empty string. 2640** 2641** In all cases, the memory returned is obtained from sqlite3_malloc64() 2642** and should be released by the caller invoking sqlite3_free(). 2643*/ 2644static char *shell_error_context(const char *zSql, sqlite3 *db){ 2645 int iOffset; 2646 size_t len; 2647 char *zCode; 2648 char *zMsg; 2649 int i; 2650 if( db==0 2651 || zSql==0 2652 || (iOffset = sqlite3_error_offset(db))<0 2653 ){ 2654 return sqlite3_mprintf(""); 2655 } 2656 while( iOffset>50 ){ 2657 iOffset--; 2658 zSql++; 2659 while( (zSql[0]&0xc0)==0x80 ){ zSql++; iOffset--; } 2660 } 2661 len = strlen(zSql); 2662 if( len>78 ){ 2663 len = 78; 2664 while( (zSql[len]&0xc0)==0x80 ) len--; 2665 } 2666 zCode = sqlite3_mprintf("%.*s", len, zSql); 2667 for(i=0; zCode[i]; i++){ if( IsSpace(zSql[i]) ) zCode[i] = ' '; } 2668 if( iOffset<25 ){ 2669 zMsg = sqlite3_mprintf("\n %z\n %*s^--- error here", zCode, iOffset, ""); 2670 }else{ 2671 zMsg = sqlite3_mprintf("\n %z\n %*serror here ---^", zCode, iOffset-14, ""); 2672 } 2673 return zMsg; 2674} 2675 2676 2677/* 2678** Execute a query statement that will generate SQL output. Print 2679** the result columns, comma-separated, on a line and then add a 2680** semicolon terminator to the end of that line. 2681** 2682** If the number of columns is 1 and that column contains text "--" 2683** then write the semicolon on a separate line. That way, if a 2684** "--" comment occurs at the end of the statement, the comment 2685** won't consume the semicolon terminator. 2686*/ 2687static int run_table_dump_query( 2688 ShellState *p, /* Query context */ 2689 const char *zSelect /* SELECT statement to extract content */ 2690){ 2691 sqlite3_stmt *pSelect; 2692 int rc; 2693 int nResult; 2694 int i; 2695 const char *z; 2696 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); 2697 if( rc!=SQLITE_OK || !pSelect ){ 2698 char *zContext = shell_error_context(zSelect, p->db); 2699 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n%s", rc, 2700 sqlite3_errmsg(p->db), zContext); 2701 sqlite3_free(zContext); 2702 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2703 return rc; 2704 } 2705 rc = sqlite3_step(pSelect); 2706 nResult = sqlite3_column_count(pSelect); 2707 while( rc==SQLITE_ROW ){ 2708 z = (const char*)sqlite3_column_text(pSelect, 0); 2709 utf8_printf(p->out, "%s", z); 2710 for(i=1; i<nResult; i++){ 2711 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); 2712 } 2713 if( z==0 ) z = ""; 2714 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; 2715 if( z[0] ){ 2716 raw_printf(p->out, "\n;\n"); 2717 }else{ 2718 raw_printf(p->out, ";\n"); 2719 } 2720 rc = sqlite3_step(pSelect); 2721 } 2722 rc = sqlite3_finalize(pSelect); 2723 if( rc!=SQLITE_OK ){ 2724 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, 2725 sqlite3_errmsg(p->db)); 2726 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; 2727 } 2728 return rc; 2729} 2730 2731/* 2732** Allocate space and save off string indicating current error. 2733*/ 2734static char *save_err_msg( 2735 sqlite3 *db, /* Database to query */ 2736 const char *zPhase, /* When the error occcurs */ 2737 int rc, /* Error code returned from API */ 2738 const char *zSql /* SQL string, or NULL */ 2739){ 2740 char *zErr; 2741 char *zContext; 2742 sqlite3_str *pStr = sqlite3_str_new(0); 2743 sqlite3_str_appendf(pStr, "%s, %s", zPhase, sqlite3_errmsg(db)); 2744 if( rc>1 ){ 2745 sqlite3_str_appendf(pStr, " (%d)", rc); 2746 } 2747 zContext = shell_error_context(zSql, db); 2748 if( zContext ){ 2749 sqlite3_str_appendall(pStr, zContext); 2750 sqlite3_free(zContext); 2751 } 2752 zErr = sqlite3_str_finish(pStr); 2753 shell_check_oom(zErr); 2754 return zErr; 2755} 2756 2757#ifdef __linux__ 2758/* 2759** Attempt to display I/O stats on Linux using /proc/PID/io 2760*/ 2761static void displayLinuxIoStats(FILE *out){ 2762 FILE *in; 2763 char z[200]; 2764 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); 2765 in = fopen(z, "rb"); 2766 if( in==0 ) return; 2767 while( fgets(z, sizeof(z), in)!=0 ){ 2768 static const struct { 2769 const char *zPattern; 2770 const char *zDesc; 2771 } aTrans[] = { 2772 { "rchar: ", "Bytes received by read():" }, 2773 { "wchar: ", "Bytes sent to write():" }, 2774 { "syscr: ", "Read() system calls:" }, 2775 { "syscw: ", "Write() system calls:" }, 2776 { "read_bytes: ", "Bytes read from storage:" }, 2777 { "write_bytes: ", "Bytes written to storage:" }, 2778 { "cancelled_write_bytes: ", "Cancelled write bytes:" }, 2779 }; 2780 int i; 2781 for(i=0; i<ArraySize(aTrans); i++){ 2782 int n = strlen30(aTrans[i].zPattern); 2783 if( cli_strncmp(aTrans[i].zPattern, z, n)==0 ){ 2784 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); 2785 break; 2786 } 2787 } 2788 } 2789 fclose(in); 2790} 2791#endif 2792 2793/* 2794** Display a single line of status using 64-bit values. 2795*/ 2796static void displayStatLine( 2797 ShellState *p, /* The shell context */ 2798 char *zLabel, /* Label for this one line */ 2799 char *zFormat, /* Format for the result */ 2800 int iStatusCtrl, /* Which status to display */ 2801 int bReset /* True to reset the stats */ 2802){ 2803 sqlite3_int64 iCur = -1; 2804 sqlite3_int64 iHiwtr = -1; 2805 int i, nPercent; 2806 char zLine[200]; 2807 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset); 2808 for(i=0, nPercent=0; zFormat[i]; i++){ 2809 if( zFormat[i]=='%' ) nPercent++; 2810 } 2811 if( nPercent>1 ){ 2812 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr); 2813 }else{ 2814 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr); 2815 } 2816 raw_printf(p->out, "%-36s %s\n", zLabel, zLine); 2817} 2818 2819/* 2820** Display memory stats. 2821*/ 2822static int display_stats( 2823 sqlite3 *db, /* Database to query */ 2824 ShellState *pArg, /* Pointer to ShellState */ 2825 int bReset /* True to reset the stats */ 2826){ 2827 int iCur; 2828 int iHiwtr; 2829 FILE *out; 2830 if( pArg==0 || pArg->out==0 ) return 0; 2831 out = pArg->out; 2832 2833 if( pArg->pStmt && pArg->statsOn==2 ){ 2834 int nCol, i, x; 2835 sqlite3_stmt *pStmt = pArg->pStmt; 2836 char z[100]; 2837 nCol = sqlite3_column_count(pStmt); 2838 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol); 2839 for(i=0; i<nCol; i++){ 2840 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x); 2841 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i)); 2842#ifndef SQLITE_OMIT_DECLTYPE 2843 sqlite3_snprintf(30, z+x, "declared type:"); 2844 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i)); 2845#endif 2846#ifdef SQLITE_ENABLE_COLUMN_METADATA 2847 sqlite3_snprintf(30, z+x, "database name:"); 2848 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i)); 2849 sqlite3_snprintf(30, z+x, "table name:"); 2850 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i)); 2851 sqlite3_snprintf(30, z+x, "origin name:"); 2852 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i)); 2853#endif 2854 } 2855 } 2856 2857 if( pArg->statsOn==3 ){ 2858 if( pArg->pStmt ){ 2859 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2860 raw_printf(pArg->out, "VM-steps: %d\n", iCur); 2861 } 2862 return 0; 2863 } 2864 2865 displayStatLine(pArg, "Memory Used:", 2866 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset); 2867 displayStatLine(pArg, "Number of Outstanding Allocations:", 2868 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset); 2869 if( pArg->shellFlgs & SHFLG_Pagecache ){ 2870 displayStatLine(pArg, "Number of Pcache Pages Used:", 2871 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset); 2872 } 2873 displayStatLine(pArg, "Number of Pcache Overflow Bytes:", 2874 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset); 2875 displayStatLine(pArg, "Largest Allocation:", 2876 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset); 2877 displayStatLine(pArg, "Largest Pcache Allocation:", 2878 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset); 2879#ifdef YYTRACKMAXSTACKDEPTH 2880 displayStatLine(pArg, "Deepest Parser Stack:", 2881 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset); 2882#endif 2883 2884 if( db ){ 2885 if( pArg->shellFlgs & SHFLG_Lookaside ){ 2886 iHiwtr = iCur = -1; 2887 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, 2888 &iCur, &iHiwtr, bReset); 2889 raw_printf(pArg->out, 2890 "Lookaside Slots Used: %d (max %d)\n", 2891 iCur, iHiwtr); 2892 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, 2893 &iCur, &iHiwtr, bReset); 2894 raw_printf(pArg->out, "Successful lookaside attempts: %d\n", 2895 iHiwtr); 2896 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, 2897 &iCur, &iHiwtr, bReset); 2898 raw_printf(pArg->out, "Lookaside failures due to size: %d\n", 2899 iHiwtr); 2900 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, 2901 &iCur, &iHiwtr, bReset); 2902 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", 2903 iHiwtr); 2904 } 2905 iHiwtr = iCur = -1; 2906 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); 2907 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", 2908 iCur); 2909 iHiwtr = iCur = -1; 2910 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); 2911 raw_printf(pArg->out, "Page cache hits: %d\n", iCur); 2912 iHiwtr = iCur = -1; 2913 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); 2914 raw_printf(pArg->out, "Page cache misses: %d\n", iCur); 2915 iHiwtr = iCur = -1; 2916 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); 2917 raw_printf(pArg->out, "Page cache writes: %d\n", iCur); 2918 iHiwtr = iCur = -1; 2919 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1); 2920 raw_printf(pArg->out, "Page cache spills: %d\n", iCur); 2921 iHiwtr = iCur = -1; 2922 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); 2923 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", 2924 iCur); 2925 iHiwtr = iCur = -1; 2926 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); 2927 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", 2928 iCur); 2929 } 2930 2931 if( pArg->pStmt ){ 2932 int iHit, iMiss; 2933 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, 2934 bReset); 2935 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); 2936 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); 2937 raw_printf(pArg->out, "Sort Operations: %d\n", iCur); 2938 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); 2939 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); 2940 iHit = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_HIT, bReset); 2941 iMiss = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FILTER_MISS, bReset); 2942 if( iHit || iMiss ){ 2943 raw_printf(pArg->out, "Bloom filter bypass taken: %d/%d\n", 2944 iHit, iHit+iMiss); 2945 } 2946 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); 2947 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); 2948 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE,bReset); 2949 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur); 2950 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset); 2951 raw_printf(pArg->out, "Number of times run: %d\n", iCur); 2952 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset); 2953 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur); 2954 } 2955 2956#ifdef __linux__ 2957 displayLinuxIoStats(pArg->out); 2958#endif 2959 2960 /* Do not remove this machine readable comment: extra-stats-output-here */ 2961 2962 return 0; 2963} 2964 2965/* 2966** Display scan stats. 2967*/ 2968static void display_scanstats( 2969 sqlite3 *db, /* Database to query */ 2970 ShellState *pArg /* Pointer to ShellState */ 2971){ 2972#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 2973 UNUSED_PARAMETER(db); 2974 UNUSED_PARAMETER(pArg); 2975#else 2976 int i, k, n, mx; 2977 raw_printf(pArg->out, "-------- scanstats --------\n"); 2978 mx = 0; 2979 for(k=0; k<=mx; k++){ 2980 double rEstLoop = 1.0; 2981 for(i=n=0; 1; i++){ 2982 sqlite3_stmt *p = pArg->pStmt; 2983 sqlite3_int64 nLoop, nVisit; 2984 double rEst; 2985 int iSid; 2986 const char *zExplain; 2987 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ 2988 break; 2989 } 2990 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); 2991 if( iSid>mx ) mx = iSid; 2992 if( iSid!=k ) continue; 2993 if( n==0 ){ 2994 rEstLoop = (double)nLoop; 2995 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); 2996 } 2997 n++; 2998 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); 2999 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); 3000 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); 3001 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); 3002 rEstLoop *= rEst; 3003 raw_printf(pArg->out, 3004 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", 3005 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst 3006 ); 3007 } 3008 } 3009 raw_printf(pArg->out, "---------------------------\n"); 3010#endif 3011} 3012 3013/* 3014** Parameter azArray points to a zero-terminated array of strings. zStr 3015** points to a single nul-terminated string. Return non-zero if zStr 3016** is equal, according to strcmp(), to any of the strings in the array. 3017** Otherwise, return zero. 3018*/ 3019static int str_in_array(const char *zStr, const char **azArray){ 3020 int i; 3021 for(i=0; azArray[i]; i++){ 3022 if( 0==cli_strcmp(zStr, azArray[i]) ) return 1; 3023 } 3024 return 0; 3025} 3026 3027/* 3028** If compiled statement pSql appears to be an EXPLAIN statement, allocate 3029** and populate the ShellState.aiIndent[] array with the number of 3030** spaces each opcode should be indented before it is output. 3031** 3032** The indenting rules are: 3033** 3034** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent 3035** all opcodes that occur between the p2 jump destination and the opcode 3036** itself by 2 spaces. 3037** 3038** * Do the previous for "Return" instructions for when P2 is positive. 3039** See tag-20220407a in wherecode.c and vdbe.c. 3040** 3041** * For each "Goto", if the jump destination is earlier in the program 3042** and ends on one of: 3043** Yield SeekGt SeekLt RowSetRead Rewind 3044** or if the P1 parameter is one instead of zero, 3045** then indent all opcodes between the earlier instruction 3046** and "Goto" by 2 spaces. 3047*/ 3048static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ 3049 const char *zSql; /* The text of the SQL statement */ 3050 const char *z; /* Used to check if this is an EXPLAIN */ 3051 int *abYield = 0; /* True if op is an OP_Yield */ 3052 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ 3053 int iOp; /* Index of operation in p->aiIndent[] */ 3054 3055 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 3056 "Return", 0 }; 3057 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", 3058 "Rewind", 0 }; 3059 const char *azGoto[] = { "Goto", 0 }; 3060 3061 /* Try to figure out if this is really an EXPLAIN statement. If this 3062 ** cannot be verified, return early. */ 3063 if( sqlite3_column_count(pSql)!=8 ){ 3064 p->cMode = p->mode; 3065 return; 3066 } 3067 zSql = sqlite3_sql(pSql); 3068 if( zSql==0 ) return; 3069 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); 3070 if( sqlite3_strnicmp(z, "explain", 7) ){ 3071 p->cMode = p->mode; 3072 return; 3073 } 3074 3075 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ 3076 int i; 3077 int iAddr = sqlite3_column_int(pSql, 0); 3078 const char *zOp = (const char*)sqlite3_column_text(pSql, 1); 3079 3080 /* Set p2 to the P2 field of the current opcode. Then, assuming that 3081 ** p2 is an instruction address, set variable p2op to the index of that 3082 ** instruction in the aiIndent[] array. p2 and p2op may be different if 3083 ** the current instruction is part of a sub-program generated by an 3084 ** SQL trigger or foreign key. */ 3085 int p2 = sqlite3_column_int(pSql, 3); 3086 int p2op = (p2 + (iOp-iAddr)); 3087 3088 /* Grow the p->aiIndent array as required */ 3089 if( iOp>=nAlloc ){ 3090 if( iOp==0 ){ 3091 /* Do further verfication that this is explain output. Abort if 3092 ** it is not */ 3093 static const char *explainCols[] = { 3094 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; 3095 int jj; 3096 for(jj=0; jj<ArraySize(explainCols); jj++){ 3097 if( cli_strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ 3098 p->cMode = p->mode; 3099 sqlite3_reset(pSql); 3100 return; 3101 } 3102 } 3103 } 3104 nAlloc += 100; 3105 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); 3106 shell_check_oom(p->aiIndent); 3107 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); 3108 shell_check_oom(abYield); 3109 } 3110 abYield[iOp] = str_in_array(zOp, azYield); 3111 p->aiIndent[iOp] = 0; 3112 p->nIndent = iOp+1; 3113 3114 if( str_in_array(zOp, azNext) && p2op>0 ){ 3115 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 3116 } 3117 if( str_in_array(zOp, azGoto) && p2op<p->nIndent 3118 && (abYield[p2op] || sqlite3_column_int(pSql, 2)) 3119 ){ 3120 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; 3121 } 3122 } 3123 3124 p->iIndent = 0; 3125 sqlite3_free(abYield); 3126 sqlite3_reset(pSql); 3127} 3128 3129/* 3130** Free the array allocated by explain_data_prepare(). 3131*/ 3132static void explain_data_delete(ShellState *p){ 3133 sqlite3_free(p->aiIndent); 3134 p->aiIndent = 0; 3135 p->nIndent = 0; 3136 p->iIndent = 0; 3137} 3138 3139/* 3140** Disable and restore .wheretrace and .treetrace/.selecttrace settings. 3141*/ 3142static unsigned int savedSelectTrace; 3143static unsigned int savedWhereTrace; 3144static void disable_debug_trace_modes(void){ 3145 unsigned int zero = 0; 3146 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace); 3147 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero); 3148 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace); 3149 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero); 3150} 3151static void restore_debug_trace_modes(void){ 3152 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace); 3153 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace); 3154} 3155 3156/* Create the TEMP table used to store parameter bindings */ 3157static void bind_table_init(ShellState *p){ 3158 int wrSchema = 0; 3159 int defensiveMode = 0; 3160 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode); 3161 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0); 3162 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema); 3163 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 3164 sqlite3_exec(p->db, 3165 "CREATE TABLE IF NOT EXISTS temp.sqlite_parameters(\n" 3166 " key TEXT PRIMARY KEY,\n" 3167 " value\n" 3168 ") WITHOUT ROWID;", 3169 0, 0, 0); 3170 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0); 3171 sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0); 3172} 3173 3174/* 3175** Bind parameters on a prepared statement. 3176** 3177** Parameter bindings are taken from a TEMP table of the form: 3178** 3179** CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value) 3180** WITHOUT ROWID; 3181** 3182** No bindings occur if this table does not exist. The name of the table 3183** begins with "sqlite_" so that it will not collide with ordinary application 3184** tables. The table must be in the TEMP schema. 3185*/ 3186static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){ 3187 int nVar; 3188 int i; 3189 int rc; 3190 sqlite3_stmt *pQ = 0; 3191 3192 nVar = sqlite3_bind_parameter_count(pStmt); 3193 if( nVar==0 ) return; /* Nothing to do */ 3194 if( sqlite3_table_column_metadata(pArg->db, "TEMP", "sqlite_parameters", 3195 "key", 0, 0, 0, 0, 0)!=SQLITE_OK ){ 3196 return; /* Parameter table does not exist */ 3197 } 3198 rc = sqlite3_prepare_v2(pArg->db, 3199 "SELECT value FROM temp.sqlite_parameters" 3200 " WHERE key=?1", -1, &pQ, 0); 3201 if( rc || pQ==0 ) return; 3202 for(i=1; i<=nVar; i++){ 3203 char zNum[30]; 3204 const char *zVar = sqlite3_bind_parameter_name(pStmt, i); 3205 if( zVar==0 ){ 3206 sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i); 3207 zVar = zNum; 3208 } 3209 sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC); 3210 if( sqlite3_step(pQ)==SQLITE_ROW ){ 3211 sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0)); 3212 }else{ 3213 sqlite3_bind_null(pStmt, i); 3214 } 3215 sqlite3_reset(pQ); 3216 } 3217 sqlite3_finalize(pQ); 3218} 3219 3220/* 3221** UTF8 box-drawing characters. Imagine box lines like this: 3222** 3223** 1 3224** | 3225** 4 --+-- 2 3226** | 3227** 3 3228** 3229** Each box characters has between 2 and 4 of the lines leading from 3230** the center. The characters are here identified by the numbers of 3231** their corresponding lines. 3232*/ 3233#define BOX_24 "\342\224\200" /* U+2500 --- */ 3234#define BOX_13 "\342\224\202" /* U+2502 | */ 3235#define BOX_23 "\342\224\214" /* U+250c ,- */ 3236#define BOX_34 "\342\224\220" /* U+2510 -, */ 3237#define BOX_12 "\342\224\224" /* U+2514 '- */ 3238#define BOX_14 "\342\224\230" /* U+2518 -' */ 3239#define BOX_123 "\342\224\234" /* U+251c |- */ 3240#define BOX_134 "\342\224\244" /* U+2524 -| */ 3241#define BOX_234 "\342\224\254" /* U+252c -,- */ 3242#define BOX_124 "\342\224\264" /* U+2534 -'- */ 3243#define BOX_1234 "\342\224\274" /* U+253c -|- */ 3244 3245/* Draw horizontal line N characters long using unicode box 3246** characters 3247*/ 3248static void print_box_line(FILE *out, int N){ 3249 const char zDash[] = 3250 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 3251 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24; 3252 const int nDash = sizeof(zDash) - 1; 3253 N *= 3; 3254 while( N>nDash ){ 3255 utf8_printf(out, zDash); 3256 N -= nDash; 3257 } 3258 utf8_printf(out, "%.*s", N, zDash); 3259} 3260 3261/* 3262** Draw a horizontal separator for a MODE_Box table. 3263*/ 3264static void print_box_row_separator( 3265 ShellState *p, 3266 int nArg, 3267 const char *zSep1, 3268 const char *zSep2, 3269 const char *zSep3 3270){ 3271 int i; 3272 if( nArg>0 ){ 3273 utf8_printf(p->out, "%s", zSep1); 3274 print_box_line(p->out, p->actualWidth[0]+2); 3275 for(i=1; i<nArg; i++){ 3276 utf8_printf(p->out, "%s", zSep2); 3277 print_box_line(p->out, p->actualWidth[i]+2); 3278 } 3279 utf8_printf(p->out, "%s", zSep3); 3280 } 3281 fputs("\n", p->out); 3282} 3283 3284/* 3285** z[] is a line of text that is to be displayed the .mode box or table or 3286** similar tabular formats. z[] might contain control characters such 3287** as \n, \t, \f, or \r. 3288** 3289** Compute characters to display on the first line of z[]. Stop at the 3290** first \r, \n, or \f. Expand \t into spaces. Return a copy (obtained 3291** from malloc()) of that first line, which caller should free sometime. 3292** Write anything to display on the next line into *pzTail. If this is 3293** the last line, write a NULL into *pzTail. (*pzTail is not allocated.) 3294*/ 3295static char *translateForDisplayAndDup( 3296 const unsigned char *z, /* Input text to be transformed */ 3297 const unsigned char **pzTail, /* OUT: Tail of the input for next line */ 3298 int mxWidth, /* Max width. 0 means no limit */ 3299 u8 bWordWrap /* If true, avoid breaking mid-word */ 3300){ 3301 int i; /* Input bytes consumed */ 3302 int j; /* Output bytes generated */ 3303 int k; /* Input bytes to be displayed */ 3304 int n; /* Output column number */ 3305 unsigned char *zOut; /* Output text */ 3306 3307 if( z==0 ){ 3308 *pzTail = 0; 3309 return 0; 3310 } 3311 if( mxWidth<0 ) mxWidth = -mxWidth; 3312 if( mxWidth==0 ) mxWidth = 1000000; 3313 i = j = n = 0; 3314 while( n<mxWidth ){ 3315 if( z[i]>=' ' ){ 3316 n++; 3317 do{ i++; j++; }while( (z[i]&0xc0)==0x80 ); 3318 continue; 3319 } 3320 if( z[i]=='\t' ){ 3321 do{ 3322 n++; 3323 j++; 3324 }while( (n&7)!=0 && n<mxWidth ); 3325 i++; 3326 continue; 3327 } 3328 break; 3329 } 3330 if( n>=mxWidth && bWordWrap ){ 3331 /* Perhaps try to back up to a better place to break the line */ 3332 for(k=i; k>i/2; k--){ 3333 if( isspace(z[k-1]) ) break; 3334 } 3335 if( k<=i/2 ){ 3336 for(k=i; k>i/2; k--){ 3337 if( isalnum(z[k-1])!=isalnum(z[k]) && (z[k]&0xc0)!=0x80 ) break; 3338 } 3339 } 3340 if( k<=i/2 ){ 3341 k = i; 3342 }else{ 3343 i = k; 3344 while( z[i]==' ' ) i++; 3345 } 3346 }else{ 3347 k = i; 3348 } 3349 if( n>=mxWidth && z[i]>=' ' ){ 3350 *pzTail = &z[i]; 3351 }else if( z[i]=='\r' && z[i+1]=='\n' ){ 3352 *pzTail = z[i+2] ? &z[i+2] : 0; 3353 }else if( z[i]==0 || z[i+1]==0 ){ 3354 *pzTail = 0; 3355 }else{ 3356 *pzTail = &z[i+1]; 3357 } 3358 zOut = malloc( j+1 ); 3359 shell_check_oom(zOut); 3360 i = j = n = 0; 3361 while( i<k ){ 3362 if( z[i]>=' ' ){ 3363 n++; 3364 do{ zOut[j++] = z[i++]; }while( (z[i]&0xc0)==0x80 ); 3365 continue; 3366 } 3367 if( z[i]=='\t' ){ 3368 do{ 3369 n++; 3370 zOut[j++] = ' '; 3371 }while( (n&7)!=0 && n<mxWidth ); 3372 i++; 3373 continue; 3374 } 3375 break; 3376 } 3377 zOut[j] = 0; 3378 return (char*)zOut; 3379} 3380 3381/* Extract the value of the i-th current column for pStmt as an SQL literal 3382** value. Memory is obtained from sqlite3_malloc64() and must be freed by 3383** the caller. 3384*/ 3385static char *quoted_column(sqlite3_stmt *pStmt, int i){ 3386 switch( sqlite3_column_type(pStmt, i) ){ 3387 case SQLITE_NULL: { 3388 return sqlite3_mprintf("NULL"); 3389 } 3390 case SQLITE_INTEGER: 3391 case SQLITE_FLOAT: { 3392 return sqlite3_mprintf("%s",sqlite3_column_text(pStmt,i)); 3393 } 3394 case SQLITE_TEXT: { 3395 return sqlite3_mprintf("%Q",sqlite3_column_text(pStmt,i)); 3396 } 3397 case SQLITE_BLOB: { 3398 int j; 3399 sqlite3_str *pStr = sqlite3_str_new(0); 3400 const unsigned char *a = sqlite3_column_blob(pStmt,i); 3401 int n = sqlite3_column_bytes(pStmt,i); 3402 sqlite3_str_append(pStr, "x'", 2); 3403 for(j=0; j<n; j++){ 3404 sqlite3_str_appendf(pStr, "%02x", a[j]); 3405 } 3406 sqlite3_str_append(pStr, "'", 1); 3407 return sqlite3_str_finish(pStr); 3408 } 3409 } 3410 return 0; /* Not reached */ 3411} 3412 3413/* 3414** Run a prepared statement and output the result in one of the 3415** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table, 3416** or MODE_Box. 3417** 3418** This is different from ordinary exec_prepared_stmt() in that 3419** it has to run the entire query and gather the results into memory 3420** first, in order to determine column widths, before providing 3421** any output. 3422*/ 3423static void exec_prepared_stmt_columnar( 3424 ShellState *p, /* Pointer to ShellState */ 3425 sqlite3_stmt *pStmt /* Statment to run */ 3426){ 3427 sqlite3_int64 nRow = 0; 3428 int nColumn = 0; 3429 char **azData = 0; 3430 sqlite3_int64 nAlloc = 0; 3431 char *abRowDiv = 0; 3432 const unsigned char *uz; 3433 const char *z; 3434 char **azQuoted = 0; 3435 int rc; 3436 sqlite3_int64 i, nData; 3437 int j, nTotal, w, n; 3438 const char *colSep = 0; 3439 const char *rowSep = 0; 3440 const unsigned char **azNextLine = 0; 3441 int bNextLine = 0; 3442 int bMultiLineRowExists = 0; 3443 int bw = p->cmOpts.bWordWrap; 3444 const char *zEmpty = ""; 3445 const char *zShowNull = p->nullValue; 3446 3447 rc = sqlite3_step(pStmt); 3448 if( rc!=SQLITE_ROW ) return; 3449 nColumn = sqlite3_column_count(pStmt); 3450 nAlloc = nColumn*4; 3451 if( nAlloc<=0 ) nAlloc = 1; 3452 azData = sqlite3_malloc64( nAlloc*sizeof(char*) ); 3453 shell_check_oom(azData); 3454 azNextLine = sqlite3_malloc64( nColumn*sizeof(char*) ); 3455 shell_check_oom((void*)azNextLine); 3456 memset((void*)azNextLine, 0, nColumn*sizeof(char*) ); 3457 if( p->cmOpts.bQuote ){ 3458 azQuoted = sqlite3_malloc64( nColumn*sizeof(char*) ); 3459 shell_check_oom(azQuoted); 3460 memset(azQuoted, 0, nColumn*sizeof(char*) ); 3461 } 3462 abRowDiv = sqlite3_malloc64( nAlloc/nColumn ); 3463 shell_check_oom(abRowDiv); 3464 if( nColumn>p->nWidth ){ 3465 p->colWidth = realloc(p->colWidth, (nColumn+1)*2*sizeof(int)); 3466 shell_check_oom(p->colWidth); 3467 for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0; 3468 p->nWidth = nColumn; 3469 p->actualWidth = &p->colWidth[nColumn]; 3470 } 3471 memset(p->actualWidth, 0, nColumn*sizeof(int)); 3472 for(i=0; i<nColumn; i++){ 3473 w = p->colWidth[i]; 3474 if( w<0 ) w = -w; 3475 p->actualWidth[i] = w; 3476 } 3477 for(i=0; i<nColumn; i++){ 3478 const unsigned char *zNotUsed; 3479 int wx = p->colWidth[i]; 3480 if( wx==0 ){ 3481 wx = p->cmOpts.iWrap; 3482 } 3483 if( wx<0 ) wx = -wx; 3484 uz = (const unsigned char*)sqlite3_column_name(pStmt,i); 3485 azData[i] = translateForDisplayAndDup(uz, &zNotUsed, wx, bw); 3486 } 3487 do{ 3488 int useNextLine = bNextLine; 3489 bNextLine = 0; 3490 if( (nRow+2)*nColumn >= nAlloc ){ 3491 nAlloc *= 2; 3492 azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*)); 3493 shell_check_oom(azData); 3494 abRowDiv = sqlite3_realloc64(abRowDiv, nAlloc/nColumn); 3495 shell_check_oom(abRowDiv); 3496 } 3497 abRowDiv[nRow] = 1; 3498 nRow++; 3499 for(i=0; i<nColumn; i++){ 3500 int wx = p->colWidth[i]; 3501 if( wx==0 ){ 3502 wx = p->cmOpts.iWrap; 3503 } 3504 if( wx<0 ) wx = -wx; 3505 if( useNextLine ){ 3506 uz = azNextLine[i]; 3507 if( uz==0 ) uz = (u8*)zEmpty; 3508 }else if( p->cmOpts.bQuote ){ 3509 sqlite3_free(azQuoted[i]); 3510 azQuoted[i] = quoted_column(pStmt,i); 3511 uz = (const unsigned char*)azQuoted[i]; 3512 }else{ 3513 uz = (const unsigned char*)sqlite3_column_text(pStmt,i); 3514 if( uz==0 ) uz = (u8*)zShowNull; 3515 } 3516 azData[nRow*nColumn + i] 3517 = translateForDisplayAndDup(uz, &azNextLine[i], wx, bw); 3518 if( azNextLine[i] ){ 3519 bNextLine = 1; 3520 abRowDiv[nRow-1] = 0; 3521 bMultiLineRowExists = 1; 3522 } 3523 } 3524 }while( bNextLine || sqlite3_step(pStmt)==SQLITE_ROW ); 3525 nTotal = nColumn*(nRow+1); 3526 for(i=0; i<nTotal; i++){ 3527 z = azData[i]; 3528 if( z==0 ) z = (char*)zEmpty; 3529 n = strlenChar(z); 3530 j = i%nColumn; 3531 if( n>p->actualWidth[j] ) p->actualWidth[j] = n; 3532 } 3533 if( seenInterrupt ) goto columnar_end; 3534 if( nColumn==0 ) goto columnar_end; 3535 switch( p->cMode ){ 3536 case MODE_Column: { 3537 colSep = " "; 3538 rowSep = "\n"; 3539 if( p->showHeader ){ 3540 for(i=0; i<nColumn; i++){ 3541 w = p->actualWidth[i]; 3542 if( p->colWidth[i]<0 ) w = -w; 3543 utf8_width_print(p->out, w, azData[i]); 3544 fputs(i==nColumn-1?"\n":" ", p->out); 3545 } 3546 for(i=0; i<nColumn; i++){ 3547 print_dashes(p->out, p->actualWidth[i]); 3548 fputs(i==nColumn-1?"\n":" ", p->out); 3549 } 3550 } 3551 break; 3552 } 3553 case MODE_Table: { 3554 colSep = " | "; 3555 rowSep = " |\n"; 3556 print_row_separator(p, nColumn, "+"); 3557 fputs("| ", p->out); 3558 for(i=0; i<nColumn; i++){ 3559 w = p->actualWidth[i]; 3560 n = strlenChar(azData[i]); 3561 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3562 fputs(i==nColumn-1?" |\n":" | ", p->out); 3563 } 3564 print_row_separator(p, nColumn, "+"); 3565 break; 3566 } 3567 case MODE_Markdown: { 3568 colSep = " | "; 3569 rowSep = " |\n"; 3570 fputs("| ", p->out); 3571 for(i=0; i<nColumn; i++){ 3572 w = p->actualWidth[i]; 3573 n = strlenChar(azData[i]); 3574 utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, ""); 3575 fputs(i==nColumn-1?" |\n":" | ", p->out); 3576 } 3577 print_row_separator(p, nColumn, "|"); 3578 break; 3579 } 3580 case MODE_Box: { 3581 colSep = " " BOX_13 " "; 3582 rowSep = " " BOX_13 "\n"; 3583 print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34); 3584 utf8_printf(p->out, BOX_13 " "); 3585 for(i=0; i<nColumn; i++){ 3586 w = p->actualWidth[i]; 3587 n = strlenChar(azData[i]); 3588 utf8_printf(p->out, "%*s%s%*s%s", 3589 (w-n)/2, "", azData[i], (w-n+1)/2, "", 3590 i==nColumn-1?" "BOX_13"\n":" "BOX_13" "); 3591 } 3592 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); 3593 break; 3594 } 3595 } 3596 for(i=nColumn, j=0; i<nTotal; i++, j++){ 3597 if( j==0 && p->cMode!=MODE_Column ){ 3598 utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| "); 3599 } 3600 z = azData[i]; 3601 if( z==0 ) z = p->nullValue; 3602 w = p->actualWidth[j]; 3603 if( p->colWidth[j]<0 ) w = -w; 3604 utf8_width_print(p->out, w, z); 3605 if( j==nColumn-1 ){ 3606 utf8_printf(p->out, "%s", rowSep); 3607 if( bMultiLineRowExists && abRowDiv[i/nColumn-1] && i+1<nTotal ){ 3608 if( p->cMode==MODE_Table ){ 3609 print_row_separator(p, nColumn, "+"); 3610 }else if( p->cMode==MODE_Box ){ 3611 print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134); 3612 }else if( p->cMode==MODE_Column ){ 3613 raw_printf(p->out, "\n"); 3614 } 3615 } 3616 j = -1; 3617 if( seenInterrupt ) goto columnar_end; 3618 }else{ 3619 utf8_printf(p->out, "%s", colSep); 3620 } 3621 } 3622 if( p->cMode==MODE_Table ){ 3623 print_row_separator(p, nColumn, "+"); 3624 }else if( p->cMode==MODE_Box ){ 3625 print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14); 3626 } 3627columnar_end: 3628 if( seenInterrupt ){ 3629 utf8_printf(p->out, "Interrupt\n"); 3630 } 3631 nData = (nRow+1)*nColumn; 3632 for(i=0; i<nData; i++){ 3633 z = azData[i]; 3634 if( z!=zEmpty && z!=zShowNull ) free(azData[i]); 3635 } 3636 sqlite3_free(azData); 3637 sqlite3_free((void*)azNextLine); 3638 sqlite3_free(abRowDiv); 3639 if( azQuoted ){ 3640 for(i=0; i<nColumn; i++) sqlite3_free(azQuoted[i]); 3641 sqlite3_free(azQuoted); 3642 } 3643} 3644 3645/* 3646** Run a prepared statement 3647*/ 3648static void exec_prepared_stmt( 3649 ShellState *pArg, /* Pointer to ShellState */ 3650 sqlite3_stmt *pStmt /* Statment to run */ 3651){ 3652 int rc; 3653 sqlite3_uint64 nRow = 0; 3654 3655 if( pArg->cMode==MODE_Column 3656 || pArg->cMode==MODE_Table 3657 || pArg->cMode==MODE_Box 3658 || pArg->cMode==MODE_Markdown 3659 ){ 3660 exec_prepared_stmt_columnar(pArg, pStmt); 3661 return; 3662 } 3663 3664 /* perform the first step. this will tell us if we 3665 ** have a result set or not and how wide it is. 3666 */ 3667 rc = sqlite3_step(pStmt); 3668 /* if we have a result set... */ 3669 if( SQLITE_ROW == rc ){ 3670 /* allocate space for col name ptr, value ptr, and type */ 3671 int nCol = sqlite3_column_count(pStmt); 3672 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); 3673 if( !pData ){ 3674 shell_out_of_memory(); 3675 }else{ 3676 char **azCols = (char **)pData; /* Names of result columns */ 3677 char **azVals = &azCols[nCol]; /* Results */ 3678 int *aiTypes = (int *)&azVals[nCol]; /* Result types */ 3679 int i, x; 3680 assert(sizeof(int) <= sizeof(char *)); 3681 /* save off ptrs to column names */ 3682 for(i=0; i<nCol; i++){ 3683 azCols[i] = (char *)sqlite3_column_name(pStmt, i); 3684 } 3685 do{ 3686 nRow++; 3687 /* extract the data and data types */ 3688 for(i=0; i<nCol; i++){ 3689 aiTypes[i] = x = sqlite3_column_type(pStmt, i); 3690 if( x==SQLITE_BLOB 3691 && pArg 3692 && (pArg->cMode==MODE_Insert || pArg->cMode==MODE_Quote) 3693 ){ 3694 azVals[i] = ""; 3695 }else{ 3696 azVals[i] = (char*)sqlite3_column_text(pStmt, i); 3697 } 3698 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ 3699 rc = SQLITE_NOMEM; 3700 break; /* from for */ 3701 } 3702 } /* end for */ 3703 3704 /* if data and types extracted successfully... */ 3705 if( SQLITE_ROW == rc ){ 3706 /* call the supplied callback with the result row data */ 3707 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){ 3708 rc = SQLITE_ABORT; 3709 }else{ 3710 rc = sqlite3_step(pStmt); 3711 } 3712 } 3713 } while( SQLITE_ROW == rc ); 3714 sqlite3_free(pData); 3715 if( pArg->cMode==MODE_Json ){ 3716 fputs("]\n", pArg->out); 3717 }else if( pArg->cMode==MODE_Count ){ 3718 char zBuf[200]; 3719 sqlite3_snprintf(sizeof(zBuf), zBuf, "%llu row%s\n", 3720 nRow, nRow!=1 ? "s" : ""); 3721 printf("%s", zBuf); 3722 } 3723 } 3724 } 3725} 3726 3727#ifndef SQLITE_OMIT_VIRTUALTABLE 3728/* 3729** This function is called to process SQL if the previous shell command 3730** was ".expert". It passes the SQL in the second argument directly to 3731** the sqlite3expert object. 3732** 3733** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3734** code. In this case, (*pzErr) may be set to point to a buffer containing 3735** an English language error message. It is the responsibility of the 3736** caller to eventually free this buffer using sqlite3_free(). 3737*/ 3738static int expertHandleSQL( 3739 ShellState *pState, 3740 const char *zSql, 3741 char **pzErr 3742){ 3743 assert( pState->expert.pExpert ); 3744 assert( pzErr==0 || *pzErr==0 ); 3745 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr); 3746} 3747 3748/* 3749** This function is called either to silently clean up the object 3750** created by the ".expert" command (if bCancel==1), or to generate a 3751** report from it and then clean it up (if bCancel==0). 3752** 3753** If successful, SQLITE_OK is returned. Otherwise, an SQLite error 3754** code. In this case, (*pzErr) may be set to point to a buffer containing 3755** an English language error message. It is the responsibility of the 3756** caller to eventually free this buffer using sqlite3_free(). 3757*/ 3758static int expertFinish( 3759 ShellState *pState, 3760 int bCancel, 3761 char **pzErr 3762){ 3763 int rc = SQLITE_OK; 3764 sqlite3expert *p = pState->expert.pExpert; 3765 assert( p ); 3766 assert( bCancel || pzErr==0 || *pzErr==0 ); 3767 if( bCancel==0 ){ 3768 FILE *out = pState->out; 3769 int bVerbose = pState->expert.bVerbose; 3770 3771 rc = sqlite3_expert_analyze(p, pzErr); 3772 if( rc==SQLITE_OK ){ 3773 int nQuery = sqlite3_expert_count(p); 3774 int i; 3775 3776 if( bVerbose ){ 3777 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES); 3778 raw_printf(out, "-- Candidates -----------------------------\n"); 3779 raw_printf(out, "%s\n", zCand); 3780 } 3781 for(i=0; i<nQuery; i++){ 3782 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL); 3783 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES); 3784 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN); 3785 if( zIdx==0 ) zIdx = "(no new indexes)\n"; 3786 if( bVerbose ){ 3787 raw_printf(out, "-- Query %d --------------------------------\n",i+1); 3788 raw_printf(out, "%s\n\n", zSql); 3789 } 3790 raw_printf(out, "%s\n", zIdx); 3791 raw_printf(out, "%s\n", zEQP); 3792 } 3793 } 3794 } 3795 sqlite3_expert_destroy(p); 3796 pState->expert.pExpert = 0; 3797 return rc; 3798} 3799 3800/* 3801** Implementation of ".expert" dot command. 3802*/ 3803static int expertDotCommand( 3804 ShellState *pState, /* Current shell tool state */ 3805 char **azArg, /* Array of arguments passed to dot command */ 3806 int nArg /* Number of entries in azArg[] */ 3807){ 3808 int rc = SQLITE_OK; 3809 char *zErr = 0; 3810 int i; 3811 int iSample = 0; 3812 3813 assert( pState->expert.pExpert==0 ); 3814 memset(&pState->expert, 0, sizeof(ExpertInfo)); 3815 3816 for(i=1; rc==SQLITE_OK && i<nArg; i++){ 3817 char *z = azArg[i]; 3818 int n; 3819 if( z[0]=='-' && z[1]=='-' ) z++; 3820 n = strlen30(z); 3821 if( n>=2 && 0==cli_strncmp(z, "-verbose", n) ){ 3822 pState->expert.bVerbose = 1; 3823 } 3824 else if( n>=2 && 0==cli_strncmp(z, "-sample", n) ){ 3825 if( i==(nArg-1) ){ 3826 raw_printf(stderr, "option requires an argument: %s\n", z); 3827 rc = SQLITE_ERROR; 3828 }else{ 3829 iSample = (int)integerValue(azArg[++i]); 3830 if( iSample<0 || iSample>100 ){ 3831 raw_printf(stderr, "value out of range: %s\n", azArg[i]); 3832 rc = SQLITE_ERROR; 3833 } 3834 } 3835 } 3836 else{ 3837 raw_printf(stderr, "unknown option: %s\n", z); 3838 rc = SQLITE_ERROR; 3839 } 3840 } 3841 3842 if( rc==SQLITE_OK ){ 3843 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr); 3844 if( pState->expert.pExpert==0 ){ 3845 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr ? zErr : "out of memory"); 3846 rc = SQLITE_ERROR; 3847 }else{ 3848 sqlite3_expert_config( 3849 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample 3850 ); 3851 } 3852 } 3853 sqlite3_free(zErr); 3854 3855 return rc; 3856} 3857#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ 3858 3859/* 3860** Execute a statement or set of statements. Print 3861** any result rows/columns depending on the current mode 3862** set via the supplied callback. 3863** 3864** This is very similar to SQLite's built-in sqlite3_exec() 3865** function except it takes a slightly different callback 3866** and callback data argument. 3867*/ 3868static int shell_exec( 3869 ShellState *pArg, /* Pointer to ShellState */ 3870 const char *zSql, /* SQL to be evaluated */ 3871 char **pzErrMsg /* Error msg written here */ 3872){ 3873 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ 3874 int rc = SQLITE_OK; /* Return Code */ 3875 int rc2; 3876 const char *zLeftover; /* Tail of unprocessed SQL */ 3877 sqlite3 *db = pArg->db; 3878 3879 if( pzErrMsg ){ 3880 *pzErrMsg = NULL; 3881 } 3882 3883#ifndef SQLITE_OMIT_VIRTUALTABLE 3884 if( pArg->expert.pExpert ){ 3885 rc = expertHandleSQL(pArg, zSql, pzErrMsg); 3886 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg); 3887 } 3888#endif 3889 3890 while( zSql[0] && (SQLITE_OK == rc) ){ 3891 static const char *zStmtSql; 3892 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); 3893 if( SQLITE_OK != rc ){ 3894 if( pzErrMsg ){ 3895 *pzErrMsg = save_err_msg(db, "in prepare", rc, zSql); 3896 } 3897 }else{ 3898 if( !pStmt ){ 3899 /* this happens for a comment or white-space */ 3900 zSql = zLeftover; 3901 while( IsSpace(zSql[0]) ) zSql++; 3902 continue; 3903 } 3904 zStmtSql = sqlite3_sql(pStmt); 3905 if( zStmtSql==0 ) zStmtSql = ""; 3906 while( IsSpace(zStmtSql[0]) ) zStmtSql++; 3907 3908 /* save off the prepared statment handle and reset row count */ 3909 if( pArg ){ 3910 pArg->pStmt = pStmt; 3911 pArg->cnt = 0; 3912 } 3913 3914 /* Show the EXPLAIN QUERY PLAN if .eqp is on */ 3915 if( pArg && pArg->autoEQP && sqlite3_stmt_isexplain(pStmt)==0 ){ 3916 sqlite3_stmt *pExplain; 3917 char *zEQP; 3918 int triggerEQP = 0; 3919 disable_debug_trace_modes(); 3920 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP); 3921 if( pArg->autoEQP>=AUTOEQP_trigger ){ 3922 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0); 3923 } 3924 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); 3925 shell_check_oom(zEQP); 3926 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3927 if( rc==SQLITE_OK ){ 3928 while( sqlite3_step(pExplain)==SQLITE_ROW ){ 3929 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3); 3930 int iEqpId = sqlite3_column_int(pExplain, 0); 3931 int iParentId = sqlite3_column_int(pExplain, 1); 3932 if( zEQPLine==0 ) zEQPLine = ""; 3933 if( zEQPLine[0]=='-' ) eqp_render(pArg); 3934 eqp_append(pArg, iEqpId, iParentId, zEQPLine); 3935 } 3936 eqp_render(pArg); 3937 } 3938 sqlite3_finalize(pExplain); 3939 sqlite3_free(zEQP); 3940 if( pArg->autoEQP>=AUTOEQP_full ){ 3941 /* Also do an EXPLAIN for ".eqp full" mode */ 3942 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); 3943 shell_check_oom(zEQP); 3944 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 3945 if( rc==SQLITE_OK ){ 3946 pArg->cMode = MODE_Explain; 3947 explain_data_prepare(pArg, pExplain); 3948 exec_prepared_stmt(pArg, pExplain); 3949 explain_data_delete(pArg); 3950 } 3951 sqlite3_finalize(pExplain); 3952 sqlite3_free(zEQP); 3953 } 3954 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){ 3955 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0); 3956 /* Reprepare pStmt before reactiving trace modes */ 3957 sqlite3_finalize(pStmt); 3958 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 3959 if( pArg ) pArg->pStmt = pStmt; 3960 } 3961 restore_debug_trace_modes(); 3962 } 3963 3964 if( pArg ){ 3965 pArg->cMode = pArg->mode; 3966 if( pArg->autoExplain ){ 3967 if( sqlite3_stmt_isexplain(pStmt)==1 ){ 3968 pArg->cMode = MODE_Explain; 3969 } 3970 if( sqlite3_stmt_isexplain(pStmt)==2 ){ 3971 pArg->cMode = MODE_EQP; 3972 } 3973 } 3974 3975 /* If the shell is currently in ".explain" mode, gather the extra 3976 ** data required to add indents to the output.*/ 3977 if( pArg->cMode==MODE_Explain ){ 3978 explain_data_prepare(pArg, pStmt); 3979 } 3980 } 3981 3982 bind_prepared_stmt(pArg, pStmt); 3983 exec_prepared_stmt(pArg, pStmt); 3984 explain_data_delete(pArg); 3985 eqp_render(pArg); 3986 3987 /* print usage stats if stats on */ 3988 if( pArg && pArg->statsOn ){ 3989 display_stats(db, pArg, 0); 3990 } 3991 3992 /* print loop-counters if required */ 3993 if( pArg && pArg->scanstatsOn ){ 3994 display_scanstats(db, pArg); 3995 } 3996 3997 /* Finalize the statement just executed. If this fails, save a 3998 ** copy of the error message. Otherwise, set zSql to point to the 3999 ** next statement to execute. */ 4000 rc2 = sqlite3_finalize(pStmt); 4001 if( rc!=SQLITE_NOMEM ) rc = rc2; 4002 if( rc==SQLITE_OK ){ 4003 zSql = zLeftover; 4004 while( IsSpace(zSql[0]) ) zSql++; 4005 }else if( pzErrMsg ){ 4006 *pzErrMsg = save_err_msg(db, "stepping", rc, 0); 4007 } 4008 4009 /* clear saved stmt handle */ 4010 if( pArg ){ 4011 pArg->pStmt = NULL; 4012 } 4013 } 4014 } /* end while */ 4015 4016 return rc; 4017} 4018 4019/* 4020** Release memory previously allocated by tableColumnList(). 4021*/ 4022static void freeColumnList(char **azCol){ 4023 int i; 4024 for(i=1; azCol[i]; i++){ 4025 sqlite3_free(azCol[i]); 4026 } 4027 /* azCol[0] is a static string */ 4028 sqlite3_free(azCol); 4029} 4030 4031/* 4032** Return a list of pointers to strings which are the names of all 4033** columns in table zTab. The memory to hold the names is dynamically 4034** allocated and must be released by the caller using a subsequent call 4035** to freeColumnList(). 4036** 4037** The azCol[0] entry is usually NULL. However, if zTab contains a rowid 4038** value that needs to be preserved, then azCol[0] is filled in with the 4039** name of the rowid column. 4040** 4041** The first regular column in the table is azCol[1]. The list is terminated 4042** by an entry with azCol[i]==0. 4043*/ 4044static char **tableColumnList(ShellState *p, const char *zTab){ 4045 char **azCol = 0; 4046 sqlite3_stmt *pStmt; 4047 char *zSql; 4048 int nCol = 0; 4049 int nAlloc = 0; 4050 int nPK = 0; /* Number of PRIMARY KEY columns seen */ 4051 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ 4052 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid); 4053 int rc; 4054 4055 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); 4056 shell_check_oom(zSql); 4057 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4058 sqlite3_free(zSql); 4059 if( rc ) return 0; 4060 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 4061 if( nCol>=nAlloc-2 ){ 4062 nAlloc = nAlloc*2 + nCol + 10; 4063 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); 4064 shell_check_oom(azCol); 4065 } 4066 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); 4067 shell_check_oom(azCol[nCol]); 4068 if( sqlite3_column_int(pStmt, 5) ){ 4069 nPK++; 4070 if( nPK==1 4071 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), 4072 "INTEGER")==0 4073 ){ 4074 isIPK = 1; 4075 }else{ 4076 isIPK = 0; 4077 } 4078 } 4079 } 4080 sqlite3_finalize(pStmt); 4081 if( azCol==0 ) return 0; 4082 azCol[0] = 0; 4083 azCol[nCol+1] = 0; 4084 4085 /* The decision of whether or not a rowid really needs to be preserved 4086 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table 4087 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve 4088 ** rowids on tables where the rowid is inaccessible because there are other 4089 ** columns in the table named "rowid", "_rowid_", and "oid". 4090 */ 4091 if( preserveRowid && isIPK ){ 4092 /* If a single PRIMARY KEY column with type INTEGER was seen, then it 4093 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID 4094 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are 4095 ** ROWID aliases. To distinguish these cases, check to see if 4096 ** there is a "pk" entry in "PRAGMA index_list". There will be 4097 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. 4098 */ 4099 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" 4100 " WHERE origin='pk'", zTab); 4101 shell_check_oom(zSql); 4102 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 4103 sqlite3_free(zSql); 4104 if( rc ){ 4105 freeColumnList(azCol); 4106 return 0; 4107 } 4108 rc = sqlite3_step(pStmt); 4109 sqlite3_finalize(pStmt); 4110 preserveRowid = rc==SQLITE_ROW; 4111 } 4112 if( preserveRowid ){ 4113 /* Only preserve the rowid if we can find a name to use for the 4114 ** rowid */ 4115 static char *azRowid[] = { "rowid", "_rowid_", "oid" }; 4116 int i, j; 4117 for(j=0; j<3; j++){ 4118 for(i=1; i<=nCol; i++){ 4119 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; 4120 } 4121 if( i>nCol ){ 4122 /* At this point, we know that azRowid[j] is not the name of any 4123 ** ordinary column in the table. Verify that azRowid[j] is a valid 4124 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID 4125 ** tables will fail this last check */ 4126 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); 4127 if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; 4128 break; 4129 } 4130 } 4131 } 4132 return azCol; 4133} 4134 4135/* 4136** Toggle the reverse_unordered_selects setting. 4137*/ 4138static void toggleSelectOrder(sqlite3 *db){ 4139 sqlite3_stmt *pStmt = 0; 4140 int iSetting = 0; 4141 char zStmt[100]; 4142 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0); 4143 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 4144 iSetting = sqlite3_column_int(pStmt, 0); 4145 } 4146 sqlite3_finalize(pStmt); 4147 sqlite3_snprintf(sizeof(zStmt), zStmt, 4148 "PRAGMA reverse_unordered_selects(%d)", !iSetting); 4149 sqlite3_exec(db, zStmt, 0, 0, 0); 4150} 4151 4152/* 4153** This is a different callback routine used for dumping the database. 4154** Each row received by this callback consists of a table name, 4155** the table type ("index" or "table") and SQL to create the table. 4156** This routine should print text sufficient to recreate the table. 4157*/ 4158static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){ 4159 int rc; 4160 const char *zTable; 4161 const char *zType; 4162 const char *zSql; 4163 ShellState *p = (ShellState *)pArg; 4164 int dataOnly; 4165 int noSys; 4166 4167 UNUSED_PARAMETER(azNotUsed); 4168 if( nArg!=3 || azArg==0 ) return 0; 4169 zTable = azArg[0]; 4170 zType = azArg[1]; 4171 zSql = azArg[2]; 4172 if( zTable==0 ) return 0; 4173 if( zType==0 ) return 0; 4174 dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0; 4175 noSys = (p->shellFlgs & SHFLG_DumpNoSys)!=0; 4176 4177 if( cli_strcmp(zTable, "sqlite_sequence")==0 && !noSys ){ 4178 if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n"); 4179 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){ 4180 if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 4181 }else if( cli_strncmp(zTable, "sqlite_", 7)==0 ){ 4182 return 0; 4183 }else if( dataOnly ){ 4184 /* no-op */ 4185 }else if( cli_strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ 4186 char *zIns; 4187 if( !p->writableSchema ){ 4188 raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); 4189 p->writableSchema = 1; 4190 } 4191 zIns = sqlite3_mprintf( 4192 "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)" 4193 "VALUES('table','%q','%q',0,'%q');", 4194 zTable, zTable, zSql); 4195 shell_check_oom(zIns); 4196 utf8_printf(p->out, "%s\n", zIns); 4197 sqlite3_free(zIns); 4198 return 0; 4199 }else{ 4200 printSchemaLine(p->out, zSql, ";\n"); 4201 } 4202 4203 if( cli_strcmp(zType, "table")==0 ){ 4204 ShellText sSelect; 4205 ShellText sTable; 4206 char **azCol; 4207 int i; 4208 char *savedDestTable; 4209 int savedMode; 4210 4211 azCol = tableColumnList(p, zTable); 4212 if( azCol==0 ){ 4213 p->nErr++; 4214 return 0; 4215 } 4216 4217 /* Always quote the table name, even if it appears to be pure ascii, 4218 ** in case it is a keyword. Ex: INSERT INTO "table" ... */ 4219 initText(&sTable); 4220 appendText(&sTable, zTable, quoteChar(zTable)); 4221 /* If preserving the rowid, add a column list after the table name. 4222 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" 4223 ** instead of the usual "INSERT INTO tab VALUES(...)". 4224 */ 4225 if( azCol[0] ){ 4226 appendText(&sTable, "(", 0); 4227 appendText(&sTable, azCol[0], 0); 4228 for(i=1; azCol[i]; i++){ 4229 appendText(&sTable, ",", 0); 4230 appendText(&sTable, azCol[i], quoteChar(azCol[i])); 4231 } 4232 appendText(&sTable, ")", 0); 4233 } 4234 4235 /* Build an appropriate SELECT statement */ 4236 initText(&sSelect); 4237 appendText(&sSelect, "SELECT ", 0); 4238 if( azCol[0] ){ 4239 appendText(&sSelect, azCol[0], 0); 4240 appendText(&sSelect, ",", 0); 4241 } 4242 for(i=1; azCol[i]; i++){ 4243 appendText(&sSelect, azCol[i], quoteChar(azCol[i])); 4244 if( azCol[i+1] ){ 4245 appendText(&sSelect, ",", 0); 4246 } 4247 } 4248 freeColumnList(azCol); 4249 appendText(&sSelect, " FROM ", 0); 4250 appendText(&sSelect, zTable, quoteChar(zTable)); 4251 4252 savedDestTable = p->zDestTable; 4253 savedMode = p->mode; 4254 p->zDestTable = sTable.z; 4255 p->mode = p->cMode = MODE_Insert; 4256 rc = shell_exec(p, sSelect.z, 0); 4257 if( (rc&0xff)==SQLITE_CORRUPT ){ 4258 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 4259 toggleSelectOrder(p->db); 4260 shell_exec(p, sSelect.z, 0); 4261 toggleSelectOrder(p->db); 4262 } 4263 p->zDestTable = savedDestTable; 4264 p->mode = savedMode; 4265 freeText(&sTable); 4266 freeText(&sSelect); 4267 if( rc ) p->nErr++; 4268 } 4269 return 0; 4270} 4271 4272/* 4273** Run zQuery. Use dump_callback() as the callback routine so that 4274** the contents of the query are output as SQL statements. 4275** 4276** If we get a SQLITE_CORRUPT error, rerun the query after appending 4277** "ORDER BY rowid DESC" to the end. 4278*/ 4279static int run_schema_dump_query( 4280 ShellState *p, 4281 const char *zQuery 4282){ 4283 int rc; 4284 char *zErr = 0; 4285 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); 4286 if( rc==SQLITE_CORRUPT ){ 4287 char *zQ2; 4288 int len = strlen30(zQuery); 4289 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); 4290 if( zErr ){ 4291 utf8_printf(p->out, "/****** %s ******/\n", zErr); 4292 sqlite3_free(zErr); 4293 zErr = 0; 4294 } 4295 zQ2 = malloc( len+100 ); 4296 if( zQ2==0 ) return rc; 4297 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); 4298 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); 4299 if( rc ){ 4300 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); 4301 }else{ 4302 rc = SQLITE_CORRUPT; 4303 } 4304 sqlite3_free(zErr); 4305 free(zQ2); 4306 } 4307 return rc; 4308} 4309 4310/* 4311** Text of help messages. 4312** 4313** The help text for each individual command begins with a line that starts 4314** with ".". Subsequent lines are supplemental information. 4315** 4316** There must be two or more spaces between the end of the command and the 4317** start of the description of what that command does. 4318*/ 4319static const char *(azHelp[]) = { 4320#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) \ 4321 && !defined(SQLITE_SHELL_FIDDLE) 4322 ".archive ... Manage SQL archives", 4323 " Each command must have exactly one of the following options:", 4324 " -c, --create Create a new archive", 4325 " -u, --update Add or update files with changed mtime", 4326 " -i, --insert Like -u but always add even if unchanged", 4327 " -r, --remove Remove files from archive", 4328 " -t, --list List contents of archive", 4329 " -x, --extract Extract files from archive", 4330 " Optional arguments:", 4331 " -v, --verbose Print each filename as it is processed", 4332 " -f FILE, --file FILE Use archive FILE (default is current db)", 4333 " -a FILE, --append FILE Open FILE using the apndvfs VFS", 4334 " -C DIR, --directory DIR Read/extract files from directory DIR", 4335 " -g, --glob Use glob matching for names in archive", 4336 " -n, --dryrun Show the SQL that would have occurred", 4337 " Examples:", 4338 " .ar -cf ARCHIVE foo bar # Create ARCHIVE from files foo and bar", 4339 " .ar -tf ARCHIVE # List members of ARCHIVE", 4340 " .ar -xvf ARCHIVE # Verbosely extract files from ARCHIVE", 4341 " See also:", 4342 " http://sqlite.org/cli.html#sqlite_archive_support", 4343#endif 4344#ifndef SQLITE_OMIT_AUTHORIZATION 4345 ".auth ON|OFF Show authorizer callbacks", 4346#endif 4347#ifndef SQLITE_SHELL_FIDDLE 4348 ".backup ?DB? FILE Backup DB (default \"main\") to FILE", 4349 " Options:", 4350 " --append Use the appendvfs", 4351 " --async Write to FILE without journal and fsync()", 4352#endif 4353 ".bail on|off Stop after hitting an error. Default OFF", 4354 ".binary on|off Turn binary output on or off. Default OFF", 4355#ifndef SQLITE_SHELL_FIDDLE 4356 ".cd DIRECTORY Change the working directory to DIRECTORY", 4357#endif 4358 ".changes on|off Show number of rows changed by SQL", 4359#ifndef SQLITE_SHELL_FIDDLE 4360 ".check GLOB Fail if output since .testcase does not match", 4361 ".clone NEWDB Clone data into NEWDB from the existing database", 4362#endif 4363 ".connection [close] [#] Open or close an auxiliary database connection", 4364 ".databases List names and files of attached databases", 4365 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options", 4366#if SQLITE_SHELL_HAVE_RECOVER 4367 ".dbinfo ?DB? Show status information about the database", 4368#endif 4369 ".dump ?OBJECTS? Render database content as SQL", 4370 " Options:", 4371 " --data-only Output only INSERT statements", 4372 " --newlines Allow unescaped newline characters in output", 4373 " --nosys Omit system tables (ex: \"sqlite_stat1\")", 4374 " --preserve-rowids Include ROWID values in the output", 4375 " OBJECTS is a LIKE pattern for tables, indexes, triggers or views to dump", 4376 " Additional LIKE patterns can be given in subsequent arguments", 4377 ".echo on|off Turn command echo on or off", 4378 ".eqp on|off|full|... Enable or disable automatic EXPLAIN QUERY PLAN", 4379 " Other Modes:", 4380#ifdef SQLITE_DEBUG 4381 " test Show raw EXPLAIN QUERY PLAN output", 4382 " trace Like \"full\" but enable \"PRAGMA vdbe_trace\"", 4383#endif 4384 " trigger Like \"full\" but also show trigger bytecode", 4385#ifndef SQLITE_SHELL_FIDDLE 4386 ".excel Display the output of next command in spreadsheet", 4387 " --bom Put a UTF8 byte-order mark on intermediate file", 4388#endif 4389#ifndef SQLITE_SHELL_FIDDLE 4390 ".exit ?CODE? Exit this program with return-code CODE", 4391#endif 4392 ".expert EXPERIMENTAL. Suggest indexes for queries", 4393 ".explain ?on|off|auto? Change the EXPLAIN formatting mode. Default: auto", 4394 ".filectrl CMD ... Run various sqlite3_file_control() operations", 4395 " --schema SCHEMA Use SCHEMA instead of \"main\"", 4396 " --help Show CMD details", 4397 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables", 4398 ".headers on|off Turn display of headers on or off", 4399 ".help ?-all? ?PATTERN? Show help text for PATTERN", 4400#ifndef SQLITE_SHELL_FIDDLE 4401 ".import FILE TABLE Import data from FILE into TABLE", 4402 " Options:", 4403 " --ascii Use \\037 and \\036 as column and row separators", 4404 " --csv Use , and \\n as column and row separators", 4405 " --skip N Skip the first N rows of input", 4406 " --schema S Target table to be S.TABLE", 4407 " -v \"Verbose\" - increase auxiliary output", 4408 " Notes:", 4409 " * If TABLE does not exist, it is created. The first row of input", 4410 " determines the column names.", 4411 " * If neither --csv or --ascii are used, the input mode is derived", 4412 " from the \".mode\" output mode", 4413 " * If FILE begins with \"|\" then it is a command that generates the", 4414 " input text.", 4415#endif 4416#ifndef SQLITE_OMIT_TEST_CONTROL 4417 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX", 4418#endif 4419 ".indexes ?TABLE? Show names of indexes", 4420 " If TABLE is specified, only show indexes for", 4421 " tables matching TABLE using the LIKE operator.", 4422#ifdef SQLITE_ENABLE_IOTRACE 4423 ".iotrace FILE Enable I/O diagnostic logging to FILE", 4424#endif 4425 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT", 4426 ".lint OPTIONS Report potential schema issues.", 4427 " Options:", 4428 " fkey-indexes Find missing foreign key indexes", 4429#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE) 4430 ".load FILE ?ENTRY? Load an extension library", 4431#endif 4432#ifndef SQLITE_SHELL_FIDDLE 4433 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout", 4434#endif 4435 ".mode MODE ?OPTIONS? Set output mode", 4436 " MODE is one of:", 4437 " ascii Columns/rows delimited by 0x1F and 0x1E", 4438 " box Tables using unicode box-drawing characters", 4439 " csv Comma-separated values", 4440 " column Output in columns. (See .width)", 4441 " html HTML <table> code", 4442 " insert SQL insert statements for TABLE", 4443 " json Results in a JSON array", 4444 " line One value per line", 4445 " list Values delimited by \"|\"", 4446 " markdown Markdown table format", 4447 " qbox Shorthand for \"box --wrap 60 --quote\"", 4448 " quote Escape answers as for SQL", 4449 " table ASCII-art table", 4450 " tabs Tab-separated values", 4451 " tcl TCL list elements", 4452 " OPTIONS: (for columnar modes or insert mode):", 4453 " --wrap N Wrap output lines to no longer than N characters", 4454 " --wordwrap B Wrap or not at word boundaries per B (on/off)", 4455 " --ww Shorthand for \"--wordwrap 1\"", 4456 " --quote Quote output text as SQL literals", 4457 " --noquote Do not quote output text", 4458 " TABLE The name of SQL table used for \"insert\" mode", 4459#ifndef SQLITE_SHELL_FIDDLE 4460 ".nonce STRING Suspend safe mode for one command if nonce matches", 4461#endif 4462 ".nullvalue STRING Use STRING in place of NULL values", 4463#ifndef SQLITE_SHELL_FIDDLE 4464 ".once ?OPTIONS? ?FILE? Output for the next SQL command only to FILE", 4465 " If FILE begins with '|' then open as a pipe", 4466 " --bom Put a UTF8 byte-order mark at the beginning", 4467 " -e Send output to the system text editor", 4468 " -x Send output as CSV to a spreadsheet (same as \".excel\")", 4469 /* Note that .open is (partially) available in WASM builds but is 4470 ** currently only intended to be used by the fiddle tool, not 4471 ** end users, so is "undocumented." */ 4472 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE", 4473 " Options:", 4474 " --append Use appendvfs to append database to the end of FILE", 4475#endif 4476#ifndef SQLITE_OMIT_DESERIALIZE 4477 " --deserialize Load into memory using sqlite3_deserialize()", 4478 " --hexdb Load the output of \"dbtotxt\" as an in-memory db", 4479 " --maxsize N Maximum size for --hexdb or --deserialized database", 4480#endif 4481 " --new Initialize FILE to an empty database", 4482 " --nofollow Do not follow symbolic links", 4483 " --readonly Open FILE readonly", 4484 " --zip FILE is a ZIP archive", 4485#ifndef SQLITE_SHELL_FIDDLE 4486 ".output ?FILE? Send output to FILE or stdout if FILE is omitted", 4487 " If FILE begins with '|' then open it as a pipe.", 4488 " Options:", 4489 " --bom Prefix output with a UTF8 byte-order mark", 4490 " -e Send output to the system text editor", 4491 " -x Send output as CSV to a spreadsheet", 4492#endif 4493 ".parameter CMD ... Manage SQL parameter bindings", 4494 " clear Erase all bindings", 4495 " init Initialize the TEMP table that holds bindings", 4496 " list List the current parameter bindings", 4497 " set PARAMETER VALUE Given SQL parameter PARAMETER a value of VALUE", 4498 " PARAMETER should start with one of: $ : @ ?", 4499 " unset PARAMETER Remove PARAMETER from the binding table", 4500 ".print STRING... Print literal STRING", 4501#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 4502 ".progress N Invoke progress handler after every N opcodes", 4503 " --limit N Interrupt after N progress callbacks", 4504 " --once Do no more than one progress interrupt", 4505 " --quiet|-q No output except at interrupts", 4506 " --reset Reset the count for each input and interrupt", 4507#endif 4508 ".prompt MAIN CONTINUE Replace the standard prompts", 4509#ifndef SQLITE_SHELL_FIDDLE 4510 ".quit Exit this program", 4511 ".read FILE Read input from FILE or command output", 4512 " If FILE begins with \"|\", it is a command that generates the input.", 4513#endif 4514#if SQLITE_SHELL_HAVE_RECOVER 4515 ".recover Recover as much data as possible from corrupt db.", 4516 " --ignore-freelist Ignore pages that appear to be on db freelist", 4517 " --recovery-db NAME Store recovery metadata in database file NAME", 4518 " --lost-and-found TABLE Alternative name for the lost-and-found table", 4519 " --no-rowids Do not attempt to recover rowid values", 4520 " that are not also INTEGER PRIMARY KEYs", 4521#endif 4522#ifndef SQLITE_SHELL_FIDDLE 4523 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE", 4524 ".save ?OPTIONS? FILE Write database to FILE (an alias for .backup ...)", 4525#endif 4526 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off", 4527 ".schema ?PATTERN? Show the CREATE statements matching PATTERN", 4528 " Options:", 4529 " --indent Try to pretty-print the schema", 4530 " --nosys Omit objects whose names start with \"sqlite_\"", 4531 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table", 4532 " Options:", 4533 " --init Create a new SELFTEST table", 4534 " -v Verbose output", 4535 ".separator COL ?ROW? Change the column and row separators", 4536#if defined(SQLITE_ENABLE_SESSION) 4537 ".session ?NAME? CMD ... Create or control sessions", 4538 " Subcommands:", 4539 " attach TABLE Attach TABLE", 4540 " changeset FILE Write a changeset into FILE", 4541 " close Close one session", 4542 " enable ?BOOLEAN? Set or query the enable bit", 4543 " filter GLOB... Reject tables matching GLOBs", 4544 " indirect ?BOOLEAN? Mark or query the indirect status", 4545 " isempty Query whether the session is empty", 4546 " list List currently open session names", 4547 " open DB NAME Open a new session on DB", 4548 " patchset FILE Write a patchset into FILE", 4549 " If ?NAME? is omitted, the first defined session is used.", 4550#endif 4551 ".sha3sum ... Compute a SHA3 hash of database content", 4552 " Options:", 4553 " --schema Also hash the sqlite_schema table", 4554 " --sha3-224 Use the sha3-224 algorithm", 4555 " --sha3-256 Use the sha3-256 algorithm (default)", 4556 " --sha3-384 Use the sha3-384 algorithm", 4557 " --sha3-512 Use the sha3-512 algorithm", 4558 " Any other argument is a LIKE pattern for tables to hash", 4559#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) 4560 ".shell CMD ARGS... Run CMD ARGS... in a system shell", 4561#endif 4562 ".show Show the current values for various settings", 4563 ".stats ?ARG? Show stats or turn stats on or off", 4564 " off Turn off automatic stat display", 4565 " on Turn on automatic stat display", 4566 " stmt Show statement stats", 4567 " vmstep Show the virtual machine step count only", 4568#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) 4569 ".system CMD ARGS... Run CMD ARGS... in a system shell", 4570#endif 4571 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE", 4572#ifndef SQLITE_SHELL_FIDDLE 4573 ".testcase NAME Begin redirecting output to 'testcase-out.txt'", 4574#endif 4575 ".testctrl CMD ... Run various sqlite3_test_control() operations", 4576 " Run \".testctrl\" with no arguments for details", 4577 ".timeout MS Try opening locked tables for MS milliseconds", 4578 ".timer on|off Turn SQL timer on or off", 4579#ifndef SQLITE_OMIT_TRACE 4580 ".trace ?OPTIONS? Output each SQL statement as it is run", 4581 " FILE Send output to FILE", 4582 " stdout Send output to stdout", 4583 " stderr Send output to stderr", 4584 " off Disable tracing", 4585 " --expanded Expand query parameters", 4586#ifdef SQLITE_ENABLE_NORMALIZE 4587 " --normalized Normal the SQL statements", 4588#endif 4589 " --plain Show SQL as it is input", 4590 " --stmt Trace statement execution (SQLITE_TRACE_STMT)", 4591 " --profile Profile statements (SQLITE_TRACE_PROFILE)", 4592 " --row Trace each row (SQLITE_TRACE_ROW)", 4593 " --close Trace connection close (SQLITE_TRACE_CLOSE)", 4594#endif /* SQLITE_OMIT_TRACE */ 4595#ifdef SQLITE_DEBUG 4596 ".unmodule NAME ... Unregister virtual table modules", 4597 " --allexcept Unregister everything except those named", 4598#endif 4599 ".vfsinfo ?AUX? Information about the top-level VFS", 4600 ".vfslist List all available VFSes", 4601 ".vfsname ?AUX? Print the name of the VFS stack", 4602 ".width NUM1 NUM2 ... Set minimum column widths for columnar output", 4603 " Negative values right-justify", 4604}; 4605 4606/* 4607** Output help text. 4608** 4609** zPattern describes the set of commands for which help text is provided. 4610** If zPattern is NULL, then show all commands, but only give a one-line 4611** description of each. 4612** 4613** Return the number of matches. 4614*/ 4615static int showHelp(FILE *out, const char *zPattern){ 4616 int i = 0; 4617 int j = 0; 4618 int n = 0; 4619 char *zPat; 4620 if( zPattern==0 4621 || zPattern[0]=='0' 4622 || cli_strcmp(zPattern,"-a")==0 4623 || cli_strcmp(zPattern,"-all")==0 4624 || cli_strcmp(zPattern,"--all")==0 4625 ){ 4626 /* Show all commands, but only one line per command */ 4627 if( zPattern==0 ) zPattern = ""; 4628 for(i=0; i<ArraySize(azHelp); i++){ 4629 if( azHelp[i][0]=='.' || zPattern[0] ){ 4630 utf8_printf(out, "%s\n", azHelp[i]); 4631 n++; 4632 } 4633 } 4634 }else{ 4635 /* Look for commands that for which zPattern is an exact prefix */ 4636 zPat = sqlite3_mprintf(".%s*", zPattern); 4637 shell_check_oom(zPat); 4638 for(i=0; i<ArraySize(azHelp); i++){ 4639 if( sqlite3_strglob(zPat, azHelp[i])==0 ){ 4640 utf8_printf(out, "%s\n", azHelp[i]); 4641 j = i+1; 4642 n++; 4643 } 4644 } 4645 sqlite3_free(zPat); 4646 if( n ){ 4647 if( n==1 ){ 4648 /* when zPattern is a prefix of exactly one command, then include the 4649 ** details of that command, which should begin at offset j */ 4650 while( j<ArraySize(azHelp)-1 && azHelp[j][0]!='.' ){ 4651 utf8_printf(out, "%s\n", azHelp[j]); 4652 j++; 4653 } 4654 } 4655 return n; 4656 } 4657 /* Look for commands that contain zPattern anywhere. Show the complete 4658 ** text of all commands that match. */ 4659 zPat = sqlite3_mprintf("%%%s%%", zPattern); 4660 shell_check_oom(zPat); 4661 for(i=0; i<ArraySize(azHelp); i++){ 4662 if( azHelp[i][0]=='.' ) j = i; 4663 if( sqlite3_strlike(zPat, azHelp[i], 0)==0 ){ 4664 utf8_printf(out, "%s\n", azHelp[j]); 4665 while( j<ArraySize(azHelp)-1 && azHelp[j+1][0]!='.' ){ 4666 j++; 4667 utf8_printf(out, "%s\n", azHelp[j]); 4668 } 4669 i = j; 4670 n++; 4671 } 4672 } 4673 sqlite3_free(zPat); 4674 } 4675 return n; 4676} 4677 4678/* Forward reference */ 4679static int process_input(ShellState *p); 4680 4681/* 4682** Read the content of file zName into memory obtained from sqlite3_malloc64() 4683** and return a pointer to the buffer. The caller is responsible for freeing 4684** the memory. 4685** 4686** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes 4687** read. 4688** 4689** For convenience, a nul-terminator byte is always appended to the data read 4690** from the file before the buffer is returned. This byte is not included in 4691** the final value of (*pnByte), if applicable. 4692** 4693** NULL is returned if any error is encountered. The final value of *pnByte 4694** is undefined in this case. 4695*/ 4696static char *readFile(const char *zName, int *pnByte){ 4697 FILE *in = fopen(zName, "rb"); 4698 long nIn; 4699 size_t nRead; 4700 char *pBuf; 4701 if( in==0 ) return 0; 4702 fseek(in, 0, SEEK_END); 4703 nIn = ftell(in); 4704 rewind(in); 4705 pBuf = sqlite3_malloc64( nIn+1 ); 4706 if( pBuf==0 ){ fclose(in); return 0; } 4707 nRead = fread(pBuf, nIn, 1, in); 4708 fclose(in); 4709 if( nRead!=1 ){ 4710 sqlite3_free(pBuf); 4711 return 0; 4712 } 4713 pBuf[nIn] = 0; 4714 if( pnByte ) *pnByte = nIn; 4715 return pBuf; 4716} 4717 4718#if defined(SQLITE_ENABLE_SESSION) 4719/* 4720** Close a single OpenSession object and release all of its associated 4721** resources. 4722*/ 4723static void session_close(OpenSession *pSession){ 4724 int i; 4725 sqlite3session_delete(pSession->p); 4726 sqlite3_free(pSession->zName); 4727 for(i=0; i<pSession->nFilter; i++){ 4728 sqlite3_free(pSession->azFilter[i]); 4729 } 4730 sqlite3_free(pSession->azFilter); 4731 memset(pSession, 0, sizeof(OpenSession)); 4732} 4733#endif 4734 4735/* 4736** Close all OpenSession objects and release all associated resources. 4737*/ 4738#if defined(SQLITE_ENABLE_SESSION) 4739static void session_close_all(ShellState *p, int i){ 4740 int j; 4741 struct AuxDb *pAuxDb = i<0 ? p->pAuxDb : &p->aAuxDb[i]; 4742 for(j=0; j<pAuxDb->nSession; j++){ 4743 session_close(&pAuxDb->aSession[j]); 4744 } 4745 pAuxDb->nSession = 0; 4746} 4747#else 4748# define session_close_all(X,Y) 4749#endif 4750 4751/* 4752** Implementation of the xFilter function for an open session. Omit 4753** any tables named by ".session filter" but let all other table through. 4754*/ 4755#if defined(SQLITE_ENABLE_SESSION) 4756static int session_filter(void *pCtx, const char *zTab){ 4757 OpenSession *pSession = (OpenSession*)pCtx; 4758 int i; 4759 for(i=0; i<pSession->nFilter; i++){ 4760 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; 4761 } 4762 return 1; 4763} 4764#endif 4765 4766/* 4767** Try to deduce the type of file for zName based on its content. Return 4768** one of the SHELL_OPEN_* constants. 4769** 4770** If the file does not exist or is empty but its name looks like a ZIP 4771** archive and the dfltZip flag is true, then assume it is a ZIP archive. 4772** Otherwise, assume an ordinary database regardless of the filename if 4773** the type cannot be determined from content. 4774*/ 4775int deduceDatabaseType(const char *zName, int dfltZip){ 4776 FILE *f = fopen(zName, "rb"); 4777 size_t n; 4778 int rc = SHELL_OPEN_UNSPEC; 4779 char zBuf[100]; 4780 if( f==0 ){ 4781 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4782 return SHELL_OPEN_ZIPFILE; 4783 }else{ 4784 return SHELL_OPEN_NORMAL; 4785 } 4786 } 4787 n = fread(zBuf, 16, 1, f); 4788 if( n==1 && memcmp(zBuf, "SQLite format 3", 16)==0 ){ 4789 fclose(f); 4790 return SHELL_OPEN_NORMAL; 4791 } 4792 fseek(f, -25, SEEK_END); 4793 n = fread(zBuf, 25, 1, f); 4794 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){ 4795 rc = SHELL_OPEN_APPENDVFS; 4796 }else{ 4797 fseek(f, -22, SEEK_END); 4798 n = fread(zBuf, 22, 1, f); 4799 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05 4800 && zBuf[3]==0x06 ){ 4801 rc = SHELL_OPEN_ZIPFILE; 4802 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){ 4803 rc = SHELL_OPEN_ZIPFILE; 4804 } 4805 } 4806 fclose(f); 4807 return rc; 4808} 4809 4810#ifndef SQLITE_OMIT_DESERIALIZE 4811/* 4812** Reconstruct an in-memory database using the output from the "dbtotxt" 4813** program. Read content from the file in p->aAuxDb[].zDbFilename. 4814** If p->aAuxDb[].zDbFilename is 0, then read from standard input. 4815*/ 4816static unsigned char *readHexDb(ShellState *p, int *pnData){ 4817 unsigned char *a = 0; 4818 int nLine; 4819 int n = 0; 4820 int pgsz = 0; 4821 int iOffset = 0; 4822 int j, k; 4823 int rc; 4824 FILE *in; 4825 const char *zDbFilename = p->pAuxDb->zDbFilename; 4826 unsigned int x[16]; 4827 char zLine[1000]; 4828 if( zDbFilename ){ 4829 in = fopen(zDbFilename, "r"); 4830 if( in==0 ){ 4831 utf8_printf(stderr, "cannot open \"%s\" for reading\n", zDbFilename); 4832 return 0; 4833 } 4834 nLine = 0; 4835 }else{ 4836 in = p->in; 4837 nLine = p->lineno; 4838 if( in==0 ) in = stdin; 4839 } 4840 *pnData = 0; 4841 nLine++; 4842 if( fgets(zLine, sizeof(zLine), in)==0 ) goto readHexDb_error; 4843 rc = sscanf(zLine, "| size %d pagesize %d", &n, &pgsz); 4844 if( rc!=2 ) goto readHexDb_error; 4845 if( n<0 ) goto readHexDb_error; 4846 if( pgsz<512 || pgsz>65536 || (pgsz&(pgsz-1))!=0 ) goto readHexDb_error; 4847 n = (n+pgsz-1)&~(pgsz-1); /* Round n up to the next multiple of pgsz */ 4848 a = sqlite3_malloc( n ? n : 1 ); 4849 shell_check_oom(a); 4850 memset(a, 0, n); 4851 if( pgsz<512 || pgsz>65536 || (pgsz & (pgsz-1))!=0 ){ 4852 utf8_printf(stderr, "invalid pagesize\n"); 4853 goto readHexDb_error; 4854 } 4855 for(nLine++; fgets(zLine, sizeof(zLine), in)!=0; nLine++){ 4856 rc = sscanf(zLine, "| page %d offset %d", &j, &k); 4857 if( rc==2 ){ 4858 iOffset = k; 4859 continue; 4860 } 4861 if( cli_strncmp(zLine, "| end ", 6)==0 ){ 4862 break; 4863 } 4864 rc = sscanf(zLine,"| %d: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x", 4865 &j, &x[0], &x[1], &x[2], &x[3], &x[4], &x[5], &x[6], &x[7], 4866 &x[8], &x[9], &x[10], &x[11], &x[12], &x[13], &x[14], &x[15]); 4867 if( rc==17 ){ 4868 k = iOffset+j; 4869 if( k+16<=n && k>=0 ){ 4870 int ii; 4871 for(ii=0; ii<16; ii++) a[k+ii] = x[ii]&0xff; 4872 } 4873 } 4874 } 4875 *pnData = n; 4876 if( in!=p->in ){ 4877 fclose(in); 4878 }else{ 4879 p->lineno = nLine; 4880 } 4881 return a; 4882 4883readHexDb_error: 4884 if( in!=p->in ){ 4885 fclose(in); 4886 }else{ 4887 while( fgets(zLine, sizeof(zLine), p->in)!=0 ){ 4888 nLine++; 4889 if(cli_strncmp(zLine, "| end ", 6)==0 ) break; 4890 } 4891 p->lineno = nLine; 4892 } 4893 sqlite3_free(a); 4894 utf8_printf(stderr,"Error on line %d of --hexdb input\n", nLine); 4895 return 0; 4896} 4897#endif /* SQLITE_OMIT_DESERIALIZE */ 4898 4899/* 4900** Scalar function "shell_int32". The first argument to this function 4901** must be a blob. The second a non-negative integer. This function 4902** reads and returns a 32-bit big-endian integer from byte 4903** offset (4*<arg2>) of the blob. 4904*/ 4905static void shellInt32( 4906 sqlite3_context *context, 4907 int argc, 4908 sqlite3_value **argv 4909){ 4910 const unsigned char *pBlob; 4911 int nBlob; 4912 int iInt; 4913 4914 UNUSED_PARAMETER(argc); 4915 nBlob = sqlite3_value_bytes(argv[0]); 4916 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 4917 iInt = sqlite3_value_int(argv[1]); 4918 4919 if( iInt>=0 && (iInt+1)*4<=nBlob ){ 4920 const unsigned char *a = &pBlob[iInt*4]; 4921 sqlite3_int64 iVal = ((sqlite3_int64)a[0]<<24) 4922 + ((sqlite3_int64)a[1]<<16) 4923 + ((sqlite3_int64)a[2]<< 8) 4924 + ((sqlite3_int64)a[3]<< 0); 4925 sqlite3_result_int64(context, iVal); 4926 } 4927} 4928 4929/* 4930** Scalar function "shell_idquote(X)" returns string X quoted as an identifier, 4931** using "..." with internal double-quote characters doubled. 4932*/ 4933static void shellIdQuote( 4934 sqlite3_context *context, 4935 int argc, 4936 sqlite3_value **argv 4937){ 4938 const char *zName = (const char*)sqlite3_value_text(argv[0]); 4939 UNUSED_PARAMETER(argc); 4940 if( zName ){ 4941 char *z = sqlite3_mprintf("\"%w\"", zName); 4942 sqlite3_result_text(context, z, -1, sqlite3_free); 4943 } 4944} 4945 4946/* 4947** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X. 4948*/ 4949static void shellUSleepFunc( 4950 sqlite3_context *context, 4951 int argcUnused, 4952 sqlite3_value **argv 4953){ 4954 int sleep = sqlite3_value_int(argv[0]); 4955 (void)argcUnused; 4956 sqlite3_sleep(sleep/1000); 4957 sqlite3_result_int(context, sleep); 4958} 4959 4960/* 4961** Scalar function "shell_escape_crnl" used by the .recover command. 4962** The argument passed to this function is the output of built-in 4963** function quote(). If the first character of the input is "'", 4964** indicating that the value passed to quote() was a text value, 4965** then this function searches the input for "\n" and "\r" characters 4966** and adds a wrapper similar to the following: 4967** 4968** replace(replace(<input>, '\n', char(10), '\r', char(13)); 4969** 4970** Or, if the first character of the input is not "'", then a copy 4971** of the input is returned. 4972*/ 4973static void shellEscapeCrnl( 4974 sqlite3_context *context, 4975 int argc, 4976 sqlite3_value **argv 4977){ 4978 const char *zText = (const char*)sqlite3_value_text(argv[0]); 4979 UNUSED_PARAMETER(argc); 4980 if( zText && zText[0]=='\'' ){ 4981 i64 nText = sqlite3_value_bytes(argv[0]); 4982 i64 i; 4983 char zBuf1[20]; 4984 char zBuf2[20]; 4985 const char *zNL = 0; 4986 const char *zCR = 0; 4987 i64 nCR = 0; 4988 i64 nNL = 0; 4989 4990 for(i=0; zText[i]; i++){ 4991 if( zNL==0 && zText[i]=='\n' ){ 4992 zNL = unused_string(zText, "\\n", "\\012", zBuf1); 4993 nNL = strlen(zNL); 4994 } 4995 if( zCR==0 && zText[i]=='\r' ){ 4996 zCR = unused_string(zText, "\\r", "\\015", zBuf2); 4997 nCR = strlen(zCR); 4998 } 4999 } 5000 5001 if( zNL || zCR ){ 5002 i64 iOut = 0; 5003 i64 nMax = (nNL > nCR) ? nNL : nCR; 5004 i64 nAlloc = nMax * nText + (nMax+64)*2; 5005 char *zOut = (char*)sqlite3_malloc64(nAlloc); 5006 if( zOut==0 ){ 5007 sqlite3_result_error_nomem(context); 5008 return; 5009 } 5010 5011 if( zNL && zCR ){ 5012 memcpy(&zOut[iOut], "replace(replace(", 16); 5013 iOut += 16; 5014 }else{ 5015 memcpy(&zOut[iOut], "replace(", 8); 5016 iOut += 8; 5017 } 5018 for(i=0; zText[i]; i++){ 5019 if( zText[i]=='\n' ){ 5020 memcpy(&zOut[iOut], zNL, nNL); 5021 iOut += nNL; 5022 }else if( zText[i]=='\r' ){ 5023 memcpy(&zOut[iOut], zCR, nCR); 5024 iOut += nCR; 5025 }else{ 5026 zOut[iOut] = zText[i]; 5027 iOut++; 5028 } 5029 } 5030 5031 if( zNL ){ 5032 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 5033 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 5034 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 5035 } 5036 if( zCR ){ 5037 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 5038 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 5039 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 5040 } 5041 5042 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 5043 sqlite3_free(zOut); 5044 return; 5045 } 5046 } 5047 5048 sqlite3_result_value(context, argv[0]); 5049} 5050 5051/* Flags for open_db(). 5052** 5053** The default behavior of open_db() is to exit(1) if the database fails to 5054** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error 5055** but still returns without calling exit. 5056** 5057** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a 5058** ZIP archive if the file does not exist or is empty and its name matches 5059** the *.zip pattern. 5060*/ 5061#define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */ 5062#define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */ 5063 5064/* 5065** Make sure the database is open. If it is not, then open it. If 5066** the database fails to open, print an error message and exit. 5067*/ 5068static void open_db(ShellState *p, int openFlags){ 5069 if( p->db==0 ){ 5070 const char *zDbFilename = p->pAuxDb->zDbFilename; 5071 if( p->openMode==SHELL_OPEN_UNSPEC ){ 5072 if( zDbFilename==0 || zDbFilename[0]==0 ){ 5073 p->openMode = SHELL_OPEN_NORMAL; 5074 }else{ 5075 p->openMode = (u8)deduceDatabaseType(zDbFilename, 5076 (openFlags & OPEN_DB_ZIPFILE)!=0); 5077 } 5078 } 5079 switch( p->openMode ){ 5080 case SHELL_OPEN_APPENDVFS: { 5081 sqlite3_open_v2(zDbFilename, &p->db, 5082 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs"); 5083 break; 5084 } 5085 case SHELL_OPEN_HEXDB: 5086 case SHELL_OPEN_DESERIALIZE: { 5087 sqlite3_open(0, &p->db); 5088 break; 5089 } 5090 case SHELL_OPEN_ZIPFILE: { 5091 sqlite3_open(":memory:", &p->db); 5092 break; 5093 } 5094 case SHELL_OPEN_READONLY: { 5095 sqlite3_open_v2(zDbFilename, &p->db, 5096 SQLITE_OPEN_READONLY|p->openFlags, 0); 5097 break; 5098 } 5099 case SHELL_OPEN_UNSPEC: 5100 case SHELL_OPEN_NORMAL: { 5101 sqlite3_open_v2(zDbFilename, &p->db, 5102 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0); 5103 break; 5104 } 5105 } 5106 globalDb = p->db; 5107 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ 5108 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", 5109 zDbFilename, sqlite3_errmsg(p->db)); 5110 if( openFlags & OPEN_DB_KEEPALIVE ){ 5111 sqlite3_open(":memory:", &p->db); 5112 return; 5113 } 5114 exit(1); 5115 } 5116#ifndef SQLITE_OMIT_LOAD_EXTENSION 5117 sqlite3_enable_load_extension(p->db, 1); 5118#endif 5119 sqlite3_shathree_init(p->db, 0, 0); 5120 sqlite3_uint_init(p->db, 0, 0); 5121 sqlite3_decimal_init(p->db, 0, 0); 5122 sqlite3_regexp_init(p->db, 0, 0); 5123 sqlite3_ieee_init(p->db, 0, 0); 5124 sqlite3_series_init(p->db, 0, 0); 5125#ifndef SQLITE_SHELL_FIDDLE 5126 sqlite3_fileio_init(p->db, 0, 0); 5127 sqlite3_completion_init(p->db, 0, 0); 5128#endif 5129#if SQLITE_SHELL_HAVE_RECOVER 5130 sqlite3_dbdata_init(p->db, 0, 0); 5131#endif 5132#ifdef SQLITE_HAVE_ZLIB 5133 if( !p->bSafeModePersist ){ 5134 sqlite3_zipfile_init(p->db, 0, 0); 5135 sqlite3_sqlar_init(p->db, 0, 0); 5136 } 5137#endif 5138 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0, 5139 shellAddSchemaName, 0, 0); 5140 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0, 5141 shellModuleSchema, 0, 0); 5142 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p, 5143 shellPutsFunc, 0, 0); 5144 sqlite3_create_function(p->db, "shell_escape_crnl", 1, SQLITE_UTF8, 0, 5145 shellEscapeCrnl, 0, 0); 5146 sqlite3_create_function(p->db, "shell_int32", 2, SQLITE_UTF8, 0, 5147 shellInt32, 0, 0); 5148 sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0, 5149 shellIdQuote, 0, 0); 5150 sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0, 5151 shellUSleepFunc, 0, 0); 5152#ifndef SQLITE_NOHAVE_SYSTEM 5153 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0, 5154 editFunc, 0, 0); 5155 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0, 5156 editFunc, 0, 0); 5157#endif 5158 if( p->openMode==SHELL_OPEN_ZIPFILE ){ 5159 char *zSql = sqlite3_mprintf( 5160 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", zDbFilename); 5161 shell_check_oom(zSql); 5162 sqlite3_exec(p->db, zSql, 0, 0, 0); 5163 sqlite3_free(zSql); 5164 } 5165#ifndef SQLITE_OMIT_DESERIALIZE 5166 else 5167 if( p->openMode==SHELL_OPEN_DESERIALIZE || p->openMode==SHELL_OPEN_HEXDB ){ 5168 int rc; 5169 int nData = 0; 5170 unsigned char *aData; 5171 if( p->openMode==SHELL_OPEN_DESERIALIZE ){ 5172 aData = (unsigned char*)readFile(zDbFilename, &nData); 5173 }else{ 5174 aData = readHexDb(p, &nData); 5175 if( aData==0 ){ 5176 return; 5177 } 5178 } 5179 rc = sqlite3_deserialize(p->db, "main", aData, nData, nData, 5180 SQLITE_DESERIALIZE_RESIZEABLE | 5181 SQLITE_DESERIALIZE_FREEONCLOSE); 5182 if( rc ){ 5183 utf8_printf(stderr, "Error: sqlite3_deserialize() returns %d\n", rc); 5184 } 5185 if( p->szMax>0 ){ 5186 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_SIZE_LIMIT, &p->szMax); 5187 } 5188 } 5189#endif 5190 } 5191 if( p->bSafeModePersist && p->db!=0 ){ 5192 sqlite3_set_authorizer(p->db, safeModeAuth, p); 5193 } 5194} 5195 5196/* 5197** Attempt to close the databaes connection. Report errors. 5198*/ 5199void close_db(sqlite3 *db){ 5200 int rc = sqlite3_close(db); 5201 if( rc ){ 5202 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n", 5203 rc, sqlite3_errmsg(db)); 5204 } 5205} 5206 5207#if HAVE_READLINE || HAVE_EDITLINE 5208/* 5209** Readline completion callbacks 5210*/ 5211static char *readline_completion_generator(const char *text, int state){ 5212 static sqlite3_stmt *pStmt = 0; 5213 char *zRet; 5214 if( state==0 ){ 5215 char *zSql; 5216 sqlite3_finalize(pStmt); 5217 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 5218 " FROM completion(%Q) ORDER BY 1", text); 5219 shell_check_oom(zSql); 5220 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 5221 sqlite3_free(zSql); 5222 } 5223 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 5224 const char *z = (const char*)sqlite3_column_text(pStmt,0); 5225 zRet = z ? strdup(z) : 0; 5226 }else{ 5227 sqlite3_finalize(pStmt); 5228 pStmt = 0; 5229 zRet = 0; 5230 } 5231 return zRet; 5232} 5233static char **readline_completion(const char *zText, int iStart, int iEnd){ 5234 rl_attempted_completion_over = 1; 5235 return rl_completion_matches(zText, readline_completion_generator); 5236} 5237 5238#elif HAVE_LINENOISE 5239/* 5240** Linenoise completion callback 5241*/ 5242static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){ 5243 i64 nLine = strlen(zLine); 5244 i64 i, iStart; 5245 sqlite3_stmt *pStmt = 0; 5246 char *zSql; 5247 char zBuf[1000]; 5248 5249 if( nLine>sizeof(zBuf)-30 ) return; 5250 if( zLine[0]=='.' || zLine[0]=='#') return; 5251 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){} 5252 if( i==nLine-1 ) return; 5253 iStart = i+1; 5254 memcpy(zBuf, zLine, iStart); 5255 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase" 5256 " FROM completion(%Q,%Q) ORDER BY 1", 5257 &zLine[iStart], zLine); 5258 shell_check_oom(zSql); 5259 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0); 5260 sqlite3_free(zSql); 5261 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */ 5262 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 5263 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0); 5264 int nCompletion = sqlite3_column_bytes(pStmt, 0); 5265 if( iStart+nCompletion < sizeof(zBuf)-1 && zCompletion ){ 5266 memcpy(zBuf+iStart, zCompletion, nCompletion+1); 5267 linenoiseAddCompletion(lc, zBuf); 5268 } 5269 } 5270 sqlite3_finalize(pStmt); 5271} 5272#endif 5273 5274/* 5275** Do C-language style dequoting. 5276** 5277** \a -> alarm 5278** \b -> backspace 5279** \t -> tab 5280** \n -> newline 5281** \v -> vertical tab 5282** \f -> form feed 5283** \r -> carriage return 5284** \s -> space 5285** \" -> " 5286** \' -> ' 5287** \\ -> backslash 5288** \NNN -> ascii character NNN in octal 5289*/ 5290static void resolve_backslashes(char *z){ 5291 int i, j; 5292 char c; 5293 while( *z && *z!='\\' ) z++; 5294 for(i=j=0; (c = z[i])!=0; i++, j++){ 5295 if( c=='\\' && z[i+1]!=0 ){ 5296 c = z[++i]; 5297 if( c=='a' ){ 5298 c = '\a'; 5299 }else if( c=='b' ){ 5300 c = '\b'; 5301 }else if( c=='t' ){ 5302 c = '\t'; 5303 }else if( c=='n' ){ 5304 c = '\n'; 5305 }else if( c=='v' ){ 5306 c = '\v'; 5307 }else if( c=='f' ){ 5308 c = '\f'; 5309 }else if( c=='r' ){ 5310 c = '\r'; 5311 }else if( c=='"' ){ 5312 c = '"'; 5313 }else if( c=='\'' ){ 5314 c = '\''; 5315 }else if( c=='\\' ){ 5316 c = '\\'; 5317 }else if( c>='0' && c<='7' ){ 5318 c -= '0'; 5319 if( z[i+1]>='0' && z[i+1]<='7' ){ 5320 i++; 5321 c = (c<<3) + z[i] - '0'; 5322 if( z[i+1]>='0' && z[i+1]<='7' ){ 5323 i++; 5324 c = (c<<3) + z[i] - '0'; 5325 } 5326 } 5327 } 5328 } 5329 z[j] = c; 5330 } 5331 if( j<i ) z[j] = 0; 5332} 5333 5334/* 5335** Interpret zArg as either an integer or a boolean value. Return 1 or 0 5336** for TRUE and FALSE. Return the integer value if appropriate. 5337*/ 5338static int booleanValue(const char *zArg){ 5339 int i; 5340 if( zArg[0]=='0' && zArg[1]=='x' ){ 5341 for(i=2; hexDigitValue(zArg[i])>=0; i++){} 5342 }else{ 5343 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} 5344 } 5345 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); 5346 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ 5347 return 1; 5348 } 5349 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ 5350 return 0; 5351 } 5352 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", 5353 zArg); 5354 return 0; 5355} 5356 5357/* 5358** Set or clear a shell flag according to a boolean value. 5359*/ 5360static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){ 5361 if( booleanValue(zArg) ){ 5362 ShellSetFlag(p, mFlag); 5363 }else{ 5364 ShellClearFlag(p, mFlag); 5365 } 5366} 5367 5368/* 5369** Close an output file, assuming it is not stderr or stdout 5370*/ 5371static void output_file_close(FILE *f){ 5372 if( f && f!=stdout && f!=stderr ) fclose(f); 5373} 5374 5375/* 5376** Try to open an output file. The names "stdout" and "stderr" are 5377** recognized and do the right thing. NULL is returned if the output 5378** filename is "off". 5379*/ 5380static FILE *output_file_open(const char *zFile, int bTextMode){ 5381 FILE *f; 5382 if( cli_strcmp(zFile,"stdout")==0 ){ 5383 f = stdout; 5384 }else if( cli_strcmp(zFile, "stderr")==0 ){ 5385 f = stderr; 5386 }else if( cli_strcmp(zFile, "off")==0 ){ 5387 f = 0; 5388 }else{ 5389 f = fopen(zFile, bTextMode ? "w" : "wb"); 5390 if( f==0 ){ 5391 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 5392 } 5393 } 5394 return f; 5395} 5396 5397#ifndef SQLITE_OMIT_TRACE 5398/* 5399** A routine for handling output from sqlite3_trace(). 5400*/ 5401static int sql_trace_callback( 5402 unsigned mType, /* The trace type */ 5403 void *pArg, /* The ShellState pointer */ 5404 void *pP, /* Usually a pointer to sqlite_stmt */ 5405 void *pX /* Auxiliary output */ 5406){ 5407 ShellState *p = (ShellState*)pArg; 5408 sqlite3_stmt *pStmt; 5409 const char *zSql; 5410 i64 nSql; 5411 if( p->traceOut==0 ) return 0; 5412 if( mType==SQLITE_TRACE_CLOSE ){ 5413 utf8_printf(p->traceOut, "-- closing database connection\n"); 5414 return 0; 5415 } 5416 if( mType!=SQLITE_TRACE_ROW && ((const char*)pX)[0]=='-' ){ 5417 zSql = (const char*)pX; 5418 }else{ 5419 pStmt = (sqlite3_stmt*)pP; 5420 switch( p->eTraceType ){ 5421 case SHELL_TRACE_EXPANDED: { 5422 zSql = sqlite3_expanded_sql(pStmt); 5423 break; 5424 } 5425#ifdef SQLITE_ENABLE_NORMALIZE 5426 case SHELL_TRACE_NORMALIZED: { 5427 zSql = sqlite3_normalized_sql(pStmt); 5428 break; 5429 } 5430#endif 5431 default: { 5432 zSql = sqlite3_sql(pStmt); 5433 break; 5434 } 5435 } 5436 } 5437 if( zSql==0 ) return 0; 5438 nSql = strlen(zSql); 5439 if( nSql>1000000000 ) nSql = 1000000000; 5440 while( nSql>0 && zSql[nSql-1]==';' ){ nSql--; } 5441 switch( mType ){ 5442 case SQLITE_TRACE_ROW: 5443 case SQLITE_TRACE_STMT: { 5444 utf8_printf(p->traceOut, "%.*s;\n", (int)nSql, zSql); 5445 break; 5446 } 5447 case SQLITE_TRACE_PROFILE: { 5448 sqlite3_int64 nNanosec = *(sqlite3_int64*)pX; 5449 utf8_printf(p->traceOut, "%.*s; -- %lld ns\n", (int)nSql, zSql, nNanosec); 5450 break; 5451 } 5452 } 5453 return 0; 5454} 5455#endif 5456 5457/* 5458** A no-op routine that runs with the ".breakpoint" doc-command. This is 5459** a useful spot to set a debugger breakpoint. 5460*/ 5461static void test_breakpoint(void){ 5462 static int nCall = 0; 5463 nCall++; 5464} 5465 5466/* 5467** An object used to read a CSV and other files for import. 5468*/ 5469typedef struct ImportCtx ImportCtx; 5470struct ImportCtx { 5471 const char *zFile; /* Name of the input file */ 5472 FILE *in; /* Read the CSV text from this input stream */ 5473 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close in */ 5474 char *z; /* Accumulated text for a field */ 5475 int n; /* Number of bytes in z */ 5476 int nAlloc; /* Space allocated for z[] */ 5477 int nLine; /* Current line number */ 5478 int nRow; /* Number of rows imported */ 5479 int nErr; /* Number of errors encountered */ 5480 int bNotFirst; /* True if one or more bytes already read */ 5481 int cTerm; /* Character that terminated the most recent field */ 5482 int cColSep; /* The column separator character. (Usually ",") */ 5483 int cRowSep; /* The row separator character. (Usually "\n") */ 5484}; 5485 5486/* Clean up resourced used by an ImportCtx */ 5487static void import_cleanup(ImportCtx *p){ 5488 if( p->in!=0 && p->xCloser!=0 ){ 5489 p->xCloser(p->in); 5490 p->in = 0; 5491 } 5492 sqlite3_free(p->z); 5493 p->z = 0; 5494} 5495 5496/* Append a single byte to z[] */ 5497static void import_append_char(ImportCtx *p, int c){ 5498 if( p->n+1>=p->nAlloc ){ 5499 p->nAlloc += p->nAlloc + 100; 5500 p->z = sqlite3_realloc64(p->z, p->nAlloc); 5501 shell_check_oom(p->z); 5502 } 5503 p->z[p->n++] = (char)c; 5504} 5505 5506/* Read a single field of CSV text. Compatible with rfc4180 and extended 5507** with the option of having a separator other than ",". 5508** 5509** + Input comes from p->in. 5510** + Store results in p->z of length p->n. Space to hold p->z comes 5511** from sqlite3_malloc64(). 5512** + Use p->cSep as the column separator. The default is ",". 5513** + Use p->rSep as the row separator. The default is "\n". 5514** + Keep track of the line number in p->nLine. 5515** + Store the character that terminates the field in p->cTerm. Store 5516** EOF on end-of-file. 5517** + Report syntax errors on stderr 5518*/ 5519static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ 5520 int c; 5521 int cSep = p->cColSep; 5522 int rSep = p->cRowSep; 5523 p->n = 0; 5524 c = fgetc(p->in); 5525 if( c==EOF || seenInterrupt ){ 5526 p->cTerm = EOF; 5527 return 0; 5528 } 5529 if( c=='"' ){ 5530 int pc, ppc; 5531 int startLine = p->nLine; 5532 int cQuote = c; 5533 pc = ppc = 0; 5534 while( 1 ){ 5535 c = fgetc(p->in); 5536 if( c==rSep ) p->nLine++; 5537 if( c==cQuote ){ 5538 if( pc==cQuote ){ 5539 pc = 0; 5540 continue; 5541 } 5542 } 5543 if( (c==cSep && pc==cQuote) 5544 || (c==rSep && pc==cQuote) 5545 || (c==rSep && pc=='\r' && ppc==cQuote) 5546 || (c==EOF && pc==cQuote) 5547 ){ 5548 do{ p->n--; }while( p->z[p->n]!=cQuote ); 5549 p->cTerm = c; 5550 break; 5551 } 5552 if( pc==cQuote && c!='\r' ){ 5553 utf8_printf(stderr, "%s:%d: unescaped %c character\n", 5554 p->zFile, p->nLine, cQuote); 5555 } 5556 if( c==EOF ){ 5557 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", 5558 p->zFile, startLine, cQuote); 5559 p->cTerm = c; 5560 break; 5561 } 5562 import_append_char(p, c); 5563 ppc = pc; 5564 pc = c; 5565 } 5566 }else{ 5567 /* If this is the first field being parsed and it begins with the 5568 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 5569 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 5570 import_append_char(p, c); 5571 c = fgetc(p->in); 5572 if( (c&0xff)==0xbb ){ 5573 import_append_char(p, c); 5574 c = fgetc(p->in); 5575 if( (c&0xff)==0xbf ){ 5576 p->bNotFirst = 1; 5577 p->n = 0; 5578 return csv_read_one_field(p); 5579 } 5580 } 5581 } 5582 while( c!=EOF && c!=cSep && c!=rSep ){ 5583 import_append_char(p, c); 5584 c = fgetc(p->in); 5585 } 5586 if( c==rSep ){ 5587 p->nLine++; 5588 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 5589 } 5590 p->cTerm = c; 5591 } 5592 if( p->z ) p->z[p->n] = 0; 5593 p->bNotFirst = 1; 5594 return p->z; 5595} 5596 5597/* Read a single field of ASCII delimited text. 5598** 5599** + Input comes from p->in. 5600** + Store results in p->z of length p->n. Space to hold p->z comes 5601** from sqlite3_malloc64(). 5602** + Use p->cSep as the column separator. The default is "\x1F". 5603** + Use p->rSep as the row separator. The default is "\x1E". 5604** + Keep track of the row number in p->nLine. 5605** + Store the character that terminates the field in p->cTerm. Store 5606** EOF on end-of-file. 5607** + Report syntax errors on stderr 5608*/ 5609static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ 5610 int c; 5611 int cSep = p->cColSep; 5612 int rSep = p->cRowSep; 5613 p->n = 0; 5614 c = fgetc(p->in); 5615 if( c==EOF || seenInterrupt ){ 5616 p->cTerm = EOF; 5617 return 0; 5618 } 5619 while( c!=EOF && c!=cSep && c!=rSep ){ 5620 import_append_char(p, c); 5621 c = fgetc(p->in); 5622 } 5623 if( c==rSep ){ 5624 p->nLine++; 5625 } 5626 p->cTerm = c; 5627 if( p->z ) p->z[p->n] = 0; 5628 return p->z; 5629} 5630 5631/* 5632** Try to transfer data for table zTable. If an error is seen while 5633** moving forward, try to go backwards. The backwards movement won't 5634** work for WITHOUT ROWID tables. 5635*/ 5636static void tryToCloneData( 5637 ShellState *p, 5638 sqlite3 *newDb, 5639 const char *zTable 5640){ 5641 sqlite3_stmt *pQuery = 0; 5642 sqlite3_stmt *pInsert = 0; 5643 char *zQuery = 0; 5644 char *zInsert = 0; 5645 int rc; 5646 int i, j, n; 5647 int nTable = strlen30(zTable); 5648 int k = 0; 5649 int cnt = 0; 5650 const int spinRate = 10000; 5651 5652 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); 5653 shell_check_oom(zQuery); 5654 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5655 if( rc ){ 5656 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5657 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5658 zQuery); 5659 goto end_data_xfer; 5660 } 5661 n = sqlite3_column_count(pQuery); 5662 zInsert = sqlite3_malloc64(200 + nTable + n*3); 5663 shell_check_oom(zInsert); 5664 sqlite3_snprintf(200+nTable,zInsert, 5665 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); 5666 i = strlen30(zInsert); 5667 for(j=1; j<n; j++){ 5668 memcpy(zInsert+i, ",?", 2); 5669 i += 2; 5670 } 5671 memcpy(zInsert+i, ");", 3); 5672 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); 5673 if( rc ){ 5674 utf8_printf(stderr, "Error %d: %s on [%s]\n", 5675 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), 5676 zQuery); 5677 goto end_data_xfer; 5678 } 5679 for(k=0; k<2; k++){ 5680 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5681 for(i=0; i<n; i++){ 5682 switch( sqlite3_column_type(pQuery, i) ){ 5683 case SQLITE_NULL: { 5684 sqlite3_bind_null(pInsert, i+1); 5685 break; 5686 } 5687 case SQLITE_INTEGER: { 5688 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); 5689 break; 5690 } 5691 case SQLITE_FLOAT: { 5692 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); 5693 break; 5694 } 5695 case SQLITE_TEXT: { 5696 sqlite3_bind_text(pInsert, i+1, 5697 (const char*)sqlite3_column_text(pQuery,i), 5698 -1, SQLITE_STATIC); 5699 break; 5700 } 5701 case SQLITE_BLOB: { 5702 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), 5703 sqlite3_column_bytes(pQuery,i), 5704 SQLITE_STATIC); 5705 break; 5706 } 5707 } 5708 } /* End for */ 5709 rc = sqlite3_step(pInsert); 5710 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ 5711 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), 5712 sqlite3_errmsg(newDb)); 5713 } 5714 sqlite3_reset(pInsert); 5715 cnt++; 5716 if( (cnt%spinRate)==0 ){ 5717 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); 5718 fflush(stdout); 5719 } 5720 } /* End while */ 5721 if( rc==SQLITE_DONE ) break; 5722 sqlite3_finalize(pQuery); 5723 sqlite3_free(zQuery); 5724 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", 5725 zTable); 5726 shell_check_oom(zQuery); 5727 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5728 if( rc ){ 5729 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); 5730 break; 5731 } 5732 } /* End for(k=0...) */ 5733 5734end_data_xfer: 5735 sqlite3_finalize(pQuery); 5736 sqlite3_finalize(pInsert); 5737 sqlite3_free(zQuery); 5738 sqlite3_free(zInsert); 5739} 5740 5741 5742/* 5743** Try to transfer all rows of the schema that match zWhere. For 5744** each row, invoke xForEach() on the object defined by that row. 5745** If an error is encountered while moving forward through the 5746** sqlite_schema table, try again moving backwards. 5747*/ 5748static void tryToCloneSchema( 5749 ShellState *p, 5750 sqlite3 *newDb, 5751 const char *zWhere, 5752 void (*xForEach)(ShellState*,sqlite3*,const char*) 5753){ 5754 sqlite3_stmt *pQuery = 0; 5755 char *zQuery = 0; 5756 int rc; 5757 const unsigned char *zName; 5758 const unsigned char *zSql; 5759 char *zErrMsg = 0; 5760 5761 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5762 " WHERE %s", zWhere); 5763 shell_check_oom(zQuery); 5764 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5765 if( rc ){ 5766 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5767 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5768 zQuery); 5769 goto end_schema_xfer; 5770 } 5771 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ 5772 zName = sqlite3_column_text(pQuery, 0); 5773 zSql = sqlite3_column_text(pQuery, 1); 5774 if( zName==0 || zSql==0 ) continue; 5775 printf("%s... ", zName); fflush(stdout); 5776 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5777 if( zErrMsg ){ 5778 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5779 sqlite3_free(zErrMsg); 5780 zErrMsg = 0; 5781 } 5782 if( xForEach ){ 5783 xForEach(p, newDb, (const char*)zName); 5784 } 5785 printf("done\n"); 5786 } 5787 if( rc!=SQLITE_DONE ){ 5788 sqlite3_finalize(pQuery); 5789 sqlite3_free(zQuery); 5790 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema" 5791 " WHERE %s ORDER BY rowid DESC", zWhere); 5792 shell_check_oom(zQuery); 5793 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); 5794 if( rc ){ 5795 utf8_printf(stderr, "Error: (%d) %s on [%s]\n", 5796 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), 5797 zQuery); 5798 goto end_schema_xfer; 5799 } 5800 while( sqlite3_step(pQuery)==SQLITE_ROW ){ 5801 zName = sqlite3_column_text(pQuery, 0); 5802 zSql = sqlite3_column_text(pQuery, 1); 5803 if( zName==0 || zSql==0 ) continue; 5804 printf("%s... ", zName); fflush(stdout); 5805 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); 5806 if( zErrMsg ){ 5807 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); 5808 sqlite3_free(zErrMsg); 5809 zErrMsg = 0; 5810 } 5811 if( xForEach ){ 5812 xForEach(p, newDb, (const char*)zName); 5813 } 5814 printf("done\n"); 5815 } 5816 } 5817end_schema_xfer: 5818 sqlite3_finalize(pQuery); 5819 sqlite3_free(zQuery); 5820} 5821 5822/* 5823** Open a new database file named "zNewDb". Try to recover as much information 5824** as possible out of the main database (which might be corrupt) and write it 5825** into zNewDb. 5826*/ 5827static void tryToClone(ShellState *p, const char *zNewDb){ 5828 int rc; 5829 sqlite3 *newDb = 0; 5830 if( access(zNewDb,0)==0 ){ 5831 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); 5832 return; 5833 } 5834 rc = sqlite3_open(zNewDb, &newDb); 5835 if( rc ){ 5836 utf8_printf(stderr, "Cannot create output database: %s\n", 5837 sqlite3_errmsg(newDb)); 5838 }else{ 5839 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); 5840 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); 5841 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); 5842 tryToCloneSchema(p, newDb, "type!='table'", 0); 5843 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); 5844 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 5845 } 5846 close_db(newDb); 5847} 5848 5849/* 5850** Change the output file back to stdout. 5851** 5852** If the p->doXdgOpen flag is set, that means the output was being 5853** redirected to a temporary file named by p->zTempFile. In that case, 5854** launch start/open/xdg-open on that temporary file. 5855*/ 5856static void output_reset(ShellState *p){ 5857 if( p->outfile[0]=='|' ){ 5858#ifndef SQLITE_OMIT_POPEN 5859 pclose(p->out); 5860#endif 5861 }else{ 5862 output_file_close(p->out); 5863#ifndef SQLITE_NOHAVE_SYSTEM 5864 if( p->doXdgOpen ){ 5865 const char *zXdgOpenCmd = 5866#if defined(_WIN32) 5867 "start"; 5868#elif defined(__APPLE__) 5869 "open"; 5870#else 5871 "xdg-open"; 5872#endif 5873 char *zCmd; 5874 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile); 5875 if( system(zCmd) ){ 5876 utf8_printf(stderr, "Failed: [%s]\n", zCmd); 5877 }else{ 5878 /* Give the start/open/xdg-open command some time to get 5879 ** going before we continue, and potential delete the 5880 ** p->zTempFile data file out from under it */ 5881 sqlite3_sleep(2000); 5882 } 5883 sqlite3_free(zCmd); 5884 outputModePop(p); 5885 p->doXdgOpen = 0; 5886 } 5887#endif /* !defined(SQLITE_NOHAVE_SYSTEM) */ 5888 } 5889 p->outfile[0] = 0; 5890 p->out = stdout; 5891} 5892 5893/* 5894** Run an SQL command and return the single integer result. 5895*/ 5896static int db_int(sqlite3 *db, const char *zSql){ 5897 sqlite3_stmt *pStmt; 5898 int res = 0; 5899 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); 5900 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 5901 res = sqlite3_column_int(pStmt,0); 5902 } 5903 sqlite3_finalize(pStmt); 5904 return res; 5905} 5906 5907#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) 5908/* 5909** Convert a 2-byte or 4-byte big-endian integer into a native integer 5910*/ 5911static unsigned int get2byteInt(unsigned char *a){ 5912 return (a[0]<<8) + a[1]; 5913} 5914static unsigned int get4byteInt(unsigned char *a){ 5915 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; 5916} 5917 5918/* 5919** Implementation of the ".dbinfo" command. 5920** 5921** Return 1 on error, 2 to exit, and 0 otherwise. 5922*/ 5923static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ 5924 static const struct { const char *zName; int ofst; } aField[] = { 5925 { "file change counter:", 24 }, 5926 { "database page count:", 28 }, 5927 { "freelist page count:", 36 }, 5928 { "schema cookie:", 40 }, 5929 { "schema format:", 44 }, 5930 { "default cache size:", 48 }, 5931 { "autovacuum top root:", 52 }, 5932 { "incremental vacuum:", 64 }, 5933 { "text encoding:", 56 }, 5934 { "user version:", 60 }, 5935 { "application id:", 68 }, 5936 { "software version:", 96 }, 5937 }; 5938 static const struct { const char *zName; const char *zSql; } aQuery[] = { 5939 { "number of tables:", 5940 "SELECT count(*) FROM %s WHERE type='table'" }, 5941 { "number of indexes:", 5942 "SELECT count(*) FROM %s WHERE type='index'" }, 5943 { "number of triggers:", 5944 "SELECT count(*) FROM %s WHERE type='trigger'" }, 5945 { "number of views:", 5946 "SELECT count(*) FROM %s WHERE type='view'" }, 5947 { "schema size:", 5948 "SELECT total(length(sql)) FROM %s" }, 5949 }; 5950 int i, rc; 5951 unsigned iDataVersion; 5952 char *zSchemaTab; 5953 char *zDb = nArg>=2 ? azArg[1] : "main"; 5954 sqlite3_stmt *pStmt = 0; 5955 unsigned char aHdr[100]; 5956 open_db(p, 0); 5957 if( p->db==0 ) return 1; 5958 rc = sqlite3_prepare_v2(p->db, 5959 "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1", 5960 -1, &pStmt, 0); 5961 if( rc ){ 5962 utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db)); 5963 sqlite3_finalize(pStmt); 5964 return 1; 5965 } 5966 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC); 5967 if( sqlite3_step(pStmt)==SQLITE_ROW 5968 && sqlite3_column_bytes(pStmt,0)>100 5969 ){ 5970 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100); 5971 sqlite3_finalize(pStmt); 5972 }else{ 5973 raw_printf(stderr, "unable to read database header\n"); 5974 sqlite3_finalize(pStmt); 5975 return 1; 5976 } 5977 i = get2byteInt(aHdr+16); 5978 if( i==1 ) i = 65536; 5979 utf8_printf(p->out, "%-20s %d\n", "database page size:", i); 5980 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); 5981 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); 5982 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); 5983 for(i=0; i<ArraySize(aField); i++){ 5984 int ofst = aField[i].ofst; 5985 unsigned int val = get4byteInt(aHdr + ofst); 5986 utf8_printf(p->out, "%-20s %u", aField[i].zName, val); 5987 switch( ofst ){ 5988 case 56: { 5989 if( val==1 ) raw_printf(p->out, " (utf8)"); 5990 if( val==2 ) raw_printf(p->out, " (utf16le)"); 5991 if( val==3 ) raw_printf(p->out, " (utf16be)"); 5992 } 5993 } 5994 raw_printf(p->out, "\n"); 5995 } 5996 if( zDb==0 ){ 5997 zSchemaTab = sqlite3_mprintf("main.sqlite_schema"); 5998 }else if( cli_strcmp(zDb,"temp")==0 ){ 5999 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema"); 6000 }else{ 6001 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb); 6002 } 6003 for(i=0; i<ArraySize(aQuery); i++){ 6004 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); 6005 int val = db_int(p->db, zSql); 6006 sqlite3_free(zSql); 6007 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); 6008 } 6009 sqlite3_free(zSchemaTab); 6010 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion); 6011 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion); 6012 return 0; 6013} 6014#endif /* SQLITE_SHELL_HAVE_RECOVER */ 6015 6016/* 6017** Print the current sqlite3_errmsg() value to stderr and return 1. 6018*/ 6019static int shellDatabaseError(sqlite3 *db){ 6020 const char *zErr = sqlite3_errmsg(db); 6021 utf8_printf(stderr, "Error: %s\n", zErr); 6022 return 1; 6023} 6024 6025/* 6026** Compare the pattern in zGlob[] against the text in z[]. Return TRUE 6027** if they match and FALSE (0) if they do not match. 6028** 6029** Globbing rules: 6030** 6031** '*' Matches any sequence of zero or more characters. 6032** 6033** '?' Matches exactly one character. 6034** 6035** [...] Matches one character from the enclosed list of 6036** characters. 6037** 6038** [^...] Matches one character not in the enclosed list. 6039** 6040** '#' Matches any sequence of one or more digits with an 6041** optional + or - sign in front 6042** 6043** ' ' Any span of whitespace matches any other span of 6044** whitespace. 6045** 6046** Extra whitespace at the end of z[] is ignored. 6047*/ 6048static int testcase_glob(const char *zGlob, const char *z){ 6049 int c, c2; 6050 int invert; 6051 int seen; 6052 6053 while( (c = (*(zGlob++)))!=0 ){ 6054 if( IsSpace(c) ){ 6055 if( !IsSpace(*z) ) return 0; 6056 while( IsSpace(*zGlob) ) zGlob++; 6057 while( IsSpace(*z) ) z++; 6058 }else if( c=='*' ){ 6059 while( (c=(*(zGlob++))) == '*' || c=='?' ){ 6060 if( c=='?' && (*(z++))==0 ) return 0; 6061 } 6062 if( c==0 ){ 6063 return 1; 6064 }else if( c=='[' ){ 6065 while( *z && testcase_glob(zGlob-1,z)==0 ){ 6066 z++; 6067 } 6068 return (*z)!=0; 6069 } 6070 while( (c2 = (*(z++)))!=0 ){ 6071 while( c2!=c ){ 6072 c2 = *(z++); 6073 if( c2==0 ) return 0; 6074 } 6075 if( testcase_glob(zGlob,z) ) return 1; 6076 } 6077 return 0; 6078 }else if( c=='?' ){ 6079 if( (*(z++))==0 ) return 0; 6080 }else if( c=='[' ){ 6081 int prior_c = 0; 6082 seen = 0; 6083 invert = 0; 6084 c = *(z++); 6085 if( c==0 ) return 0; 6086 c2 = *(zGlob++); 6087 if( c2=='^' ){ 6088 invert = 1; 6089 c2 = *(zGlob++); 6090 } 6091 if( c2==']' ){ 6092 if( c==']' ) seen = 1; 6093 c2 = *(zGlob++); 6094 } 6095 while( c2 && c2!=']' ){ 6096 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){ 6097 c2 = *(zGlob++); 6098 if( c>=prior_c && c<=c2 ) seen = 1; 6099 prior_c = 0; 6100 }else{ 6101 if( c==c2 ){ 6102 seen = 1; 6103 } 6104 prior_c = c2; 6105 } 6106 c2 = *(zGlob++); 6107 } 6108 if( c2==0 || (seen ^ invert)==0 ) return 0; 6109 }else if( c=='#' ){ 6110 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++; 6111 if( !IsDigit(z[0]) ) return 0; 6112 z++; 6113 while( IsDigit(z[0]) ){ z++; } 6114 }else{ 6115 if( c!=(*(z++)) ) return 0; 6116 } 6117 } 6118 while( IsSpace(*z) ){ z++; } 6119 return *z==0; 6120} 6121 6122 6123/* 6124** Compare the string as a command-line option with either one or two 6125** initial "-" characters. 6126*/ 6127static int optionMatch(const char *zStr, const char *zOpt){ 6128 if( zStr[0]!='-' ) return 0; 6129 zStr++; 6130 if( zStr[0]=='-' ) zStr++; 6131 return cli_strcmp(zStr, zOpt)==0; 6132} 6133 6134/* 6135** Delete a file. 6136*/ 6137int shellDeleteFile(const char *zFilename){ 6138 int rc; 6139#ifdef _WIN32 6140 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename); 6141 rc = _wunlink(z); 6142 sqlite3_free(z); 6143#else 6144 rc = unlink(zFilename); 6145#endif 6146 return rc; 6147} 6148 6149/* 6150** Try to delete the temporary file (if there is one) and free the 6151** memory used to hold the name of the temp file. 6152*/ 6153static void clearTempFile(ShellState *p){ 6154 if( p->zTempFile==0 ) return; 6155 if( p->doXdgOpen ) return; 6156 if( shellDeleteFile(p->zTempFile) ) return; 6157 sqlite3_free(p->zTempFile); 6158 p->zTempFile = 0; 6159} 6160 6161/* 6162** Create a new temp file name with the given suffix. 6163*/ 6164static void newTempFile(ShellState *p, const char *zSuffix){ 6165 clearTempFile(p); 6166 sqlite3_free(p->zTempFile); 6167 p->zTempFile = 0; 6168 if( p->db ){ 6169 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile); 6170 } 6171 if( p->zTempFile==0 ){ 6172 /* If p->db is an in-memory database then the TEMPFILENAME file-control 6173 ** will not work and we will need to fallback to guessing */ 6174 char *zTemp; 6175 sqlite3_uint64 r; 6176 sqlite3_randomness(sizeof(r), &r); 6177 zTemp = getenv("TEMP"); 6178 if( zTemp==0 ) zTemp = getenv("TMP"); 6179 if( zTemp==0 ){ 6180#ifdef _WIN32 6181 zTemp = "\\tmp"; 6182#else 6183 zTemp = "/tmp"; 6184#endif 6185 } 6186 p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix); 6187 }else{ 6188 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix); 6189 } 6190 shell_check_oom(p->zTempFile); 6191} 6192 6193 6194/* 6195** The implementation of SQL scalar function fkey_collate_clause(), used 6196** by the ".lint fkey-indexes" command. This scalar function is always 6197** called with four arguments - the parent table name, the parent column name, 6198** the child table name and the child column name. 6199** 6200** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col') 6201** 6202** If either of the named tables or columns do not exist, this function 6203** returns an empty string. An empty string is also returned if both tables 6204** and columns exist but have the same default collation sequence. Or, 6205** if both exist but the default collation sequences are different, this 6206** function returns the string " COLLATE <parent-collation>", where 6207** <parent-collation> is the default collation sequence of the parent column. 6208*/ 6209static void shellFkeyCollateClause( 6210 sqlite3_context *pCtx, 6211 int nVal, 6212 sqlite3_value **apVal 6213){ 6214 sqlite3 *db = sqlite3_context_db_handle(pCtx); 6215 const char *zParent; 6216 const char *zParentCol; 6217 const char *zParentSeq; 6218 const char *zChild; 6219 const char *zChildCol; 6220 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */ 6221 int rc; 6222 6223 assert( nVal==4 ); 6224 zParent = (const char*)sqlite3_value_text(apVal[0]); 6225 zParentCol = (const char*)sqlite3_value_text(apVal[1]); 6226 zChild = (const char*)sqlite3_value_text(apVal[2]); 6227 zChildCol = (const char*)sqlite3_value_text(apVal[3]); 6228 6229 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC); 6230 rc = sqlite3_table_column_metadata( 6231 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0 6232 ); 6233 if( rc==SQLITE_OK ){ 6234 rc = sqlite3_table_column_metadata( 6235 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0 6236 ); 6237 } 6238 6239 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){ 6240 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq); 6241 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT); 6242 sqlite3_free(z); 6243 } 6244} 6245 6246 6247/* 6248** The implementation of dot-command ".lint fkey-indexes". 6249*/ 6250static int lintFkeyIndexes( 6251 ShellState *pState, /* Current shell tool state */ 6252 char **azArg, /* Array of arguments passed to dot command */ 6253 int nArg /* Number of entries in azArg[] */ 6254){ 6255 sqlite3 *db = pState->db; /* Database handle to query "main" db of */ 6256 FILE *out = pState->out; /* Stream to write non-error output to */ 6257 int bVerbose = 0; /* If -verbose is present */ 6258 int bGroupByParent = 0; /* If -groupbyparent is present */ 6259 int i; /* To iterate through azArg[] */ 6260 const char *zIndent = ""; /* How much to indent CREATE INDEX by */ 6261 int rc; /* Return code */ 6262 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */ 6263 6264 /* 6265 ** This SELECT statement returns one row for each foreign key constraint 6266 ** in the schema of the main database. The column values are: 6267 ** 6268 ** 0. The text of an SQL statement similar to: 6269 ** 6270 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?" 6271 ** 6272 ** This SELECT is similar to the one that the foreign keys implementation 6273 ** needs to run internally on child tables. If there is an index that can 6274 ** be used to optimize this query, then it can also be used by the FK 6275 ** implementation to optimize DELETE or UPDATE statements on the parent 6276 ** table. 6277 ** 6278 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by 6279 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema 6280 ** contains an index that can be used to optimize the query. 6281 ** 6282 ** 2. Human readable text that describes the child table and columns. e.g. 6283 ** 6284 ** "child_table(child_key1, child_key2)" 6285 ** 6286 ** 3. Human readable text that describes the parent table and columns. e.g. 6287 ** 6288 ** "parent_table(parent_key1, parent_key2)" 6289 ** 6290 ** 4. A full CREATE INDEX statement for an index that could be used to 6291 ** optimize DELETE or UPDATE statements on the parent table. e.g. 6292 ** 6293 ** "CREATE INDEX child_table_child_key ON child_table(child_key)" 6294 ** 6295 ** 5. The name of the parent table. 6296 ** 6297 ** These six values are used by the C logic below to generate the report. 6298 */ 6299 const char *zSql = 6300 "SELECT " 6301 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '" 6302 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' " 6303 " || fkey_collate_clause(" 6304 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')" 6305 ", " 6306 " 'SEARCH ' || s.name || ' USING COVERING INDEX*('" 6307 " || group_concat('*=?', ' AND ') || ')'" 6308 ", " 6309 " s.name || '(' || group_concat(f.[from], ', ') || ')'" 6310 ", " 6311 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'" 6312 ", " 6313 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))" 6314 " || ' ON ' || quote(s.name) || '('" 6315 " || group_concat(quote(f.[from]) ||" 6316 " fkey_collate_clause(" 6317 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')" 6318 " || ');'" 6319 ", " 6320 " f.[table] " 6321 "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f " 6322 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) " 6323 "GROUP BY s.name, f.id " 6324 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)" 6325 ; 6326 const char *zGlobIPK = "SEARCH * USING INTEGER PRIMARY KEY (rowid=?)"; 6327 6328 for(i=2; i<nArg; i++){ 6329 int n = strlen30(azArg[i]); 6330 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){ 6331 bVerbose = 1; 6332 } 6333 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){ 6334 bGroupByParent = 1; 6335 zIndent = " "; 6336 } 6337 else{ 6338 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n", 6339 azArg[0], azArg[1] 6340 ); 6341 return SQLITE_ERROR; 6342 } 6343 } 6344 6345 /* Register the fkey_collate_clause() SQL function */ 6346 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8, 6347 0, shellFkeyCollateClause, 0, 0 6348 ); 6349 6350 6351 if( rc==SQLITE_OK ){ 6352 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0); 6353 } 6354 if( rc==SQLITE_OK ){ 6355 sqlite3_bind_int(pSql, 1, bGroupByParent); 6356 } 6357 6358 if( rc==SQLITE_OK ){ 6359 int rc2; 6360 char *zPrev = 0; 6361 while( SQLITE_ROW==sqlite3_step(pSql) ){ 6362 int res = -1; 6363 sqlite3_stmt *pExplain = 0; 6364 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0); 6365 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1); 6366 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2); 6367 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3); 6368 const char *zCI = (const char*)sqlite3_column_text(pSql, 4); 6369 const char *zParent = (const char*)sqlite3_column_text(pSql, 5); 6370 6371 if( zEQP==0 ) continue; 6372 if( zGlob==0 ) continue; 6373 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); 6374 if( rc!=SQLITE_OK ) break; 6375 if( SQLITE_ROW==sqlite3_step(pExplain) ){ 6376 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3); 6377 res = zPlan!=0 && ( 0==sqlite3_strglob(zGlob, zPlan) 6378 || 0==sqlite3_strglob(zGlobIPK, zPlan)); 6379 } 6380 rc = sqlite3_finalize(pExplain); 6381 if( rc!=SQLITE_OK ) break; 6382 6383 if( res<0 ){ 6384 raw_printf(stderr, "Error: internal error"); 6385 break; 6386 }else{ 6387 if( bGroupByParent 6388 && (bVerbose || res==0) 6389 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev)) 6390 ){ 6391 raw_printf(out, "-- Parent table %s\n", zParent); 6392 sqlite3_free(zPrev); 6393 zPrev = sqlite3_mprintf("%s", zParent); 6394 } 6395 6396 if( res==0 ){ 6397 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget); 6398 }else if( bVerbose ){ 6399 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n", 6400 zIndent, zFrom, zTarget 6401 ); 6402 } 6403 } 6404 } 6405 sqlite3_free(zPrev); 6406 6407 if( rc!=SQLITE_OK ){ 6408 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6409 } 6410 6411 rc2 = sqlite3_finalize(pSql); 6412 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){ 6413 rc = rc2; 6414 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6415 } 6416 }else{ 6417 raw_printf(stderr, "%s\n", sqlite3_errmsg(db)); 6418 } 6419 6420 return rc; 6421} 6422 6423/* 6424** Implementation of ".lint" dot command. 6425*/ 6426static int lintDotCommand( 6427 ShellState *pState, /* Current shell tool state */ 6428 char **azArg, /* Array of arguments passed to dot command */ 6429 int nArg /* Number of entries in azArg[] */ 6430){ 6431 int n; 6432 n = (nArg>=2 ? strlen30(azArg[1]) : 0); 6433 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage; 6434 return lintFkeyIndexes(pState, azArg, nArg); 6435 6436 usage: 6437 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]); 6438 raw_printf(stderr, "Where sub-commands are:\n"); 6439 raw_printf(stderr, " fkey-indexes\n"); 6440 return SQLITE_ERROR; 6441} 6442 6443#if !defined SQLITE_OMIT_VIRTUALTABLE 6444static void shellPrepare( 6445 sqlite3 *db, 6446 int *pRc, 6447 const char *zSql, 6448 sqlite3_stmt **ppStmt 6449){ 6450 *ppStmt = 0; 6451 if( *pRc==SQLITE_OK ){ 6452 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0); 6453 if( rc!=SQLITE_OK ){ 6454 raw_printf(stderr, "sql error: %s (%d)\n", 6455 sqlite3_errmsg(db), sqlite3_errcode(db) 6456 ); 6457 *pRc = rc; 6458 } 6459 } 6460} 6461 6462/* 6463** Create a prepared statement using printf-style arguments for the SQL. 6464** 6465** This routine is could be marked "static". But it is not always used, 6466** depending on compile-time options. By omitting the "static", we avoid 6467** nuisance compiler warnings about "defined but not used". 6468*/ 6469void shellPreparePrintf( 6470 sqlite3 *db, 6471 int *pRc, 6472 sqlite3_stmt **ppStmt, 6473 const char *zFmt, 6474 ... 6475){ 6476 *ppStmt = 0; 6477 if( *pRc==SQLITE_OK ){ 6478 va_list ap; 6479 char *z; 6480 va_start(ap, zFmt); 6481 z = sqlite3_vmprintf(zFmt, ap); 6482 va_end(ap); 6483 if( z==0 ){ 6484 *pRc = SQLITE_NOMEM; 6485 }else{ 6486 shellPrepare(db, pRc, z, ppStmt); 6487 sqlite3_free(z); 6488 } 6489 } 6490} 6491 6492/* Finalize the prepared statement created using shellPreparePrintf(). 6493** 6494** This routine is could be marked "static". But it is not always used, 6495** depending on compile-time options. By omitting the "static", we avoid 6496** nuisance compiler warnings about "defined but not used". 6497*/ 6498void shellFinalize( 6499 int *pRc, 6500 sqlite3_stmt *pStmt 6501){ 6502 if( pStmt ){ 6503 sqlite3 *db = sqlite3_db_handle(pStmt); 6504 int rc = sqlite3_finalize(pStmt); 6505 if( *pRc==SQLITE_OK ){ 6506 if( rc!=SQLITE_OK ){ 6507 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6508 } 6509 *pRc = rc; 6510 } 6511 } 6512} 6513 6514/* Reset the prepared statement created using shellPreparePrintf(). 6515** 6516** This routine is could be marked "static". But it is not always used, 6517** depending on compile-time options. By omitting the "static", we avoid 6518** nuisance compiler warnings about "defined but not used". 6519*/ 6520void shellReset( 6521 int *pRc, 6522 sqlite3_stmt *pStmt 6523){ 6524 int rc = sqlite3_reset(pStmt); 6525 if( *pRc==SQLITE_OK ){ 6526 if( rc!=SQLITE_OK ){ 6527 sqlite3 *db = sqlite3_db_handle(pStmt); 6528 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db)); 6529 } 6530 *pRc = rc; 6531 } 6532} 6533#endif /* !defined SQLITE_OMIT_VIRTUALTABLE */ 6534 6535#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 6536/****************************************************************************** 6537** The ".archive" or ".ar" command. 6538*/ 6539/* 6540** Structure representing a single ".ar" command. 6541*/ 6542typedef struct ArCommand ArCommand; 6543struct ArCommand { 6544 u8 eCmd; /* An AR_CMD_* value */ 6545 u8 bVerbose; /* True if --verbose */ 6546 u8 bZip; /* True if the archive is a ZIP */ 6547 u8 bDryRun; /* True if --dry-run */ 6548 u8 bAppend; /* True if --append */ 6549 u8 bGlob; /* True if --glob */ 6550 u8 fromCmdLine; /* Run from -A instead of .archive */ 6551 int nArg; /* Number of command arguments */ 6552 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */ 6553 const char *zFile; /* --file argument, or NULL */ 6554 const char *zDir; /* --directory argument, or NULL */ 6555 char **azArg; /* Array of command arguments */ 6556 ShellState *p; /* Shell state */ 6557 sqlite3 *db; /* Database containing the archive */ 6558}; 6559 6560/* 6561** Print a usage message for the .ar command to stderr and return SQLITE_ERROR. 6562*/ 6563static int arUsage(FILE *f){ 6564 showHelp(f,"archive"); 6565 return SQLITE_ERROR; 6566} 6567 6568/* 6569** Print an error message for the .ar command to stderr and return 6570** SQLITE_ERROR. 6571*/ 6572static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){ 6573 va_list ap; 6574 char *z; 6575 va_start(ap, zFmt); 6576 z = sqlite3_vmprintf(zFmt, ap); 6577 va_end(ap); 6578 utf8_printf(stderr, "Error: %s\n", z); 6579 if( pAr->fromCmdLine ){ 6580 utf8_printf(stderr, "Use \"-A\" for more help\n"); 6581 }else{ 6582 utf8_printf(stderr, "Use \".archive --help\" for more help\n"); 6583 } 6584 sqlite3_free(z); 6585 return SQLITE_ERROR; 6586} 6587 6588/* 6589** Values for ArCommand.eCmd. 6590*/ 6591#define AR_CMD_CREATE 1 6592#define AR_CMD_UPDATE 2 6593#define AR_CMD_INSERT 3 6594#define AR_CMD_EXTRACT 4 6595#define AR_CMD_LIST 5 6596#define AR_CMD_HELP 6 6597#define AR_CMD_REMOVE 7 6598 6599/* 6600** Other (non-command) switches. 6601*/ 6602#define AR_SWITCH_VERBOSE 8 6603#define AR_SWITCH_FILE 9 6604#define AR_SWITCH_DIRECTORY 10 6605#define AR_SWITCH_APPEND 11 6606#define AR_SWITCH_DRYRUN 12 6607#define AR_SWITCH_GLOB 13 6608 6609static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){ 6610 switch( eSwitch ){ 6611 case AR_CMD_CREATE: 6612 case AR_CMD_EXTRACT: 6613 case AR_CMD_LIST: 6614 case AR_CMD_REMOVE: 6615 case AR_CMD_UPDATE: 6616 case AR_CMD_INSERT: 6617 case AR_CMD_HELP: 6618 if( pAr->eCmd ){ 6619 return arErrorMsg(pAr, "multiple command options"); 6620 } 6621 pAr->eCmd = eSwitch; 6622 break; 6623 6624 case AR_SWITCH_DRYRUN: 6625 pAr->bDryRun = 1; 6626 break; 6627 case AR_SWITCH_GLOB: 6628 pAr->bGlob = 1; 6629 break; 6630 case AR_SWITCH_VERBOSE: 6631 pAr->bVerbose = 1; 6632 break; 6633 case AR_SWITCH_APPEND: 6634 pAr->bAppend = 1; 6635 /* Fall thru into --file */ 6636 case AR_SWITCH_FILE: 6637 pAr->zFile = zArg; 6638 break; 6639 case AR_SWITCH_DIRECTORY: 6640 pAr->zDir = zArg; 6641 break; 6642 } 6643 6644 return SQLITE_OK; 6645} 6646 6647/* 6648** Parse the command line for an ".ar" command. The results are written into 6649** structure (*pAr). SQLITE_OK is returned if the command line is parsed 6650** successfully, otherwise an error message is written to stderr and 6651** SQLITE_ERROR returned. 6652*/ 6653static int arParseCommand( 6654 char **azArg, /* Array of arguments passed to dot command */ 6655 int nArg, /* Number of entries in azArg[] */ 6656 ArCommand *pAr /* Populate this object */ 6657){ 6658 struct ArSwitch { 6659 const char *zLong; 6660 char cShort; 6661 u8 eSwitch; 6662 u8 bArg; 6663 } aSwitch[] = { 6664 { "create", 'c', AR_CMD_CREATE, 0 }, 6665 { "extract", 'x', AR_CMD_EXTRACT, 0 }, 6666 { "insert", 'i', AR_CMD_INSERT, 0 }, 6667 { "list", 't', AR_CMD_LIST, 0 }, 6668 { "remove", 'r', AR_CMD_REMOVE, 0 }, 6669 { "update", 'u', AR_CMD_UPDATE, 0 }, 6670 { "help", 'h', AR_CMD_HELP, 0 }, 6671 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 }, 6672 { "file", 'f', AR_SWITCH_FILE, 1 }, 6673 { "append", 'a', AR_SWITCH_APPEND, 1 }, 6674 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 }, 6675 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 }, 6676 { "glob", 'g', AR_SWITCH_GLOB, 0 }, 6677 }; 6678 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch); 6679 struct ArSwitch *pEnd = &aSwitch[nSwitch]; 6680 6681 if( nArg<=1 ){ 6682 utf8_printf(stderr, "Wrong number of arguments. Usage:\n"); 6683 return arUsage(stderr); 6684 }else{ 6685 char *z = azArg[1]; 6686 if( z[0]!='-' ){ 6687 /* Traditional style [tar] invocation */ 6688 int i; 6689 int iArg = 2; 6690 for(i=0; z[i]; i++){ 6691 const char *zArg = 0; 6692 struct ArSwitch *pOpt; 6693 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6694 if( z[i]==pOpt->cShort ) break; 6695 } 6696 if( pOpt==pEnd ){ 6697 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6698 } 6699 if( pOpt->bArg ){ 6700 if( iArg>=nArg ){ 6701 return arErrorMsg(pAr, "option requires an argument: %c",z[i]); 6702 } 6703 zArg = azArg[iArg++]; 6704 } 6705 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6706 } 6707 pAr->nArg = nArg-iArg; 6708 if( pAr->nArg>0 ){ 6709 pAr->azArg = &azArg[iArg]; 6710 } 6711 }else{ 6712 /* Non-traditional invocation */ 6713 int iArg; 6714 for(iArg=1; iArg<nArg; iArg++){ 6715 int n; 6716 z = azArg[iArg]; 6717 if( z[0]!='-' ){ 6718 /* All remaining command line words are command arguments. */ 6719 pAr->azArg = &azArg[iArg]; 6720 pAr->nArg = nArg-iArg; 6721 break; 6722 } 6723 n = strlen30(z); 6724 6725 if( z[1]!='-' ){ 6726 int i; 6727 /* One or more short options */ 6728 for(i=1; i<n; i++){ 6729 const char *zArg = 0; 6730 struct ArSwitch *pOpt; 6731 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6732 if( z[i]==pOpt->cShort ) break; 6733 } 6734 if( pOpt==pEnd ){ 6735 return arErrorMsg(pAr, "unrecognized option: %c", z[i]); 6736 } 6737 if( pOpt->bArg ){ 6738 if( i<(n-1) ){ 6739 zArg = &z[i+1]; 6740 i = n; 6741 }else{ 6742 if( iArg>=(nArg-1) ){ 6743 return arErrorMsg(pAr, "option requires an argument: %c", 6744 z[i]); 6745 } 6746 zArg = azArg[++iArg]; 6747 } 6748 } 6749 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR; 6750 } 6751 }else if( z[2]=='\0' ){ 6752 /* A -- option, indicating that all remaining command line words 6753 ** are command arguments. */ 6754 pAr->azArg = &azArg[iArg+1]; 6755 pAr->nArg = nArg-iArg-1; 6756 break; 6757 }else{ 6758 /* A long option */ 6759 const char *zArg = 0; /* Argument for option, if any */ 6760 struct ArSwitch *pMatch = 0; /* Matching option */ 6761 struct ArSwitch *pOpt; /* Iterator */ 6762 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){ 6763 const char *zLong = pOpt->zLong; 6764 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){ 6765 if( pMatch ){ 6766 return arErrorMsg(pAr, "ambiguous option: %s",z); 6767 }else{ 6768 pMatch = pOpt; 6769 } 6770 } 6771 } 6772 6773 if( pMatch==0 ){ 6774 return arErrorMsg(pAr, "unrecognized option: %s", z); 6775 } 6776 if( pMatch->bArg ){ 6777 if( iArg>=(nArg-1) ){ 6778 return arErrorMsg(pAr, "option requires an argument: %s", z); 6779 } 6780 zArg = azArg[++iArg]; 6781 } 6782 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR; 6783 } 6784 } 6785 } 6786 } 6787 6788 return SQLITE_OK; 6789} 6790 6791/* 6792** This function assumes that all arguments within the ArCommand.azArg[] 6793** array refer to archive members, as for the --extract, --list or --remove 6794** commands. It checks that each of them are "present". If any specified 6795** file is not present in the archive, an error is printed to stderr and an 6796** error code returned. Otherwise, if all specified arguments are present 6797** in the archive, SQLITE_OK is returned. Here, "present" means either an 6798** exact equality when pAr->bGlob is false or a "name GLOB pattern" match 6799** when pAr->bGlob is true. 6800** 6801** This function strips any trailing '/' characters from each argument. 6802** This is consistent with the way the [tar] command seems to work on 6803** Linux. 6804*/ 6805static int arCheckEntries(ArCommand *pAr){ 6806 int rc = SQLITE_OK; 6807 if( pAr->nArg ){ 6808 int i, j; 6809 sqlite3_stmt *pTest = 0; 6810 const char *zSel = (pAr->bGlob) 6811 ? "SELECT name FROM %s WHERE glob($name,name)" 6812 : "SELECT name FROM %s WHERE name=$name"; 6813 6814 shellPreparePrintf(pAr->db, &rc, &pTest, zSel, pAr->zSrcTable); 6815 j = sqlite3_bind_parameter_index(pTest, "$name"); 6816 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 6817 char *z = pAr->azArg[i]; 6818 int n = strlen30(z); 6819 int bOk = 0; 6820 while( n>0 && z[n-1]=='/' ) n--; 6821 z[n] = '\0'; 6822 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC); 6823 if( SQLITE_ROW==sqlite3_step(pTest) ){ 6824 bOk = 1; 6825 } 6826 shellReset(&rc, pTest); 6827 if( rc==SQLITE_OK && bOk==0 ){ 6828 utf8_printf(stderr, "not found in archive: %s\n", z); 6829 rc = SQLITE_ERROR; 6830 } 6831 } 6832 shellFinalize(&rc, pTest); 6833 } 6834 return rc; 6835} 6836 6837/* 6838** Format a WHERE clause that can be used against the "sqlar" table to 6839** identify all archive members that match the command arguments held 6840** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning. 6841** The caller is responsible for eventually calling sqlite3_free() on 6842** any non-NULL (*pzWhere) value. Here, "match" means strict equality 6843** when pAr->bGlob is false and GLOB match when pAr->bGlob is true. 6844*/ 6845static void arWhereClause( 6846 int *pRc, 6847 ArCommand *pAr, 6848 char **pzWhere /* OUT: New WHERE clause */ 6849){ 6850 char *zWhere = 0; 6851 const char *zSameOp = (pAr->bGlob)? "GLOB" : "="; 6852 if( *pRc==SQLITE_OK ){ 6853 if( pAr->nArg==0 ){ 6854 zWhere = sqlite3_mprintf("1"); 6855 }else{ 6856 int i; 6857 const char *zSep = ""; 6858 for(i=0; i<pAr->nArg; i++){ 6859 const char *z = pAr->azArg[i]; 6860 zWhere = sqlite3_mprintf( 6861 "%z%s name %s '%q' OR substr(name,1,%d) %s '%q/'", 6862 zWhere, zSep, zSameOp, z, strlen30(z)+1, zSameOp, z 6863 ); 6864 if( zWhere==0 ){ 6865 *pRc = SQLITE_NOMEM; 6866 break; 6867 } 6868 zSep = " OR "; 6869 } 6870 } 6871 } 6872 *pzWhere = zWhere; 6873} 6874 6875/* 6876** Implementation of .ar "lisT" command. 6877*/ 6878static int arListCommand(ArCommand *pAr){ 6879 const char *zSql = "SELECT %s FROM %s WHERE %s"; 6880 const char *azCols[] = { 6881 "name", 6882 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name" 6883 }; 6884 6885 char *zWhere = 0; 6886 sqlite3_stmt *pSql = 0; 6887 int rc; 6888 6889 rc = arCheckEntries(pAr); 6890 arWhereClause(&rc, pAr, &zWhere); 6891 6892 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose], 6893 pAr->zSrcTable, zWhere); 6894 if( pAr->bDryRun ){ 6895 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 6896 }else{ 6897 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 6898 if( pAr->bVerbose ){ 6899 utf8_printf(pAr->p->out, "%s % 10d %s %s\n", 6900 sqlite3_column_text(pSql, 0), 6901 sqlite3_column_int(pSql, 1), 6902 sqlite3_column_text(pSql, 2), 6903 sqlite3_column_text(pSql, 3) 6904 ); 6905 }else{ 6906 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 6907 } 6908 } 6909 } 6910 shellFinalize(&rc, pSql); 6911 sqlite3_free(zWhere); 6912 return rc; 6913} 6914 6915 6916/* 6917** Implementation of .ar "Remove" command. 6918*/ 6919static int arRemoveCommand(ArCommand *pAr){ 6920 int rc = 0; 6921 char *zSql = 0; 6922 char *zWhere = 0; 6923 6924 if( pAr->nArg ){ 6925 /* Verify that args actually exist within the archive before proceeding. 6926 ** And formulate a WHERE clause to match them. */ 6927 rc = arCheckEntries(pAr); 6928 arWhereClause(&rc, pAr, &zWhere); 6929 } 6930 if( rc==SQLITE_OK ){ 6931 zSql = sqlite3_mprintf("DELETE FROM %s WHERE %s;", 6932 pAr->zSrcTable, zWhere); 6933 if( pAr->bDryRun ){ 6934 utf8_printf(pAr->p->out, "%s\n", zSql); 6935 }else{ 6936 char *zErr = 0; 6937 rc = sqlite3_exec(pAr->db, "SAVEPOINT ar;", 0, 0, 0); 6938 if( rc==SQLITE_OK ){ 6939 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 6940 if( rc!=SQLITE_OK ){ 6941 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 6942 }else{ 6943 rc = sqlite3_exec(pAr->db, "RELEASE ar;", 0, 0, 0); 6944 } 6945 } 6946 if( zErr ){ 6947 utf8_printf(stdout, "ERROR: %s\n", zErr); 6948 sqlite3_free(zErr); 6949 } 6950 } 6951 } 6952 sqlite3_free(zWhere); 6953 sqlite3_free(zSql); 6954 return rc; 6955} 6956 6957/* 6958** Implementation of .ar "eXtract" command. 6959*/ 6960static int arExtractCommand(ArCommand *pAr){ 6961 const char *zSql1 = 6962 "SELECT " 6963 " ($dir || name)," 6964 " writefile(($dir || name), %s, mode, mtime) " 6965 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)" 6966 " AND name NOT GLOB '*..[/\\]*'"; 6967 6968 const char *azExtraArg[] = { 6969 "sqlar_uncompress(data, sz)", 6970 "data" 6971 }; 6972 6973 sqlite3_stmt *pSql = 0; 6974 int rc = SQLITE_OK; 6975 char *zDir = 0; 6976 char *zWhere = 0; 6977 int i, j; 6978 6979 /* If arguments are specified, check that they actually exist within 6980 ** the archive before proceeding. And formulate a WHERE clause to 6981 ** match them. */ 6982 rc = arCheckEntries(pAr); 6983 arWhereClause(&rc, pAr, &zWhere); 6984 6985 if( rc==SQLITE_OK ){ 6986 if( pAr->zDir ){ 6987 zDir = sqlite3_mprintf("%s/", pAr->zDir); 6988 }else{ 6989 zDir = sqlite3_mprintf(""); 6990 } 6991 if( zDir==0 ) rc = SQLITE_NOMEM; 6992 } 6993 6994 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1, 6995 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere 6996 ); 6997 6998 if( rc==SQLITE_OK ){ 6999 j = sqlite3_bind_parameter_index(pSql, "$dir"); 7000 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC); 7001 7002 /* Run the SELECT statement twice. The first time, writefile() is called 7003 ** for all archive members that should be extracted. The second time, 7004 ** only for the directories. This is because the timestamps for 7005 ** extracted directories must be reset after they are populated (as 7006 ** populating them changes the timestamp). */ 7007 for(i=0; i<2; i++){ 7008 j = sqlite3_bind_parameter_index(pSql, "$dirOnly"); 7009 sqlite3_bind_int(pSql, j, i); 7010 if( pAr->bDryRun ){ 7011 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql)); 7012 }else{ 7013 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){ 7014 if( i==0 && pAr->bVerbose ){ 7015 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0)); 7016 } 7017 } 7018 } 7019 shellReset(&rc, pSql); 7020 } 7021 shellFinalize(&rc, pSql); 7022 } 7023 7024 sqlite3_free(zDir); 7025 sqlite3_free(zWhere); 7026 return rc; 7027} 7028 7029/* 7030** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out. 7031*/ 7032static int arExecSql(ArCommand *pAr, const char *zSql){ 7033 int rc; 7034 if( pAr->bDryRun ){ 7035 utf8_printf(pAr->p->out, "%s\n", zSql); 7036 rc = SQLITE_OK; 7037 }else{ 7038 char *zErr = 0; 7039 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr); 7040 if( zErr ){ 7041 utf8_printf(stdout, "ERROR: %s\n", zErr); 7042 sqlite3_free(zErr); 7043 } 7044 } 7045 return rc; 7046} 7047 7048 7049/* 7050** Implementation of .ar "create", "insert", and "update" commands. 7051** 7052** create -> Create a new SQL archive 7053** insert -> Insert or reinsert all files listed 7054** update -> Insert files that have changed or that were not 7055** previously in the archive 7056** 7057** Create the "sqlar" table in the database if it does not already exist. 7058** Then add each file in the azFile[] array to the archive. Directories 7059** are added recursively. If argument bVerbose is non-zero, a message is 7060** printed on stdout for each file archived. 7061** 7062** The create command is the same as update, except that it drops 7063** any existing "sqlar" table before beginning. The "insert" command 7064** always overwrites every file named on the command-line, where as 7065** "update" only overwrites if the size or mtime or mode has changed. 7066*/ 7067static int arCreateOrUpdateCommand( 7068 ArCommand *pAr, /* Command arguments and options */ 7069 int bUpdate, /* true for a --create. */ 7070 int bOnlyIfChanged /* Only update if file has changed */ 7071){ 7072 const char *zCreate = 7073 "CREATE TABLE IF NOT EXISTS sqlar(\n" 7074 " name TEXT PRIMARY KEY, -- name of the file\n" 7075 " mode INT, -- access permissions\n" 7076 " mtime INT, -- last modification time\n" 7077 " sz INT, -- original file size\n" 7078 " data BLOB -- compressed content\n" 7079 ")"; 7080 const char *zDrop = "DROP TABLE IF EXISTS sqlar"; 7081 const char *zInsertFmt[2] = { 7082 "REPLACE INTO %s(name,mode,mtime,sz,data)\n" 7083 " SELECT\n" 7084 " %s,\n" 7085 " mode,\n" 7086 " mtime,\n" 7087 " CASE substr(lsmode(mode),1,1)\n" 7088 " WHEN '-' THEN length(data)\n" 7089 " WHEN 'd' THEN 0\n" 7090 " ELSE -1 END,\n" 7091 " sqlar_compress(data)\n" 7092 " FROM fsdir(%Q,%Q) AS disk\n" 7093 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 7094 , 7095 "REPLACE INTO %s(name,mode,mtime,data)\n" 7096 " SELECT\n" 7097 " %s,\n" 7098 " mode,\n" 7099 " mtime,\n" 7100 " data\n" 7101 " FROM fsdir(%Q,%Q) AS disk\n" 7102 " WHERE lsmode(mode) NOT LIKE '?%%'%s;" 7103 }; 7104 int i; /* For iterating through azFile[] */ 7105 int rc; /* Return code */ 7106 const char *zTab = 0; /* SQL table into which to insert */ 7107 char *zSql; 7108 char zTemp[50]; 7109 char *zExists = 0; 7110 7111 arExecSql(pAr, "PRAGMA page_size=512"); 7112 rc = arExecSql(pAr, "SAVEPOINT ar;"); 7113 if( rc!=SQLITE_OK ) return rc; 7114 zTemp[0] = 0; 7115 if( pAr->bZip ){ 7116 /* Initialize the zipfile virtual table, if necessary */ 7117 if( pAr->zFile ){ 7118 sqlite3_uint64 r; 7119 sqlite3_randomness(sizeof(r),&r); 7120 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r); 7121 zTab = zTemp; 7122 zSql = sqlite3_mprintf( 7123 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)", 7124 zTab, pAr->zFile 7125 ); 7126 rc = arExecSql(pAr, zSql); 7127 sqlite3_free(zSql); 7128 }else{ 7129 zTab = "zip"; 7130 } 7131 }else{ 7132 /* Initialize the table for an SQLAR */ 7133 zTab = "sqlar"; 7134 if( bUpdate==0 ){ 7135 rc = arExecSql(pAr, zDrop); 7136 if( rc!=SQLITE_OK ) goto end_ar_transaction; 7137 } 7138 rc = arExecSql(pAr, zCreate); 7139 } 7140 if( bOnlyIfChanged ){ 7141 zExists = sqlite3_mprintf( 7142 " AND NOT EXISTS(" 7143 "SELECT 1 FROM %s AS mem" 7144 " WHERE mem.name=disk.name" 7145 " AND mem.mtime=disk.mtime" 7146 " AND mem.mode=disk.mode)", zTab); 7147 }else{ 7148 zExists = sqlite3_mprintf(""); 7149 } 7150 if( zExists==0 ) rc = SQLITE_NOMEM; 7151 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){ 7152 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab, 7153 pAr->bVerbose ? "shell_putsnl(name)" : "name", 7154 pAr->azArg[i], pAr->zDir, zExists); 7155 rc = arExecSql(pAr, zSql2); 7156 sqlite3_free(zSql2); 7157 } 7158end_ar_transaction: 7159 if( rc!=SQLITE_OK ){ 7160 sqlite3_exec(pAr->db, "ROLLBACK TO ar; RELEASE ar;", 0, 0, 0); 7161 }else{ 7162 rc = arExecSql(pAr, "RELEASE ar;"); 7163 if( pAr->bZip && pAr->zFile ){ 7164 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp); 7165 arExecSql(pAr, zSql); 7166 sqlite3_free(zSql); 7167 } 7168 } 7169 sqlite3_free(zExists); 7170 return rc; 7171} 7172 7173/* 7174** Implementation of ".ar" dot command. 7175*/ 7176static int arDotCommand( 7177 ShellState *pState, /* Current shell tool state */ 7178 int fromCmdLine, /* True if -A command-line option, not .ar cmd */ 7179 char **azArg, /* Array of arguments passed to dot command */ 7180 int nArg /* Number of entries in azArg[] */ 7181){ 7182 ArCommand cmd; 7183 int rc; 7184 memset(&cmd, 0, sizeof(cmd)); 7185 cmd.fromCmdLine = fromCmdLine; 7186 rc = arParseCommand(azArg, nArg, &cmd); 7187 if( rc==SQLITE_OK ){ 7188 int eDbType = SHELL_OPEN_UNSPEC; 7189 cmd.p = pState; 7190 cmd.db = pState->db; 7191 if( cmd.zFile ){ 7192 eDbType = deduceDatabaseType(cmd.zFile, 1); 7193 }else{ 7194 eDbType = pState->openMode; 7195 } 7196 if( eDbType==SHELL_OPEN_ZIPFILE ){ 7197 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){ 7198 if( cmd.zFile==0 ){ 7199 cmd.zSrcTable = sqlite3_mprintf("zip"); 7200 }else{ 7201 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile); 7202 } 7203 } 7204 cmd.bZip = 1; 7205 }else if( cmd.zFile ){ 7206 int flags; 7207 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS; 7208 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_INSERT 7209 || cmd.eCmd==AR_CMD_REMOVE || cmd.eCmd==AR_CMD_UPDATE ){ 7210 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE; 7211 }else{ 7212 flags = SQLITE_OPEN_READONLY; 7213 } 7214 cmd.db = 0; 7215 if( cmd.bDryRun ){ 7216 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile, 7217 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : ""); 7218 } 7219 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags, 7220 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0); 7221 if( rc!=SQLITE_OK ){ 7222 utf8_printf(stderr, "cannot open file: %s (%s)\n", 7223 cmd.zFile, sqlite3_errmsg(cmd.db) 7224 ); 7225 goto end_ar_command; 7226 } 7227 sqlite3_fileio_init(cmd.db, 0, 0); 7228 sqlite3_sqlar_init(cmd.db, 0, 0); 7229 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p, 7230 shellPutsFunc, 0, 0); 7231 7232 } 7233 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){ 7234 if( cmd.eCmd!=AR_CMD_CREATE 7235 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0) 7236 ){ 7237 utf8_printf(stderr, "database does not contain an 'sqlar' table\n"); 7238 rc = SQLITE_ERROR; 7239 goto end_ar_command; 7240 } 7241 cmd.zSrcTable = sqlite3_mprintf("sqlar"); 7242 } 7243 7244 switch( cmd.eCmd ){ 7245 case AR_CMD_CREATE: 7246 rc = arCreateOrUpdateCommand(&cmd, 0, 0); 7247 break; 7248 7249 case AR_CMD_EXTRACT: 7250 rc = arExtractCommand(&cmd); 7251 break; 7252 7253 case AR_CMD_LIST: 7254 rc = arListCommand(&cmd); 7255 break; 7256 7257 case AR_CMD_HELP: 7258 arUsage(pState->out); 7259 break; 7260 7261 case AR_CMD_INSERT: 7262 rc = arCreateOrUpdateCommand(&cmd, 1, 0); 7263 break; 7264 7265 case AR_CMD_REMOVE: 7266 rc = arRemoveCommand(&cmd); 7267 break; 7268 7269 default: 7270 assert( cmd.eCmd==AR_CMD_UPDATE ); 7271 rc = arCreateOrUpdateCommand(&cmd, 1, 1); 7272 break; 7273 } 7274 } 7275end_ar_command: 7276 if( cmd.db!=pState->db ){ 7277 close_db(cmd.db); 7278 } 7279 sqlite3_free(cmd.zSrcTable); 7280 7281 return rc; 7282} 7283/* End of the ".archive" or ".ar" command logic 7284*******************************************************************************/ 7285#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */ 7286 7287#if SQLITE_SHELL_HAVE_RECOVER 7288 7289/* 7290** This function is used as a callback by the recover extension. Simply 7291** print the supplied SQL statement to stdout. 7292*/ 7293static int recoverSqlCb(void *pCtx, const char *zSql){ 7294 ShellState *pState = (ShellState*)pCtx; 7295 utf8_printf(pState->out, "%s;\n", zSql); 7296 return SQLITE_OK; 7297} 7298 7299/* 7300** This function is called to recover data from the database. A script 7301** to construct a new database containing all recovered data is output 7302** on stream pState->out. 7303*/ 7304static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ 7305 int rc = SQLITE_OK; 7306 const char *zRecoveryDb = ""; /* Name of "recovery" database */ 7307 const char *zLAF = "lost_and_found"; 7308 int bFreelist = 1; /* 0 if --ignore-freelist is specified */ 7309 int bRowids = 1; /* 0 if --no-rowids */ 7310 sqlite3_recover *p = 0; 7311 int i = 0; 7312 7313 for(i=1; i<nArg; i++){ 7314 char *z = azArg[i]; 7315 int n; 7316 if( z[0]=='-' && z[1]=='-' ) z++; 7317 n = strlen30(z); 7318 if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){ 7319 bFreelist = 0; 7320 }else 7321 if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){ 7322 i++; 7323 zRecoveryDb = azArg[i]; 7324 }else 7325 if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){ 7326 i++; 7327 zLAF = azArg[i]; 7328 }else 7329 if( n<=10 && memcmp("-no-rowids", z, n)==0 ){ 7330 bRowids = 0; 7331 } 7332 else{ 7333 utf8_printf(stderr, "unexpected option: %s\n", azArg[i]); 7334 showHelp(pState->out, azArg[0]); 7335 return 1; 7336 } 7337 } 7338 7339 p = sqlite3_recover_init_sql( 7340 pState->db, "main", recoverSqlCb, (void*)pState 7341 ); 7342 7343 sqlite3_recover_config(p, 789, (void*)zRecoveryDb); 7344 sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF); 7345 sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids); 7346 sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist); 7347 7348 sqlite3_recover_run(p); 7349 if( sqlite3_recover_errcode(p)!=SQLITE_OK ){ 7350 const char *zErr = sqlite3_recover_errmsg(p); 7351 int errCode = sqlite3_recover_errcode(p); 7352 raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode); 7353 } 7354 rc = sqlite3_recover_finish(p); 7355 return rc; 7356} 7357#endif /* SQLITE_SHELL_HAVE_RECOVER */ 7358 7359 7360/* 7361 * zAutoColumn(zCol, &db, ?) => Maybe init db, add column zCol to it. 7362 * zAutoColumn(0, &db, ?) => (db!=0) Form columns spec for CREATE TABLE, 7363 * close db and set it to 0, and return the columns spec, to later 7364 * be sqlite3_free()'ed by the caller. 7365 * The return is 0 when either: 7366 * (a) The db was not initialized and zCol==0 (There are no columns.) 7367 * (b) zCol!=0 (Column was added, db initialized as needed.) 7368 * The 3rd argument, pRenamed, references an out parameter. If the 7369 * pointer is non-zero, its referent will be set to a summary of renames 7370 * done if renaming was necessary, or set to 0 if none was done. The out 7371 * string (if any) must be sqlite3_free()'ed by the caller. 7372 */ 7373#ifdef SHELL_DEBUG 7374#define rc_err_oom_die(rc) \ 7375 if( rc==SQLITE_NOMEM ) shell_check_oom(0); \ 7376 else if(!(rc==SQLITE_OK||rc==SQLITE_DONE)) \ 7377 fprintf(stderr,"E:%d\n",rc), assert(0) 7378#else 7379static void rc_err_oom_die(int rc){ 7380 if( rc==SQLITE_NOMEM ) shell_check_oom(0); 7381 assert(rc==SQLITE_OK||rc==SQLITE_DONE); 7382} 7383#endif 7384 7385#ifdef SHELL_COLFIX_DB /* If this is set, the DB can be in a file. */ 7386static char zCOL_DB[] = SHELL_STRINGIFY(SHELL_COLFIX_DB); 7387#else /* Otherwise, memory is faster/better for the transient DB. */ 7388static const char *zCOL_DB = ":memory:"; 7389#endif 7390 7391/* Define character (as C string) to separate generated column ordinal 7392 * from protected part of incoming column names. This defaults to "_" 7393 * so that incoming column identifiers that did not need not be quoted 7394 * remain usable without being quoted. It must be one character. 7395 */ 7396#ifndef SHELL_AUTOCOLUMN_SEP 7397# define AUTOCOLUMN_SEP "_" 7398#else 7399# define AUTOCOLUMN_SEP SHELL_STRINGIFY(SHELL_AUTOCOLUMN_SEP) 7400#endif 7401 7402static char *zAutoColumn(const char *zColNew, sqlite3 **pDb, char **pzRenamed){ 7403 /* Queries and D{D,M}L used here */ 7404 static const char * const zTabMake = "\ 7405CREATE TABLE ColNames(\ 7406 cpos INTEGER PRIMARY KEY,\ 7407 name TEXT, nlen INT, chop INT, reps INT, suff TEXT);\ 7408CREATE VIEW RepeatedNames AS \ 7409SELECT DISTINCT t.name FROM ColNames t \ 7410WHERE t.name COLLATE NOCASE IN (\ 7411 SELECT o.name FROM ColNames o WHERE o.cpos<>t.cpos\ 7412);\ 7413"; 7414 static const char * const zTabFill = "\ 7415INSERT INTO ColNames(name,nlen,chop,reps,suff)\ 7416 VALUES(iif(length(?1)>0,?1,'?'),max(length(?1),1),0,0,'')\ 7417"; 7418 static const char * const zHasDupes = "\ 7419SELECT count(DISTINCT (substring(name,1,nlen-chop)||suff) COLLATE NOCASE)\ 7420 <count(name) FROM ColNames\ 7421"; 7422#ifdef SHELL_COLUMN_RENAME_CLEAN 7423 static const char * const zDedoctor = "\ 7424UPDATE ColNames SET chop=iif(\ 7425 (substring(name,nlen,1) BETWEEN '0' AND '9')\ 7426 AND (rtrim(name,'0123456790') glob '*"AUTOCOLUMN_SEP"'),\ 7427 nlen-length(rtrim(name, '"AUTOCOLUMN_SEP"0123456789')),\ 7428 0\ 7429)\ 7430"; 7431#endif 7432 static const char * const zSetReps = "\ 7433UPDATE ColNames AS t SET reps=\ 7434(SELECT count(*) FROM ColNames d \ 7435 WHERE substring(t.name,1,t.nlen-t.chop)=substring(d.name,1,d.nlen-d.chop)\ 7436 COLLATE NOCASE\ 7437)\ 7438"; 7439#ifdef SQLITE_ENABLE_MATH_FUNCTIONS 7440 static const char * const zColDigits = "\ 7441SELECT CAST(ceil(log(count(*)+0.5)) AS INT) FROM ColNames \ 7442"; 7443#else 7444 /* Counting on SQLITE_MAX_COLUMN < 100,000 here. (32767 is the hard limit.) */ 7445 static const char * const zColDigits = "\ 7446SELECT CASE WHEN (nc < 10) THEN 1 WHEN (nc < 100) THEN 2 \ 7447 WHEN (nc < 1000) THEN 3 WHEN (nc < 10000) THEN 4 \ 7448 ELSE 5 FROM (SELECT count(*) AS nc FROM ColNames) \ 7449"; 7450#endif 7451 static const char * const zRenameRank = 7452#ifdef SHELL_COLUMN_RENAME_CLEAN 7453 "UPDATE ColNames AS t SET suff=" 7454 "iif(reps>1, printf('%c%0*d', '"AUTOCOLUMN_SEP"', $1, cpos), '')" 7455#else /* ...RENAME_MINIMAL_ONE_PASS */ 7456"WITH Lzn(nlz) AS (" /* Find minimum extraneous leading 0's for uniqueness */ 7457" SELECT 0 AS nlz" 7458" UNION" 7459" SELECT nlz+1 AS nlz FROM Lzn" 7460" WHERE EXISTS(" 7461" SELECT 1" 7462" FROM ColNames t, ColNames o" 7463" WHERE" 7464" iif(t.name IN (SELECT * FROM RepeatedNames)," 7465" printf('%s"AUTOCOLUMN_SEP"%s'," 7466" t.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,t.cpos),2))," 7467" t.name" 7468" )" 7469" =" 7470" iif(o.name IN (SELECT * FROM RepeatedNames)," 7471" printf('%s"AUTOCOLUMN_SEP"%s'," 7472" o.name, substring(printf('%.*c%0.*d',nlz+1,'0',$1,o.cpos),2))," 7473" o.name" 7474" )" 7475" COLLATE NOCASE" 7476" AND o.cpos<>t.cpos" 7477" GROUP BY t.cpos" 7478" )" 7479") UPDATE Colnames AS t SET" 7480" chop = 0," /* No chopping, never touch incoming names. */ 7481" suff = iif(name IN (SELECT * FROM RepeatedNames)," 7482" printf('"AUTOCOLUMN_SEP"%s', substring(" 7483" printf('%.*c%0.*d',(SELECT max(nlz) FROM Lzn)+1,'0',1,t.cpos),2))," 7484" ''" 7485" )" 7486#endif 7487 ; 7488 static const char * const zCollectVar = "\ 7489SELECT\ 7490 '('||x'0a'\ 7491 || group_concat(\ 7492 cname||' TEXT',\ 7493 ','||iif((cpos-1)%4>0, ' ', x'0a'||' '))\ 7494 ||')' AS ColsSpec \ 7495FROM (\ 7496 SELECT cpos, printf('\"%w\"',printf('%!.*s%s', nlen-chop,name,suff)) AS cname \ 7497 FROM ColNames ORDER BY cpos\ 7498)"; 7499 static const char * const zRenamesDone = 7500 "SELECT group_concat(" 7501 " printf('\"%w\" to \"%w\"',name,printf('%!.*s%s', nlen-chop, name, suff))," 7502 " ','||x'0a')" 7503 "FROM ColNames WHERE suff<>'' OR chop!=0" 7504 ; 7505 int rc; 7506 sqlite3_stmt *pStmt = 0; 7507 assert(pDb!=0); 7508 if( zColNew ){ 7509 /* Add initial or additional column. Init db if necessary. */ 7510 if( *pDb==0 ){ 7511 if( SQLITE_OK!=sqlite3_open(zCOL_DB, pDb) ) return 0; 7512#ifdef SHELL_COLFIX_DB 7513 if(*zCOL_DB!=':') 7514 sqlite3_exec(*pDb,"drop table if exists ColNames;" 7515 "drop view if exists RepeatedNames;",0,0,0); 7516#endif 7517 rc = sqlite3_exec(*pDb, zTabMake, 0, 0, 0); 7518 rc_err_oom_die(rc); 7519 } 7520 assert(*pDb!=0); 7521 rc = sqlite3_prepare_v2(*pDb, zTabFill, -1, &pStmt, 0); 7522 rc_err_oom_die(rc); 7523 rc = sqlite3_bind_text(pStmt, 1, zColNew, -1, 0); 7524 rc_err_oom_die(rc); 7525 rc = sqlite3_step(pStmt); 7526 rc_err_oom_die(rc); 7527 sqlite3_finalize(pStmt); 7528 return 0; 7529 }else if( *pDb==0 ){ 7530 return 0; 7531 }else{ 7532 /* Formulate the columns spec, close the DB, zero *pDb. */ 7533 char *zColsSpec = 0; 7534 int hasDupes = db_int(*pDb, zHasDupes); 7535 int nDigits = (hasDupes)? db_int(*pDb, zColDigits) : 0; 7536 if( hasDupes ){ 7537#ifdef SHELL_COLUMN_RENAME_CLEAN 7538 rc = sqlite3_exec(*pDb, zDedoctor, 0, 0, 0); 7539 rc_err_oom_die(rc); 7540#endif 7541 rc = sqlite3_exec(*pDb, zSetReps, 0, 0, 0); 7542 rc_err_oom_die(rc); 7543 rc = sqlite3_prepare_v2(*pDb, zRenameRank, -1, &pStmt, 0); 7544 rc_err_oom_die(rc); 7545 sqlite3_bind_int(pStmt, 1, nDigits); 7546 rc = sqlite3_step(pStmt); 7547 sqlite3_finalize(pStmt); 7548 assert(rc==SQLITE_DONE); 7549 } 7550 assert(db_int(*pDb, zHasDupes)==0); /* Consider: remove this */ 7551 rc = sqlite3_prepare_v2(*pDb, zCollectVar, -1, &pStmt, 0); 7552 rc_err_oom_die(rc); 7553 rc = sqlite3_step(pStmt); 7554 if( rc==SQLITE_ROW ){ 7555 zColsSpec = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 7556 }else{ 7557 zColsSpec = 0; 7558 } 7559 if( pzRenamed!=0 ){ 7560 if( !hasDupes ) *pzRenamed = 0; 7561 else{ 7562 sqlite3_finalize(pStmt); 7563 if( SQLITE_OK==sqlite3_prepare_v2(*pDb, zRenamesDone, -1, &pStmt, 0) 7564 && SQLITE_ROW==sqlite3_step(pStmt) ){ 7565 *pzRenamed = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 7566 }else 7567 *pzRenamed = 0; 7568 } 7569 } 7570 sqlite3_finalize(pStmt); 7571 sqlite3_close(*pDb); 7572 *pDb = 0; 7573 return zColsSpec; 7574 } 7575} 7576 7577/* 7578** If an input line begins with "." then invoke this routine to 7579** process that line. 7580** 7581** Return 1 on error, 2 to exit, and 0 otherwise. 7582*/ 7583static int do_meta_command(char *zLine, ShellState *p){ 7584 int h = 1; 7585 int nArg = 0; 7586 int n, c; 7587 int rc = 0; 7588 char *azArg[52]; 7589 7590#ifndef SQLITE_OMIT_VIRTUALTABLE 7591 if( p->expert.pExpert ){ 7592 expertFinish(p, 1, 0); 7593 } 7594#endif 7595 7596 /* Parse the input line into tokens. 7597 */ 7598 while( zLine[h] && nArg<ArraySize(azArg)-1 ){ 7599 while( IsSpace(zLine[h]) ){ h++; } 7600 if( zLine[h]==0 ) break; 7601 if( zLine[h]=='\'' || zLine[h]=='"' ){ 7602 int delim = zLine[h++]; 7603 azArg[nArg++] = &zLine[h]; 7604 while( zLine[h] && zLine[h]!=delim ){ 7605 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; 7606 h++; 7607 } 7608 if( zLine[h]==delim ){ 7609 zLine[h++] = 0; 7610 } 7611 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); 7612 }else{ 7613 azArg[nArg++] = &zLine[h]; 7614 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } 7615 if( zLine[h] ) zLine[h++] = 0; 7616 resolve_backslashes(azArg[nArg-1]); 7617 } 7618 } 7619 azArg[nArg] = 0; 7620 7621 /* Process the input line. 7622 */ 7623 if( nArg==0 ) return 0; /* no tokens, no error */ 7624 n = strlen30(azArg[0]); 7625 c = azArg[0][0]; 7626 clearTempFile(p); 7627 7628#ifndef SQLITE_OMIT_AUTHORIZATION 7629 if( c=='a' && cli_strncmp(azArg[0], "auth", n)==0 ){ 7630 if( nArg!=2 ){ 7631 raw_printf(stderr, "Usage: .auth ON|OFF\n"); 7632 rc = 1; 7633 goto meta_command_exit; 7634 } 7635 open_db(p, 0); 7636 if( booleanValue(azArg[1]) ){ 7637 sqlite3_set_authorizer(p->db, shellAuth, p); 7638 }else if( p->bSafeModePersist ){ 7639 sqlite3_set_authorizer(p->db, safeModeAuth, p); 7640 }else{ 7641 sqlite3_set_authorizer(p->db, 0, 0); 7642 } 7643 }else 7644#endif 7645 7646#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) \ 7647 && !defined(SQLITE_SHELL_FIDDLE) 7648 if( c=='a' && cli_strncmp(azArg[0], "archive", n)==0 ){ 7649 open_db(p, 0); 7650 failIfSafeMode(p, "cannot run .archive in safe mode"); 7651 rc = arDotCommand(p, 0, azArg, nArg); 7652 }else 7653#endif 7654 7655#ifndef SQLITE_SHELL_FIDDLE 7656 if( (c=='b' && n>=3 && cli_strncmp(azArg[0], "backup", n)==0) 7657 || (c=='s' && n>=3 && cli_strncmp(azArg[0], "save", n)==0) 7658 ){ 7659 const char *zDestFile = 0; 7660 const char *zDb = 0; 7661 sqlite3 *pDest; 7662 sqlite3_backup *pBackup; 7663 int j; 7664 int bAsync = 0; 7665 const char *zVfs = 0; 7666 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 7667 for(j=1; j<nArg; j++){ 7668 const char *z = azArg[j]; 7669 if( z[0]=='-' ){ 7670 if( z[1]=='-' ) z++; 7671 if( cli_strcmp(z, "-append")==0 ){ 7672 zVfs = "apndvfs"; 7673 }else 7674 if( cli_strcmp(z, "-async")==0 ){ 7675 bAsync = 1; 7676 }else 7677 { 7678 utf8_printf(stderr, "unknown option: %s\n", azArg[j]); 7679 return 1; 7680 } 7681 }else if( zDestFile==0 ){ 7682 zDestFile = azArg[j]; 7683 }else if( zDb==0 ){ 7684 zDb = zDestFile; 7685 zDestFile = azArg[j]; 7686 }else{ 7687 raw_printf(stderr, "Usage: .backup ?DB? ?OPTIONS? FILENAME\n"); 7688 return 1; 7689 } 7690 } 7691 if( zDestFile==0 ){ 7692 raw_printf(stderr, "missing FILENAME argument on .backup\n"); 7693 return 1; 7694 } 7695 if( zDb==0 ) zDb = "main"; 7696 rc = sqlite3_open_v2(zDestFile, &pDest, 7697 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs); 7698 if( rc!=SQLITE_OK ){ 7699 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); 7700 close_db(pDest); 7701 return 1; 7702 } 7703 if( bAsync ){ 7704 sqlite3_exec(pDest, "PRAGMA synchronous=OFF; PRAGMA journal_mode=OFF;", 7705 0, 0, 0); 7706 } 7707 open_db(p, 0); 7708 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); 7709 if( pBackup==0 ){ 7710 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7711 close_db(pDest); 7712 return 1; 7713 } 7714 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} 7715 sqlite3_backup_finish(pBackup); 7716 if( rc==SQLITE_DONE ){ 7717 rc = 0; 7718 }else{ 7719 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); 7720 rc = 1; 7721 } 7722 close_db(pDest); 7723 }else 7724#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 7725 7726 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "bail", n)==0 ){ 7727 if( nArg==2 ){ 7728 bail_on_error = booleanValue(azArg[1]); 7729 }else{ 7730 raw_printf(stderr, "Usage: .bail on|off\n"); 7731 rc = 1; 7732 } 7733 }else 7734 7735 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "binary", n)==0 ){ 7736 if( nArg==2 ){ 7737 if( booleanValue(azArg[1]) ){ 7738 setBinaryMode(p->out, 1); 7739 }else{ 7740 setTextMode(p->out, 1); 7741 } 7742 }else{ 7743 raw_printf(stderr, "Usage: .binary on|off\n"); 7744 rc = 1; 7745 } 7746 }else 7747 7748 /* The undocumented ".breakpoint" command causes a call to the no-op 7749 ** routine named test_breakpoint(). 7750 */ 7751 if( c=='b' && n>=3 && cli_strncmp(azArg[0], "breakpoint", n)==0 ){ 7752 test_breakpoint(); 7753 }else 7754 7755#ifndef SQLITE_SHELL_FIDDLE 7756 if( c=='c' && cli_strcmp(azArg[0],"cd")==0 ){ 7757 failIfSafeMode(p, "cannot run .cd in safe mode"); 7758 if( nArg==2 ){ 7759#if defined(_WIN32) || defined(WIN32) 7760 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]); 7761 rc = !SetCurrentDirectoryW(z); 7762 sqlite3_free(z); 7763#else 7764 rc = chdir(azArg[1]); 7765#endif 7766 if( rc ){ 7767 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]); 7768 rc = 1; 7769 } 7770 }else{ 7771 raw_printf(stderr, "Usage: .cd DIRECTORY\n"); 7772 rc = 1; 7773 } 7774 }else 7775#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 7776 7777 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "changes", n)==0 ){ 7778 if( nArg==2 ){ 7779 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]); 7780 }else{ 7781 raw_printf(stderr, "Usage: .changes on|off\n"); 7782 rc = 1; 7783 } 7784 }else 7785 7786#ifndef SQLITE_SHELL_FIDDLE 7787 /* Cancel output redirection, if it is currently set (by .testcase) 7788 ** Then read the content of the testcase-out.txt file and compare against 7789 ** azArg[1]. If there are differences, report an error and exit. 7790 */ 7791 if( c=='c' && n>=3 && cli_strncmp(azArg[0], "check", n)==0 ){ 7792 char *zRes = 0; 7793 output_reset(p); 7794 if( nArg!=2 ){ 7795 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n"); 7796 rc = 2; 7797 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){ 7798 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n"); 7799 rc = 2; 7800 }else if( testcase_glob(azArg[1],zRes)==0 ){ 7801 utf8_printf(stderr, 7802 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n", 7803 p->zTestcase, azArg[1], zRes); 7804 rc = 1; 7805 }else{ 7806 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase); 7807 p->nCheck++; 7808 } 7809 sqlite3_free(zRes); 7810 }else 7811#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 7812 7813#ifndef SQLITE_SHELL_FIDDLE 7814 if( c=='c' && cli_strncmp(azArg[0], "clone", n)==0 ){ 7815 failIfSafeMode(p, "cannot run .clone in safe mode"); 7816 if( nArg==2 ){ 7817 tryToClone(p, azArg[1]); 7818 }else{ 7819 raw_printf(stderr, "Usage: .clone FILENAME\n"); 7820 rc = 1; 7821 } 7822 }else 7823#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 7824 7825 if( c=='c' && cli_strncmp(azArg[0], "connection", n)==0 ){ 7826 if( nArg==1 ){ 7827 /* List available connections */ 7828 int i; 7829 for(i=0; i<ArraySize(p->aAuxDb); i++){ 7830 const char *zFile = p->aAuxDb[i].zDbFilename; 7831 if( p->aAuxDb[i].db==0 && p->pAuxDb!=&p->aAuxDb[i] ){ 7832 zFile = "(not open)"; 7833 }else if( zFile==0 ){ 7834 zFile = "(memory)"; 7835 }else if( zFile[0]==0 ){ 7836 zFile = "(temporary-file)"; 7837 } 7838 if( p->pAuxDb == &p->aAuxDb[i] ){ 7839 utf8_printf(stdout, "ACTIVE %d: %s\n", i, zFile); 7840 }else if( p->aAuxDb[i].db!=0 ){ 7841 utf8_printf(stdout, " %d: %s\n", i, zFile); 7842 } 7843 } 7844 }else if( nArg==2 && IsDigit(azArg[1][0]) && azArg[1][1]==0 ){ 7845 int i = azArg[1][0] - '0'; 7846 if( p->pAuxDb != &p->aAuxDb[i] && i>=0 && i<ArraySize(p->aAuxDb) ){ 7847 p->pAuxDb->db = p->db; 7848 p->pAuxDb = &p->aAuxDb[i]; 7849 globalDb = p->db = p->pAuxDb->db; 7850 p->pAuxDb->db = 0; 7851 } 7852 }else if( nArg==3 && cli_strcmp(azArg[1], "close")==0 7853 && IsDigit(azArg[2][0]) && azArg[2][1]==0 ){ 7854 int i = azArg[2][0] - '0'; 7855 if( i<0 || i>=ArraySize(p->aAuxDb) ){ 7856 /* No-op */ 7857 }else if( p->pAuxDb == &p->aAuxDb[i] ){ 7858 raw_printf(stderr, "cannot close the active database connection\n"); 7859 rc = 1; 7860 }else if( p->aAuxDb[i].db ){ 7861 session_close_all(p, i); 7862 close_db(p->aAuxDb[i].db); 7863 p->aAuxDb[i].db = 0; 7864 } 7865 }else{ 7866 raw_printf(stderr, "Usage: .connection [close] [CONNECTION-NUMBER]\n"); 7867 rc = 1; 7868 } 7869 }else 7870 7871 if( c=='d' && n>1 && cli_strncmp(azArg[0], "databases", n)==0 ){ 7872 char **azName = 0; 7873 int nName = 0; 7874 sqlite3_stmt *pStmt; 7875 int i; 7876 open_db(p, 0); 7877 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 7878 if( rc ){ 7879 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 7880 rc = 1; 7881 }else{ 7882 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 7883 const char *zSchema = (const char *)sqlite3_column_text(pStmt,1); 7884 const char *zFile = (const char*)sqlite3_column_text(pStmt,2); 7885 if( zSchema==0 || zFile==0 ) continue; 7886 azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*)); 7887 shell_check_oom(azName); 7888 azName[nName*2] = strdup(zSchema); 7889 azName[nName*2+1] = strdup(zFile); 7890 nName++; 7891 } 7892 } 7893 sqlite3_finalize(pStmt); 7894 for(i=0; i<nName; i++){ 7895 int eTxn = sqlite3_txn_state(p->db, azName[i*2]); 7896 int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]); 7897 const char *z = azName[i*2+1]; 7898 utf8_printf(p->out, "%s: %s %s%s\n", 7899 azName[i*2], 7900 z && z[0] ? z : "\"\"", 7901 bRdonly ? "r/o" : "r/w", 7902 eTxn==SQLITE_TXN_NONE ? "" : 7903 eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn"); 7904 free(azName[i*2]); 7905 free(azName[i*2+1]); 7906 } 7907 sqlite3_free(azName); 7908 }else 7909 7910 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbconfig", n)==0 ){ 7911 static const struct DbConfigChoices { 7912 const char *zName; 7913 int op; 7914 } aDbConfig[] = { 7915 { "defensive", SQLITE_DBCONFIG_DEFENSIVE }, 7916 { "dqs_ddl", SQLITE_DBCONFIG_DQS_DDL }, 7917 { "dqs_dml", SQLITE_DBCONFIG_DQS_DML }, 7918 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY }, 7919 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG }, 7920 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER }, 7921 { "enable_view", SQLITE_DBCONFIG_ENABLE_VIEW }, 7922 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER }, 7923 { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE }, 7924 { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT }, 7925 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION }, 7926 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE }, 7927 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE }, 7928 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP }, 7929 { "trusted_schema", SQLITE_DBCONFIG_TRUSTED_SCHEMA }, 7930 { "writable_schema", SQLITE_DBCONFIG_WRITABLE_SCHEMA }, 7931 }; 7932 int ii, v; 7933 open_db(p, 0); 7934 for(ii=0; ii<ArraySize(aDbConfig); ii++){ 7935 if( nArg>1 && cli_strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue; 7936 if( nArg>=3 ){ 7937 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0); 7938 } 7939 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v); 7940 utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off"); 7941 if( nArg>1 ) break; 7942 } 7943 if( nArg>1 && ii==ArraySize(aDbConfig) ){ 7944 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]); 7945 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n"); 7946 } 7947 }else 7948 7949#if SQLITE_SHELL_HAVE_RECOVER 7950 if( c=='d' && n>=3 && cli_strncmp(azArg[0], "dbinfo", n)==0 ){ 7951 rc = shell_dbinfo_command(p, nArg, azArg); 7952 }else 7953 7954 if( c=='r' && cli_strncmp(azArg[0], "recover", n)==0 ){ 7955 open_db(p, 0); 7956 rc = recoverDatabaseCmd(p, nArg, azArg); 7957 }else 7958#endif /* SQLITE_SHELL_HAVE_RECOVER */ 7959 7960 if( c=='d' && cli_strncmp(azArg[0], "dump", n)==0 ){ 7961 char *zLike = 0; 7962 char *zSql; 7963 int i; 7964 int savedShowHeader = p->showHeader; 7965 int savedShellFlags = p->shellFlgs; 7966 ShellClearFlag(p, 7967 SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo 7968 |SHFLG_DumpDataOnly|SHFLG_DumpNoSys); 7969 for(i=1; i<nArg; i++){ 7970 if( azArg[i][0]=='-' ){ 7971 const char *z = azArg[i]+1; 7972 if( z[0]=='-' ) z++; 7973 if( cli_strcmp(z,"preserve-rowids")==0 ){ 7974#ifdef SQLITE_OMIT_VIRTUALTABLE 7975 raw_printf(stderr, "The --preserve-rowids option is not compatible" 7976 " with SQLITE_OMIT_VIRTUALTABLE\n"); 7977 rc = 1; 7978 sqlite3_free(zLike); 7979 goto meta_command_exit; 7980#else 7981 ShellSetFlag(p, SHFLG_PreserveRowid); 7982#endif 7983 }else 7984 if( cli_strcmp(z,"newlines")==0 ){ 7985 ShellSetFlag(p, SHFLG_Newlines); 7986 }else 7987 if( cli_strcmp(z,"data-only")==0 ){ 7988 ShellSetFlag(p, SHFLG_DumpDataOnly); 7989 }else 7990 if( cli_strcmp(z,"nosys")==0 ){ 7991 ShellSetFlag(p, SHFLG_DumpNoSys); 7992 }else 7993 { 7994 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]); 7995 rc = 1; 7996 sqlite3_free(zLike); 7997 goto meta_command_exit; 7998 } 7999 }else{ 8000 /* azArg[i] contains a LIKE pattern. This ".dump" request should 8001 ** only dump data for tables for which either the table name matches 8002 ** the LIKE pattern, or the table appears to be a shadow table of 8003 ** a virtual table for which the name matches the LIKE pattern. 8004 */ 8005 char *zExpr = sqlite3_mprintf( 8006 "name LIKE %Q ESCAPE '\\' OR EXISTS (" 8007 " SELECT 1 FROM sqlite_schema WHERE " 8008 " name LIKE %Q ESCAPE '\\' AND" 8009 " sql LIKE 'CREATE VIRTUAL TABLE%%' AND" 8010 " substr(o.name, 1, length(name)+1) == (name||'_')" 8011 ")", azArg[i], azArg[i] 8012 ); 8013 8014 if( zLike ){ 8015 zLike = sqlite3_mprintf("%z OR %z", zLike, zExpr); 8016 }else{ 8017 zLike = zExpr; 8018 } 8019 } 8020 } 8021 8022 open_db(p, 0); 8023 8024 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8025 /* When playing back a "dump", the content might appear in an order 8026 ** which causes immediate foreign key constraints to be violated. 8027 ** So disable foreign-key constraint enforcement to prevent problems. */ 8028 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); 8029 raw_printf(p->out, "BEGIN TRANSACTION;\n"); 8030 } 8031 p->writableSchema = 0; 8032 p->showHeader = 0; 8033 /* Set writable_schema=ON since doing so forces SQLite to initialize 8034 ** as much of the schema as it can even if the sqlite_schema table is 8035 ** corrupt. */ 8036 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); 8037 p->nErr = 0; 8038 if( zLike==0 ) zLike = sqlite3_mprintf("true"); 8039 zSql = sqlite3_mprintf( 8040 "SELECT name, type, sql FROM sqlite_schema AS o " 8041 "WHERE (%s) AND type=='table'" 8042 " AND sql NOT NULL" 8043 " ORDER BY tbl_name='sqlite_sequence', rowid", 8044 zLike 8045 ); 8046 run_schema_dump_query(p,zSql); 8047 sqlite3_free(zSql); 8048 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8049 zSql = sqlite3_mprintf( 8050 "SELECT sql FROM sqlite_schema AS o " 8051 "WHERE (%s) AND sql NOT NULL" 8052 " AND type IN ('index','trigger','view')", 8053 zLike 8054 ); 8055 run_table_dump_query(p, zSql); 8056 sqlite3_free(zSql); 8057 } 8058 sqlite3_free(zLike); 8059 if( p->writableSchema ){ 8060 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); 8061 p->writableSchema = 0; 8062 } 8063 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); 8064 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); 8065 if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){ 8066 raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n"); 8067 } 8068 p->showHeader = savedShowHeader; 8069 p->shellFlgs = savedShellFlags; 8070 }else 8071 8072 if( c=='e' && cli_strncmp(azArg[0], "echo", n)==0 ){ 8073 if( nArg==2 ){ 8074 setOrClearFlag(p, SHFLG_Echo, azArg[1]); 8075 }else{ 8076 raw_printf(stderr, "Usage: .echo on|off\n"); 8077 rc = 1; 8078 } 8079 }else 8080 8081 if( c=='e' && cli_strncmp(azArg[0], "eqp", n)==0 ){ 8082 if( nArg==2 ){ 8083 p->autoEQPtest = 0; 8084 if( p->autoEQPtrace ){ 8085 if( p->db ) sqlite3_exec(p->db, "PRAGMA vdbe_trace=OFF;", 0, 0, 0); 8086 p->autoEQPtrace = 0; 8087 } 8088 if( cli_strcmp(azArg[1],"full")==0 ){ 8089 p->autoEQP = AUTOEQP_full; 8090 }else if( cli_strcmp(azArg[1],"trigger")==0 ){ 8091 p->autoEQP = AUTOEQP_trigger; 8092#ifdef SQLITE_DEBUG 8093 }else if( cli_strcmp(azArg[1],"test")==0 ){ 8094 p->autoEQP = AUTOEQP_on; 8095 p->autoEQPtest = 1; 8096 }else if( cli_strcmp(azArg[1],"trace")==0 ){ 8097 p->autoEQP = AUTOEQP_full; 8098 p->autoEQPtrace = 1; 8099 open_db(p, 0); 8100 sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0); 8101 sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0); 8102#endif 8103 }else{ 8104 p->autoEQP = (u8)booleanValue(azArg[1]); 8105 } 8106 }else{ 8107 raw_printf(stderr, "Usage: .eqp off|on|trace|trigger|full\n"); 8108 rc = 1; 8109 } 8110 }else 8111 8112#ifndef SQLITE_SHELL_FIDDLE 8113 if( c=='e' && cli_strncmp(azArg[0], "exit", n)==0 ){ 8114 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); 8115 rc = 2; 8116 }else 8117#endif 8118 8119 /* The ".explain" command is automatic now. It is largely pointless. It 8120 ** retained purely for backwards compatibility */ 8121 if( c=='e' && cli_strncmp(azArg[0], "explain", n)==0 ){ 8122 int val = 1; 8123 if( nArg>=2 ){ 8124 if( cli_strcmp(azArg[1],"auto")==0 ){ 8125 val = 99; 8126 }else{ 8127 val = booleanValue(azArg[1]); 8128 } 8129 } 8130 if( val==1 && p->mode!=MODE_Explain ){ 8131 p->normalMode = p->mode; 8132 p->mode = MODE_Explain; 8133 p->autoExplain = 0; 8134 }else if( val==0 ){ 8135 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8136 p->autoExplain = 0; 8137 }else if( val==99 ){ 8138 if( p->mode==MODE_Explain ) p->mode = p->normalMode; 8139 p->autoExplain = 1; 8140 } 8141 }else 8142 8143#ifndef SQLITE_OMIT_VIRTUALTABLE 8144 if( c=='e' && cli_strncmp(azArg[0], "expert", n)==0 ){ 8145 if( p->bSafeMode ){ 8146 raw_printf(stderr, 8147 "Cannot run experimental commands such as \"%s\" in safe mode\n", 8148 azArg[0]); 8149 rc = 1; 8150 }else{ 8151 open_db(p, 0); 8152 expertDotCommand(p, azArg, nArg); 8153 } 8154 }else 8155#endif 8156 8157 if( c=='f' && cli_strncmp(azArg[0], "filectrl", n)==0 ){ 8158 static const struct { 8159 const char *zCtrlName; /* Name of a test-control option */ 8160 int ctrlCode; /* Integer code for that option */ 8161 const char *zUsage; /* Usage notes */ 8162 } aCtrl[] = { 8163 { "chunk_size", SQLITE_FCNTL_CHUNK_SIZE, "SIZE" }, 8164 { "data_version", SQLITE_FCNTL_DATA_VERSION, "" }, 8165 { "has_moved", SQLITE_FCNTL_HAS_MOVED, "" }, 8166 { "lock_timeout", SQLITE_FCNTL_LOCK_TIMEOUT, "MILLISEC" }, 8167 { "persist_wal", SQLITE_FCNTL_PERSIST_WAL, "[BOOLEAN]" }, 8168 /* { "pragma", SQLITE_FCNTL_PRAGMA, "NAME ARG" },*/ 8169 { "psow", SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]" }, 8170 { "reserve_bytes", SQLITE_FCNTL_RESERVE_BYTES, "[N]" }, 8171 { "size_limit", SQLITE_FCNTL_SIZE_LIMIT, "[LIMIT]" }, 8172 { "tempfilename", SQLITE_FCNTL_TEMPFILENAME, "" }, 8173 /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY, "COUNT DELAY" },*/ 8174 }; 8175 int filectrl = -1; 8176 int iCtrl = -1; 8177 sqlite3_int64 iRes = 0; /* Integer result to display if rc2==1 */ 8178 int isOk = 0; /* 0: usage 1: %lld 2: no-result */ 8179 int n2, i; 8180 const char *zCmd = 0; 8181 const char *zSchema = 0; 8182 8183 open_db(p, 0); 8184 zCmd = nArg>=2 ? azArg[1] : "help"; 8185 8186 if( zCmd[0]=='-' 8187 && (cli_strcmp(zCmd,"--schema")==0 || cli_strcmp(zCmd,"-schema")==0) 8188 && nArg>=4 8189 ){ 8190 zSchema = azArg[2]; 8191 for(i=3; i<nArg; i++) azArg[i-2] = azArg[i]; 8192 nArg -= 2; 8193 zCmd = azArg[1]; 8194 } 8195 8196 /* The argument can optionally begin with "-" or "--" */ 8197 if( zCmd[0]=='-' && zCmd[1] ){ 8198 zCmd++; 8199 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 8200 } 8201 8202 /* --help lists all file-controls */ 8203 if( cli_strcmp(zCmd,"help")==0 ){ 8204 utf8_printf(p->out, "Available file-controls:\n"); 8205 for(i=0; i<ArraySize(aCtrl); i++){ 8206 utf8_printf(p->out, " .filectrl %s %s\n", 8207 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 8208 } 8209 rc = 1; 8210 goto meta_command_exit; 8211 } 8212 8213 /* convert filectrl text option to value. allow any unique prefix 8214 ** of the option name, or a numerical value. */ 8215 n2 = strlen30(zCmd); 8216 for(i=0; i<ArraySize(aCtrl); i++){ 8217 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 8218 if( filectrl<0 ){ 8219 filectrl = aCtrl[i].ctrlCode; 8220 iCtrl = i; 8221 }else{ 8222 utf8_printf(stderr, "Error: ambiguous file-control: \"%s\"\n" 8223 "Use \".filectrl --help\" for help\n", zCmd); 8224 rc = 1; 8225 goto meta_command_exit; 8226 } 8227 } 8228 } 8229 if( filectrl<0 ){ 8230 utf8_printf(stderr,"Error: unknown file-control: %s\n" 8231 "Use \".filectrl --help\" for help\n", zCmd); 8232 }else{ 8233 switch(filectrl){ 8234 case SQLITE_FCNTL_SIZE_LIMIT: { 8235 if( nArg!=2 && nArg!=3 ) break; 8236 iRes = nArg==3 ? integerValue(azArg[2]) : -1; 8237 sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes); 8238 isOk = 1; 8239 break; 8240 } 8241 case SQLITE_FCNTL_LOCK_TIMEOUT: 8242 case SQLITE_FCNTL_CHUNK_SIZE: { 8243 int x; 8244 if( nArg!=3 ) break; 8245 x = (int)integerValue(azArg[2]); 8246 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8247 isOk = 2; 8248 break; 8249 } 8250 case SQLITE_FCNTL_PERSIST_WAL: 8251 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: { 8252 int x; 8253 if( nArg!=2 && nArg!=3 ) break; 8254 x = nArg==3 ? booleanValue(azArg[2]) : -1; 8255 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8256 iRes = x; 8257 isOk = 1; 8258 break; 8259 } 8260 case SQLITE_FCNTL_DATA_VERSION: 8261 case SQLITE_FCNTL_HAS_MOVED: { 8262 int x; 8263 if( nArg!=2 ) break; 8264 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8265 iRes = x; 8266 isOk = 1; 8267 break; 8268 } 8269 case SQLITE_FCNTL_TEMPFILENAME: { 8270 char *z = 0; 8271 if( nArg!=2 ) break; 8272 sqlite3_file_control(p->db, zSchema, filectrl, &z); 8273 if( z ){ 8274 utf8_printf(p->out, "%s\n", z); 8275 sqlite3_free(z); 8276 } 8277 isOk = 2; 8278 break; 8279 } 8280 case SQLITE_FCNTL_RESERVE_BYTES: { 8281 int x; 8282 if( nArg>=3 ){ 8283 x = atoi(azArg[2]); 8284 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8285 } 8286 x = -1; 8287 sqlite3_file_control(p->db, zSchema, filectrl, &x); 8288 utf8_printf(p->out,"%d\n", x); 8289 isOk = 2; 8290 break; 8291 } 8292 } 8293 } 8294 if( isOk==0 && iCtrl>=0 ){ 8295 utf8_printf(p->out, "Usage: .filectrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 8296 rc = 1; 8297 }else if( isOk==1 ){ 8298 char zBuf[100]; 8299 sqlite3_snprintf(sizeof(zBuf), zBuf, "%lld", iRes); 8300 raw_printf(p->out, "%s\n", zBuf); 8301 } 8302 }else 8303 8304 if( c=='f' && cli_strncmp(azArg[0], "fullschema", n)==0 ){ 8305 ShellState data; 8306 int doStats = 0; 8307 memcpy(&data, p, sizeof(data)); 8308 data.showHeader = 0; 8309 data.cMode = data.mode = MODE_Semi; 8310 if( nArg==2 && optionMatch(azArg[1], "indent") ){ 8311 data.cMode = data.mode = MODE_Pretty; 8312 nArg = 1; 8313 } 8314 if( nArg!=1 ){ 8315 raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); 8316 rc = 1; 8317 goto meta_command_exit; 8318 } 8319 open_db(p, 0); 8320 rc = sqlite3_exec(p->db, 8321 "SELECT sql FROM" 8322 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" 8323 " FROM sqlite_schema UNION ALL" 8324 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) " 8325 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " 8326 "ORDER BY x", 8327 callback, &data, 0 8328 ); 8329 if( rc==SQLITE_OK ){ 8330 sqlite3_stmt *pStmt; 8331 rc = sqlite3_prepare_v2(p->db, 8332 "SELECT rowid FROM sqlite_schema" 8333 " WHERE name GLOB 'sqlite_stat[134]'", 8334 -1, &pStmt, 0); 8335 doStats = sqlite3_step(pStmt)==SQLITE_ROW; 8336 sqlite3_finalize(pStmt); 8337 } 8338 if( doStats==0 ){ 8339 raw_printf(p->out, "/* No STAT tables available */\n"); 8340 }else{ 8341 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8342 data.cMode = data.mode = MODE_Insert; 8343 data.zDestTable = "sqlite_stat1"; 8344 shell_exec(&data, "SELECT * FROM sqlite_stat1", 0); 8345 data.zDestTable = "sqlite_stat4"; 8346 shell_exec(&data, "SELECT * FROM sqlite_stat4", 0); 8347 raw_printf(p->out, "ANALYZE sqlite_schema;\n"); 8348 } 8349 }else 8350 8351 if( c=='h' && cli_strncmp(azArg[0], "headers", n)==0 ){ 8352 if( nArg==2 ){ 8353 p->showHeader = booleanValue(azArg[1]); 8354 p->shellFlgs |= SHFLG_HeaderSet; 8355 }else{ 8356 raw_printf(stderr, "Usage: .headers on|off\n"); 8357 rc = 1; 8358 } 8359 }else 8360 8361 if( c=='h' && cli_strncmp(azArg[0], "help", n)==0 ){ 8362 if( nArg>=2 ){ 8363 n = showHelp(p->out, azArg[1]); 8364 if( n==0 ){ 8365 utf8_printf(p->out, "Nothing matches '%s'\n", azArg[1]); 8366 } 8367 }else{ 8368 showHelp(p->out, 0); 8369 } 8370 }else 8371 8372#ifndef SQLITE_SHELL_FIDDLE 8373 if( c=='i' && cli_strncmp(azArg[0], "import", n)==0 ){ 8374 char *zTable = 0; /* Insert data into this table */ 8375 char *zSchema = 0; /* within this schema (may default to "main") */ 8376 char *zFile = 0; /* Name of file to extra content from */ 8377 sqlite3_stmt *pStmt = NULL; /* A statement */ 8378 int nCol; /* Number of columns in the table */ 8379 int nByte; /* Number of bytes in an SQL string */ 8380 int i, j; /* Loop counters */ 8381 int needCommit; /* True to COMMIT or ROLLBACK at end */ 8382 int nSep; /* Number of bytes in p->colSeparator[] */ 8383 char *zSql; /* An SQL statement */ 8384 char *zFullTabName; /* Table name with schema if applicable */ 8385 ImportCtx sCtx; /* Reader context */ 8386 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ 8387 int eVerbose = 0; /* Larger for more console output */ 8388 int nSkip = 0; /* Initial lines to skip */ 8389 int useOutputMode = 1; /* Use output mode to determine separators */ 8390 char *zCreate = 0; /* CREATE TABLE statement text */ 8391 8392 failIfSafeMode(p, "cannot run .import in safe mode"); 8393 memset(&sCtx, 0, sizeof(sCtx)); 8394 if( p->mode==MODE_Ascii ){ 8395 xRead = ascii_read_one_field; 8396 }else{ 8397 xRead = csv_read_one_field; 8398 } 8399 rc = 1; 8400 for(i=1; i<nArg; i++){ 8401 char *z = azArg[i]; 8402 if( z[0]=='-' && z[1]=='-' ) z++; 8403 if( z[0]!='-' ){ 8404 if( zFile==0 ){ 8405 zFile = z; 8406 }else if( zTable==0 ){ 8407 zTable = z; 8408 }else{ 8409 utf8_printf(p->out, "ERROR: extra argument: \"%s\". Usage:\n", z); 8410 showHelp(p->out, "import"); 8411 goto meta_command_exit; 8412 } 8413 }else if( cli_strcmp(z,"-v")==0 ){ 8414 eVerbose++; 8415 }else if( cli_strcmp(z,"-schema")==0 && i<nArg-1 ){ 8416 zSchema = azArg[++i]; 8417 }else if( cli_strcmp(z,"-skip")==0 && i<nArg-1 ){ 8418 nSkip = integerValue(azArg[++i]); 8419 }else if( cli_strcmp(z,"-ascii")==0 ){ 8420 sCtx.cColSep = SEP_Unit[0]; 8421 sCtx.cRowSep = SEP_Record[0]; 8422 xRead = ascii_read_one_field; 8423 useOutputMode = 0; 8424 }else if( cli_strcmp(z,"-csv")==0 ){ 8425 sCtx.cColSep = ','; 8426 sCtx.cRowSep = '\n'; 8427 xRead = csv_read_one_field; 8428 useOutputMode = 0; 8429 }else{ 8430 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", z); 8431 showHelp(p->out, "import"); 8432 goto meta_command_exit; 8433 } 8434 } 8435 if( zTable==0 ){ 8436 utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n", 8437 zFile==0 ? "FILE" : "TABLE"); 8438 showHelp(p->out, "import"); 8439 goto meta_command_exit; 8440 } 8441 seenInterrupt = 0; 8442 open_db(p, 0); 8443 if( useOutputMode ){ 8444 /* If neither the --csv or --ascii options are specified, then set 8445 ** the column and row separator characters from the output mode. */ 8446 nSep = strlen30(p->colSeparator); 8447 if( nSep==0 ){ 8448 raw_printf(stderr, 8449 "Error: non-null column separator required for import\n"); 8450 goto meta_command_exit; 8451 } 8452 if( nSep>1 ){ 8453 raw_printf(stderr, 8454 "Error: multi-character column separators not allowed" 8455 " for import\n"); 8456 goto meta_command_exit; 8457 } 8458 nSep = strlen30(p->rowSeparator); 8459 if( nSep==0 ){ 8460 raw_printf(stderr, 8461 "Error: non-null row separator required for import\n"); 8462 goto meta_command_exit; 8463 } 8464 if( nSep==2 && p->mode==MODE_Csv 8465 && cli_strcmp(p->rowSeparator,SEP_CrLf)==0 8466 ){ 8467 /* When importing CSV (only), if the row separator is set to the 8468 ** default output row separator, change it to the default input 8469 ** row separator. This avoids having to maintain different input 8470 ** and output row separators. */ 8471 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8472 nSep = strlen30(p->rowSeparator); 8473 } 8474 if( nSep>1 ){ 8475 raw_printf(stderr, "Error: multi-character row separators not allowed" 8476 " for import\n"); 8477 goto meta_command_exit; 8478 } 8479 sCtx.cColSep = p->colSeparator[0]; 8480 sCtx.cRowSep = p->rowSeparator[0]; 8481 } 8482 sCtx.zFile = zFile; 8483 sCtx.nLine = 1; 8484 if( sCtx.zFile[0]=='|' ){ 8485#ifdef SQLITE_OMIT_POPEN 8486 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 8487 goto meta_command_exit; 8488#else 8489 sCtx.in = popen(sCtx.zFile+1, "r"); 8490 sCtx.zFile = "<pipe>"; 8491 sCtx.xCloser = pclose; 8492#endif 8493 }else{ 8494 sCtx.in = fopen(sCtx.zFile, "rb"); 8495 sCtx.xCloser = fclose; 8496 } 8497 if( sCtx.in==0 ){ 8498 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); 8499 goto meta_command_exit; 8500 } 8501 if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){ 8502 char zSep[2]; 8503 zSep[1] = 0; 8504 zSep[0] = sCtx.cColSep; 8505 utf8_printf(p->out, "Column separator "); 8506 output_c_string(p->out, zSep); 8507 utf8_printf(p->out, ", row separator "); 8508 zSep[0] = sCtx.cRowSep; 8509 output_c_string(p->out, zSep); 8510 utf8_printf(p->out, "\n"); 8511 } 8512 sCtx.z = sqlite3_malloc64(120); 8513 if( sCtx.z==0 ){ 8514 import_cleanup(&sCtx); 8515 shell_out_of_memory(); 8516 } 8517 /* Below, resources must be freed before exit. */ 8518 while( (nSkip--)>0 ){ 8519 while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){} 8520 } 8521 if( zSchema!=0 ){ 8522 zFullTabName = sqlite3_mprintf("\"%w\".\"%w\"", zSchema, zTable); 8523 }else{ 8524 zFullTabName = sqlite3_mprintf("\"%w\"", zTable); 8525 } 8526 zSql = sqlite3_mprintf("SELECT * FROM %s", zFullTabName); 8527 if( zSql==0 || zFullTabName==0 ){ 8528 import_cleanup(&sCtx); 8529 shell_out_of_memory(); 8530 } 8531 nByte = strlen30(zSql); 8532 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8533 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ 8534 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ 8535 sqlite3 *dbCols = 0; 8536 char *zRenames = 0; 8537 char *zColDefs; 8538 zCreate = sqlite3_mprintf("CREATE TABLE %s", zFullTabName); 8539 while( xRead(&sCtx) ){ 8540 zAutoColumn(sCtx.z, &dbCols, 0); 8541 if( sCtx.cTerm!=sCtx.cColSep ) break; 8542 } 8543 zColDefs = zAutoColumn(0, &dbCols, &zRenames); 8544 if( zRenames!=0 ){ 8545 utf8_printf((stdin_is_interactive && p->in==stdin)? p->out : stderr, 8546 "Columns renamed during .import %s due to duplicates:\n" 8547 "%s\n", sCtx.zFile, zRenames); 8548 sqlite3_free(zRenames); 8549 } 8550 assert(dbCols==0); 8551 if( zColDefs==0 ){ 8552 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); 8553 import_fail: 8554 sqlite3_free(zCreate); 8555 sqlite3_free(zSql); 8556 sqlite3_free(zFullTabName); 8557 import_cleanup(&sCtx); 8558 rc = 1; 8559 goto meta_command_exit; 8560 } 8561 zCreate = sqlite3_mprintf("%z%z\n", zCreate, zColDefs); 8562 if( eVerbose>=1 ){ 8563 utf8_printf(p->out, "%s\n", zCreate); 8564 } 8565 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); 8566 if( rc ){ 8567 utf8_printf(stderr, "%s failed:\n%s\n", zCreate, sqlite3_errmsg(p->db)); 8568 goto import_fail; 8569 } 8570 sqlite3_free(zCreate); 8571 zCreate = 0; 8572 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8573 } 8574 if( rc ){ 8575 if (pStmt) sqlite3_finalize(pStmt); 8576 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); 8577 goto import_fail; 8578 } 8579 sqlite3_free(zSql); 8580 nCol = sqlite3_column_count(pStmt); 8581 sqlite3_finalize(pStmt); 8582 pStmt = 0; 8583 if( nCol==0 ) return 0; /* no columns, no error */ 8584 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); 8585 if( zSql==0 ){ 8586 import_cleanup(&sCtx); 8587 shell_out_of_memory(); 8588 } 8589 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zFullTabName); 8590 j = strlen30(zSql); 8591 for(i=1; i<nCol; i++){ 8592 zSql[j++] = ','; 8593 zSql[j++] = '?'; 8594 } 8595 zSql[j++] = ')'; 8596 zSql[j] = 0; 8597 if( eVerbose>=2 ){ 8598 utf8_printf(p->out, "Insert using: %s\n", zSql); 8599 } 8600 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8601 if( rc ){ 8602 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 8603 if (pStmt) sqlite3_finalize(pStmt); 8604 goto import_fail; 8605 } 8606 sqlite3_free(zSql); 8607 sqlite3_free(zFullTabName); 8608 needCommit = sqlite3_get_autocommit(p->db); 8609 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); 8610 do{ 8611 int startLine = sCtx.nLine; 8612 for(i=0; i<nCol; i++){ 8613 char *z = xRead(&sCtx); 8614 /* 8615 ** Did we reach end-of-file before finding any columns? 8616 ** If so, stop instead of NULL filling the remaining columns. 8617 */ 8618 if( z==0 && i==0 ) break; 8619 /* 8620 ** Did we reach end-of-file OR end-of-line before finding any 8621 ** columns in ASCII mode? If so, stop instead of NULL filling 8622 ** the remaining columns. 8623 */ 8624 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; 8625 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); 8626 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ 8627 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8628 "filling the rest with NULL\n", 8629 sCtx.zFile, startLine, nCol, i+1); 8630 i += 2; 8631 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } 8632 } 8633 } 8634 if( sCtx.cTerm==sCtx.cColSep ){ 8635 do{ 8636 xRead(&sCtx); 8637 i++; 8638 }while( sCtx.cTerm==sCtx.cColSep ); 8639 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " 8640 "extras ignored\n", 8641 sCtx.zFile, startLine, nCol, i); 8642 } 8643 if( i>=nCol ){ 8644 sqlite3_step(pStmt); 8645 rc = sqlite3_reset(pStmt); 8646 if( rc!=SQLITE_OK ){ 8647 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, 8648 startLine, sqlite3_errmsg(p->db)); 8649 sCtx.nErr++; 8650 }else{ 8651 sCtx.nRow++; 8652 } 8653 } 8654 }while( sCtx.cTerm!=EOF ); 8655 8656 import_cleanup(&sCtx); 8657 sqlite3_finalize(pStmt); 8658 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); 8659 if( eVerbose>0 ){ 8660 utf8_printf(p->out, 8661 "Added %d rows with %d errors using %d lines of input\n", 8662 sCtx.nRow, sCtx.nErr, sCtx.nLine-1); 8663 } 8664 }else 8665#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 8666 8667#ifndef SQLITE_UNTESTABLE 8668 if( c=='i' && cli_strncmp(azArg[0], "imposter", n)==0 ){ 8669 char *zSql; 8670 char *zCollist = 0; 8671 sqlite3_stmt *pStmt; 8672 int tnum = 0; 8673 int isWO = 0; /* True if making an imposter of a WITHOUT ROWID table */ 8674 int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */ 8675 int i; 8676 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){ 8677 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n" 8678 " .imposter off\n"); 8679 /* Also allowed, but not documented: 8680 ** 8681 ** .imposter TABLE IMPOSTER 8682 ** 8683 ** where TABLE is a WITHOUT ROWID table. In that case, the 8684 ** imposter is another WITHOUT ROWID table with the columns in 8685 ** storage order. */ 8686 rc = 1; 8687 goto meta_command_exit; 8688 } 8689 open_db(p, 0); 8690 if( nArg==2 ){ 8691 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1); 8692 goto meta_command_exit; 8693 } 8694 zSql = sqlite3_mprintf( 8695 "SELECT rootpage, 0 FROM sqlite_schema" 8696 " WHERE name='%q' AND type='index'" 8697 "UNION ALL " 8698 "SELECT rootpage, 1 FROM sqlite_schema" 8699 " WHERE name='%q' AND type='table'" 8700 " AND sql LIKE '%%without%%rowid%%'", 8701 azArg[1], azArg[1] 8702 ); 8703 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8704 sqlite3_free(zSql); 8705 if( sqlite3_step(pStmt)==SQLITE_ROW ){ 8706 tnum = sqlite3_column_int(pStmt, 0); 8707 isWO = sqlite3_column_int(pStmt, 1); 8708 } 8709 sqlite3_finalize(pStmt); 8710 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]); 8711 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 8712 sqlite3_free(zSql); 8713 i = 0; 8714 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 8715 char zLabel[20]; 8716 const char *zCol = (const char*)sqlite3_column_text(pStmt,2); 8717 i++; 8718 if( zCol==0 ){ 8719 if( sqlite3_column_int(pStmt,1)==-1 ){ 8720 zCol = "_ROWID_"; 8721 }else{ 8722 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i); 8723 zCol = zLabel; 8724 } 8725 } 8726 if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){ 8727 lenPK = (int)strlen(zCollist); 8728 } 8729 if( zCollist==0 ){ 8730 zCollist = sqlite3_mprintf("\"%w\"", zCol); 8731 }else{ 8732 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol); 8733 } 8734 } 8735 sqlite3_finalize(pStmt); 8736 if( i==0 || tnum==0 ){ 8737 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]); 8738 rc = 1; 8739 sqlite3_free(zCollist); 8740 goto meta_command_exit; 8741 } 8742 if( lenPK==0 ) lenPK = 100000; 8743 zSql = sqlite3_mprintf( 8744 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID", 8745 azArg[2], zCollist, lenPK, zCollist); 8746 sqlite3_free(zCollist); 8747 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum); 8748 if( rc==SQLITE_OK ){ 8749 rc = sqlite3_exec(p->db, zSql, 0, 0, 0); 8750 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0); 8751 if( rc ){ 8752 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db)); 8753 }else{ 8754 utf8_printf(stdout, "%s;\n", zSql); 8755 raw_printf(stdout, 8756 "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n", 8757 azArg[1], isWO ? "table" : "index" 8758 ); 8759 } 8760 }else{ 8761 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc); 8762 rc = 1; 8763 } 8764 sqlite3_free(zSql); 8765 }else 8766#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */ 8767 8768#ifdef SQLITE_ENABLE_IOTRACE 8769 if( c=='i' && cli_strncmp(azArg[0], "iotrace", n)==0 ){ 8770 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); 8771 if( iotrace && iotrace!=stdout ) fclose(iotrace); 8772 iotrace = 0; 8773 if( nArg<2 ){ 8774 sqlite3IoTrace = 0; 8775 }else if( cli_strcmp(azArg[1], "-")==0 ){ 8776 sqlite3IoTrace = iotracePrintf; 8777 iotrace = stdout; 8778 }else{ 8779 iotrace = fopen(azArg[1], "w"); 8780 if( iotrace==0 ){ 8781 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 8782 sqlite3IoTrace = 0; 8783 rc = 1; 8784 }else{ 8785 sqlite3IoTrace = iotracePrintf; 8786 } 8787 } 8788 }else 8789#endif 8790 8791 if( c=='l' && n>=5 && cli_strncmp(azArg[0], "limits", n)==0 ){ 8792 static const struct { 8793 const char *zLimitName; /* Name of a limit */ 8794 int limitCode; /* Integer code for that limit */ 8795 } aLimit[] = { 8796 { "length", SQLITE_LIMIT_LENGTH }, 8797 { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, 8798 { "column", SQLITE_LIMIT_COLUMN }, 8799 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, 8800 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, 8801 { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, 8802 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, 8803 { "attached", SQLITE_LIMIT_ATTACHED }, 8804 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, 8805 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, 8806 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, 8807 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, 8808 }; 8809 int i, n2; 8810 open_db(p, 0); 8811 if( nArg==1 ){ 8812 for(i=0; i<ArraySize(aLimit); i++){ 8813 printf("%20s %d\n", aLimit[i].zLimitName, 8814 sqlite3_limit(p->db, aLimit[i].limitCode, -1)); 8815 } 8816 }else if( nArg>3 ){ 8817 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); 8818 rc = 1; 8819 goto meta_command_exit; 8820 }else{ 8821 int iLimit = -1; 8822 n2 = strlen30(azArg[1]); 8823 for(i=0; i<ArraySize(aLimit); i++){ 8824 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ 8825 if( iLimit<0 ){ 8826 iLimit = i; 8827 }else{ 8828 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); 8829 rc = 1; 8830 goto meta_command_exit; 8831 } 8832 } 8833 } 8834 if( iLimit<0 ){ 8835 utf8_printf(stderr, "unknown limit: \"%s\"\n" 8836 "enter \".limits\" with no arguments for a list.\n", 8837 azArg[1]); 8838 rc = 1; 8839 goto meta_command_exit; 8840 } 8841 if( nArg==3 ){ 8842 sqlite3_limit(p->db, aLimit[iLimit].limitCode, 8843 (int)integerValue(azArg[2])); 8844 } 8845 printf("%20s %d\n", aLimit[iLimit].zLimitName, 8846 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); 8847 } 8848 }else 8849 8850 if( c=='l' && n>2 && cli_strncmp(azArg[0], "lint", n)==0 ){ 8851 open_db(p, 0); 8852 lintDotCommand(p, azArg, nArg); 8853 }else 8854 8855#if !defined(SQLITE_OMIT_LOAD_EXTENSION) && !defined(SQLITE_SHELL_FIDDLE) 8856 if( c=='l' && cli_strncmp(azArg[0], "load", n)==0 ){ 8857 const char *zFile, *zProc; 8858 char *zErrMsg = 0; 8859 failIfSafeMode(p, "cannot run .load in safe mode"); 8860 if( nArg<2 ){ 8861 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); 8862 rc = 1; 8863 goto meta_command_exit; 8864 } 8865 zFile = azArg[1]; 8866 zProc = nArg>=3 ? azArg[2] : 0; 8867 open_db(p, 0); 8868 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); 8869 if( rc!=SQLITE_OK ){ 8870 utf8_printf(stderr, "Error: %s\n", zErrMsg); 8871 sqlite3_free(zErrMsg); 8872 rc = 1; 8873 } 8874 }else 8875#endif 8876 8877#ifndef SQLITE_SHELL_FIDDLE 8878 if( c=='l' && cli_strncmp(azArg[0], "log", n)==0 ){ 8879 failIfSafeMode(p, "cannot run .log in safe mode"); 8880 if( nArg!=2 ){ 8881 raw_printf(stderr, "Usage: .log FILENAME\n"); 8882 rc = 1; 8883 }else{ 8884 const char *zFile = azArg[1]; 8885 output_file_close(p->pLog); 8886 p->pLog = output_file_open(zFile, 0); 8887 } 8888 }else 8889#endif 8890 8891 if( c=='m' && cli_strncmp(azArg[0], "mode", n)==0 ){ 8892 const char *zMode = 0; 8893 const char *zTabname = 0; 8894 int i, n2; 8895 ColModeOpts cmOpts = ColModeOpts_default; 8896 for(i=1; i<nArg; i++){ 8897 const char *z = azArg[i]; 8898 if( optionMatch(z,"wrap") && i+1<nArg ){ 8899 cmOpts.iWrap = integerValue(azArg[++i]); 8900 }else if( optionMatch(z,"ww") ){ 8901 cmOpts.bWordWrap = 1; 8902 }else if( optionMatch(z,"wordwrap") && i+1<nArg ){ 8903 cmOpts.bWordWrap = (u8)booleanValue(azArg[++i]); 8904 }else if( optionMatch(z,"quote") ){ 8905 cmOpts.bQuote = 1; 8906 }else if( optionMatch(z,"noquote") ){ 8907 cmOpts.bQuote = 0; 8908 }else if( zMode==0 ){ 8909 zMode = z; 8910 /* Apply defaults for qbox pseudo-mode. If that 8911 * overwrites already-set values, user was informed of this. 8912 */ 8913 if( cli_strcmp(z, "qbox")==0 ){ 8914 ColModeOpts cmo = ColModeOpts_default_qbox; 8915 zMode = "box"; 8916 cmOpts = cmo; 8917 } 8918 }else if( zTabname==0 ){ 8919 zTabname = z; 8920 }else if( z[0]=='-' ){ 8921 utf8_printf(stderr, "unknown option: %s\n", z); 8922 utf8_printf(stderr, "options:\n" 8923 " --noquote\n" 8924 " --quote\n" 8925 " --wordwrap on/off\n" 8926 " --wrap N\n" 8927 " --ww\n"); 8928 rc = 1; 8929 goto meta_command_exit; 8930 }else{ 8931 utf8_printf(stderr, "extra argument: \"%s\"\n", z); 8932 rc = 1; 8933 goto meta_command_exit; 8934 } 8935 } 8936 if( zMode==0 ){ 8937 if( p->mode==MODE_Column 8938 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) 8939 ){ 8940 raw_printf 8941 (p->out, 8942 "current output mode: %s --wrap %d --wordwrap %s --%squote\n", 8943 modeDescr[p->mode], p->cmOpts.iWrap, 8944 p->cmOpts.bWordWrap ? "on" : "off", 8945 p->cmOpts.bQuote ? "" : "no"); 8946 }else{ 8947 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]); 8948 } 8949 zMode = modeDescr[p->mode]; 8950 } 8951 n2 = strlen30(zMode); 8952 if( cli_strncmp(zMode,"lines",n2)==0 ){ 8953 p->mode = MODE_Line; 8954 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8955 }else if( cli_strncmp(zMode,"columns",n2)==0 ){ 8956 p->mode = MODE_Column; 8957 if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){ 8958 p->showHeader = 1; 8959 } 8960 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8961 p->cmOpts = cmOpts; 8962 }else if( cli_strncmp(zMode,"list",n2)==0 ){ 8963 p->mode = MODE_List; 8964 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column); 8965 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8966 }else if( cli_strncmp(zMode,"html",n2)==0 ){ 8967 p->mode = MODE_Html; 8968 }else if( cli_strncmp(zMode,"tcl",n2)==0 ){ 8969 p->mode = MODE_Tcl; 8970 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); 8971 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8972 }else if( cli_strncmp(zMode,"csv",n2)==0 ){ 8973 p->mode = MODE_Csv; 8974 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8975 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 8976 }else if( cli_strncmp(zMode,"tabs",n2)==0 ){ 8977 p->mode = MODE_List; 8978 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); 8979 }else if( cli_strncmp(zMode,"insert",n2)==0 ){ 8980 p->mode = MODE_Insert; 8981 set_table_name(p, zTabname ? zTabname : "table"); 8982 }else if( cli_strncmp(zMode,"quote",n2)==0 ){ 8983 p->mode = MODE_Quote; 8984 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 8985 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); 8986 }else if( cli_strncmp(zMode,"ascii",n2)==0 ){ 8987 p->mode = MODE_Ascii; 8988 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); 8989 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); 8990 }else if( cli_strncmp(zMode,"markdown",n2)==0 ){ 8991 p->mode = MODE_Markdown; 8992 p->cmOpts = cmOpts; 8993 }else if( cli_strncmp(zMode,"table",n2)==0 ){ 8994 p->mode = MODE_Table; 8995 p->cmOpts = cmOpts; 8996 }else if( cli_strncmp(zMode,"box",n2)==0 ){ 8997 p->mode = MODE_Box; 8998 p->cmOpts = cmOpts; 8999 }else if( cli_strncmp(zMode,"count",n2)==0 ){ 9000 p->mode = MODE_Count; 9001 }else if( cli_strncmp(zMode,"off",n2)==0 ){ 9002 p->mode = MODE_Off; 9003 }else if( cli_strncmp(zMode,"json",n2)==0 ){ 9004 p->mode = MODE_Json; 9005 }else{ 9006 raw_printf(stderr, "Error: mode should be one of: " 9007 "ascii box column csv html insert json line list markdown " 9008 "qbox quote table tabs tcl\n"); 9009 rc = 1; 9010 } 9011 p->cMode = p->mode; 9012 }else 9013 9014#ifndef SQLITE_SHELL_FIDDLE 9015 if( c=='n' && cli_strcmp(azArg[0], "nonce")==0 ){ 9016 if( nArg!=2 ){ 9017 raw_printf(stderr, "Usage: .nonce NONCE\n"); 9018 rc = 1; 9019 }else if( p->zNonce==0 || cli_strcmp(azArg[1],p->zNonce)!=0 ){ 9020 raw_printf(stderr, "line %d: incorrect nonce: \"%s\"\n", 9021 p->lineno, azArg[1]); 9022 exit(1); 9023 }else{ 9024 p->bSafeMode = 0; 9025 return 0; /* Return immediately to bypass the safe mode reset 9026 ** at the end of this procedure */ 9027 } 9028 }else 9029#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 9030 9031 if( c=='n' && cli_strncmp(azArg[0], "nullvalue", n)==0 ){ 9032 if( nArg==2 ){ 9033 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, 9034 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); 9035 }else{ 9036 raw_printf(stderr, "Usage: .nullvalue STRING\n"); 9037 rc = 1; 9038 } 9039 }else 9040 9041 if( c=='o' && cli_strncmp(azArg[0], "open", n)==0 && n>=2 ){ 9042 const char *zFN = 0; /* Pointer to constant filename */ 9043 char *zNewFilename = 0; /* Name of the database file to open */ 9044 int iName = 1; /* Index in azArg[] of the filename */ 9045 int newFlag = 0; /* True to delete file before opening */ 9046 int openMode = SHELL_OPEN_UNSPEC; 9047 9048 /* Check for command-line arguments */ 9049 for(iName=1; iName<nArg; iName++){ 9050 const char *z = azArg[iName]; 9051#ifndef SQLITE_SHELL_FIDDLE 9052 if( optionMatch(z,"new") ){ 9053 newFlag = 1; 9054#ifdef SQLITE_HAVE_ZLIB 9055 }else if( optionMatch(z, "zip") ){ 9056 openMode = SHELL_OPEN_ZIPFILE; 9057#endif 9058 }else if( optionMatch(z, "append") ){ 9059 openMode = SHELL_OPEN_APPENDVFS; 9060 }else if( optionMatch(z, "readonly") ){ 9061 openMode = SHELL_OPEN_READONLY; 9062 }else if( optionMatch(z, "nofollow") ){ 9063 p->openFlags |= SQLITE_OPEN_NOFOLLOW; 9064#ifndef SQLITE_OMIT_DESERIALIZE 9065 }else if( optionMatch(z, "deserialize") ){ 9066 openMode = SHELL_OPEN_DESERIALIZE; 9067 }else if( optionMatch(z, "hexdb") ){ 9068 openMode = SHELL_OPEN_HEXDB; 9069 }else if( optionMatch(z, "maxsize") && iName+1<nArg ){ 9070 p->szMax = integerValue(azArg[++iName]); 9071#endif /* SQLITE_OMIT_DESERIALIZE */ 9072 }else 9073#endif /* !SQLITE_SHELL_FIDDLE */ 9074 if( z[0]=='-' ){ 9075 utf8_printf(stderr, "unknown option: %s\n", z); 9076 rc = 1; 9077 goto meta_command_exit; 9078 }else if( zFN ){ 9079 utf8_printf(stderr, "extra argument: \"%s\"\n", z); 9080 rc = 1; 9081 goto meta_command_exit; 9082 }else{ 9083 zFN = z; 9084 } 9085 } 9086 9087 /* Close the existing database */ 9088 session_close_all(p, -1); 9089 close_db(p->db); 9090 p->db = 0; 9091 p->pAuxDb->zDbFilename = 0; 9092 sqlite3_free(p->pAuxDb->zFreeOnClose); 9093 p->pAuxDb->zFreeOnClose = 0; 9094 p->openMode = openMode; 9095 p->openFlags = 0; 9096 p->szMax = 0; 9097 9098 /* If a filename is specified, try to open it first */ 9099 if( zFN || p->openMode==SHELL_OPEN_HEXDB ){ 9100 if( newFlag && zFN && !p->bSafeMode ) shellDeleteFile(zFN); 9101#ifndef SQLITE_SHELL_FIDDLE 9102 if( p->bSafeMode 9103 && p->openMode!=SHELL_OPEN_HEXDB 9104 && zFN 9105 && cli_strcmp(zFN,":memory:")!=0 9106 ){ 9107 failIfSafeMode(p, "cannot open disk-based database files in safe mode"); 9108 } 9109#else 9110 /* WASM mode has its own sandboxed pseudo-filesystem. */ 9111#endif 9112 if( zFN ){ 9113 zNewFilename = sqlite3_mprintf("%s", zFN); 9114 shell_check_oom(zNewFilename); 9115 }else{ 9116 zNewFilename = 0; 9117 } 9118 p->pAuxDb->zDbFilename = zNewFilename; 9119 open_db(p, OPEN_DB_KEEPALIVE); 9120 if( p->db==0 ){ 9121 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename); 9122 sqlite3_free(zNewFilename); 9123 }else{ 9124 p->pAuxDb->zFreeOnClose = zNewFilename; 9125 } 9126 } 9127 if( p->db==0 ){ 9128 /* As a fall-back open a TEMP database */ 9129 p->pAuxDb->zDbFilename = 0; 9130 open_db(p, 0); 9131 } 9132 }else 9133 9134#ifndef SQLITE_SHELL_FIDDLE 9135 if( (c=='o' 9136 && (cli_strncmp(azArg[0], "output", n)==0 9137 || cli_strncmp(azArg[0], "once", n)==0)) 9138 || (c=='e' && n==5 && cli_strcmp(azArg[0],"excel")==0) 9139 ){ 9140 char *zFile = 0; 9141 int bTxtMode = 0; 9142 int i; 9143 int eMode = 0; 9144 int bOnce = 0; /* 0: .output, 1: .once, 2: .excel */ 9145 unsigned char zBOM[4]; /* Byte-order mark to using if --bom is present */ 9146 9147 zBOM[0] = 0; 9148 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 9149 if( c=='e' ){ 9150 eMode = 'x'; 9151 bOnce = 2; 9152 }else if( cli_strncmp(azArg[0],"once",n)==0 ){ 9153 bOnce = 1; 9154 } 9155 for(i=1; i<nArg; i++){ 9156 char *z = azArg[i]; 9157 if( z[0]=='-' ){ 9158 if( z[1]=='-' ) z++; 9159 if( cli_strcmp(z,"-bom")==0 ){ 9160 zBOM[0] = 0xef; 9161 zBOM[1] = 0xbb; 9162 zBOM[2] = 0xbf; 9163 zBOM[3] = 0; 9164 }else if( c!='e' && cli_strcmp(z,"-x")==0 ){ 9165 eMode = 'x'; /* spreadsheet */ 9166 }else if( c!='e' && cli_strcmp(z,"-e")==0 ){ 9167 eMode = 'e'; /* text editor */ 9168 }else{ 9169 utf8_printf(p->out, "ERROR: unknown option: \"%s\". Usage:\n", 9170 azArg[i]); 9171 showHelp(p->out, azArg[0]); 9172 rc = 1; 9173 goto meta_command_exit; 9174 } 9175 }else if( zFile==0 && eMode!='e' && eMode!='x' ){ 9176 zFile = sqlite3_mprintf("%s", z); 9177 if( zFile && zFile[0]=='|' ){ 9178 while( i+1<nArg ) zFile = sqlite3_mprintf("%z %s", zFile, azArg[++i]); 9179 break; 9180 } 9181 }else{ 9182 utf8_printf(p->out,"ERROR: extra parameter: \"%s\". Usage:\n", 9183 azArg[i]); 9184 showHelp(p->out, azArg[0]); 9185 rc = 1; 9186 sqlite3_free(zFile); 9187 goto meta_command_exit; 9188 } 9189 } 9190 if( zFile==0 ){ 9191 zFile = sqlite3_mprintf("stdout"); 9192 } 9193 if( bOnce ){ 9194 p->outCount = 2; 9195 }else{ 9196 p->outCount = 0; 9197 } 9198 output_reset(p); 9199#ifndef SQLITE_NOHAVE_SYSTEM 9200 if( eMode=='e' || eMode=='x' ){ 9201 p->doXdgOpen = 1; 9202 outputModePush(p); 9203 if( eMode=='x' ){ 9204 /* spreadsheet mode. Output as CSV. */ 9205 newTempFile(p, "csv"); 9206 ShellClearFlag(p, SHFLG_Echo); 9207 p->mode = MODE_Csv; 9208 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); 9209 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); 9210 }else{ 9211 /* text editor mode */ 9212 newTempFile(p, "txt"); 9213 bTxtMode = 1; 9214 } 9215 sqlite3_free(zFile); 9216 zFile = sqlite3_mprintf("%s", p->zTempFile); 9217 } 9218#endif /* SQLITE_NOHAVE_SYSTEM */ 9219 shell_check_oom(zFile); 9220 if( zFile[0]=='|' ){ 9221#ifdef SQLITE_OMIT_POPEN 9222 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9223 rc = 1; 9224 p->out = stdout; 9225#else 9226 p->out = popen(zFile + 1, "w"); 9227 if( p->out==0 ){ 9228 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); 9229 p->out = stdout; 9230 rc = 1; 9231 }else{ 9232 if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out); 9233 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9234 } 9235#endif 9236 }else{ 9237 p->out = output_file_open(zFile, bTxtMode); 9238 if( p->out==0 ){ 9239 if( cli_strcmp(zFile,"off")!=0 ){ 9240 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); 9241 } 9242 p->out = stdout; 9243 rc = 1; 9244 } else { 9245 if( zBOM[0] ) fwrite(zBOM, 1, 3, p->out); 9246 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); 9247 } 9248 } 9249 sqlite3_free(zFile); 9250 }else 9251#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 9252 9253 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "parameter", n)==0 ){ 9254 open_db(p,0); 9255 if( nArg<=1 ) goto parameter_syntax_error; 9256 9257 /* .parameter clear 9258 ** Clear all bind parameters by dropping the TEMP table that holds them. 9259 */ 9260 if( nArg==2 && cli_strcmp(azArg[1],"clear")==0 ){ 9261 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp.sqlite_parameters;", 9262 0, 0, 0); 9263 }else 9264 9265 /* .parameter list 9266 ** List all bind parameters. 9267 */ 9268 if( nArg==2 && cli_strcmp(azArg[1],"list")==0 ){ 9269 sqlite3_stmt *pStmt = 0; 9270 int rx; 9271 int len = 0; 9272 rx = sqlite3_prepare_v2(p->db, 9273 "SELECT max(length(key)) " 9274 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9275 if( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9276 len = sqlite3_column_int(pStmt, 0); 9277 if( len>40 ) len = 40; 9278 } 9279 sqlite3_finalize(pStmt); 9280 pStmt = 0; 9281 if( len ){ 9282 rx = sqlite3_prepare_v2(p->db, 9283 "SELECT key, quote(value) " 9284 "FROM temp.sqlite_parameters;", -1, &pStmt, 0); 9285 while( rx==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 9286 utf8_printf(p->out, "%-*s %s\n", len, sqlite3_column_text(pStmt,0), 9287 sqlite3_column_text(pStmt,1)); 9288 } 9289 sqlite3_finalize(pStmt); 9290 } 9291 }else 9292 9293 /* .parameter init 9294 ** Make sure the TEMP table used to hold bind parameters exists. 9295 ** Create it if necessary. 9296 */ 9297 if( nArg==2 && cli_strcmp(azArg[1],"init")==0 ){ 9298 bind_table_init(p); 9299 }else 9300 9301 /* .parameter set NAME VALUE 9302 ** Set or reset a bind parameter. NAME should be the full parameter 9303 ** name exactly as it appears in the query. (ex: $abc, @def). The 9304 ** VALUE can be in either SQL literal notation, or if not it will be 9305 ** understood to be a text string. 9306 */ 9307 if( nArg==4 && cli_strcmp(azArg[1],"set")==0 ){ 9308 int rx; 9309 char *zSql; 9310 sqlite3_stmt *pStmt; 9311 const char *zKey = azArg[2]; 9312 const char *zValue = azArg[3]; 9313 bind_table_init(p); 9314 zSql = sqlite3_mprintf( 9315 "REPLACE INTO temp.sqlite_parameters(key,value)" 9316 "VALUES(%Q,%s);", zKey, zValue); 9317 shell_check_oom(zSql); 9318 pStmt = 0; 9319 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9320 sqlite3_free(zSql); 9321 if( rx!=SQLITE_OK ){ 9322 sqlite3_finalize(pStmt); 9323 pStmt = 0; 9324 zSql = sqlite3_mprintf( 9325 "REPLACE INTO temp.sqlite_parameters(key,value)" 9326 "VALUES(%Q,%Q);", zKey, zValue); 9327 shell_check_oom(zSql); 9328 rx = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 9329 sqlite3_free(zSql); 9330 if( rx!=SQLITE_OK ){ 9331 utf8_printf(p->out, "Error: %s\n", sqlite3_errmsg(p->db)); 9332 sqlite3_finalize(pStmt); 9333 pStmt = 0; 9334 rc = 1; 9335 } 9336 } 9337 sqlite3_step(pStmt); 9338 sqlite3_finalize(pStmt); 9339 }else 9340 9341 /* .parameter unset NAME 9342 ** Remove the NAME binding from the parameter binding table, if it 9343 ** exists. 9344 */ 9345 if( nArg==3 && cli_strcmp(azArg[1],"unset")==0 ){ 9346 char *zSql = sqlite3_mprintf( 9347 "DELETE FROM temp.sqlite_parameters WHERE key=%Q", azArg[2]); 9348 shell_check_oom(zSql); 9349 sqlite3_exec(p->db, zSql, 0, 0, 0); 9350 sqlite3_free(zSql); 9351 }else 9352 /* If no command name matches, show a syntax error */ 9353 parameter_syntax_error: 9354 showHelp(p->out, "parameter"); 9355 }else 9356 9357 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "print", n)==0 ){ 9358 int i; 9359 for(i=1; i<nArg; i++){ 9360 if( i>1 ) raw_printf(p->out, " "); 9361 utf8_printf(p->out, "%s", azArg[i]); 9362 } 9363 raw_printf(p->out, "\n"); 9364 }else 9365 9366#ifndef SQLITE_OMIT_PROGRESS_CALLBACK 9367 if( c=='p' && n>=3 && cli_strncmp(azArg[0], "progress", n)==0 ){ 9368 int i; 9369 int nn = 0; 9370 p->flgProgress = 0; 9371 p->mxProgress = 0; 9372 p->nProgress = 0; 9373 for(i=1; i<nArg; i++){ 9374 const char *z = azArg[i]; 9375 if( z[0]=='-' ){ 9376 z++; 9377 if( z[0]=='-' ) z++; 9378 if( cli_strcmp(z,"quiet")==0 || cli_strcmp(z,"q")==0 ){ 9379 p->flgProgress |= SHELL_PROGRESS_QUIET; 9380 continue; 9381 } 9382 if( cli_strcmp(z,"reset")==0 ){ 9383 p->flgProgress |= SHELL_PROGRESS_RESET; 9384 continue; 9385 } 9386 if( cli_strcmp(z,"once")==0 ){ 9387 p->flgProgress |= SHELL_PROGRESS_ONCE; 9388 continue; 9389 } 9390 if( cli_strcmp(z,"limit")==0 ){ 9391 if( i+1>=nArg ){ 9392 utf8_printf(stderr, "Error: missing argument on --limit\n"); 9393 rc = 1; 9394 goto meta_command_exit; 9395 }else{ 9396 p->mxProgress = (int)integerValue(azArg[++i]); 9397 } 9398 continue; 9399 } 9400 utf8_printf(stderr, "Error: unknown option: \"%s\"\n", azArg[i]); 9401 rc = 1; 9402 goto meta_command_exit; 9403 }else{ 9404 nn = (int)integerValue(z); 9405 } 9406 } 9407 open_db(p, 0); 9408 sqlite3_progress_handler(p->db, nn, progress_handler, p); 9409 }else 9410#endif /* SQLITE_OMIT_PROGRESS_CALLBACK */ 9411 9412 if( c=='p' && cli_strncmp(azArg[0], "prompt", n)==0 ){ 9413 if( nArg >= 2) { 9414 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); 9415 } 9416 if( nArg >= 3) { 9417 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); 9418 } 9419 }else 9420 9421#ifndef SQLITE_SHELL_FIDDLE 9422 if( c=='q' && cli_strncmp(azArg[0], "quit", n)==0 ){ 9423 rc = 2; 9424 }else 9425#endif 9426 9427#ifndef SQLITE_SHELL_FIDDLE 9428 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "read", n)==0 ){ 9429 FILE *inSaved = p->in; 9430 int savedLineno = p->lineno; 9431 failIfSafeMode(p, "cannot run .read in safe mode"); 9432 if( nArg!=2 ){ 9433 raw_printf(stderr, "Usage: .read FILE\n"); 9434 rc = 1; 9435 goto meta_command_exit; 9436 } 9437 if( azArg[1][0]=='|' ){ 9438#ifdef SQLITE_OMIT_POPEN 9439 raw_printf(stderr, "Error: pipes are not supported in this OS\n"); 9440 rc = 1; 9441 p->out = stdout; 9442#else 9443 p->in = popen(azArg[1]+1, "r"); 9444 if( p->in==0 ){ 9445 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); 9446 rc = 1; 9447 }else{ 9448 rc = process_input(p); 9449 pclose(p->in); 9450 } 9451#endif 9452 }else if( (p->in = openChrSource(azArg[1]))==0 ){ 9453 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); 9454 rc = 1; 9455 }else{ 9456 rc = process_input(p); 9457 fclose(p->in); 9458 } 9459 p->in = inSaved; 9460 p->lineno = savedLineno; 9461 }else 9462#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 9463 9464#ifndef SQLITE_SHELL_FIDDLE 9465 if( c=='r' && n>=3 && cli_strncmp(azArg[0], "restore", n)==0 ){ 9466 const char *zSrcFile; 9467 const char *zDb; 9468 sqlite3 *pSrc; 9469 sqlite3_backup *pBackup; 9470 int nTimeout = 0; 9471 9472 failIfSafeMode(p, "cannot run .restore in safe mode"); 9473 if( nArg==2 ){ 9474 zSrcFile = azArg[1]; 9475 zDb = "main"; 9476 }else if( nArg==3 ){ 9477 zSrcFile = azArg[2]; 9478 zDb = azArg[1]; 9479 }else{ 9480 raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); 9481 rc = 1; 9482 goto meta_command_exit; 9483 } 9484 rc = sqlite3_open(zSrcFile, &pSrc); 9485 if( rc!=SQLITE_OK ){ 9486 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); 9487 close_db(pSrc); 9488 return 1; 9489 } 9490 open_db(p, 0); 9491 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); 9492 if( pBackup==0 ){ 9493 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9494 close_db(pSrc); 9495 return 1; 9496 } 9497 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK 9498 || rc==SQLITE_BUSY ){ 9499 if( rc==SQLITE_BUSY ){ 9500 if( nTimeout++ >= 3 ) break; 9501 sqlite3_sleep(100); 9502 } 9503 } 9504 sqlite3_backup_finish(pBackup); 9505 if( rc==SQLITE_DONE ){ 9506 rc = 0; 9507 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ 9508 raw_printf(stderr, "Error: source database is busy\n"); 9509 rc = 1; 9510 }else{ 9511 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9512 rc = 1; 9513 } 9514 close_db(pSrc); 9515 }else 9516#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 9517 9518 if( c=='s' && cli_strncmp(azArg[0], "scanstats", n)==0 ){ 9519 if( nArg==2 ){ 9520 p->scanstatsOn = (u8)booleanValue(azArg[1]); 9521#ifndef SQLITE_ENABLE_STMT_SCANSTATUS 9522 raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); 9523#endif 9524 }else{ 9525 raw_printf(stderr, "Usage: .scanstats on|off\n"); 9526 rc = 1; 9527 } 9528 }else 9529 9530 if( c=='s' && cli_strncmp(azArg[0], "schema", n)==0 ){ 9531 ShellText sSelect; 9532 ShellState data; 9533 char *zErrMsg = 0; 9534 const char *zDiv = "("; 9535 const char *zName = 0; 9536 int iSchema = 0; 9537 int bDebug = 0; 9538 int bNoSystemTabs = 0; 9539 int ii; 9540 9541 open_db(p, 0); 9542 memcpy(&data, p, sizeof(data)); 9543 data.showHeader = 0; 9544 data.cMode = data.mode = MODE_Semi; 9545 initText(&sSelect); 9546 for(ii=1; ii<nArg; ii++){ 9547 if( optionMatch(azArg[ii],"indent") ){ 9548 data.cMode = data.mode = MODE_Pretty; 9549 }else if( optionMatch(azArg[ii],"debug") ){ 9550 bDebug = 1; 9551 }else if( optionMatch(azArg[ii],"nosys") ){ 9552 bNoSystemTabs = 1; 9553 }else if( azArg[ii][0]=='-' ){ 9554 utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]); 9555 rc = 1; 9556 goto meta_command_exit; 9557 }else if( zName==0 ){ 9558 zName = azArg[ii]; 9559 }else{ 9560 raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n"); 9561 rc = 1; 9562 goto meta_command_exit; 9563 } 9564 } 9565 if( zName!=0 ){ 9566 int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0 9567 || sqlite3_strlike(zName, "sqlite_schema", '\\')==0 9568 || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 9569 || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0; 9570 if( isSchema ){ 9571 char *new_argv[2], *new_colv[2]; 9572 new_argv[0] = sqlite3_mprintf( 9573 "CREATE TABLE %s (\n" 9574 " type text,\n" 9575 " name text,\n" 9576 " tbl_name text,\n" 9577 " rootpage integer,\n" 9578 " sql text\n" 9579 ")", zName); 9580 shell_check_oom(new_argv[0]); 9581 new_argv[1] = 0; 9582 new_colv[0] = "sql"; 9583 new_colv[1] = 0; 9584 callback(&data, 1, new_argv, new_colv); 9585 sqlite3_free(new_argv[0]); 9586 } 9587 } 9588 if( zDiv ){ 9589 sqlite3_stmt *pStmt = 0; 9590 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list", 9591 -1, &pStmt, 0); 9592 if( rc ){ 9593 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); 9594 sqlite3_finalize(pStmt); 9595 rc = 1; 9596 goto meta_command_exit; 9597 } 9598 appendText(&sSelect, "SELECT sql FROM", 0); 9599 iSchema = 0; 9600 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 9601 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0); 9602 char zScNum[30]; 9603 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema); 9604 appendText(&sSelect, zDiv, 0); 9605 zDiv = " UNION ALL "; 9606 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0); 9607 if( sqlite3_stricmp(zDb, "main")!=0 ){ 9608 appendText(&sSelect, zDb, '\''); 9609 }else{ 9610 appendText(&sSelect, "NULL", 0); 9611 } 9612 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0); 9613 appendText(&sSelect, zScNum, 0); 9614 appendText(&sSelect, " AS snum, ", 0); 9615 appendText(&sSelect, zDb, '\''); 9616 appendText(&sSelect, " AS sname FROM ", 0); 9617 appendText(&sSelect, zDb, quoteChar(zDb)); 9618 appendText(&sSelect, ".sqlite_schema", 0); 9619 } 9620 sqlite3_finalize(pStmt); 9621#ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS 9622 if( zName ){ 9623 appendText(&sSelect, 9624 " UNION ALL SELECT shell_module_schema(name)," 9625 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 9626 0); 9627 } 9628#endif 9629 appendText(&sSelect, ") WHERE ", 0); 9630 if( zName ){ 9631 char *zQarg = sqlite3_mprintf("%Q", zName); 9632 int bGlob; 9633 shell_check_oom(zQarg); 9634 bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 || 9635 strchr(zName, '[') != 0; 9636 if( strchr(zName, '.') ){ 9637 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0); 9638 }else{ 9639 appendText(&sSelect, "lower(tbl_name)", 0); 9640 } 9641 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0); 9642 appendText(&sSelect, zQarg, 0); 9643 if( !bGlob ){ 9644 appendText(&sSelect, " ESCAPE '\\' ", 0); 9645 } 9646 appendText(&sSelect, " AND ", 0); 9647 sqlite3_free(zQarg); 9648 } 9649 if( bNoSystemTabs ){ 9650 appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0); 9651 } 9652 appendText(&sSelect, "sql IS NOT NULL" 9653 " ORDER BY snum, rowid", 0); 9654 if( bDebug ){ 9655 utf8_printf(p->out, "SQL: %s;\n", sSelect.z); 9656 }else{ 9657 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg); 9658 } 9659 freeText(&sSelect); 9660 } 9661 if( zErrMsg ){ 9662 utf8_printf(stderr,"Error: %s\n", zErrMsg); 9663 sqlite3_free(zErrMsg); 9664 rc = 1; 9665 }else if( rc != SQLITE_OK ){ 9666 raw_printf(stderr,"Error: querying schema information\n"); 9667 rc = 1; 9668 }else{ 9669 rc = 0; 9670 } 9671 }else 9672 9673 if( (c=='s' && n==11 && cli_strncmp(azArg[0], "selecttrace", n)==0) 9674 || (c=='t' && n==9 && cli_strncmp(azArg[0], "treetrace", n)==0) 9675 ){ 9676 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 9677 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x); 9678 }else 9679 9680#if defined(SQLITE_ENABLE_SESSION) 9681 if( c=='s' && cli_strncmp(azArg[0],"session",n)==0 && n>=3 ){ 9682 struct AuxDb *pAuxDb = p->pAuxDb; 9683 OpenSession *pSession = &pAuxDb->aSession[0]; 9684 char **azCmd = &azArg[1]; 9685 int iSes = 0; 9686 int nCmd = nArg - 1; 9687 int i; 9688 if( nArg<=1 ) goto session_syntax_error; 9689 open_db(p, 0); 9690 if( nArg>=3 ){ 9691 for(iSes=0; iSes<pAuxDb->nSession; iSes++){ 9692 if( cli_strcmp(pAuxDb->aSession[iSes].zName, azArg[1])==0 ) break; 9693 } 9694 if( iSes<pAuxDb->nSession ){ 9695 pSession = &pAuxDb->aSession[iSes]; 9696 azCmd++; 9697 nCmd--; 9698 }else{ 9699 pSession = &pAuxDb->aSession[0]; 9700 iSes = 0; 9701 } 9702 } 9703 9704 /* .session attach TABLE 9705 ** Invoke the sqlite3session_attach() interface to attach a particular 9706 ** table so that it is never filtered. 9707 */ 9708 if( cli_strcmp(azCmd[0],"attach")==0 ){ 9709 if( nCmd!=2 ) goto session_syntax_error; 9710 if( pSession->p==0 ){ 9711 session_not_open: 9712 raw_printf(stderr, "ERROR: No sessions are open\n"); 9713 }else{ 9714 rc = sqlite3session_attach(pSession->p, azCmd[1]); 9715 if( rc ){ 9716 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); 9717 rc = 0; 9718 } 9719 } 9720 }else 9721 9722 /* .session changeset FILE 9723 ** .session patchset FILE 9724 ** Write a changeset or patchset into a file. The file is overwritten. 9725 */ 9726 if( cli_strcmp(azCmd[0],"changeset")==0 9727 || cli_strcmp(azCmd[0],"patchset")==0 9728 ){ 9729 FILE *out = 0; 9730 failIfSafeMode(p, "cannot run \".session %s\" in safe mode", azCmd[0]); 9731 if( nCmd!=2 ) goto session_syntax_error; 9732 if( pSession->p==0 ) goto session_not_open; 9733 out = fopen(azCmd[1], "wb"); 9734 if( out==0 ){ 9735 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", 9736 azCmd[1]); 9737 }else{ 9738 int szChng; 9739 void *pChng; 9740 if( azCmd[0][0]=='c' ){ 9741 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); 9742 }else{ 9743 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); 9744 } 9745 if( rc ){ 9746 printf("Error: error code %d\n", rc); 9747 rc = 0; 9748 } 9749 if( pChng 9750 && fwrite(pChng, szChng, 1, out)!=1 ){ 9751 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", 9752 szChng); 9753 } 9754 sqlite3_free(pChng); 9755 fclose(out); 9756 } 9757 }else 9758 9759 /* .session close 9760 ** Close the identified session 9761 */ 9762 if( cli_strcmp(azCmd[0], "close")==0 ){ 9763 if( nCmd!=1 ) goto session_syntax_error; 9764 if( pAuxDb->nSession ){ 9765 session_close(pSession); 9766 pAuxDb->aSession[iSes] = pAuxDb->aSession[--pAuxDb->nSession]; 9767 } 9768 }else 9769 9770 /* .session enable ?BOOLEAN? 9771 ** Query or set the enable flag 9772 */ 9773 if( cli_strcmp(azCmd[0], "enable")==0 ){ 9774 int ii; 9775 if( nCmd>2 ) goto session_syntax_error; 9776 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9777 if( pAuxDb->nSession ){ 9778 ii = sqlite3session_enable(pSession->p, ii); 9779 utf8_printf(p->out, "session %s enable flag = %d\n", 9780 pSession->zName, ii); 9781 } 9782 }else 9783 9784 /* .session filter GLOB .... 9785 ** Set a list of GLOB patterns of table names to be excluded. 9786 */ 9787 if( cli_strcmp(azCmd[0], "filter")==0 ){ 9788 int ii, nByte; 9789 if( nCmd<2 ) goto session_syntax_error; 9790 if( pAuxDb->nSession ){ 9791 for(ii=0; ii<pSession->nFilter; ii++){ 9792 sqlite3_free(pSession->azFilter[ii]); 9793 } 9794 sqlite3_free(pSession->azFilter); 9795 nByte = sizeof(pSession->azFilter[0])*(nCmd-1); 9796 pSession->azFilter = sqlite3_malloc( nByte ); 9797 if( pSession->azFilter==0 ){ 9798 raw_printf(stderr, "Error: out or memory\n"); 9799 exit(1); 9800 } 9801 for(ii=1; ii<nCmd; ii++){ 9802 char *x = pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); 9803 shell_check_oom(x); 9804 } 9805 pSession->nFilter = ii-1; 9806 } 9807 }else 9808 9809 /* .session indirect ?BOOLEAN? 9810 ** Query or set the indirect flag 9811 */ 9812 if( cli_strcmp(azCmd[0], "indirect")==0 ){ 9813 int ii; 9814 if( nCmd>2 ) goto session_syntax_error; 9815 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); 9816 if( pAuxDb->nSession ){ 9817 ii = sqlite3session_indirect(pSession->p, ii); 9818 utf8_printf(p->out, "session %s indirect flag = %d\n", 9819 pSession->zName, ii); 9820 } 9821 }else 9822 9823 /* .session isempty 9824 ** Determine if the session is empty 9825 */ 9826 if( cli_strcmp(azCmd[0], "isempty")==0 ){ 9827 int ii; 9828 if( nCmd!=1 ) goto session_syntax_error; 9829 if( pAuxDb->nSession ){ 9830 ii = sqlite3session_isempty(pSession->p); 9831 utf8_printf(p->out, "session %s isempty flag = %d\n", 9832 pSession->zName, ii); 9833 } 9834 }else 9835 9836 /* .session list 9837 ** List all currently open sessions 9838 */ 9839 if( cli_strcmp(azCmd[0],"list")==0 ){ 9840 for(i=0; i<pAuxDb->nSession; i++){ 9841 utf8_printf(p->out, "%d %s\n", i, pAuxDb->aSession[i].zName); 9842 } 9843 }else 9844 9845 /* .session open DB NAME 9846 ** Open a new session called NAME on the attached database DB. 9847 ** DB is normally "main". 9848 */ 9849 if( cli_strcmp(azCmd[0],"open")==0 ){ 9850 char *zName; 9851 if( nCmd!=3 ) goto session_syntax_error; 9852 zName = azCmd[2]; 9853 if( zName[0]==0 ) goto session_syntax_error; 9854 for(i=0; i<pAuxDb->nSession; i++){ 9855 if( cli_strcmp(pAuxDb->aSession[i].zName,zName)==0 ){ 9856 utf8_printf(stderr, "Session \"%s\" already exists\n", zName); 9857 goto meta_command_exit; 9858 } 9859 } 9860 if( pAuxDb->nSession>=ArraySize(pAuxDb->aSession) ){ 9861 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(pAuxDb->aSession)); 9862 goto meta_command_exit; 9863 } 9864 pSession = &pAuxDb->aSession[pAuxDb->nSession]; 9865 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); 9866 if( rc ){ 9867 raw_printf(stderr, "Cannot open session: error code=%d\n", rc); 9868 rc = 0; 9869 goto meta_command_exit; 9870 } 9871 pSession->nFilter = 0; 9872 sqlite3session_table_filter(pSession->p, session_filter, pSession); 9873 pAuxDb->nSession++; 9874 pSession->zName = sqlite3_mprintf("%s", zName); 9875 shell_check_oom(pSession->zName); 9876 }else 9877 /* If no command name matches, show a syntax error */ 9878 session_syntax_error: 9879 showHelp(p->out, "session"); 9880 }else 9881#endif 9882 9883#ifdef SQLITE_DEBUG 9884 /* Undocumented commands for internal testing. Subject to change 9885 ** without notice. */ 9886 if( c=='s' && n>=10 && cli_strncmp(azArg[0], "selftest-", 9)==0 ){ 9887 if( cli_strncmp(azArg[0]+9, "boolean", n-9)==0 ){ 9888 int i, v; 9889 for(i=1; i<nArg; i++){ 9890 v = booleanValue(azArg[i]); 9891 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); 9892 } 9893 } 9894 if( cli_strncmp(azArg[0]+9, "integer", n-9)==0 ){ 9895 int i; sqlite3_int64 v; 9896 for(i=1; i<nArg; i++){ 9897 char zBuf[200]; 9898 v = integerValue(azArg[i]); 9899 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); 9900 utf8_printf(p->out, "%s", zBuf); 9901 } 9902 } 9903 }else 9904#endif 9905 9906 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"selftest",n)==0 ){ 9907 int bIsInit = 0; /* True to initialize the SELFTEST table */ 9908 int bVerbose = 0; /* Verbose output */ 9909 int bSelftestExists; /* True if SELFTEST already exists */ 9910 int i, k; /* Loop counters */ 9911 int nTest = 0; /* Number of tests runs */ 9912 int nErr = 0; /* Number of errors seen */ 9913 ShellText str; /* Answer for a query */ 9914 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */ 9915 9916 open_db(p,0); 9917 for(i=1; i<nArg; i++){ 9918 const char *z = azArg[i]; 9919 if( z[0]=='-' && z[1]=='-' ) z++; 9920 if( cli_strcmp(z,"-init")==0 ){ 9921 bIsInit = 1; 9922 }else 9923 if( cli_strcmp(z,"-v")==0 ){ 9924 bVerbose++; 9925 }else 9926 { 9927 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 9928 azArg[i], azArg[0]); 9929 raw_printf(stderr, "Should be one of: --init -v\n"); 9930 rc = 1; 9931 goto meta_command_exit; 9932 } 9933 } 9934 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0) 9935 != SQLITE_OK ){ 9936 bSelftestExists = 0; 9937 }else{ 9938 bSelftestExists = 1; 9939 } 9940 if( bIsInit ){ 9941 createSelftestTable(p); 9942 bSelftestExists = 1; 9943 } 9944 initText(&str); 9945 appendText(&str, "x", 0); 9946 for(k=bSelftestExists; k>=0; k--){ 9947 if( k==1 ){ 9948 rc = sqlite3_prepare_v2(p->db, 9949 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno", 9950 -1, &pStmt, 0); 9951 }else{ 9952 rc = sqlite3_prepare_v2(p->db, 9953 "VALUES(0,'memo','Missing SELFTEST table - default checks only','')," 9954 " (1,'run','PRAGMA integrity_check','ok')", 9955 -1, &pStmt, 0); 9956 } 9957 if( rc ){ 9958 raw_printf(stderr, "Error querying the selftest table\n"); 9959 rc = 1; 9960 sqlite3_finalize(pStmt); 9961 goto meta_command_exit; 9962 } 9963 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 9964 int tno = sqlite3_column_int(pStmt, 0); 9965 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1); 9966 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2); 9967 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3); 9968 9969 if( zOp==0 ) continue; 9970 if( zSql==0 ) continue; 9971 if( zAns==0 ) continue; 9972 k = 0; 9973 if( bVerbose>0 ){ 9974 printf("%d: %s %s\n", tno, zOp, zSql); 9975 } 9976 if( cli_strcmp(zOp,"memo")==0 ){ 9977 utf8_printf(p->out, "%s\n", zSql); 9978 }else 9979 if( cli_strcmp(zOp,"run")==0 ){ 9980 char *zErrMsg = 0; 9981 str.n = 0; 9982 str.z[0] = 0; 9983 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg); 9984 nTest++; 9985 if( bVerbose ){ 9986 utf8_printf(p->out, "Result: %s\n", str.z); 9987 } 9988 if( rc || zErrMsg ){ 9989 nErr++; 9990 rc = 1; 9991 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg); 9992 sqlite3_free(zErrMsg); 9993 }else if( cli_strcmp(zAns,str.z)!=0 ){ 9994 nErr++; 9995 rc = 1; 9996 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns); 9997 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z); 9998 } 9999 }else 10000 { 10001 utf8_printf(stderr, 10002 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno); 10003 rc = 1; 10004 break; 10005 } 10006 } /* End loop over rows of content from SELFTEST */ 10007 sqlite3_finalize(pStmt); 10008 } /* End loop over k */ 10009 freeText(&str); 10010 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest); 10011 }else 10012 10013 if( c=='s' && cli_strncmp(azArg[0], "separator", n)==0 ){ 10014 if( nArg<2 || nArg>3 ){ 10015 raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); 10016 rc = 1; 10017 } 10018 if( nArg>=2 ){ 10019 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, 10020 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); 10021 } 10022 if( nArg>=3 ){ 10023 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, 10024 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); 10025 } 10026 }else 10027 10028 if( c=='s' && n>=4 && cli_strncmp(azArg[0],"sha3sum",n)==0 ){ 10029 const char *zLike = 0; /* Which table to checksum. 0 means everything */ 10030 int i; /* Loop counter */ 10031 int bSchema = 0; /* Also hash the schema */ 10032 int bSeparate = 0; /* Hash each table separately */ 10033 int iSize = 224; /* Hash algorithm to use */ 10034 int bDebug = 0; /* Only show the query that would have run */ 10035 sqlite3_stmt *pStmt; /* For querying tables names */ 10036 char *zSql; /* SQL to be run */ 10037 char *zSep; /* Separator */ 10038 ShellText sSql; /* Complete SQL for the query to run the hash */ 10039 ShellText sQuery; /* Set of queries used to read all content */ 10040 open_db(p, 0); 10041 for(i=1; i<nArg; i++){ 10042 const char *z = azArg[i]; 10043 if( z[0]=='-' ){ 10044 z++; 10045 if( z[0]=='-' ) z++; 10046 if( cli_strcmp(z,"schema")==0 ){ 10047 bSchema = 1; 10048 }else 10049 if( cli_strcmp(z,"sha3-224")==0 || cli_strcmp(z,"sha3-256")==0 10050 || cli_strcmp(z,"sha3-384")==0 || cli_strcmp(z,"sha3-512")==0 10051 ){ 10052 iSize = atoi(&z[5]); 10053 }else 10054 if( cli_strcmp(z,"debug")==0 ){ 10055 bDebug = 1; 10056 }else 10057 { 10058 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n", 10059 azArg[i], azArg[0]); 10060 showHelp(p->out, azArg[0]); 10061 rc = 1; 10062 goto meta_command_exit; 10063 } 10064 }else if( zLike ){ 10065 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n"); 10066 rc = 1; 10067 goto meta_command_exit; 10068 }else{ 10069 zLike = z; 10070 bSeparate = 1; 10071 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1; 10072 } 10073 } 10074 if( bSchema ){ 10075 zSql = "SELECT lower(name) FROM sqlite_schema" 10076 " WHERE type='table' AND coalesce(rootpage,0)>1" 10077 " UNION ALL SELECT 'sqlite_schema'" 10078 " ORDER BY 1 collate nocase"; 10079 }else{ 10080 zSql = "SELECT lower(name) FROM sqlite_schema" 10081 " WHERE type='table' AND coalesce(rootpage,0)>1" 10082 " AND name NOT LIKE 'sqlite_%'" 10083 " ORDER BY 1 collate nocase"; 10084 } 10085 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 10086 initText(&sQuery); 10087 initText(&sSql); 10088 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0); 10089 zSep = "VALUES("; 10090 while( SQLITE_ROW==sqlite3_step(pStmt) ){ 10091 const char *zTab = (const char*)sqlite3_column_text(pStmt,0); 10092 if( zTab==0 ) continue; 10093 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue; 10094 if( cli_strncmp(zTab, "sqlite_",7)!=0 ){ 10095 appendText(&sQuery,"SELECT * FROM ", 0); 10096 appendText(&sQuery,zTab,'"'); 10097 appendText(&sQuery," NOT INDEXED;", 0); 10098 }else if( cli_strcmp(zTab, "sqlite_schema")==0 ){ 10099 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema" 10100 " ORDER BY name;", 0); 10101 }else if( cli_strcmp(zTab, "sqlite_sequence")==0 ){ 10102 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence" 10103 " ORDER BY name;", 0); 10104 }else if( cli_strcmp(zTab, "sqlite_stat1")==0 ){ 10105 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1" 10106 " ORDER BY tbl,idx;", 0); 10107 }else if( cli_strcmp(zTab, "sqlite_stat4")==0 ){ 10108 appendText(&sQuery, "SELECT * FROM ", 0); 10109 appendText(&sQuery, zTab, 0); 10110 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0); 10111 } 10112 appendText(&sSql, zSep, 0); 10113 appendText(&sSql, sQuery.z, '\''); 10114 sQuery.n = 0; 10115 appendText(&sSql, ",", 0); 10116 appendText(&sSql, zTab, '\''); 10117 zSep = "),("; 10118 } 10119 sqlite3_finalize(pStmt); 10120 if( bSeparate ){ 10121 zSql = sqlite3_mprintf( 10122 "%s))" 10123 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label" 10124 " FROM [sha3sum$query]", 10125 sSql.z, iSize); 10126 }else{ 10127 zSql = sqlite3_mprintf( 10128 "%s))" 10129 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash" 10130 " FROM [sha3sum$query]", 10131 sSql.z, iSize); 10132 } 10133 shell_check_oom(zSql); 10134 freeText(&sQuery); 10135 freeText(&sSql); 10136 if( bDebug ){ 10137 utf8_printf(p->out, "%s\n", zSql); 10138 }else{ 10139 shell_exec(p, zSql, 0); 10140 } 10141 sqlite3_free(zSql); 10142 }else 10143 10144#if !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) 10145 if( c=='s' 10146 && (cli_strncmp(azArg[0], "shell", n)==0 10147 || cli_strncmp(azArg[0],"system",n)==0) 10148 ){ 10149 char *zCmd; 10150 int i, x; 10151 failIfSafeMode(p, "cannot run .%s in safe mode", azArg[0]); 10152 if( nArg<2 ){ 10153 raw_printf(stderr, "Usage: .system COMMAND\n"); 10154 rc = 1; 10155 goto meta_command_exit; 10156 } 10157 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); 10158 for(i=2; i<nArg && zCmd!=0; i++){ 10159 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", 10160 zCmd, azArg[i]); 10161 } 10162 x = zCmd!=0 ? system(zCmd) : 1; 10163 sqlite3_free(zCmd); 10164 if( x ) raw_printf(stderr, "System command returns %d\n", x); 10165 }else 10166#endif /* !defined(SQLITE_NOHAVE_SYSTEM) && !defined(SQLITE_SHELL_FIDDLE) */ 10167 10168 if( c=='s' && cli_strncmp(azArg[0], "show", n)==0 ){ 10169 static const char *azBool[] = { "off", "on", "trigger", "full"}; 10170 const char *zOut; 10171 int i; 10172 if( nArg!=1 ){ 10173 raw_printf(stderr, "Usage: .show\n"); 10174 rc = 1; 10175 goto meta_command_exit; 10176 } 10177 utf8_printf(p->out, "%12.12s: %s\n","echo", 10178 azBool[ShellHasFlag(p, SHFLG_Echo)]); 10179 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); 10180 utf8_printf(p->out, "%12.12s: %s\n","explain", 10181 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); 10182 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); 10183 if( p->mode==MODE_Column 10184 || (p->mode>=MODE_Markdown && p->mode<=MODE_Box) 10185 ){ 10186 utf8_printf 10187 (p->out, "%12.12s: %s --wrap %d --wordwrap %s --%squote\n", "mode", 10188 modeDescr[p->mode], p->cmOpts.iWrap, 10189 p->cmOpts.bWordWrap ? "on" : "off", 10190 p->cmOpts.bQuote ? "" : "no"); 10191 }else{ 10192 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); 10193 } 10194 utf8_printf(p->out, "%12.12s: ", "nullvalue"); 10195 output_c_string(p->out, p->nullValue); 10196 raw_printf(p->out, "\n"); 10197 utf8_printf(p->out,"%12.12s: %s\n","output", 10198 strlen30(p->outfile) ? p->outfile : "stdout"); 10199 utf8_printf(p->out,"%12.12s: ", "colseparator"); 10200 output_c_string(p->out, p->colSeparator); 10201 raw_printf(p->out, "\n"); 10202 utf8_printf(p->out,"%12.12s: ", "rowseparator"); 10203 output_c_string(p->out, p->rowSeparator); 10204 raw_printf(p->out, "\n"); 10205 switch( p->statsOn ){ 10206 case 0: zOut = "off"; break; 10207 default: zOut = "on"; break; 10208 case 2: zOut = "stmt"; break; 10209 case 3: zOut = "vmstep"; break; 10210 } 10211 utf8_printf(p->out, "%12.12s: %s\n","stats", zOut); 10212 utf8_printf(p->out, "%12.12s: ", "width"); 10213 for (i=0;i<p->nWidth;i++) { 10214 raw_printf(p->out, "%d ", p->colWidth[i]); 10215 } 10216 raw_printf(p->out, "\n"); 10217 utf8_printf(p->out, "%12.12s: %s\n", "filename", 10218 p->pAuxDb->zDbFilename ? p->pAuxDb->zDbFilename : ""); 10219 }else 10220 10221 if( c=='s' && cli_strncmp(azArg[0], "stats", n)==0 ){ 10222 if( nArg==2 ){ 10223 if( cli_strcmp(azArg[1],"stmt")==0 ){ 10224 p->statsOn = 2; 10225 }else if( cli_strcmp(azArg[1],"vmstep")==0 ){ 10226 p->statsOn = 3; 10227 }else{ 10228 p->statsOn = (u8)booleanValue(azArg[1]); 10229 } 10230 }else if( nArg==1 ){ 10231 display_stats(p->db, p, 0); 10232 }else{ 10233 raw_printf(stderr, "Usage: .stats ?on|off|stmt|vmstep?\n"); 10234 rc = 1; 10235 } 10236 }else 10237 10238 if( (c=='t' && n>1 && cli_strncmp(azArg[0], "tables", n)==0) 10239 || (c=='i' && (cli_strncmp(azArg[0], "indices", n)==0 10240 || cli_strncmp(azArg[0], "indexes", n)==0) ) 10241 ){ 10242 sqlite3_stmt *pStmt; 10243 char **azResult; 10244 int nRow, nAlloc; 10245 int ii; 10246 ShellText s; 10247 initText(&s); 10248 open_db(p, 0); 10249 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); 10250 if( rc ){ 10251 sqlite3_finalize(pStmt); 10252 return shellDatabaseError(p->db); 10253 } 10254 10255 if( nArg>2 && c=='i' ){ 10256 /* It is an historical accident that the .indexes command shows an error 10257 ** when called with the wrong number of arguments whereas the .tables 10258 ** command does not. */ 10259 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); 10260 rc = 1; 10261 sqlite3_finalize(pStmt); 10262 goto meta_command_exit; 10263 } 10264 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){ 10265 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); 10266 if( zDbName==0 ) continue; 10267 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0); 10268 if( sqlite3_stricmp(zDbName, "main")==0 ){ 10269 appendText(&s, "SELECT name FROM ", 0); 10270 }else{ 10271 appendText(&s, "SELECT ", 0); 10272 appendText(&s, zDbName, '\''); 10273 appendText(&s, "||'.'||name FROM ", 0); 10274 } 10275 appendText(&s, zDbName, '"'); 10276 appendText(&s, ".sqlite_schema ", 0); 10277 if( c=='t' ){ 10278 appendText(&s," WHERE type IN ('table','view')" 10279 " AND name NOT LIKE 'sqlite_%'" 10280 " AND name LIKE ?1", 0); 10281 }else{ 10282 appendText(&s," WHERE type='index'" 10283 " AND tbl_name LIKE ?1", 0); 10284 } 10285 } 10286 rc = sqlite3_finalize(pStmt); 10287 if( rc==SQLITE_OK ){ 10288 appendText(&s, " ORDER BY 1", 0); 10289 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0); 10290 } 10291 freeText(&s); 10292 if( rc ) return shellDatabaseError(p->db); 10293 10294 /* Run the SQL statement prepared by the above block. Store the results 10295 ** as an array of nul-terminated strings in azResult[]. */ 10296 nRow = nAlloc = 0; 10297 azResult = 0; 10298 if( nArg>1 ){ 10299 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); 10300 }else{ 10301 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); 10302 } 10303 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 10304 if( nRow>=nAlloc ){ 10305 char **azNew; 10306 int n2 = nAlloc*2 + 10; 10307 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); 10308 shell_check_oom(azNew); 10309 nAlloc = n2; 10310 azResult = azNew; 10311 } 10312 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); 10313 shell_check_oom(azResult[nRow]); 10314 nRow++; 10315 } 10316 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ 10317 rc = shellDatabaseError(p->db); 10318 } 10319 10320 /* Pretty-print the contents of array azResult[] to the output */ 10321 if( rc==0 && nRow>0 ){ 10322 int len, maxlen = 0; 10323 int i, j; 10324 int nPrintCol, nPrintRow; 10325 for(i=0; i<nRow; i++){ 10326 len = strlen30(azResult[i]); 10327 if( len>maxlen ) maxlen = len; 10328 } 10329 nPrintCol = 80/(maxlen+2); 10330 if( nPrintCol<1 ) nPrintCol = 1; 10331 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; 10332 for(i=0; i<nPrintRow; i++){ 10333 for(j=i; j<nRow; j+=nPrintRow){ 10334 char *zSp = j<nPrintRow ? "" : " "; 10335 utf8_printf(p->out, "%s%-*s", zSp, maxlen, 10336 azResult[j] ? azResult[j]:""); 10337 } 10338 raw_printf(p->out, "\n"); 10339 } 10340 } 10341 10342 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); 10343 sqlite3_free(azResult); 10344 }else 10345 10346#ifndef SQLITE_SHELL_FIDDLE 10347 /* Begin redirecting output to the file "testcase-out.txt" */ 10348 if( c=='t' && cli_strcmp(azArg[0],"testcase")==0 ){ 10349 output_reset(p); 10350 p->out = output_file_open("testcase-out.txt", 0); 10351 if( p->out==0 ){ 10352 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n"); 10353 } 10354 if( nArg>=2 ){ 10355 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]); 10356 }else{ 10357 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?"); 10358 } 10359 }else 10360#endif /* !defined(SQLITE_SHELL_FIDDLE) */ 10361 10362#ifndef SQLITE_UNTESTABLE 10363 if( c=='t' && n>=8 && cli_strncmp(azArg[0], "testctrl", n)==0 ){ 10364 static const struct { 10365 const char *zCtrlName; /* Name of a test-control option */ 10366 int ctrlCode; /* Integer code for that option */ 10367 int unSafe; /* Not valid for --safe mode */ 10368 const char *zUsage; /* Usage notes */ 10369 } aCtrl[] = { 10370 { "always", SQLITE_TESTCTRL_ALWAYS, 1, "BOOLEAN" }, 10371 { "assert", SQLITE_TESTCTRL_ASSERT, 1, "BOOLEAN" }, 10372 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS,1, "" },*/ 10373 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, 1, "" },*/ 10374 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, 0, "" }, 10375 { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,0,"BOOLEAN" }, 10376 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, 1,"" },*/ 10377 { "imposter", SQLITE_TESTCTRL_IMPOSTER,1,"SCHEMA ON/OFF ROOTPAGE"}, 10378 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS,0,"" }, 10379 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,0,"BOOLEAN" }, 10380 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT,1, "BOOLEAN" }, 10381 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS,0,"DISABLE-MASK" }, 10382#ifdef YYCOVERAGE 10383 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE,0,"" }, 10384#endif 10385 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE,0, "OFFSET " }, 10386 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE,0, "" }, 10387 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, 0, "" }, 10388 { "prng_seed", SQLITE_TESTCTRL_PRNG_SEED, 0, "SEED ?db?" }, 10389 { "seek_count", SQLITE_TESTCTRL_SEEK_COUNT, 0, "" }, 10390 { "sorter_mmap", SQLITE_TESTCTRL_SORTER_MMAP, 0, "NMAX" }, 10391 { "tune", SQLITE_TESTCTRL_TUNE, 1, "ID VALUE" }, 10392 }; 10393 int testctrl = -1; 10394 int iCtrl = -1; 10395 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */ 10396 int isOk = 0; 10397 int i, n2; 10398 const char *zCmd = 0; 10399 10400 open_db(p, 0); 10401 zCmd = nArg>=2 ? azArg[1] : "help"; 10402 10403 /* The argument can optionally begin with "-" or "--" */ 10404 if( zCmd[0]=='-' && zCmd[1] ){ 10405 zCmd++; 10406 if( zCmd[0]=='-' && zCmd[1] ) zCmd++; 10407 } 10408 10409 /* --help lists all test-controls */ 10410 if( cli_strcmp(zCmd,"help")==0 ){ 10411 utf8_printf(p->out, "Available test-controls:\n"); 10412 for(i=0; i<ArraySize(aCtrl); i++){ 10413 utf8_printf(p->out, " .testctrl %s %s\n", 10414 aCtrl[i].zCtrlName, aCtrl[i].zUsage); 10415 } 10416 rc = 1; 10417 goto meta_command_exit; 10418 } 10419 10420 /* convert testctrl text option to value. allow any unique prefix 10421 ** of the option name, or a numerical value. */ 10422 n2 = strlen30(zCmd); 10423 for(i=0; i<ArraySize(aCtrl); i++){ 10424 if( cli_strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){ 10425 if( testctrl<0 ){ 10426 testctrl = aCtrl[i].ctrlCode; 10427 iCtrl = i; 10428 }else{ 10429 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n" 10430 "Use \".testctrl --help\" for help\n", zCmd); 10431 rc = 1; 10432 goto meta_command_exit; 10433 } 10434 } 10435 } 10436 if( testctrl<0 ){ 10437 utf8_printf(stderr,"Error: unknown test-control: %s\n" 10438 "Use \".testctrl --help\" for help\n", zCmd); 10439 }else if( aCtrl[iCtrl].unSafe && p->bSafeMode ){ 10440 utf8_printf(stderr, 10441 "line %d: \".testctrl %s\" may not be used in safe mode\n", 10442 p->lineno, aCtrl[iCtrl].zCtrlName); 10443 exit(1); 10444 }else{ 10445 switch(testctrl){ 10446 10447 /* sqlite3_test_control(int, db, int) */ 10448 case SQLITE_TESTCTRL_OPTIMIZATIONS: 10449 if( nArg==3 ){ 10450 unsigned int opt = (unsigned int)strtol(azArg[2], 0, 0); 10451 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10452 isOk = 3; 10453 } 10454 break; 10455 10456 /* sqlite3_test_control(int) */ 10457 case SQLITE_TESTCTRL_PRNG_SAVE: 10458 case SQLITE_TESTCTRL_PRNG_RESTORE: 10459 case SQLITE_TESTCTRL_BYTEORDER: 10460 if( nArg==2 ){ 10461 rc2 = sqlite3_test_control(testctrl); 10462 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3; 10463 } 10464 break; 10465 10466 /* sqlite3_test_control(int, uint) */ 10467 case SQLITE_TESTCTRL_PENDING_BYTE: 10468 if( nArg==3 ){ 10469 unsigned int opt = (unsigned int)integerValue(azArg[2]); 10470 rc2 = sqlite3_test_control(testctrl, opt); 10471 isOk = 3; 10472 } 10473 break; 10474 10475 /* sqlite3_test_control(int, int, sqlite3*) */ 10476 case SQLITE_TESTCTRL_PRNG_SEED: 10477 if( nArg==3 || nArg==4 ){ 10478 int ii = (int)integerValue(azArg[2]); 10479 sqlite3 *db; 10480 if( ii==0 && cli_strcmp(azArg[2],"random")==0 ){ 10481 sqlite3_randomness(sizeof(ii),&ii); 10482 printf("-- random seed: %d\n", ii); 10483 } 10484 if( nArg==3 ){ 10485 db = 0; 10486 }else{ 10487 db = p->db; 10488 /* Make sure the schema has been loaded */ 10489 sqlite3_table_column_metadata(db, 0, "x", 0, 0, 0, 0, 0, 0); 10490 } 10491 rc2 = sqlite3_test_control(testctrl, ii, db); 10492 isOk = 3; 10493 } 10494 break; 10495 10496 /* sqlite3_test_control(int, int) */ 10497 case SQLITE_TESTCTRL_ASSERT: 10498 case SQLITE_TESTCTRL_ALWAYS: 10499 if( nArg==3 ){ 10500 int opt = booleanValue(azArg[2]); 10501 rc2 = sqlite3_test_control(testctrl, opt); 10502 isOk = 1; 10503 } 10504 break; 10505 10506 /* sqlite3_test_control(int, int) */ 10507 case SQLITE_TESTCTRL_LOCALTIME_FAULT: 10508 case SQLITE_TESTCTRL_NEVER_CORRUPT: 10509 if( nArg==3 ){ 10510 int opt = booleanValue(azArg[2]); 10511 rc2 = sqlite3_test_control(testctrl, opt); 10512 isOk = 3; 10513 } 10514 break; 10515 10516 /* sqlite3_test_control(sqlite3*) */ 10517 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: 10518 rc2 = sqlite3_test_control(testctrl, p->db); 10519 isOk = 3; 10520 break; 10521 10522 case SQLITE_TESTCTRL_IMPOSTER: 10523 if( nArg==5 ){ 10524 rc2 = sqlite3_test_control(testctrl, p->db, 10525 azArg[2], 10526 integerValue(azArg[3]), 10527 integerValue(azArg[4])); 10528 isOk = 3; 10529 } 10530 break; 10531 10532 case SQLITE_TESTCTRL_SEEK_COUNT: { 10533 u64 x = 0; 10534 rc2 = sqlite3_test_control(testctrl, p->db, &x); 10535 utf8_printf(p->out, "%llu\n", x); 10536 isOk = 3; 10537 break; 10538 } 10539 10540#ifdef YYCOVERAGE 10541 case SQLITE_TESTCTRL_PARSER_COVERAGE: { 10542 if( nArg==2 ){ 10543 sqlite3_test_control(testctrl, p->out); 10544 isOk = 3; 10545 } 10546 break; 10547 } 10548#endif 10549#ifdef SQLITE_DEBUG 10550 case SQLITE_TESTCTRL_TUNE: { 10551 if( nArg==4 ){ 10552 int id = (int)integerValue(azArg[2]); 10553 int val = (int)integerValue(azArg[3]); 10554 sqlite3_test_control(testctrl, id, &val); 10555 isOk = 3; 10556 }else if( nArg==3 ){ 10557 int id = (int)integerValue(azArg[2]); 10558 sqlite3_test_control(testctrl, -id, &rc2); 10559 isOk = 1; 10560 }else if( nArg==2 ){ 10561 int id = 1; 10562 while(1){ 10563 int val = 0; 10564 rc2 = sqlite3_test_control(testctrl, -id, &val); 10565 if( rc2!=SQLITE_OK ) break; 10566 if( id>1 ) utf8_printf(p->out, " "); 10567 utf8_printf(p->out, "%d: %d", id, val); 10568 id++; 10569 } 10570 if( id>1 ) utf8_printf(p->out, "\n"); 10571 isOk = 3; 10572 } 10573 break; 10574 } 10575#endif 10576 case SQLITE_TESTCTRL_SORTER_MMAP: 10577 if( nArg==3 ){ 10578 int opt = (unsigned int)integerValue(azArg[2]); 10579 rc2 = sqlite3_test_control(testctrl, p->db, opt); 10580 isOk = 3; 10581 } 10582 break; 10583 } 10584 } 10585 if( isOk==0 && iCtrl>=0 ){ 10586 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd,aCtrl[iCtrl].zUsage); 10587 rc = 1; 10588 }else if( isOk==1 ){ 10589 raw_printf(p->out, "%d\n", rc2); 10590 }else if( isOk==2 ){ 10591 raw_printf(p->out, "0x%08x\n", rc2); 10592 } 10593 }else 10594#endif /* !defined(SQLITE_UNTESTABLE) */ 10595 10596 if( c=='t' && n>4 && cli_strncmp(azArg[0], "timeout", n)==0 ){ 10597 open_db(p, 0); 10598 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); 10599 }else 10600 10601 if( c=='t' && n>=5 && cli_strncmp(azArg[0], "timer", n)==0 ){ 10602 if( nArg==2 ){ 10603 enableTimer = booleanValue(azArg[1]); 10604 if( enableTimer && !HAS_TIMER ){ 10605 raw_printf(stderr, "Error: timer not available on this system.\n"); 10606 enableTimer = 0; 10607 } 10608 }else{ 10609 raw_printf(stderr, "Usage: .timer on|off\n"); 10610 rc = 1; 10611 } 10612 }else 10613 10614#ifndef SQLITE_OMIT_TRACE 10615 if( c=='t' && cli_strncmp(azArg[0], "trace", n)==0 ){ 10616 int mType = 0; 10617 int jj; 10618 open_db(p, 0); 10619 for(jj=1; jj<nArg; jj++){ 10620 const char *z = azArg[jj]; 10621 if( z[0]=='-' ){ 10622 if( optionMatch(z, "expanded") ){ 10623 p->eTraceType = SHELL_TRACE_EXPANDED; 10624 } 10625#ifdef SQLITE_ENABLE_NORMALIZE 10626 else if( optionMatch(z, "normalized") ){ 10627 p->eTraceType = SHELL_TRACE_NORMALIZED; 10628 } 10629#endif 10630 else if( optionMatch(z, "plain") ){ 10631 p->eTraceType = SHELL_TRACE_PLAIN; 10632 } 10633 else if( optionMatch(z, "profile") ){ 10634 mType |= SQLITE_TRACE_PROFILE; 10635 } 10636 else if( optionMatch(z, "row") ){ 10637 mType |= SQLITE_TRACE_ROW; 10638 } 10639 else if( optionMatch(z, "stmt") ){ 10640 mType |= SQLITE_TRACE_STMT; 10641 } 10642 else if( optionMatch(z, "close") ){ 10643 mType |= SQLITE_TRACE_CLOSE; 10644 } 10645 else { 10646 raw_printf(stderr, "Unknown option \"%s\" on \".trace\"\n", z); 10647 rc = 1; 10648 goto meta_command_exit; 10649 } 10650 }else{ 10651 output_file_close(p->traceOut); 10652 p->traceOut = output_file_open(azArg[1], 0); 10653 } 10654 } 10655 if( p->traceOut==0 ){ 10656 sqlite3_trace_v2(p->db, 0, 0, 0); 10657 }else{ 10658 if( mType==0 ) mType = SQLITE_TRACE_STMT; 10659 sqlite3_trace_v2(p->db, mType, sql_trace_callback, p); 10660 } 10661 }else 10662#endif /* !defined(SQLITE_OMIT_TRACE) */ 10663 10664#if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_VIRTUALTABLE) 10665 if( c=='u' && cli_strncmp(azArg[0], "unmodule", n)==0 ){ 10666 int ii; 10667 int lenOpt; 10668 char *zOpt; 10669 if( nArg<2 ){ 10670 raw_printf(stderr, "Usage: .unmodule [--allexcept] NAME ...\n"); 10671 rc = 1; 10672 goto meta_command_exit; 10673 } 10674 open_db(p, 0); 10675 zOpt = azArg[1]; 10676 if( zOpt[0]=='-' && zOpt[1]=='-' && zOpt[2]!=0 ) zOpt++; 10677 lenOpt = (int)strlen(zOpt); 10678 if( lenOpt>=3 && cli_strncmp(zOpt, "-allexcept",lenOpt)==0 ){ 10679 assert( azArg[nArg]==0 ); 10680 sqlite3_drop_modules(p->db, nArg>2 ? (const char**)(azArg+2) : 0); 10681 }else{ 10682 for(ii=1; ii<nArg; ii++){ 10683 sqlite3_create_module(p->db, azArg[ii], 0, 0); 10684 } 10685 } 10686 }else 10687#endif 10688 10689#if SQLITE_USER_AUTHENTICATION 10690 if( c=='u' && cli_strncmp(azArg[0], "user", n)==0 ){ 10691 if( nArg<2 ){ 10692 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); 10693 rc = 1; 10694 goto meta_command_exit; 10695 } 10696 open_db(p, 0); 10697 if( cli_strcmp(azArg[1],"login")==0 ){ 10698 if( nArg!=4 ){ 10699 raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); 10700 rc = 1; 10701 goto meta_command_exit; 10702 } 10703 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], 10704 strlen30(azArg[3])); 10705 if( rc ){ 10706 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); 10707 rc = 1; 10708 } 10709 }else if( cli_strcmp(azArg[1],"add")==0 ){ 10710 if( nArg!=5 ){ 10711 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); 10712 rc = 1; 10713 goto meta_command_exit; 10714 } 10715 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10716 booleanValue(azArg[4])); 10717 if( rc ){ 10718 raw_printf(stderr, "User-Add failed: %d\n", rc); 10719 rc = 1; 10720 } 10721 }else if( cli_strcmp(azArg[1],"edit")==0 ){ 10722 if( nArg!=5 ){ 10723 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); 10724 rc = 1; 10725 goto meta_command_exit; 10726 } 10727 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]), 10728 booleanValue(azArg[4])); 10729 if( rc ){ 10730 raw_printf(stderr, "User-Edit failed: %d\n", rc); 10731 rc = 1; 10732 } 10733 }else if( cli_strcmp(azArg[1],"delete")==0 ){ 10734 if( nArg!=3 ){ 10735 raw_printf(stderr, "Usage: .user delete USER\n"); 10736 rc = 1; 10737 goto meta_command_exit; 10738 } 10739 rc = sqlite3_user_delete(p->db, azArg[2]); 10740 if( rc ){ 10741 raw_printf(stderr, "User-Delete failed: %d\n", rc); 10742 rc = 1; 10743 } 10744 }else{ 10745 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); 10746 rc = 1; 10747 goto meta_command_exit; 10748 } 10749 }else 10750#endif /* SQLITE_USER_AUTHENTICATION */ 10751 10752 if( c=='v' && cli_strncmp(azArg[0], "version", n)==0 ){ 10753 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, 10754 sqlite3_libversion(), sqlite3_sourceid()); 10755#if SQLITE_HAVE_ZLIB 10756 utf8_printf(p->out, "zlib version %s\n", zlibVersion()); 10757#endif 10758#define CTIMEOPT_VAL_(opt) #opt 10759#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt) 10760#if defined(__clang__) && defined(__clang_major__) 10761 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "." 10762 CTIMEOPT_VAL(__clang_minor__) "." 10763 CTIMEOPT_VAL(__clang_patchlevel__) "\n"); 10764#elif defined(_MSC_VER) 10765 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n"); 10766#elif defined(__GNUC__) && defined(__VERSION__) 10767 utf8_printf(p->out, "gcc-" __VERSION__ "\n"); 10768#endif 10769 }else 10770 10771 if( c=='v' && cli_strncmp(azArg[0], "vfsinfo", n)==0 ){ 10772 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10773 sqlite3_vfs *pVfs = 0; 10774 if( p->db ){ 10775 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); 10776 if( pVfs ){ 10777 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); 10778 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10779 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10780 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10781 } 10782 } 10783 }else 10784 10785 if( c=='v' && cli_strncmp(azArg[0], "vfslist", n)==0 ){ 10786 sqlite3_vfs *pVfs; 10787 sqlite3_vfs *pCurrent = 0; 10788 if( p->db ){ 10789 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); 10790 } 10791 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ 10792 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, 10793 pVfs==pCurrent ? " <--- CURRENT" : ""); 10794 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); 10795 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); 10796 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); 10797 if( pVfs->pNext ){ 10798 raw_printf(p->out, "-----------------------------------\n"); 10799 } 10800 } 10801 }else 10802 10803 if( c=='v' && cli_strncmp(azArg[0], "vfsname", n)==0 ){ 10804 const char *zDbName = nArg==2 ? azArg[1] : "main"; 10805 char *zVfsName = 0; 10806 if( p->db ){ 10807 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); 10808 if( zVfsName ){ 10809 utf8_printf(p->out, "%s\n", zVfsName); 10810 sqlite3_free(zVfsName); 10811 } 10812 } 10813 }else 10814 10815 if( c=='w' && cli_strncmp(azArg[0], "wheretrace", n)==0 ){ 10816 unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff; 10817 sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x); 10818 }else 10819 10820 if( c=='w' && cli_strncmp(azArg[0], "width", n)==0 ){ 10821 int j; 10822 assert( nArg<=ArraySize(azArg) ); 10823 p->nWidth = nArg-1; 10824 p->colWidth = realloc(p->colWidth, (p->nWidth+1)*sizeof(int)*2); 10825 if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory(); 10826 if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth]; 10827 for(j=1; j<nArg; j++){ 10828 p->colWidth[j-1] = (int)integerValue(azArg[j]); 10829 } 10830 }else 10831 10832 { 10833 utf8_printf(stderr, "Error: unknown command or invalid arguments: " 10834 " \"%s\". Enter \".help\" for help\n", azArg[0]); 10835 rc = 1; 10836 } 10837 10838meta_command_exit: 10839 if( p->outCount ){ 10840 p->outCount--; 10841 if( p->outCount==0 ) output_reset(p); 10842 } 10843 p->bSafeMode = p->bSafeModePersist; 10844 return rc; 10845} 10846 10847/* Line scan result and intermediate states (supporting scan resumption) 10848*/ 10849#ifndef CHAR_BIT 10850# define CHAR_BIT 8 10851#endif 10852typedef enum { 10853 QSS_HasDark = 1<<CHAR_BIT, QSS_EndingSemi = 2<<CHAR_BIT, 10854 QSS_CharMask = (1<<CHAR_BIT)-1, QSS_ScanMask = 3<<CHAR_BIT, 10855 QSS_Start = 0 10856} QuickScanState; 10857#define QSS_SETV(qss, newst) ((newst) | ((qss) & QSS_ScanMask)) 10858#define QSS_INPLAIN(qss) (((qss)&QSS_CharMask)==QSS_Start) 10859#define QSS_PLAINWHITE(qss) (((qss)&~QSS_EndingSemi)==QSS_Start) 10860#define QSS_PLAINDARK(qss) (((qss)&~QSS_EndingSemi)==QSS_HasDark) 10861#define QSS_SEMITERM(qss) (((qss)&~QSS_HasDark)==QSS_EndingSemi) 10862 10863/* 10864** Scan line for classification to guide shell's handling. 10865** The scan is resumable for subsequent lines when prior 10866** return values are passed as the 2nd argument. 10867*/ 10868static QuickScanState quickscan(char *zLine, QuickScanState qss){ 10869 char cin; 10870 char cWait = (char)qss; /* intentional narrowing loss */ 10871 if( cWait==0 ){ 10872 PlainScan: 10873 assert( cWait==0 ); 10874 while( (cin = *zLine++)!=0 ){ 10875 if( IsSpace(cin) ) 10876 continue; 10877 switch (cin){ 10878 case '-': 10879 if( *zLine!='-' ) 10880 break; 10881 while((cin = *++zLine)!=0 ) 10882 if( cin=='\n') 10883 goto PlainScan; 10884 return qss; 10885 case ';': 10886 qss |= QSS_EndingSemi; 10887 continue; 10888 case '/': 10889 if( *zLine=='*' ){ 10890 ++zLine; 10891 cWait = '*'; 10892 qss = QSS_SETV(qss, cWait); 10893 goto TermScan; 10894 } 10895 break; 10896 case '[': 10897 cin = ']'; 10898 /* fall thru */ 10899 case '`': case '\'': case '"': 10900 cWait = cin; 10901 qss = QSS_HasDark | cWait; 10902 goto TermScan; 10903 default: 10904 break; 10905 } 10906 qss = (qss & ~QSS_EndingSemi) | QSS_HasDark; 10907 } 10908 }else{ 10909 TermScan: 10910 while( (cin = *zLine++)!=0 ){ 10911 if( cin==cWait ){ 10912 switch( cWait ){ 10913 case '*': 10914 if( *zLine != '/' ) 10915 continue; 10916 ++zLine; 10917 cWait = 0; 10918 qss = QSS_SETV(qss, 0); 10919 goto PlainScan; 10920 case '`': case '\'': case '"': 10921 if(*zLine==cWait){ 10922 ++zLine; 10923 continue; 10924 } 10925 /* fall thru */ 10926 case ']': 10927 cWait = 0; 10928 qss = QSS_SETV(qss, 0); 10929 goto PlainScan; 10930 default: assert(0); 10931 } 10932 } 10933 } 10934 } 10935 return qss; 10936} 10937 10938/* 10939** Return TRUE if the line typed in is an SQL command terminator other 10940** than a semi-colon. The SQL Server style "go" command is understood 10941** as is the Oracle "/". 10942*/ 10943static int line_is_command_terminator(char *zLine){ 10944 while( IsSpace(zLine[0]) ){ zLine++; }; 10945 if( zLine[0]=='/' ) 10946 zLine += 1; /* Oracle */ 10947 else if ( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' ) 10948 zLine += 2; /* SQL Server */ 10949 else 10950 return 0; 10951 return quickscan(zLine, QSS_Start)==QSS_Start; 10952} 10953 10954/* 10955** We need a default sqlite3_complete() implementation to use in case 10956** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes 10957** any arbitrary text is a complete SQL statement. This is not very 10958** user-friendly, but it does seem to work. 10959*/ 10960#ifdef SQLITE_OMIT_COMPLETE 10961#define sqlite3_complete(x) 1 10962#endif 10963 10964/* 10965** Return true if zSql is a complete SQL statement. Return false if it 10966** ends in the middle of a string literal or C-style comment. 10967*/ 10968static int line_is_complete(char *zSql, int nSql){ 10969 int rc; 10970 if( zSql==0 ) return 1; 10971 zSql[nSql] = ';'; 10972 zSql[nSql+1] = 0; 10973 rc = sqlite3_complete(zSql); 10974 zSql[nSql] = 0; 10975 return rc; 10976} 10977 10978/* 10979** Run a single line of SQL. Return the number of errors. 10980*/ 10981static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){ 10982 int rc; 10983 char *zErrMsg = 0; 10984 10985 open_db(p, 0); 10986 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql); 10987 if( p->flgProgress & SHELL_PROGRESS_RESET ) p->nProgress = 0; 10988 BEGIN_TIMER; 10989 rc = shell_exec(p, zSql, &zErrMsg); 10990 END_TIMER; 10991 if( rc || zErrMsg ){ 10992 char zPrefix[100]; 10993 const char *zErrorTail; 10994 const char *zErrorType; 10995 if( zErrMsg==0 ){ 10996 zErrorType = "Error"; 10997 zErrorTail = sqlite3_errmsg(p->db); 10998 }else if( cli_strncmp(zErrMsg, "in prepare, ",12)==0 ){ 10999 zErrorType = "Parse error"; 11000 zErrorTail = &zErrMsg[12]; 11001 }else if( cli_strncmp(zErrMsg, "stepping, ", 10)==0 ){ 11002 zErrorType = "Runtime error"; 11003 zErrorTail = &zErrMsg[10]; 11004 }else{ 11005 zErrorType = "Error"; 11006 zErrorTail = zErrMsg; 11007 } 11008 if( in!=0 || !stdin_is_interactive ){ 11009 sqlite3_snprintf(sizeof(zPrefix), zPrefix, 11010 "%s near line %d:", zErrorType, startline); 11011 }else{ 11012 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "%s:", zErrorType); 11013 } 11014 utf8_printf(stderr, "%s %s\n", zPrefix, zErrorTail); 11015 sqlite3_free(zErrMsg); 11016 zErrMsg = 0; 11017 return 1; 11018 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){ 11019 char zLineBuf[2000]; 11020 sqlite3_snprintf(sizeof(zLineBuf), zLineBuf, 11021 "changes: %lld total_changes: %lld", 11022 sqlite3_changes64(p->db), sqlite3_total_changes64(p->db)); 11023 raw_printf(p->out, "%s\n", zLineBuf); 11024 } 11025 return 0; 11026} 11027 11028static void echo_group_input(ShellState *p, const char *zDo){ 11029 if( ShellHasFlag(p, SHFLG_Echo) ) utf8_printf(p->out, "%s\n", zDo); 11030} 11031 11032#ifdef SQLITE_SHELL_FIDDLE 11033/* 11034** Alternate one_input_line() impl for wasm mode. This is not in the primary impl 11035** because we need the global shellState and cannot access it from that function 11036** without moving lots of code around (creating a larger/messier diff). 11037*/ 11038static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ 11039 /* Parse the next line from shellState.wasm.zInput. */ 11040 const char *zBegin = shellState.wasm.zPos; 11041 const char *z = zBegin; 11042 char *zLine = 0; 11043 i64 nZ = 0; 11044 11045 UNUSED_PARAMETER(in); 11046 UNUSED_PARAMETER(isContinuation); 11047 if(!z || !*z){ 11048 return 0; 11049 } 11050 while(*z && isspace(*z)) ++z; 11051 zBegin = z; 11052 for(; *z && '\n'!=*z; ++nZ, ++z){} 11053 if(nZ>0 && '\r'==zBegin[nZ-1]){ 11054 --nZ; 11055 } 11056 shellState.wasm.zPos = z; 11057 zLine = realloc(zPrior, nZ+1); 11058 shell_check_oom(zLine); 11059 memcpy(zLine, zBegin, nZ); 11060 zLine[nZ] = 0; 11061 return zLine; 11062} 11063#endif /* SQLITE_SHELL_FIDDLE */ 11064 11065/* 11066** Read input from *in and process it. If *in==0 then input 11067** is interactive - the user is typing it it. Otherwise, input 11068** is coming from a file or device. A prompt is issued and history 11069** is saved only if input is interactive. An interrupt signal will 11070** cause this routine to exit immediately, unless input is interactive. 11071** 11072** Return the number of errors. 11073*/ 11074static int process_input(ShellState *p){ 11075 char *zLine = 0; /* A single input line */ 11076 char *zSql = 0; /* Accumulated SQL text */ 11077 i64 nLine; /* Length of current line */ 11078 i64 nSql = 0; /* Bytes of zSql[] used */ 11079 i64 nAlloc = 0; /* Allocated zSql[] space */ 11080 int rc; /* Error code */ 11081 int errCnt = 0; /* Number of errors seen */ 11082 i64 startline = 0; /* Line number for start of current input */ 11083 QuickScanState qss = QSS_Start; /* Accumulated line status (so far) */ 11084 11085 if( p->inputNesting==MAX_INPUT_NESTING ){ 11086 /* This will be more informative in a later version. */ 11087 utf8_printf(stderr,"Input nesting limit (%d) reached at line %d." 11088 " Check recursion.\n", MAX_INPUT_NESTING, p->lineno); 11089 return 1; 11090 } 11091 ++p->inputNesting; 11092 p->lineno = 0; 11093 while( errCnt==0 || !bail_on_error || (p->in==0 && stdin_is_interactive) ){ 11094 fflush(p->out); 11095 zLine = one_input_line(p->in, zLine, nSql>0); 11096 if( zLine==0 ){ 11097 /* End of input */ 11098 if( p->in==0 && stdin_is_interactive ) printf("\n"); 11099 break; 11100 } 11101 if( seenInterrupt ){ 11102 if( p->in!=0 ) break; 11103 seenInterrupt = 0; 11104 } 11105 p->lineno++; 11106 if( QSS_INPLAIN(qss) 11107 && line_is_command_terminator(zLine) 11108 && line_is_complete(zSql, nSql) ){ 11109 memcpy(zLine,";",2); 11110 } 11111 qss = quickscan(zLine, qss); 11112 if( QSS_PLAINWHITE(qss) && nSql==0 ){ 11113 /* Just swallow single-line whitespace */ 11114 echo_group_input(p, zLine); 11115 qss = QSS_Start; 11116 continue; 11117 } 11118 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){ 11119 echo_group_input(p, zLine); 11120 if( zLine[0]=='.' ){ 11121 rc = do_meta_command(zLine, p); 11122 if( rc==2 ){ /* exit requested */ 11123 break; 11124 }else if( rc ){ 11125 errCnt++; 11126 } 11127 } 11128 qss = QSS_Start; 11129 continue; 11130 } 11131 /* No single-line dispositions remain; accumulate line(s). */ 11132 nLine = strlen(zLine); 11133 if( nSql+nLine+2>=nAlloc ){ 11134 /* Grow buffer by half-again increments when big. */ 11135 nAlloc = nSql+(nSql>>1)+nLine+100; 11136 zSql = realloc(zSql, nAlloc); 11137 shell_check_oom(zSql); 11138 } 11139 if( nSql==0 ){ 11140 i64 i; 11141 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} 11142 assert( nAlloc>0 && zSql!=0 ); 11143 memcpy(zSql, zLine+i, nLine+1-i); 11144 startline = p->lineno; 11145 nSql = nLine-i; 11146 }else{ 11147 zSql[nSql++] = '\n'; 11148 memcpy(zSql+nSql, zLine, nLine+1); 11149 nSql += nLine; 11150 } 11151 if( nSql && QSS_SEMITERM(qss) && sqlite3_complete(zSql) ){ 11152 echo_group_input(p, zSql); 11153 errCnt += runOneSqlLine(p, zSql, p->in, startline); 11154 nSql = 0; 11155 if( p->outCount ){ 11156 output_reset(p); 11157 p->outCount = 0; 11158 }else{ 11159 clearTempFile(p); 11160 } 11161 p->bSafeMode = p->bSafeModePersist; 11162 qss = QSS_Start; 11163 }else if( nSql && QSS_PLAINWHITE(qss) ){ 11164 echo_group_input(p, zSql); 11165 nSql = 0; 11166 qss = QSS_Start; 11167 } 11168 } 11169 if( nSql ){ 11170 /* This may be incomplete. Let the SQL parser deal with that. */ 11171 echo_group_input(p, zSql); 11172 errCnt += runOneSqlLine(p, zSql, p->in, startline); 11173 } 11174 free(zSql); 11175 free(zLine); 11176 --p->inputNesting; 11177 return errCnt>0; 11178} 11179 11180/* 11181** Return a pathname which is the user's home directory. A 11182** 0 return indicates an error of some kind. 11183*/ 11184static char *find_home_dir(int clearFlag){ 11185 static char *home_dir = NULL; 11186 if( clearFlag ){ 11187 free(home_dir); 11188 home_dir = 0; 11189 return 0; 11190 } 11191 if( home_dir ) return home_dir; 11192 11193#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ 11194 && !defined(__RTP__) && !defined(_WRS_KERNEL) 11195 { 11196 struct passwd *pwent; 11197 uid_t uid = getuid(); 11198 if( (pwent=getpwuid(uid)) != NULL) { 11199 home_dir = pwent->pw_dir; 11200 } 11201 } 11202#endif 11203 11204#if defined(_WIN32_WCE) 11205 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() 11206 */ 11207 home_dir = "/"; 11208#else 11209 11210#if defined(_WIN32) || defined(WIN32) 11211 if (!home_dir) { 11212 home_dir = getenv("USERPROFILE"); 11213 } 11214#endif 11215 11216 if (!home_dir) { 11217 home_dir = getenv("HOME"); 11218 } 11219 11220#if defined(_WIN32) || defined(WIN32) 11221 if (!home_dir) { 11222 char *zDrive, *zPath; 11223 int n; 11224 zDrive = getenv("HOMEDRIVE"); 11225 zPath = getenv("HOMEPATH"); 11226 if( zDrive && zPath ){ 11227 n = strlen30(zDrive) + strlen30(zPath) + 1; 11228 home_dir = malloc( n ); 11229 if( home_dir==0 ) return 0; 11230 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); 11231 return home_dir; 11232 } 11233 home_dir = "c:\\"; 11234 } 11235#endif 11236 11237#endif /* !_WIN32_WCE */ 11238 11239 if( home_dir ){ 11240 i64 n = strlen(home_dir) + 1; 11241 char *z = malloc( n ); 11242 if( z ) memcpy(z, home_dir, n); 11243 home_dir = z; 11244 } 11245 11246 return home_dir; 11247} 11248 11249/* 11250** Read input from the file given by sqliterc_override. Or if that 11251** parameter is NULL, take input from ~/.sqliterc 11252** 11253** Returns the number of errors. 11254*/ 11255static void process_sqliterc( 11256 ShellState *p, /* Configuration data */ 11257 const char *sqliterc_override /* Name of config file. NULL to use default */ 11258){ 11259 char *home_dir = NULL; 11260 const char *sqliterc = sqliterc_override; 11261 char *zBuf = 0; 11262 FILE *inSaved = p->in; 11263 int savedLineno = p->lineno; 11264 11265 if (sqliterc == NULL) { 11266 home_dir = find_home_dir(0); 11267 if( home_dir==0 ){ 11268 raw_printf(stderr, "-- warning: cannot find home directory;" 11269 " cannot read ~/.sqliterc\n"); 11270 return; 11271 } 11272 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); 11273 shell_check_oom(zBuf); 11274 sqliterc = zBuf; 11275 } 11276 p->in = fopen(sqliterc,"rb"); 11277 if( p->in ){ 11278 if( stdin_is_interactive ){ 11279 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); 11280 } 11281 if( process_input(p) && bail_on_error ) exit(1); 11282 fclose(p->in); 11283 }else if( sqliterc_override!=0 ){ 11284 utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc); 11285 if( bail_on_error ) exit(1); 11286 } 11287 p->in = inSaved; 11288 p->lineno = savedLineno; 11289 sqlite3_free(zBuf); 11290} 11291 11292/* 11293** Show available command line options 11294*/ 11295static const char zOptions[] = 11296#if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE) 11297 " -A ARGS... run \".archive ARGS\" and exit\n" 11298#endif 11299 " -append append the database to the end of the file\n" 11300 " -ascii set output mode to 'ascii'\n" 11301 " -bail stop after hitting an error\n" 11302 " -batch force batch I/O\n" 11303 " -box set output mode to 'box'\n" 11304 " -column set output mode to 'column'\n" 11305 " -cmd COMMAND run \"COMMAND\" before reading stdin\n" 11306 " -csv set output mode to 'csv'\n" 11307#if !defined(SQLITE_OMIT_DESERIALIZE) 11308 " -deserialize open the database using sqlite3_deserialize()\n" 11309#endif 11310 " -echo print inputs before execution\n" 11311 " -init FILENAME read/process named file\n" 11312 " -[no]header turn headers on or off\n" 11313#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11314 " -heap SIZE Size of heap for memsys3 or memsys5\n" 11315#endif 11316 " -help show this message\n" 11317 " -html set output mode to HTML\n" 11318 " -interactive force interactive I/O\n" 11319 " -json set output mode to 'json'\n" 11320 " -line set output mode to 'line'\n" 11321 " -list set output mode to 'list'\n" 11322 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" 11323 " -markdown set output mode to 'markdown'\n" 11324#if !defined(SQLITE_OMIT_DESERIALIZE) 11325 " -maxsize N maximum size for a --deserialize database\n" 11326#endif 11327 " -memtrace trace all memory allocations and deallocations\n" 11328 " -mmap N default mmap size set to N\n" 11329#ifdef SQLITE_ENABLE_MULTIPLEX 11330 " -multiplex enable the multiplexor VFS\n" 11331#endif 11332 " -newline SEP set output row separator. Default: '\\n'\n" 11333 " -nofollow refuse to open symbolic links to database files\n" 11334 " -nonce STRING set the safe-mode escape nonce\n" 11335 " -nullvalue TEXT set text string for NULL values. Default ''\n" 11336 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" 11337 " -quote set output mode to 'quote'\n" 11338 " -readonly open the database read-only\n" 11339 " -safe enable safe-mode\n" 11340 " -separator SEP set output column separator. Default: '|'\n" 11341#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11342 " -sorterref SIZE sorter references threshold size\n" 11343#endif 11344 " -stats print memory stats before each finalize\n" 11345 " -table set output mode to 'table'\n" 11346 " -tabs set output mode to 'tabs'\n" 11347 " -version show SQLite version\n" 11348 " -vfs NAME use NAME as the default VFS\n" 11349#ifdef SQLITE_ENABLE_VFSTRACE 11350 " -vfstrace enable tracing of all VFS calls\n" 11351#endif 11352#ifdef SQLITE_HAVE_ZLIB 11353 " -zip open the file as a ZIP Archive\n" 11354#endif 11355; 11356static void usage(int showDetail){ 11357 utf8_printf(stderr, 11358 "Usage: %s [OPTIONS] FILENAME [SQL]\n" 11359 "FILENAME is the name of an SQLite database. A new database is created\n" 11360 "if the file does not previously exist.\n", Argv0); 11361 if( showDetail ){ 11362 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); 11363 }else{ 11364 raw_printf(stderr, "Use the -help option for additional information\n"); 11365 } 11366 exit(1); 11367} 11368 11369/* 11370** Internal check: Verify that the SQLite is uninitialized. Print a 11371** error message if it is initialized. 11372*/ 11373static void verify_uninitialized(void){ 11374 if( sqlite3_config(-1)==SQLITE_MISUSE ){ 11375 utf8_printf(stdout, "WARNING: attempt to configure SQLite after" 11376 " initialization.\n"); 11377 } 11378} 11379 11380/* 11381** Initialize the state information in data 11382*/ 11383static void main_init(ShellState *data) { 11384 memset(data, 0, sizeof(*data)); 11385 data->normalMode = data->cMode = data->mode = MODE_List; 11386 data->autoExplain = 1; 11387 data->pAuxDb = &data->aAuxDb[0]; 11388 memcpy(data->colSeparator,SEP_Column, 2); 11389 memcpy(data->rowSeparator,SEP_Row, 2); 11390 data->showHeader = 0; 11391 data->shellFlgs = SHFLG_Lookaside; 11392 verify_uninitialized(); 11393 sqlite3_config(SQLITE_CONFIG_URI, 1); 11394 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); 11395 sqlite3_config(SQLITE_CONFIG_MULTITHREAD); 11396 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); 11397 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); 11398} 11399 11400/* 11401** Output text to the console in a font that attracts extra attention. 11402*/ 11403#ifdef _WIN32 11404static void printBold(const char *zText){ 11405#if !SQLITE_OS_WINRT 11406 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 11407 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; 11408 GetConsoleScreenBufferInfo(out, &defaultScreenInfo); 11409 SetConsoleTextAttribute(out, 11410 FOREGROUND_RED|FOREGROUND_INTENSITY 11411 ); 11412#endif 11413 printf("%s", zText); 11414#if !SQLITE_OS_WINRT 11415 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); 11416#endif 11417} 11418#else 11419static void printBold(const char *zText){ 11420 printf("\033[1m%s\033[0m", zText); 11421} 11422#endif 11423 11424/* 11425** Get the argument to an --option. Throw an error and die if no argument 11426** is available. 11427*/ 11428static char *cmdline_option_value(int argc, char **argv, int i){ 11429 if( i==argc ){ 11430 utf8_printf(stderr, "%s: Error: missing argument to %s\n", 11431 argv[0], argv[argc-1]); 11432 exit(1); 11433 } 11434 return argv[i]; 11435} 11436 11437#ifndef SQLITE_SHELL_IS_UTF8 11438# if (defined(_WIN32) || defined(WIN32)) \ 11439 && (defined(_MSC_VER) || (defined(UNICODE) && defined(__GNUC__))) 11440# define SQLITE_SHELL_IS_UTF8 (0) 11441# else 11442# define SQLITE_SHELL_IS_UTF8 (1) 11443# endif 11444#endif 11445 11446#ifdef SQLITE_SHELL_FIDDLE 11447# define main fiddle_main 11448#endif 11449 11450#if SQLITE_SHELL_IS_UTF8 11451int SQLITE_CDECL main(int argc, char **argv){ 11452#else 11453int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ 11454 char **argv; 11455#endif 11456#ifdef SQLITE_DEBUG 11457 sqlite3_int64 mem_main_enter = sqlite3_memory_used(); 11458#endif 11459 char *zErrMsg = 0; 11460#ifdef SQLITE_SHELL_FIDDLE 11461# define data shellState 11462#else 11463 ShellState data; 11464#endif 11465 const char *zInitFile = 0; 11466 int i; 11467 int rc = 0; 11468 int warnInmemoryDb = 0; 11469 int readStdin = 1; 11470 int nCmd = 0; 11471 char **azCmd = 0; 11472 const char *zVfs = 0; /* Value of -vfs command-line option */ 11473#if !SQLITE_SHELL_IS_UTF8 11474 char **argvToFree = 0; 11475 int argcToFree = 0; 11476#endif 11477 11478 setBinaryMode(stdin, 0); 11479 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ 11480#ifdef SQLITE_SHELL_FIDDLE 11481 stdin_is_interactive = 0; 11482 stdout_is_console = 1; 11483 data.wasm.zDefaultDbName = "/fiddle.sqlite3"; 11484#else 11485 stdin_is_interactive = isatty(0); 11486 stdout_is_console = isatty(1); 11487#endif 11488 11489#if !defined(_WIN32_WCE) 11490 if( getenv("SQLITE_DEBUG_BREAK") ){ 11491 if( isatty(0) && isatty(2) ){ 11492 fprintf(stderr, 11493 "attach debugger to process %d and press any key to continue.\n", 11494 GETPID()); 11495 fgetc(stdin); 11496 }else{ 11497#if defined(_WIN32) || defined(WIN32) 11498#if SQLITE_OS_WINRT 11499 __debugbreak(); 11500#else 11501 DebugBreak(); 11502#endif 11503#elif defined(SIGTRAP) 11504 raise(SIGTRAP); 11505#endif 11506 } 11507 } 11508#endif 11509 11510#if USE_SYSTEM_SQLITE+0!=1 11511 if( cli_strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){ 11512 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", 11513 sqlite3_sourceid(), SQLITE_SOURCE_ID); 11514 exit(1); 11515 } 11516#endif 11517 main_init(&data); 11518 11519 /* On Windows, we must translate command-line arguments into UTF-8. 11520 ** The SQLite memory allocator subsystem has to be enabled in order to 11521 ** do this. But we want to run an sqlite3_shutdown() afterwards so that 11522 ** subsequent sqlite3_config() calls will work. So copy all results into 11523 ** memory that does not come from the SQLite memory allocator. 11524 */ 11525#if !SQLITE_SHELL_IS_UTF8 11526 sqlite3_initialize(); 11527 argvToFree = malloc(sizeof(argv[0])*argc*2); 11528 shell_check_oom(argvToFree); 11529 argcToFree = argc; 11530 argv = argvToFree + argc; 11531 for(i=0; i<argc; i++){ 11532 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]); 11533 i64 n; 11534 shell_check_oom(z); 11535 n = strlen(z); 11536 argv[i] = malloc( n+1 ); 11537 shell_check_oom(argv[i]); 11538 memcpy(argv[i], z, n+1); 11539 argvToFree[i] = argv[i]; 11540 sqlite3_free(z); 11541 } 11542 sqlite3_shutdown(); 11543#endif 11544 11545 assert( argc>=1 && argv && argv[0] ); 11546 Argv0 = argv[0]; 11547 11548 /* Make sure we have a valid signal handler early, before anything 11549 ** else is done. 11550 */ 11551#ifdef SIGINT 11552 signal(SIGINT, interrupt_handler); 11553#elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE) 11554 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); 11555#endif 11556 11557#ifdef SQLITE_SHELL_DBNAME_PROC 11558 { 11559 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name 11560 ** of a C-function that will provide the name of the database file. Use 11561 ** this compile-time option to embed this shell program in larger 11562 ** applications. */ 11563 extern void SQLITE_SHELL_DBNAME_PROC(const char**); 11564 SQLITE_SHELL_DBNAME_PROC(&data.pAuxDb->zDbFilename); 11565 warnInmemoryDb = 0; 11566 } 11567#endif 11568 11569 /* Do an initial pass through the command-line argument to locate 11570 ** the name of the database file, the name of the initialization file, 11571 ** the size of the alternative malloc heap, 11572 ** and the first command to execute. 11573 */ 11574 verify_uninitialized(); 11575 for(i=1; i<argc; i++){ 11576 char *z; 11577 z = argv[i]; 11578 if( z[0]!='-' ){ 11579 if( data.aAuxDb->zDbFilename==0 ){ 11580 data.aAuxDb->zDbFilename = z; 11581 }else{ 11582 /* Excesss arguments are interpreted as SQL (or dot-commands) and 11583 ** mean that nothing is read from stdin */ 11584 readStdin = 0; 11585 nCmd++; 11586 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); 11587 shell_check_oom(azCmd); 11588 azCmd[nCmd-1] = z; 11589 } 11590 } 11591 if( z[1]=='-' ) z++; 11592 if( cli_strcmp(z,"-separator")==0 11593 || cli_strcmp(z,"-nullvalue")==0 11594 || cli_strcmp(z,"-newline")==0 11595 || cli_strcmp(z,"-cmd")==0 11596 ){ 11597 (void)cmdline_option_value(argc, argv, ++i); 11598 }else if( cli_strcmp(z,"-init")==0 ){ 11599 zInitFile = cmdline_option_value(argc, argv, ++i); 11600 }else if( cli_strcmp(z,"-batch")==0 ){ 11601 /* Need to check for batch mode here to so we can avoid printing 11602 ** informational messages (like from process_sqliterc) before 11603 ** we do the actual processing of arguments later in a second pass. 11604 */ 11605 stdin_is_interactive = 0; 11606 }else if( cli_strcmp(z,"-heap")==0 ){ 11607#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) 11608 const char *zSize; 11609 sqlite3_int64 szHeap; 11610 11611 zSize = cmdline_option_value(argc, argv, ++i); 11612 szHeap = integerValue(zSize); 11613 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; 11614 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); 11615#else 11616 (void)cmdline_option_value(argc, argv, ++i); 11617#endif 11618 }else if( cli_strcmp(z,"-pagecache")==0 ){ 11619 sqlite3_int64 n, sz; 11620 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11621 if( sz>70000 ) sz = 70000; 11622 if( sz<0 ) sz = 0; 11623 n = integerValue(cmdline_option_value(argc,argv,++i)); 11624 if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){ 11625 n = 0xffffffffffffLL/sz; 11626 } 11627 sqlite3_config(SQLITE_CONFIG_PAGECACHE, 11628 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); 11629 data.shellFlgs |= SHFLG_Pagecache; 11630 }else if( cli_strcmp(z,"-lookaside")==0 ){ 11631 int n, sz; 11632 sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11633 if( sz<0 ) sz = 0; 11634 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11635 if( n<0 ) n = 0; 11636 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); 11637 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; 11638 }else if( cli_strcmp(z,"-threadsafe")==0 ){ 11639 int n; 11640 n = (int)integerValue(cmdline_option_value(argc,argv,++i)); 11641 switch( n ){ 11642 case 0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); break; 11643 case 2: sqlite3_config(SQLITE_CONFIG_MULTITHREAD); break; 11644 default: sqlite3_config(SQLITE_CONFIG_SERIALIZED); break; 11645 } 11646#ifdef SQLITE_ENABLE_VFSTRACE 11647 }else if( cli_strcmp(z,"-vfstrace")==0 ){ 11648 extern int vfstrace_register( 11649 const char *zTraceName, 11650 const char *zOldVfsName, 11651 int (*xOut)(const char*,void*), 11652 void *pOutArg, 11653 int makeDefault 11654 ); 11655 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); 11656#endif 11657#ifdef SQLITE_ENABLE_MULTIPLEX 11658 }else if( cli_strcmp(z,"-multiplex")==0 ){ 11659 extern int sqlite3_multiple_initialize(const char*,int); 11660 sqlite3_multiplex_initialize(0, 1); 11661#endif 11662 }else if( cli_strcmp(z,"-mmap")==0 ){ 11663 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11664 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); 11665#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11666 }else if( cli_strcmp(z,"-sorterref")==0 ){ 11667 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); 11668 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz); 11669#endif 11670 }else if( cli_strcmp(z,"-vfs")==0 ){ 11671 zVfs = cmdline_option_value(argc, argv, ++i); 11672#ifdef SQLITE_HAVE_ZLIB 11673 }else if( cli_strcmp(z,"-zip")==0 ){ 11674 data.openMode = SHELL_OPEN_ZIPFILE; 11675#endif 11676 }else if( cli_strcmp(z,"-append")==0 ){ 11677 data.openMode = SHELL_OPEN_APPENDVFS; 11678#ifndef SQLITE_OMIT_DESERIALIZE 11679 }else if( cli_strcmp(z,"-deserialize")==0 ){ 11680 data.openMode = SHELL_OPEN_DESERIALIZE; 11681 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){ 11682 data.szMax = integerValue(argv[++i]); 11683#endif 11684 }else if( cli_strcmp(z,"-readonly")==0 ){ 11685 data.openMode = SHELL_OPEN_READONLY; 11686 }else if( cli_strcmp(z,"-nofollow")==0 ){ 11687 data.openFlags = SQLITE_OPEN_NOFOLLOW; 11688#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11689 }else if( cli_strncmp(z, "-A",2)==0 ){ 11690 /* All remaining command-line arguments are passed to the ".archive" 11691 ** command, so ignore them */ 11692 break; 11693#endif 11694 }else if( cli_strcmp(z, "-memtrace")==0 ){ 11695 sqlite3MemTraceActivate(stderr); 11696 }else if( cli_strcmp(z,"-bail")==0 ){ 11697 bail_on_error = 1; 11698 }else if( cli_strcmp(z,"-nonce")==0 ){ 11699 free(data.zNonce); 11700 data.zNonce = strdup(argv[++i]); 11701 }else if( cli_strcmp(z,"-safe")==0 ){ 11702 /* no-op - catch this on the second pass */ 11703 } 11704 } 11705 verify_uninitialized(); 11706 11707 11708#ifdef SQLITE_SHELL_INIT_PROC 11709 { 11710 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name 11711 ** of a C-function that will perform initialization actions on SQLite that 11712 ** occur just before or after sqlite3_initialize(). Use this compile-time 11713 ** option to embed this shell program in larger applications. */ 11714 extern void SQLITE_SHELL_INIT_PROC(void); 11715 SQLITE_SHELL_INIT_PROC(); 11716 } 11717#else 11718 /* All the sqlite3_config() calls have now been made. So it is safe 11719 ** to call sqlite3_initialize() and process any command line -vfs option. */ 11720 sqlite3_initialize(); 11721#endif 11722 11723 if( zVfs ){ 11724 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs); 11725 if( pVfs ){ 11726 sqlite3_vfs_register(pVfs, 1); 11727 }else{ 11728 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); 11729 exit(1); 11730 } 11731 } 11732 11733 if( data.pAuxDb->zDbFilename==0 ){ 11734#ifndef SQLITE_OMIT_MEMORYDB 11735 data.pAuxDb->zDbFilename = ":memory:"; 11736 warnInmemoryDb = argc==1; 11737#else 11738 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); 11739 return 1; 11740#endif 11741 } 11742 data.out = stdout; 11743#ifndef SQLITE_SHELL_FIDDLE 11744 sqlite3_appendvfs_init(0,0,0); 11745#endif 11746 11747 /* Go ahead and open the database file if it already exists. If the 11748 ** file does not exist, delay opening it. This prevents empty database 11749 ** files from being created if a user mistypes the database name argument 11750 ** to the sqlite command-line tool. 11751 */ 11752 if( access(data.pAuxDb->zDbFilename, 0)==0 ){ 11753 open_db(&data, 0); 11754 } 11755 11756 /* Process the initialization file if there is one. If no -init option 11757 ** is given on the command line, look for a file named ~/.sqliterc and 11758 ** try to process it. 11759 */ 11760 process_sqliterc(&data,zInitFile); 11761 11762 /* Make a second pass through the command-line argument and set 11763 ** options. This second pass is delayed until after the initialization 11764 ** file is processed so that the command-line arguments will override 11765 ** settings in the initialization file. 11766 */ 11767 for(i=1; i<argc; i++){ 11768 char *z = argv[i]; 11769 if( z[0]!='-' ) continue; 11770 if( z[1]=='-' ){ z++; } 11771 if( cli_strcmp(z,"-init")==0 ){ 11772 i++; 11773 }else if( cli_strcmp(z,"-html")==0 ){ 11774 data.mode = MODE_Html; 11775 }else if( cli_strcmp(z,"-list")==0 ){ 11776 data.mode = MODE_List; 11777 }else if( cli_strcmp(z,"-quote")==0 ){ 11778 data.mode = MODE_Quote; 11779 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma); 11780 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11781 }else if( cli_strcmp(z,"-line")==0 ){ 11782 data.mode = MODE_Line; 11783 }else if( cli_strcmp(z,"-column")==0 ){ 11784 data.mode = MODE_Column; 11785 }else if( cli_strcmp(z,"-json")==0 ){ 11786 data.mode = MODE_Json; 11787 }else if( cli_strcmp(z,"-markdown")==0 ){ 11788 data.mode = MODE_Markdown; 11789 }else if( cli_strcmp(z,"-table")==0 ){ 11790 data.mode = MODE_Table; 11791 }else if( cli_strcmp(z,"-box")==0 ){ 11792 data.mode = MODE_Box; 11793 }else if( cli_strcmp(z,"-csv")==0 ){ 11794 data.mode = MODE_Csv; 11795 memcpy(data.colSeparator,",",2); 11796#ifdef SQLITE_HAVE_ZLIB 11797 }else if( cli_strcmp(z,"-zip")==0 ){ 11798 data.openMode = SHELL_OPEN_ZIPFILE; 11799#endif 11800 }else if( cli_strcmp(z,"-append")==0 ){ 11801 data.openMode = SHELL_OPEN_APPENDVFS; 11802#ifndef SQLITE_OMIT_DESERIALIZE 11803 }else if( cli_strcmp(z,"-deserialize")==0 ){ 11804 data.openMode = SHELL_OPEN_DESERIALIZE; 11805 }else if( cli_strcmp(z,"-maxsize")==0 && i+1<argc ){ 11806 data.szMax = integerValue(argv[++i]); 11807#endif 11808 }else if( cli_strcmp(z,"-readonly")==0 ){ 11809 data.openMode = SHELL_OPEN_READONLY; 11810 }else if( cli_strcmp(z,"-nofollow")==0 ){ 11811 data.openFlags |= SQLITE_OPEN_NOFOLLOW; 11812 }else if( cli_strcmp(z,"-ascii")==0 ){ 11813 data.mode = MODE_Ascii; 11814 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit); 11815 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record); 11816 }else if( cli_strcmp(z,"-tabs")==0 ){ 11817 data.mode = MODE_List; 11818 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab); 11819 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row); 11820 }else if( cli_strcmp(z,"-separator")==0 ){ 11821 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, 11822 "%s",cmdline_option_value(argc,argv,++i)); 11823 }else if( cli_strcmp(z,"-newline")==0 ){ 11824 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, 11825 "%s",cmdline_option_value(argc,argv,++i)); 11826 }else if( cli_strcmp(z,"-nullvalue")==0 ){ 11827 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, 11828 "%s",cmdline_option_value(argc,argv,++i)); 11829 }else if( cli_strcmp(z,"-header")==0 ){ 11830 data.showHeader = 1; 11831 ShellSetFlag(&data, SHFLG_HeaderSet); 11832 }else if( cli_strcmp(z,"-noheader")==0 ){ 11833 data.showHeader = 0; 11834 ShellSetFlag(&data, SHFLG_HeaderSet); 11835 }else if( cli_strcmp(z,"-echo")==0 ){ 11836 ShellSetFlag(&data, SHFLG_Echo); 11837 }else if( cli_strcmp(z,"-eqp")==0 ){ 11838 data.autoEQP = AUTOEQP_on; 11839 }else if( cli_strcmp(z,"-eqpfull")==0 ){ 11840 data.autoEQP = AUTOEQP_full; 11841 }else if( cli_strcmp(z,"-stats")==0 ){ 11842 data.statsOn = 1; 11843 }else if( cli_strcmp(z,"-scanstats")==0 ){ 11844 data.scanstatsOn = 1; 11845 }else if( cli_strcmp(z,"-backslash")==0 ){ 11846 /* Undocumented command-line option: -backslash 11847 ** Causes C-style backslash escapes to be evaluated in SQL statements 11848 ** prior to sending the SQL into SQLite. Useful for injecting 11849 ** crazy bytes in the middle of SQL statements for testing and debugging. 11850 */ 11851 ShellSetFlag(&data, SHFLG_Backslash); 11852 }else if( cli_strcmp(z,"-bail")==0 ){ 11853 /* No-op. The bail_on_error flag should already be set. */ 11854 }else if( cli_strcmp(z,"-version")==0 ){ 11855 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); 11856 return 0; 11857 }else if( cli_strcmp(z,"-interactive")==0 ){ 11858 stdin_is_interactive = 1; 11859 }else if( cli_strcmp(z,"-batch")==0 ){ 11860 stdin_is_interactive = 0; 11861 }else if( cli_strcmp(z,"-heap")==0 ){ 11862 i++; 11863 }else if( cli_strcmp(z,"-pagecache")==0 ){ 11864 i+=2; 11865 }else if( cli_strcmp(z,"-lookaside")==0 ){ 11866 i+=2; 11867 }else if( cli_strcmp(z,"-threadsafe")==0 ){ 11868 i+=2; 11869 }else if( cli_strcmp(z,"-nonce")==0 ){ 11870 i += 2; 11871 }else if( cli_strcmp(z,"-mmap")==0 ){ 11872 i++; 11873 }else if( cli_strcmp(z,"-memtrace")==0 ){ 11874 i++; 11875#ifdef SQLITE_ENABLE_SORTER_REFERENCES 11876 }else if( cli_strcmp(z,"-sorterref")==0 ){ 11877 i++; 11878#endif 11879 }else if( cli_strcmp(z,"-vfs")==0 ){ 11880 i++; 11881#ifdef SQLITE_ENABLE_VFSTRACE 11882 }else if( cli_strcmp(z,"-vfstrace")==0 ){ 11883 i++; 11884#endif 11885#ifdef SQLITE_ENABLE_MULTIPLEX 11886 }else if( cli_strcmp(z,"-multiplex")==0 ){ 11887 i++; 11888#endif 11889 }else if( cli_strcmp(z,"-help")==0 ){ 11890 usage(1); 11891 }else if( cli_strcmp(z,"-cmd")==0 ){ 11892 /* Run commands that follow -cmd first and separately from commands 11893 ** that simply appear on the command-line. This seems goofy. It would 11894 ** be better if all commands ran in the order that they appear. But 11895 ** we retain the goofy behavior for historical compatibility. */ 11896 if( i==argc-1 ) break; 11897 z = cmdline_option_value(argc,argv,++i); 11898 if( z[0]=='.' ){ 11899 rc = do_meta_command(z, &data); 11900 if( rc && bail_on_error ) return rc==2 ? 0 : rc; 11901 }else{ 11902 open_db(&data, 0); 11903 rc = shell_exec(&data, z, &zErrMsg); 11904 if( zErrMsg!=0 ){ 11905 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11906 if( bail_on_error ) return rc!=0 ? rc : 1; 11907 }else if( rc!=0 ){ 11908 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); 11909 if( bail_on_error ) return rc; 11910 } 11911 } 11912#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) 11913 }else if( cli_strncmp(z, "-A", 2)==0 ){ 11914 if( nCmd>0 ){ 11915 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands" 11916 " with \"%s\"\n", z); 11917 return 1; 11918 } 11919 open_db(&data, OPEN_DB_ZIPFILE); 11920 if( z[2] ){ 11921 argv[i] = &z[2]; 11922 arDotCommand(&data, 1, argv+(i-1), argc-(i-1)); 11923 }else{ 11924 arDotCommand(&data, 1, argv+i, argc-i); 11925 } 11926 readStdin = 0; 11927 break; 11928#endif 11929 }else if( cli_strcmp(z,"-safe")==0 ){ 11930 data.bSafeMode = data.bSafeModePersist = 1; 11931 }else{ 11932 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); 11933 raw_printf(stderr,"Use -help for a list of options.\n"); 11934 return 1; 11935 } 11936 data.cMode = data.mode; 11937 } 11938 11939 if( !readStdin ){ 11940 /* Run all arguments that do not begin with '-' as if they were separate 11941 ** command-line inputs, except for the argToSkip argument which contains 11942 ** the database filename. 11943 */ 11944 for(i=0; i<nCmd; i++){ 11945 if( azCmd[i][0]=='.' ){ 11946 rc = do_meta_command(azCmd[i], &data); 11947 if( rc ){ 11948 free(azCmd); 11949 return rc==2 ? 0 : rc; 11950 } 11951 }else{ 11952 open_db(&data, 0); 11953 rc = shell_exec(&data, azCmd[i], &zErrMsg); 11954 if( zErrMsg || rc ){ 11955 if( zErrMsg!=0 ){ 11956 utf8_printf(stderr,"Error: %s\n", zErrMsg); 11957 }else{ 11958 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); 11959 } 11960 sqlite3_free(zErrMsg); 11961 free(azCmd); 11962 return rc!=0 ? rc : 1; 11963 } 11964 } 11965 } 11966 }else{ 11967 /* Run commands received from standard input 11968 */ 11969 if( stdin_is_interactive ){ 11970 char *zHome; 11971 char *zHistory; 11972 int nHistory; 11973 printf( 11974 "SQLite version %s %.19s\n" /*extra-version-info*/ 11975 "Enter \".help\" for usage hints.\n", 11976 sqlite3_libversion(), sqlite3_sourceid() 11977 ); 11978 if( warnInmemoryDb ){ 11979 printf("Connected to a "); 11980 printBold("transient in-memory database"); 11981 printf(".\nUse \".open FILENAME\" to reopen on a " 11982 "persistent database.\n"); 11983 } 11984 zHistory = getenv("SQLITE_HISTORY"); 11985 if( zHistory ){ 11986 zHistory = strdup(zHistory); 11987 }else if( (zHome = find_home_dir(0))!=0 ){ 11988 nHistory = strlen30(zHome) + 20; 11989 if( (zHistory = malloc(nHistory))!=0 ){ 11990 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); 11991 } 11992 } 11993 if( zHistory ){ shell_read_history(zHistory); } 11994#if HAVE_READLINE || HAVE_EDITLINE 11995 rl_attempted_completion_function = readline_completion; 11996#elif HAVE_LINENOISE 11997 linenoiseSetCompletionCallback(linenoise_completion); 11998#endif 11999 data.in = 0; 12000 rc = process_input(&data); 12001 if( zHistory ){ 12002 shell_stifle_history(2000); 12003 shell_write_history(zHistory); 12004 free(zHistory); 12005 } 12006 }else{ 12007 data.in = stdin; 12008 rc = process_input(&data); 12009 } 12010 } 12011#ifndef SQLITE_SHELL_FIDDLE 12012 /* In WASM mode we have to leave the db state in place so that 12013 ** client code can "push" SQL into it after this call returns. */ 12014 free(azCmd); 12015 set_table_name(&data, 0); 12016 if( data.db ){ 12017 session_close_all(&data, -1); 12018 close_db(data.db); 12019 } 12020 for(i=0; i<ArraySize(data.aAuxDb); i++){ 12021 sqlite3_free(data.aAuxDb[i].zFreeOnClose); 12022 if( data.aAuxDb[i].db ){ 12023 session_close_all(&data, i); 12024 close_db(data.aAuxDb[i].db); 12025 } 12026 } 12027 find_home_dir(1); 12028 output_reset(&data); 12029 data.doXdgOpen = 0; 12030 clearTempFile(&data); 12031#if !SQLITE_SHELL_IS_UTF8 12032 for(i=0; i<argcToFree; i++) free(argvToFree[i]); 12033 free(argvToFree); 12034#endif 12035 free(data.colWidth); 12036 free(data.zNonce); 12037 /* Clear the global data structure so that valgrind will detect memory 12038 ** leaks */ 12039 memset(&data, 0, sizeof(data)); 12040#ifdef SQLITE_DEBUG 12041 if( sqlite3_memory_used()>mem_main_enter ){ 12042 utf8_printf(stderr, "Memory leaked: %u bytes\n", 12043 (unsigned int)(sqlite3_memory_used()-mem_main_enter)); 12044 } 12045#endif 12046#endif /* !SQLITE_SHELL_FIDDLE */ 12047 return rc; 12048} 12049 12050 12051#ifdef SQLITE_SHELL_FIDDLE 12052/* Only for emcc experimentation purposes. */ 12053int fiddle_experiment(int a,int b){ 12054 return a + b; 12055} 12056 12057/* 12058** Returns a pointer to the current DB handle. 12059*/ 12060sqlite3 * fiddle_db_handle(){ 12061 return globalDb; 12062} 12063 12064/* 12065** Returns a pointer to the given DB name's VFS. If zDbName is 0 then 12066** "main" is assumed. Returns 0 if no db with the given name is 12067** open. 12068*/ 12069sqlite3_vfs * fiddle_db_vfs(const char *zDbName){ 12070 sqlite3_vfs * pVfs = 0; 12071 if(globalDb){ 12072 sqlite3_file_control(globalDb, zDbName ? zDbName : "main", 12073 SQLITE_FCNTL_VFS_POINTER, &pVfs); 12074 } 12075 return pVfs; 12076} 12077 12078/* Only for emcc experimentation purposes. */ 12079sqlite3 * fiddle_db_arg(sqlite3 *arg){ 12080 printf("fiddle_db_arg(%p)\n", (const void*)arg); 12081 return arg; 12082} 12083 12084/* 12085** Intended to be called via a SharedWorker() while a separate 12086** SharedWorker() (which manages the wasm module) is performing work 12087** which should be interrupted. Unfortunately, SharedWorker is not 12088** portable enough to make real use of. 12089*/ 12090void fiddle_interrupt(void){ 12091 if( globalDb ) sqlite3_interrupt(globalDb); 12092} 12093 12094/* 12095** Returns the filename of the given db name, assuming "main" if 12096** zDbName is NULL. Returns NULL if globalDb is not opened. 12097*/ 12098const char * fiddle_db_filename(const char * zDbName){ 12099 return globalDb 12100 ? sqlite3_db_filename(globalDb, zDbName ? zDbName : "main") 12101 : NULL; 12102} 12103 12104/* 12105** Completely wipes out the contents of the currently-opened database 12106** but leaves its storage intact for reuse. 12107*/ 12108void fiddle_reset_db(void){ 12109 if( globalDb ){ 12110 int rc = sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); 12111 if( 0==rc ) rc = sqlite3_exec(globalDb, "VACUUM", 0, 0, 0); 12112 sqlite3_db_config(globalDb, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); 12113 } 12114} 12115 12116/* 12117** Uses the current database's VFS xRead to stream the db file's 12118** contents out to the given callback. The callback gets a single 12119** chunk of size n (its 2nd argument) on each call and must return 0 12120** on success, non-0 on error. This function returns 0 on success, 12121** SQLITE_NOTFOUND if no db is open, or propagates any other non-0 12122** code from the callback. Note that this is not thread-friendly: it 12123** expects that it will be the only thread reading the db file and 12124** takes no measures to ensure that is the case. 12125*/ 12126int fiddle_export_db( int (*xCallback)(unsigned const char *zOut, int n) ){ 12127 sqlite3_int64 nSize = 0; 12128 sqlite3_int64 nPos = 0; 12129 sqlite3_file * pFile = 0; 12130 unsigned char buf[1024 * 8]; 12131 int nBuf = (int)sizeof(buf); 12132 int rc = shellState.db 12133 ? sqlite3_file_control(shellState.db, "main", 12134 SQLITE_FCNTL_FILE_POINTER, &pFile) 12135 : SQLITE_NOTFOUND; 12136 if( rc ) return rc; 12137 rc = pFile->pMethods->xFileSize(pFile, &nSize); 12138 if( rc ) return rc; 12139 if(nSize % nBuf){ 12140 /* DB size is not an even multiple of the buffer size. Reduce 12141 ** buffer size so that we do not unduly inflate the db size when 12142 ** exporting. */ 12143 if(0 == nSize % 4096) nBuf = 4096; 12144 else if(0 == nSize % 2048) nBuf = 2048; 12145 else if(0 == nSize % 1024) nBuf = 1024; 12146 else nBuf = 512; 12147 } 12148 for( ; 0==rc && nPos<nSize; nPos += nBuf ){ 12149 rc = pFile->pMethods->xRead(pFile, buf, nBuf, nPos); 12150 if(SQLITE_IOERR_SHORT_READ == rc){ 12151 rc = (nPos + nBuf) < nSize ? rc : 0/*assume EOF*/; 12152 } 12153 if( 0==rc ) rc = xCallback(buf, nBuf); 12154 } 12155 return rc; 12156} 12157 12158/* 12159** Trivial exportable function for emscripten. It processes zSql as if 12160** it were input to the sqlite3 shell and redirects all output to the 12161** wasm binding. fiddle_main() must have been called before this 12162** is called, or results are undefined. 12163*/ 12164void fiddle_exec(const char * zSql){ 12165 if(zSql && *zSql){ 12166 if('.'==*zSql) puts(zSql); 12167 shellState.wasm.zInput = zSql; 12168 shellState.wasm.zPos = zSql; 12169 process_input(&shellState); 12170 shellState.wasm.zInput = shellState.wasm.zPos = 0; 12171 } 12172} 12173#endif /* SQLITE_SHELL_FIDDLE */ 12174