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