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