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