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