You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

16333 lines
487 KiB

  1. /* DO NOT EDIT!
  2. ** This file is automatically generated by the script in the canonical
  3. ** SQLite source tree at tool/mkshellc.tcl. That script combines source
  4. ** code from various constituent source files of SQLite into this single
  5. ** "shell.c" file used to implement the SQLite command-line shell.
  6. **
  7. ** Most of the code found below comes from the "src/shell.c.in" file in
  8. ** the canonical SQLite source tree. That main file contains "INCLUDE"
  9. ** lines that specify other files in the canonical source tree that are
  10. ** inserted to getnerate this complete program source file.
  11. **
  12. ** The code from multiple files is combined into this single "shell.c"
  13. ** source file to help make the command-line program easier to compile.
  14. **
  15. ** To modify this program, get a copy of the canonical SQLite source tree,
  16. ** edit the src/shell.c.in" and/or some of the other files that are included
  17. ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
  18. */
  19. /*
  20. ** 2001 September 15
  21. **
  22. ** The author disclaims copyright to this source code. In place of
  23. ** a legal notice, here is a blessing:
  24. **
  25. ** May you do good and not evil.
  26. ** May you find forgiveness for yourself and forgive others.
  27. ** May you share freely, never taking more than you give.
  28. **
  29. *************************************************************************
  30. ** This file contains code to implement the "sqlite" command line
  31. ** utility for accessing SQLite databases.
  32. */
  33. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  34. /* This needs to come before any includes for MSVC compiler */
  35. #define _CRT_SECURE_NO_WARNINGS
  36. #endif
  37. /*
  38. ** Warning pragmas copied from msvc.h in the core.
  39. */
  40. #if defined(_MSC_VER)
  41. #pragma warning(disable : 4054)
  42. #pragma warning(disable : 4055)
  43. #pragma warning(disable : 4100)
  44. #pragma warning(disable : 4127)
  45. #pragma warning(disable : 4130)
  46. #pragma warning(disable : 4152)
  47. #pragma warning(disable : 4189)
  48. #pragma warning(disable : 4206)
  49. #pragma warning(disable : 4210)
  50. #pragma warning(disable : 4232)
  51. #pragma warning(disable : 4244)
  52. #pragma warning(disable : 4305)
  53. #pragma warning(disable : 4306)
  54. #pragma warning(disable : 4702)
  55. #pragma warning(disable : 4706)
  56. #endif /* defined(_MSC_VER) */
  57. /*
  58. ** No support for loadable extensions in VxWorks.
  59. */
  60. #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
  61. # define SQLITE_OMIT_LOAD_EXTENSION 1
  62. #endif
  63. /*
  64. ** Enable large-file support for fopen() and friends on unix.
  65. */
  66. #ifndef SQLITE_DISABLE_LFS
  67. # define _LARGE_FILE 1
  68. # ifndef _FILE_OFFSET_BITS
  69. # define _FILE_OFFSET_BITS 64
  70. # endif
  71. # define _LARGEFILE_SOURCE 1
  72. #endif
  73. #include <stdlib.h>
  74. #include <string.h>
  75. #include <stdio.h>
  76. #include <assert.h>
  77. #include "sqlite3.h"
  78. typedef sqlite3_int64 i64;
  79. typedef sqlite3_uint64 u64;
  80. typedef unsigned char u8;
  81. #if SQLITE_USER_AUTHENTICATION
  82. # include "sqlite3userauth.h"
  83. #endif
  84. #include <ctype.h>
  85. #include <stdarg.h>
  86. #if !defined(_WIN32) && !defined(WIN32)
  87. # include <signal.h>
  88. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  89. # include <pwd.h>
  90. # endif
  91. #endif
  92. #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
  93. # include <unistd.h>
  94. # include <dirent.h>
  95. # define GETPID getpid
  96. # if defined(__MINGW32__)
  97. # define DIRENT dirent
  98. # ifndef S_ISLNK
  99. # define S_ISLNK(mode) (0)
  100. # endif
  101. # endif
  102. #else
  103. # define GETPID (int)GetCurrentProcessId
  104. #endif
  105. #include <sys/types.h>
  106. #include <sys/stat.h>
  107. #if HAVE_READLINE
  108. # include <readline/readline.h>
  109. # include <readline/history.h>
  110. #endif
  111. #if HAVE_EDITLINE
  112. # include <editline/readline.h>
  113. #endif
  114. #if HAVE_EDITLINE || HAVE_READLINE
  115. # define shell_add_history(X) add_history(X)
  116. # define shell_read_history(X) read_history(X)
  117. # define shell_write_history(X) write_history(X)
  118. # define shell_stifle_history(X) stifle_history(X)
  119. # define shell_readline(X) readline(X)
  120. #elif HAVE_LINENOISE
  121. # include "linenoise.h"
  122. # define shell_add_history(X) linenoiseHistoryAdd(X)
  123. # define shell_read_history(X) linenoiseHistoryLoad(X)
  124. # define shell_write_history(X) linenoiseHistorySave(X)
  125. # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
  126. # define shell_readline(X) linenoise(X)
  127. #else
  128. # define shell_read_history(X)
  129. # define shell_write_history(X)
  130. # define shell_stifle_history(X)
  131. # define SHELL_USE_LOCAL_GETLINE 1
  132. #endif
  133. #if defined(_WIN32) || defined(WIN32)
  134. # include <io.h>
  135. # include <fcntl.h>
  136. # define isatty(h) _isatty(h)
  137. # ifndef access
  138. # define access(f,m) _access((f),(m))
  139. # endif
  140. # ifndef unlink
  141. # define unlink _unlink
  142. # endif
  143. # undef popen
  144. # define popen _popen
  145. # undef pclose
  146. # define pclose _pclose
  147. #else
  148. /* Make sure isatty() has a prototype. */
  149. extern int isatty(int);
  150. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  151. /* popen and pclose are not C89 functions and so are
  152. ** sometimes omitted from the <stdio.h> header */
  153. extern FILE *popen(const char*,const char*);
  154. extern int pclose(FILE*);
  155. # else
  156. # define SQLITE_OMIT_POPEN 1
  157. # endif
  158. #endif
  159. #if defined(_WIN32_WCE)
  160. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  161. * thus we always assume that we have a console. That can be
  162. * overridden with the -batch command line option.
  163. */
  164. #define isatty(x) 1
  165. #endif
  166. /* ctype macros that work with signed characters */
  167. #define IsSpace(X) isspace((unsigned char)X)
  168. #define IsDigit(X) isdigit((unsigned char)X)
  169. #define ToLower(X) (char)tolower((unsigned char)X)
  170. #if defined(_WIN32) || defined(WIN32)
  171. #include <windows.h>
  172. /* string conversion routines only needed on Win32 */
  173. extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
  174. extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
  175. extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
  176. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
  177. #endif
  178. /* On Windows, we normally run with output mode of TEXT so that \n characters
  179. ** are automatically translated into \r\n. However, this behavior needs
  180. ** to be disabled in some cases (ex: when generating CSV output and when
  181. ** rendering quoted strings that contain \n characters). The following
  182. ** routines take care of that.
  183. */
  184. #if defined(_WIN32) || defined(WIN32)
  185. static void setBinaryMode(FILE *file, int isOutput){
  186. if( isOutput ) fflush(file);
  187. _setmode(_fileno(file), _O_BINARY);
  188. }
  189. static void setTextMode(FILE *file, int isOutput){
  190. if( isOutput ) fflush(file);
  191. _setmode(_fileno(file), _O_TEXT);
  192. }
  193. #else
  194. # define setBinaryMode(X,Y)
  195. # define setTextMode(X,Y)
  196. #endif
  197. /* True if the timer is enabled */
  198. static int enableTimer = 0;
  199. /* Return the current wall-clock time */
  200. static sqlite3_int64 timeOfDay(void){
  201. static sqlite3_vfs *clockVfs = 0;
  202. sqlite3_int64 t;
  203. if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
  204. if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
  205. clockVfs->xCurrentTimeInt64(clockVfs, &t);
  206. }else{
  207. double r;
  208. clockVfs->xCurrentTime(clockVfs, &r);
  209. t = (sqlite3_int64)(r*86400000.0);
  210. }
  211. return t;
  212. }
  213. #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
  214. #include <sys/time.h>
  215. #include <sys/resource.h>
  216. /* VxWorks does not support getrusage() as far as we can determine */
  217. #if defined(_WRS_KERNEL) || defined(__RTP__)
  218. struct rusage {
  219. struct timeval ru_utime; /* user CPU time used */
  220. struct timeval ru_stime; /* system CPU time used */
  221. };
  222. #define getrusage(A,B) memset(B,0,sizeof(*B))
  223. #endif
  224. /* Saved resource information for the beginning of an operation */
  225. static struct rusage sBegin; /* CPU time at start */
  226. static sqlite3_int64 iBegin; /* Wall-clock time at start */
  227. /*
  228. ** Begin timing an operation
  229. */
  230. static void beginTimer(void){
  231. if( enableTimer ){
  232. getrusage(RUSAGE_SELF, &sBegin);
  233. iBegin = timeOfDay();
  234. }
  235. }
  236. /* Return the difference of two time_structs in seconds */
  237. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  238. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  239. (double)(pEnd->tv_sec - pStart->tv_sec);
  240. }
  241. /*
  242. ** Print the timing results.
  243. */
  244. static void endTimer(void){
  245. if( enableTimer ){
  246. sqlite3_int64 iEnd = timeOfDay();
  247. struct rusage sEnd;
  248. getrusage(RUSAGE_SELF, &sEnd);
  249. printf("Run Time: real %.3f user %f sys %f\n",
  250. (iEnd - iBegin)*0.001,
  251. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  252. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  253. }
  254. }
  255. #define BEGIN_TIMER beginTimer()
  256. #define END_TIMER endTimer()
  257. #define HAS_TIMER 1
  258. #elif (defined(_WIN32) || defined(WIN32))
  259. /* Saved resource information for the beginning of an operation */
  260. static HANDLE hProcess;
  261. static FILETIME ftKernelBegin;
  262. static FILETIME ftUserBegin;
  263. static sqlite3_int64 ftWallBegin;
  264. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
  265. LPFILETIME, LPFILETIME);
  266. static GETPROCTIMES getProcessTimesAddr = NULL;
  267. /*
  268. ** Check to see if we have timer support. Return 1 if necessary
  269. ** support found (or found previously).
  270. */
  271. static int hasTimer(void){
  272. if( getProcessTimesAddr ){
  273. return 1;
  274. } else {
  275. /* GetProcessTimes() isn't supported in WIN95 and some other Windows
  276. ** versions. See if the version we are running on has it, and if it
  277. ** does, save off a pointer to it and the current process handle.
  278. */
  279. hProcess = GetCurrentProcess();
  280. if( hProcess ){
  281. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  282. if( NULL != hinstLib ){
  283. getProcessTimesAddr =
  284. (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  285. if( NULL != getProcessTimesAddr ){
  286. return 1;
  287. }
  288. FreeLibrary(hinstLib);
  289. }
  290. }
  291. }
  292. return 0;
  293. }
  294. /*
  295. ** Begin timing an operation
  296. */
  297. static void beginTimer(void){
  298. if( enableTimer && getProcessTimesAddr ){
  299. FILETIME ftCreation, ftExit;
  300. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
  301. &ftKernelBegin,&ftUserBegin);
  302. ftWallBegin = timeOfDay();
  303. }
  304. }
  305. /* Return the difference of two FILETIME structs in seconds */
  306. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  307. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  308. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  309. return (double) ((i64End - i64Start) / 10000000.0);
  310. }
  311. /*
  312. ** Print the timing results.
  313. */
  314. static void endTimer(void){
  315. if( enableTimer && getProcessTimesAddr){
  316. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  317. sqlite3_int64 ftWallEnd = timeOfDay();
  318. getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
  319. printf("Run Time: real %.3f user %f sys %f\n",
  320. (ftWallEnd - ftWallBegin)*0.001,
  321. timeDiff(&ftUserBegin, &ftUserEnd),
  322. timeDiff(&ftKernelBegin, &ftKernelEnd));
  323. }
  324. }
  325. #define BEGIN_TIMER beginTimer()
  326. #define END_TIMER endTimer()
  327. #define HAS_TIMER hasTimer()
  328. #else
  329. #define BEGIN_TIMER
  330. #define END_TIMER
  331. #define HAS_TIMER 0
  332. #endif
  333. /*
  334. ** Used to prevent warnings about unused parameters
  335. */
  336. #define UNUSED_PARAMETER(x) (void)(x)
  337. /*
  338. ** Number of elements in an array
  339. */
  340. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  341. /*
  342. ** If the following flag is set, then command execution stops
  343. ** at an error if we are not interactive.
  344. */
  345. static int bail_on_error = 0;
  346. /*
  347. ** Threat stdin as an interactive input if the following variable
  348. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  349. */
  350. static int stdin_is_interactive = 1;
  351. /*
  352. ** On Windows systems we have to know if standard output is a console
  353. ** in order to translate UTF-8 into MBCS. The following variable is
  354. ** true if translation is required.
  355. */
  356. static int stdout_is_console = 1;
  357. /*
  358. ** The following is the open SQLite database. We make a pointer
  359. ** to this database a static variable so that it can be accessed
  360. ** by the SIGINT handler to interrupt database processing.
  361. */
  362. static sqlite3 *globalDb = 0;
  363. /*
  364. ** True if an interrupt (Control-C) has been received.
  365. */
  366. static volatile int seenInterrupt = 0;
  367. /*
  368. ** This is the name of our program. It is set in main(), used
  369. ** in a number of other places, mostly for error messages.
  370. */
  371. static char *Argv0;
  372. /*
  373. ** Prompt strings. Initialized in main. Settable with
  374. ** .prompt main continue
  375. */
  376. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  377. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  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. ** Render output like fprintf(). This should not be used on anything that
  403. ** includes string formatting (e.g. "%s").
  404. */
  405. #if !defined(raw_printf)
  406. # define raw_printf fprintf
  407. #endif
  408. /* Indicate out-of-memory and exit. */
  409. static void shell_out_of_memory(void){
  410. raw_printf(stderr,"Error: out of memory\n");
  411. exit(1);
  412. }
  413. /*
  414. ** Write I/O traces to the following stream.
  415. */
  416. #ifdef SQLITE_ENABLE_IOTRACE
  417. static FILE *iotrace = 0;
  418. #endif
  419. /*
  420. ** This routine works like printf in that its first argument is a
  421. ** format string and subsequent arguments are values to be substituted
  422. ** in place of % fields. The result of formatting this string
  423. ** is written to iotrace.
  424. */
  425. #ifdef SQLITE_ENABLE_IOTRACE
  426. static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
  427. va_list ap;
  428. char *z;
  429. if( iotrace==0 ) return;
  430. va_start(ap, zFormat);
  431. z = sqlite3_vmprintf(zFormat, ap);
  432. va_end(ap);
  433. utf8_printf(iotrace, "%s", z);
  434. sqlite3_free(z);
  435. }
  436. #endif
  437. /*
  438. ** Output string zUtf to stream pOut as w characters. If w is negative,
  439. ** then right-justify the text. W is the width in UTF-8 characters, not
  440. ** in bytes. This is different from the %*.*s specification in printf
  441. ** since with %*.*s the width is measured in bytes, not characters.
  442. */
  443. static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
  444. int i;
  445. int n;
  446. int aw = w<0 ? -w : w;
  447. char zBuf[1000];
  448. if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
  449. for(i=n=0; zUtf[i]; i++){
  450. if( (zUtf[i]&0xc0)!=0x80 ){
  451. n++;
  452. if( n==aw ){
  453. do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
  454. break;
  455. }
  456. }
  457. }
  458. if( n>=aw ){
  459. utf8_printf(pOut, "%.*s", i, zUtf);
  460. }else if( w<0 ){
  461. utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
  462. }else{
  463. utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
  464. }
  465. }
  466. /*
  467. ** Determines if a string is a number of not.
  468. */
  469. static int isNumber(const char *z, int *realnum){
  470. if( *z=='-' || *z=='+' ) z++;
  471. if( !IsDigit(*z) ){
  472. return 0;
  473. }
  474. z++;
  475. if( realnum ) *realnum = 0;
  476. while( IsDigit(*z) ){ z++; }
  477. if( *z=='.' ){
  478. z++;
  479. if( !IsDigit(*z) ) return 0;
  480. while( IsDigit(*z) ){ z++; }
  481. if( realnum ) *realnum = 1;
  482. }
  483. if( *z=='e' || *z=='E' ){
  484. z++;
  485. if( *z=='+' || *z=='-' ) z++;
  486. if( !IsDigit(*z) ) return 0;
  487. while( IsDigit(*z) ){ z++; }
  488. if( realnum ) *realnum = 1;
  489. }
  490. return *z==0;
  491. }
  492. /*
  493. ** Compute a string length that is limited to what can be stored in
  494. ** lower 30 bits of a 32-bit signed integer.
  495. */
  496. static int strlen30(const char *z){
  497. const char *z2 = z;
  498. while( *z2 ){ z2++; }
  499. return 0x3fffffff & (int)(z2 - z);
  500. }
  501. /*
  502. ** Return the length of a string in characters. Multibyte UTF8 characters
  503. ** count as a single character.
  504. */
  505. static int strlenChar(const char *z){
  506. int n = 0;
  507. while( *z ){
  508. if( (0xc0&*(z++))!=0x80 ) n++;
  509. }
  510. return n;
  511. }
  512. /*
  513. ** This routine reads a line of text from FILE in, stores
  514. ** the text in memory obtained from malloc() and returns a pointer
  515. ** to the text. NULL is returned at end of file, or if malloc()
  516. ** fails.
  517. **
  518. ** If zLine is not NULL then it is a malloced buffer returned from
  519. ** a previous call to this routine that may be reused.
  520. */
  521. static char *local_getline(char *zLine, FILE *in){
  522. int nLine = zLine==0 ? 0 : 100;
  523. int n = 0;
  524. while( 1 ){
  525. if( n+100>nLine ){
  526. nLine = nLine*2 + 100;
  527. zLine = realloc(zLine, nLine);
  528. if( zLine==0 ) shell_out_of_memory();
  529. }
  530. if( fgets(&zLine[n], nLine - n, in)==0 ){
  531. if( n==0 ){
  532. free(zLine);
  533. return 0;
  534. }
  535. zLine[n] = 0;
  536. break;
  537. }
  538. while( zLine[n] ) n++;
  539. if( n>0 && zLine[n-1]=='\n' ){
  540. n--;
  541. if( n>0 && zLine[n-1]=='\r' ) n--;
  542. zLine[n] = 0;
  543. break;
  544. }
  545. }
  546. #if defined(_WIN32) || defined(WIN32)
  547. /* For interactive input on Windows systems, translate the
  548. ** multi-byte characterset characters into UTF-8. */
  549. if( stdin_is_interactive && in==stdin ){
  550. char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
  551. if( zTrans ){
  552. int nTrans = strlen30(zTrans)+1;
  553. if( nTrans>nLine ){
  554. zLine = realloc(zLine, nTrans);
  555. if( zLine==0 ) shell_out_of_memory();
  556. }
  557. memcpy(zLine, zTrans, nTrans);
  558. sqlite3_free(zTrans);
  559. }
  560. }
  561. #endif /* defined(_WIN32) || defined(WIN32) */
  562. return zLine;
  563. }
  564. /*
  565. ** Retrieve a single line of input text.
  566. **
  567. ** If in==0 then read from standard input and prompt before each line.
  568. ** If isContinuation is true, then a continuation prompt is appropriate.
  569. ** If isContinuation is zero, then the main prompt should be used.
  570. **
  571. ** If zPrior is not NULL then it is a buffer from a prior call to this
  572. ** routine that can be reused.
  573. **
  574. ** The result is stored in space obtained from malloc() and must either
  575. ** be freed by the caller or else passed back into this routine via the
  576. ** zPrior argument for reuse.
  577. */
  578. static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
  579. char *zPrompt;
  580. char *zResult;
  581. if( in!=0 ){
  582. zResult = local_getline(zPrior, in);
  583. }else{
  584. zPrompt = isContinuation ? continuePrompt : mainPrompt;
  585. #if SHELL_USE_LOCAL_GETLINE
  586. printf("%s", zPrompt);
  587. fflush(stdout);
  588. zResult = local_getline(zPrior, stdin);
  589. #else
  590. free(zPrior);
  591. zResult = shell_readline(zPrompt);
  592. if( zResult && *zResult ) shell_add_history(zResult);
  593. #endif
  594. }
  595. return zResult;
  596. }
  597. /*
  598. ** Return the value of a hexadecimal digit. Return -1 if the input
  599. ** is not a hex digit.
  600. */
  601. static int hexDigitValue(char c){
  602. if( c>='0' && c<='9' ) return c - '0';
  603. if( c>='a' && c<='f' ) return c - 'a' + 10;
  604. if( c>='A' && c<='F' ) return c - 'A' + 10;
  605. return -1;
  606. }
  607. /*
  608. ** Interpret zArg as an integer value, possibly with suffixes.
  609. */
  610. static sqlite3_int64 integerValue(const char *zArg){
  611. sqlite3_int64 v = 0;
  612. static const struct { char *zSuffix; int iMult; } aMult[] = {
  613. { "KiB", 1024 },
  614. { "MiB", 1024*1024 },
  615. { "GiB", 1024*1024*1024 },
  616. { "KB", 1000 },
  617. { "MB", 1000000 },
  618. { "GB", 1000000000 },
  619. { "K", 1000 },
  620. { "M", 1000000 },
  621. { "G", 1000000000 },
  622. };
  623. int i;
  624. int isNeg = 0;
  625. if( zArg[0]=='-' ){
  626. isNeg = 1;
  627. zArg++;
  628. }else if( zArg[0]=='+' ){
  629. zArg++;
  630. }
  631. if( zArg[0]=='0' && zArg[1]=='x' ){
  632. int x;
  633. zArg += 2;
  634. while( (x = hexDigitValue(zArg[0]))>=0 ){
  635. v = (v<<4) + x;
  636. zArg++;
  637. }
  638. }else{
  639. while( IsDigit(zArg[0]) ){
  640. v = v*10 + zArg[0] - '0';
  641. zArg++;
  642. }
  643. }
  644. for(i=0; i<ArraySize(aMult); i++){
  645. if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  646. v *= aMult[i].iMult;
  647. break;
  648. }
  649. }
  650. return isNeg? -v : v;
  651. }
  652. /*
  653. ** A variable length string to which one can append text.
  654. */
  655. typedef struct ShellText ShellText;
  656. struct ShellText {
  657. char *z;
  658. int n;
  659. int nAlloc;
  660. };
  661. /*
  662. ** Initialize and destroy a ShellText object
  663. */
  664. static void initText(ShellText *p){
  665. memset(p, 0, sizeof(*p));
  666. }
  667. static void freeText(ShellText *p){
  668. free(p->z);
  669. initText(p);
  670. }
  671. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  672. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  673. ** added to zIn, and the result returned in memory obtained from malloc().
  674. ** zIn, if it was not NULL, is freed.
  675. **
  676. ** If the third argument, quote, is not '\0', then it is used as a
  677. ** quote character for zAppend.
  678. */
  679. static void appendText(ShellText *p, char const *zAppend, char quote){
  680. int len;
  681. int i;
  682. int nAppend = strlen30(zAppend);
  683. len = nAppend+p->n+1;
  684. if( quote ){
  685. len += 2;
  686. for(i=0; i<nAppend; i++){
  687. if( zAppend[i]==quote ) len++;
  688. }
  689. }
  690. if( p->n+len>=p->nAlloc ){
  691. p->nAlloc = p->nAlloc*2 + len + 20;
  692. p->z = realloc(p->z, p->nAlloc);
  693. if( p->z==0 ) shell_out_of_memory();
  694. }
  695. if( quote ){
  696. char *zCsr = p->z+p->n;
  697. *zCsr++ = quote;
  698. for(i=0; i<nAppend; i++){
  699. *zCsr++ = zAppend[i];
  700. if( zAppend[i]==quote ) *zCsr++ = quote;
  701. }
  702. *zCsr++ = quote;
  703. p->n = (int)(zCsr - p->z);
  704. *zCsr = '\0';
  705. }else{
  706. memcpy(p->z+p->n, zAppend, nAppend);
  707. p->n += nAppend;
  708. p->z[p->n] = '\0';
  709. }
  710. }
  711. /*
  712. ** Attempt to determine if identifier zName needs to be quoted, either
  713. ** because it contains non-alphanumeric characters, or because it is an
  714. ** SQLite keyword. Be conservative in this estimate: When in doubt assume
  715. ** that quoting is required.
  716. **
  717. ** Return '"' if quoting is required. Return 0 if no quoting is required.
  718. */
  719. static char quoteChar(const char *zName){
  720. int i;
  721. if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
  722. for(i=0; zName[i]; i++){
  723. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
  724. }
  725. return sqlite3_keyword_check(zName, i) ? '"' : 0;
  726. }
  727. /*
  728. ** Construct a fake object name and column list to describe the structure
  729. ** of the view, virtual table, or table valued function zSchema.zName.
  730. */
  731. static char *shellFakeSchema(
  732. sqlite3 *db, /* The database connection containing the vtab */
  733. const char *zSchema, /* Schema of the database holding the vtab */
  734. const char *zName /* The name of the virtual table */
  735. ){
  736. sqlite3_stmt *pStmt = 0;
  737. char *zSql;
  738. ShellText s;
  739. char cQuote;
  740. char *zDiv = "(";
  741. int nRow = 0;
  742. zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
  743. zSchema ? zSchema : "main", zName);
  744. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  745. sqlite3_free(zSql);
  746. initText(&s);
  747. if( zSchema ){
  748. cQuote = quoteChar(zSchema);
  749. if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
  750. appendText(&s, zSchema, cQuote);
  751. appendText(&s, ".", 0);
  752. }
  753. cQuote = quoteChar(zName);
  754. appendText(&s, zName, cQuote);
  755. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  756. const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
  757. nRow++;
  758. appendText(&s, zDiv, 0);
  759. zDiv = ",";
  760. cQuote = quoteChar(zCol);
  761. appendText(&s, zCol, cQuote);
  762. }
  763. appendText(&s, ")", 0);
  764. sqlite3_finalize(pStmt);
  765. if( nRow==0 ){
  766. freeText(&s);
  767. s.z = 0;
  768. }
  769. return s.z;
  770. }
  771. /*
  772. ** SQL function: shell_module_schema(X)
  773. **
  774. ** Return a fake schema for the table-valued function or eponymous virtual
  775. ** table X.
  776. */
  777. static void shellModuleSchema(
  778. sqlite3_context *pCtx,
  779. int nVal,
  780. sqlite3_value **apVal
  781. ){
  782. const char *zName = (const char*)sqlite3_value_text(apVal[0]);
  783. char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
  784. UNUSED_PARAMETER(nVal);
  785. if( zFake ){
  786. sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
  787. -1, sqlite3_free);
  788. free(zFake);
  789. }
  790. }
  791. /*
  792. ** SQL function: shell_add_schema(S,X)
  793. **
  794. ** Add the schema name X to the CREATE statement in S and return the result.
  795. ** Examples:
  796. **
  797. ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
  798. **
  799. ** Also works on
  800. **
  801. ** CREATE INDEX
  802. ** CREATE UNIQUE INDEX
  803. ** CREATE VIEW
  804. ** CREATE TRIGGER
  805. ** CREATE VIRTUAL TABLE
  806. **
  807. ** This UDF is used by the .schema command to insert the schema name of
  808. ** attached databases into the middle of the sqlite_master.sql field.
  809. */
  810. static void shellAddSchemaName(
  811. sqlite3_context *pCtx,
  812. int nVal,
  813. sqlite3_value **apVal
  814. ){
  815. static const char *aPrefix[] = {
  816. "TABLE",
  817. "INDEX",
  818. "UNIQUE INDEX",
  819. "VIEW",
  820. "TRIGGER",
  821. "VIRTUAL TABLE"
  822. };
  823. int i = 0;
  824. const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
  825. const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
  826. const char *zName = (const char*)sqlite3_value_text(apVal[2]);
  827. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  828. UNUSED_PARAMETER(nVal);
  829. if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
  830. for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
  831. int n = strlen30(aPrefix[i]);
  832. if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
  833. char *z = 0;
  834. char *zFake = 0;
  835. if( zSchema ){
  836. char cQuote = quoteChar(zSchema);
  837. if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
  838. z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
  839. }else{
  840. z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
  841. }
  842. }
  843. if( zName
  844. && aPrefix[i][0]=='V'
  845. && (zFake = shellFakeSchema(db, zSchema, zName))!=0
  846. ){
  847. if( z==0 ){
  848. z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
  849. }else{
  850. z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
  851. }
  852. free(zFake);
  853. }
  854. if( z ){
  855. sqlite3_result_text(pCtx, z, -1, sqlite3_free);
  856. return;
  857. }
  858. }
  859. }
  860. }
  861. sqlite3_result_value(pCtx, apVal[0]);
  862. }
  863. /*
  864. ** The source code for several run-time loadable extensions is inserted
  865. ** below by the ../tool/mkshellc.tcl script. Before processing that included
  866. ** code, we need to override some macros to make the included program code
  867. ** work here in the middle of this regular program.
  868. */
  869. #define SQLITE_EXTENSION_INIT1
  870. #define SQLITE_EXTENSION_INIT2(X) (void)(X)
  871. #if defined(_WIN32) && defined(_MSC_VER)
  872. /************************* Begin test_windirent.h ******************/
  873. /*
  874. ** 2015 November 30
  875. **
  876. ** The author disclaims copyright to this source code. In place of
  877. ** a legal notice, here is a blessing:
  878. **
  879. ** May you do good and not evil.
  880. ** May you find forgiveness for yourself and forgive others.
  881. ** May you share freely, never taking more than you give.
  882. **
  883. *************************************************************************
  884. ** This file contains declarations for most of the opendir() family of
  885. ** POSIX functions on Win32 using the MSVCRT.
  886. */
  887. #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
  888. #define SQLITE_WINDIRENT_H
  889. /*
  890. ** We need several data types from the Windows SDK header.
  891. */
  892. #ifndef WIN32_LEAN_AND_MEAN
  893. #define WIN32_LEAN_AND_MEAN
  894. #endif
  895. #include "windows.h"
  896. /*
  897. ** We need several support functions from the SQLite core.
  898. */
  899. /*
  900. ** We need several things from the ANSI and MSVCRT headers.
  901. */
  902. #include <stdio.h>
  903. #include <stdlib.h>
  904. #include <errno.h>
  905. #include <io.h>
  906. #include <limits.h>
  907. #include <sys/types.h>
  908. #include <sys/stat.h>
  909. /*
  910. ** We may need several defines that should have been in "sys/stat.h".
  911. */
  912. #ifndef S_ISREG
  913. #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
  914. #endif
  915. #ifndef S_ISDIR
  916. #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
  917. #endif
  918. #ifndef S_ISLNK
  919. #define S_ISLNK(mode) (0)
  920. #endif
  921. /*
  922. ** We may need to provide the "mode_t" type.
  923. */
  924. #ifndef MODE_T_DEFINED
  925. #define MODE_T_DEFINED
  926. typedef unsigned short mode_t;
  927. #endif
  928. /*
  929. ** We may need to provide the "ino_t" type.
  930. */
  931. #ifndef INO_T_DEFINED
  932. #define INO_T_DEFINED
  933. typedef unsigned short ino_t;
  934. #endif
  935. /*
  936. ** We need to define "NAME_MAX" if it was not present in "limits.h".
  937. */
  938. #ifndef NAME_MAX
  939. # ifdef FILENAME_MAX
  940. # define NAME_MAX (FILENAME_MAX)
  941. # else
  942. # define NAME_MAX (260)
  943. # endif
  944. #endif
  945. /*
  946. ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
  947. */
  948. #ifndef NULL_INTPTR_T
  949. # define NULL_INTPTR_T ((intptr_t)(0))
  950. #endif
  951. #ifndef BAD_INTPTR_T
  952. # define BAD_INTPTR_T ((intptr_t)(-1))
  953. #endif
  954. /*
  955. ** We need to provide the necessary structures and related types.
  956. */
  957. #ifndef DIRENT_DEFINED
  958. #define DIRENT_DEFINED
  959. typedef struct DIRENT DIRENT;
  960. typedef DIRENT *LPDIRENT;
  961. struct DIRENT {
  962. ino_t d_ino; /* Sequence number, do not use. */
  963. unsigned d_attributes; /* Win32 file attributes. */
  964. char d_name[NAME_MAX + 1]; /* Name within the directory. */
  965. };
  966. #endif
  967. #ifndef DIR_DEFINED
  968. #define DIR_DEFINED
  969. typedef struct DIR DIR;
  970. typedef DIR *LPDIR;
  971. struct DIR {
  972. intptr_t d_handle; /* Value returned by "_findfirst". */
  973. DIRENT d_first; /* DIRENT constructed based on "_findfirst". */
  974. DIRENT d_next; /* DIRENT constructed based on "_findnext". */
  975. };
  976. #endif
  977. /*
  978. ** Provide a macro, for use by the implementation, to determine if a
  979. ** particular directory entry should be skipped over when searching for
  980. ** the next directory entry that should be returned by the readdir() or
  981. ** readdir_r() functions.
  982. */
  983. #ifndef is_filtered
  984. # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
  985. #endif
  986. /*
  987. ** Provide the function prototype for the POSIX compatiable getenv()
  988. ** function. This function is not thread-safe.
  989. */
  990. extern const char *windirent_getenv(const char *name);
  991. /*
  992. ** Finally, we can provide the function prototypes for the opendir(),
  993. ** readdir(), readdir_r(), and closedir() POSIX functions.
  994. */
  995. extern LPDIR opendir(const char *dirname);
  996. extern LPDIRENT readdir(LPDIR dirp);
  997. extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
  998. extern INT closedir(LPDIR dirp);
  999. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1000. /************************* End test_windirent.h ********************/
  1001. /************************* Begin test_windirent.c ******************/
  1002. /*
  1003. ** 2015 November 30
  1004. **
  1005. ** The author disclaims copyright to this source code. In place of
  1006. ** a legal notice, here is a blessing:
  1007. **
  1008. ** May you do good and not evil.
  1009. ** May you find forgiveness for yourself and forgive others.
  1010. ** May you share freely, never taking more than you give.
  1011. **
  1012. *************************************************************************
  1013. ** This file contains code to implement most of the opendir() family of
  1014. ** POSIX functions on Win32 using the MSVCRT.
  1015. */
  1016. #if defined(_WIN32) && defined(_MSC_VER)
  1017. /* #include "test_windirent.h" */
  1018. /*
  1019. ** Implementation of the POSIX getenv() function using the Win32 API.
  1020. ** This function is not thread-safe.
  1021. */
  1022. const char *windirent_getenv(
  1023. const char *name
  1024. ){
  1025. static char value[32768]; /* Maximum length, per MSDN */
  1026. DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
  1027. DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
  1028. memset(value, 0, sizeof(value));
  1029. dwRet = GetEnvironmentVariableA(name, value, dwSize);
  1030. if( dwRet==0 || dwRet>dwSize ){
  1031. /*
  1032. ** The function call to GetEnvironmentVariableA() failed -OR-
  1033. ** the buffer is not large enough. Either way, return NULL.
  1034. */
  1035. return 0;
  1036. }else{
  1037. /*
  1038. ** The function call to GetEnvironmentVariableA() succeeded
  1039. ** -AND- the buffer contains the entire value.
  1040. */
  1041. return value;
  1042. }
  1043. }
  1044. /*
  1045. ** Implementation of the POSIX opendir() function using the MSVCRT.
  1046. */
  1047. LPDIR opendir(
  1048. const char *dirname
  1049. ){
  1050. struct _finddata_t data;
  1051. LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
  1052. SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
  1053. if( dirp==NULL ) return NULL;
  1054. memset(dirp, 0, sizeof(DIR));
  1055. /* TODO: Remove this if Unix-style root paths are not used. */
  1056. if( sqlite3_stricmp(dirname, "/")==0 ){
  1057. dirname = windirent_getenv("SystemDrive");
  1058. }
  1059. memset(&data, 0, sizeof(struct _finddata_t));
  1060. _snprintf(data.name, namesize, "%s\\*", dirname);
  1061. dirp->d_handle = _findfirst(data.name, &data);
  1062. if( dirp->d_handle==BAD_INTPTR_T ){
  1063. closedir(dirp);
  1064. return NULL;
  1065. }
  1066. /* TODO: Remove this block to allow hidden and/or system files. */
  1067. if( is_filtered(data) ){
  1068. next:
  1069. memset(&data, 0, sizeof(struct _finddata_t));
  1070. if( _findnext(dirp->d_handle, &data)==-1 ){
  1071. closedir(dirp);
  1072. return NULL;
  1073. }
  1074. /* TODO: Remove this block to allow hidden and/or system files. */
  1075. if( is_filtered(data) ) goto next;
  1076. }
  1077. dirp->d_first.d_attributes = data.attrib;
  1078. strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
  1079. dirp->d_first.d_name[NAME_MAX] = '\0';
  1080. return dirp;
  1081. }
  1082. /*
  1083. ** Implementation of the POSIX readdir() function using the MSVCRT.
  1084. */
  1085. LPDIRENT readdir(
  1086. LPDIR dirp
  1087. ){
  1088. struct _finddata_t data;
  1089. if( dirp==NULL ) return NULL;
  1090. if( dirp->d_first.d_ino==0 ){
  1091. dirp->d_first.d_ino++;
  1092. dirp->d_next.d_ino++;
  1093. return &dirp->d_first;
  1094. }
  1095. next:
  1096. memset(&data, 0, sizeof(struct _finddata_t));
  1097. if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
  1098. /* TODO: Remove this block to allow hidden and/or system files. */
  1099. if( is_filtered(data) ) goto next;
  1100. dirp->d_next.d_ino++;
  1101. dirp->d_next.d_attributes = data.attrib;
  1102. strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
  1103. dirp->d_next.d_name[NAME_MAX] = '\0';
  1104. return &dirp->d_next;
  1105. }
  1106. /*
  1107. ** Implementation of the POSIX readdir_r() function using the MSVCRT.
  1108. */
  1109. INT readdir_r(
  1110. LPDIR dirp,
  1111. LPDIRENT entry,
  1112. LPDIRENT *result
  1113. ){
  1114. struct _finddata_t data;
  1115. if( dirp==NULL ) return EBADF;
  1116. if( dirp->d_first.d_ino==0 ){
  1117. dirp->d_first.d_ino++;
  1118. dirp->d_next.d_ino++;
  1119. entry->d_ino = dirp->d_first.d_ino;
  1120. entry->d_attributes = dirp->d_first.d_attributes;
  1121. strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
  1122. entry->d_name[NAME_MAX] = '\0';
  1123. *result = entry;
  1124. return 0;
  1125. }
  1126. next:
  1127. memset(&data, 0, sizeof(struct _finddata_t));
  1128. if( _findnext(dirp->d_handle, &data)==-1 ){
  1129. *result = NULL;
  1130. return ENOENT;
  1131. }
  1132. /* TODO: Remove this block to allow hidden and/or system files. */
  1133. if( is_filtered(data) ) goto next;
  1134. entry->d_ino = (ino_t)-1; /* not available */
  1135. entry->d_attributes = data.attrib;
  1136. strncpy(entry->d_name, data.name, NAME_MAX);
  1137. entry->d_name[NAME_MAX] = '\0';
  1138. *result = entry;
  1139. return 0;
  1140. }
  1141. /*
  1142. ** Implementation of the POSIX closedir() function using the MSVCRT.
  1143. */
  1144. INT closedir(
  1145. LPDIR dirp
  1146. ){
  1147. INT result = 0;
  1148. if( dirp==NULL ) return EINVAL;
  1149. if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
  1150. result = _findclose(dirp->d_handle);
  1151. }
  1152. sqlite3_free(dirp);
  1153. return result;
  1154. }
  1155. #endif /* defined(WIN32) && defined(_MSC_VER) */
  1156. /************************* End test_windirent.c ********************/
  1157. #define dirent DIRENT
  1158. #endif
  1159. /************************* Begin ../ext/misc/shathree.c ******************/
  1160. /*
  1161. ** 2017-03-08
  1162. **
  1163. ** The author disclaims copyright to this source code. In place of
  1164. ** a legal notice, here is a blessing:
  1165. **
  1166. ** May you do good and not evil.
  1167. ** May you find forgiveness for yourself and forgive others.
  1168. ** May you share freely, never taking more than you give.
  1169. **
  1170. ******************************************************************************
  1171. **
  1172. ** This SQLite extension implements a functions that compute SHA1 hashes.
  1173. ** Two SQL functions are implemented:
  1174. **
  1175. ** sha3(X,SIZE)
  1176. ** sha3_query(Y,SIZE)
  1177. **
  1178. ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
  1179. ** X is NULL.
  1180. **
  1181. ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
  1182. ** and returns a hash of their results.
  1183. **
  1184. ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
  1185. ** is used. If SIZE is included it must be one of the integers 224, 256,
  1186. ** 384, or 512, to determine SHA3 hash variant that is computed.
  1187. */
  1188. SQLITE_EXTENSION_INIT1
  1189. #include <assert.h>
  1190. #include <string.h>
  1191. #include <stdarg.h>
  1192. /* typedef sqlite3_uint64 u64; */
  1193. /******************************************************************************
  1194. ** The Hash Engine
  1195. */
  1196. /*
  1197. ** Macros to determine whether the machine is big or little endian,
  1198. ** and whether or not that determination is run-time or compile-time.
  1199. **
  1200. ** For best performance, an attempt is made to guess at the byte-order
  1201. ** using C-preprocessor macros. If that is unsuccessful, or if
  1202. ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
  1203. ** at run-time.
  1204. */
  1205. #ifndef SHA3_BYTEORDER
  1206. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  1207. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  1208. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  1209. defined(__arm__)
  1210. # define SHA3_BYTEORDER 1234
  1211. # elif defined(sparc) || defined(__ppc__)
  1212. # define SHA3_BYTEORDER 4321
  1213. # else
  1214. # define SHA3_BYTEORDER 0
  1215. # endif
  1216. #endif
  1217. /*
  1218. ** State structure for a SHA3 hash in progress
  1219. */
  1220. typedef struct SHA3Context SHA3Context;
  1221. struct SHA3Context {
  1222. union {
  1223. u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
  1224. unsigned char x[1600]; /* ... or 1600 bytes */
  1225. } u;
  1226. unsigned nRate; /* Bytes of input accepted per Keccak iteration */
  1227. unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
  1228. unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
  1229. };
  1230. /*
  1231. ** A single step of the Keccak mixing function for a 1600-bit state
  1232. */
  1233. static void KeccakF1600Step(SHA3Context *p){
  1234. int i;
  1235. u64 b0, b1, b2, b3, b4;
  1236. u64 c0, c1, c2, c3, c4;
  1237. u64 d0, d1, d2, d3, d4;
  1238. static const u64 RC[] = {
  1239. 0x0000000000000001ULL, 0x0000000000008082ULL,
  1240. 0x800000000000808aULL, 0x8000000080008000ULL,
  1241. 0x000000000000808bULL, 0x0000000080000001ULL,
  1242. 0x8000000080008081ULL, 0x8000000000008009ULL,
  1243. 0x000000000000008aULL, 0x0000000000000088ULL,
  1244. 0x0000000080008009ULL, 0x000000008000000aULL,
  1245. 0x000000008000808bULL, 0x800000000000008bULL,
  1246. 0x8000000000008089ULL, 0x8000000000008003ULL,
  1247. 0x8000000000008002ULL, 0x8000000000000080ULL,
  1248. 0x000000000000800aULL, 0x800000008000000aULL,
  1249. 0x8000000080008081ULL, 0x8000000000008080ULL,
  1250. 0x0000000080000001ULL, 0x8000000080008008ULL
  1251. };
  1252. # define a00 (p->u.s[0])
  1253. # define a01 (p->u.s[1])
  1254. # define a02 (p->u.s[2])
  1255. # define a03 (p->u.s[3])
  1256. # define a04 (p->u.s[4])
  1257. # define a10 (p->u.s[5])
  1258. # define a11 (p->u.s[6])
  1259. # define a12 (p->u.s[7])
  1260. # define a13 (p->u.s[8])
  1261. # define a14 (p->u.s[9])
  1262. # define a20 (p->u.s[10])
  1263. # define a21 (p->u.s[11])
  1264. # define a22 (p->u.s[12])
  1265. # define a23 (p->u.s[13])
  1266. # define a24 (p->u.s[14])
  1267. # define a30 (p->u.s[15])
  1268. # define a31 (p->u.s[16])
  1269. # define a32 (p->u.s[17])
  1270. # define a33 (p->u.s[18])
  1271. # define a34 (p->u.s[19])
  1272. # define a40 (p->u.s[20])
  1273. # define a41 (p->u.s[21])
  1274. # define a42 (p->u.s[22])
  1275. # define a43 (p->u.s[23])
  1276. # define a44 (p->u.s[24])
  1277. # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
  1278. for(i=0; i<24; i+=4){
  1279. c0 = a00^a10^a20^a30^a40;
  1280. c1 = a01^a11^a21^a31^a41;
  1281. c2 = a02^a12^a22^a32^a42;
  1282. c3 = a03^a13^a23^a33^a43;
  1283. c4 = a04^a14^a24^a34^a44;
  1284. d0 = c4^ROL64(c1, 1);
  1285. d1 = c0^ROL64(c2, 1);
  1286. d2 = c1^ROL64(c3, 1);
  1287. d3 = c2^ROL64(c4, 1);
  1288. d4 = c3^ROL64(c0, 1);
  1289. b0 = (a00^d0);
  1290. b1 = ROL64((a11^d1), 44);
  1291. b2 = ROL64((a22^d2), 43);
  1292. b3 = ROL64((a33^d3), 21);
  1293. b4 = ROL64((a44^d4), 14);
  1294. a00 = b0 ^((~b1)& b2 );
  1295. a00 ^= RC[i];
  1296. a11 = b1 ^((~b2)& b3 );
  1297. a22 = b2 ^((~b3)& b4 );
  1298. a33 = b3 ^((~b4)& b0 );
  1299. a44 = b4 ^((~b0)& b1 );
  1300. b2 = ROL64((a20^d0), 3);
  1301. b3 = ROL64((a31^d1), 45);
  1302. b4 = ROL64((a42^d2), 61);
  1303. b0 = ROL64((a03^d3), 28);
  1304. b1 = ROL64((a14^d4), 20);
  1305. a20 = b0 ^((~b1)& b2 );
  1306. a31 = b1 ^((~b2)& b3 );
  1307. a42 = b2 ^((~b3)& b4 );
  1308. a03 = b3 ^((~b4)& b0 );
  1309. a14 = b4 ^((~b0)& b1 );
  1310. b4 = ROL64((a40^d0), 18);
  1311. b0 = ROL64((a01^d1), 1);
  1312. b1 = ROL64((a12^d2), 6);
  1313. b2 = ROL64((a23^d3), 25);
  1314. b3 = ROL64((a34^d4), 8);
  1315. a40 = b0 ^((~b1)& b2 );
  1316. a01 = b1 ^((~b2)& b3 );
  1317. a12 = b2 ^((~b3)& b4 );
  1318. a23 = b3 ^((~b4)& b0 );
  1319. a34 = b4 ^((~b0)& b1 );
  1320. b1 = ROL64((a10^d0), 36);
  1321. b2 = ROL64((a21^d1), 10);
  1322. b3 = ROL64((a32^d2), 15);
  1323. b4 = ROL64((a43^d3), 56);
  1324. b0 = ROL64((a04^d4), 27);
  1325. a10 = b0 ^((~b1)& b2 );
  1326. a21 = b1 ^((~b2)& b3 );
  1327. a32 = b2 ^((~b3)& b4 );
  1328. a43 = b3 ^((~b4)& b0 );
  1329. a04 = b4 ^((~b0)& b1 );
  1330. b3 = ROL64((a30^d0), 41);
  1331. b4 = ROL64((a41^d1), 2);
  1332. b0 = ROL64((a02^d2), 62);
  1333. b1 = ROL64((a13^d3), 55);
  1334. b2 = ROL64((a24^d4), 39);
  1335. a30 = b0 ^((~b1)& b2 );
  1336. a41 = b1 ^((~b2)& b3 );
  1337. a02 = b2 ^((~b3)& b4 );
  1338. a13 = b3 ^((~b4)& b0 );
  1339. a24 = b4 ^((~b0)& b1 );
  1340. c0 = a00^a20^a40^a10^a30;
  1341. c1 = a11^a31^a01^a21^a41;
  1342. c2 = a22^a42^a12^a32^a02;
  1343. c3 = a33^a03^a23^a43^a13;
  1344. c4 = a44^a14^a34^a04^a24;
  1345. d0 = c4^ROL64(c1, 1);
  1346. d1 = c0^ROL64(c2, 1);
  1347. d2 = c1^ROL64(c3, 1);
  1348. d3 = c2^ROL64(c4, 1);
  1349. d4 = c3^ROL64(c0, 1);
  1350. b0 = (a00^d0);
  1351. b1 = ROL64((a31^d1), 44);
  1352. b2 = ROL64((a12^d2), 43);
  1353. b3 = ROL64((a43^d3), 21);
  1354. b4 = ROL64((a24^d4), 14);
  1355. a00 = b0 ^((~b1)& b2 );
  1356. a00 ^= RC[i+1];
  1357. a31 = b1 ^((~b2)& b3 );
  1358. a12 = b2 ^((~b3)& b4 );
  1359. a43 = b3 ^((~b4)& b0 );
  1360. a24 = b4 ^((~b0)& b1 );
  1361. b2 = ROL64((a40^d0), 3);
  1362. b3 = ROL64((a21^d1), 45);
  1363. b4 = ROL64((a02^d2), 61);
  1364. b0 = ROL64((a33^d3), 28);
  1365. b1 = ROL64((a14^d4), 20);
  1366. a40 = b0 ^((~b1)& b2 );
  1367. a21 = b1 ^((~b2)& b3 );
  1368. a02 = b2 ^((~b3)& b4 );
  1369. a33 = b3 ^((~b4)& b0 );
  1370. a14 = b4 ^((~b0)& b1 );
  1371. b4 = ROL64((a30^d0), 18);
  1372. b0 = ROL64((a11^d1), 1);
  1373. b1 = ROL64((a42^d2), 6);
  1374. b2 = ROL64((a23^d3), 25);
  1375. b3 = ROL64((a04^d4), 8);
  1376. a30 = b0 ^((~b1)& b2 );
  1377. a11 = b1 ^((~b2)& b3 );
  1378. a42 = b2 ^((~b3)& b4 );
  1379. a23 = b3 ^((~b4)& b0 );
  1380. a04 = b4 ^((~b0)& b1 );
  1381. b1 = ROL64((a20^d0), 36);
  1382. b2 = ROL64((a01^d1), 10);
  1383. b3 = ROL64((a32^d2), 15);
  1384. b4 = ROL64((a13^d3), 56);
  1385. b0 = ROL64((a44^d4), 27);
  1386. a20 = b0 ^((~b1)& b2 );
  1387. a01 = b1 ^((~b2)& b3 );
  1388. a32 = b2 ^((~b3)& b4 );
  1389. a13 = b3 ^((~b4)& b0 );
  1390. a44 = b4 ^((~b0)& b1 );
  1391. b3 = ROL64((a10^d0), 41);
  1392. b4 = ROL64((a41^d1), 2);
  1393. b0 = ROL64((a22^d2), 62);
  1394. b1 = ROL64((a03^d3), 55);
  1395. b2 = ROL64((a34^d4), 39);
  1396. a10 = b0 ^((~b1)& b2 );
  1397. a41 = b1 ^((~b2)& b3 );
  1398. a22 = b2 ^((~b3)& b4 );
  1399. a03 = b3 ^((~b4)& b0 );
  1400. a34 = b4 ^((~b0)& b1 );
  1401. c0 = a00^a40^a30^a20^a10;
  1402. c1 = a31^a21^a11^a01^a41;
  1403. c2 = a12^a02^a42^a32^a22;
  1404. c3 = a43^a33^a23^a13^a03;
  1405. c4 = a24^a14^a04^a44^a34;
  1406. d0 = c4^ROL64(c1, 1);
  1407. d1 = c0^ROL64(c2, 1);
  1408. d2 = c1^ROL64(c3, 1);
  1409. d3 = c2^ROL64(c4, 1);
  1410. d4 = c3^ROL64(c0, 1);
  1411. b0 = (a00^d0);
  1412. b1 = ROL64((a21^d1), 44);
  1413. b2 = ROL64((a42^d2), 43);
  1414. b3 = ROL64((a13^d3), 21);
  1415. b4 = ROL64((a34^d4), 14);
  1416. a00 = b0 ^((~b1)& b2 );
  1417. a00 ^= RC[i+2];
  1418. a21 = b1 ^((~b2)& b3 );
  1419. a42 = b2 ^((~b3)& b4 );
  1420. a13 = b3 ^((~b4)& b0 );
  1421. a34 = b4 ^((~b0)& b1 );
  1422. b2 = ROL64((a30^d0), 3);
  1423. b3 = ROL64((a01^d1), 45);
  1424. b4 = ROL64((a22^d2), 61);
  1425. b0 = ROL64((a43^d3), 28);
  1426. b1 = ROL64((a14^d4), 20);
  1427. a30 = b0 ^((~b1)& b2 );
  1428. a01 = b1 ^((~b2)& b3 );
  1429. a22 = b2 ^((~b3)& b4 );
  1430. a43 = b3 ^((~b4)& b0 );
  1431. a14 = b4 ^((~b0)& b1 );
  1432. b4 = ROL64((a10^d0), 18);
  1433. b0 = ROL64((a31^d1), 1);
  1434. b1 = ROL64((a02^d2), 6);
  1435. b2 = ROL64((a23^d3), 25);
  1436. b3 = ROL64((a44^d4), 8);
  1437. a10 = b0 ^((~b1)& b2 );
  1438. a31 = b1 ^((~b2)& b3 );
  1439. a02 = b2 ^((~b3)& b4 );
  1440. a23 = b3 ^((~b4)& b0 );
  1441. a44 = b4 ^((~b0)& b1 );
  1442. b1 = ROL64((a40^d0), 36);
  1443. b2 = ROL64((a11^d1), 10);
  1444. b3 = ROL64((a32^d2), 15);
  1445. b4 = ROL64((a03^d3), 56);
  1446. b0 = ROL64((a24^d4), 27);
  1447. a40 = b0 ^((~b1)& b2 );
  1448. a11 = b1 ^((~b2)& b3 );
  1449. a32 = b2 ^((~b3)& b4 );
  1450. a03 = b3 ^((~b4)& b0 );
  1451. a24 = b4 ^((~b0)& b1 );
  1452. b3 = ROL64((a20^d0), 41);
  1453. b4 = ROL64((a41^d1), 2);
  1454. b0 = ROL64((a12^d2), 62);
  1455. b1 = ROL64((a33^d3), 55);
  1456. b2 = ROL64((a04^d4), 39);
  1457. a20 = b0 ^((~b1)& b2 );
  1458. a41 = b1 ^((~b2)& b3 );
  1459. a12 = b2 ^((~b3)& b4 );
  1460. a33 = b3 ^((~b4)& b0 );
  1461. a04 = b4 ^((~b0)& b1 );
  1462. c0 = a00^a30^a10^a40^a20;
  1463. c1 = a21^a01^a31^a11^a41;
  1464. c2 = a42^a22^a02^a32^a12;
  1465. c3 = a13^a43^a23^a03^a33;
  1466. c4 = a34^a14^a44^a24^a04;
  1467. d0 = c4^ROL64(c1, 1);
  1468. d1 = c0^ROL64(c2, 1);
  1469. d2 = c1^ROL64(c3, 1);
  1470. d3 = c2^ROL64(c4, 1);
  1471. d4 = c3^ROL64(c0, 1);
  1472. b0 = (a00^d0);
  1473. b1 = ROL64((a01^d1), 44);
  1474. b2 = ROL64((a02^d2), 43);
  1475. b3 = ROL64((a03^d3), 21);
  1476. b4 = ROL64((a04^d4), 14);
  1477. a00 = b0 ^((~b1)& b2 );
  1478. a00 ^= RC[i+3];
  1479. a01 = b1 ^((~b2)& b3 );
  1480. a02 = b2 ^((~b3)& b4 );
  1481. a03 = b3 ^((~b4)& b0 );
  1482. a04 = b4 ^((~b0)& b1 );
  1483. b2 = ROL64((a10^d0), 3);
  1484. b3 = ROL64((a11^d1), 45);
  1485. b4 = ROL64((a12^d2), 61);
  1486. b0 = ROL64((a13^d3), 28);
  1487. b1 = ROL64((a14^d4), 20);
  1488. a10 = b0 ^((~b1)& b2 );
  1489. a11 = b1 ^((~b2)& b3 );
  1490. a12 = b2 ^((~b3)& b4 );
  1491. a13 = b3 ^((~b4)& b0 );
  1492. a14 = b4 ^((~b0)& b1 );
  1493. b4 = ROL64((a20^d0), 18);
  1494. b0 = ROL64((a21^d1), 1);
  1495. b1 = ROL64((a22^d2), 6);
  1496. b2 = ROL64((a23^d3), 25);
  1497. b3 = ROL64((a24^d4), 8);
  1498. a20 = b0 ^((~b1)& b2 );
  1499. a21 = b1 ^((~b2)& b3 );
  1500. a22 = b2 ^((~b3)& b4 );
  1501. a23 = b3 ^((~b4)& b0 );
  1502. a24 = b4 ^((~b0)& b1 );
  1503. b1 = ROL64((a30^d0), 36);
  1504. b2 = ROL64((a31^d1), 10);
  1505. b3 = ROL64((a32^d2), 15);
  1506. b4 = ROL64((a33^d3), 56);
  1507. b0 = ROL64((a34^d4), 27);
  1508. a30 = b0 ^((~b1)& b2 );
  1509. a31 = b1 ^((~b2)& b3 );
  1510. a32 = b2 ^((~b3)& b4 );
  1511. a33 = b3 ^((~b4)& b0 );
  1512. a34 = b4 ^((~b0)& b1 );
  1513. b3 = ROL64((a40^d0), 41);
  1514. b4 = ROL64((a41^d1), 2);
  1515. b0 = ROL64((a42^d2), 62);
  1516. b1 = ROL64((a43^d3), 55);
  1517. b2 = ROL64((a44^d4), 39);
  1518. a40 = b0 ^((~b1)& b2 );
  1519. a41 = b1 ^((~b2)& b3 );
  1520. a42 = b2 ^((~b3)& b4 );
  1521. a43 = b3 ^((~b4)& b0 );
  1522. a44 = b4 ^((~b0)& b1 );
  1523. }
  1524. }
  1525. /*
  1526. ** Initialize a new hash. iSize determines the size of the hash
  1527. ** in bits and should be one of 224, 256, 384, or 512. Or iSize
  1528. ** can be zero to use the default hash size of 256 bits.
  1529. */
  1530. static void SHA3Init(SHA3Context *p, int iSize){
  1531. memset(p, 0, sizeof(*p));
  1532. if( iSize>=128 && iSize<=512 ){
  1533. p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
  1534. }else{
  1535. p->nRate = (1600 - 2*256)/8;
  1536. }
  1537. #if SHA3_BYTEORDER==1234
  1538. /* Known to be little-endian at compile-time. No-op */
  1539. #elif SHA3_BYTEORDER==4321
  1540. p->ixMask = 7; /* Big-endian */
  1541. #else
  1542. {
  1543. static unsigned int one = 1;
  1544. if( 1==*(unsigned char*)&one ){
  1545. /* Little endian. No byte swapping. */
  1546. p->ixMask = 0;
  1547. }else{
  1548. /* Big endian. Byte swap. */
  1549. p->ixMask = 7;
  1550. }
  1551. }
  1552. #endif
  1553. }
  1554. /*
  1555. ** Make consecutive calls to the SHA3Update function to add new content
  1556. ** to the hash
  1557. */
  1558. static void SHA3Update(
  1559. SHA3Context *p,
  1560. const unsigned char *aData,
  1561. unsigned int nData
  1562. ){
  1563. unsigned int i = 0;
  1564. #if SHA3_BYTEORDER==1234
  1565. if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
  1566. for(; i+7<nData; i+=8){
  1567. p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
  1568. p->nLoaded += 8;
  1569. if( p->nLoaded>=p->nRate ){
  1570. KeccakF1600Step(p);
  1571. p->nLoaded = 0;
  1572. }
  1573. }
  1574. }
  1575. #endif
  1576. for(; i<nData; i++){
  1577. #if SHA3_BYTEORDER==1234
  1578. p->u.x[p->nLoaded] ^= aData[i];
  1579. #elif SHA3_BYTEORDER==4321
  1580. p->u.x[p->nLoaded^0x07] ^= aData[i];
  1581. #else
  1582. p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
  1583. #endif
  1584. p->nLoaded++;
  1585. if( p->nLoaded==p->nRate ){
  1586. KeccakF1600Step(p);
  1587. p->nLoaded = 0;
  1588. }
  1589. }
  1590. }
  1591. /*
  1592. ** After all content has been added, invoke SHA3Final() to compute
  1593. ** the final hash. The function returns a pointer to the binary
  1594. ** hash value.
  1595. */
  1596. static unsigned char *SHA3Final(SHA3Context *p){
  1597. unsigned int i;
  1598. if( p->nLoaded==p->nRate-1 ){
  1599. const unsigned char c1 = 0x86;
  1600. SHA3Update(p, &c1, 1);
  1601. }else{
  1602. const unsigned char c2 = 0x06;
  1603. const unsigned char c3 = 0x80;
  1604. SHA3Update(p, &c2, 1);
  1605. p->nLoaded = p->nRate - 1;
  1606. SHA3Update(p, &c3, 1);
  1607. }
  1608. for(i=0; i<p->nRate; i++){
  1609. p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
  1610. }
  1611. return &p->u.x[p->nRate];
  1612. }
  1613. /* End of the hashing logic
  1614. *****************************************************************************/
  1615. /*
  1616. ** Implementation of the sha3(X,SIZE) function.
  1617. **
  1618. ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
  1619. ** size is 256. If X is a BLOB, it is hashed as is.
  1620. ** For all other non-NULL types of input, X is converted into a UTF-8 string
  1621. ** and the string is hashed without the trailing 0x00 terminator. The hash
  1622. ** of a NULL value is NULL.
  1623. */
  1624. static void sha3Func(
  1625. sqlite3_context *context,
  1626. int argc,
  1627. sqlite3_value **argv
  1628. ){
  1629. SHA3Context cx;
  1630. int eType = sqlite3_value_type(argv[0]);
  1631. int nByte = sqlite3_value_bytes(argv[0]);
  1632. int iSize;
  1633. if( argc==1 ){
  1634. iSize = 256;
  1635. }else{
  1636. iSize = sqlite3_value_int(argv[1]);
  1637. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1638. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1639. "384 512", -1);
  1640. return;
  1641. }
  1642. }
  1643. if( eType==SQLITE_NULL ) return;
  1644. SHA3Init(&cx, iSize);
  1645. if( eType==SQLITE_BLOB ){
  1646. SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
  1647. }else{
  1648. SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
  1649. }
  1650. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1651. }
  1652. /* Compute a string using sqlite3_vsnprintf() with a maximum length
  1653. ** of 50 bytes and add it to the hash.
  1654. */
  1655. static void hash_step_vformat(
  1656. SHA3Context *p, /* Add content to this context */
  1657. const char *zFormat,
  1658. ...
  1659. ){
  1660. va_list ap;
  1661. int n;
  1662. char zBuf[50];
  1663. va_start(ap, zFormat);
  1664. sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
  1665. va_end(ap);
  1666. n = (int)strlen(zBuf);
  1667. SHA3Update(p, (unsigned char*)zBuf, n);
  1668. }
  1669. /*
  1670. ** Implementation of the sha3_query(SQL,SIZE) function.
  1671. **
  1672. ** This function compiles and runs the SQL statement(s) given in the
  1673. ** argument. The results are hashed using a SIZE-bit SHA3. The default
  1674. ** size is 256.
  1675. **
  1676. ** The format of the byte stream that is hashed is summarized as follows:
  1677. **
  1678. ** S<n>:<sql>
  1679. ** R
  1680. ** N
  1681. ** I<int>
  1682. ** F<ieee-float>
  1683. ** B<size>:<bytes>
  1684. ** T<size>:<text>
  1685. **
  1686. ** <sql> is the original SQL text for each statement run and <n> is
  1687. ** the size of that text. The SQL text is UTF-8. A single R character
  1688. ** occurs before the start of each row. N means a NULL value.
  1689. ** I mean an 8-byte little-endian integer <int>. F is a floating point
  1690. ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
  1691. ** B means blobs of <size> bytes. T means text rendered as <size>
  1692. ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
  1693. ** text integers.
  1694. **
  1695. ** For each SQL statement in the X input, there is one S segment. Each
  1696. ** S segment is followed by zero or more R segments, one for each row in the
  1697. ** result set. After each R, there are one or more N, I, F, B, or T segments,
  1698. ** one for each column in the result set. Segments are concatentated directly
  1699. ** with no delimiters of any kind.
  1700. */
  1701. static void sha3QueryFunc(
  1702. sqlite3_context *context,
  1703. int argc,
  1704. sqlite3_value **argv
  1705. ){
  1706. sqlite3 *db = sqlite3_context_db_handle(context);
  1707. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  1708. sqlite3_stmt *pStmt = 0;
  1709. int nCol; /* Number of columns in the result set */
  1710. int i; /* Loop counter */
  1711. int rc;
  1712. int n;
  1713. const char *z;
  1714. SHA3Context cx;
  1715. int iSize;
  1716. if( argc==1 ){
  1717. iSize = 256;
  1718. }else{
  1719. iSize = sqlite3_value_int(argv[1]);
  1720. if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
  1721. sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
  1722. "384 512", -1);
  1723. return;
  1724. }
  1725. }
  1726. if( zSql==0 ) return;
  1727. SHA3Init(&cx, iSize);
  1728. while( zSql[0] ){
  1729. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
  1730. if( rc ){
  1731. char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
  1732. zSql, sqlite3_errmsg(db));
  1733. sqlite3_finalize(pStmt);
  1734. sqlite3_result_error(context, zMsg, -1);
  1735. sqlite3_free(zMsg);
  1736. return;
  1737. }
  1738. if( !sqlite3_stmt_readonly(pStmt) ){
  1739. char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
  1740. sqlite3_finalize(pStmt);
  1741. sqlite3_result_error(context, zMsg, -1);
  1742. sqlite3_free(zMsg);
  1743. return;
  1744. }
  1745. nCol = sqlite3_column_count(pStmt);
  1746. z = sqlite3_sql(pStmt);
  1747. n = (int)strlen(z);
  1748. hash_step_vformat(&cx,"S%d:",n);
  1749. SHA3Update(&cx,(unsigned char*)z,n);
  1750. /* Compute a hash over the result of the query */
  1751. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  1752. SHA3Update(&cx,(const unsigned char*)"R",1);
  1753. for(i=0; i<nCol; i++){
  1754. switch( sqlite3_column_type(pStmt,i) ){
  1755. case SQLITE_NULL: {
  1756. SHA3Update(&cx, (const unsigned char*)"N",1);
  1757. break;
  1758. }
  1759. case SQLITE_INTEGER: {
  1760. sqlite3_uint64 u;
  1761. int j;
  1762. unsigned char x[9];
  1763. sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
  1764. memcpy(&u, &v, 8);
  1765. for(j=8; j>=1; j--){
  1766. x[j] = u & 0xff;
  1767. u >>= 8;
  1768. }
  1769. x[0] = 'I';
  1770. SHA3Update(&cx, x, 9);
  1771. break;
  1772. }
  1773. case SQLITE_FLOAT: {
  1774. sqlite3_uint64 u;
  1775. int j;
  1776. unsigned char x[9];
  1777. double r = sqlite3_column_double(pStmt,i);
  1778. memcpy(&u, &r, 8);
  1779. for(j=8; j>=1; j--){
  1780. x[j] = u & 0xff;
  1781. u >>= 8;
  1782. }
  1783. x[0] = 'F';
  1784. SHA3Update(&cx,x,9);
  1785. break;
  1786. }
  1787. case SQLITE_TEXT: {
  1788. int n2 = sqlite3_column_bytes(pStmt, i);
  1789. const unsigned char *z2 = sqlite3_column_text(pStmt, i);
  1790. hash_step_vformat(&cx,"T%d:",n2);
  1791. SHA3Update(&cx, z2, n2);
  1792. break;
  1793. }
  1794. case SQLITE_BLOB: {
  1795. int n2 = sqlite3_column_bytes(pStmt, i);
  1796. const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
  1797. hash_step_vformat(&cx,"B%d:",n2);
  1798. SHA3Update(&cx, z2, n2);
  1799. break;
  1800. }
  1801. }
  1802. }
  1803. }
  1804. sqlite3_finalize(pStmt);
  1805. }
  1806. sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
  1807. }
  1808. #ifdef _WIN32
  1809. #endif
  1810. int sqlite3_shathree_init(
  1811. sqlite3 *db,
  1812. char **pzErrMsg,
  1813. const sqlite3_api_routines *pApi
  1814. ){
  1815. int rc = SQLITE_OK;
  1816. SQLITE_EXTENSION_INIT2(pApi);
  1817. (void)pzErrMsg; /* Unused parameter */
  1818. rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
  1819. sha3Func, 0, 0);
  1820. if( rc==SQLITE_OK ){
  1821. rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
  1822. sha3Func, 0, 0);
  1823. }
  1824. if( rc==SQLITE_OK ){
  1825. rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
  1826. sha3QueryFunc, 0, 0);
  1827. }
  1828. if( rc==SQLITE_OK ){
  1829. rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
  1830. sha3QueryFunc, 0, 0);
  1831. }
  1832. return rc;
  1833. }
  1834. /************************* End ../ext/misc/shathree.c ********************/
  1835. /************************* Begin ../ext/misc/fileio.c ******************/
  1836. /*
  1837. ** 2014-06-13
  1838. **
  1839. ** The author disclaims copyright to this source code. In place of
  1840. ** a legal notice, here is a blessing:
  1841. **
  1842. ** May you do good and not evil.
  1843. ** May you find forgiveness for yourself and forgive others.
  1844. ** May you share freely, never taking more than you give.
  1845. **
  1846. ******************************************************************************
  1847. **
  1848. ** This SQLite extension implements SQL functions readfile() and
  1849. ** writefile(), and eponymous virtual type "fsdir".
  1850. **
  1851. ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
  1852. **
  1853. ** If neither of the optional arguments is present, then this UDF
  1854. ** function writes blob DATA to file FILE. If successful, the number
  1855. ** of bytes written is returned. If an error occurs, NULL is returned.
  1856. **
  1857. ** If the first option argument - MODE - is present, then it must
  1858. ** be passed an integer value that corresponds to a POSIX mode
  1859. ** value (file type + permissions, as returned in the stat.st_mode
  1860. ** field by the stat() system call). Three types of files may
  1861. ** be written/created:
  1862. **
  1863. ** regular files: (mode & 0170000)==0100000
  1864. ** symbolic links: (mode & 0170000)==0120000
  1865. ** directories: (mode & 0170000)==0040000
  1866. **
  1867. ** For a directory, the DATA is ignored. For a symbolic link, it is
  1868. ** interpreted as text and used as the target of the link. For a
  1869. ** regular file, it is interpreted as a blob and written into the
  1870. ** named file. Regardless of the type of file, its permissions are
  1871. ** set to (mode & 0777) before returning.
  1872. **
  1873. ** If the optional MTIME argument is present, then it is interpreted
  1874. ** as an integer - the number of seconds since the unix epoch. The
  1875. ** modification-time of the target file is set to this value before
  1876. ** returning.
  1877. **
  1878. ** If three or more arguments are passed to this function and an
  1879. ** error is encountered, an exception is raised.
  1880. **
  1881. ** READFILE(FILE):
  1882. **
  1883. ** Read and return the contents of file FILE (type blob) from disk.
  1884. **
  1885. ** FSDIR:
  1886. **
  1887. ** Used as follows:
  1888. **
  1889. ** SELECT * FROM fsdir($path [, $dir]);
  1890. **
  1891. ** Parameter $path is an absolute or relative pathname. If the file that it
  1892. ** refers to does not exist, it is an error. If the path refers to a regular
  1893. ** file or symbolic link, it returns a single row. Or, if the path refers
  1894. ** to a directory, it returns one row for the directory, and one row for each
  1895. ** file within the hierarchy rooted at $path.
  1896. **
  1897. ** Each row has the following columns:
  1898. **
  1899. ** name: Path to file or directory (text value).
  1900. ** mode: Value of stat.st_mode for directory entry (an integer).
  1901. ** mtime: Value of stat.st_mtime for directory entry (an integer).
  1902. ** data: For a regular file, a blob containing the file data. For a
  1903. ** symlink, a text value containing the text of the link. For a
  1904. ** directory, NULL.
  1905. **
  1906. ** If a non-NULL value is specified for the optional $dir parameter and
  1907. ** $path is a relative path, then $path is interpreted relative to $dir.
  1908. ** And the paths returned in the "name" column of the table are also
  1909. ** relative to directory $dir.
  1910. */
  1911. SQLITE_EXTENSION_INIT1
  1912. #include <stdio.h>
  1913. #include <string.h>
  1914. #include <assert.h>
  1915. #include <sys/types.h>
  1916. #include <sys/stat.h>
  1917. #include <fcntl.h>
  1918. #if !defined(_WIN32) && !defined(WIN32)
  1919. # include <unistd.h>
  1920. # include <dirent.h>
  1921. # include <utime.h>
  1922. # include <sys/time.h>
  1923. #else
  1924. # include "windows.h"
  1925. # include <io.h>
  1926. # include <direct.h>
  1927. /* # include "test_windirent.h" */
  1928. # define dirent DIRENT
  1929. # ifndef chmod
  1930. # define chmod _chmod
  1931. # endif
  1932. # ifndef stat
  1933. # define stat _stat
  1934. # endif
  1935. # define mkdir(path,mode) _mkdir(path)
  1936. # define lstat(path,buf) stat(path,buf)
  1937. #endif
  1938. #include <time.h>
  1939. #include <errno.h>
  1940. #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
  1941. /*
  1942. ** Set the result stored by context ctx to a blob containing the
  1943. ** contents of file zName.
  1944. */
  1945. static void readFileContents(sqlite3_context *ctx, const char *zName){
  1946. FILE *in;
  1947. long nIn;
  1948. void *pBuf;
  1949. in = fopen(zName, "rb");
  1950. if( in==0 ) return;
  1951. fseek(in, 0, SEEK_END);
  1952. nIn = ftell(in);
  1953. rewind(in);
  1954. pBuf = sqlite3_malloc( nIn );
  1955. if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
  1956. sqlite3_result_blob(ctx, pBuf, nIn, sqlite3_free);
  1957. }else{
  1958. sqlite3_free(pBuf);
  1959. }
  1960. fclose(in);
  1961. }
  1962. /*
  1963. ** Implementation of the "readfile(X)" SQL function. The entire content
  1964. ** of the file named X is read and returned as a BLOB. NULL is returned
  1965. ** if the file does not exist or is unreadable.
  1966. */
  1967. static void readfileFunc(
  1968. sqlite3_context *context,
  1969. int argc,
  1970. sqlite3_value **argv
  1971. ){
  1972. const char *zName;
  1973. (void)(argc); /* Unused parameter */
  1974. zName = (const char*)sqlite3_value_text(argv[0]);
  1975. if( zName==0 ) return;
  1976. readFileContents(context, zName);
  1977. }
  1978. /*
  1979. ** Set the error message contained in context ctx to the results of
  1980. ** vprintf(zFmt, ...).
  1981. */
  1982. static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  1983. char *zMsg = 0;
  1984. va_list ap;
  1985. va_start(ap, zFmt);
  1986. zMsg = sqlite3_vmprintf(zFmt, ap);
  1987. sqlite3_result_error(ctx, zMsg, -1);
  1988. sqlite3_free(zMsg);
  1989. va_end(ap);
  1990. }
  1991. #if defined(_WIN32)
  1992. /*
  1993. ** This function is designed to convert a Win32 FILETIME structure into the
  1994. ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
  1995. */
  1996. static sqlite3_uint64 fileTimeToUnixTime(
  1997. LPFILETIME pFileTime
  1998. ){
  1999. SYSTEMTIME epochSystemTime;
  2000. ULARGE_INTEGER epochIntervals;
  2001. FILETIME epochFileTime;
  2002. ULARGE_INTEGER fileIntervals;
  2003. memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
  2004. epochSystemTime.wYear = 1970;
  2005. epochSystemTime.wMonth = 1;
  2006. epochSystemTime.wDay = 1;
  2007. SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
  2008. epochIntervals.LowPart = epochFileTime.dwLowDateTime;
  2009. epochIntervals.HighPart = epochFileTime.dwHighDateTime;
  2010. fileIntervals.LowPart = pFileTime->dwLowDateTime;
  2011. fileIntervals.HighPart = pFileTime->dwHighDateTime;
  2012. return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
  2013. }
  2014. /*
  2015. ** This function attempts to normalize the time values found in the stat()
  2016. ** buffer to UTC. This is necessary on Win32, where the runtime library
  2017. ** appears to return these values as local times.
  2018. */
  2019. static void statTimesToUtc(
  2020. const char *zPath,
  2021. struct stat *pStatBuf
  2022. ){
  2023. HANDLE hFindFile;
  2024. WIN32_FIND_DATAW fd;
  2025. LPWSTR zUnicodeName;
  2026. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2027. zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
  2028. if( zUnicodeName ){
  2029. memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
  2030. hFindFile = FindFirstFileW(zUnicodeName, &fd);
  2031. if( hFindFile!=NULL ){
  2032. pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
  2033. pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
  2034. pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
  2035. FindClose(hFindFile);
  2036. }
  2037. sqlite3_free(zUnicodeName);
  2038. }
  2039. }
  2040. #endif
  2041. /*
  2042. ** This function is used in place of stat(). On Windows, special handling
  2043. ** is required in order for the included time to be returned as UTC. On all
  2044. ** other systems, this function simply calls stat().
  2045. */
  2046. static int fileStat(
  2047. const char *zPath,
  2048. struct stat *pStatBuf
  2049. ){
  2050. #if defined(_WIN32)
  2051. int rc = stat(zPath, pStatBuf);
  2052. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2053. return rc;
  2054. #else
  2055. return stat(zPath, pStatBuf);
  2056. #endif
  2057. }
  2058. /*
  2059. ** This function is used in place of lstat(). On Windows, special handling
  2060. ** is required in order for the included time to be returned as UTC. On all
  2061. ** other systems, this function simply calls lstat().
  2062. */
  2063. static int fileLinkStat(
  2064. const char *zPath,
  2065. struct stat *pStatBuf
  2066. ){
  2067. #if defined(_WIN32)
  2068. int rc = lstat(zPath, pStatBuf);
  2069. if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
  2070. return rc;
  2071. #else
  2072. return lstat(zPath, pStatBuf);
  2073. #endif
  2074. }
  2075. /*
  2076. ** Argument zFile is the name of a file that will be created and/or written
  2077. ** by SQL function writefile(). This function ensures that the directory
  2078. ** zFile will be written to exists, creating it if required. The permissions
  2079. ** for any path components created by this function are set to (mode&0777).
  2080. **
  2081. ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
  2082. ** SQLITE_OK is returned if the directory is successfully created, or
  2083. ** SQLITE_ERROR otherwise.
  2084. */
  2085. static int makeDirectory(
  2086. const char *zFile,
  2087. mode_t mode
  2088. ){
  2089. char *zCopy = sqlite3_mprintf("%s", zFile);
  2090. int rc = SQLITE_OK;
  2091. if( zCopy==0 ){
  2092. rc = SQLITE_NOMEM;
  2093. }else{
  2094. int nCopy = (int)strlen(zCopy);
  2095. int i = 1;
  2096. while( rc==SQLITE_OK ){
  2097. struct stat sStat;
  2098. int rc2;
  2099. for(; zCopy[i]!='/' && i<nCopy; i++);
  2100. if( i==nCopy ) break;
  2101. zCopy[i] = '\0';
  2102. rc2 = fileStat(zCopy, &sStat);
  2103. if( rc2!=0 ){
  2104. if( mkdir(zCopy, mode & 0777) ) rc = SQLITE_ERROR;
  2105. }else{
  2106. if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
  2107. }
  2108. zCopy[i] = '/';
  2109. i++;
  2110. }
  2111. sqlite3_free(zCopy);
  2112. }
  2113. return rc;
  2114. }
  2115. /*
  2116. ** This function does the work for the writefile() UDF. Refer to
  2117. ** header comments at the top of this file for details.
  2118. */
  2119. static int writeFile(
  2120. sqlite3_context *pCtx, /* Context to return bytes written in */
  2121. const char *zFile, /* File to write */
  2122. sqlite3_value *pData, /* Data to write */
  2123. mode_t mode, /* MODE parameter passed to writefile() */
  2124. sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */
  2125. ){
  2126. #if !defined(_WIN32) && !defined(WIN32)
  2127. if( S_ISLNK(mode) ){
  2128. const char *zTo = (const char*)sqlite3_value_text(pData);
  2129. if( symlink(zTo, zFile)<0 ) return 1;
  2130. }else
  2131. #endif
  2132. {
  2133. if( S_ISDIR(mode) ){
  2134. if( mkdir(zFile, mode) ){
  2135. /* The mkdir() call to create the directory failed. This might not
  2136. ** be an error though - if there is already a directory at the same
  2137. ** path and either the permissions already match or can be changed
  2138. ** to do so using chmod(), it is not an error. */
  2139. struct stat sStat;
  2140. if( errno!=EEXIST
  2141. || 0!=fileStat(zFile, &sStat)
  2142. || !S_ISDIR(sStat.st_mode)
  2143. || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
  2144. ){
  2145. return 1;
  2146. }
  2147. }
  2148. }else{
  2149. sqlite3_int64 nWrite = 0;
  2150. const char *z;
  2151. int rc = 0;
  2152. FILE *out = fopen(zFile, "wb");
  2153. if( out==0 ) return 1;
  2154. z = (const char*)sqlite3_value_blob(pData);
  2155. if( z ){
  2156. sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
  2157. nWrite = sqlite3_value_bytes(pData);
  2158. if( nWrite!=n ){
  2159. rc = 1;
  2160. }
  2161. }
  2162. fclose(out);
  2163. if( rc==0 && mode && chmod(zFile, mode & 0777) ){
  2164. rc = 1;
  2165. }
  2166. if( rc ) return 2;
  2167. sqlite3_result_int64(pCtx, nWrite);
  2168. }
  2169. }
  2170. if( mtime>=0 ){
  2171. #if defined(_WIN32)
  2172. /* Windows */
  2173. FILETIME lastAccess;
  2174. FILETIME lastWrite;
  2175. SYSTEMTIME currentTime;
  2176. LONGLONG intervals;
  2177. HANDLE hFile;
  2178. LPWSTR zUnicodeName;
  2179. extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
  2180. GetSystemTime(&currentTime);
  2181. SystemTimeToFileTime(&currentTime, &lastAccess);
  2182. intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
  2183. lastWrite.dwLowDateTime = (DWORD)intervals;
  2184. lastWrite.dwHighDateTime = intervals >> 32;
  2185. zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
  2186. if( zUnicodeName==0 ){
  2187. return 1;
  2188. }
  2189. hFile = CreateFileW(
  2190. zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
  2191. FILE_FLAG_BACKUP_SEMANTICS, NULL
  2192. );
  2193. sqlite3_free(zUnicodeName);
  2194. if( hFile!=INVALID_HANDLE_VALUE ){
  2195. BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
  2196. CloseHandle(hFile);
  2197. return !bResult;
  2198. }else{
  2199. return 1;
  2200. }
  2201. #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
  2202. /* Recent unix */
  2203. struct timespec times[2];
  2204. times[0].tv_nsec = times[1].tv_nsec = 0;
  2205. times[0].tv_sec = time(0);
  2206. times[1].tv_sec = mtime;
  2207. if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
  2208. return 1;
  2209. }
  2210. #else
  2211. /* Legacy unix */
  2212. struct timeval times[2];
  2213. times[0].tv_usec = times[1].tv_usec = 0;
  2214. times[0].tv_sec = time(0);
  2215. times[1].tv_sec = mtime;
  2216. if( utimes(zFile, times) ){
  2217. return 1;
  2218. }
  2219. #endif
  2220. }
  2221. return 0;
  2222. }
  2223. /*
  2224. ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
  2225. ** Refer to header comments at the top of this file for details.
  2226. */
  2227. static void writefileFunc(
  2228. sqlite3_context *context,
  2229. int argc,
  2230. sqlite3_value **argv
  2231. ){
  2232. const char *zFile;
  2233. mode_t mode = 0;
  2234. int res;
  2235. sqlite3_int64 mtime = -1;
  2236. if( argc<2 || argc>4 ){
  2237. sqlite3_result_error(context,
  2238. "wrong number of arguments to function writefile()", -1
  2239. );
  2240. return;
  2241. }
  2242. zFile = (const char*)sqlite3_value_text(argv[0]);
  2243. if( zFile==0 ) return;
  2244. if( argc>=3 ){
  2245. mode = (mode_t)sqlite3_value_int(argv[2]);
  2246. }
  2247. if( argc==4 ){
  2248. mtime = sqlite3_value_int64(argv[3]);
  2249. }
  2250. res = writeFile(context, zFile, argv[1], mode, mtime);
  2251. if( res==1 && errno==ENOENT ){
  2252. if( makeDirectory(zFile, mode)==SQLITE_OK ){
  2253. res = writeFile(context, zFile, argv[1], mode, mtime);
  2254. }
  2255. }
  2256. if( argc>2 && res!=0 ){
  2257. if( S_ISLNK(mode) ){
  2258. ctxErrorMsg(context, "failed to create symlink: %s", zFile);
  2259. }else if( S_ISDIR(mode) ){
  2260. ctxErrorMsg(context, "failed to create directory: %s", zFile);
  2261. }else{
  2262. ctxErrorMsg(context, "failed to write file: %s", zFile);
  2263. }
  2264. }
  2265. }
  2266. /*
  2267. ** SQL function: lsmode(MODE)
  2268. **
  2269. ** Given a numberic st_mode from stat(), convert it into a human-readable
  2270. ** text string in the style of "ls -l".
  2271. */
  2272. static void lsModeFunc(
  2273. sqlite3_context *context,
  2274. int argc,
  2275. sqlite3_value **argv
  2276. ){
  2277. int i;
  2278. int iMode = sqlite3_value_int(argv[0]);
  2279. char z[16];
  2280. (void)argc;
  2281. if( S_ISLNK(iMode) ){
  2282. z[0] = 'l';
  2283. }else if( S_ISREG(iMode) ){
  2284. z[0] = '-';
  2285. }else if( S_ISDIR(iMode) ){
  2286. z[0] = 'd';
  2287. }else{
  2288. z[0] = '?';
  2289. }
  2290. for(i=0; i<3; i++){
  2291. int m = (iMode >> ((2-i)*3));
  2292. char *a = &z[1 + i*3];
  2293. a[0] = (m & 0x4) ? 'r' : '-';
  2294. a[1] = (m & 0x2) ? 'w' : '-';
  2295. a[2] = (m & 0x1) ? 'x' : '-';
  2296. }
  2297. z[10] = '\0';
  2298. sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
  2299. }
  2300. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2301. /*
  2302. ** Cursor type for recursively iterating through a directory structure.
  2303. */
  2304. typedef struct fsdir_cursor fsdir_cursor;
  2305. typedef struct FsdirLevel FsdirLevel;
  2306. struct FsdirLevel {
  2307. DIR *pDir; /* From opendir() */
  2308. char *zDir; /* Name of directory (nul-terminated) */
  2309. };
  2310. struct fsdir_cursor {
  2311. sqlite3_vtab_cursor base; /* Base class - must be first */
  2312. int nLvl; /* Number of entries in aLvl[] array */
  2313. int iLvl; /* Index of current entry */
  2314. FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
  2315. const char *zBase;
  2316. int nBase;
  2317. struct stat sStat; /* Current lstat() results */
  2318. char *zPath; /* Path to current entry */
  2319. sqlite3_int64 iRowid; /* Current rowid */
  2320. };
  2321. typedef struct fsdir_tab fsdir_tab;
  2322. struct fsdir_tab {
  2323. sqlite3_vtab base; /* Base class - must be first */
  2324. };
  2325. /*
  2326. ** Construct a new fsdir virtual table object.
  2327. */
  2328. static int fsdirConnect(
  2329. sqlite3 *db,
  2330. void *pAux,
  2331. int argc, const char *const*argv,
  2332. sqlite3_vtab **ppVtab,
  2333. char **pzErr
  2334. ){
  2335. fsdir_tab *pNew = 0;
  2336. int rc;
  2337. (void)pAux;
  2338. (void)argc;
  2339. (void)argv;
  2340. (void)pzErr;
  2341. rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
  2342. if( rc==SQLITE_OK ){
  2343. pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
  2344. if( pNew==0 ) return SQLITE_NOMEM;
  2345. memset(pNew, 0, sizeof(*pNew));
  2346. }
  2347. *ppVtab = (sqlite3_vtab*)pNew;
  2348. return rc;
  2349. }
  2350. /*
  2351. ** This method is the destructor for fsdir vtab objects.
  2352. */
  2353. static int fsdirDisconnect(sqlite3_vtab *pVtab){
  2354. sqlite3_free(pVtab);
  2355. return SQLITE_OK;
  2356. }
  2357. /*
  2358. ** Constructor for a new fsdir_cursor object.
  2359. */
  2360. static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2361. fsdir_cursor *pCur;
  2362. (void)p;
  2363. pCur = sqlite3_malloc( sizeof(*pCur) );
  2364. if( pCur==0 ) return SQLITE_NOMEM;
  2365. memset(pCur, 0, sizeof(*pCur));
  2366. pCur->iLvl = -1;
  2367. *ppCursor = &pCur->base;
  2368. return SQLITE_OK;
  2369. }
  2370. /*
  2371. ** Reset a cursor back to the state it was in when first returned
  2372. ** by fsdirOpen().
  2373. */
  2374. static void fsdirResetCursor(fsdir_cursor *pCur){
  2375. int i;
  2376. for(i=0; i<=pCur->iLvl; i++){
  2377. FsdirLevel *pLvl = &pCur->aLvl[i];
  2378. if( pLvl->pDir ) closedir(pLvl->pDir);
  2379. sqlite3_free(pLvl->zDir);
  2380. }
  2381. sqlite3_free(pCur->zPath);
  2382. sqlite3_free(pCur->aLvl);
  2383. pCur->aLvl = 0;
  2384. pCur->zPath = 0;
  2385. pCur->zBase = 0;
  2386. pCur->nBase = 0;
  2387. pCur->nLvl = 0;
  2388. pCur->iLvl = -1;
  2389. pCur->iRowid = 1;
  2390. }
  2391. /*
  2392. ** Destructor for an fsdir_cursor.
  2393. */
  2394. static int fsdirClose(sqlite3_vtab_cursor *cur){
  2395. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2396. fsdirResetCursor(pCur);
  2397. sqlite3_free(pCur);
  2398. return SQLITE_OK;
  2399. }
  2400. /*
  2401. ** Set the error message for the virtual table associated with cursor
  2402. ** pCur to the results of vprintf(zFmt, ...).
  2403. */
  2404. static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
  2405. va_list ap;
  2406. va_start(ap, zFmt);
  2407. pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  2408. va_end(ap);
  2409. }
  2410. /*
  2411. ** Advance an fsdir_cursor to its next row of output.
  2412. */
  2413. static int fsdirNext(sqlite3_vtab_cursor *cur){
  2414. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2415. mode_t m = pCur->sStat.st_mode;
  2416. pCur->iRowid++;
  2417. if( S_ISDIR(m) ){
  2418. /* Descend into this directory */
  2419. int iNew = pCur->iLvl + 1;
  2420. FsdirLevel *pLvl;
  2421. if( iNew>=pCur->nLvl ){
  2422. int nNew = iNew+1;
  2423. int nByte = nNew*sizeof(FsdirLevel);
  2424. FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc(pCur->aLvl, nByte);
  2425. if( aNew==0 ) return SQLITE_NOMEM;
  2426. memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
  2427. pCur->aLvl = aNew;
  2428. pCur->nLvl = nNew;
  2429. }
  2430. pCur->iLvl = iNew;
  2431. pLvl = &pCur->aLvl[iNew];
  2432. pLvl->zDir = pCur->zPath;
  2433. pCur->zPath = 0;
  2434. pLvl->pDir = opendir(pLvl->zDir);
  2435. if( pLvl->pDir==0 ){
  2436. fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
  2437. return SQLITE_ERROR;
  2438. }
  2439. }
  2440. while( pCur->iLvl>=0 ){
  2441. FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
  2442. struct dirent *pEntry = readdir(pLvl->pDir);
  2443. if( pEntry ){
  2444. if( pEntry->d_name[0]=='.' ){
  2445. if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
  2446. if( pEntry->d_name[1]=='\0' ) continue;
  2447. }
  2448. sqlite3_free(pCur->zPath);
  2449. pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
  2450. if( pCur->zPath==0 ) return SQLITE_NOMEM;
  2451. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2452. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2453. return SQLITE_ERROR;
  2454. }
  2455. return SQLITE_OK;
  2456. }
  2457. closedir(pLvl->pDir);
  2458. sqlite3_free(pLvl->zDir);
  2459. pLvl->pDir = 0;
  2460. pLvl->zDir = 0;
  2461. pCur->iLvl--;
  2462. }
  2463. /* EOF */
  2464. sqlite3_free(pCur->zPath);
  2465. pCur->zPath = 0;
  2466. return SQLITE_OK;
  2467. }
  2468. /*
  2469. ** Return values of columns for the row at which the series_cursor
  2470. ** is currently pointing.
  2471. */
  2472. static int fsdirColumn(
  2473. sqlite3_vtab_cursor *cur, /* The cursor */
  2474. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  2475. int i /* Which column to return */
  2476. ){
  2477. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2478. switch( i ){
  2479. case 0: { /* name */
  2480. sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
  2481. break;
  2482. }
  2483. case 1: /* mode */
  2484. sqlite3_result_int64(ctx, pCur->sStat.st_mode);
  2485. break;
  2486. case 2: /* mtime */
  2487. sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
  2488. break;
  2489. case 3: { /* data */
  2490. mode_t m = pCur->sStat.st_mode;
  2491. if( S_ISDIR(m) ){
  2492. sqlite3_result_null(ctx);
  2493. #if !defined(_WIN32) && !defined(WIN32)
  2494. }else if( S_ISLNK(m) ){
  2495. char aStatic[64];
  2496. char *aBuf = aStatic;
  2497. int nBuf = 64;
  2498. int n;
  2499. while( 1 ){
  2500. n = readlink(pCur->zPath, aBuf, nBuf);
  2501. if( n<nBuf ) break;
  2502. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2503. nBuf = nBuf*2;
  2504. aBuf = sqlite3_malloc(nBuf);
  2505. if( aBuf==0 ){
  2506. sqlite3_result_error_nomem(ctx);
  2507. return SQLITE_NOMEM;
  2508. }
  2509. }
  2510. sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
  2511. if( aBuf!=aStatic ) sqlite3_free(aBuf);
  2512. #endif
  2513. }else{
  2514. readFileContents(ctx, pCur->zPath);
  2515. }
  2516. }
  2517. }
  2518. return SQLITE_OK;
  2519. }
  2520. /*
  2521. ** Return the rowid for the current row. In this implementation, the
  2522. ** first row returned is assigned rowid value 1, and each subsequent
  2523. ** row a value 1 more than that of the previous.
  2524. */
  2525. static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  2526. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2527. *pRowid = pCur->iRowid;
  2528. return SQLITE_OK;
  2529. }
  2530. /*
  2531. ** Return TRUE if the cursor has been moved off of the last
  2532. ** row of output.
  2533. */
  2534. static int fsdirEof(sqlite3_vtab_cursor *cur){
  2535. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2536. return (pCur->zPath==0);
  2537. }
  2538. /*
  2539. ** xFilter callback.
  2540. */
  2541. static int fsdirFilter(
  2542. sqlite3_vtab_cursor *cur,
  2543. int idxNum, const char *idxStr,
  2544. int argc, sqlite3_value **argv
  2545. ){
  2546. const char *zDir = 0;
  2547. fsdir_cursor *pCur = (fsdir_cursor*)cur;
  2548. (void)idxStr;
  2549. fsdirResetCursor(pCur);
  2550. if( idxNum==0 ){
  2551. fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
  2552. return SQLITE_ERROR;
  2553. }
  2554. assert( argc==idxNum && (argc==1 || argc==2) );
  2555. zDir = (const char*)sqlite3_value_text(argv[0]);
  2556. if( zDir==0 ){
  2557. fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
  2558. return SQLITE_ERROR;
  2559. }
  2560. if( argc==2 ){
  2561. pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
  2562. }
  2563. if( pCur->zBase ){
  2564. pCur->nBase = (int)strlen(pCur->zBase)+1;
  2565. pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
  2566. }else{
  2567. pCur->zPath = sqlite3_mprintf("%s", zDir);
  2568. }
  2569. if( pCur->zPath==0 ){
  2570. return SQLITE_NOMEM;
  2571. }
  2572. if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
  2573. fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
  2574. return SQLITE_ERROR;
  2575. }
  2576. return SQLITE_OK;
  2577. }
  2578. /*
  2579. ** SQLite will invoke this method one or more times while planning a query
  2580. ** that uses the generate_series virtual table. This routine needs to create
  2581. ** a query plan for each invocation and compute an estimated cost for that
  2582. ** plan.
  2583. **
  2584. ** In this implementation idxNum is used to represent the
  2585. ** query plan. idxStr is unused.
  2586. **
  2587. ** The query plan is represented by bits in idxNum:
  2588. **
  2589. ** (1) start = $value -- constraint exists
  2590. ** (2) stop = $value -- constraint exists
  2591. ** (4) step = $value -- constraint exists
  2592. ** (8) output in descending order
  2593. */
  2594. static int fsdirBestIndex(
  2595. sqlite3_vtab *tab,
  2596. sqlite3_index_info *pIdxInfo
  2597. ){
  2598. int i; /* Loop over constraints */
  2599. int idx4 = -1;
  2600. int idx5 = -1;
  2601. const struct sqlite3_index_constraint *pConstraint;
  2602. (void)tab;
  2603. pConstraint = pIdxInfo->aConstraint;
  2604. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  2605. if( pConstraint->usable==0 ) continue;
  2606. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  2607. if( pConstraint->iColumn==4 ) idx4 = i;
  2608. if( pConstraint->iColumn==5 ) idx5 = i;
  2609. }
  2610. if( idx4<0 ){
  2611. pIdxInfo->idxNum = 0;
  2612. pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
  2613. }else{
  2614. pIdxInfo->aConstraintUsage[idx4].omit = 1;
  2615. pIdxInfo->aConstraintUsage[idx4].argvIndex = 1;
  2616. if( idx5>=0 ){
  2617. pIdxInfo->aConstraintUsage[idx5].omit = 1;
  2618. pIdxInfo->aConstraintUsage[idx5].argvIndex = 2;
  2619. pIdxInfo->idxNum = 2;
  2620. pIdxInfo->estimatedCost = 10.0;
  2621. }else{
  2622. pIdxInfo->idxNum = 1;
  2623. pIdxInfo->estimatedCost = 100.0;
  2624. }
  2625. }
  2626. return SQLITE_OK;
  2627. }
  2628. /*
  2629. ** Register the "fsdir" virtual table.
  2630. */
  2631. static int fsdirRegister(sqlite3 *db){
  2632. static sqlite3_module fsdirModule = {
  2633. 0, /* iVersion */
  2634. 0, /* xCreate */
  2635. fsdirConnect, /* xConnect */
  2636. fsdirBestIndex, /* xBestIndex */
  2637. fsdirDisconnect, /* xDisconnect */
  2638. 0, /* xDestroy */
  2639. fsdirOpen, /* xOpen - open a cursor */
  2640. fsdirClose, /* xClose - close a cursor */
  2641. fsdirFilter, /* xFilter - configure scan constraints */
  2642. fsdirNext, /* xNext - advance a cursor */
  2643. fsdirEof, /* xEof - check for end of scan */
  2644. fsdirColumn, /* xColumn - read data */
  2645. fsdirRowid, /* xRowid - read data */
  2646. 0, /* xUpdate */
  2647. 0, /* xBegin */
  2648. 0, /* xSync */
  2649. 0, /* xCommit */
  2650. 0, /* xRollback */
  2651. 0, /* xFindMethod */
  2652. 0, /* xRename */
  2653. 0, /* xSavepoint */
  2654. 0, /* xRelease */
  2655. 0 /* xRollbackTo */
  2656. };
  2657. int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
  2658. return rc;
  2659. }
  2660. #else /* SQLITE_OMIT_VIRTUALTABLE */
  2661. # define fsdirRegister(x) SQLITE_OK
  2662. #endif
  2663. #ifdef _WIN32
  2664. #endif
  2665. int sqlite3_fileio_init(
  2666. sqlite3 *db,
  2667. char **pzErrMsg,
  2668. const sqlite3_api_routines *pApi
  2669. ){
  2670. int rc = SQLITE_OK;
  2671. SQLITE_EXTENSION_INIT2(pApi);
  2672. (void)pzErrMsg; /* Unused parameter */
  2673. rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
  2674. readfileFunc, 0, 0);
  2675. if( rc==SQLITE_OK ){
  2676. rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
  2677. writefileFunc, 0, 0);
  2678. }
  2679. if( rc==SQLITE_OK ){
  2680. rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
  2681. lsModeFunc, 0, 0);
  2682. }
  2683. if( rc==SQLITE_OK ){
  2684. rc = fsdirRegister(db);
  2685. }
  2686. return rc;
  2687. }
  2688. /************************* End ../ext/misc/fileio.c ********************/
  2689. /************************* Begin ../ext/misc/completion.c ******************/
  2690. /*
  2691. ** 2017-07-10
  2692. **
  2693. ** The author disclaims copyright to this source code. In place of
  2694. ** a legal notice, here is a blessing:
  2695. **
  2696. ** May you do good and not evil.
  2697. ** May you find forgiveness for yourself and forgive others.
  2698. ** May you share freely, never taking more than you give.
  2699. **
  2700. *************************************************************************
  2701. **
  2702. ** This file implements an eponymous virtual table that returns suggested
  2703. ** completions for a partial SQL input.
  2704. **
  2705. ** Suggested usage:
  2706. **
  2707. ** SELECT DISTINCT candidate COLLATE nocase
  2708. ** FROM completion($prefix,$wholeline)
  2709. ** ORDER BY 1;
  2710. **
  2711. ** The two query parameters are optional. $prefix is the text of the
  2712. ** current word being typed and that is to be completed. $wholeline is
  2713. ** the complete input line, used for context.
  2714. **
  2715. ** The raw completion() table might return the same candidate multiple
  2716. ** times, for example if the same column name is used to two or more
  2717. ** tables. And the candidates are returned in an arbitrary order. Hence,
  2718. ** the DISTINCT and ORDER BY are recommended.
  2719. **
  2720. ** This virtual table operates at the speed of human typing, and so there
  2721. ** is no attempt to make it fast. Even a slow implementation will be much
  2722. ** faster than any human can type.
  2723. **
  2724. */
  2725. SQLITE_EXTENSION_INIT1
  2726. #include <assert.h>
  2727. #include <string.h>
  2728. #include <ctype.h>
  2729. #ifndef SQLITE_OMIT_VIRTUALTABLE
  2730. /* completion_vtab is a subclass of sqlite3_vtab which will
  2731. ** serve as the underlying representation of a completion virtual table
  2732. */
  2733. typedef struct completion_vtab completion_vtab;
  2734. struct completion_vtab {
  2735. sqlite3_vtab base; /* Base class - must be first */
  2736. sqlite3 *db; /* Database connection for this completion vtab */
  2737. };
  2738. /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
  2739. ** serve as the underlying representation of a cursor that scans
  2740. ** over rows of the result
  2741. */
  2742. typedef struct completion_cursor completion_cursor;
  2743. struct completion_cursor {
  2744. sqlite3_vtab_cursor base; /* Base class - must be first */
  2745. sqlite3 *db; /* Database connection for this cursor */
  2746. int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
  2747. char *zPrefix; /* The prefix for the word we want to complete */
  2748. char *zLine; /* The whole that we want to complete */
  2749. const char *zCurrentRow; /* Current output row */
  2750. int szRow; /* Length of the zCurrentRow string */
  2751. sqlite3_stmt *pStmt; /* Current statement */
  2752. sqlite3_int64 iRowid; /* The rowid */
  2753. int ePhase; /* Current phase */
  2754. int j; /* inter-phase counter */
  2755. };
  2756. /* Values for ePhase:
  2757. */
  2758. #define COMPLETION_FIRST_PHASE 1
  2759. #define COMPLETION_KEYWORDS 1
  2760. #define COMPLETION_PRAGMAS 2
  2761. #define COMPLETION_FUNCTIONS 3
  2762. #define COMPLETION_COLLATIONS 4
  2763. #define COMPLETION_INDEXES 5
  2764. #define COMPLETION_TRIGGERS 6
  2765. #define COMPLETION_DATABASES 7
  2766. #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
  2767. #define COMPLETION_COLUMNS 9
  2768. #define COMPLETION_MODULES 10
  2769. #define COMPLETION_EOF 11
  2770. /*
  2771. ** The completionConnect() method is invoked to create a new
  2772. ** completion_vtab that describes the completion virtual table.
  2773. **
  2774. ** Think of this routine as the constructor for completion_vtab objects.
  2775. **
  2776. ** All this routine needs to do is:
  2777. **
  2778. ** (1) Allocate the completion_vtab object and initialize all fields.
  2779. **
  2780. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  2781. ** result set of queries against completion will look like.
  2782. */
  2783. static int completionConnect(
  2784. sqlite3 *db,
  2785. void *pAux,
  2786. int argc, const char *const*argv,
  2787. sqlite3_vtab **ppVtab,
  2788. char **pzErr
  2789. ){
  2790. completion_vtab *pNew;
  2791. int rc;
  2792. (void)(pAux); /* Unused parameter */
  2793. (void)(argc); /* Unused parameter */
  2794. (void)(argv); /* Unused parameter */
  2795. (void)(pzErr); /* Unused parameter */
  2796. /* Column numbers */
  2797. #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
  2798. #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
  2799. #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
  2800. #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
  2801. rc = sqlite3_declare_vtab(db,
  2802. "CREATE TABLE x("
  2803. " candidate TEXT,"
  2804. " prefix TEXT HIDDEN,"
  2805. " wholeline TEXT HIDDEN,"
  2806. " phase INT HIDDEN" /* Used for debugging only */
  2807. ")");
  2808. if( rc==SQLITE_OK ){
  2809. pNew = sqlite3_malloc( sizeof(*pNew) );
  2810. *ppVtab = (sqlite3_vtab*)pNew;
  2811. if( pNew==0 ) return SQLITE_NOMEM;
  2812. memset(pNew, 0, sizeof(*pNew));
  2813. pNew->db = db;
  2814. }
  2815. return rc;
  2816. }
  2817. /*
  2818. ** This method is the destructor for completion_cursor objects.
  2819. */
  2820. static int completionDisconnect(sqlite3_vtab *pVtab){
  2821. sqlite3_free(pVtab);
  2822. return SQLITE_OK;
  2823. }
  2824. /*
  2825. ** Constructor for a new completion_cursor object.
  2826. */
  2827. static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  2828. completion_cursor *pCur;
  2829. pCur = sqlite3_malloc( sizeof(*pCur) );
  2830. if( pCur==0 ) return SQLITE_NOMEM;
  2831. memset(pCur, 0, sizeof(*pCur));
  2832. pCur->db = ((completion_vtab*)p)->db;
  2833. *ppCursor = &pCur->base;
  2834. return SQLITE_OK;
  2835. }
  2836. /*
  2837. ** Reset the completion_cursor.
  2838. */
  2839. static void completionCursorReset(completion_cursor *pCur){
  2840. sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
  2841. sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
  2842. sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
  2843. pCur->j = 0;
  2844. }
  2845. /*
  2846. ** Destructor for a completion_cursor.
  2847. */
  2848. static int completionClose(sqlite3_vtab_cursor *cur){
  2849. completionCursorReset((completion_cursor*)cur);
  2850. sqlite3_free(cur);
  2851. return SQLITE_OK;
  2852. }
  2853. /*
  2854. ** Advance a completion_cursor to its next row of output.
  2855. **
  2856. ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
  2857. ** record the current state of the scan. This routine sets ->zCurrentRow
  2858. ** to the current row of output and then returns. If no more rows remain,
  2859. ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
  2860. ** table that has reached the end of its scan.
  2861. **
  2862. ** The current implementation just lists potential identifiers and
  2863. ** keywords and filters them by zPrefix. Future enhancements should
  2864. ** take zLine into account to try to restrict the set of identifiers and
  2865. ** keywords based on what would be legal at the current point of input.
  2866. */
  2867. static int completionNext(sqlite3_vtab_cursor *cur){
  2868. completion_cursor *pCur = (completion_cursor*)cur;
  2869. int eNextPhase = 0; /* Next phase to try if current phase reaches end */
  2870. int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
  2871. pCur->iRowid++;
  2872. while( pCur->ePhase!=COMPLETION_EOF ){
  2873. switch( pCur->ePhase ){
  2874. case COMPLETION_KEYWORDS: {
  2875. if( pCur->j >= sqlite3_keyword_count() ){
  2876. pCur->zCurrentRow = 0;
  2877. pCur->ePhase = COMPLETION_DATABASES;
  2878. }else{
  2879. sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
  2880. }
  2881. iCol = -1;
  2882. break;
  2883. }
  2884. case COMPLETION_DATABASES: {
  2885. if( pCur->pStmt==0 ){
  2886. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
  2887. &pCur->pStmt, 0);
  2888. }
  2889. iCol = 1;
  2890. eNextPhase = COMPLETION_TABLES;
  2891. break;
  2892. }
  2893. case COMPLETION_TABLES: {
  2894. if( pCur->pStmt==0 ){
  2895. sqlite3_stmt *pS2;
  2896. char *zSql = 0;
  2897. const char *zSep = "";
  2898. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  2899. while( sqlite3_step(pS2)==SQLITE_ROW ){
  2900. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  2901. zSql = sqlite3_mprintf(
  2902. "%z%s"
  2903. "SELECT name FROM \"%w\".sqlite_master",
  2904. zSql, zSep, zDb
  2905. );
  2906. if( zSql==0 ) return SQLITE_NOMEM;
  2907. zSep = " UNION ";
  2908. }
  2909. sqlite3_finalize(pS2);
  2910. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  2911. sqlite3_free(zSql);
  2912. }
  2913. iCol = 0;
  2914. eNextPhase = COMPLETION_COLUMNS;
  2915. break;
  2916. }
  2917. case COMPLETION_COLUMNS: {
  2918. if( pCur->pStmt==0 ){
  2919. sqlite3_stmt *pS2;
  2920. char *zSql = 0;
  2921. const char *zSep = "";
  2922. sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
  2923. while( sqlite3_step(pS2)==SQLITE_ROW ){
  2924. const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
  2925. zSql = sqlite3_mprintf(
  2926. "%z%s"
  2927. "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
  2928. " JOIN pragma_table_info(sm.name,%Q) AS pti"
  2929. " WHERE sm.type='table'",
  2930. zSql, zSep, zDb, zDb
  2931. );
  2932. if( zSql==0 ) return SQLITE_NOMEM;
  2933. zSep = " UNION ";
  2934. }
  2935. sqlite3_finalize(pS2);
  2936. sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
  2937. sqlite3_free(zSql);
  2938. }
  2939. iCol = 0;
  2940. eNextPhase = COMPLETION_EOF;
  2941. break;
  2942. }
  2943. }
  2944. if( iCol<0 ){
  2945. /* This case is when the phase presets zCurrentRow */
  2946. if( pCur->zCurrentRow==0 ) continue;
  2947. }else{
  2948. if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
  2949. /* Extract the next row of content */
  2950. pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
  2951. pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
  2952. }else{
  2953. /* When all rows are finished, advance to the next phase */
  2954. sqlite3_finalize(pCur->pStmt);
  2955. pCur->pStmt = 0;
  2956. pCur->ePhase = eNextPhase;
  2957. continue;
  2958. }
  2959. }
  2960. if( pCur->nPrefix==0 ) break;
  2961. if( pCur->nPrefix<=pCur->szRow
  2962. && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
  2963. ){
  2964. break;
  2965. }
  2966. }
  2967. return SQLITE_OK;
  2968. }
  2969. /*
  2970. ** Return values of columns for the row at which the completion_cursor
  2971. ** is currently pointing.
  2972. */
  2973. static int completionColumn(
  2974. sqlite3_vtab_cursor *cur, /* The cursor */
  2975. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  2976. int i /* Which column to return */
  2977. ){
  2978. completion_cursor *pCur = (completion_cursor*)cur;
  2979. switch( i ){
  2980. case COMPLETION_COLUMN_CANDIDATE: {
  2981. sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
  2982. break;
  2983. }
  2984. case COMPLETION_COLUMN_PREFIX: {
  2985. sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
  2986. break;
  2987. }
  2988. case COMPLETION_COLUMN_WHOLELINE: {
  2989. sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
  2990. break;
  2991. }
  2992. case COMPLETION_COLUMN_PHASE: {
  2993. sqlite3_result_int(ctx, pCur->ePhase);
  2994. break;
  2995. }
  2996. }
  2997. return SQLITE_OK;
  2998. }
  2999. /*
  3000. ** Return the rowid for the current row. In this implementation, the
  3001. ** rowid is the same as the output value.
  3002. */
  3003. static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  3004. completion_cursor *pCur = (completion_cursor*)cur;
  3005. *pRowid = pCur->iRowid;
  3006. return SQLITE_OK;
  3007. }
  3008. /*
  3009. ** Return TRUE if the cursor has been moved off of the last
  3010. ** row of output.
  3011. */
  3012. static int completionEof(sqlite3_vtab_cursor *cur){
  3013. completion_cursor *pCur = (completion_cursor*)cur;
  3014. return pCur->ePhase >= COMPLETION_EOF;
  3015. }
  3016. /*
  3017. ** This method is called to "rewind" the completion_cursor object back
  3018. ** to the first row of output. This method is always called at least
  3019. ** once prior to any call to completionColumn() or completionRowid() or
  3020. ** completionEof().
  3021. */
  3022. static int completionFilter(
  3023. sqlite3_vtab_cursor *pVtabCursor,
  3024. int idxNum, const char *idxStr,
  3025. int argc, sqlite3_value **argv
  3026. ){
  3027. completion_cursor *pCur = (completion_cursor *)pVtabCursor;
  3028. int iArg = 0;
  3029. (void)(idxStr); /* Unused parameter */
  3030. (void)(argc); /* Unused parameter */
  3031. completionCursorReset(pCur);
  3032. if( idxNum & 1 ){
  3033. pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
  3034. if( pCur->nPrefix>0 ){
  3035. pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3036. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3037. }
  3038. iArg = 1;
  3039. }
  3040. if( idxNum & 2 ){
  3041. pCur->nLine = sqlite3_value_bytes(argv[iArg]);
  3042. if( pCur->nLine>0 ){
  3043. pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
  3044. if( pCur->zLine==0 ) return SQLITE_NOMEM;
  3045. }
  3046. }
  3047. if( pCur->zLine!=0 && pCur->zPrefix==0 ){
  3048. int i = pCur->nLine;
  3049. while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
  3050. i--;
  3051. }
  3052. pCur->nPrefix = pCur->nLine - i;
  3053. if( pCur->nPrefix>0 ){
  3054. pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
  3055. if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
  3056. }
  3057. }
  3058. pCur->iRowid = 0;
  3059. pCur->ePhase = COMPLETION_FIRST_PHASE;
  3060. return completionNext(pVtabCursor);
  3061. }
  3062. /*
  3063. ** SQLite will invoke this method one or more times while planning a query
  3064. ** that uses the completion virtual table. This routine needs to create
  3065. ** a query plan for each invocation and compute an estimated cost for that
  3066. ** plan.
  3067. **
  3068. ** There are two hidden parameters that act as arguments to the table-valued
  3069. ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
  3070. ** is available and bit 1 is set if "wholeline" is available.
  3071. */
  3072. static int completionBestIndex(
  3073. sqlite3_vtab *tab,
  3074. sqlite3_index_info *pIdxInfo
  3075. ){
  3076. int i; /* Loop over constraints */
  3077. int idxNum = 0; /* The query plan bitmask */
  3078. int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
  3079. int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
  3080. int nArg = 0; /* Number of arguments that completeFilter() expects */
  3081. const struct sqlite3_index_constraint *pConstraint;
  3082. (void)(tab); /* Unused parameter */
  3083. pConstraint = pIdxInfo->aConstraint;
  3084. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  3085. if( pConstraint->usable==0 ) continue;
  3086. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  3087. switch( pConstraint->iColumn ){
  3088. case COMPLETION_COLUMN_PREFIX:
  3089. prefixIdx = i;
  3090. idxNum |= 1;
  3091. break;
  3092. case COMPLETION_COLUMN_WHOLELINE:
  3093. wholelineIdx = i;
  3094. idxNum |= 2;
  3095. break;
  3096. }
  3097. }
  3098. if( prefixIdx>=0 ){
  3099. pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
  3100. pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
  3101. }
  3102. if( wholelineIdx>=0 ){
  3103. pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
  3104. pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
  3105. }
  3106. pIdxInfo->idxNum = idxNum;
  3107. pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
  3108. pIdxInfo->estimatedRows = 500 - 100*nArg;
  3109. return SQLITE_OK;
  3110. }
  3111. /*
  3112. ** This following structure defines all the methods for the
  3113. ** completion virtual table.
  3114. */
  3115. static sqlite3_module completionModule = {
  3116. 0, /* iVersion */
  3117. 0, /* xCreate */
  3118. completionConnect, /* xConnect */
  3119. completionBestIndex, /* xBestIndex */
  3120. completionDisconnect, /* xDisconnect */
  3121. 0, /* xDestroy */
  3122. completionOpen, /* xOpen - open a cursor */
  3123. completionClose, /* xClose - close a cursor */
  3124. completionFilter, /* xFilter - configure scan constraints */
  3125. completionNext, /* xNext - advance a cursor */
  3126. completionEof, /* xEof - check for end of scan */
  3127. completionColumn, /* xColumn - read data */
  3128. completionRowid, /* xRowid - read data */
  3129. 0, /* xUpdate */
  3130. 0, /* xBegin */
  3131. 0, /* xSync */
  3132. 0, /* xCommit */
  3133. 0, /* xRollback */
  3134. 0, /* xFindMethod */
  3135. 0, /* xRename */
  3136. 0, /* xSavepoint */
  3137. 0, /* xRelease */
  3138. 0 /* xRollbackTo */
  3139. };
  3140. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  3141. int sqlite3CompletionVtabInit(sqlite3 *db){
  3142. int rc = SQLITE_OK;
  3143. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3144. rc = sqlite3_create_module(db, "completion", &completionModule, 0);
  3145. #endif
  3146. return rc;
  3147. }
  3148. #ifdef _WIN32
  3149. #endif
  3150. int sqlite3_completion_init(
  3151. sqlite3 *db,
  3152. char **pzErrMsg,
  3153. const sqlite3_api_routines *pApi
  3154. ){
  3155. int rc = SQLITE_OK;
  3156. SQLITE_EXTENSION_INIT2(pApi);
  3157. (void)(pzErrMsg); /* Unused parameter */
  3158. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3159. rc = sqlite3CompletionVtabInit(db);
  3160. #endif
  3161. return rc;
  3162. }
  3163. /************************* End ../ext/misc/completion.c ********************/
  3164. /************************* Begin ../ext/misc/appendvfs.c ******************/
  3165. /*
  3166. ** 2017-10-20
  3167. **
  3168. ** The author disclaims copyright to this source code. In place of
  3169. ** a legal notice, here is a blessing:
  3170. **
  3171. ** May you do good and not evil.
  3172. ** May you find forgiveness for yourself and forgive others.
  3173. ** May you share freely, never taking more than you give.
  3174. **
  3175. ******************************************************************************
  3176. **
  3177. ** This file implements a VFS shim that allows an SQLite database to be
  3178. ** appended onto the end of some other file, such as an executable.
  3179. **
  3180. ** A special record must appear at the end of the file that identifies the
  3181. ** file as an appended database and provides an offset to page 1. For
  3182. ** best performance page 1 should be located at a disk page boundary, though
  3183. ** that is not required.
  3184. **
  3185. ** When opening a database using this VFS, the connection might treat
  3186. ** the file as an ordinary SQLite database, or it might treat is as a
  3187. ** database appended onto some other file. Here are the rules:
  3188. **
  3189. ** (1) When opening a new empty file, that file is treated as an ordinary
  3190. ** database.
  3191. **
  3192. ** (2) When opening a file that begins with the standard SQLite prefix
  3193. ** string "SQLite format 3", that file is treated as an ordinary
  3194. ** database.
  3195. **
  3196. ** (3) When opening a file that ends with the appendvfs trailer string
  3197. ** "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
  3198. ** database.
  3199. **
  3200. ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is
  3201. ** set, then a new database is appended to the already existing file.
  3202. **
  3203. ** (5) Otherwise, SQLITE_CANTOPEN is returned.
  3204. **
  3205. ** To avoid unnecessary complications with the PENDING_BYTE, the size of
  3206. ** the file containing the database is limited to 1GB. This VFS will refuse
  3207. ** to read or write past the 1GB mark. This restriction might be lifted in
  3208. ** future versions. For now, if you need a large database, then keep the
  3209. ** database in a separate file.
  3210. **
  3211. ** If the file being opened is not an appended database, then this shim is
  3212. ** a pass-through into the default underlying VFS.
  3213. **/
  3214. SQLITE_EXTENSION_INIT1
  3215. #include <string.h>
  3216. #include <assert.h>
  3217. /* The append mark at the end of the database is:
  3218. **
  3219. ** Start-Of-SQLite3-NNNNNNNN
  3220. ** 123456789 123456789 12345
  3221. **
  3222. ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
  3223. ** the offset to page 1.
  3224. */
  3225. #define APND_MARK_PREFIX "Start-Of-SQLite3-"
  3226. #define APND_MARK_PREFIX_SZ 17
  3227. #define APND_MARK_SIZE 25
  3228. /*
  3229. ** Maximum size of the combined prefix + database + append-mark. This
  3230. ** must be less than 0x40000000 to avoid locking issues on Windows.
  3231. */
  3232. #define APND_MAX_SIZE (65536*15259)
  3233. /*
  3234. ** Forward declaration of objects used by this utility
  3235. */
  3236. typedef struct sqlite3_vfs ApndVfs;
  3237. typedef struct ApndFile ApndFile;
  3238. /* Access to a lower-level VFS that (might) implement dynamic loading,
  3239. ** access to randomness, etc.
  3240. */
  3241. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  3242. #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
  3243. /* An open file */
  3244. struct ApndFile {
  3245. sqlite3_file base; /* IO methods */
  3246. sqlite3_int64 iPgOne; /* File offset to page 1 */
  3247. sqlite3_int64 iMark; /* Start of the append-mark */
  3248. };
  3249. /*
  3250. ** Methods for ApndFile
  3251. */
  3252. static int apndClose(sqlite3_file*);
  3253. static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  3254. static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  3255. static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
  3256. static int apndSync(sqlite3_file*, int flags);
  3257. static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  3258. static int apndLock(sqlite3_file*, int);
  3259. static int apndUnlock(sqlite3_file*, int);
  3260. static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
  3261. static int apndFileControl(sqlite3_file*, int op, void *pArg);
  3262. static int apndSectorSize(sqlite3_file*);
  3263. static int apndDeviceCharacteristics(sqlite3_file*);
  3264. static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  3265. static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
  3266. static void apndShmBarrier(sqlite3_file*);
  3267. static int apndShmUnmap(sqlite3_file*, int deleteFlag);
  3268. static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  3269. static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  3270. /*
  3271. ** Methods for ApndVfs
  3272. */
  3273. static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  3274. static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
  3275. static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  3276. static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  3277. static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
  3278. static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  3279. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  3280. static void apndDlClose(sqlite3_vfs*, void*);
  3281. static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
  3282. static int apndSleep(sqlite3_vfs*, int microseconds);
  3283. static int apndCurrentTime(sqlite3_vfs*, double*);
  3284. static int apndGetLastError(sqlite3_vfs*, int, char *);
  3285. static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  3286. static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
  3287. static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
  3288. static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
  3289. static sqlite3_vfs apnd_vfs = {
  3290. 3, /* iVersion (set when registered) */
  3291. 0, /* szOsFile (set when registered) */
  3292. 1024, /* mxPathname */
  3293. 0, /* pNext */
  3294. "apndvfs", /* zName */
  3295. 0, /* pAppData (set when registered) */
  3296. apndOpen, /* xOpen */
  3297. apndDelete, /* xDelete */
  3298. apndAccess, /* xAccess */
  3299. apndFullPathname, /* xFullPathname */
  3300. apndDlOpen, /* xDlOpen */
  3301. apndDlError, /* xDlError */
  3302. apndDlSym, /* xDlSym */
  3303. apndDlClose, /* xDlClose */
  3304. apndRandomness, /* xRandomness */
  3305. apndSleep, /* xSleep */
  3306. apndCurrentTime, /* xCurrentTime */
  3307. apndGetLastError, /* xGetLastError */
  3308. apndCurrentTimeInt64, /* xCurrentTimeInt64 */
  3309. apndSetSystemCall, /* xSetSystemCall */
  3310. apndGetSystemCall, /* xGetSystemCall */
  3311. apndNextSystemCall /* xNextSystemCall */
  3312. };
  3313. static const sqlite3_io_methods apnd_io_methods = {
  3314. 3, /* iVersion */
  3315. apndClose, /* xClose */
  3316. apndRead, /* xRead */
  3317. apndWrite, /* xWrite */
  3318. apndTruncate, /* xTruncate */
  3319. apndSync, /* xSync */
  3320. apndFileSize, /* xFileSize */
  3321. apndLock, /* xLock */
  3322. apndUnlock, /* xUnlock */
  3323. apndCheckReservedLock, /* xCheckReservedLock */
  3324. apndFileControl, /* xFileControl */
  3325. apndSectorSize, /* xSectorSize */
  3326. apndDeviceCharacteristics, /* xDeviceCharacteristics */
  3327. apndShmMap, /* xShmMap */
  3328. apndShmLock, /* xShmLock */
  3329. apndShmBarrier, /* xShmBarrier */
  3330. apndShmUnmap, /* xShmUnmap */
  3331. apndFetch, /* xFetch */
  3332. apndUnfetch /* xUnfetch */
  3333. };
  3334. /*
  3335. ** Close an apnd-file.
  3336. */
  3337. static int apndClose(sqlite3_file *pFile){
  3338. pFile = ORIGFILE(pFile);
  3339. return pFile->pMethods->xClose(pFile);
  3340. }
  3341. /*
  3342. ** Read data from an apnd-file.
  3343. */
  3344. static int apndRead(
  3345. sqlite3_file *pFile,
  3346. void *zBuf,
  3347. int iAmt,
  3348. sqlite_int64 iOfst
  3349. ){
  3350. ApndFile *p = (ApndFile *)pFile;
  3351. pFile = ORIGFILE(pFile);
  3352. return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
  3353. }
  3354. /*
  3355. ** Add the append-mark onto the end of the file.
  3356. */
  3357. static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
  3358. int i;
  3359. unsigned char a[APND_MARK_SIZE];
  3360. memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
  3361. for(i=0; i<8; i++){
  3362. a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
  3363. }
  3364. return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
  3365. }
  3366. /*
  3367. ** Write data to an apnd-file.
  3368. */
  3369. static int apndWrite(
  3370. sqlite3_file *pFile,
  3371. const void *zBuf,
  3372. int iAmt,
  3373. sqlite_int64 iOfst
  3374. ){
  3375. int rc;
  3376. ApndFile *p = (ApndFile *)pFile;
  3377. pFile = ORIGFILE(pFile);
  3378. if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
  3379. rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
  3380. if( rc==SQLITE_OK && iOfst + iAmt + p->iPgOne > p->iMark ){
  3381. sqlite3_int64 sz = 0;
  3382. rc = pFile->pMethods->xFileSize(pFile, &sz);
  3383. if( rc==SQLITE_OK ){
  3384. p->iMark = sz - APND_MARK_SIZE;
  3385. if( iOfst + iAmt + p->iPgOne > p->iMark ){
  3386. p->iMark = p->iPgOne + iOfst + iAmt;
  3387. rc = apndWriteMark(p, pFile);
  3388. }
  3389. }
  3390. }
  3391. return rc;
  3392. }
  3393. /*
  3394. ** Truncate an apnd-file.
  3395. */
  3396. static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
  3397. int rc;
  3398. ApndFile *p = (ApndFile *)pFile;
  3399. pFile = ORIGFILE(pFile);
  3400. rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
  3401. if( rc==SQLITE_OK ){
  3402. p->iMark = p->iPgOne+size;
  3403. rc = apndWriteMark(p, pFile);
  3404. }
  3405. return rc;
  3406. }
  3407. /*
  3408. ** Sync an apnd-file.
  3409. */
  3410. static int apndSync(sqlite3_file *pFile, int flags){
  3411. pFile = ORIGFILE(pFile);
  3412. return pFile->pMethods->xSync(pFile, flags);
  3413. }
  3414. /*
  3415. ** Return the current file-size of an apnd-file.
  3416. */
  3417. static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  3418. ApndFile *p = (ApndFile *)pFile;
  3419. int rc;
  3420. pFile = ORIGFILE(p);
  3421. rc = pFile->pMethods->xFileSize(pFile, pSize);
  3422. if( rc==SQLITE_OK && p->iPgOne ){
  3423. *pSize -= p->iPgOne + APND_MARK_SIZE;
  3424. }
  3425. return rc;
  3426. }
  3427. /*
  3428. ** Lock an apnd-file.
  3429. */
  3430. static int apndLock(sqlite3_file *pFile, int eLock){
  3431. pFile = ORIGFILE(pFile);
  3432. return pFile->pMethods->xLock(pFile, eLock);
  3433. }
  3434. /*
  3435. ** Unlock an apnd-file.
  3436. */
  3437. static int apndUnlock(sqlite3_file *pFile, int eLock){
  3438. pFile = ORIGFILE(pFile);
  3439. return pFile->pMethods->xUnlock(pFile, eLock);
  3440. }
  3441. /*
  3442. ** Check if another file-handle holds a RESERVED lock on an apnd-file.
  3443. */
  3444. static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  3445. pFile = ORIGFILE(pFile);
  3446. return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
  3447. }
  3448. /*
  3449. ** File control method. For custom operations on an apnd-file.
  3450. */
  3451. static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
  3452. ApndFile *p = (ApndFile *)pFile;
  3453. int rc;
  3454. pFile = ORIGFILE(pFile);
  3455. rc = pFile->pMethods->xFileControl(pFile, op, pArg);
  3456. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  3457. *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
  3458. }
  3459. return rc;
  3460. }
  3461. /*
  3462. ** Return the sector-size in bytes for an apnd-file.
  3463. */
  3464. static int apndSectorSize(sqlite3_file *pFile){
  3465. pFile = ORIGFILE(pFile);
  3466. return pFile->pMethods->xSectorSize(pFile);
  3467. }
  3468. /*
  3469. ** Return the device characteristic flags supported by an apnd-file.
  3470. */
  3471. static int apndDeviceCharacteristics(sqlite3_file *pFile){
  3472. pFile = ORIGFILE(pFile);
  3473. return pFile->pMethods->xDeviceCharacteristics(pFile);
  3474. }
  3475. /* Create a shared memory file mapping */
  3476. static int apndShmMap(
  3477. sqlite3_file *pFile,
  3478. int iPg,
  3479. int pgsz,
  3480. int bExtend,
  3481. void volatile **pp
  3482. ){
  3483. pFile = ORIGFILE(pFile);
  3484. return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
  3485. }
  3486. /* Perform locking on a shared-memory segment */
  3487. static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
  3488. pFile = ORIGFILE(pFile);
  3489. return pFile->pMethods->xShmLock(pFile,offset,n,flags);
  3490. }
  3491. /* Memory barrier operation on shared memory */
  3492. static void apndShmBarrier(sqlite3_file *pFile){
  3493. pFile = ORIGFILE(pFile);
  3494. pFile->pMethods->xShmBarrier(pFile);
  3495. }
  3496. /* Unmap a shared memory segment */
  3497. static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
  3498. pFile = ORIGFILE(pFile);
  3499. return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
  3500. }
  3501. /* Fetch a page of a memory-mapped file */
  3502. static int apndFetch(
  3503. sqlite3_file *pFile,
  3504. sqlite3_int64 iOfst,
  3505. int iAmt,
  3506. void **pp
  3507. ){
  3508. ApndFile *p = (ApndFile *)pFile;
  3509. pFile = ORIGFILE(pFile);
  3510. return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
  3511. }
  3512. /* Release a memory-mapped page */
  3513. static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  3514. ApndFile *p = (ApndFile *)pFile;
  3515. pFile = ORIGFILE(pFile);
  3516. return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
  3517. }
  3518. /*
  3519. ** Check to see if the file is an ordinary SQLite database file.
  3520. */
  3521. static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
  3522. int rc;
  3523. char zHdr[16];
  3524. static const char aSqliteHdr[] = "SQLite format 3";
  3525. if( sz<512 ) return 0;
  3526. rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
  3527. if( rc ) return 0;
  3528. return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
  3529. }
  3530. /*
  3531. ** Try to read the append-mark off the end of a file. Return the
  3532. ** start of the appended database if the append-mark is present. If
  3533. ** there is no append-mark, return -1;
  3534. */
  3535. static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
  3536. int rc, i;
  3537. sqlite3_int64 iMark;
  3538. unsigned char a[APND_MARK_SIZE];
  3539. if( sz<=APND_MARK_SIZE ) return -1;
  3540. rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
  3541. if( rc ) return -1;
  3542. if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
  3543. iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
  3544. for(i=1; i<8; i++){
  3545. iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
  3546. }
  3547. return iMark;
  3548. }
  3549. /*
  3550. ** Open an apnd file handle.
  3551. */
  3552. static int apndOpen(
  3553. sqlite3_vfs *pVfs,
  3554. const char *zName,
  3555. sqlite3_file *pFile,
  3556. int flags,
  3557. int *pOutFlags
  3558. ){
  3559. ApndFile *p;
  3560. sqlite3_file *pSubFile;
  3561. sqlite3_vfs *pSubVfs;
  3562. int rc;
  3563. sqlite3_int64 sz;
  3564. pSubVfs = ORIGVFS(pVfs);
  3565. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  3566. return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
  3567. }
  3568. p = (ApndFile*)pFile;
  3569. memset(p, 0, sizeof(*p));
  3570. pSubFile = ORIGFILE(pFile);
  3571. p->base.pMethods = &apnd_io_methods;
  3572. rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
  3573. if( rc ) goto apnd_open_done;
  3574. rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
  3575. if( rc ){
  3576. pSubFile->pMethods->xClose(pSubFile);
  3577. goto apnd_open_done;
  3578. }
  3579. if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
  3580. memmove(pFile, pSubFile, pSubVfs->szOsFile);
  3581. return SQLITE_OK;
  3582. }
  3583. p->iMark = 0;
  3584. p->iPgOne = apndReadMark(sz, pFile);
  3585. if( p->iPgOne>0 ){
  3586. return SQLITE_OK;
  3587. }
  3588. if( (flags & SQLITE_OPEN_CREATE)==0 ){
  3589. pSubFile->pMethods->xClose(pSubFile);
  3590. rc = SQLITE_CANTOPEN;
  3591. }
  3592. p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
  3593. apnd_open_done:
  3594. if( rc ) pFile->pMethods = 0;
  3595. return rc;
  3596. }
  3597. /*
  3598. ** All other VFS methods are pass-thrus.
  3599. */
  3600. static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  3601. return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
  3602. }
  3603. static int apndAccess(
  3604. sqlite3_vfs *pVfs,
  3605. const char *zPath,
  3606. int flags,
  3607. int *pResOut
  3608. ){
  3609. return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
  3610. }
  3611. static int apndFullPathname(
  3612. sqlite3_vfs *pVfs,
  3613. const char *zPath,
  3614. int nOut,
  3615. char *zOut
  3616. ){
  3617. return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
  3618. }
  3619. static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  3620. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  3621. }
  3622. static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  3623. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  3624. }
  3625. static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  3626. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  3627. }
  3628. static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
  3629. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  3630. }
  3631. static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  3632. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  3633. }
  3634. static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
  3635. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  3636. }
  3637. static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  3638. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  3639. }
  3640. static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  3641. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  3642. }
  3643. static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  3644. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  3645. }
  3646. static int apndSetSystemCall(
  3647. sqlite3_vfs *pVfs,
  3648. const char *zName,
  3649. sqlite3_syscall_ptr pCall
  3650. ){
  3651. return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
  3652. }
  3653. static sqlite3_syscall_ptr apndGetSystemCall(
  3654. sqlite3_vfs *pVfs,
  3655. const char *zName
  3656. ){
  3657. return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
  3658. }
  3659. static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
  3660. return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
  3661. }
  3662. #ifdef _WIN32
  3663. #endif
  3664. /*
  3665. ** This routine is called when the extension is loaded.
  3666. ** Register the new VFS.
  3667. */
  3668. int sqlite3_appendvfs_init(
  3669. sqlite3 *db,
  3670. char **pzErrMsg,
  3671. const sqlite3_api_routines *pApi
  3672. ){
  3673. int rc = SQLITE_OK;
  3674. sqlite3_vfs *pOrig;
  3675. SQLITE_EXTENSION_INIT2(pApi);
  3676. (void)pzErrMsg;
  3677. (void)db;
  3678. pOrig = sqlite3_vfs_find(0);
  3679. apnd_vfs.iVersion = pOrig->iVersion;
  3680. apnd_vfs.pAppData = pOrig;
  3681. apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
  3682. rc = sqlite3_vfs_register(&apnd_vfs, 0);
  3683. #ifdef APPENDVFS_TEST
  3684. if( rc==SQLITE_OK ){
  3685. rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
  3686. }
  3687. #endif
  3688. if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
  3689. return rc;
  3690. }
  3691. /************************* End ../ext/misc/appendvfs.c ********************/
  3692. #ifdef SQLITE_HAVE_ZLIB
  3693. /************************* Begin ../ext/misc/zipfile.c ******************/
  3694. /*
  3695. ** 2017-12-26
  3696. **
  3697. ** The author disclaims copyright to this source code. In place of
  3698. ** a legal notice, here is a blessing:
  3699. **
  3700. ** May you do good and not evil.
  3701. ** May you find forgiveness for yourself and forgive others.
  3702. ** May you share freely, never taking more than you give.
  3703. **
  3704. ******************************************************************************
  3705. **
  3706. ** This file implements a virtual table for reading and writing ZIP archive
  3707. ** files.
  3708. **
  3709. ** Usage example:
  3710. **
  3711. ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
  3712. **
  3713. ** Current limitations:
  3714. **
  3715. ** * No support for encryption
  3716. ** * No support for ZIP archives spanning multiple files
  3717. ** * No support for zip64 extensions
  3718. ** * Only the "inflate/deflate" (zlib) compression method is supported
  3719. */
  3720. SQLITE_EXTENSION_INIT1
  3721. #include <stdio.h>
  3722. #include <string.h>
  3723. #include <assert.h>
  3724. #include <zlib.h>
  3725. #ifndef SQLITE_OMIT_VIRTUALTABLE
  3726. #ifndef SQLITE_AMALGAMATION
  3727. /* typedef sqlite3_int64 i64; */
  3728. /* typedef unsigned char u8; */
  3729. typedef unsigned short u16;
  3730. typedef unsigned long u32;
  3731. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  3732. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  3733. # define ALWAYS(X) (1)
  3734. # define NEVER(X) (0)
  3735. #elif !defined(NDEBUG)
  3736. # define ALWAYS(X) ((X)?1:(assert(0),0))
  3737. # define NEVER(X) ((X)?(assert(0),1):0)
  3738. #else
  3739. # define ALWAYS(X) (X)
  3740. # define NEVER(X) (X)
  3741. #endif
  3742. #endif /* SQLITE_AMALGAMATION */
  3743. /*
  3744. ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
  3745. **
  3746. ** In some ways it would be better to obtain these values from system
  3747. ** header files. But, the dependency is undesirable and (a) these
  3748. ** have been stable for decades, (b) the values are part of POSIX and
  3749. ** are also made explicit in [man stat], and (c) are part of the
  3750. ** file format for zip archives.
  3751. */
  3752. #ifndef S_IFDIR
  3753. # define S_IFDIR 0040000
  3754. #endif
  3755. #ifndef S_IFREG
  3756. # define S_IFREG 0100000
  3757. #endif
  3758. #ifndef S_IFLNK
  3759. # define S_IFLNK 0120000
  3760. #endif
  3761. static const char ZIPFILE_SCHEMA[] =
  3762. "CREATE TABLE y("
  3763. "name PRIMARY KEY," /* 0: Name of file in zip archive */
  3764. "mode," /* 1: POSIX mode for file */
  3765. "mtime," /* 2: Last modification time (secs since 1970)*/
  3766. "sz," /* 3: Size of object */
  3767. "rawdata," /* 4: Raw data */
  3768. "data," /* 5: Uncompressed data */
  3769. "method," /* 6: Compression method (integer) */
  3770. "z HIDDEN" /* 7: Name of zip file */
  3771. ") WITHOUT ROWID;";
  3772. #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */
  3773. #define ZIPFILE_BUFFER_SIZE (64*1024)
  3774. /*
  3775. ** Magic numbers used to read and write zip files.
  3776. **
  3777. ** ZIPFILE_NEWENTRY_MADEBY:
  3778. ** Use this value for the "version-made-by" field in new zip file
  3779. ** entries. The upper byte indicates "unix", and the lower byte
  3780. ** indicates that the zip file matches pkzip specification 3.0.
  3781. ** This is what info-zip seems to do.
  3782. **
  3783. ** ZIPFILE_NEWENTRY_REQUIRED:
  3784. ** Value for "version-required-to-extract" field of new entries.
  3785. ** Version 2.0 is required to support folders and deflate compression.
  3786. **
  3787. ** ZIPFILE_NEWENTRY_FLAGS:
  3788. ** Value for "general-purpose-bit-flags" field of new entries. Bit
  3789. ** 11 means "utf-8 filename and comment".
  3790. **
  3791. ** ZIPFILE_SIGNATURE_CDS:
  3792. ** First 4 bytes of a valid CDS record.
  3793. **
  3794. ** ZIPFILE_SIGNATURE_LFH:
  3795. ** First 4 bytes of a valid LFH record.
  3796. **
  3797. ** ZIPFILE_SIGNATURE_EOCD
  3798. ** First 4 bytes of a valid EOCD record.
  3799. */
  3800. #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
  3801. #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
  3802. #define ZIPFILE_NEWENTRY_REQUIRED 20
  3803. #define ZIPFILE_NEWENTRY_FLAGS 0x800
  3804. #define ZIPFILE_SIGNATURE_CDS 0x02014b50
  3805. #define ZIPFILE_SIGNATURE_LFH 0x04034b50
  3806. #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
  3807. /*
  3808. ** The sizes of the fixed-size part of each of the three main data
  3809. ** structures in a zip archive.
  3810. */
  3811. #define ZIPFILE_LFH_FIXED_SZ 30
  3812. #define ZIPFILE_EOCD_FIXED_SZ 22
  3813. #define ZIPFILE_CDS_FIXED_SZ 46
  3814. /*
  3815. *** 4.3.16 End of central directory record:
  3816. ***
  3817. *** end of central dir signature 4 bytes (0x06054b50)
  3818. *** number of this disk 2 bytes
  3819. *** number of the disk with the
  3820. *** start of the central directory 2 bytes
  3821. *** total number of entries in the
  3822. *** central directory on this disk 2 bytes
  3823. *** total number of entries in
  3824. *** the central directory 2 bytes
  3825. *** size of the central directory 4 bytes
  3826. *** offset of start of central
  3827. *** directory with respect to
  3828. *** the starting disk number 4 bytes
  3829. *** .ZIP file comment length 2 bytes
  3830. *** .ZIP file comment (variable size)
  3831. */
  3832. typedef struct ZipfileEOCD ZipfileEOCD;
  3833. struct ZipfileEOCD {
  3834. u16 iDisk;
  3835. u16 iFirstDisk;
  3836. u16 nEntry;
  3837. u16 nEntryTotal;
  3838. u32 nSize;
  3839. u32 iOffset;
  3840. };
  3841. /*
  3842. *** 4.3.12 Central directory structure:
  3843. ***
  3844. *** ...
  3845. ***
  3846. *** central file header signature 4 bytes (0x02014b50)
  3847. *** version made by 2 bytes
  3848. *** version needed to extract 2 bytes
  3849. *** general purpose bit flag 2 bytes
  3850. *** compression method 2 bytes
  3851. *** last mod file time 2 bytes
  3852. *** last mod file date 2 bytes
  3853. *** crc-32 4 bytes
  3854. *** compressed size 4 bytes
  3855. *** uncompressed size 4 bytes
  3856. *** file name length 2 bytes
  3857. *** extra field length 2 bytes
  3858. *** file comment length 2 bytes
  3859. *** disk number start 2 bytes
  3860. *** internal file attributes 2 bytes
  3861. *** external file attributes 4 bytes
  3862. *** relative offset of local header 4 bytes
  3863. */
  3864. typedef struct ZipfileCDS ZipfileCDS;
  3865. struct ZipfileCDS {
  3866. u16 iVersionMadeBy;
  3867. u16 iVersionExtract;
  3868. u16 flags;
  3869. u16 iCompression;
  3870. u16 mTime;
  3871. u16 mDate;
  3872. u32 crc32;
  3873. u32 szCompressed;
  3874. u32 szUncompressed;
  3875. u16 nFile;
  3876. u16 nExtra;
  3877. u16 nComment;
  3878. u16 iDiskStart;
  3879. u16 iInternalAttr;
  3880. u32 iExternalAttr;
  3881. u32 iOffset;
  3882. char *zFile; /* Filename (sqlite3_malloc()) */
  3883. };
  3884. /*
  3885. *** 4.3.7 Local file header:
  3886. ***
  3887. *** local file header signature 4 bytes (0x04034b50)
  3888. *** version needed to extract 2 bytes
  3889. *** general purpose bit flag 2 bytes
  3890. *** compression method 2 bytes
  3891. *** last mod file time 2 bytes
  3892. *** last mod file date 2 bytes
  3893. *** crc-32 4 bytes
  3894. *** compressed size 4 bytes
  3895. *** uncompressed size 4 bytes
  3896. *** file name length 2 bytes
  3897. *** extra field length 2 bytes
  3898. ***
  3899. */
  3900. typedef struct ZipfileLFH ZipfileLFH;
  3901. struct ZipfileLFH {
  3902. u16 iVersionExtract;
  3903. u16 flags;
  3904. u16 iCompression;
  3905. u16 mTime;
  3906. u16 mDate;
  3907. u32 crc32;
  3908. u32 szCompressed;
  3909. u32 szUncompressed;
  3910. u16 nFile;
  3911. u16 nExtra;
  3912. };
  3913. typedef struct ZipfileEntry ZipfileEntry;
  3914. struct ZipfileEntry {
  3915. ZipfileCDS cds; /* Parsed CDS record */
  3916. u32 mUnixTime; /* Modification time, in UNIX format */
  3917. u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */
  3918. i64 iDataOff; /* Offset to data in file (if aData==0) */
  3919. u8 *aData; /* cds.szCompressed bytes of compressed data */
  3920. ZipfileEntry *pNext; /* Next element in in-memory CDS */
  3921. };
  3922. /*
  3923. ** Cursor type for zipfile tables.
  3924. */
  3925. typedef struct ZipfileCsr ZipfileCsr;
  3926. struct ZipfileCsr {
  3927. sqlite3_vtab_cursor base; /* Base class - must be first */
  3928. i64 iId; /* Cursor ID */
  3929. u8 bEof; /* True when at EOF */
  3930. u8 bNoop; /* If next xNext() call is no-op */
  3931. /* Used outside of write transactions */
  3932. FILE *pFile; /* Zip file */
  3933. i64 iNextOff; /* Offset of next record in central directory */
  3934. ZipfileEOCD eocd; /* Parse of central directory record */
  3935. ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
  3936. ZipfileEntry *pCurrent; /* Current entry */
  3937. ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */
  3938. };
  3939. typedef struct ZipfileTab ZipfileTab;
  3940. struct ZipfileTab {
  3941. sqlite3_vtab base; /* Base class - must be first */
  3942. char *zFile; /* Zip file this table accesses (may be NULL) */
  3943. sqlite3 *db; /* Host database connection */
  3944. u8 *aBuffer; /* Temporary buffer used for various tasks */
  3945. ZipfileCsr *pCsrList; /* List of cursors */
  3946. i64 iNextCsrid;
  3947. /* The following are used by write transactions only */
  3948. ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
  3949. ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */
  3950. FILE *pWriteFd; /* File handle open on zip archive */
  3951. i64 szCurrent; /* Current size of zip archive */
  3952. i64 szOrig; /* Size of archive at start of transaction */
  3953. };
  3954. /*
  3955. ** Set the error message contained in context ctx to the results of
  3956. ** vprintf(zFmt, ...).
  3957. */
  3958. static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
  3959. char *zMsg = 0;
  3960. va_list ap;
  3961. va_start(ap, zFmt);
  3962. zMsg = sqlite3_vmprintf(zFmt, ap);
  3963. sqlite3_result_error(ctx, zMsg, -1);
  3964. sqlite3_free(zMsg);
  3965. va_end(ap);
  3966. }
  3967. /*
  3968. ** If string zIn is quoted, dequote it in place. Otherwise, if the string
  3969. ** is not quoted, do nothing.
  3970. */
  3971. static void zipfileDequote(char *zIn){
  3972. char q = zIn[0];
  3973. if( q=='"' || q=='\'' || q=='`' || q=='[' ){
  3974. int iIn = 1;
  3975. int iOut = 0;
  3976. if( q=='[' ) q = ']';
  3977. while( ALWAYS(zIn[iIn]) ){
  3978. char c = zIn[iIn++];
  3979. if( c==q && zIn[iIn++]!=q ) break;
  3980. zIn[iOut++] = c;
  3981. }
  3982. zIn[iOut] = '\0';
  3983. }
  3984. }
  3985. /*
  3986. ** Construct a new ZipfileTab virtual table object.
  3987. **
  3988. ** argv[0] -> module name ("zipfile")
  3989. ** argv[1] -> database name
  3990. ** argv[2] -> table name
  3991. ** argv[...] -> "column name" and other module argument fields.
  3992. */
  3993. static int zipfileConnect(
  3994. sqlite3 *db,
  3995. void *pAux,
  3996. int argc, const char *const*argv,
  3997. sqlite3_vtab **ppVtab,
  3998. char **pzErr
  3999. ){
  4000. int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
  4001. int nFile = 0;
  4002. const char *zFile = 0;
  4003. ZipfileTab *pNew = 0;
  4004. int rc;
  4005. /* If the table name is not "zipfile", require that the argument be
  4006. ** specified. This stops zipfile tables from being created as:
  4007. **
  4008. ** CREATE VIRTUAL TABLE zzz USING zipfile();
  4009. **
  4010. ** It does not prevent:
  4011. **
  4012. ** CREATE VIRTUAL TABLE zipfile USING zipfile();
  4013. */
  4014. assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
  4015. if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
  4016. *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
  4017. return SQLITE_ERROR;
  4018. }
  4019. if( argc>3 ){
  4020. zFile = argv[3];
  4021. nFile = (int)strlen(zFile)+1;
  4022. }
  4023. rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
  4024. if( rc==SQLITE_OK ){
  4025. pNew = (ZipfileTab*)sqlite3_malloc(nByte+nFile);
  4026. if( pNew==0 ) return SQLITE_NOMEM;
  4027. memset(pNew, 0, nByte+nFile);
  4028. pNew->db = db;
  4029. pNew->aBuffer = (u8*)&pNew[1];
  4030. if( zFile ){
  4031. pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
  4032. memcpy(pNew->zFile, zFile, nFile);
  4033. zipfileDequote(pNew->zFile);
  4034. }
  4035. }
  4036. *ppVtab = (sqlite3_vtab*)pNew;
  4037. return rc;
  4038. }
  4039. /*
  4040. ** Free the ZipfileEntry structure indicated by the only argument.
  4041. */
  4042. static void zipfileEntryFree(ZipfileEntry *p){
  4043. if( p ){
  4044. sqlite3_free(p->cds.zFile);
  4045. sqlite3_free(p);
  4046. }
  4047. }
  4048. /*
  4049. ** Release resources that should be freed at the end of a write
  4050. ** transaction.
  4051. */
  4052. static void zipfileCleanupTransaction(ZipfileTab *pTab){
  4053. ZipfileEntry *pEntry;
  4054. ZipfileEntry *pNext;
  4055. if( pTab->pWriteFd ){
  4056. fclose(pTab->pWriteFd);
  4057. pTab->pWriteFd = 0;
  4058. }
  4059. for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
  4060. pNext = pEntry->pNext;
  4061. zipfileEntryFree(pEntry);
  4062. }
  4063. pTab->pFirstEntry = 0;
  4064. pTab->pLastEntry = 0;
  4065. pTab->szCurrent = 0;
  4066. pTab->szOrig = 0;
  4067. }
  4068. /*
  4069. ** This method is the destructor for zipfile vtab objects.
  4070. */
  4071. static int zipfileDisconnect(sqlite3_vtab *pVtab){
  4072. zipfileCleanupTransaction((ZipfileTab*)pVtab);
  4073. sqlite3_free(pVtab);
  4074. return SQLITE_OK;
  4075. }
  4076. /*
  4077. ** Constructor for a new ZipfileCsr object.
  4078. */
  4079. static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
  4080. ZipfileTab *pTab = (ZipfileTab*)p;
  4081. ZipfileCsr *pCsr;
  4082. pCsr = sqlite3_malloc(sizeof(*pCsr));
  4083. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  4084. if( pCsr==0 ){
  4085. return SQLITE_NOMEM;
  4086. }
  4087. memset(pCsr, 0, sizeof(*pCsr));
  4088. pCsr->iId = ++pTab->iNextCsrid;
  4089. pCsr->pCsrNext = pTab->pCsrList;
  4090. pTab->pCsrList = pCsr;
  4091. return SQLITE_OK;
  4092. }
  4093. /*
  4094. ** Reset a cursor back to the state it was in when first returned
  4095. ** by zipfileOpen().
  4096. */
  4097. static void zipfileResetCursor(ZipfileCsr *pCsr){
  4098. ZipfileEntry *p;
  4099. ZipfileEntry *pNext;
  4100. pCsr->bEof = 0;
  4101. if( pCsr->pFile ){
  4102. fclose(pCsr->pFile);
  4103. pCsr->pFile = 0;
  4104. zipfileEntryFree(pCsr->pCurrent);
  4105. pCsr->pCurrent = 0;
  4106. }
  4107. for(p=pCsr->pFreeEntry; p; p=pNext){
  4108. pNext = p->pNext;
  4109. zipfileEntryFree(p);
  4110. }
  4111. }
  4112. /*
  4113. ** Destructor for an ZipfileCsr.
  4114. */
  4115. static int zipfileClose(sqlite3_vtab_cursor *cur){
  4116. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4117. ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
  4118. ZipfileCsr **pp;
  4119. zipfileResetCursor(pCsr);
  4120. /* Remove this cursor from the ZipfileTab.pCsrList list. */
  4121. for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
  4122. *pp = pCsr->pCsrNext;
  4123. sqlite3_free(pCsr);
  4124. return SQLITE_OK;
  4125. }
  4126. /*
  4127. ** Set the error message for the virtual table associated with cursor
  4128. ** pCsr to the results of vprintf(zFmt, ...).
  4129. */
  4130. static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
  4131. va_list ap;
  4132. va_start(ap, zFmt);
  4133. sqlite3_free(pTab->base.zErrMsg);
  4134. pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
  4135. va_end(ap);
  4136. }
  4137. static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
  4138. va_list ap;
  4139. va_start(ap, zFmt);
  4140. sqlite3_free(pCsr->base.pVtab->zErrMsg);
  4141. pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
  4142. va_end(ap);
  4143. }
  4144. /*
  4145. ** Read nRead bytes of data from offset iOff of file pFile into buffer
  4146. ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
  4147. ** otherwise.
  4148. **
  4149. ** If an error does occur, output variable (*pzErrmsg) may be set to point
  4150. ** to an English language error message. It is the responsibility of the
  4151. ** caller to eventually free this buffer using
  4152. ** sqlite3_free().
  4153. */
  4154. static int zipfileReadData(
  4155. FILE *pFile, /* Read from this file */
  4156. u8 *aRead, /* Read into this buffer */
  4157. int nRead, /* Number of bytes to read */
  4158. i64 iOff, /* Offset to read from */
  4159. char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
  4160. ){
  4161. size_t n;
  4162. fseek(pFile, (long)iOff, SEEK_SET);
  4163. n = fread(aRead, 1, nRead, pFile);
  4164. if( (int)n!=nRead ){
  4165. *pzErrmsg = sqlite3_mprintf("error in fread()");
  4166. return SQLITE_ERROR;
  4167. }
  4168. return SQLITE_OK;
  4169. }
  4170. static int zipfileAppendData(
  4171. ZipfileTab *pTab,
  4172. const u8 *aWrite,
  4173. int nWrite
  4174. ){
  4175. size_t n;
  4176. fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
  4177. n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
  4178. if( (int)n!=nWrite ){
  4179. pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
  4180. return SQLITE_ERROR;
  4181. }
  4182. pTab->szCurrent += nWrite;
  4183. return SQLITE_OK;
  4184. }
  4185. /*
  4186. ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
  4187. */
  4188. static u16 zipfileGetU16(const u8 *aBuf){
  4189. return (aBuf[1] << 8) + aBuf[0];
  4190. }
  4191. /*
  4192. ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
  4193. */
  4194. static u32 zipfileGetU32(const u8 *aBuf){
  4195. return ((u32)(aBuf[3]) << 24)
  4196. + ((u32)(aBuf[2]) << 16)
  4197. + ((u32)(aBuf[1]) << 8)
  4198. + ((u32)(aBuf[0]) << 0);
  4199. }
  4200. /*
  4201. ** Write a 16-bit little endiate integer into buffer aBuf.
  4202. */
  4203. static void zipfilePutU16(u8 *aBuf, u16 val){
  4204. aBuf[0] = val & 0xFF;
  4205. aBuf[1] = (val>>8) & 0xFF;
  4206. }
  4207. /*
  4208. ** Write a 32-bit little endiate integer into buffer aBuf.
  4209. */
  4210. static void zipfilePutU32(u8 *aBuf, u32 val){
  4211. aBuf[0] = val & 0xFF;
  4212. aBuf[1] = (val>>8) & 0xFF;
  4213. aBuf[2] = (val>>16) & 0xFF;
  4214. aBuf[3] = (val>>24) & 0xFF;
  4215. }
  4216. #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
  4217. #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
  4218. #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
  4219. #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
  4220. /*
  4221. ** Magic numbers used to read CDS records.
  4222. */
  4223. #define ZIPFILE_CDS_NFILE_OFF 28
  4224. #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
  4225. /*
  4226. ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
  4227. ** if the record is not well-formed, or SQLITE_OK otherwise.
  4228. */
  4229. static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
  4230. u8 *aRead = aBuf;
  4231. u32 sig = zipfileRead32(aRead);
  4232. int rc = SQLITE_OK;
  4233. if( sig!=ZIPFILE_SIGNATURE_CDS ){
  4234. rc = SQLITE_ERROR;
  4235. }else{
  4236. pCDS->iVersionMadeBy = zipfileRead16(aRead);
  4237. pCDS->iVersionExtract = zipfileRead16(aRead);
  4238. pCDS->flags = zipfileRead16(aRead);
  4239. pCDS->iCompression = zipfileRead16(aRead);
  4240. pCDS->mTime = zipfileRead16(aRead);
  4241. pCDS->mDate = zipfileRead16(aRead);
  4242. pCDS->crc32 = zipfileRead32(aRead);
  4243. pCDS->szCompressed = zipfileRead32(aRead);
  4244. pCDS->szUncompressed = zipfileRead32(aRead);
  4245. assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  4246. pCDS->nFile = zipfileRead16(aRead);
  4247. pCDS->nExtra = zipfileRead16(aRead);
  4248. pCDS->nComment = zipfileRead16(aRead);
  4249. pCDS->iDiskStart = zipfileRead16(aRead);
  4250. pCDS->iInternalAttr = zipfileRead16(aRead);
  4251. pCDS->iExternalAttr = zipfileRead32(aRead);
  4252. pCDS->iOffset = zipfileRead32(aRead);
  4253. assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
  4254. }
  4255. return rc;
  4256. }
  4257. /*
  4258. ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
  4259. ** if the record is not well-formed, or SQLITE_OK otherwise.
  4260. */
  4261. static int zipfileReadLFH(
  4262. u8 *aBuffer,
  4263. ZipfileLFH *pLFH
  4264. ){
  4265. u8 *aRead = aBuffer;
  4266. int rc = SQLITE_OK;
  4267. u32 sig = zipfileRead32(aRead);
  4268. if( sig!=ZIPFILE_SIGNATURE_LFH ){
  4269. rc = SQLITE_ERROR;
  4270. }else{
  4271. pLFH->iVersionExtract = zipfileRead16(aRead);
  4272. pLFH->flags = zipfileRead16(aRead);
  4273. pLFH->iCompression = zipfileRead16(aRead);
  4274. pLFH->mTime = zipfileRead16(aRead);
  4275. pLFH->mDate = zipfileRead16(aRead);
  4276. pLFH->crc32 = zipfileRead32(aRead);
  4277. pLFH->szCompressed = zipfileRead32(aRead);
  4278. pLFH->szUncompressed = zipfileRead32(aRead);
  4279. pLFH->nFile = zipfileRead16(aRead);
  4280. pLFH->nExtra = zipfileRead16(aRead);
  4281. }
  4282. return rc;
  4283. }
  4284. /*
  4285. ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
  4286. ** Scan through this buffer to find an "extra-timestamp" field. If one
  4287. ** exists, extract the 32-bit modification-timestamp from it and store
  4288. ** the value in output parameter *pmTime.
  4289. **
  4290. ** Zero is returned if no extra-timestamp record could be found (and so
  4291. ** *pmTime is left unchanged), or non-zero otherwise.
  4292. **
  4293. ** The general format of an extra field is:
  4294. **
  4295. ** Header ID 2 bytes
  4296. ** Data Size 2 bytes
  4297. ** Data N bytes
  4298. */
  4299. static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
  4300. int ret = 0;
  4301. u8 *p = aExtra;
  4302. u8 *pEnd = &aExtra[nExtra];
  4303. while( p<pEnd ){
  4304. u16 id = zipfileRead16(p);
  4305. u16 nByte = zipfileRead16(p);
  4306. switch( id ){
  4307. case ZIPFILE_EXTRA_TIMESTAMP: {
  4308. u8 b = p[0];
  4309. if( b & 0x01 ){ /* 0x01 -> modtime is present */
  4310. *pmTime = zipfileGetU32(&p[1]);
  4311. ret = 1;
  4312. }
  4313. break;
  4314. }
  4315. }
  4316. p += nByte;
  4317. }
  4318. return ret;
  4319. }
  4320. /*
  4321. ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
  4322. ** fields of the CDS structure passed as the only argument to a 32-bit
  4323. ** UNIX seconds-since-the-epoch timestamp. Return the result.
  4324. **
  4325. ** "Standard" MS-DOS time format:
  4326. **
  4327. ** File modification time:
  4328. ** Bits 00-04: seconds divided by 2
  4329. ** Bits 05-10: minute
  4330. ** Bits 11-15: hour
  4331. ** File modification date:
  4332. ** Bits 00-04: day
  4333. ** Bits 05-08: month (1-12)
  4334. ** Bits 09-15: years from 1980
  4335. **
  4336. ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
  4337. */
  4338. static u32 zipfileMtime(ZipfileCDS *pCDS){
  4339. int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
  4340. int M = ((pCDS->mDate >> 5) & 0x0F);
  4341. int D = (pCDS->mDate & 0x1F);
  4342. int B = -13;
  4343. int sec = (pCDS->mTime & 0x1F)*2;
  4344. int min = (pCDS->mTime >> 5) & 0x3F;
  4345. int hr = (pCDS->mTime >> 11) & 0x1F;
  4346. i64 JD;
  4347. /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
  4348. /* Calculate the JD in seconds for noon on the day in question */
  4349. if( M<3 ){
  4350. Y = Y-1;
  4351. M = M+12;
  4352. }
  4353. JD = (i64)(24*60*60) * (
  4354. (int)(365.25 * (Y + 4716))
  4355. + (int)(30.6001 * (M + 1))
  4356. + D + B - 1524
  4357. );
  4358. /* Correct the JD for the time within the day */
  4359. JD += (hr-12) * 3600 + min * 60 + sec;
  4360. /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
  4361. return (u32)(JD - (i64)(24405875) * 24*60*6);
  4362. }
  4363. /*
  4364. ** The opposite of zipfileMtime(). This function populates the mTime and
  4365. ** mDate fields of the CDS structure passed as the first argument according
  4366. ** to the UNIX timestamp value passed as the second.
  4367. */
  4368. static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
  4369. /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
  4370. i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
  4371. int A, B, C, D, E;
  4372. int yr, mon, day;
  4373. int hr, min, sec;
  4374. A = (int)((JD - 1867216.25)/36524.25);
  4375. A = (int)(JD + 1 + A - (A/4));
  4376. B = A + 1524;
  4377. C = (int)((B - 122.1)/365.25);
  4378. D = (36525*(C&32767))/100;
  4379. E = (int)((B-D)/30.6001);
  4380. day = B - D - (int)(30.6001*E);
  4381. mon = (E<14 ? E-1 : E-13);
  4382. yr = mon>2 ? C-4716 : C-4715;
  4383. hr = (mUnixTime % (24*60*60)) / (60*60);
  4384. min = (mUnixTime % (60*60)) / 60;
  4385. sec = (mUnixTime % 60);
  4386. if( yr>=1980 ){
  4387. pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
  4388. pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
  4389. }else{
  4390. pCds->mDate = pCds->mTime = 0;
  4391. }
  4392. assert( mUnixTime<315507600
  4393. || mUnixTime==zipfileMtime(pCds)
  4394. || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
  4395. /* || (mUnixTime % 2) */
  4396. );
  4397. }
  4398. /*
  4399. ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
  4400. ** size) containing an entire zip archive image. Or, if aBlob is NULL,
  4401. ** then pFile is a file-handle open on a zip file. In either case, this
  4402. ** function creates a ZipfileEntry object based on the zip archive entry
  4403. ** for which the CDS record is at offset iOff.
  4404. **
  4405. ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
  4406. ** the new object. Otherwise, an SQLite error code is returned and the
  4407. ** final value of (*ppEntry) undefined.
  4408. */
  4409. static int zipfileGetEntry(
  4410. ZipfileTab *pTab, /* Store any error message here */
  4411. const u8 *aBlob, /* Pointer to in-memory file image */
  4412. int nBlob, /* Size of aBlob[] in bytes */
  4413. FILE *pFile, /* If aBlob==0, read from this file */
  4414. i64 iOff, /* Offset of CDS record */
  4415. ZipfileEntry **ppEntry /* OUT: Pointer to new object */
  4416. ){
  4417. u8 *aRead;
  4418. char **pzErr = &pTab->base.zErrMsg;
  4419. int rc = SQLITE_OK;
  4420. if( aBlob==0 ){
  4421. aRead = pTab->aBuffer;
  4422. rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
  4423. }else{
  4424. aRead = (u8*)&aBlob[iOff];
  4425. }
  4426. if( rc==SQLITE_OK ){
  4427. int nAlloc;
  4428. ZipfileEntry *pNew;
  4429. int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
  4430. int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
  4431. nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
  4432. nAlloc = sizeof(ZipfileEntry) + nExtra;
  4433. if( aBlob ){
  4434. nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
  4435. }
  4436. pNew = (ZipfileEntry*)sqlite3_malloc(nAlloc);
  4437. if( pNew==0 ){
  4438. rc = SQLITE_NOMEM;
  4439. }else{
  4440. memset(pNew, 0, sizeof(ZipfileEntry));
  4441. rc = zipfileReadCDS(aRead, &pNew->cds);
  4442. if( rc!=SQLITE_OK ){
  4443. *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
  4444. }else if( aBlob==0 ){
  4445. rc = zipfileReadData(
  4446. pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
  4447. );
  4448. }else{
  4449. aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
  4450. }
  4451. }
  4452. if( rc==SQLITE_OK ){
  4453. u32 *pt = &pNew->mUnixTime;
  4454. pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
  4455. pNew->aExtra = (u8*)&pNew[1];
  4456. memcpy(pNew->aExtra, &aRead[nFile], nExtra);
  4457. if( pNew->cds.zFile==0 ){
  4458. rc = SQLITE_NOMEM;
  4459. }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
  4460. pNew->mUnixTime = zipfileMtime(&pNew->cds);
  4461. }
  4462. }
  4463. if( rc==SQLITE_OK ){
  4464. static const int szFix = ZIPFILE_LFH_FIXED_SZ;
  4465. ZipfileLFH lfh;
  4466. if( pFile ){
  4467. rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
  4468. }else{
  4469. aRead = (u8*)&aBlob[pNew->cds.iOffset];
  4470. }
  4471. rc = zipfileReadLFH(aRead, &lfh);
  4472. if( rc==SQLITE_OK ){
  4473. pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
  4474. pNew->iDataOff += lfh.nFile + lfh.nExtra;
  4475. if( aBlob && pNew->cds.szCompressed ){
  4476. pNew->aData = &pNew->aExtra[nExtra];
  4477. memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
  4478. }
  4479. }else{
  4480. *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
  4481. (int)pNew->cds.iOffset
  4482. );
  4483. }
  4484. }
  4485. if( rc!=SQLITE_OK ){
  4486. zipfileEntryFree(pNew);
  4487. }else{
  4488. *ppEntry = pNew;
  4489. }
  4490. }
  4491. return rc;
  4492. }
  4493. /*
  4494. ** Advance an ZipfileCsr to its next row of output.
  4495. */
  4496. static int zipfileNext(sqlite3_vtab_cursor *cur){
  4497. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4498. int rc = SQLITE_OK;
  4499. if( pCsr->pFile ){
  4500. i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
  4501. zipfileEntryFree(pCsr->pCurrent);
  4502. pCsr->pCurrent = 0;
  4503. if( pCsr->iNextOff>=iEof ){
  4504. pCsr->bEof = 1;
  4505. }else{
  4506. ZipfileEntry *p = 0;
  4507. ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
  4508. rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
  4509. if( rc==SQLITE_OK ){
  4510. pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
  4511. pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
  4512. }
  4513. pCsr->pCurrent = p;
  4514. }
  4515. }else{
  4516. if( !pCsr->bNoop ){
  4517. pCsr->pCurrent = pCsr->pCurrent->pNext;
  4518. }
  4519. if( pCsr->pCurrent==0 ){
  4520. pCsr->bEof = 1;
  4521. }
  4522. }
  4523. pCsr->bNoop = 0;
  4524. return rc;
  4525. }
  4526. static void zipfileFree(void *p) {
  4527. sqlite3_free(p);
  4528. }
  4529. /*
  4530. ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
  4531. ** size is nOut bytes. This function uncompresses the data and sets the
  4532. ** return value in context pCtx to the result (a blob).
  4533. **
  4534. ** If an error occurs, an error code is left in pCtx instead.
  4535. */
  4536. static void zipfileInflate(
  4537. sqlite3_context *pCtx, /* Store result here */
  4538. const u8 *aIn, /* Compressed data */
  4539. int nIn, /* Size of buffer aIn[] in bytes */
  4540. int nOut /* Expected output size */
  4541. ){
  4542. u8 *aRes = sqlite3_malloc(nOut);
  4543. if( aRes==0 ){
  4544. sqlite3_result_error_nomem(pCtx);
  4545. }else{
  4546. int err;
  4547. z_stream str;
  4548. memset(&str, 0, sizeof(str));
  4549. str.next_in = (Byte*)aIn;
  4550. str.avail_in = nIn;
  4551. str.next_out = (Byte*)aRes;
  4552. str.avail_out = nOut;
  4553. err = inflateInit2(&str, -15);
  4554. if( err!=Z_OK ){
  4555. zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
  4556. }else{
  4557. err = inflate(&str, Z_NO_FLUSH);
  4558. if( err!=Z_STREAM_END ){
  4559. zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
  4560. }else{
  4561. sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
  4562. aRes = 0;
  4563. }
  4564. }
  4565. sqlite3_free(aRes);
  4566. inflateEnd(&str);
  4567. }
  4568. }
  4569. /*
  4570. ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
  4571. ** compresses it and sets (*ppOut) to point to a buffer containing the
  4572. ** compressed data. The caller is responsible for eventually calling
  4573. ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
  4574. ** is set to the size of buffer (*ppOut) in bytes.
  4575. **
  4576. ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
  4577. ** code is returned and an error message left in virtual-table handle
  4578. ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
  4579. ** case.
  4580. */
  4581. static int zipfileDeflate(
  4582. const u8 *aIn, int nIn, /* Input */
  4583. u8 **ppOut, int *pnOut, /* Output */
  4584. char **pzErr /* OUT: Error message */
  4585. ){
  4586. int nAlloc = (int)compressBound(nIn);
  4587. u8 *aOut;
  4588. int rc = SQLITE_OK;
  4589. aOut = (u8*)sqlite3_malloc(nAlloc);
  4590. if( aOut==0 ){
  4591. rc = SQLITE_NOMEM;
  4592. }else{
  4593. int res;
  4594. z_stream str;
  4595. memset(&str, 0, sizeof(str));
  4596. str.next_in = (Bytef*)aIn;
  4597. str.avail_in = nIn;
  4598. str.next_out = aOut;
  4599. str.avail_out = nAlloc;
  4600. deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
  4601. res = deflate(&str, Z_FINISH);
  4602. if( res==Z_STREAM_END ){
  4603. *ppOut = aOut;
  4604. *pnOut = (int)str.total_out;
  4605. }else{
  4606. sqlite3_free(aOut);
  4607. *pzErr = sqlite3_mprintf("zipfile: deflate() error");
  4608. rc = SQLITE_ERROR;
  4609. }
  4610. deflateEnd(&str);
  4611. }
  4612. return rc;
  4613. }
  4614. /*
  4615. ** Return values of columns for the row at which the series_cursor
  4616. ** is currently pointing.
  4617. */
  4618. static int zipfileColumn(
  4619. sqlite3_vtab_cursor *cur, /* The cursor */
  4620. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  4621. int i /* Which column to return */
  4622. ){
  4623. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4624. ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
  4625. int rc = SQLITE_OK;
  4626. switch( i ){
  4627. case 0: /* name */
  4628. sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
  4629. break;
  4630. case 1: /* mode */
  4631. /* TODO: Whether or not the following is correct surely depends on
  4632. ** the platform on which the archive was created. */
  4633. sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
  4634. break;
  4635. case 2: { /* mtime */
  4636. sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
  4637. break;
  4638. }
  4639. case 3: { /* sz */
  4640. if( sqlite3_vtab_nochange(ctx)==0 ){
  4641. sqlite3_result_int64(ctx, pCDS->szUncompressed);
  4642. }
  4643. break;
  4644. }
  4645. case 4: /* rawdata */
  4646. if( sqlite3_vtab_nochange(ctx) ) break;
  4647. case 5: { /* data */
  4648. if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
  4649. int sz = pCDS->szCompressed;
  4650. int szFinal = pCDS->szUncompressed;
  4651. if( szFinal>0 ){
  4652. u8 *aBuf;
  4653. u8 *aFree = 0;
  4654. if( pCsr->pCurrent->aData ){
  4655. aBuf = pCsr->pCurrent->aData;
  4656. }else{
  4657. aBuf = aFree = sqlite3_malloc(sz);
  4658. if( aBuf==0 ){
  4659. rc = SQLITE_NOMEM;
  4660. }else{
  4661. FILE *pFile = pCsr->pFile;
  4662. if( pFile==0 ){
  4663. pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
  4664. }
  4665. rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
  4666. &pCsr->base.pVtab->zErrMsg
  4667. );
  4668. }
  4669. }
  4670. if( rc==SQLITE_OK ){
  4671. if( i==5 && pCDS->iCompression ){
  4672. zipfileInflate(ctx, aBuf, sz, szFinal);
  4673. }else{
  4674. sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
  4675. }
  4676. }
  4677. sqlite3_free(aFree);
  4678. }else{
  4679. /* Figure out if this is a directory or a zero-sized file. Consider
  4680. ** it to be a directory either if the mode suggests so, or if
  4681. ** the final character in the name is '/'. */
  4682. u32 mode = pCDS->iExternalAttr >> 16;
  4683. if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
  4684. sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
  4685. }
  4686. }
  4687. }
  4688. break;
  4689. }
  4690. case 6: /* method */
  4691. sqlite3_result_int(ctx, pCDS->iCompression);
  4692. break;
  4693. default: /* z */
  4694. assert( i==7 );
  4695. sqlite3_result_int64(ctx, pCsr->iId);
  4696. break;
  4697. }
  4698. return rc;
  4699. }
  4700. /*
  4701. ** Return TRUE if the cursor is at EOF.
  4702. */
  4703. static int zipfileEof(sqlite3_vtab_cursor *cur){
  4704. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4705. return pCsr->bEof;
  4706. }
  4707. /*
  4708. ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
  4709. ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
  4710. ** is guaranteed to be a file-handle open on a zip file.
  4711. **
  4712. ** This function attempts to locate the EOCD record within the zip archive
  4713. ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
  4714. ** returned if successful. Otherwise, an SQLite error code is returned and
  4715. ** an English language error message may be left in virtual-table pTab.
  4716. */
  4717. static int zipfileReadEOCD(
  4718. ZipfileTab *pTab, /* Return errors here */
  4719. const u8 *aBlob, /* Pointer to in-memory file image */
  4720. int nBlob, /* Size of aBlob[] in bytes */
  4721. FILE *pFile, /* Read from this file if aBlob==0 */
  4722. ZipfileEOCD *pEOCD /* Object to populate */
  4723. ){
  4724. u8 *aRead = pTab->aBuffer; /* Temporary buffer */
  4725. int nRead; /* Bytes to read from file */
  4726. int rc = SQLITE_OK;
  4727. if( aBlob==0 ){
  4728. i64 iOff; /* Offset to read from */
  4729. i64 szFile; /* Total size of file in bytes */
  4730. fseek(pFile, 0, SEEK_END);
  4731. szFile = (i64)ftell(pFile);
  4732. if( szFile==0 ){
  4733. memset(pEOCD, 0, sizeof(ZipfileEOCD));
  4734. return SQLITE_OK;
  4735. }
  4736. nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
  4737. iOff = szFile - nRead;
  4738. rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
  4739. }else{
  4740. nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
  4741. aRead = (u8*)&aBlob[nBlob-nRead];
  4742. }
  4743. if( rc==SQLITE_OK ){
  4744. int i;
  4745. /* Scan backwards looking for the signature bytes */
  4746. for(i=nRead-20; i>=0; i--){
  4747. if( aRead[i]==0x50 && aRead[i+1]==0x4b
  4748. && aRead[i+2]==0x05 && aRead[i+3]==0x06
  4749. ){
  4750. break;
  4751. }
  4752. }
  4753. if( i<0 ){
  4754. pTab->base.zErrMsg = sqlite3_mprintf(
  4755. "cannot find end of central directory record"
  4756. );
  4757. return SQLITE_ERROR;
  4758. }
  4759. aRead += i+4;
  4760. pEOCD->iDisk = zipfileRead16(aRead);
  4761. pEOCD->iFirstDisk = zipfileRead16(aRead);
  4762. pEOCD->nEntry = zipfileRead16(aRead);
  4763. pEOCD->nEntryTotal = zipfileRead16(aRead);
  4764. pEOCD->nSize = zipfileRead32(aRead);
  4765. pEOCD->iOffset = zipfileRead32(aRead);
  4766. }
  4767. return rc;
  4768. }
  4769. /*
  4770. ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
  4771. ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
  4772. ** to the end of the list. Otherwise, it is added to the list immediately
  4773. ** before pBefore (which is guaranteed to be a part of said list).
  4774. */
  4775. static void zipfileAddEntry(
  4776. ZipfileTab *pTab,
  4777. ZipfileEntry *pBefore,
  4778. ZipfileEntry *pNew
  4779. ){
  4780. assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
  4781. assert( pNew->pNext==0 );
  4782. if( pBefore==0 ){
  4783. if( pTab->pFirstEntry==0 ){
  4784. pTab->pFirstEntry = pTab->pLastEntry = pNew;
  4785. }else{
  4786. assert( pTab->pLastEntry->pNext==0 );
  4787. pTab->pLastEntry->pNext = pNew;
  4788. pTab->pLastEntry = pNew;
  4789. }
  4790. }else{
  4791. ZipfileEntry **pp;
  4792. for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
  4793. pNew->pNext = pBefore;
  4794. *pp = pNew;
  4795. }
  4796. }
  4797. static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
  4798. ZipfileEOCD eocd;
  4799. int rc;
  4800. int i;
  4801. i64 iOff;
  4802. rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
  4803. iOff = eocd.iOffset;
  4804. for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
  4805. ZipfileEntry *pNew = 0;
  4806. rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
  4807. if( rc==SQLITE_OK ){
  4808. zipfileAddEntry(pTab, 0, pNew);
  4809. iOff += ZIPFILE_CDS_FIXED_SZ;
  4810. iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
  4811. }
  4812. }
  4813. return rc;
  4814. }
  4815. /*
  4816. ** xFilter callback.
  4817. */
  4818. static int zipfileFilter(
  4819. sqlite3_vtab_cursor *cur,
  4820. int idxNum, const char *idxStr,
  4821. int argc, sqlite3_value **argv
  4822. ){
  4823. ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
  4824. ZipfileCsr *pCsr = (ZipfileCsr*)cur;
  4825. const char *zFile = 0; /* Zip file to scan */
  4826. int rc = SQLITE_OK; /* Return Code */
  4827. int bInMemory = 0; /* True for an in-memory zipfile */
  4828. zipfileResetCursor(pCsr);
  4829. if( pTab->zFile ){
  4830. zFile = pTab->zFile;
  4831. }else if( idxNum==0 ){
  4832. zipfileCursorErr(pCsr, "zipfile() function requires an argument");
  4833. return SQLITE_ERROR;
  4834. }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  4835. const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
  4836. int nBlob = sqlite3_value_bytes(argv[0]);
  4837. assert( pTab->pFirstEntry==0 );
  4838. rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
  4839. pCsr->pFreeEntry = pTab->pFirstEntry;
  4840. pTab->pFirstEntry = pTab->pLastEntry = 0;
  4841. if( rc!=SQLITE_OK ) return rc;
  4842. bInMemory = 1;
  4843. }else{
  4844. zFile = (const char*)sqlite3_value_text(argv[0]);
  4845. }
  4846. if( 0==pTab->pWriteFd && 0==bInMemory ){
  4847. pCsr->pFile = fopen(zFile, "rb");
  4848. if( pCsr->pFile==0 ){
  4849. zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
  4850. rc = SQLITE_ERROR;
  4851. }else{
  4852. rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
  4853. if( rc==SQLITE_OK ){
  4854. if( pCsr->eocd.nEntry==0 ){
  4855. pCsr->bEof = 1;
  4856. }else{
  4857. pCsr->iNextOff = pCsr->eocd.iOffset;
  4858. rc = zipfileNext(cur);
  4859. }
  4860. }
  4861. }
  4862. }else{
  4863. pCsr->bNoop = 1;
  4864. pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
  4865. rc = zipfileNext(cur);
  4866. }
  4867. return rc;
  4868. }
  4869. /*
  4870. ** xBestIndex callback.
  4871. */
  4872. static int zipfileBestIndex(
  4873. sqlite3_vtab *tab,
  4874. sqlite3_index_info *pIdxInfo
  4875. ){
  4876. int i;
  4877. for(i=0; i<pIdxInfo->nConstraint; i++){
  4878. const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  4879. if( pCons->usable==0 ) continue;
  4880. if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  4881. if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
  4882. break;
  4883. }
  4884. if( i<pIdxInfo->nConstraint ){
  4885. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  4886. pIdxInfo->aConstraintUsage[i].omit = 1;
  4887. pIdxInfo->estimatedCost = 1000.0;
  4888. pIdxInfo->idxNum = 1;
  4889. }else{
  4890. pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
  4891. pIdxInfo->idxNum = 0;
  4892. }
  4893. return SQLITE_OK;
  4894. }
  4895. static ZipfileEntry *zipfileNewEntry(const char *zPath){
  4896. ZipfileEntry *pNew;
  4897. pNew = sqlite3_malloc(sizeof(ZipfileEntry));
  4898. if( pNew ){
  4899. memset(pNew, 0, sizeof(ZipfileEntry));
  4900. pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
  4901. if( pNew->cds.zFile==0 ){
  4902. sqlite3_free(pNew);
  4903. pNew = 0;
  4904. }
  4905. }
  4906. return pNew;
  4907. }
  4908. static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
  4909. ZipfileCDS *pCds = &pEntry->cds;
  4910. u8 *a = aBuf;
  4911. pCds->nExtra = 9;
  4912. /* Write the LFH itself */
  4913. zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
  4914. zipfileWrite16(a, pCds->iVersionExtract);
  4915. zipfileWrite16(a, pCds->flags);
  4916. zipfileWrite16(a, pCds->iCompression);
  4917. zipfileWrite16(a, pCds->mTime);
  4918. zipfileWrite16(a, pCds->mDate);
  4919. zipfileWrite32(a, pCds->crc32);
  4920. zipfileWrite32(a, pCds->szCompressed);
  4921. zipfileWrite32(a, pCds->szUncompressed);
  4922. zipfileWrite16(a, (u16)pCds->nFile);
  4923. zipfileWrite16(a, pCds->nExtra);
  4924. assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
  4925. /* Add the file name */
  4926. memcpy(a, pCds->zFile, (int)pCds->nFile);
  4927. a += (int)pCds->nFile;
  4928. /* The "extra" data */
  4929. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  4930. zipfileWrite16(a, 5);
  4931. *a++ = 0x01;
  4932. zipfileWrite32(a, pEntry->mUnixTime);
  4933. return a-aBuf;
  4934. }
  4935. static int zipfileAppendEntry(
  4936. ZipfileTab *pTab,
  4937. ZipfileEntry *pEntry,
  4938. const u8 *pData,
  4939. int nData
  4940. ){
  4941. u8 *aBuf = pTab->aBuffer;
  4942. int nBuf;
  4943. int rc;
  4944. nBuf = zipfileSerializeLFH(pEntry, aBuf);
  4945. rc = zipfileAppendData(pTab, aBuf, nBuf);
  4946. if( rc==SQLITE_OK ){
  4947. pEntry->iDataOff = pTab->szCurrent;
  4948. rc = zipfileAppendData(pTab, pData, nData);
  4949. }
  4950. return rc;
  4951. }
  4952. static int zipfileGetMode(
  4953. sqlite3_value *pVal,
  4954. int bIsDir, /* If true, default to directory */
  4955. u32 *pMode, /* OUT: Mode value */
  4956. char **pzErr /* OUT: Error message */
  4957. ){
  4958. const char *z = (const char*)sqlite3_value_text(pVal);
  4959. u32 mode = 0;
  4960. if( z==0 ){
  4961. mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
  4962. }else if( z[0]>='0' && z[0]<='9' ){
  4963. mode = (unsigned int)sqlite3_value_int(pVal);
  4964. }else{
  4965. const char zTemplate[11] = "-rwxrwxrwx";
  4966. int i;
  4967. if( strlen(z)!=10 ) goto parse_error;
  4968. switch( z[0] ){
  4969. case '-': mode |= S_IFREG; break;
  4970. case 'd': mode |= S_IFDIR; break;
  4971. case 'l': mode |= S_IFLNK; break;
  4972. default: goto parse_error;
  4973. }
  4974. for(i=1; i<10; i++){
  4975. if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
  4976. else if( z[i]!='-' ) goto parse_error;
  4977. }
  4978. }
  4979. if( ((mode & S_IFDIR)==0)==bIsDir ){
  4980. /* The "mode" attribute is a directory, but data has been specified.
  4981. ** Or vice-versa - no data but "mode" is a file or symlink. */
  4982. *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
  4983. return SQLITE_CONSTRAINT;
  4984. }
  4985. *pMode = mode;
  4986. return SQLITE_OK;
  4987. parse_error:
  4988. *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
  4989. return SQLITE_ERROR;
  4990. }
  4991. /*
  4992. ** Both (const char*) arguments point to nul-terminated strings. Argument
  4993. ** nB is the value of strlen(zB). This function returns 0 if the strings are
  4994. ** identical, ignoring any trailing '/' character in either path. */
  4995. static int zipfileComparePath(const char *zA, const char *zB, int nB){
  4996. int nA = (int)strlen(zA);
  4997. if( zA[nA-1]=='/' ) nA--;
  4998. if( zB[nB-1]=='/' ) nB--;
  4999. if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
  5000. return 1;
  5001. }
  5002. static int zipfileBegin(sqlite3_vtab *pVtab){
  5003. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  5004. int rc = SQLITE_OK;
  5005. assert( pTab->pWriteFd==0 );
  5006. /* Open a write fd on the file. Also load the entire central directory
  5007. ** structure into memory. During the transaction any new file data is
  5008. ** appended to the archive file, but the central directory is accumulated
  5009. ** in main-memory until the transaction is committed. */
  5010. pTab->pWriteFd = fopen(pTab->zFile, "ab+");
  5011. if( pTab->pWriteFd==0 ){
  5012. pTab->base.zErrMsg = sqlite3_mprintf(
  5013. "zipfile: failed to open file %s for writing", pTab->zFile
  5014. );
  5015. rc = SQLITE_ERROR;
  5016. }else{
  5017. fseek(pTab->pWriteFd, 0, SEEK_END);
  5018. pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
  5019. rc = zipfileLoadDirectory(pTab, 0, 0);
  5020. }
  5021. if( rc!=SQLITE_OK ){
  5022. zipfileCleanupTransaction(pTab);
  5023. }
  5024. return rc;
  5025. }
  5026. /*
  5027. ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
  5028. ** time(2)).
  5029. */
  5030. static u32 zipfileTime(void){
  5031. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  5032. u32 ret;
  5033. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  5034. i64 ms;
  5035. pVfs->xCurrentTimeInt64(pVfs, &ms);
  5036. ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
  5037. }else{
  5038. double day;
  5039. pVfs->xCurrentTime(pVfs, &day);
  5040. ret = (u32)((day - 2440587.5) * 86400);
  5041. }
  5042. return ret;
  5043. }
  5044. /*
  5045. ** Return a 32-bit timestamp in UNIX epoch format.
  5046. **
  5047. ** If the value passed as the only argument is either NULL or an SQL NULL,
  5048. ** return the current time. Otherwise, return the value stored in (*pVal)
  5049. ** cast to a 32-bit unsigned integer.
  5050. */
  5051. static u32 zipfileGetTime(sqlite3_value *pVal){
  5052. if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
  5053. return zipfileTime();
  5054. }
  5055. return (u32)sqlite3_value_int64(pVal);
  5056. }
  5057. /*
  5058. ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
  5059. ** linked list. Remove it from the list and free the object.
  5060. */
  5061. static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
  5062. if( pOld ){
  5063. ZipfileEntry **pp;
  5064. for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
  5065. *pp = (*pp)->pNext;
  5066. zipfileEntryFree(pOld);
  5067. }
  5068. }
  5069. /*
  5070. ** xUpdate method.
  5071. */
  5072. static int zipfileUpdate(
  5073. sqlite3_vtab *pVtab,
  5074. int nVal,
  5075. sqlite3_value **apVal,
  5076. sqlite_int64 *pRowid
  5077. ){
  5078. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  5079. int rc = SQLITE_OK; /* Return Code */
  5080. ZipfileEntry *pNew = 0; /* New in-memory CDS entry */
  5081. u32 mode = 0; /* Mode for new entry */
  5082. u32 mTime = 0; /* Modification time for new entry */
  5083. i64 sz = 0; /* Uncompressed size */
  5084. const char *zPath = 0; /* Path for new entry */
  5085. int nPath = 0; /* strlen(zPath) */
  5086. const u8 *pData = 0; /* Pointer to buffer containing content */
  5087. int nData = 0; /* Size of pData buffer in bytes */
  5088. int iMethod = 0; /* Compression method for new entry */
  5089. u8 *pFree = 0; /* Free this */
  5090. char *zFree = 0; /* Also free this */
  5091. ZipfileEntry *pOld = 0;
  5092. ZipfileEntry *pOld2 = 0;
  5093. int bUpdate = 0; /* True for an update that modifies "name" */
  5094. int bIsDir = 0;
  5095. u32 iCrc32 = 0;
  5096. if( pTab->pWriteFd==0 ){
  5097. rc = zipfileBegin(pVtab);
  5098. if( rc!=SQLITE_OK ) return rc;
  5099. }
  5100. /* If this is a DELETE or UPDATE, find the archive entry to delete. */
  5101. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  5102. const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
  5103. int nDelete = (int)strlen(zDelete);
  5104. if( nVal>1 ){
  5105. const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
  5106. if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
  5107. bUpdate = 1;
  5108. }
  5109. }
  5110. for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
  5111. if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
  5112. break;
  5113. }
  5114. assert( pOld->pNext );
  5115. }
  5116. }
  5117. if( nVal>1 ){
  5118. /* Check that "sz" and "rawdata" are both NULL: */
  5119. if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
  5120. zipfileTableErr(pTab, "sz must be NULL");
  5121. rc = SQLITE_CONSTRAINT;
  5122. }
  5123. if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
  5124. zipfileTableErr(pTab, "rawdata must be NULL");
  5125. rc = SQLITE_CONSTRAINT;
  5126. }
  5127. if( rc==SQLITE_OK ){
  5128. if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
  5129. /* data=NULL. A directory */
  5130. bIsDir = 1;
  5131. }else{
  5132. /* Value specified for "data", and possibly "method". This must be
  5133. ** a regular file or a symlink. */
  5134. const u8 *aIn = sqlite3_value_blob(apVal[7]);
  5135. int nIn = sqlite3_value_bytes(apVal[7]);
  5136. int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
  5137. iMethod = sqlite3_value_int(apVal[8]);
  5138. sz = nIn;
  5139. pData = aIn;
  5140. nData = nIn;
  5141. if( iMethod!=0 && iMethod!=8 ){
  5142. zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
  5143. rc = SQLITE_CONSTRAINT;
  5144. }else{
  5145. if( bAuto || iMethod ){
  5146. int nCmp;
  5147. rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
  5148. if( rc==SQLITE_OK ){
  5149. if( iMethod || nCmp<nIn ){
  5150. iMethod = 8;
  5151. pData = pFree;
  5152. nData = nCmp;
  5153. }
  5154. }
  5155. }
  5156. iCrc32 = crc32(0, aIn, nIn);
  5157. }
  5158. }
  5159. }
  5160. if( rc==SQLITE_OK ){
  5161. rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
  5162. }
  5163. if( rc==SQLITE_OK ){
  5164. zPath = (const char*)sqlite3_value_text(apVal[2]);
  5165. nPath = (int)strlen(zPath);
  5166. mTime = zipfileGetTime(apVal[4]);
  5167. }
  5168. if( rc==SQLITE_OK && bIsDir ){
  5169. /* For a directory, check that the last character in the path is a
  5170. ** '/'. This appears to be required for compatibility with info-zip
  5171. ** (the unzip command on unix). It does not create directories
  5172. ** otherwise. */
  5173. if( zPath[nPath-1]!='/' ){
  5174. zFree = sqlite3_mprintf("%s/", zPath);
  5175. if( zFree==0 ){ rc = SQLITE_NOMEM; }
  5176. zPath = (const char*)zFree;
  5177. nPath++;
  5178. }
  5179. }
  5180. /* Check that we're not inserting a duplicate entry -OR- updating an
  5181. ** entry with a path, thereby making it into a duplicate. */
  5182. if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
  5183. ZipfileEntry *p;
  5184. for(p=pTab->pFirstEntry; p; p=p->pNext){
  5185. if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
  5186. switch( sqlite3_vtab_on_conflict(pTab->db) ){
  5187. case SQLITE_IGNORE: {
  5188. goto zipfile_update_done;
  5189. }
  5190. case SQLITE_REPLACE: {
  5191. pOld2 = p;
  5192. break;
  5193. }
  5194. default: {
  5195. zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
  5196. rc = SQLITE_CONSTRAINT;
  5197. break;
  5198. }
  5199. }
  5200. break;
  5201. }
  5202. }
  5203. }
  5204. if( rc==SQLITE_OK ){
  5205. /* Create the new CDS record. */
  5206. pNew = zipfileNewEntry(zPath);
  5207. if( pNew==0 ){
  5208. rc = SQLITE_NOMEM;
  5209. }else{
  5210. pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  5211. pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  5212. pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  5213. pNew->cds.iCompression = (u16)iMethod;
  5214. zipfileMtimeToDos(&pNew->cds, mTime);
  5215. pNew->cds.crc32 = iCrc32;
  5216. pNew->cds.szCompressed = nData;
  5217. pNew->cds.szUncompressed = (u32)sz;
  5218. pNew->cds.iExternalAttr = (mode<<16);
  5219. pNew->cds.iOffset = (u32)pTab->szCurrent;
  5220. pNew->cds.nFile = (u16)nPath;
  5221. pNew->mUnixTime = (u32)mTime;
  5222. rc = zipfileAppendEntry(pTab, pNew, pData, nData);
  5223. zipfileAddEntry(pTab, pOld, pNew);
  5224. }
  5225. }
  5226. }
  5227. if( rc==SQLITE_OK && (pOld || pOld2) ){
  5228. ZipfileCsr *pCsr;
  5229. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  5230. if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
  5231. pCsr->pCurrent = pCsr->pCurrent->pNext;
  5232. pCsr->bNoop = 1;
  5233. }
  5234. }
  5235. zipfileRemoveEntryFromList(pTab, pOld);
  5236. zipfileRemoveEntryFromList(pTab, pOld2);
  5237. }
  5238. zipfile_update_done:
  5239. sqlite3_free(pFree);
  5240. sqlite3_free(zFree);
  5241. return rc;
  5242. }
  5243. static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
  5244. u8 *a = aBuf;
  5245. zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
  5246. zipfileWrite16(a, p->iDisk);
  5247. zipfileWrite16(a, p->iFirstDisk);
  5248. zipfileWrite16(a, p->nEntry);
  5249. zipfileWrite16(a, p->nEntryTotal);
  5250. zipfileWrite32(a, p->nSize);
  5251. zipfileWrite32(a, p->iOffset);
  5252. zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/
  5253. return a-aBuf;
  5254. }
  5255. static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
  5256. int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
  5257. assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
  5258. return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
  5259. }
  5260. /*
  5261. ** Serialize the CDS structure into buffer aBuf[]. Return the number
  5262. ** of bytes written.
  5263. */
  5264. static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
  5265. u8 *a = aBuf;
  5266. ZipfileCDS *pCDS = &pEntry->cds;
  5267. if( pEntry->aExtra==0 ){
  5268. pCDS->nExtra = 9;
  5269. }
  5270. zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
  5271. zipfileWrite16(a, pCDS->iVersionMadeBy);
  5272. zipfileWrite16(a, pCDS->iVersionExtract);
  5273. zipfileWrite16(a, pCDS->flags);
  5274. zipfileWrite16(a, pCDS->iCompression);
  5275. zipfileWrite16(a, pCDS->mTime);
  5276. zipfileWrite16(a, pCDS->mDate);
  5277. zipfileWrite32(a, pCDS->crc32);
  5278. zipfileWrite32(a, pCDS->szCompressed);
  5279. zipfileWrite32(a, pCDS->szUncompressed);
  5280. assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
  5281. zipfileWrite16(a, pCDS->nFile);
  5282. zipfileWrite16(a, pCDS->nExtra);
  5283. zipfileWrite16(a, pCDS->nComment);
  5284. zipfileWrite16(a, pCDS->iDiskStart);
  5285. zipfileWrite16(a, pCDS->iInternalAttr);
  5286. zipfileWrite32(a, pCDS->iExternalAttr);
  5287. zipfileWrite32(a, pCDS->iOffset);
  5288. memcpy(a, pCDS->zFile, pCDS->nFile);
  5289. a += pCDS->nFile;
  5290. if( pEntry->aExtra ){
  5291. int n = (int)pCDS->nExtra + (int)pCDS->nComment;
  5292. memcpy(a, pEntry->aExtra, n);
  5293. a += n;
  5294. }else{
  5295. assert( pCDS->nExtra==9 );
  5296. zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
  5297. zipfileWrite16(a, 5);
  5298. *a++ = 0x01;
  5299. zipfileWrite32(a, pEntry->mUnixTime);
  5300. }
  5301. return a-aBuf;
  5302. }
  5303. static int zipfileCommit(sqlite3_vtab *pVtab){
  5304. ZipfileTab *pTab = (ZipfileTab*)pVtab;
  5305. int rc = SQLITE_OK;
  5306. if( pTab->pWriteFd ){
  5307. i64 iOffset = pTab->szCurrent;
  5308. ZipfileEntry *p;
  5309. ZipfileEOCD eocd;
  5310. int nEntry = 0;
  5311. /* Write out all entries */
  5312. for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
  5313. int n = zipfileSerializeCDS(p, pTab->aBuffer);
  5314. rc = zipfileAppendData(pTab, pTab->aBuffer, n);
  5315. nEntry++;
  5316. }
  5317. /* Write out the EOCD record */
  5318. eocd.iDisk = 0;
  5319. eocd.iFirstDisk = 0;
  5320. eocd.nEntry = (u16)nEntry;
  5321. eocd.nEntryTotal = (u16)nEntry;
  5322. eocd.nSize = (u32)(pTab->szCurrent - iOffset);
  5323. eocd.iOffset = (u32)iOffset;
  5324. rc = zipfileAppendEOCD(pTab, &eocd);
  5325. zipfileCleanupTransaction(pTab);
  5326. }
  5327. return rc;
  5328. }
  5329. static int zipfileRollback(sqlite3_vtab *pVtab){
  5330. return zipfileCommit(pVtab);
  5331. }
  5332. static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
  5333. ZipfileCsr *pCsr;
  5334. for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
  5335. if( iId==pCsr->iId ) break;
  5336. }
  5337. return pCsr;
  5338. }
  5339. static void zipfileFunctionCds(
  5340. sqlite3_context *context,
  5341. int argc,
  5342. sqlite3_value **argv
  5343. ){
  5344. ZipfileCsr *pCsr;
  5345. ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
  5346. assert( argc>0 );
  5347. pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
  5348. if( pCsr ){
  5349. ZipfileCDS *p = &pCsr->pCurrent->cds;
  5350. char *zRes = sqlite3_mprintf("{"
  5351. "\"version-made-by\" : %u, "
  5352. "\"version-to-extract\" : %u, "
  5353. "\"flags\" : %u, "
  5354. "\"compression\" : %u, "
  5355. "\"time\" : %u, "
  5356. "\"date\" : %u, "
  5357. "\"crc32\" : %u, "
  5358. "\"compressed-size\" : %u, "
  5359. "\"uncompressed-size\" : %u, "
  5360. "\"file-name-length\" : %u, "
  5361. "\"extra-field-length\" : %u, "
  5362. "\"file-comment-length\" : %u, "
  5363. "\"disk-number-start\" : %u, "
  5364. "\"internal-attr\" : %u, "
  5365. "\"external-attr\" : %u, "
  5366. "\"offset\" : %u }",
  5367. (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
  5368. (u32)p->flags, (u32)p->iCompression,
  5369. (u32)p->mTime, (u32)p->mDate,
  5370. (u32)p->crc32, (u32)p->szCompressed,
  5371. (u32)p->szUncompressed, (u32)p->nFile,
  5372. (u32)p->nExtra, (u32)p->nComment,
  5373. (u32)p->iDiskStart, (u32)p->iInternalAttr,
  5374. (u32)p->iExternalAttr, (u32)p->iOffset
  5375. );
  5376. if( zRes==0 ){
  5377. sqlite3_result_error_nomem(context);
  5378. }else{
  5379. sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
  5380. sqlite3_free(zRes);
  5381. }
  5382. }
  5383. }
  5384. /*
  5385. ** xFindFunction method.
  5386. */
  5387. static int zipfileFindFunction(
  5388. sqlite3_vtab *pVtab, /* Virtual table handle */
  5389. int nArg, /* Number of SQL function arguments */
  5390. const char *zName, /* Name of SQL function */
  5391. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  5392. void **ppArg /* OUT: User data for *pxFunc */
  5393. ){
  5394. if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
  5395. *pxFunc = zipfileFunctionCds;
  5396. *ppArg = (void*)pVtab;
  5397. return 1;
  5398. }
  5399. return 0;
  5400. }
  5401. typedef struct ZipfileBuffer ZipfileBuffer;
  5402. struct ZipfileBuffer {
  5403. u8 *a; /* Pointer to buffer */
  5404. int n; /* Size of buffer in bytes */
  5405. int nAlloc; /* Byte allocated at a[] */
  5406. };
  5407. typedef struct ZipfileCtx ZipfileCtx;
  5408. struct ZipfileCtx {
  5409. int nEntry;
  5410. ZipfileBuffer body;
  5411. ZipfileBuffer cds;
  5412. };
  5413. static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
  5414. if( pBuf->n+nByte>pBuf->nAlloc ){
  5415. u8 *aNew;
  5416. int nNew = pBuf->n ? pBuf->n*2 : 512;
  5417. int nReq = pBuf->n + nByte;
  5418. while( nNew<nReq ) nNew = nNew*2;
  5419. aNew = sqlite3_realloc(pBuf->a, nNew);
  5420. if( aNew==0 ) return SQLITE_NOMEM;
  5421. pBuf->a = aNew;
  5422. pBuf->nAlloc = nNew;
  5423. }
  5424. return SQLITE_OK;
  5425. }
  5426. /*
  5427. ** xStep() callback for the zipfile() aggregate. This can be called in
  5428. ** any of the following ways:
  5429. **
  5430. ** SELECT zipfile(name,data) ...
  5431. ** SELECT zipfile(name,mode,mtime,data) ...
  5432. ** SELECT zipfile(name,mode,mtime,data,method) ...
  5433. */
  5434. void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
  5435. ZipfileCtx *p; /* Aggregate function context */
  5436. ZipfileEntry e; /* New entry to add to zip archive */
  5437. sqlite3_value *pName = 0;
  5438. sqlite3_value *pMode = 0;
  5439. sqlite3_value *pMtime = 0;
  5440. sqlite3_value *pData = 0;
  5441. sqlite3_value *pMethod = 0;
  5442. int bIsDir = 0;
  5443. u32 mode;
  5444. int rc = SQLITE_OK;
  5445. char *zErr = 0;
  5446. int iMethod = -1; /* Compression method to use (0 or 8) */
  5447. const u8 *aData = 0; /* Possibly compressed data for new entry */
  5448. int nData = 0; /* Size of aData[] in bytes */
  5449. int szUncompressed = 0; /* Size of data before compression */
  5450. u8 *aFree = 0; /* Free this before returning */
  5451. u32 iCrc32 = 0; /* crc32 of uncompressed data */
  5452. char *zName = 0; /* Path (name) of new entry */
  5453. int nName = 0; /* Size of zName in bytes */
  5454. char *zFree = 0; /* Free this before returning */
  5455. int nByte;
  5456. memset(&e, 0, sizeof(e));
  5457. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  5458. if( p==0 ) return;
  5459. /* Martial the arguments into stack variables */
  5460. if( nVal!=2 && nVal!=4 && nVal!=5 ){
  5461. zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
  5462. rc = SQLITE_ERROR;
  5463. goto zipfile_step_out;
  5464. }
  5465. pName = apVal[0];
  5466. if( nVal==2 ){
  5467. pData = apVal[1];
  5468. }else{
  5469. pMode = apVal[1];
  5470. pMtime = apVal[2];
  5471. pData = apVal[3];
  5472. if( nVal==5 ){
  5473. pMethod = apVal[4];
  5474. }
  5475. }
  5476. /* Check that the 'name' parameter looks ok. */
  5477. zName = (char*)sqlite3_value_text(pName);
  5478. nName = sqlite3_value_bytes(pName);
  5479. if( zName==0 ){
  5480. zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
  5481. rc = SQLITE_ERROR;
  5482. goto zipfile_step_out;
  5483. }
  5484. /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
  5485. ** deflate compression) or NULL (choose automatically). */
  5486. if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
  5487. iMethod = (int)sqlite3_value_int64(pMethod);
  5488. if( iMethod!=0 && iMethod!=8 ){
  5489. zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
  5490. rc = SQLITE_ERROR;
  5491. goto zipfile_step_out;
  5492. }
  5493. }
  5494. /* Now inspect the data. If this is NULL, then the new entry must be a
  5495. ** directory. Otherwise, figure out whether or not the data should
  5496. ** be deflated or simply stored in the zip archive. */
  5497. if( sqlite3_value_type(pData)==SQLITE_NULL ){
  5498. bIsDir = 1;
  5499. iMethod = 0;
  5500. }else{
  5501. aData = sqlite3_value_blob(pData);
  5502. szUncompressed = nData = sqlite3_value_bytes(pData);
  5503. iCrc32 = crc32(0, aData, nData);
  5504. if( iMethod<0 || iMethod==8 ){
  5505. int nOut = 0;
  5506. rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
  5507. if( rc!=SQLITE_OK ){
  5508. goto zipfile_step_out;
  5509. }
  5510. if( iMethod==8 || nOut<nData ){
  5511. aData = aFree;
  5512. nData = nOut;
  5513. iMethod = 8;
  5514. }else{
  5515. iMethod = 0;
  5516. }
  5517. }
  5518. }
  5519. /* Decode the "mode" argument. */
  5520. rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
  5521. if( rc ) goto zipfile_step_out;
  5522. /* Decode the "mtime" argument. */
  5523. e.mUnixTime = zipfileGetTime(pMtime);
  5524. /* If this is a directory entry, ensure that there is exactly one '/'
  5525. ** at the end of the path. Or, if this is not a directory and the path
  5526. ** ends in '/' it is an error. */
  5527. if( bIsDir==0 ){
  5528. if( zName[nName-1]=='/' ){
  5529. zErr = sqlite3_mprintf("non-directory name must not end with /");
  5530. rc = SQLITE_ERROR;
  5531. goto zipfile_step_out;
  5532. }
  5533. }else{
  5534. if( zName[nName-1]!='/' ){
  5535. zName = zFree = sqlite3_mprintf("%s/", zName);
  5536. nName++;
  5537. if( zName==0 ){
  5538. rc = SQLITE_NOMEM;
  5539. goto zipfile_step_out;
  5540. }
  5541. }else{
  5542. while( nName>1 && zName[nName-2]=='/' ) nName--;
  5543. }
  5544. }
  5545. /* Assemble the ZipfileEntry object for the new zip archive entry */
  5546. e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
  5547. e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
  5548. e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
  5549. e.cds.iCompression = (u16)iMethod;
  5550. zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
  5551. e.cds.crc32 = iCrc32;
  5552. e.cds.szCompressed = nData;
  5553. e.cds.szUncompressed = szUncompressed;
  5554. e.cds.iExternalAttr = (mode<<16);
  5555. e.cds.iOffset = p->body.n;
  5556. e.cds.nFile = (u16)nName;
  5557. e.cds.zFile = zName;
  5558. /* Append the LFH to the body of the new archive */
  5559. nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
  5560. if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
  5561. p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
  5562. /* Append the data to the body of the new archive */
  5563. if( nData>0 ){
  5564. if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
  5565. memcpy(&p->body.a[p->body.n], aData, nData);
  5566. p->body.n += nData;
  5567. }
  5568. /* Append the CDS record to the directory of the new archive */
  5569. nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
  5570. if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
  5571. p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
  5572. /* Increment the count of entries in the archive */
  5573. p->nEntry++;
  5574. zipfile_step_out:
  5575. sqlite3_free(aFree);
  5576. sqlite3_free(zFree);
  5577. if( rc ){
  5578. if( zErr ){
  5579. sqlite3_result_error(pCtx, zErr, -1);
  5580. }else{
  5581. sqlite3_result_error_code(pCtx, rc);
  5582. }
  5583. }
  5584. sqlite3_free(zErr);
  5585. }
  5586. /*
  5587. ** xFinalize() callback for zipfile aggregate function.
  5588. */
  5589. void zipfileFinal(sqlite3_context *pCtx){
  5590. ZipfileCtx *p;
  5591. ZipfileEOCD eocd;
  5592. int nZip;
  5593. u8 *aZip;
  5594. p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
  5595. if( p==0 ) return;
  5596. if( p->nEntry>0 ){
  5597. memset(&eocd, 0, sizeof(eocd));
  5598. eocd.nEntry = (u16)p->nEntry;
  5599. eocd.nEntryTotal = (u16)p->nEntry;
  5600. eocd.nSize = p->cds.n;
  5601. eocd.iOffset = p->body.n;
  5602. nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
  5603. aZip = (u8*)sqlite3_malloc(nZip);
  5604. if( aZip==0 ){
  5605. sqlite3_result_error_nomem(pCtx);
  5606. }else{
  5607. memcpy(aZip, p->body.a, p->body.n);
  5608. memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
  5609. zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
  5610. sqlite3_result_blob(pCtx, aZip, nZip, zipfileFree);
  5611. }
  5612. }
  5613. sqlite3_free(p->body.a);
  5614. sqlite3_free(p->cds.a);
  5615. }
  5616. /*
  5617. ** Register the "zipfile" virtual table.
  5618. */
  5619. static int zipfileRegister(sqlite3 *db){
  5620. static sqlite3_module zipfileModule = {
  5621. 1, /* iVersion */
  5622. zipfileConnect, /* xCreate */
  5623. zipfileConnect, /* xConnect */
  5624. zipfileBestIndex, /* xBestIndex */
  5625. zipfileDisconnect, /* xDisconnect */
  5626. zipfileDisconnect, /* xDestroy */
  5627. zipfileOpen, /* xOpen - open a cursor */
  5628. zipfileClose, /* xClose - close a cursor */
  5629. zipfileFilter, /* xFilter - configure scan constraints */
  5630. zipfileNext, /* xNext - advance a cursor */
  5631. zipfileEof, /* xEof - check for end of scan */
  5632. zipfileColumn, /* xColumn - read data */
  5633. 0, /* xRowid - read data */
  5634. zipfileUpdate, /* xUpdate */
  5635. zipfileBegin, /* xBegin */
  5636. 0, /* xSync */
  5637. zipfileCommit, /* xCommit */
  5638. zipfileRollback, /* xRollback */
  5639. zipfileFindFunction, /* xFindMethod */
  5640. 0, /* xRename */
  5641. };
  5642. int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
  5643. if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
  5644. if( rc==SQLITE_OK ){
  5645. rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
  5646. zipfileStep, zipfileFinal
  5647. );
  5648. }
  5649. return rc;
  5650. }
  5651. #else /* SQLITE_OMIT_VIRTUALTABLE */
  5652. # define zipfileRegister(x) SQLITE_OK
  5653. #endif
  5654. #ifdef _WIN32
  5655. #endif
  5656. int sqlite3_zipfile_init(
  5657. sqlite3 *db,
  5658. char **pzErrMsg,
  5659. const sqlite3_api_routines *pApi
  5660. ){
  5661. SQLITE_EXTENSION_INIT2(pApi);
  5662. (void)pzErrMsg; /* Unused parameter */
  5663. return zipfileRegister(db);
  5664. }
  5665. /************************* End ../ext/misc/zipfile.c ********************/
  5666. /************************* Begin ../ext/misc/sqlar.c ******************/
  5667. /*
  5668. ** 2017-12-17
  5669. **
  5670. ** The author disclaims copyright to this source code. In place of
  5671. ** a legal notice, here is a blessing:
  5672. **
  5673. ** May you do good and not evil.
  5674. ** May you find forgiveness for yourself and forgive others.
  5675. ** May you share freely, never taking more than you give.
  5676. **
  5677. ******************************************************************************
  5678. **
  5679. ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
  5680. ** for working with sqlar archives and used by the shell tool's built-in
  5681. ** sqlar support.
  5682. */
  5683. SQLITE_EXTENSION_INIT1
  5684. #include <zlib.h>
  5685. /*
  5686. ** Implementation of the "sqlar_compress(X)" SQL function.
  5687. **
  5688. ** If the type of X is SQLITE_BLOB, and compressing that blob using
  5689. ** zlib utility function compress() yields a smaller blob, return the
  5690. ** compressed blob. Otherwise, return a copy of X.
  5691. **
  5692. ** SQLar uses the "zlib format" for compressed content. The zlib format
  5693. ** contains a two-byte identification header and a four-byte checksum at
  5694. ** the end. This is different from ZIP which uses the raw deflate format.
  5695. **
  5696. ** Future enhancements to SQLar might add support for new compression formats.
  5697. ** If so, those new formats will be identified by alternative headers in the
  5698. ** compressed data.
  5699. */
  5700. static void sqlarCompressFunc(
  5701. sqlite3_context *context,
  5702. int argc,
  5703. sqlite3_value **argv
  5704. ){
  5705. assert( argc==1 );
  5706. if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
  5707. const Bytef *pData = sqlite3_value_blob(argv[0]);
  5708. uLong nData = sqlite3_value_bytes(argv[0]);
  5709. uLongf nOut = compressBound(nData);
  5710. Bytef *pOut;
  5711. pOut = (Bytef*)sqlite3_malloc(nOut);
  5712. if( pOut==0 ){
  5713. sqlite3_result_error_nomem(context);
  5714. return;
  5715. }else{
  5716. if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
  5717. sqlite3_result_error(context, "error in compress()", -1);
  5718. }else if( nOut<nData ){
  5719. sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
  5720. }else{
  5721. sqlite3_result_value(context, argv[0]);
  5722. }
  5723. sqlite3_free(pOut);
  5724. }
  5725. }else{
  5726. sqlite3_result_value(context, argv[0]);
  5727. }
  5728. }
  5729. /*
  5730. ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
  5731. **
  5732. ** Parameter SZ is interpreted as an integer. If it is less than or
  5733. ** equal to zero, then this function returns a copy of X. Or, if
  5734. ** SZ is equal to the size of X when interpreted as a blob, also
  5735. ** return a copy of X. Otherwise, decompress blob X using zlib
  5736. ** utility function uncompress() and return the results (another
  5737. ** blob).
  5738. */
  5739. static void sqlarUncompressFunc(
  5740. sqlite3_context *context,
  5741. int argc,
  5742. sqlite3_value **argv
  5743. ){
  5744. uLong nData;
  5745. uLongf sz;
  5746. assert( argc==2 );
  5747. sz = sqlite3_value_int(argv[1]);
  5748. if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
  5749. sqlite3_result_value(context, argv[0]);
  5750. }else{
  5751. const Bytef *pData= sqlite3_value_blob(argv[0]);
  5752. Bytef *pOut = sqlite3_malloc(sz);
  5753. if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
  5754. sqlite3_result_error(context, "error in uncompress()", -1);
  5755. }else{
  5756. sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
  5757. }
  5758. sqlite3_free(pOut);
  5759. }
  5760. }
  5761. #ifdef _WIN32
  5762. #endif
  5763. int sqlite3_sqlar_init(
  5764. sqlite3 *db,
  5765. char **pzErrMsg,
  5766. const sqlite3_api_routines *pApi
  5767. ){
  5768. int rc = SQLITE_OK;
  5769. SQLITE_EXTENSION_INIT2(pApi);
  5770. (void)pzErrMsg; /* Unused parameter */
  5771. rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
  5772. sqlarCompressFunc, 0, 0);
  5773. if( rc==SQLITE_OK ){
  5774. rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
  5775. sqlarUncompressFunc, 0, 0);
  5776. }
  5777. return rc;
  5778. }
  5779. /************************* End ../ext/misc/sqlar.c ********************/
  5780. #endif
  5781. /************************* Begin ../ext/expert/sqlite3expert.h ******************/
  5782. /*
  5783. ** 2017 April 07
  5784. **
  5785. ** The author disclaims copyright to this source code. In place of
  5786. ** a legal notice, here is a blessing:
  5787. **
  5788. ** May you do good and not evil.
  5789. ** May you find forgiveness for yourself and forgive others.
  5790. ** May you share freely, never taking more than you give.
  5791. **
  5792. *************************************************************************
  5793. */
  5794. typedef struct sqlite3expert sqlite3expert;
  5795. /*
  5796. ** Create a new sqlite3expert object.
  5797. **
  5798. ** If successful, a pointer to the new object is returned and (*pzErr) set
  5799. ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
  5800. ** an English-language error message. In this case it is the responsibility
  5801. ** of the caller to eventually free the error message buffer using
  5802. ** sqlite3_free().
  5803. */
  5804. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
  5805. /*
  5806. ** Configure an sqlite3expert object.
  5807. **
  5808. ** EXPERT_CONFIG_SAMPLE:
  5809. ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
  5810. ** each candidate index. This involves scanning and sorting the entire
  5811. ** contents of each user database table once for each candidate index
  5812. ** associated with the table. For large databases, this can be
  5813. ** prohibitively slow. This option allows the sqlite3expert object to
  5814. ** be configured so that sqlite_stat1 data is instead generated based on a
  5815. ** subset of each table, or so that no sqlite_stat1 data is used at all.
  5816. **
  5817. ** A single integer argument is passed to this option. If the value is less
  5818. ** than or equal to zero, then no sqlite_stat1 data is generated or used by
  5819. ** the analysis - indexes are recommended based on the database schema only.
  5820. ** Or, if the value is 100 or greater, complete sqlite_stat1 data is
  5821. ** generated for each candidate index (this is the default). Finally, if the
  5822. ** value falls between 0 and 100, then it represents the percentage of user
  5823. ** table rows that should be considered when generating sqlite_stat1 data.
  5824. **
  5825. ** Examples:
  5826. **
  5827. ** // Do not generate any sqlite_stat1 data
  5828. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
  5829. **
  5830. ** // Generate sqlite_stat1 data based on 10% of the rows in each table.
  5831. ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
  5832. */
  5833. int sqlite3_expert_config(sqlite3expert *p, int op, ...);
  5834. #define EXPERT_CONFIG_SAMPLE 1 /* int */
  5835. /*
  5836. ** Specify zero or more SQL statements to be included in the analysis.
  5837. **
  5838. ** Buffer zSql must contain zero or more complete SQL statements. This
  5839. ** function parses all statements contained in the buffer and adds them
  5840. ** to the internal list of statements to analyze. If successful, SQLITE_OK
  5841. ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
  5842. ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
  5843. ** may be set to point to an English language error message. In this case
  5844. ** the caller is responsible for eventually freeing the error message buffer
  5845. ** using sqlite3_free().
  5846. **
  5847. ** If an error does occur while processing one of the statements in the
  5848. ** buffer passed as the second argument, none of the statements in the
  5849. ** buffer are added to the analysis.
  5850. **
  5851. ** This function must be called before sqlite3_expert_analyze(). If a call
  5852. ** to this function is made on an sqlite3expert object that has already
  5853. ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
  5854. ** immediately and no statements are added to the analysis.
  5855. */
  5856. int sqlite3_expert_sql(
  5857. sqlite3expert *p, /* From a successful sqlite3_expert_new() */
  5858. const char *zSql, /* SQL statement(s) to add */
  5859. char **pzErr /* OUT: Error message (if any) */
  5860. );
  5861. /*
  5862. ** This function is called after the sqlite3expert object has been configured
  5863. ** with all SQL statements using sqlite3_expert_sql() to actually perform
  5864. ** the analysis. Once this function has been called, it is not possible to
  5865. ** add further SQL statements to the analysis.
  5866. **
  5867. ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
  5868. ** an error occurs, an SQLite error code is returned and (*pzErr) set to
  5869. ** point to a buffer containing an English language error message. In this
  5870. ** case it is the responsibility of the caller to eventually free the buffer
  5871. ** using sqlite3_free().
  5872. **
  5873. ** If an error does occur within this function, the sqlite3expert object
  5874. ** is no longer useful for any purpose. At that point it is no longer
  5875. ** possible to add further SQL statements to the object or to re-attempt
  5876. ** the analysis. The sqlite3expert object must still be freed using a call
  5877. ** sqlite3_expert_destroy().
  5878. */
  5879. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
  5880. /*
  5881. ** Return the total number of statements loaded using sqlite3_expert_sql().
  5882. ** The total number of SQL statements may be different from the total number
  5883. ** to calls to sqlite3_expert_sql().
  5884. */
  5885. int sqlite3_expert_count(sqlite3expert*);
  5886. /*
  5887. ** Return a component of the report.
  5888. **
  5889. ** This function is called after sqlite3_expert_analyze() to extract the
  5890. ** results of the analysis. Each call to this function returns either a
  5891. ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
  5892. ** The value passed as the third argument must be one of the EXPERT_REPORT_*
  5893. ** #define constants defined below.
  5894. **
  5895. ** For some EXPERT_REPORT_* parameters, the buffer returned contains
  5896. ** information relating to a specific SQL statement. In these cases that
  5897. ** SQL statement is identified by the value passed as the second argument.
  5898. ** SQL statements are numbered from 0 in the order in which they are parsed.
  5899. ** If an out-of-range value (less than zero or equal to or greater than the
  5900. ** value returned by sqlite3_expert_count()) is passed as the second argument
  5901. ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
  5902. **
  5903. ** EXPERT_REPORT_SQL:
  5904. ** Return the text of SQL statement iStmt.
  5905. **
  5906. ** EXPERT_REPORT_INDEXES:
  5907. ** Return a buffer containing the CREATE INDEX statements for all recommended
  5908. ** indexes for statement iStmt. If there are no new recommeded indexes, NULL
  5909. ** is returned.
  5910. **
  5911. ** EXPERT_REPORT_PLAN:
  5912. ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
  5913. ** iStmt after the proposed indexes have been added to the database schema.
  5914. **
  5915. ** EXPERT_REPORT_CANDIDATES:
  5916. ** Return a pointer to a buffer containing the CREATE INDEX statements
  5917. ** for all indexes that were tested (for all SQL statements). The iStmt
  5918. ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
  5919. */
  5920. const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
  5921. /*
  5922. ** Values for the third argument passed to sqlite3_expert_report().
  5923. */
  5924. #define EXPERT_REPORT_SQL 1
  5925. #define EXPERT_REPORT_INDEXES 2
  5926. #define EXPERT_REPORT_PLAN 3
  5927. #define EXPERT_REPORT_CANDIDATES 4
  5928. /*
  5929. ** Free an (sqlite3expert*) handle and all associated resources. There
  5930. ** should be one call to this function for each successful call to
  5931. ** sqlite3-expert_new().
  5932. */
  5933. void sqlite3_expert_destroy(sqlite3expert*);
  5934. /************************* End ../ext/expert/sqlite3expert.h ********************/
  5935. /************************* Begin ../ext/expert/sqlite3expert.c ******************/
  5936. /*
  5937. ** 2017 April 09
  5938. **
  5939. ** The author disclaims copyright to this source code. In place of
  5940. ** a legal notice, here is a blessing:
  5941. **
  5942. ** May you do good and not evil.
  5943. ** May you find forgiveness for yourself and forgive others.
  5944. ** May you share freely, never taking more than you give.
  5945. **
  5946. *************************************************************************
  5947. */
  5948. #include <assert.h>
  5949. #include <string.h>
  5950. #include <stdio.h>
  5951. #ifndef SQLITE_OMIT_VIRTUALTABLE
  5952. /* typedef sqlite3_int64 i64; */
  5953. /* typedef sqlite3_uint64 u64; */
  5954. typedef struct IdxColumn IdxColumn;
  5955. typedef struct IdxConstraint IdxConstraint;
  5956. typedef struct IdxScan IdxScan;
  5957. typedef struct IdxStatement IdxStatement;
  5958. typedef struct IdxTable IdxTable;
  5959. typedef struct IdxWrite IdxWrite;
  5960. #define STRLEN (int)strlen
  5961. /*
  5962. ** A temp table name that we assume no user database will actually use.
  5963. ** If this assumption proves incorrect triggers on the table with the
  5964. ** conflicting name will be ignored.
  5965. */
  5966. #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
  5967. /*
  5968. ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
  5969. ** any other type of single-ended range constraint on a column).
  5970. **
  5971. ** pLink:
  5972. ** Used to temporarily link IdxConstraint objects into lists while
  5973. ** creating candidate indexes.
  5974. */
  5975. struct IdxConstraint {
  5976. char *zColl; /* Collation sequence */
  5977. int bRange; /* True for range, false for eq */
  5978. int iCol; /* Constrained table column */
  5979. int bFlag; /* Used by idxFindCompatible() */
  5980. int bDesc; /* True if ORDER BY <expr> DESC */
  5981. IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
  5982. IdxConstraint *pLink; /* See above */
  5983. };
  5984. /*
  5985. ** A single scan of a single table.
  5986. */
  5987. struct IdxScan {
  5988. IdxTable *pTab; /* Associated table object */
  5989. int iDb; /* Database containing table zTable */
  5990. i64 covering; /* Mask of columns required for cov. index */
  5991. IdxConstraint *pOrder; /* ORDER BY columns */
  5992. IdxConstraint *pEq; /* List of == constraints */
  5993. IdxConstraint *pRange; /* List of < constraints */
  5994. IdxScan *pNextScan; /* Next IdxScan object for same analysis */
  5995. };
  5996. /*
  5997. ** Information regarding a single database table. Extracted from
  5998. ** "PRAGMA table_info" by function idxGetTableInfo().
  5999. */
  6000. struct IdxColumn {
  6001. char *zName;
  6002. char *zColl;
  6003. int iPk;
  6004. };
  6005. struct IdxTable {
  6006. int nCol;
  6007. char *zName; /* Table name */
  6008. IdxColumn *aCol;
  6009. IdxTable *pNext; /* Next table in linked list of all tables */
  6010. };
  6011. /*
  6012. ** An object of the following type is created for each unique table/write-op
  6013. ** seen. The objects are stored in a singly-linked list beginning at
  6014. ** sqlite3expert.pWrite.
  6015. */
  6016. struct IdxWrite {
  6017. IdxTable *pTab;
  6018. int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
  6019. IdxWrite *pNext;
  6020. };
  6021. /*
  6022. ** Each statement being analyzed is represented by an instance of this
  6023. ** structure.
  6024. */
  6025. struct IdxStatement {
  6026. int iId; /* Statement number */
  6027. char *zSql; /* SQL statement */
  6028. char *zIdx; /* Indexes */
  6029. char *zEQP; /* Plan */
  6030. IdxStatement *pNext;
  6031. };
  6032. /*
  6033. ** A hash table for storing strings. With space for a payload string
  6034. ** with each entry. Methods are:
  6035. **
  6036. ** idxHashInit()
  6037. ** idxHashClear()
  6038. ** idxHashAdd()
  6039. ** idxHashSearch()
  6040. */
  6041. #define IDX_HASH_SIZE 1023
  6042. typedef struct IdxHashEntry IdxHashEntry;
  6043. typedef struct IdxHash IdxHash;
  6044. struct IdxHashEntry {
  6045. char *zKey; /* nul-terminated key */
  6046. char *zVal; /* nul-terminated value string */
  6047. char *zVal2; /* nul-terminated value string 2 */
  6048. IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
  6049. IdxHashEntry *pNext; /* Next entry in hash */
  6050. };
  6051. struct IdxHash {
  6052. IdxHashEntry *pFirst;
  6053. IdxHashEntry *aHash[IDX_HASH_SIZE];
  6054. };
  6055. /*
  6056. ** sqlite3expert object.
  6057. */
  6058. struct sqlite3expert {
  6059. int iSample; /* Percentage of tables to sample for stat1 */
  6060. sqlite3 *db; /* User database */
  6061. sqlite3 *dbm; /* In-memory db for this analysis */
  6062. sqlite3 *dbv; /* Vtab schema for this analysis */
  6063. IdxTable *pTable; /* List of all IdxTable objects */
  6064. IdxScan *pScan; /* List of scan objects */
  6065. IdxWrite *pWrite; /* List of write objects */
  6066. IdxStatement *pStatement; /* List of IdxStatement objects */
  6067. int bRun; /* True once analysis has run */
  6068. char **pzErrmsg;
  6069. int rc; /* Error code from whereinfo hook */
  6070. IdxHash hIdx; /* Hash containing all candidate indexes */
  6071. char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
  6072. };
  6073. /*
  6074. ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
  6075. ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
  6076. */
  6077. static void *idxMalloc(int *pRc, int nByte){
  6078. void *pRet;
  6079. assert( *pRc==SQLITE_OK );
  6080. assert( nByte>0 );
  6081. pRet = sqlite3_malloc(nByte);
  6082. if( pRet ){
  6083. memset(pRet, 0, nByte);
  6084. }else{
  6085. *pRc = SQLITE_NOMEM;
  6086. }
  6087. return pRet;
  6088. }
  6089. /*
  6090. ** Initialize an IdxHash hash table.
  6091. */
  6092. static void idxHashInit(IdxHash *pHash){
  6093. memset(pHash, 0, sizeof(IdxHash));
  6094. }
  6095. /*
  6096. ** Reset an IdxHash hash table.
  6097. */
  6098. static void idxHashClear(IdxHash *pHash){
  6099. int i;
  6100. for(i=0; i<IDX_HASH_SIZE; i++){
  6101. IdxHashEntry *pEntry;
  6102. IdxHashEntry *pNext;
  6103. for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
  6104. pNext = pEntry->pHashNext;
  6105. sqlite3_free(pEntry->zVal2);
  6106. sqlite3_free(pEntry);
  6107. }
  6108. }
  6109. memset(pHash, 0, sizeof(IdxHash));
  6110. }
  6111. /*
  6112. ** Return the index of the hash bucket that the string specified by the
  6113. ** arguments to this function belongs.
  6114. */
  6115. static int idxHashString(const char *z, int n){
  6116. unsigned int ret = 0;
  6117. int i;
  6118. for(i=0; i<n; i++){
  6119. ret += (ret<<3) + (unsigned char)(z[i]);
  6120. }
  6121. return (int)(ret % IDX_HASH_SIZE);
  6122. }
  6123. /*
  6124. ** If zKey is already present in the hash table, return non-zero and do
  6125. ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
  6126. ** the hash table passed as the second argument.
  6127. */
  6128. static int idxHashAdd(
  6129. int *pRc,
  6130. IdxHash *pHash,
  6131. const char *zKey,
  6132. const char *zVal
  6133. ){
  6134. int nKey = STRLEN(zKey);
  6135. int iHash = idxHashString(zKey, nKey);
  6136. int nVal = (zVal ? STRLEN(zVal) : 0);
  6137. IdxHashEntry *pEntry;
  6138. assert( iHash>=0 );
  6139. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  6140. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  6141. return 1;
  6142. }
  6143. }
  6144. pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
  6145. if( pEntry ){
  6146. pEntry->zKey = (char*)&pEntry[1];
  6147. memcpy(pEntry->zKey, zKey, nKey);
  6148. if( zVal ){
  6149. pEntry->zVal = &pEntry->zKey[nKey+1];
  6150. memcpy(pEntry->zVal, zVal, nVal);
  6151. }
  6152. pEntry->pHashNext = pHash->aHash[iHash];
  6153. pHash->aHash[iHash] = pEntry;
  6154. pEntry->pNext = pHash->pFirst;
  6155. pHash->pFirst = pEntry;
  6156. }
  6157. return 0;
  6158. }
  6159. /*
  6160. ** If zKey/nKey is present in the hash table, return a pointer to the
  6161. ** hash-entry object.
  6162. */
  6163. static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
  6164. int iHash;
  6165. IdxHashEntry *pEntry;
  6166. if( nKey<0 ) nKey = STRLEN(zKey);
  6167. iHash = idxHashString(zKey, nKey);
  6168. assert( iHash>=0 );
  6169. for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
  6170. if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
  6171. return pEntry;
  6172. }
  6173. }
  6174. return 0;
  6175. }
  6176. /*
  6177. ** If the hash table contains an entry with a key equal to the string
  6178. ** passed as the final two arguments to this function, return a pointer
  6179. ** to the payload string. Otherwise, if zKey/nKey is not present in the
  6180. ** hash table, return NULL.
  6181. */
  6182. static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
  6183. IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
  6184. if( pEntry ) return pEntry->zVal;
  6185. return 0;
  6186. }
  6187. /*
  6188. ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
  6189. ** variable to point to a copy of nul-terminated string zColl.
  6190. */
  6191. static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
  6192. IdxConstraint *pNew;
  6193. int nColl = STRLEN(zColl);
  6194. assert( *pRc==SQLITE_OK );
  6195. pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
  6196. if( pNew ){
  6197. pNew->zColl = (char*)&pNew[1];
  6198. memcpy(pNew->zColl, zColl, nColl+1);
  6199. }
  6200. return pNew;
  6201. }
  6202. /*
  6203. ** An error associated with database handle db has just occurred. Pass
  6204. ** the error message to callback function xOut.
  6205. */
  6206. static void idxDatabaseError(
  6207. sqlite3 *db, /* Database handle */
  6208. char **pzErrmsg /* Write error here */
  6209. ){
  6210. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  6211. }
  6212. /*
  6213. ** Prepare an SQL statement.
  6214. */
  6215. static int idxPrepareStmt(
  6216. sqlite3 *db, /* Database handle to compile against */
  6217. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  6218. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  6219. const char *zSql /* SQL statement to compile */
  6220. ){
  6221. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  6222. if( rc!=SQLITE_OK ){
  6223. *ppStmt = 0;
  6224. idxDatabaseError(db, pzErrmsg);
  6225. }
  6226. return rc;
  6227. }
  6228. /*
  6229. ** Prepare an SQL statement using the results of a printf() formatting.
  6230. */
  6231. static int idxPrintfPrepareStmt(
  6232. sqlite3 *db, /* Database handle to compile against */
  6233. sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
  6234. char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
  6235. const char *zFmt, /* printf() format of SQL statement */
  6236. ... /* Trailing printf() arguments */
  6237. ){
  6238. va_list ap;
  6239. int rc;
  6240. char *zSql;
  6241. va_start(ap, zFmt);
  6242. zSql = sqlite3_vmprintf(zFmt, ap);
  6243. if( zSql==0 ){
  6244. rc = SQLITE_NOMEM;
  6245. }else{
  6246. rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
  6247. sqlite3_free(zSql);
  6248. }
  6249. va_end(ap);
  6250. return rc;
  6251. }
  6252. /*************************************************************************
  6253. ** Beginning of virtual table implementation.
  6254. */
  6255. typedef struct ExpertVtab ExpertVtab;
  6256. struct ExpertVtab {
  6257. sqlite3_vtab base;
  6258. IdxTable *pTab;
  6259. sqlite3expert *pExpert;
  6260. };
  6261. typedef struct ExpertCsr ExpertCsr;
  6262. struct ExpertCsr {
  6263. sqlite3_vtab_cursor base;
  6264. sqlite3_stmt *pData;
  6265. };
  6266. static char *expertDequote(const char *zIn){
  6267. int n = STRLEN(zIn);
  6268. char *zRet = sqlite3_malloc(n);
  6269. assert( zIn[0]=='\'' );
  6270. assert( zIn[n-1]=='\'' );
  6271. if( zRet ){
  6272. int iOut = 0;
  6273. int iIn = 0;
  6274. for(iIn=1; iIn<(n-1); iIn++){
  6275. if( zIn[iIn]=='\'' ){
  6276. assert( zIn[iIn+1]=='\'' );
  6277. iIn++;
  6278. }
  6279. zRet[iOut++] = zIn[iIn];
  6280. }
  6281. zRet[iOut] = '\0';
  6282. }
  6283. return zRet;
  6284. }
  6285. /*
  6286. ** This function is the implementation of both the xConnect and xCreate
  6287. ** methods of the r-tree virtual table.
  6288. **
  6289. ** argv[0] -> module name
  6290. ** argv[1] -> database name
  6291. ** argv[2] -> table name
  6292. ** argv[...] -> column names...
  6293. */
  6294. static int expertConnect(
  6295. sqlite3 *db,
  6296. void *pAux,
  6297. int argc, const char *const*argv,
  6298. sqlite3_vtab **ppVtab,
  6299. char **pzErr
  6300. ){
  6301. sqlite3expert *pExpert = (sqlite3expert*)pAux;
  6302. ExpertVtab *p = 0;
  6303. int rc;
  6304. if( argc!=4 ){
  6305. *pzErr = sqlite3_mprintf("internal error!");
  6306. rc = SQLITE_ERROR;
  6307. }else{
  6308. char *zCreateTable = expertDequote(argv[3]);
  6309. if( zCreateTable ){
  6310. rc = sqlite3_declare_vtab(db, zCreateTable);
  6311. if( rc==SQLITE_OK ){
  6312. p = idxMalloc(&rc, sizeof(ExpertVtab));
  6313. }
  6314. if( rc==SQLITE_OK ){
  6315. p->pExpert = pExpert;
  6316. p->pTab = pExpert->pTable;
  6317. assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
  6318. }
  6319. sqlite3_free(zCreateTable);
  6320. }else{
  6321. rc = SQLITE_NOMEM;
  6322. }
  6323. }
  6324. *ppVtab = (sqlite3_vtab*)p;
  6325. return rc;
  6326. }
  6327. static int expertDisconnect(sqlite3_vtab *pVtab){
  6328. ExpertVtab *p = (ExpertVtab*)pVtab;
  6329. sqlite3_free(p);
  6330. return SQLITE_OK;
  6331. }
  6332. static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
  6333. ExpertVtab *p = (ExpertVtab*)pVtab;
  6334. int rc = SQLITE_OK;
  6335. int n = 0;
  6336. IdxScan *pScan;
  6337. const int opmask =
  6338. SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
  6339. SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
  6340. SQLITE_INDEX_CONSTRAINT_LE;
  6341. pScan = idxMalloc(&rc, sizeof(IdxScan));
  6342. if( pScan ){
  6343. int i;
  6344. /* Link the new scan object into the list */
  6345. pScan->pTab = p->pTab;
  6346. pScan->pNextScan = p->pExpert->pScan;
  6347. p->pExpert->pScan = pScan;
  6348. /* Add the constraints to the IdxScan object */
  6349. for(i=0; i<pIdxInfo->nConstraint; i++){
  6350. struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
  6351. if( pCons->usable
  6352. && pCons->iColumn>=0
  6353. && p->pTab->aCol[pCons->iColumn].iPk==0
  6354. && (pCons->op & opmask)
  6355. ){
  6356. IdxConstraint *pNew;
  6357. const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
  6358. pNew = idxNewConstraint(&rc, zColl);
  6359. if( pNew ){
  6360. pNew->iCol = pCons->iColumn;
  6361. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  6362. pNew->pNext = pScan->pEq;
  6363. pScan->pEq = pNew;
  6364. }else{
  6365. pNew->bRange = 1;
  6366. pNew->pNext = pScan->pRange;
  6367. pScan->pRange = pNew;
  6368. }
  6369. }
  6370. n++;
  6371. pIdxInfo->aConstraintUsage[i].argvIndex = n;
  6372. }
  6373. }
  6374. /* Add the ORDER BY to the IdxScan object */
  6375. for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
  6376. int iCol = pIdxInfo->aOrderBy[i].iColumn;
  6377. if( iCol>=0 ){
  6378. IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
  6379. if( pNew ){
  6380. pNew->iCol = iCol;
  6381. pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
  6382. pNew->pNext = pScan->pOrder;
  6383. pNew->pLink = pScan->pOrder;
  6384. pScan->pOrder = pNew;
  6385. n++;
  6386. }
  6387. }
  6388. }
  6389. }
  6390. pIdxInfo->estimatedCost = 1000000.0 / (n+1);
  6391. return rc;
  6392. }
  6393. static int expertUpdate(
  6394. sqlite3_vtab *pVtab,
  6395. int nData,
  6396. sqlite3_value **azData,
  6397. sqlite_int64 *pRowid
  6398. ){
  6399. (void)pVtab;
  6400. (void)nData;
  6401. (void)azData;
  6402. (void)pRowid;
  6403. return SQLITE_OK;
  6404. }
  6405. /*
  6406. ** Virtual table module xOpen method.
  6407. */
  6408. static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  6409. int rc = SQLITE_OK;
  6410. ExpertCsr *pCsr;
  6411. (void)pVTab;
  6412. pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
  6413. *ppCursor = (sqlite3_vtab_cursor*)pCsr;
  6414. return rc;
  6415. }
  6416. /*
  6417. ** Virtual table module xClose method.
  6418. */
  6419. static int expertClose(sqlite3_vtab_cursor *cur){
  6420. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6421. sqlite3_finalize(pCsr->pData);
  6422. sqlite3_free(pCsr);
  6423. return SQLITE_OK;
  6424. }
  6425. /*
  6426. ** Virtual table module xEof method.
  6427. **
  6428. ** Return non-zero if the cursor does not currently point to a valid
  6429. ** record (i.e if the scan has finished), or zero otherwise.
  6430. */
  6431. static int expertEof(sqlite3_vtab_cursor *cur){
  6432. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6433. return pCsr->pData==0;
  6434. }
  6435. /*
  6436. ** Virtual table module xNext method.
  6437. */
  6438. static int expertNext(sqlite3_vtab_cursor *cur){
  6439. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6440. int rc = SQLITE_OK;
  6441. assert( pCsr->pData );
  6442. rc = sqlite3_step(pCsr->pData);
  6443. if( rc!=SQLITE_ROW ){
  6444. rc = sqlite3_finalize(pCsr->pData);
  6445. pCsr->pData = 0;
  6446. }else{
  6447. rc = SQLITE_OK;
  6448. }
  6449. return rc;
  6450. }
  6451. /*
  6452. ** Virtual table module xRowid method.
  6453. */
  6454. static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  6455. (void)cur;
  6456. *pRowid = 0;
  6457. return SQLITE_OK;
  6458. }
  6459. /*
  6460. ** Virtual table module xColumn method.
  6461. */
  6462. static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  6463. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6464. sqlite3_value *pVal;
  6465. pVal = sqlite3_column_value(pCsr->pData, i);
  6466. if( pVal ){
  6467. sqlite3_result_value(ctx, pVal);
  6468. }
  6469. return SQLITE_OK;
  6470. }
  6471. /*
  6472. ** Virtual table module xFilter method.
  6473. */
  6474. static int expertFilter(
  6475. sqlite3_vtab_cursor *cur,
  6476. int idxNum, const char *idxStr,
  6477. int argc, sqlite3_value **argv
  6478. ){
  6479. ExpertCsr *pCsr = (ExpertCsr*)cur;
  6480. ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
  6481. sqlite3expert *pExpert = pVtab->pExpert;
  6482. int rc;
  6483. (void)idxNum;
  6484. (void)idxStr;
  6485. (void)argc;
  6486. (void)argv;
  6487. rc = sqlite3_finalize(pCsr->pData);
  6488. pCsr->pData = 0;
  6489. if( rc==SQLITE_OK ){
  6490. rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
  6491. "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
  6492. );
  6493. }
  6494. if( rc==SQLITE_OK ){
  6495. rc = expertNext(cur);
  6496. }
  6497. return rc;
  6498. }
  6499. static int idxRegisterVtab(sqlite3expert *p){
  6500. static sqlite3_module expertModule = {
  6501. 2, /* iVersion */
  6502. expertConnect, /* xCreate - create a table */
  6503. expertConnect, /* xConnect - connect to an existing table */
  6504. expertBestIndex, /* xBestIndex - Determine search strategy */
  6505. expertDisconnect, /* xDisconnect - Disconnect from a table */
  6506. expertDisconnect, /* xDestroy - Drop a table */
  6507. expertOpen, /* xOpen - open a cursor */
  6508. expertClose, /* xClose - close a cursor */
  6509. expertFilter, /* xFilter - configure scan constraints */
  6510. expertNext, /* xNext - advance a cursor */
  6511. expertEof, /* xEof */
  6512. expertColumn, /* xColumn - read data */
  6513. expertRowid, /* xRowid - read data */
  6514. expertUpdate, /* xUpdate - write data */
  6515. 0, /* xBegin - begin transaction */
  6516. 0, /* xSync - sync transaction */
  6517. 0, /* xCommit - commit transaction */
  6518. 0, /* xRollback - rollback transaction */
  6519. 0, /* xFindFunction - function overloading */
  6520. 0, /* xRename - rename the table */
  6521. 0, /* xSavepoint */
  6522. 0, /* xRelease */
  6523. 0, /* xRollbackTo */
  6524. };
  6525. return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
  6526. }
  6527. /*
  6528. ** End of virtual table implementation.
  6529. *************************************************************************/
  6530. /*
  6531. ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
  6532. ** is called, set it to the return value of sqlite3_finalize() before
  6533. ** returning. Otherwise, discard the sqlite3_finalize() return value.
  6534. */
  6535. static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
  6536. int rc = sqlite3_finalize(pStmt);
  6537. if( *pRc==SQLITE_OK ) *pRc = rc;
  6538. }
  6539. /*
  6540. ** Attempt to allocate an IdxTable structure corresponding to table zTab
  6541. ** in the main database of connection db. If successful, set (*ppOut) to
  6542. ** point to the new object and return SQLITE_OK. Otherwise, return an
  6543. ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
  6544. ** set to point to an error string.
  6545. **
  6546. ** It is the responsibility of the caller to eventually free either the
  6547. ** IdxTable object or error message using sqlite3_free().
  6548. */
  6549. static int idxGetTableInfo(
  6550. sqlite3 *db, /* Database connection to read details from */
  6551. const char *zTab, /* Table name */
  6552. IdxTable **ppOut, /* OUT: New object (if successful) */
  6553. char **pzErrmsg /* OUT: Error message (if not) */
  6554. ){
  6555. sqlite3_stmt *p1 = 0;
  6556. int nCol = 0;
  6557. int nTab = STRLEN(zTab);
  6558. int nByte = sizeof(IdxTable) + nTab + 1;
  6559. IdxTable *pNew = 0;
  6560. int rc, rc2;
  6561. char *pCsr = 0;
  6562. rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
  6563. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  6564. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  6565. nByte += 1 + STRLEN(zCol);
  6566. rc = sqlite3_table_column_metadata(
  6567. db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
  6568. );
  6569. nByte += 1 + STRLEN(zCol);
  6570. nCol++;
  6571. }
  6572. rc2 = sqlite3_reset(p1);
  6573. if( rc==SQLITE_OK ) rc = rc2;
  6574. nByte += sizeof(IdxColumn) * nCol;
  6575. if( rc==SQLITE_OK ){
  6576. pNew = idxMalloc(&rc, nByte);
  6577. }
  6578. if( rc==SQLITE_OK ){
  6579. pNew->aCol = (IdxColumn*)&pNew[1];
  6580. pNew->nCol = nCol;
  6581. pCsr = (char*)&pNew->aCol[nCol];
  6582. }
  6583. nCol = 0;
  6584. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
  6585. const char *zCol = (const char*)sqlite3_column_text(p1, 1);
  6586. int nCopy = STRLEN(zCol) + 1;
  6587. pNew->aCol[nCol].zName = pCsr;
  6588. pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
  6589. memcpy(pCsr, zCol, nCopy);
  6590. pCsr += nCopy;
  6591. rc = sqlite3_table_column_metadata(
  6592. db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
  6593. );
  6594. if( rc==SQLITE_OK ){
  6595. nCopy = STRLEN(zCol) + 1;
  6596. pNew->aCol[nCol].zColl = pCsr;
  6597. memcpy(pCsr, zCol, nCopy);
  6598. pCsr += nCopy;
  6599. }
  6600. nCol++;
  6601. }
  6602. idxFinalize(&rc, p1);
  6603. if( rc!=SQLITE_OK ){
  6604. sqlite3_free(pNew);
  6605. pNew = 0;
  6606. }else{
  6607. pNew->zName = pCsr;
  6608. memcpy(pNew->zName, zTab, nTab+1);
  6609. }
  6610. *ppOut = pNew;
  6611. return rc;
  6612. }
  6613. /*
  6614. ** This function is a no-op if *pRc is set to anything other than
  6615. ** SQLITE_OK when it is called.
  6616. **
  6617. ** If *pRc is initially set to SQLITE_OK, then the text specified by
  6618. ** the printf() style arguments is appended to zIn and the result returned
  6619. ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
  6620. ** zIn before returning.
  6621. */
  6622. static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
  6623. va_list ap;
  6624. char *zAppend = 0;
  6625. char *zRet = 0;
  6626. int nIn = zIn ? STRLEN(zIn) : 0;
  6627. int nAppend = 0;
  6628. va_start(ap, zFmt);
  6629. if( *pRc==SQLITE_OK ){
  6630. zAppend = sqlite3_vmprintf(zFmt, ap);
  6631. if( zAppend ){
  6632. nAppend = STRLEN(zAppend);
  6633. zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
  6634. }
  6635. if( zAppend && zRet ){
  6636. if( nIn ) memcpy(zRet, zIn, nIn);
  6637. memcpy(&zRet[nIn], zAppend, nAppend+1);
  6638. }else{
  6639. sqlite3_free(zRet);
  6640. zRet = 0;
  6641. *pRc = SQLITE_NOMEM;
  6642. }
  6643. sqlite3_free(zAppend);
  6644. sqlite3_free(zIn);
  6645. }
  6646. va_end(ap);
  6647. return zRet;
  6648. }
  6649. /*
  6650. ** Return true if zId must be quoted in order to use it as an SQL
  6651. ** identifier, or false otherwise.
  6652. */
  6653. static int idxIdentifierRequiresQuotes(const char *zId){
  6654. int i;
  6655. for(i=0; zId[i]; i++){
  6656. if( !(zId[i]=='_')
  6657. && !(zId[i]>='0' && zId[i]<='9')
  6658. && !(zId[i]>='a' && zId[i]<='z')
  6659. && !(zId[i]>='A' && zId[i]<='Z')
  6660. ){
  6661. return 1;
  6662. }
  6663. }
  6664. return 0;
  6665. }
  6666. /*
  6667. ** This function appends an index column definition suitable for constraint
  6668. ** pCons to the string passed as zIn and returns the result.
  6669. */
  6670. static char *idxAppendColDefn(
  6671. int *pRc, /* IN/OUT: Error code */
  6672. char *zIn, /* Column defn accumulated so far */
  6673. IdxTable *pTab, /* Table index will be created on */
  6674. IdxConstraint *pCons
  6675. ){
  6676. char *zRet = zIn;
  6677. IdxColumn *p = &pTab->aCol[pCons->iCol];
  6678. if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
  6679. if( idxIdentifierRequiresQuotes(p->zName) ){
  6680. zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
  6681. }else{
  6682. zRet = idxAppendText(pRc, zRet, "%s", p->zName);
  6683. }
  6684. if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
  6685. if( idxIdentifierRequiresQuotes(pCons->zColl) ){
  6686. zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
  6687. }else{
  6688. zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
  6689. }
  6690. }
  6691. if( pCons->bDesc ){
  6692. zRet = idxAppendText(pRc, zRet, " DESC");
  6693. }
  6694. return zRet;
  6695. }
  6696. /*
  6697. ** Search database dbm for an index compatible with the one idxCreateFromCons()
  6698. ** would create from arguments pScan, pEq and pTail. If no error occurs and
  6699. ** such an index is found, return non-zero. Or, if no such index is found,
  6700. ** return zero.
  6701. **
  6702. ** If an error occurs, set *pRc to an SQLite error code and return zero.
  6703. */
  6704. static int idxFindCompatible(
  6705. int *pRc, /* OUT: Error code */
  6706. sqlite3* dbm, /* Database to search */
  6707. IdxScan *pScan, /* Scan for table to search for index on */
  6708. IdxConstraint *pEq, /* List of == constraints */
  6709. IdxConstraint *pTail /* List of range constraints */
  6710. ){
  6711. const char *zTbl = pScan->pTab->zName;
  6712. sqlite3_stmt *pIdxList = 0;
  6713. IdxConstraint *pIter;
  6714. int nEq = 0; /* Number of elements in pEq */
  6715. int rc;
  6716. /* Count the elements in list pEq */
  6717. for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
  6718. rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
  6719. while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
  6720. int bMatch = 1;
  6721. IdxConstraint *pT = pTail;
  6722. sqlite3_stmt *pInfo = 0;
  6723. const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
  6724. /* Zero the IdxConstraint.bFlag values in the pEq list */
  6725. for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
  6726. rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
  6727. while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
  6728. int iIdx = sqlite3_column_int(pInfo, 0);
  6729. int iCol = sqlite3_column_int(pInfo, 1);
  6730. const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
  6731. if( iIdx<nEq ){
  6732. for(pIter=pEq; pIter; pIter=pIter->pLink){
  6733. if( pIter->bFlag ) continue;
  6734. if( pIter->iCol!=iCol ) continue;
  6735. if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
  6736. pIter->bFlag = 1;
  6737. break;
  6738. }
  6739. if( pIter==0 ){
  6740. bMatch = 0;
  6741. break;
  6742. }
  6743. }else{
  6744. if( pT ){
  6745. if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
  6746. bMatch = 0;
  6747. break;
  6748. }
  6749. pT = pT->pLink;
  6750. }
  6751. }
  6752. }
  6753. idxFinalize(&rc, pInfo);
  6754. if( rc==SQLITE_OK && bMatch ){
  6755. sqlite3_finalize(pIdxList);
  6756. return 1;
  6757. }
  6758. }
  6759. idxFinalize(&rc, pIdxList);
  6760. *pRc = rc;
  6761. return 0;
  6762. }
  6763. static int idxCreateFromCons(
  6764. sqlite3expert *p,
  6765. IdxScan *pScan,
  6766. IdxConstraint *pEq,
  6767. IdxConstraint *pTail
  6768. ){
  6769. sqlite3 *dbm = p->dbm;
  6770. int rc = SQLITE_OK;
  6771. if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
  6772. IdxTable *pTab = pScan->pTab;
  6773. char *zCols = 0;
  6774. char *zIdx = 0;
  6775. IdxConstraint *pCons;
  6776. unsigned int h = 0;
  6777. const char *zFmt;
  6778. for(pCons=pEq; pCons; pCons=pCons->pLink){
  6779. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  6780. }
  6781. for(pCons=pTail; pCons; pCons=pCons->pLink){
  6782. zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
  6783. }
  6784. if( rc==SQLITE_OK ){
  6785. /* Hash the list of columns to come up with a name for the index */
  6786. const char *zTable = pScan->pTab->zName;
  6787. char *zName; /* Index name */
  6788. int i;
  6789. for(i=0; zCols[i]; i++){
  6790. h += ((h<<3) + zCols[i]);
  6791. }
  6792. zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
  6793. if( zName==0 ){
  6794. rc = SQLITE_NOMEM;
  6795. }else{
  6796. if( idxIdentifierRequiresQuotes(zTable) ){
  6797. zFmt = "CREATE INDEX '%q' ON %Q(%s)";
  6798. }else{
  6799. zFmt = "CREATE INDEX %s ON %s(%s)";
  6800. }
  6801. zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
  6802. if( !zIdx ){
  6803. rc = SQLITE_NOMEM;
  6804. }else{
  6805. rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
  6806. idxHashAdd(&rc, &p->hIdx, zName, zIdx);
  6807. }
  6808. sqlite3_free(zName);
  6809. sqlite3_free(zIdx);
  6810. }
  6811. }
  6812. sqlite3_free(zCols);
  6813. }
  6814. return rc;
  6815. }
  6816. /*
  6817. ** Return true if list pList (linked by IdxConstraint.pLink) contains
  6818. ** a constraint compatible with *p. Otherwise return false.
  6819. */
  6820. static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
  6821. IdxConstraint *pCmp;
  6822. for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
  6823. if( p->iCol==pCmp->iCol ) return 1;
  6824. }
  6825. return 0;
  6826. }
  6827. static int idxCreateFromWhere(
  6828. sqlite3expert *p,
  6829. IdxScan *pScan, /* Create indexes for this scan */
  6830. IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
  6831. ){
  6832. IdxConstraint *p1 = 0;
  6833. IdxConstraint *pCon;
  6834. int rc;
  6835. /* Gather up all the == constraints. */
  6836. for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
  6837. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  6838. pCon->pLink = p1;
  6839. p1 = pCon;
  6840. }
  6841. }
  6842. /* Create an index using the == constraints collected above. And the
  6843. ** range constraint/ORDER BY terms passed in by the caller, if any. */
  6844. rc = idxCreateFromCons(p, pScan, p1, pTail);
  6845. /* If no range/ORDER BY passed by the caller, create a version of the
  6846. ** index for each range constraint. */
  6847. if( pTail==0 ){
  6848. for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
  6849. assert( pCon->pLink==0 );
  6850. if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
  6851. rc = idxCreateFromCons(p, pScan, p1, pCon);
  6852. }
  6853. }
  6854. }
  6855. return rc;
  6856. }
  6857. /*
  6858. ** Create candidate indexes in database [dbm] based on the data in
  6859. ** linked-list pScan.
  6860. */
  6861. static int idxCreateCandidates(sqlite3expert *p){
  6862. int rc = SQLITE_OK;
  6863. IdxScan *pIter;
  6864. for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
  6865. rc = idxCreateFromWhere(p, pIter, 0);
  6866. if( rc==SQLITE_OK && pIter->pOrder ){
  6867. rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
  6868. }
  6869. }
  6870. return rc;
  6871. }
  6872. /*
  6873. ** Free all elements of the linked list starting at pConstraint.
  6874. */
  6875. static void idxConstraintFree(IdxConstraint *pConstraint){
  6876. IdxConstraint *pNext;
  6877. IdxConstraint *p;
  6878. for(p=pConstraint; p; p=pNext){
  6879. pNext = p->pNext;
  6880. sqlite3_free(p);
  6881. }
  6882. }
  6883. /*
  6884. ** Free all elements of the linked list starting from pScan up until pLast
  6885. ** (pLast is not freed).
  6886. */
  6887. static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
  6888. IdxScan *p;
  6889. IdxScan *pNext;
  6890. for(p=pScan; p!=pLast; p=pNext){
  6891. pNext = p->pNextScan;
  6892. idxConstraintFree(p->pOrder);
  6893. idxConstraintFree(p->pEq);
  6894. idxConstraintFree(p->pRange);
  6895. sqlite3_free(p);
  6896. }
  6897. }
  6898. /*
  6899. ** Free all elements of the linked list starting from pStatement up
  6900. ** until pLast (pLast is not freed).
  6901. */
  6902. static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
  6903. IdxStatement *p;
  6904. IdxStatement *pNext;
  6905. for(p=pStatement; p!=pLast; p=pNext){
  6906. pNext = p->pNext;
  6907. sqlite3_free(p->zEQP);
  6908. sqlite3_free(p->zIdx);
  6909. sqlite3_free(p);
  6910. }
  6911. }
  6912. /*
  6913. ** Free the linked list of IdxTable objects starting at pTab.
  6914. */
  6915. static void idxTableFree(IdxTable *pTab){
  6916. IdxTable *pIter;
  6917. IdxTable *pNext;
  6918. for(pIter=pTab; pIter; pIter=pNext){
  6919. pNext = pIter->pNext;
  6920. sqlite3_free(pIter);
  6921. }
  6922. }
  6923. /*
  6924. ** Free the linked list of IdxWrite objects starting at pTab.
  6925. */
  6926. static void idxWriteFree(IdxWrite *pTab){
  6927. IdxWrite *pIter;
  6928. IdxWrite *pNext;
  6929. for(pIter=pTab; pIter; pIter=pNext){
  6930. pNext = pIter->pNext;
  6931. sqlite3_free(pIter);
  6932. }
  6933. }
  6934. /*
  6935. ** This function is called after candidate indexes have been created. It
  6936. ** runs all the queries to see which indexes they prefer, and populates
  6937. ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
  6938. */
  6939. int idxFindIndexes(
  6940. sqlite3expert *p,
  6941. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  6942. ){
  6943. IdxStatement *pStmt;
  6944. sqlite3 *dbm = p->dbm;
  6945. int rc = SQLITE_OK;
  6946. IdxHash hIdx;
  6947. idxHashInit(&hIdx);
  6948. for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
  6949. IdxHashEntry *pEntry;
  6950. sqlite3_stmt *pExplain = 0;
  6951. idxHashClear(&hIdx);
  6952. rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
  6953. "EXPLAIN QUERY PLAN %s", pStmt->zSql
  6954. );
  6955. while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
  6956. /* int iId = sqlite3_column_int(pExplain, 0); */
  6957. /* int iParent = sqlite3_column_int(pExplain, 1); */
  6958. /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
  6959. const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
  6960. int nDetail = STRLEN(zDetail);
  6961. int i;
  6962. for(i=0; i<nDetail; i++){
  6963. const char *zIdx = 0;
  6964. if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
  6965. zIdx = &zDetail[i+13];
  6966. }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
  6967. zIdx = &zDetail[i+22];
  6968. }
  6969. if( zIdx ){
  6970. const char *zSql;
  6971. int nIdx = 0;
  6972. while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
  6973. nIdx++;
  6974. }
  6975. zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
  6976. if( zSql ){
  6977. idxHashAdd(&rc, &hIdx, zSql, 0);
  6978. if( rc ) goto find_indexes_out;
  6979. }
  6980. break;
  6981. }
  6982. }
  6983. if( zDetail[0]!='-' ){
  6984. pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
  6985. }
  6986. }
  6987. for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  6988. pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
  6989. }
  6990. idxFinalize(&rc, pExplain);
  6991. }
  6992. find_indexes_out:
  6993. idxHashClear(&hIdx);
  6994. return rc;
  6995. }
  6996. static int idxAuthCallback(
  6997. void *pCtx,
  6998. int eOp,
  6999. const char *z3,
  7000. const char *z4,
  7001. const char *zDb,
  7002. const char *zTrigger
  7003. ){
  7004. int rc = SQLITE_OK;
  7005. (void)z4;
  7006. (void)zTrigger;
  7007. if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
  7008. if( sqlite3_stricmp(zDb, "main")==0 ){
  7009. sqlite3expert *p = (sqlite3expert*)pCtx;
  7010. IdxTable *pTab;
  7011. for(pTab=p->pTable; pTab; pTab=pTab->pNext){
  7012. if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
  7013. }
  7014. if( pTab ){
  7015. IdxWrite *pWrite;
  7016. for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
  7017. if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
  7018. }
  7019. if( pWrite==0 ){
  7020. pWrite = idxMalloc(&rc, sizeof(IdxWrite));
  7021. if( rc==SQLITE_OK ){
  7022. pWrite->pTab = pTab;
  7023. pWrite->eOp = eOp;
  7024. pWrite->pNext = p->pWrite;
  7025. p->pWrite = pWrite;
  7026. }
  7027. }
  7028. }
  7029. }
  7030. }
  7031. return rc;
  7032. }
  7033. static int idxProcessOneTrigger(
  7034. sqlite3expert *p,
  7035. IdxWrite *pWrite,
  7036. char **pzErr
  7037. ){
  7038. static const char *zInt = UNIQUE_TABLE_NAME;
  7039. static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
  7040. IdxTable *pTab = pWrite->pTab;
  7041. const char *zTab = pTab->zName;
  7042. const char *zSql =
  7043. "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
  7044. "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
  7045. "ORDER BY type;";
  7046. sqlite3_stmt *pSelect = 0;
  7047. int rc = SQLITE_OK;
  7048. char *zWrite = 0;
  7049. /* Create the table and its triggers in the temp schema */
  7050. rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
  7051. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
  7052. const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
  7053. rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
  7054. }
  7055. idxFinalize(&rc, pSelect);
  7056. /* Rename the table in the temp schema to zInt */
  7057. if( rc==SQLITE_OK ){
  7058. char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
  7059. if( z==0 ){
  7060. rc = SQLITE_NOMEM;
  7061. }else{
  7062. rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
  7063. sqlite3_free(z);
  7064. }
  7065. }
  7066. switch( pWrite->eOp ){
  7067. case SQLITE_INSERT: {
  7068. int i;
  7069. zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
  7070. for(i=0; i<pTab->nCol; i++){
  7071. zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
  7072. }
  7073. zWrite = idxAppendText(&rc, zWrite, ")");
  7074. break;
  7075. }
  7076. case SQLITE_UPDATE: {
  7077. int i;
  7078. zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
  7079. for(i=0; i<pTab->nCol; i++){
  7080. zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
  7081. pTab->aCol[i].zName
  7082. );
  7083. }
  7084. break;
  7085. }
  7086. default: {
  7087. assert( pWrite->eOp==SQLITE_DELETE );
  7088. if( rc==SQLITE_OK ){
  7089. zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
  7090. if( zWrite==0 ) rc = SQLITE_NOMEM;
  7091. }
  7092. }
  7093. }
  7094. if( rc==SQLITE_OK ){
  7095. sqlite3_stmt *pX = 0;
  7096. rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
  7097. idxFinalize(&rc, pX);
  7098. if( rc!=SQLITE_OK ){
  7099. idxDatabaseError(p->dbv, pzErr);
  7100. }
  7101. }
  7102. sqlite3_free(zWrite);
  7103. if( rc==SQLITE_OK ){
  7104. rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
  7105. }
  7106. return rc;
  7107. }
  7108. static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
  7109. int rc = SQLITE_OK;
  7110. IdxWrite *pEnd = 0;
  7111. IdxWrite *pFirst = p->pWrite;
  7112. while( rc==SQLITE_OK && pFirst!=pEnd ){
  7113. IdxWrite *pIter;
  7114. for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
  7115. rc = idxProcessOneTrigger(p, pIter, pzErr);
  7116. }
  7117. pEnd = pFirst;
  7118. pFirst = p->pWrite;
  7119. }
  7120. return rc;
  7121. }
  7122. static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
  7123. int rc = idxRegisterVtab(p);
  7124. sqlite3_stmt *pSchema = 0;
  7125. /* For each table in the main db schema:
  7126. **
  7127. ** 1) Add an entry to the p->pTable list, and
  7128. ** 2) Create the equivalent virtual table in dbv.
  7129. */
  7130. rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
  7131. "SELECT type, name, sql, 1 FROM sqlite_master "
  7132. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
  7133. " UNION ALL "
  7134. "SELECT type, name, sql, 2 FROM sqlite_master "
  7135. "WHERE type = 'trigger'"
  7136. " AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
  7137. "ORDER BY 4, 1"
  7138. );
  7139. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
  7140. const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
  7141. const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
  7142. const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
  7143. if( zType[0]=='v' || zType[1]=='r' ){
  7144. rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
  7145. }else{
  7146. IdxTable *pTab;
  7147. rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
  7148. if( rc==SQLITE_OK ){
  7149. int i;
  7150. char *zInner = 0;
  7151. char *zOuter = 0;
  7152. pTab->pNext = p->pTable;
  7153. p->pTable = pTab;
  7154. /* The statement the vtab will pass to sqlite3_declare_vtab() */
  7155. zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
  7156. for(i=0; i<pTab->nCol; i++){
  7157. zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
  7158. (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
  7159. );
  7160. }
  7161. zInner = idxAppendText(&rc, zInner, ")");
  7162. /* The CVT statement to create the vtab */
  7163. zOuter = idxAppendText(&rc, 0,
  7164. "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
  7165. );
  7166. if( rc==SQLITE_OK ){
  7167. rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
  7168. }
  7169. sqlite3_free(zInner);
  7170. sqlite3_free(zOuter);
  7171. }
  7172. }
  7173. }
  7174. idxFinalize(&rc, pSchema);
  7175. return rc;
  7176. }
  7177. struct IdxSampleCtx {
  7178. int iTarget;
  7179. double target; /* Target nRet/nRow value */
  7180. double nRow; /* Number of rows seen */
  7181. double nRet; /* Number of rows returned */
  7182. };
  7183. static void idxSampleFunc(
  7184. sqlite3_context *pCtx,
  7185. int argc,
  7186. sqlite3_value **argv
  7187. ){
  7188. struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
  7189. int bRet;
  7190. (void)argv;
  7191. assert( argc==0 );
  7192. if( p->nRow==0.0 ){
  7193. bRet = 1;
  7194. }else{
  7195. bRet = (p->nRet / p->nRow) <= p->target;
  7196. if( bRet==0 ){
  7197. unsigned short rnd;
  7198. sqlite3_randomness(2, (void*)&rnd);
  7199. bRet = ((int)rnd % 100) <= p->iTarget;
  7200. }
  7201. }
  7202. sqlite3_result_int(pCtx, bRet);
  7203. p->nRow += 1.0;
  7204. p->nRet += (double)bRet;
  7205. }
  7206. struct IdxRemCtx {
  7207. int nSlot;
  7208. struct IdxRemSlot {
  7209. int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
  7210. i64 iVal; /* SQLITE_INTEGER value */
  7211. double rVal; /* SQLITE_FLOAT value */
  7212. int nByte; /* Bytes of space allocated at z */
  7213. int n; /* Size of buffer z */
  7214. char *z; /* SQLITE_TEXT/BLOB value */
  7215. } aSlot[1];
  7216. };
  7217. /*
  7218. ** Implementation of scalar function rem().
  7219. */
  7220. static void idxRemFunc(
  7221. sqlite3_context *pCtx,
  7222. int argc,
  7223. sqlite3_value **argv
  7224. ){
  7225. struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
  7226. struct IdxRemSlot *pSlot;
  7227. int iSlot;
  7228. assert( argc==2 );
  7229. iSlot = sqlite3_value_int(argv[0]);
  7230. assert( iSlot<=p->nSlot );
  7231. pSlot = &p->aSlot[iSlot];
  7232. switch( pSlot->eType ){
  7233. case SQLITE_NULL:
  7234. /* no-op */
  7235. break;
  7236. case SQLITE_INTEGER:
  7237. sqlite3_result_int64(pCtx, pSlot->iVal);
  7238. break;
  7239. case SQLITE_FLOAT:
  7240. sqlite3_result_double(pCtx, pSlot->rVal);
  7241. break;
  7242. case SQLITE_BLOB:
  7243. sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  7244. break;
  7245. case SQLITE_TEXT:
  7246. sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
  7247. break;
  7248. }
  7249. pSlot->eType = sqlite3_value_type(argv[1]);
  7250. switch( pSlot->eType ){
  7251. case SQLITE_NULL:
  7252. /* no-op */
  7253. break;
  7254. case SQLITE_INTEGER:
  7255. pSlot->iVal = sqlite3_value_int64(argv[1]);
  7256. break;
  7257. case SQLITE_FLOAT:
  7258. pSlot->rVal = sqlite3_value_double(argv[1]);
  7259. break;
  7260. case SQLITE_BLOB:
  7261. case SQLITE_TEXT: {
  7262. int nByte = sqlite3_value_bytes(argv[1]);
  7263. if( nByte>pSlot->nByte ){
  7264. char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
  7265. if( zNew==0 ){
  7266. sqlite3_result_error_nomem(pCtx);
  7267. return;
  7268. }
  7269. pSlot->nByte = nByte*2;
  7270. pSlot->z = zNew;
  7271. }
  7272. pSlot->n = nByte;
  7273. if( pSlot->eType==SQLITE_BLOB ){
  7274. memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
  7275. }else{
  7276. memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
  7277. }
  7278. break;
  7279. }
  7280. }
  7281. }
  7282. static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
  7283. int rc = SQLITE_OK;
  7284. const char *zMax =
  7285. "SELECT max(i.seqno) FROM "
  7286. " sqlite_master AS s, "
  7287. " pragma_index_list(s.name) AS l, "
  7288. " pragma_index_info(l.name) AS i "
  7289. "WHERE s.type = 'table'";
  7290. sqlite3_stmt *pMax = 0;
  7291. *pnMax = 0;
  7292. rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
  7293. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  7294. *pnMax = sqlite3_column_int(pMax, 0) + 1;
  7295. }
  7296. idxFinalize(&rc, pMax);
  7297. return rc;
  7298. }
  7299. static int idxPopulateOneStat1(
  7300. sqlite3expert *p,
  7301. sqlite3_stmt *pIndexXInfo,
  7302. sqlite3_stmt *pWriteStat,
  7303. const char *zTab,
  7304. const char *zIdx,
  7305. char **pzErr
  7306. ){
  7307. char *zCols = 0;
  7308. char *zOrder = 0;
  7309. char *zQuery = 0;
  7310. int nCol = 0;
  7311. int i;
  7312. sqlite3_stmt *pQuery = 0;
  7313. int *aStat = 0;
  7314. int rc = SQLITE_OK;
  7315. assert( p->iSample>0 );
  7316. /* Formulate the query text */
  7317. sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
  7318. while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
  7319. const char *zComma = zCols==0 ? "" : ", ";
  7320. const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
  7321. const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
  7322. zCols = idxAppendText(&rc, zCols,
  7323. "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
  7324. );
  7325. zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
  7326. }
  7327. sqlite3_reset(pIndexXInfo);
  7328. if( rc==SQLITE_OK ){
  7329. if( p->iSample==100 ){
  7330. zQuery = sqlite3_mprintf(
  7331. "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
  7332. );
  7333. }else{
  7334. zQuery = sqlite3_mprintf(
  7335. "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
  7336. );
  7337. }
  7338. }
  7339. sqlite3_free(zCols);
  7340. sqlite3_free(zOrder);
  7341. /* Formulate the query text */
  7342. if( rc==SQLITE_OK ){
  7343. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  7344. rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
  7345. }
  7346. sqlite3_free(zQuery);
  7347. if( rc==SQLITE_OK ){
  7348. aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
  7349. }
  7350. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  7351. IdxHashEntry *pEntry;
  7352. char *zStat = 0;
  7353. for(i=0; i<=nCol; i++) aStat[i] = 1;
  7354. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
  7355. aStat[0]++;
  7356. for(i=0; i<nCol; i++){
  7357. if( sqlite3_column_int(pQuery, i)==0 ) break;
  7358. }
  7359. for(/*no-op*/; i<nCol; i++){
  7360. aStat[i+1]++;
  7361. }
  7362. }
  7363. if( rc==SQLITE_OK ){
  7364. int s0 = aStat[0];
  7365. zStat = sqlite3_mprintf("%d", s0);
  7366. if( zStat==0 ) rc = SQLITE_NOMEM;
  7367. for(i=1; rc==SQLITE_OK && i<=nCol; i++){
  7368. zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
  7369. }
  7370. }
  7371. if( rc==SQLITE_OK ){
  7372. sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
  7373. sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
  7374. sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
  7375. sqlite3_step(pWriteStat);
  7376. rc = sqlite3_reset(pWriteStat);
  7377. }
  7378. pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
  7379. if( pEntry ){
  7380. assert( pEntry->zVal2==0 );
  7381. pEntry->zVal2 = zStat;
  7382. }else{
  7383. sqlite3_free(zStat);
  7384. }
  7385. }
  7386. sqlite3_free(aStat);
  7387. idxFinalize(&rc, pQuery);
  7388. return rc;
  7389. }
  7390. static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
  7391. int rc;
  7392. char *zSql;
  7393. rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  7394. if( rc!=SQLITE_OK ) return rc;
  7395. zSql = sqlite3_mprintf(
  7396. "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
  7397. );
  7398. if( zSql==0 ) return SQLITE_NOMEM;
  7399. rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
  7400. sqlite3_free(zSql);
  7401. return rc;
  7402. }
  7403. /*
  7404. ** This function is called as part of sqlite3_expert_analyze(). Candidate
  7405. ** indexes have already been created in database sqlite3expert.dbm, this
  7406. ** function populates sqlite_stat1 table in the same database.
  7407. **
  7408. ** The stat1 data is generated by querying the
  7409. */
  7410. static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
  7411. int rc = SQLITE_OK;
  7412. int nMax =0;
  7413. struct IdxRemCtx *pCtx = 0;
  7414. struct IdxSampleCtx samplectx;
  7415. int i;
  7416. i64 iPrev = -100000;
  7417. sqlite3_stmt *pAllIndex = 0;
  7418. sqlite3_stmt *pIndexXInfo = 0;
  7419. sqlite3_stmt *pWrite = 0;
  7420. const char *zAllIndex =
  7421. "SELECT s.rowid, s.name, l.name FROM "
  7422. " sqlite_master AS s, "
  7423. " pragma_index_list(s.name) AS l "
  7424. "WHERE s.type = 'table'";
  7425. const char *zIndexXInfo =
  7426. "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
  7427. const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
  7428. /* If iSample==0, no sqlite_stat1 data is required. */
  7429. if( p->iSample==0 ) return SQLITE_OK;
  7430. rc = idxLargestIndex(p->dbm, &nMax, pzErr);
  7431. if( nMax<=0 || rc!=SQLITE_OK ) return rc;
  7432. rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
  7433. if( rc==SQLITE_OK ){
  7434. int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
  7435. pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
  7436. }
  7437. if( rc==SQLITE_OK ){
  7438. sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
  7439. rc = sqlite3_create_function(
  7440. dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
  7441. );
  7442. }
  7443. if( rc==SQLITE_OK ){
  7444. rc = sqlite3_create_function(
  7445. p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
  7446. );
  7447. }
  7448. if( rc==SQLITE_OK ){
  7449. pCtx->nSlot = nMax+1;
  7450. rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
  7451. }
  7452. if( rc==SQLITE_OK ){
  7453. rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
  7454. }
  7455. if( rc==SQLITE_OK ){
  7456. rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
  7457. }
  7458. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
  7459. i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
  7460. const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
  7461. const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
  7462. if( p->iSample<100 && iPrev!=iRowid ){
  7463. samplectx.target = (double)p->iSample / 100.0;
  7464. samplectx.iTarget = p->iSample;
  7465. samplectx.nRow = 0.0;
  7466. samplectx.nRet = 0.0;
  7467. rc = idxBuildSampleTable(p, zTab);
  7468. if( rc!=SQLITE_OK ) break;
  7469. }
  7470. rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
  7471. iPrev = iRowid;
  7472. }
  7473. if( rc==SQLITE_OK && p->iSample<100 ){
  7474. rc = sqlite3_exec(p->dbv,
  7475. "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
  7476. );
  7477. }
  7478. idxFinalize(&rc, pAllIndex);
  7479. idxFinalize(&rc, pIndexXInfo);
  7480. idxFinalize(&rc, pWrite);
  7481. for(i=0; i<pCtx->nSlot; i++){
  7482. sqlite3_free(pCtx->aSlot[i].z);
  7483. }
  7484. sqlite3_free(pCtx);
  7485. if( rc==SQLITE_OK ){
  7486. rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
  7487. }
  7488. sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
  7489. return rc;
  7490. }
  7491. /*
  7492. ** Allocate a new sqlite3expert object.
  7493. */
  7494. sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
  7495. int rc = SQLITE_OK;
  7496. sqlite3expert *pNew;
  7497. pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
  7498. /* Open two in-memory databases to work with. The "vtab database" (dbv)
  7499. ** will contain a virtual table corresponding to each real table in
  7500. ** the user database schema, and a copy of each view. It is used to
  7501. ** collect information regarding the WHERE, ORDER BY and other clauses
  7502. ** of the user's query.
  7503. */
  7504. if( rc==SQLITE_OK ){
  7505. pNew->db = db;
  7506. pNew->iSample = 100;
  7507. rc = sqlite3_open(":memory:", &pNew->dbv);
  7508. }
  7509. if( rc==SQLITE_OK ){
  7510. rc = sqlite3_open(":memory:", &pNew->dbm);
  7511. if( rc==SQLITE_OK ){
  7512. sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
  7513. }
  7514. }
  7515. /* Copy the entire schema of database [db] into [dbm]. */
  7516. if( rc==SQLITE_OK ){
  7517. sqlite3_stmt *pSql;
  7518. rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
  7519. "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
  7520. " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
  7521. );
  7522. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  7523. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  7524. rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
  7525. }
  7526. idxFinalize(&rc, pSql);
  7527. }
  7528. /* Create the vtab schema */
  7529. if( rc==SQLITE_OK ){
  7530. rc = idxCreateVtabSchema(pNew, pzErrmsg);
  7531. }
  7532. /* Register the auth callback with dbv */
  7533. if( rc==SQLITE_OK ){
  7534. sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
  7535. }
  7536. /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
  7537. ** return the new sqlite3expert handle. */
  7538. if( rc!=SQLITE_OK ){
  7539. sqlite3_expert_destroy(pNew);
  7540. pNew = 0;
  7541. }
  7542. return pNew;
  7543. }
  7544. /*
  7545. ** Configure an sqlite3expert object.
  7546. */
  7547. int sqlite3_expert_config(sqlite3expert *p, int op, ...){
  7548. int rc = SQLITE_OK;
  7549. va_list ap;
  7550. va_start(ap, op);
  7551. switch( op ){
  7552. case EXPERT_CONFIG_SAMPLE: {
  7553. int iVal = va_arg(ap, int);
  7554. if( iVal<0 ) iVal = 0;
  7555. if( iVal>100 ) iVal = 100;
  7556. p->iSample = iVal;
  7557. break;
  7558. }
  7559. default:
  7560. rc = SQLITE_NOTFOUND;
  7561. break;
  7562. }
  7563. va_end(ap);
  7564. return rc;
  7565. }
  7566. /*
  7567. ** Add an SQL statement to the analysis.
  7568. */
  7569. int sqlite3_expert_sql(
  7570. sqlite3expert *p, /* From sqlite3_expert_new() */
  7571. const char *zSql, /* SQL statement to add */
  7572. char **pzErr /* OUT: Error message (if any) */
  7573. ){
  7574. IdxScan *pScanOrig = p->pScan;
  7575. IdxStatement *pStmtOrig = p->pStatement;
  7576. int rc = SQLITE_OK;
  7577. const char *zStmt = zSql;
  7578. if( p->bRun ) return SQLITE_MISUSE;
  7579. while( rc==SQLITE_OK && zStmt && zStmt[0] ){
  7580. sqlite3_stmt *pStmt = 0;
  7581. rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
  7582. if( rc==SQLITE_OK ){
  7583. if( pStmt ){
  7584. IdxStatement *pNew;
  7585. const char *z = sqlite3_sql(pStmt);
  7586. int n = STRLEN(z);
  7587. pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
  7588. if( rc==SQLITE_OK ){
  7589. pNew->zSql = (char*)&pNew[1];
  7590. memcpy(pNew->zSql, z, n+1);
  7591. pNew->pNext = p->pStatement;
  7592. if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
  7593. p->pStatement = pNew;
  7594. }
  7595. sqlite3_finalize(pStmt);
  7596. }
  7597. }else{
  7598. idxDatabaseError(p->dbv, pzErr);
  7599. }
  7600. }
  7601. if( rc!=SQLITE_OK ){
  7602. idxScanFree(p->pScan, pScanOrig);
  7603. idxStatementFree(p->pStatement, pStmtOrig);
  7604. p->pScan = pScanOrig;
  7605. p->pStatement = pStmtOrig;
  7606. }
  7607. return rc;
  7608. }
  7609. int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
  7610. int rc;
  7611. IdxHashEntry *pEntry;
  7612. /* Do trigger processing to collect any extra IdxScan structures */
  7613. rc = idxProcessTriggers(p, pzErr);
  7614. /* Create candidate indexes within the in-memory database file */
  7615. if( rc==SQLITE_OK ){
  7616. rc = idxCreateCandidates(p);
  7617. }
  7618. /* Generate the stat1 data */
  7619. if( rc==SQLITE_OK ){
  7620. rc = idxPopulateStat1(p, pzErr);
  7621. }
  7622. /* Formulate the EXPERT_REPORT_CANDIDATES text */
  7623. for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
  7624. p->zCandidates = idxAppendText(&rc, p->zCandidates,
  7625. "%s;%s%s\n", pEntry->zVal,
  7626. pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
  7627. );
  7628. }
  7629. /* Figure out which of the candidate indexes are preferred by the query
  7630. ** planner and report the results to the user. */
  7631. if( rc==SQLITE_OK ){
  7632. rc = idxFindIndexes(p, pzErr);
  7633. }
  7634. if( rc==SQLITE_OK ){
  7635. p->bRun = 1;
  7636. }
  7637. return rc;
  7638. }
  7639. /*
  7640. ** Return the total number of statements that have been added to this
  7641. ** sqlite3expert using sqlite3_expert_sql().
  7642. */
  7643. int sqlite3_expert_count(sqlite3expert *p){
  7644. int nRet = 0;
  7645. if( p->pStatement ) nRet = p->pStatement->iId+1;
  7646. return nRet;
  7647. }
  7648. /*
  7649. ** Return a component of the report.
  7650. */
  7651. const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
  7652. const char *zRet = 0;
  7653. IdxStatement *pStmt;
  7654. if( p->bRun==0 ) return 0;
  7655. for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
  7656. switch( eReport ){
  7657. case EXPERT_REPORT_SQL:
  7658. if( pStmt ) zRet = pStmt->zSql;
  7659. break;
  7660. case EXPERT_REPORT_INDEXES:
  7661. if( pStmt ) zRet = pStmt->zIdx;
  7662. break;
  7663. case EXPERT_REPORT_PLAN:
  7664. if( pStmt ) zRet = pStmt->zEQP;
  7665. break;
  7666. case EXPERT_REPORT_CANDIDATES:
  7667. zRet = p->zCandidates;
  7668. break;
  7669. }
  7670. return zRet;
  7671. }
  7672. /*
  7673. ** Free an sqlite3expert object.
  7674. */
  7675. void sqlite3_expert_destroy(sqlite3expert *p){
  7676. if( p ){
  7677. sqlite3_close(p->dbm);
  7678. sqlite3_close(p->dbv);
  7679. idxScanFree(p->pScan, 0);
  7680. idxStatementFree(p->pStatement, 0);
  7681. idxTableFree(p->pTable);
  7682. idxWriteFree(p->pWrite);
  7683. idxHashClear(&p->hIdx);
  7684. sqlite3_free(p->zCandidates);
  7685. sqlite3_free(p);
  7686. }
  7687. }
  7688. #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
  7689. /************************* End ../ext/expert/sqlite3expert.c ********************/
  7690. #if defined(SQLITE_ENABLE_SESSION)
  7691. /*
  7692. ** State information for a single open session
  7693. */
  7694. typedef struct OpenSession OpenSession;
  7695. struct OpenSession {
  7696. char *zName; /* Symbolic name for this session */
  7697. int nFilter; /* Number of xFilter rejection GLOB patterns */
  7698. char **azFilter; /* Array of xFilter rejection GLOB patterns */
  7699. sqlite3_session *p; /* The open session */
  7700. };
  7701. #endif
  7702. /*
  7703. ** Shell output mode information from before ".explain on",
  7704. ** saved so that it can be restored by ".explain off"
  7705. */
  7706. typedef struct SavedModeInfo SavedModeInfo;
  7707. struct SavedModeInfo {
  7708. int valid; /* Is there legit data in here? */
  7709. int mode; /* Mode prior to ".explain on" */
  7710. int showHeader; /* The ".header" setting prior to ".explain on" */
  7711. int colWidth[100]; /* Column widths prior to ".explain on" */
  7712. };
  7713. typedef struct ExpertInfo ExpertInfo;
  7714. struct ExpertInfo {
  7715. sqlite3expert *pExpert;
  7716. int bVerbose;
  7717. };
  7718. /* A single line in the EQP output */
  7719. typedef struct EQPGraphRow EQPGraphRow;
  7720. struct EQPGraphRow {
  7721. int iEqpId; /* ID for this row */
  7722. int iParentId; /* ID of the parent row */
  7723. EQPGraphRow *pNext; /* Next row in sequence */
  7724. char zText[1]; /* Text to display for this row */
  7725. };
  7726. /* All EQP output is collected into an instance of the following */
  7727. typedef struct EQPGraph EQPGraph;
  7728. struct EQPGraph {
  7729. EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
  7730. EQPGraphRow *pLast; /* Last element of the pRow list */
  7731. char zPrefix[100]; /* Graph prefix */
  7732. };
  7733. /*
  7734. ** State information about the database connection is contained in an
  7735. ** instance of the following structure.
  7736. */
  7737. typedef struct ShellState ShellState;
  7738. struct ShellState {
  7739. sqlite3 *db; /* The database */
  7740. u8 autoExplain; /* Automatically turn on .explain mode */
  7741. u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  7742. u8 autoEQPtest; /* autoEQP is in test mode */
  7743. u8 statsOn; /* True to display memory stats before each finalize */
  7744. u8 scanstatsOn; /* True to display scan stats before each finalize */
  7745. u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
  7746. u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
  7747. u8 nEqpLevel; /* Depth of the EQP output graph */
  7748. unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
  7749. int outCount; /* Revert to stdout when reaching zero */
  7750. int cnt; /* Number of records displayed so far */
  7751. FILE *out; /* Write results here */
  7752. FILE *traceOut; /* Output for sqlite3_trace() */
  7753. int nErr; /* Number of errors seen */
  7754. int mode; /* An output mode setting */
  7755. int modePrior; /* Saved mode */
  7756. int cMode; /* temporary output mode for the current query */
  7757. int normalMode; /* Output mode before ".explain on" */
  7758. int writableSchema; /* True if PRAGMA writable_schema=ON */
  7759. int showHeader; /* True to show column names in List or Column mode */
  7760. int nCheck; /* Number of ".check" commands run */
  7761. unsigned shellFlgs; /* Various flags */
  7762. char *zDestTable; /* Name of destination table when MODE_Insert */
  7763. char *zTempFile; /* Temporary file that might need deleting */
  7764. char zTestcase[30]; /* Name of current test case */
  7765. char colSeparator[20]; /* Column separator character for several modes */
  7766. char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  7767. char colSepPrior[20]; /* Saved column separator */
  7768. char rowSepPrior[20]; /* Saved row separator */
  7769. int colWidth[100]; /* Requested width of each column when in column mode*/
  7770. int actualWidth[100]; /* Actual width of each column */
  7771. char nullValue[20]; /* The text to print when a NULL comes back from
  7772. ** the database */
  7773. char outfile[FILENAME_MAX]; /* Filename for *out */
  7774. const char *zDbFilename; /* name of the database file */
  7775. char *zFreeOnClose; /* Filename to free when closing */
  7776. const char *zVfs; /* Name of VFS to use */
  7777. sqlite3_stmt *pStmt; /* Current statement if any. */
  7778. FILE *pLog; /* Write log output here */
  7779. int *aiIndent; /* Array of indents used in MODE_Explain */
  7780. int nIndent; /* Size of array aiIndent[] */
  7781. int iIndent; /* Index of current op in aiIndent[] */
  7782. EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
  7783. #if defined(SQLITE_ENABLE_SESSION)
  7784. int nSession; /* Number of active sessions */
  7785. OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
  7786. #endif
  7787. ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
  7788. };
  7789. /* Allowed values for ShellState.autoEQP
  7790. */
  7791. #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
  7792. #define AUTOEQP_on 1 /* Automatic EQP is on */
  7793. #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
  7794. #define AUTOEQP_full 3 /* Show full EXPLAIN */
  7795. /* Allowed values for ShellState.openMode
  7796. */
  7797. #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
  7798. #define SHELL_OPEN_NORMAL 1 /* Normal database file */
  7799. #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
  7800. #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
  7801. #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
  7802. /*
  7803. ** These are the allowed shellFlgs values
  7804. */
  7805. #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
  7806. #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
  7807. #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
  7808. #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
  7809. #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
  7810. #define SHFLG_CountChanges 0x00000020 /* .changes setting */
  7811. #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
  7812. /*
  7813. ** Macros for testing and setting shellFlgs
  7814. */
  7815. #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
  7816. #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
  7817. #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
  7818. /*
  7819. ** These are the allowed modes.
  7820. */
  7821. #define MODE_Line 0 /* One column per line. Blank line between records */
  7822. #define MODE_Column 1 /* One record per line in neat columns */
  7823. #define MODE_List 2 /* One record per line with a separator */
  7824. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  7825. #define MODE_Html 4 /* Generate an XHTML table */
  7826. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  7827. #define MODE_Quote 6 /* Quote values as for SQL */
  7828. #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
  7829. #define MODE_Csv 8 /* Quote strings, numbers are plain */
  7830. #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
  7831. #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
  7832. #define MODE_Pretty 11 /* Pretty-print schemas */
  7833. #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
  7834. static const char *modeDescr[] = {
  7835. "line",
  7836. "column",
  7837. "list",
  7838. "semi",
  7839. "html",
  7840. "insert",
  7841. "quote",
  7842. "tcl",
  7843. "csv",
  7844. "explain",
  7845. "ascii",
  7846. "prettyprint",
  7847. "eqp"
  7848. };
  7849. /*
  7850. ** These are the column/row/line separators used by the various
  7851. ** import/export modes.
  7852. */
  7853. #define SEP_Column "|"
  7854. #define SEP_Row "\n"
  7855. #define SEP_Tab "\t"
  7856. #define SEP_Space " "
  7857. #define SEP_Comma ","
  7858. #define SEP_CrLf "\r\n"
  7859. #define SEP_Unit "\x1F"
  7860. #define SEP_Record "\x1E"
  7861. /*
  7862. ** A callback for the sqlite3_log() interface.
  7863. */
  7864. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  7865. ShellState *p = (ShellState*)pArg;
  7866. if( p->pLog==0 ) return;
  7867. utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  7868. fflush(p->pLog);
  7869. }
  7870. /*
  7871. ** SQL function: shell_putsnl(X)
  7872. **
  7873. ** Write the text X to the screen (or whatever output is being directed)
  7874. ** adding a newline at the end, and then return X.
  7875. */
  7876. static void shellPutsFunc(
  7877. sqlite3_context *pCtx,
  7878. int nVal,
  7879. sqlite3_value **apVal
  7880. ){
  7881. ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
  7882. (void)nVal;
  7883. utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
  7884. sqlite3_result_value(pCtx, apVal[0]);
  7885. }
  7886. /*
  7887. ** SQL function: edit(VALUE)
  7888. ** edit(VALUE,EDITOR)
  7889. **
  7890. ** These steps:
  7891. **
  7892. ** (1) Write VALUE into a temporary file.
  7893. ** (2) Run program EDITOR on that temporary file.
  7894. ** (3) Read the temporary file back and return its content as the result.
  7895. ** (4) Delete the temporary file
  7896. **
  7897. ** If the EDITOR argument is omitted, use the value in the VISUAL
  7898. ** environment variable. If still there is no EDITOR, through an error.
  7899. **
  7900. ** Also throw an error if the EDITOR program returns a non-zero exit code.
  7901. */
  7902. #ifndef SQLITE_NOHAVE_SYSTEM
  7903. static void editFunc(
  7904. sqlite3_context *context,
  7905. int argc,
  7906. sqlite3_value **argv
  7907. ){
  7908. const char *zEditor;
  7909. char *zTempFile = 0;
  7910. sqlite3 *db;
  7911. char *zCmd = 0;
  7912. int bBin;
  7913. int rc;
  7914. int hasCRNL = 0;
  7915. FILE *f = 0;
  7916. sqlite3_int64 sz;
  7917. sqlite3_int64 x;
  7918. unsigned char *p = 0;
  7919. if( argc==2 ){
  7920. zEditor = (const char*)sqlite3_value_text(argv[1]);
  7921. }else{
  7922. zEditor = getenv("VISUAL");
  7923. }
  7924. if( zEditor==0 ){
  7925. sqlite3_result_error(context, "no editor for edit()", -1);
  7926. return;
  7927. }
  7928. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  7929. sqlite3_result_error(context, "NULL input to edit()", -1);
  7930. return;
  7931. }
  7932. db = sqlite3_context_db_handle(context);
  7933. zTempFile = 0;
  7934. sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
  7935. if( zTempFile==0 ){
  7936. sqlite3_uint64 r = 0;
  7937. sqlite3_randomness(sizeof(r), &r);
  7938. zTempFile = sqlite3_mprintf("temp%llx", r);
  7939. if( zTempFile==0 ){
  7940. sqlite3_result_error_nomem(context);
  7941. return;
  7942. }
  7943. }
  7944. bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
  7945. /* When writing the file to be edited, do \n to \r\n conversions on systems
  7946. ** that want \r\n line endings */
  7947. f = fopen(zTempFile, bBin ? "wb" : "w");
  7948. if( f==0 ){
  7949. sqlite3_result_error(context, "edit() cannot open temp file", -1);
  7950. goto edit_func_end;
  7951. }
  7952. sz = sqlite3_value_bytes(argv[0]);
  7953. if( bBin ){
  7954. x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
  7955. }else{
  7956. const char *z = (const char*)sqlite3_value_text(argv[0]);
  7957. /* Remember whether or not the value originally contained \r\n */
  7958. if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
  7959. x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
  7960. }
  7961. fclose(f);
  7962. f = 0;
  7963. if( x!=sz ){
  7964. sqlite3_result_error(context, "edit() could not write the whole file", -1);
  7965. goto edit_func_end;
  7966. }
  7967. zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
  7968. if( zCmd==0 ){
  7969. sqlite3_result_error_nomem(context);
  7970. goto edit_func_end;
  7971. }
  7972. rc = system(zCmd);
  7973. sqlite3_free(zCmd);
  7974. if( rc ){
  7975. sqlite3_result_error(context, "EDITOR returned non-zero", -1);
  7976. goto edit_func_end;
  7977. }
  7978. f = fopen(zTempFile, "rb");
  7979. if( f==0 ){
  7980. sqlite3_result_error(context,
  7981. "edit() cannot reopen temp file after edit", -1);
  7982. goto edit_func_end;
  7983. }
  7984. fseek(f, 0, SEEK_END);
  7985. sz = ftell(f);
  7986. rewind(f);
  7987. p = sqlite3_malloc64( sz+(bBin==0) );
  7988. if( p==0 ){
  7989. sqlite3_result_error_nomem(context);
  7990. goto edit_func_end;
  7991. }
  7992. x = fread(p, 1, sz, f);
  7993. fclose(f);
  7994. f = 0;
  7995. if( x!=sz ){
  7996. sqlite3_result_error(context, "could not read back the whole file", -1);
  7997. goto edit_func_end;
  7998. }
  7999. if( bBin ){
  8000. sqlite3_result_blob64(context, p, sz, sqlite3_free);
  8001. }else{
  8002. int i, j;
  8003. if( hasCRNL ){
  8004. /* If the original contains \r\n then do no conversions back to \n */
  8005. j = sz;
  8006. }else{
  8007. /* If the file did not originally contain \r\n then convert any new
  8008. ** \r\n back into \n */
  8009. for(i=j=0; i<sz; i++){
  8010. if( p[i]=='\r' && p[i+1]=='\n' ) i++;
  8011. p[j++] = p[i];
  8012. }
  8013. sz = j;
  8014. p[sz] = 0;
  8015. }
  8016. sqlite3_result_text64(context, (const char*)p, sz,
  8017. sqlite3_free, SQLITE_UTF8);
  8018. }
  8019. p = 0;
  8020. edit_func_end:
  8021. if( f ) fclose(f);
  8022. unlink(zTempFile);
  8023. sqlite3_free(zTempFile);
  8024. sqlite3_free(p);
  8025. }
  8026. #endif /* SQLITE_NOHAVE_SYSTEM */
  8027. /*
  8028. ** Save or restore the current output mode
  8029. */
  8030. static void outputModePush(ShellState *p){
  8031. p->modePrior = p->mode;
  8032. memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
  8033. memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
  8034. }
  8035. static void outputModePop(ShellState *p){
  8036. p->mode = p->modePrior;
  8037. memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
  8038. memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
  8039. }
  8040. /*
  8041. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  8042. */
  8043. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  8044. int i;
  8045. char *zBlob = (char *)pBlob;
  8046. raw_printf(out,"X'");
  8047. for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  8048. raw_printf(out,"'");
  8049. }
  8050. /*
  8051. ** Find a string that is not found anywhere in z[]. Return a pointer
  8052. ** to that string.
  8053. **
  8054. ** Try to use zA and zB first. If both of those are already found in z[]
  8055. ** then make up some string and store it in the buffer zBuf.
  8056. */
  8057. static const char *unused_string(
  8058. const char *z, /* Result must not appear anywhere in z */
  8059. const char *zA, const char *zB, /* Try these first */
  8060. char *zBuf /* Space to store a generated string */
  8061. ){
  8062. unsigned i = 0;
  8063. if( strstr(z, zA)==0 ) return zA;
  8064. if( strstr(z, zB)==0 ) return zB;
  8065. do{
  8066. sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
  8067. }while( strstr(z,zBuf)!=0 );
  8068. return zBuf;
  8069. }
  8070. /*
  8071. ** Output the given string as a quoted string using SQL quoting conventions.
  8072. **
  8073. ** See also: output_quoted_escaped_string()
  8074. */
  8075. static void output_quoted_string(FILE *out, const char *z){
  8076. int i;
  8077. char c;
  8078. setBinaryMode(out, 1);
  8079. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  8080. if( c==0 ){
  8081. utf8_printf(out,"'%s'",z);
  8082. }else{
  8083. raw_printf(out, "'");
  8084. while( *z ){
  8085. for(i=0; (c = z[i])!=0 && c!='\''; i++){}
  8086. if( c=='\'' ) i++;
  8087. if( i ){
  8088. utf8_printf(out, "%.*s", i, z);
  8089. z += i;
  8090. }
  8091. if( c=='\'' ){
  8092. raw_printf(out, "'");
  8093. continue;
  8094. }
  8095. if( c==0 ){
  8096. break;
  8097. }
  8098. z++;
  8099. }
  8100. raw_printf(out, "'");
  8101. }
  8102. setTextMode(out, 1);
  8103. }
  8104. /*
  8105. ** Output the given string as a quoted string using SQL quoting conventions.
  8106. ** Additionallly , escape the "\n" and "\r" characters so that they do not
  8107. ** get corrupted by end-of-line translation facilities in some operating
  8108. ** systems.
  8109. **
  8110. ** This is like output_quoted_string() but with the addition of the \r\n
  8111. ** escape mechanism.
  8112. */
  8113. static void output_quoted_escaped_string(FILE *out, const char *z){
  8114. int i;
  8115. char c;
  8116. setBinaryMode(out, 1);
  8117. for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  8118. if( c==0 ){
  8119. utf8_printf(out,"'%s'",z);
  8120. }else{
  8121. const char *zNL = 0;
  8122. const char *zCR = 0;
  8123. int nNL = 0;
  8124. int nCR = 0;
  8125. char zBuf1[20], zBuf2[20];
  8126. for(i=0; z[i]; i++){
  8127. if( z[i]=='\n' ) nNL++;
  8128. if( z[i]=='\r' ) nCR++;
  8129. }
  8130. if( nNL ){
  8131. raw_printf(out, "replace(");
  8132. zNL = unused_string(z, "\\n", "\\012", zBuf1);
  8133. }
  8134. if( nCR ){
  8135. raw_printf(out, "replace(");
  8136. zCR = unused_string(z, "\\r", "\\015", zBuf2);
  8137. }
  8138. raw_printf(out, "'");
  8139. while( *z ){
  8140. for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  8141. if( c=='\'' ) i++;
  8142. if( i ){
  8143. utf8_printf(out, "%.*s", i, z);
  8144. z += i;
  8145. }
  8146. if( c=='\'' ){
  8147. raw_printf(out, "'");
  8148. continue;
  8149. }
  8150. if( c==0 ){
  8151. break;
  8152. }
  8153. z++;
  8154. if( c=='\n' ){
  8155. raw_printf(out, "%s", zNL);
  8156. continue;
  8157. }
  8158. raw_printf(out, "%s", zCR);
  8159. }
  8160. raw_printf(out, "'");
  8161. if( nCR ){
  8162. raw_printf(out, ",'%s',char(13))", zCR);
  8163. }
  8164. if( nNL ){
  8165. raw_printf(out, ",'%s',char(10))", zNL);
  8166. }
  8167. }
  8168. setTextMode(out, 1);
  8169. }
  8170. /*
  8171. ** Output the given string as a quoted according to C or TCL quoting rules.
  8172. */
  8173. static void output_c_string(FILE *out, const char *z){
  8174. unsigned int c;
  8175. fputc('"', out);
  8176. while( (c = *(z++))!=0 ){
  8177. if( c=='\\' ){
  8178. fputc(c, out);
  8179. fputc(c, out);
  8180. }else if( c=='"' ){
  8181. fputc('\\', out);
  8182. fputc('"', out);
  8183. }else if( c=='\t' ){
  8184. fputc('\\', out);
  8185. fputc('t', out);
  8186. }else if( c=='\n' ){
  8187. fputc('\\', out);
  8188. fputc('n', out);
  8189. }else if( c=='\r' ){
  8190. fputc('\\', out);
  8191. fputc('r', out);
  8192. }else if( !isprint(c&0xff) ){
  8193. raw_printf(out, "\\%03o", c&0xff);
  8194. }else{
  8195. fputc(c, out);
  8196. }
  8197. }
  8198. fputc('"', out);
  8199. }
  8200. /*
  8201. ** Output the given string with characters that are special to
  8202. ** HTML escaped.
  8203. */
  8204. static void output_html_string(FILE *out, const char *z){
  8205. int i;
  8206. if( z==0 ) z = "";
  8207. while( *z ){
  8208. for(i=0; z[i]
  8209. && z[i]!='<'
  8210. && z[i]!='&'
  8211. && z[i]!='>'
  8212. && z[i]!='\"'
  8213. && z[i]!='\'';
  8214. i++){}
  8215. if( i>0 ){
  8216. utf8_printf(out,"%.*s",i,z);
  8217. }
  8218. if( z[i]=='<' ){
  8219. raw_printf(out,"&lt;");
  8220. }else if( z[i]=='&' ){
  8221. raw_printf(out,"&amp;");
  8222. }else if( z[i]=='>' ){
  8223. raw_printf(out,"&gt;");
  8224. }else if( z[i]=='\"' ){
  8225. raw_printf(out,"&quot;");
  8226. }else if( z[i]=='\'' ){
  8227. raw_printf(out,"&#39;");
  8228. }else{
  8229. break;
  8230. }
  8231. z += i + 1;
  8232. }
  8233. }
  8234. /*
  8235. ** If a field contains any character identified by a 1 in the following
  8236. ** array, then the string must be quoted for CSV.
  8237. */
  8238. static const char needCsvQuote[] = {
  8239. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8240. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8241. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  8242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  8246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  8247. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8248. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8249. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8250. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8251. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8252. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8253. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8254. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  8255. };
  8256. /*
  8257. ** Output a single term of CSV. Actually, p->colSeparator is used for
  8258. ** the separator, which may or may not be a comma. p->nullValue is
  8259. ** the null value. Strings are quoted if necessary. The separator
  8260. ** is only issued if bSep is true.
  8261. */
  8262. static void output_csv(ShellState *p, const char *z, int bSep){
  8263. FILE *out = p->out;
  8264. if( z==0 ){
  8265. utf8_printf(out,"%s",p->nullValue);
  8266. }else{
  8267. int i;
  8268. int nSep = strlen30(p->colSeparator);
  8269. for(i=0; z[i]; i++){
  8270. if( needCsvQuote[((unsigned char*)z)[i]]
  8271. || (z[i]==p->colSeparator[0] &&
  8272. (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  8273. i = 0;
  8274. break;
  8275. }
  8276. }
  8277. if( i==0 ){
  8278. char *zQuoted = sqlite3_mprintf("\"%w\"", z);
  8279. utf8_printf(out, "%s", zQuoted);
  8280. sqlite3_free(zQuoted);
  8281. }else{
  8282. utf8_printf(out, "%s", z);
  8283. }
  8284. }
  8285. if( bSep ){
  8286. utf8_printf(p->out, "%s", p->colSeparator);
  8287. }
  8288. }
  8289. /*
  8290. ** This routine runs when the user presses Ctrl-C
  8291. */
  8292. static void interrupt_handler(int NotUsed){
  8293. UNUSED_PARAMETER(NotUsed);
  8294. seenInterrupt++;
  8295. if( seenInterrupt>2 ) exit(1);
  8296. if( globalDb ) sqlite3_interrupt(globalDb);
  8297. }
  8298. #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  8299. /*
  8300. ** This routine runs for console events (e.g. Ctrl-C) on Win32
  8301. */
  8302. static BOOL WINAPI ConsoleCtrlHandler(
  8303. DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
  8304. ){
  8305. if( dwCtrlType==CTRL_C_EVENT ){
  8306. interrupt_handler(0);
  8307. return TRUE;
  8308. }
  8309. return FALSE;
  8310. }
  8311. #endif
  8312. #ifndef SQLITE_OMIT_AUTHORIZATION
  8313. /*
  8314. ** When the ".auth ON" is set, the following authorizer callback is
  8315. ** invoked. It always returns SQLITE_OK.
  8316. */
  8317. static int shellAuth(
  8318. void *pClientData,
  8319. int op,
  8320. const char *zA1,
  8321. const char *zA2,
  8322. const char *zA3,
  8323. const char *zA4
  8324. ){
  8325. ShellState *p = (ShellState*)pClientData;
  8326. static const char *azAction[] = { 0,
  8327. "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
  8328. "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
  8329. "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
  8330. "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
  8331. "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
  8332. "DROP_TRIGGER", "DROP_VIEW", "INSERT",
  8333. "PRAGMA", "READ", "SELECT",
  8334. "TRANSACTION", "UPDATE", "ATTACH",
  8335. "DETACH", "ALTER_TABLE", "REINDEX",
  8336. "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
  8337. "FUNCTION", "SAVEPOINT", "RECURSIVE"
  8338. };
  8339. int i;
  8340. const char *az[4];
  8341. az[0] = zA1;
  8342. az[1] = zA2;
  8343. az[2] = zA3;
  8344. az[3] = zA4;
  8345. utf8_printf(p->out, "authorizer: %s", azAction[op]);
  8346. for(i=0; i<4; i++){
  8347. raw_printf(p->out, " ");
  8348. if( az[i] ){
  8349. output_c_string(p->out, az[i]);
  8350. }else{
  8351. raw_printf(p->out, "NULL");
  8352. }
  8353. }
  8354. raw_printf(p->out, "\n");
  8355. return SQLITE_OK;
  8356. }
  8357. #endif
  8358. /*
  8359. ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
  8360. **
  8361. ** This routine converts some CREATE TABLE statements for shadow tables
  8362. ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
  8363. */
  8364. static void printSchemaLine(FILE *out, const char *z, const char *zTail){
  8365. if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
  8366. utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
  8367. }else{
  8368. utf8_printf(out, "%s%s", z, zTail);
  8369. }
  8370. }
  8371. static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
  8372. char c = z[n];
  8373. z[n] = 0;
  8374. printSchemaLine(out, z, zTail);
  8375. z[n] = c;
  8376. }
  8377. /*
  8378. ** Return true if string z[] has nothing but whitespace and comments to the
  8379. ** end of the first line.
  8380. */
  8381. static int wsToEol(const char *z){
  8382. int i;
  8383. for(i=0; z[i]; i++){
  8384. if( z[i]=='\n' ) return 1;
  8385. if( IsSpace(z[i]) ) continue;
  8386. if( z[i]=='-' && z[i+1]=='-' ) return 1;
  8387. return 0;
  8388. }
  8389. return 1;
  8390. }
  8391. /*
  8392. ** Add a new entry to the EXPLAIN QUERY PLAN data
  8393. */
  8394. static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
  8395. EQPGraphRow *pNew;
  8396. int nText = strlen30(zText);
  8397. if( p->autoEQPtest ){
  8398. utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
  8399. }
  8400. pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
  8401. if( pNew==0 ) shell_out_of_memory();
  8402. pNew->iEqpId = iEqpId;
  8403. pNew->iParentId = p2;
  8404. memcpy(pNew->zText, zText, nText+1);
  8405. pNew->pNext = 0;
  8406. if( p->sGraph.pLast ){
  8407. p->sGraph.pLast->pNext = pNew;
  8408. }else{
  8409. p->sGraph.pRow = pNew;
  8410. }
  8411. p->sGraph.pLast = pNew;
  8412. }
  8413. /*
  8414. ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
  8415. ** in p->sGraph.
  8416. */
  8417. static void eqp_reset(ShellState *p){
  8418. EQPGraphRow *pRow, *pNext;
  8419. for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
  8420. pNext = pRow->pNext;
  8421. sqlite3_free(pRow);
  8422. }
  8423. memset(&p->sGraph, 0, sizeof(p->sGraph));
  8424. }
  8425. /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
  8426. ** pOld, or return the first such line if pOld is NULL
  8427. */
  8428. static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
  8429. EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
  8430. while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
  8431. return pRow;
  8432. }
  8433. /* Render a single level of the graph that has iEqpId as its parent. Called
  8434. ** recursively to render sublevels.
  8435. */
  8436. static void eqp_render_level(ShellState *p, int iEqpId){
  8437. EQPGraphRow *pRow, *pNext;
  8438. int n = strlen30(p->sGraph.zPrefix);
  8439. char *z;
  8440. for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
  8441. pNext = eqp_next_row(p, iEqpId, pRow);
  8442. z = pRow->zText;
  8443. utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
  8444. if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
  8445. memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
  8446. eqp_render_level(p, pRow->iEqpId);
  8447. p->sGraph.zPrefix[n] = 0;
  8448. }
  8449. }
  8450. }
  8451. /*
  8452. ** Display and reset the EXPLAIN QUERY PLAN data
  8453. */
  8454. static void eqp_render(ShellState *p){
  8455. EQPGraphRow *pRow = p->sGraph.pRow;
  8456. if( pRow ){
  8457. if( pRow->zText[0]=='-' ){
  8458. if( pRow->pNext==0 ){
  8459. eqp_reset(p);
  8460. return;
  8461. }
  8462. utf8_printf(p->out, "%s\n", pRow->zText+3);
  8463. p->sGraph.pRow = pRow->pNext;
  8464. sqlite3_free(pRow);
  8465. }else{
  8466. utf8_printf(p->out, "QUERY PLAN\n");
  8467. }
  8468. p->sGraph.zPrefix[0] = 0;
  8469. eqp_render_level(p, 0);
  8470. eqp_reset(p);
  8471. }
  8472. }
  8473. /*
  8474. ** This is the callback routine that the shell
  8475. ** invokes for each row of a query result.
  8476. */
  8477. static int shell_callback(
  8478. void *pArg,
  8479. int nArg, /* Number of result columns */
  8480. char **azArg, /* Text of each result column */
  8481. char **azCol, /* Column names */
  8482. int *aiType /* Column types */
  8483. ){
  8484. int i;
  8485. ShellState *p = (ShellState*)pArg;
  8486. if( azArg==0 ) return 0;
  8487. switch( p->cMode ){
  8488. case MODE_Line: {
  8489. int w = 5;
  8490. if( azArg==0 ) break;
  8491. for(i=0; i<nArg; i++){
  8492. int len = strlen30(azCol[i] ? azCol[i] : "");
  8493. if( len>w ) w = len;
  8494. }
  8495. if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  8496. for(i=0; i<nArg; i++){
  8497. utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  8498. azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  8499. }
  8500. break;
  8501. }
  8502. case MODE_Explain:
  8503. case MODE_Column: {
  8504. static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
  8505. const int *colWidth;
  8506. int showHdr;
  8507. char *rowSep;
  8508. if( p->cMode==MODE_Column ){
  8509. colWidth = p->colWidth;
  8510. showHdr = p->showHeader;
  8511. rowSep = p->rowSeparator;
  8512. }else{
  8513. colWidth = aExplainWidths;
  8514. showHdr = 1;
  8515. rowSep = SEP_Row;
  8516. }
  8517. if( p->cnt++==0 ){
  8518. for(i=0; i<nArg; i++){
  8519. int w, n;
  8520. if( i<ArraySize(p->colWidth) ){
  8521. w = colWidth[i];
  8522. }else{
  8523. w = 0;
  8524. }
  8525. if( w==0 ){
  8526. w = strlenChar(azCol[i] ? azCol[i] : "");
  8527. if( w<10 ) w = 10;
  8528. n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
  8529. if( w<n ) w = n;
  8530. }
  8531. if( i<ArraySize(p->actualWidth) ){
  8532. p->actualWidth[i] = w;
  8533. }
  8534. if( showHdr ){
  8535. utf8_width_print(p->out, w, azCol[i]);
  8536. utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
  8537. }
  8538. }
  8539. if( showHdr ){
  8540. for(i=0; i<nArg; i++){
  8541. int w;
  8542. if( i<ArraySize(p->actualWidth) ){
  8543. w = p->actualWidth[i];
  8544. if( w<0 ) w = -w;
  8545. }else{
  8546. w = 10;
  8547. }
  8548. utf8_printf(p->out,"%-*.*s%s",w,w,
  8549. "----------------------------------------------------------"
  8550. "----------------------------------------------------------",
  8551. i==nArg-1 ? rowSep : " ");
  8552. }
  8553. }
  8554. }
  8555. if( azArg==0 ) break;
  8556. for(i=0; i<nArg; i++){
  8557. int w;
  8558. if( i<ArraySize(p->actualWidth) ){
  8559. w = p->actualWidth[i];
  8560. }else{
  8561. w = 10;
  8562. }
  8563. if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
  8564. w = strlenChar(azArg[i]);
  8565. }
  8566. if( i==1 && p->aiIndent && p->pStmt ){
  8567. if( p->iIndent<p->nIndent ){
  8568. utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  8569. }
  8570. p->iIndent++;
  8571. }
  8572. utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  8573. utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
  8574. }
  8575. break;
  8576. }
  8577. case MODE_Semi: { /* .schema and .fullschema output */
  8578. printSchemaLine(p->out, azArg[0], ";\n");
  8579. break;
  8580. }
  8581. case MODE_Pretty: { /* .schema and .fullschema with --indent */
  8582. char *z;
  8583. int j;
  8584. int nParen = 0;
  8585. char cEnd = 0;
  8586. char c;
  8587. int nLine = 0;
  8588. assert( nArg==1 );
  8589. if( azArg[0]==0 ) break;
  8590. if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  8591. || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  8592. ){
  8593. utf8_printf(p->out, "%s;\n", azArg[0]);
  8594. break;
  8595. }
  8596. z = sqlite3_mprintf("%s", azArg[0]);
  8597. j = 0;
  8598. for(i=0; IsSpace(z[i]); i++){}
  8599. for(; (c = z[i])!=0; i++){
  8600. if( IsSpace(c) ){
  8601. if( z[j-1]=='\r' ) z[j-1] = '\n';
  8602. if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  8603. }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  8604. j--;
  8605. }
  8606. z[j++] = c;
  8607. }
  8608. while( j>0 && IsSpace(z[j-1]) ){ j--; }
  8609. z[j] = 0;
  8610. if( strlen30(z)>=79 ){
  8611. for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
  8612. if( c==cEnd ){
  8613. cEnd = 0;
  8614. }else if( c=='"' || c=='\'' || c=='`' ){
  8615. cEnd = c;
  8616. }else if( c=='[' ){
  8617. cEnd = ']';
  8618. }else if( c=='-' && z[i+1]=='-' ){
  8619. cEnd = '\n';
  8620. }else if( c=='(' ){
  8621. nParen++;
  8622. }else if( c==')' ){
  8623. nParen--;
  8624. if( nLine>0 && nParen==0 && j>0 ){
  8625. printSchemaLineN(p->out, z, j, "\n");
  8626. j = 0;
  8627. }
  8628. }
  8629. z[j++] = c;
  8630. if( nParen==1 && cEnd==0
  8631. && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
  8632. ){
  8633. if( c=='\n' ) j--;
  8634. printSchemaLineN(p->out, z, j, "\n ");
  8635. j = 0;
  8636. nLine++;
  8637. while( IsSpace(z[i+1]) ){ i++; }
  8638. }
  8639. }
  8640. z[j] = 0;
  8641. }
  8642. printSchemaLine(p->out, z, ";\n");
  8643. sqlite3_free(z);
  8644. break;
  8645. }
  8646. case MODE_List: {
  8647. if( p->cnt++==0 && p->showHeader ){
  8648. for(i=0; i<nArg; i++){
  8649. utf8_printf(p->out,"%s%s",azCol[i],
  8650. i==nArg-1 ? p->rowSeparator : p->colSeparator);
  8651. }
  8652. }
  8653. if( azArg==0 ) break;
  8654. for(i=0; i<nArg; i++){
  8655. char *z = azArg[i];
  8656. if( z==0 ) z = p->nullValue;
  8657. utf8_printf(p->out, "%s", z);
  8658. if( i<nArg-1 ){
  8659. utf8_printf(p->out, "%s", p->colSeparator);
  8660. }else{
  8661. utf8_printf(p->out, "%s", p->rowSeparator);
  8662. }
  8663. }
  8664. break;
  8665. }
  8666. case MODE_Html: {
  8667. if( p->cnt++==0 && p->showHeader ){
  8668. raw_printf(p->out,"<TR>");
  8669. for(i=0; i<nArg; i++){
  8670. raw_printf(p->out,"<TH>");
  8671. output_html_string(p->out, azCol[i]);
  8672. raw_printf(p->out,"</TH>\n");
  8673. }
  8674. raw_printf(p->out,"</TR>\n");
  8675. }
  8676. if( azArg==0 ) break;
  8677. raw_printf(p->out,"<TR>");
  8678. for(i=0; i<nArg; i++){
  8679. raw_printf(p->out,"<TD>");
  8680. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  8681. raw_printf(p->out,"</TD>\n");
  8682. }
  8683. raw_printf(p->out,"</TR>\n");
  8684. break;
  8685. }
  8686. case MODE_Tcl: {
  8687. if( p->cnt++==0 && p->showHeader ){
  8688. for(i=0; i<nArg; i++){
  8689. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  8690. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  8691. }
  8692. utf8_printf(p->out, "%s", p->rowSeparator);
  8693. }
  8694. if( azArg==0 ) break;
  8695. for(i=0; i<nArg; i++){
  8696. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  8697. if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  8698. }
  8699. utf8_printf(p->out, "%s", p->rowSeparator);
  8700. break;
  8701. }
  8702. case MODE_Csv: {
  8703. setBinaryMode(p->out, 1);
  8704. if( p->cnt++==0 && p->showHeader ){
  8705. for(i=0; i<nArg; i++){
  8706. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  8707. }
  8708. utf8_printf(p->out, "%s", p->rowSeparator);
  8709. }
  8710. if( nArg>0 ){
  8711. for(i=0; i<nArg; i++){
  8712. output_csv(p, azArg[i], i<nArg-1);
  8713. }
  8714. utf8_printf(p->out, "%s", p->rowSeparator);
  8715. }
  8716. setTextMode(p->out, 1);
  8717. break;
  8718. }
  8719. case MODE_Insert: {
  8720. if( azArg==0 ) break;
  8721. utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  8722. if( p->showHeader ){
  8723. raw_printf(p->out,"(");
  8724. for(i=0; i<nArg; i++){
  8725. if( i>0 ) raw_printf(p->out, ",");
  8726. if( quoteChar(azCol[i]) ){
  8727. char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
  8728. utf8_printf(p->out, "%s", z);
  8729. sqlite3_free(z);
  8730. }else{
  8731. raw_printf(p->out, "%s", azCol[i]);
  8732. }
  8733. }
  8734. raw_printf(p->out,")");
  8735. }
  8736. p->cnt++;
  8737. for(i=0; i<nArg; i++){
  8738. raw_printf(p->out, i>0 ? "," : " VALUES(");
  8739. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  8740. utf8_printf(p->out,"NULL");
  8741. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  8742. if( ShellHasFlag(p, SHFLG_Newlines) ){
  8743. output_quoted_string(p->out, azArg[i]);
  8744. }else{
  8745. output_quoted_escaped_string(p->out, azArg[i]);
  8746. }
  8747. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  8748. utf8_printf(p->out,"%s", azArg[i]);
  8749. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  8750. char z[50];
  8751. double r = sqlite3_column_double(p->pStmt, i);
  8752. sqlite3_uint64 ur;
  8753. memcpy(&ur,&r,sizeof(r));
  8754. if( ur==0x7ff0000000000000LL ){
  8755. raw_printf(p->out, "1e999");
  8756. }else if( ur==0xfff0000000000000LL ){
  8757. raw_printf(p->out, "-1e999");
  8758. }else{
  8759. sqlite3_snprintf(50,z,"%!.20g", r);
  8760. raw_printf(p->out, "%s", z);
  8761. }
  8762. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  8763. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  8764. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  8765. output_hex_blob(p->out, pBlob, nBlob);
  8766. }else if( isNumber(azArg[i], 0) ){
  8767. utf8_printf(p->out,"%s", azArg[i]);
  8768. }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  8769. output_quoted_string(p->out, azArg[i]);
  8770. }else{
  8771. output_quoted_escaped_string(p->out, azArg[i]);
  8772. }
  8773. }
  8774. raw_printf(p->out,");\n");
  8775. break;
  8776. }
  8777. case MODE_Quote: {
  8778. if( azArg==0 ) break;
  8779. if( p->cnt==0 && p->showHeader ){
  8780. for(i=0; i<nArg; i++){
  8781. if( i>0 ) raw_printf(p->out, ",");
  8782. output_quoted_string(p->out, azCol[i]);
  8783. }
  8784. raw_printf(p->out,"\n");
  8785. }
  8786. p->cnt++;
  8787. for(i=0; i<nArg; i++){
  8788. if( i>0 ) raw_printf(p->out, ",");
  8789. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  8790. utf8_printf(p->out,"NULL");
  8791. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  8792. output_quoted_string(p->out, azArg[i]);
  8793. }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  8794. utf8_printf(p->out,"%s", azArg[i]);
  8795. }else if( aiType && aiType[i]==SQLITE_FLOAT ){
  8796. char z[50];
  8797. double r = sqlite3_column_double(p->pStmt, i);
  8798. sqlite3_snprintf(50,z,"%!.20g", r);
  8799. raw_printf(p->out, "%s", z);
  8800. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  8801. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  8802. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  8803. output_hex_blob(p->out, pBlob, nBlob);
  8804. }else if( isNumber(azArg[i], 0) ){
  8805. utf8_printf(p->out,"%s", azArg[i]);
  8806. }else{
  8807. output_quoted_string(p->out, azArg[i]);
  8808. }
  8809. }
  8810. raw_printf(p->out,"\n");
  8811. break;
  8812. }
  8813. case MODE_Ascii: {
  8814. if( p->cnt++==0 && p->showHeader ){
  8815. for(i=0; i<nArg; i++){
  8816. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  8817. utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  8818. }
  8819. utf8_printf(p->out, "%s", p->rowSeparator);
  8820. }
  8821. if( azArg==0 ) break;
  8822. for(i=0; i<nArg; i++){
  8823. if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  8824. utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  8825. }
  8826. utf8_printf(p->out, "%s", p->rowSeparator);
  8827. break;
  8828. }
  8829. case MODE_EQP: {
  8830. eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
  8831. break;
  8832. }
  8833. }
  8834. return 0;
  8835. }
  8836. /*
  8837. ** This is the callback routine that the SQLite library
  8838. ** invokes for each row of a query result.
  8839. */
  8840. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  8841. /* since we don't have type info, call the shell_callback with a NULL value */
  8842. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  8843. }
  8844. /*
  8845. ** This is the callback routine from sqlite3_exec() that appends all
  8846. ** output onto the end of a ShellText object.
  8847. */
  8848. static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  8849. ShellText *p = (ShellText*)pArg;
  8850. int i;
  8851. UNUSED_PARAMETER(az);
  8852. if( azArg==0 ) return 0;
  8853. if( p->n ) appendText(p, "|", 0);
  8854. for(i=0; i<nArg; i++){
  8855. if( i ) appendText(p, ",", 0);
  8856. if( azArg[i] ) appendText(p, azArg[i], 0);
  8857. }
  8858. return 0;
  8859. }
  8860. /*
  8861. ** Generate an appropriate SELFTEST table in the main database.
  8862. */
  8863. static void createSelftestTable(ShellState *p){
  8864. char *zErrMsg = 0;
  8865. sqlite3_exec(p->db,
  8866. "SAVEPOINT selftest_init;\n"
  8867. "CREATE TABLE IF NOT EXISTS selftest(\n"
  8868. " tno INTEGER PRIMARY KEY,\n" /* Test number */
  8869. " op TEXT,\n" /* Operator: memo run */
  8870. " cmd TEXT,\n" /* Command text */
  8871. " ans TEXT\n" /* Desired answer */
  8872. ");"
  8873. "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
  8874. "INSERT INTO [_shell$self](rowid,op,cmd)\n"
  8875. " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
  8876. " 'memo','Tests generated by --init');\n"
  8877. "INSERT INTO [_shell$self]\n"
  8878. " SELECT 'run',\n"
  8879. " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
  8880. "FROM sqlite_master ORDER BY 2'',224))',\n"
  8881. " hex(sha3_query('SELECT type,name,tbl_name,sql "
  8882. "FROM sqlite_master ORDER BY 2',224));\n"
  8883. "INSERT INTO [_shell$self]\n"
  8884. " SELECT 'run',"
  8885. " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
  8886. " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
  8887. " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
  8888. " FROM (\n"
  8889. " SELECT name FROM sqlite_master\n"
  8890. " WHERE type='table'\n"
  8891. " AND name<>'selftest'\n"
  8892. " AND coalesce(rootpage,0)>0\n"
  8893. " )\n"
  8894. " ORDER BY name;\n"
  8895. "INSERT INTO [_shell$self]\n"
  8896. " VALUES('run','PRAGMA integrity_check','ok');\n"
  8897. "INSERT INTO selftest(tno,op,cmd,ans)"
  8898. " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
  8899. "DROP TABLE [_shell$self];"
  8900. ,0,0,&zErrMsg);
  8901. if( zErrMsg ){
  8902. utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
  8903. sqlite3_free(zErrMsg);
  8904. }
  8905. sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
  8906. }
  8907. /*
  8908. ** Set the destination table field of the ShellState structure to
  8909. ** the name of the table given. Escape any quote characters in the
  8910. ** table name.
  8911. */
  8912. static void set_table_name(ShellState *p, const char *zName){
  8913. int i, n;
  8914. char cQuote;
  8915. char *z;
  8916. if( p->zDestTable ){
  8917. free(p->zDestTable);
  8918. p->zDestTable = 0;
  8919. }
  8920. if( zName==0 ) return;
  8921. cQuote = quoteChar(zName);
  8922. n = strlen30(zName);
  8923. if( cQuote ) n += n+2;
  8924. z = p->zDestTable = malloc( n+1 );
  8925. if( z==0 ) shell_out_of_memory();
  8926. n = 0;
  8927. if( cQuote ) z[n++] = cQuote;
  8928. for(i=0; zName[i]; i++){
  8929. z[n++] = zName[i];
  8930. if( zName[i]==cQuote ) z[n++] = cQuote;
  8931. }
  8932. if( cQuote ) z[n++] = cQuote;
  8933. z[n] = 0;
  8934. }
  8935. /*
  8936. ** Execute a query statement that will generate SQL output. Print
  8937. ** the result columns, comma-separated, on a line and then add a
  8938. ** semicolon terminator to the end of that line.
  8939. **
  8940. ** If the number of columns is 1 and that column contains text "--"
  8941. ** then write the semicolon on a separate line. That way, if a
  8942. ** "--" comment occurs at the end of the statement, the comment
  8943. ** won't consume the semicolon terminator.
  8944. */
  8945. static int run_table_dump_query(
  8946. ShellState *p, /* Query context */
  8947. const char *zSelect, /* SELECT statement to extract content */
  8948. const char *zFirstRow /* Print before first row, if not NULL */
  8949. ){
  8950. sqlite3_stmt *pSelect;
  8951. int rc;
  8952. int nResult;
  8953. int i;
  8954. const char *z;
  8955. rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  8956. if( rc!=SQLITE_OK || !pSelect ){
  8957. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  8958. sqlite3_errmsg(p->db));
  8959. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  8960. return rc;
  8961. }
  8962. rc = sqlite3_step(pSelect);
  8963. nResult = sqlite3_column_count(pSelect);
  8964. while( rc==SQLITE_ROW ){
  8965. if( zFirstRow ){
  8966. utf8_printf(p->out, "%s", zFirstRow);
  8967. zFirstRow = 0;
  8968. }
  8969. z = (const char*)sqlite3_column_text(pSelect, 0);
  8970. utf8_printf(p->out, "%s", z);
  8971. for(i=1; i<nResult; i++){
  8972. utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  8973. }
  8974. if( z==0 ) z = "";
  8975. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  8976. if( z[0] ){
  8977. raw_printf(p->out, "\n;\n");
  8978. }else{
  8979. raw_printf(p->out, ";\n");
  8980. }
  8981. rc = sqlite3_step(pSelect);
  8982. }
  8983. rc = sqlite3_finalize(pSelect);
  8984. if( rc!=SQLITE_OK ){
  8985. utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  8986. sqlite3_errmsg(p->db));
  8987. if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  8988. }
  8989. return rc;
  8990. }
  8991. /*
  8992. ** Allocate space and save off current error string.
  8993. */
  8994. static char *save_err_msg(
  8995. sqlite3 *db /* Database to query */
  8996. ){
  8997. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  8998. char *zErrMsg = sqlite3_malloc64(nErrMsg);
  8999. if( zErrMsg ){
  9000. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  9001. }
  9002. return zErrMsg;
  9003. }
  9004. #ifdef __linux__
  9005. /*
  9006. ** Attempt to display I/O stats on Linux using /proc/PID/io
  9007. */
  9008. static void displayLinuxIoStats(FILE *out){
  9009. FILE *in;
  9010. char z[200];
  9011. sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  9012. in = fopen(z, "rb");
  9013. if( in==0 ) return;
  9014. while( fgets(z, sizeof(z), in)!=0 ){
  9015. static const struct {
  9016. const char *zPattern;
  9017. const char *zDesc;
  9018. } aTrans[] = {
  9019. { "rchar: ", "Bytes received by read():" },
  9020. { "wchar: ", "Bytes sent to write():" },
  9021. { "syscr: ", "Read() system calls:" },
  9022. { "syscw: ", "Write() system calls:" },
  9023. { "read_bytes: ", "Bytes read from storage:" },
  9024. { "write_bytes: ", "Bytes written to storage:" },
  9025. { "cancelled_write_bytes: ", "Cancelled write bytes:" },
  9026. };
  9027. int i;
  9028. for(i=0; i<ArraySize(aTrans); i++){
  9029. int n = strlen30(aTrans[i].zPattern);
  9030. if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  9031. utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  9032. break;
  9033. }
  9034. }
  9035. }
  9036. fclose(in);
  9037. }
  9038. #endif
  9039. /*
  9040. ** Display a single line of status using 64-bit values.
  9041. */
  9042. static void displayStatLine(
  9043. ShellState *p, /* The shell context */
  9044. char *zLabel, /* Label for this one line */
  9045. char *zFormat, /* Format for the result */
  9046. int iStatusCtrl, /* Which status to display */
  9047. int bReset /* True to reset the stats */
  9048. ){
  9049. sqlite3_int64 iCur = -1;
  9050. sqlite3_int64 iHiwtr = -1;
  9051. int i, nPercent;
  9052. char zLine[200];
  9053. sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
  9054. for(i=0, nPercent=0; zFormat[i]; i++){
  9055. if( zFormat[i]=='%' ) nPercent++;
  9056. }
  9057. if( nPercent>1 ){
  9058. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
  9059. }else{
  9060. sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
  9061. }
  9062. raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
  9063. }
  9064. /*
  9065. ** Display memory stats.
  9066. */
  9067. static int display_stats(
  9068. sqlite3 *db, /* Database to query */
  9069. ShellState *pArg, /* Pointer to ShellState */
  9070. int bReset /* True to reset the stats */
  9071. ){
  9072. int iCur;
  9073. int iHiwtr;
  9074. FILE *out;
  9075. if( pArg==0 || pArg->out==0 ) return 0;
  9076. out = pArg->out;
  9077. if( pArg->pStmt && (pArg->statsOn & 2) ){
  9078. int nCol, i, x;
  9079. sqlite3_stmt *pStmt = pArg->pStmt;
  9080. char z[100];
  9081. nCol = sqlite3_column_count(pStmt);
  9082. raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
  9083. for(i=0; i<nCol; i++){
  9084. sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
  9085. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
  9086. #ifndef SQLITE_OMIT_DECLTYPE
  9087. sqlite3_snprintf(30, z+x, "declared type:");
  9088. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
  9089. #endif
  9090. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  9091. sqlite3_snprintf(30, z+x, "database name:");
  9092. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
  9093. sqlite3_snprintf(30, z+x, "table name:");
  9094. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
  9095. sqlite3_snprintf(30, z+x, "origin name:");
  9096. utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
  9097. #endif
  9098. }
  9099. }
  9100. displayStatLine(pArg, "Memory Used:",
  9101. "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
  9102. displayStatLine(pArg, "Number of Outstanding Allocations:",
  9103. "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
  9104. if( pArg->shellFlgs & SHFLG_Pagecache ){
  9105. displayStatLine(pArg, "Number of Pcache Pages Used:",
  9106. "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  9107. }
  9108. displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  9109. "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  9110. displayStatLine(pArg, "Largest Allocation:",
  9111. "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
  9112. displayStatLine(pArg, "Largest Pcache Allocation:",
  9113. "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
  9114. #ifdef YYTRACKMAXSTACKDEPTH
  9115. displayStatLine(pArg, "Deepest Parser Stack:",
  9116. "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  9117. #endif
  9118. if( db ){
  9119. if( pArg->shellFlgs & SHFLG_Lookaside ){
  9120. iHiwtr = iCur = -1;
  9121. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  9122. &iCur, &iHiwtr, bReset);
  9123. raw_printf(pArg->out,
  9124. "Lookaside Slots Used: %d (max %d)\n",
  9125. iCur, iHiwtr);
  9126. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  9127. &iCur, &iHiwtr, bReset);
  9128. raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
  9129. iHiwtr);
  9130. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  9131. &iCur, &iHiwtr, bReset);
  9132. raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
  9133. iHiwtr);
  9134. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  9135. &iCur, &iHiwtr, bReset);
  9136. raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
  9137. iHiwtr);
  9138. }
  9139. iHiwtr = iCur = -1;
  9140. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  9141. raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
  9142. iCur);
  9143. iHiwtr = iCur = -1;
  9144. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  9145. raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
  9146. iHiwtr = iCur = -1;
  9147. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  9148. raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
  9149. iHiwtr = iCur = -1;
  9150. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  9151. raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
  9152. iHiwtr = iCur = -1;
  9153. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
  9154. raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
  9155. iHiwtr = iCur = -1;
  9156. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  9157. raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
  9158. iCur);
  9159. iHiwtr = iCur = -1;
  9160. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  9161. raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
  9162. iCur);
  9163. }
  9164. if( pArg->pStmt ){
  9165. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  9166. bReset);
  9167. raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
  9168. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  9169. raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
  9170. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  9171. raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  9172. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  9173. raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
  9174. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
  9175. raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
  9176. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
  9177. raw_printf(pArg->out, "Number of times run: %d\n", iCur);
  9178. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
  9179. raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
  9180. }
  9181. #ifdef __linux__
  9182. displayLinuxIoStats(pArg->out);
  9183. #endif
  9184. /* Do not remove this machine readable comment: extra-stats-output-here */
  9185. return 0;
  9186. }
  9187. /*
  9188. ** Display scan stats.
  9189. */
  9190. static void display_scanstats(
  9191. sqlite3 *db, /* Database to query */
  9192. ShellState *pArg /* Pointer to ShellState */
  9193. ){
  9194. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  9195. UNUSED_PARAMETER(db);
  9196. UNUSED_PARAMETER(pArg);
  9197. #else
  9198. int i, k, n, mx;
  9199. raw_printf(pArg->out, "-------- scanstats --------\n");
  9200. mx = 0;
  9201. for(k=0; k<=mx; k++){
  9202. double rEstLoop = 1.0;
  9203. for(i=n=0; 1; i++){
  9204. sqlite3_stmt *p = pArg->pStmt;
  9205. sqlite3_int64 nLoop, nVisit;
  9206. double rEst;
  9207. int iSid;
  9208. const char *zExplain;
  9209. if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  9210. break;
  9211. }
  9212. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  9213. if( iSid>mx ) mx = iSid;
  9214. if( iSid!=k ) continue;
  9215. if( n==0 ){
  9216. rEstLoop = (double)nLoop;
  9217. if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  9218. }
  9219. n++;
  9220. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  9221. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  9222. sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  9223. utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  9224. rEstLoop *= rEst;
  9225. raw_printf(pArg->out,
  9226. " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  9227. nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  9228. );
  9229. }
  9230. }
  9231. raw_printf(pArg->out, "---------------------------\n");
  9232. #endif
  9233. }
  9234. /*
  9235. ** Parameter azArray points to a zero-terminated array of strings. zStr
  9236. ** points to a single nul-terminated string. Return non-zero if zStr
  9237. ** is equal, according to strcmp(), to any of the strings in the array.
  9238. ** Otherwise, return zero.
  9239. */
  9240. static int str_in_array(const char *zStr, const char **azArray){
  9241. int i;
  9242. for(i=0; azArray[i]; i++){
  9243. if( 0==strcmp(zStr, azArray[i]) ) return 1;
  9244. }
  9245. return 0;
  9246. }
  9247. /*
  9248. ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  9249. ** and populate the ShellState.aiIndent[] array with the number of
  9250. ** spaces each opcode should be indented before it is output.
  9251. **
  9252. ** The indenting rules are:
  9253. **
  9254. ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  9255. ** all opcodes that occur between the p2 jump destination and the opcode
  9256. ** itself by 2 spaces.
  9257. **
  9258. ** * For each "Goto", if the jump destination is earlier in the program
  9259. ** and ends on one of:
  9260. ** Yield SeekGt SeekLt RowSetRead Rewind
  9261. ** or if the P1 parameter is one instead of zero,
  9262. ** then indent all opcodes between the earlier instruction
  9263. ** and "Goto" by 2 spaces.
  9264. */
  9265. static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  9266. const char *zSql; /* The text of the SQL statement */
  9267. const char *z; /* Used to check if this is an EXPLAIN */
  9268. int *abYield = 0; /* True if op is an OP_Yield */
  9269. int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
  9270. int iOp; /* Index of operation in p->aiIndent[] */
  9271. const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
  9272. const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  9273. "Rewind", 0 };
  9274. const char *azGoto[] = { "Goto", 0 };
  9275. /* Try to figure out if this is really an EXPLAIN statement. If this
  9276. ** cannot be verified, return early. */
  9277. if( sqlite3_column_count(pSql)!=8 ){
  9278. p->cMode = p->mode;
  9279. return;
  9280. }
  9281. zSql = sqlite3_sql(pSql);
  9282. if( zSql==0 ) return;
  9283. for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  9284. if( sqlite3_strnicmp(z, "explain", 7) ){
  9285. p->cMode = p->mode;
  9286. return;
  9287. }
  9288. for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  9289. int i;
  9290. int iAddr = sqlite3_column_int(pSql, 0);
  9291. const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  9292. /* Set p2 to the P2 field of the current opcode. Then, assuming that
  9293. ** p2 is an instruction address, set variable p2op to the index of that
  9294. ** instruction in the aiIndent[] array. p2 and p2op may be different if
  9295. ** the current instruction is part of a sub-program generated by an
  9296. ** SQL trigger or foreign key. */
  9297. int p2 = sqlite3_column_int(pSql, 3);
  9298. int p2op = (p2 + (iOp-iAddr));
  9299. /* Grow the p->aiIndent array as required */
  9300. if( iOp>=nAlloc ){
  9301. if( iOp==0 ){
  9302. /* Do further verfication that this is explain output. Abort if
  9303. ** it is not */
  9304. static const char *explainCols[] = {
  9305. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  9306. int jj;
  9307. for(jj=0; jj<ArraySize(explainCols); jj++){
  9308. if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  9309. p->cMode = p->mode;
  9310. sqlite3_reset(pSql);
  9311. return;
  9312. }
  9313. }
  9314. }
  9315. nAlloc += 100;
  9316. p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  9317. if( p->aiIndent==0 ) shell_out_of_memory();
  9318. abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  9319. if( abYield==0 ) shell_out_of_memory();
  9320. }
  9321. abYield[iOp] = str_in_array(zOp, azYield);
  9322. p->aiIndent[iOp] = 0;
  9323. p->nIndent = iOp+1;
  9324. if( str_in_array(zOp, azNext) ){
  9325. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  9326. }
  9327. if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  9328. && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  9329. ){
  9330. for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  9331. }
  9332. }
  9333. p->iIndent = 0;
  9334. sqlite3_free(abYield);
  9335. sqlite3_reset(pSql);
  9336. }
  9337. /*
  9338. ** Free the array allocated by explain_data_prepare().
  9339. */
  9340. static void explain_data_delete(ShellState *p){
  9341. sqlite3_free(p->aiIndent);
  9342. p->aiIndent = 0;
  9343. p->nIndent = 0;
  9344. p->iIndent = 0;
  9345. }
  9346. /*
  9347. ** Disable and restore .wheretrace and .selecttrace settings.
  9348. */
  9349. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  9350. extern int sqlite3SelectTrace;
  9351. static int savedSelectTrace;
  9352. #endif
  9353. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  9354. extern int sqlite3WhereTrace;
  9355. static int savedWhereTrace;
  9356. #endif
  9357. static void disable_debug_trace_modes(void){
  9358. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  9359. savedSelectTrace = sqlite3SelectTrace;
  9360. sqlite3SelectTrace = 0;
  9361. #endif
  9362. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  9363. savedWhereTrace = sqlite3WhereTrace;
  9364. sqlite3WhereTrace = 0;
  9365. #endif
  9366. }
  9367. static void restore_debug_trace_modes(void){
  9368. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  9369. sqlite3SelectTrace = savedSelectTrace;
  9370. #endif
  9371. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  9372. sqlite3WhereTrace = savedWhereTrace;
  9373. #endif
  9374. }
  9375. /*
  9376. ** Run a prepared statement
  9377. */
  9378. static void exec_prepared_stmt(
  9379. ShellState *pArg, /* Pointer to ShellState */
  9380. sqlite3_stmt *pStmt /* Statment to run */
  9381. ){
  9382. int rc;
  9383. /* perform the first step. this will tell us if we
  9384. ** have a result set or not and how wide it is.
  9385. */
  9386. rc = sqlite3_step(pStmt);
  9387. /* if we have a result set... */
  9388. if( SQLITE_ROW == rc ){
  9389. /* allocate space for col name ptr, value ptr, and type */
  9390. int nCol = sqlite3_column_count(pStmt);
  9391. void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
  9392. if( !pData ){
  9393. rc = SQLITE_NOMEM;
  9394. }else{
  9395. char **azCols = (char **)pData; /* Names of result columns */
  9396. char **azVals = &azCols[nCol]; /* Results */
  9397. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  9398. int i, x;
  9399. assert(sizeof(int) <= sizeof(char *));
  9400. /* save off ptrs to column names */
  9401. for(i=0; i<nCol; i++){
  9402. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  9403. }
  9404. do{
  9405. /* extract the data and data types */
  9406. for(i=0; i<nCol; i++){
  9407. aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  9408. if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  9409. azVals[i] = "";
  9410. }else{
  9411. azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  9412. }
  9413. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  9414. rc = SQLITE_NOMEM;
  9415. break; /* from for */
  9416. }
  9417. } /* end for */
  9418. /* if data and types extracted successfully... */
  9419. if( SQLITE_ROW == rc ){
  9420. /* call the supplied callback with the result row data */
  9421. if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
  9422. rc = SQLITE_ABORT;
  9423. }else{
  9424. rc = sqlite3_step(pStmt);
  9425. }
  9426. }
  9427. } while( SQLITE_ROW == rc );
  9428. sqlite3_free(pData);
  9429. }
  9430. }
  9431. }
  9432. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9433. /*
  9434. ** This function is called to process SQL if the previous shell command
  9435. ** was ".expert". It passes the SQL in the second argument directly to
  9436. ** the sqlite3expert object.
  9437. **
  9438. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  9439. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  9440. ** an English language error message. It is the responsibility of the
  9441. ** caller to eventually free this buffer using sqlite3_free().
  9442. */
  9443. static int expertHandleSQL(
  9444. ShellState *pState,
  9445. const char *zSql,
  9446. char **pzErr
  9447. ){
  9448. assert( pState->expert.pExpert );
  9449. assert( pzErr==0 || *pzErr==0 );
  9450. return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
  9451. }
  9452. /*
  9453. ** This function is called either to silently clean up the object
  9454. ** created by the ".expert" command (if bCancel==1), or to generate a
  9455. ** report from it and then clean it up (if bCancel==0).
  9456. **
  9457. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
  9458. ** code. In this case, (*pzErr) may be set to point to a buffer containing
  9459. ** an English language error message. It is the responsibility of the
  9460. ** caller to eventually free this buffer using sqlite3_free().
  9461. */
  9462. static int expertFinish(
  9463. ShellState *pState,
  9464. int bCancel,
  9465. char **pzErr
  9466. ){
  9467. int rc = SQLITE_OK;
  9468. sqlite3expert *p = pState->expert.pExpert;
  9469. assert( p );
  9470. assert( bCancel || pzErr==0 || *pzErr==0 );
  9471. if( bCancel==0 ){
  9472. FILE *out = pState->out;
  9473. int bVerbose = pState->expert.bVerbose;
  9474. rc = sqlite3_expert_analyze(p, pzErr);
  9475. if( rc==SQLITE_OK ){
  9476. int nQuery = sqlite3_expert_count(p);
  9477. int i;
  9478. if( bVerbose ){
  9479. const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
  9480. raw_printf(out, "-- Candidates -----------------------------\n");
  9481. raw_printf(out, "%s\n", zCand);
  9482. }
  9483. for(i=0; i<nQuery; i++){
  9484. const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
  9485. const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
  9486. const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
  9487. if( zIdx==0 ) zIdx = "(no new indexes)\n";
  9488. if( bVerbose ){
  9489. raw_printf(out, "-- Query %d --------------------------------\n",i+1);
  9490. raw_printf(out, "%s\n\n", zSql);
  9491. }
  9492. raw_printf(out, "%s\n", zIdx);
  9493. raw_printf(out, "%s\n", zEQP);
  9494. }
  9495. }
  9496. }
  9497. sqlite3_expert_destroy(p);
  9498. pState->expert.pExpert = 0;
  9499. return rc;
  9500. }
  9501. /*
  9502. ** Implementation of ".expert" dot command.
  9503. */
  9504. static int expertDotCommand(
  9505. ShellState *pState, /* Current shell tool state */
  9506. char **azArg, /* Array of arguments passed to dot command */
  9507. int nArg /* Number of entries in azArg[] */
  9508. ){
  9509. int rc = SQLITE_OK;
  9510. char *zErr = 0;
  9511. int i;
  9512. int iSample = 0;
  9513. assert( pState->expert.pExpert==0 );
  9514. memset(&pState->expert, 0, sizeof(ExpertInfo));
  9515. for(i=1; rc==SQLITE_OK && i<nArg; i++){
  9516. char *z = azArg[i];
  9517. int n;
  9518. if( z[0]=='-' && z[1]=='-' ) z++;
  9519. n = strlen30(z);
  9520. if( n>=2 && 0==strncmp(z, "-verbose", n) ){
  9521. pState->expert.bVerbose = 1;
  9522. }
  9523. else if( n>=2 && 0==strncmp(z, "-sample", n) ){
  9524. if( i==(nArg-1) ){
  9525. raw_printf(stderr, "option requires an argument: %s\n", z);
  9526. rc = SQLITE_ERROR;
  9527. }else{
  9528. iSample = (int)integerValue(azArg[++i]);
  9529. if( iSample<0 || iSample>100 ){
  9530. raw_printf(stderr, "value out of range: %s\n", azArg[i]);
  9531. rc = SQLITE_ERROR;
  9532. }
  9533. }
  9534. }
  9535. else{
  9536. raw_printf(stderr, "unknown option: %s\n", z);
  9537. rc = SQLITE_ERROR;
  9538. }
  9539. }
  9540. if( rc==SQLITE_OK ){
  9541. pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
  9542. if( pState->expert.pExpert==0 ){
  9543. raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
  9544. rc = SQLITE_ERROR;
  9545. }else{
  9546. sqlite3_expert_config(
  9547. pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
  9548. );
  9549. }
  9550. }
  9551. return rc;
  9552. }
  9553. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  9554. /*
  9555. ** Execute a statement or set of statements. Print
  9556. ** any result rows/columns depending on the current mode
  9557. ** set via the supplied callback.
  9558. **
  9559. ** This is very similar to SQLite's built-in sqlite3_exec()
  9560. ** function except it takes a slightly different callback
  9561. ** and callback data argument.
  9562. */
  9563. static int shell_exec(
  9564. ShellState *pArg, /* Pointer to ShellState */
  9565. const char *zSql, /* SQL to be evaluated */
  9566. char **pzErrMsg /* Error msg written here */
  9567. ){
  9568. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  9569. int rc = SQLITE_OK; /* Return Code */
  9570. int rc2;
  9571. const char *zLeftover; /* Tail of unprocessed SQL */
  9572. sqlite3 *db = pArg->db;
  9573. if( pzErrMsg ){
  9574. *pzErrMsg = NULL;
  9575. }
  9576. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9577. if( pArg->expert.pExpert ){
  9578. rc = expertHandleSQL(pArg, zSql, pzErrMsg);
  9579. return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
  9580. }
  9581. #endif
  9582. while( zSql[0] && (SQLITE_OK == rc) ){
  9583. static const char *zStmtSql;
  9584. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  9585. if( SQLITE_OK != rc ){
  9586. if( pzErrMsg ){
  9587. *pzErrMsg = save_err_msg(db);
  9588. }
  9589. }else{
  9590. if( !pStmt ){
  9591. /* this happens for a comment or white-space */
  9592. zSql = zLeftover;
  9593. while( IsSpace(zSql[0]) ) zSql++;
  9594. continue;
  9595. }
  9596. zStmtSql = sqlite3_sql(pStmt);
  9597. if( zStmtSql==0 ) zStmtSql = "";
  9598. while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  9599. /* save off the prepared statment handle and reset row count */
  9600. if( pArg ){
  9601. pArg->pStmt = pStmt;
  9602. pArg->cnt = 0;
  9603. }
  9604. /* echo the sql statement if echo on */
  9605. if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
  9606. utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  9607. }
  9608. /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  9609. if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
  9610. sqlite3_stmt *pExplain;
  9611. char *zEQP;
  9612. int triggerEQP = 0;
  9613. disable_debug_trace_modes();
  9614. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
  9615. if( pArg->autoEQP>=AUTOEQP_trigger ){
  9616. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
  9617. }
  9618. zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  9619. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  9620. if( rc==SQLITE_OK ){
  9621. while( sqlite3_step(pExplain)==SQLITE_ROW ){
  9622. const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
  9623. int iEqpId = sqlite3_column_int(pExplain, 0);
  9624. int iParentId = sqlite3_column_int(pExplain, 1);
  9625. if( zEQPLine[0]=='-' ) eqp_render(pArg);
  9626. eqp_append(pArg, iEqpId, iParentId, zEQPLine);
  9627. }
  9628. eqp_render(pArg);
  9629. }
  9630. sqlite3_finalize(pExplain);
  9631. sqlite3_free(zEQP);
  9632. if( pArg->autoEQP>=AUTOEQP_full ){
  9633. /* Also do an EXPLAIN for ".eqp full" mode */
  9634. zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  9635. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  9636. if( rc==SQLITE_OK ){
  9637. pArg->cMode = MODE_Explain;
  9638. explain_data_prepare(pArg, pExplain);
  9639. exec_prepared_stmt(pArg, pExplain);
  9640. explain_data_delete(pArg);
  9641. }
  9642. sqlite3_finalize(pExplain);
  9643. sqlite3_free(zEQP);
  9644. }
  9645. if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
  9646. sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
  9647. /* Reprepare pStmt before reactiving trace modes */
  9648. sqlite3_finalize(pStmt);
  9649. sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  9650. if( pArg ) pArg->pStmt = pStmt;
  9651. }
  9652. restore_debug_trace_modes();
  9653. }
  9654. if( pArg ){
  9655. pArg->cMode = pArg->mode;
  9656. if( pArg->autoExplain ){
  9657. if( sqlite3_column_count(pStmt)==8
  9658. && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
  9659. ){
  9660. pArg->cMode = MODE_Explain;
  9661. }
  9662. if( sqlite3_column_count(pStmt)==4
  9663. && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
  9664. pArg->cMode = MODE_EQP;
  9665. }
  9666. }
  9667. /* If the shell is currently in ".explain" mode, gather the extra
  9668. ** data required to add indents to the output.*/
  9669. if( pArg->cMode==MODE_Explain ){
  9670. explain_data_prepare(pArg, pStmt);
  9671. }
  9672. }
  9673. exec_prepared_stmt(pArg, pStmt);
  9674. explain_data_delete(pArg);
  9675. eqp_render(pArg);
  9676. /* print usage stats if stats on */
  9677. if( pArg && pArg->statsOn ){
  9678. display_stats(db, pArg, 0);
  9679. }
  9680. /* print loop-counters if required */
  9681. if( pArg && pArg->scanstatsOn ){
  9682. display_scanstats(db, pArg);
  9683. }
  9684. /* Finalize the statement just executed. If this fails, save a
  9685. ** copy of the error message. Otherwise, set zSql to point to the
  9686. ** next statement to execute. */
  9687. rc2 = sqlite3_finalize(pStmt);
  9688. if( rc!=SQLITE_NOMEM ) rc = rc2;
  9689. if( rc==SQLITE_OK ){
  9690. zSql = zLeftover;
  9691. while( IsSpace(zSql[0]) ) zSql++;
  9692. }else if( pzErrMsg ){
  9693. *pzErrMsg = save_err_msg(db);
  9694. }
  9695. /* clear saved stmt handle */
  9696. if( pArg ){
  9697. pArg->pStmt = NULL;
  9698. }
  9699. }
  9700. } /* end while */
  9701. return rc;
  9702. }
  9703. /*
  9704. ** Release memory previously allocated by tableColumnList().
  9705. */
  9706. static void freeColumnList(char **azCol){
  9707. int i;
  9708. for(i=1; azCol[i]; i++){
  9709. sqlite3_free(azCol[i]);
  9710. }
  9711. /* azCol[0] is a static string */
  9712. sqlite3_free(azCol);
  9713. }
  9714. /*
  9715. ** Return a list of pointers to strings which are the names of all
  9716. ** columns in table zTab. The memory to hold the names is dynamically
  9717. ** allocated and must be released by the caller using a subsequent call
  9718. ** to freeColumnList().
  9719. **
  9720. ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
  9721. ** value that needs to be preserved, then azCol[0] is filled in with the
  9722. ** name of the rowid column.
  9723. **
  9724. ** The first regular column in the table is azCol[1]. The list is terminated
  9725. ** by an entry with azCol[i]==0.
  9726. */
  9727. static char **tableColumnList(ShellState *p, const char *zTab){
  9728. char **azCol = 0;
  9729. sqlite3_stmt *pStmt;
  9730. char *zSql;
  9731. int nCol = 0;
  9732. int nAlloc = 0;
  9733. int nPK = 0; /* Number of PRIMARY KEY columns seen */
  9734. int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
  9735. int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  9736. int rc;
  9737. zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
  9738. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  9739. sqlite3_free(zSql);
  9740. if( rc ) return 0;
  9741. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  9742. if( nCol>=nAlloc-2 ){
  9743. nAlloc = nAlloc*2 + nCol + 10;
  9744. azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
  9745. if( azCol==0 ) shell_out_of_memory();
  9746. }
  9747. azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
  9748. if( sqlite3_column_int(pStmt, 5) ){
  9749. nPK++;
  9750. if( nPK==1
  9751. && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
  9752. "INTEGER")==0
  9753. ){
  9754. isIPK = 1;
  9755. }else{
  9756. isIPK = 0;
  9757. }
  9758. }
  9759. }
  9760. sqlite3_finalize(pStmt);
  9761. if( azCol==0 ) return 0;
  9762. azCol[0] = 0;
  9763. azCol[nCol+1] = 0;
  9764. /* The decision of whether or not a rowid really needs to be preserved
  9765. ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
  9766. ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
  9767. ** rowids on tables where the rowid is inaccessible because there are other
  9768. ** columns in the table named "rowid", "_rowid_", and "oid".
  9769. */
  9770. if( preserveRowid && isIPK ){
  9771. /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  9772. ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
  9773. ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  9774. ** ROWID aliases. To distinguish these cases, check to see if
  9775. ** there is a "pk" entry in "PRAGMA index_list". There will be
  9776. ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  9777. */
  9778. zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  9779. " WHERE origin='pk'", zTab);
  9780. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  9781. sqlite3_free(zSql);
  9782. if( rc ){
  9783. freeColumnList(azCol);
  9784. return 0;
  9785. }
  9786. rc = sqlite3_step(pStmt);
  9787. sqlite3_finalize(pStmt);
  9788. preserveRowid = rc==SQLITE_ROW;
  9789. }
  9790. if( preserveRowid ){
  9791. /* Only preserve the rowid if we can find a name to use for the
  9792. ** rowid */
  9793. static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  9794. int i, j;
  9795. for(j=0; j<3; j++){
  9796. for(i=1; i<=nCol; i++){
  9797. if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  9798. }
  9799. if( i>nCol ){
  9800. /* At this point, we know that azRowid[j] is not the name of any
  9801. ** ordinary column in the table. Verify that azRowid[j] is a valid
  9802. ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
  9803. ** tables will fail this last check */
  9804. rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  9805. if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  9806. break;
  9807. }
  9808. }
  9809. }
  9810. return azCol;
  9811. }
  9812. /*
  9813. ** Toggle the reverse_unordered_selects setting.
  9814. */
  9815. static void toggleSelectOrder(sqlite3 *db){
  9816. sqlite3_stmt *pStmt = 0;
  9817. int iSetting = 0;
  9818. char zStmt[100];
  9819. sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  9820. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  9821. iSetting = sqlite3_column_int(pStmt, 0);
  9822. }
  9823. sqlite3_finalize(pStmt);
  9824. sqlite3_snprintf(sizeof(zStmt), zStmt,
  9825. "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  9826. sqlite3_exec(db, zStmt, 0, 0, 0);
  9827. }
  9828. /*
  9829. ** This is a different callback routine used for dumping the database.
  9830. ** Each row received by this callback consists of a table name,
  9831. ** the table type ("index" or "table") and SQL to create the table.
  9832. ** This routine should print text sufficient to recreate the table.
  9833. */
  9834. static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  9835. int rc;
  9836. const char *zTable;
  9837. const char *zType;
  9838. const char *zSql;
  9839. ShellState *p = (ShellState *)pArg;
  9840. UNUSED_PARAMETER(azNotUsed);
  9841. if( nArg!=3 || azArg==0 ) return 0;
  9842. zTable = azArg[0];
  9843. zType = azArg[1];
  9844. zSql = azArg[2];
  9845. if( strcmp(zTable, "sqlite_sequence")==0 ){
  9846. raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  9847. }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  9848. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  9849. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  9850. return 0;
  9851. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  9852. char *zIns;
  9853. if( !p->writableSchema ){
  9854. raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  9855. p->writableSchema = 1;
  9856. }
  9857. zIns = sqlite3_mprintf(
  9858. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  9859. "VALUES('table','%q','%q',0,'%q');",
  9860. zTable, zTable, zSql);
  9861. utf8_printf(p->out, "%s\n", zIns);
  9862. sqlite3_free(zIns);
  9863. return 0;
  9864. }else{
  9865. printSchemaLine(p->out, zSql, ";\n");
  9866. }
  9867. if( strcmp(zType, "table")==0 ){
  9868. ShellText sSelect;
  9869. ShellText sTable;
  9870. char **azCol;
  9871. int i;
  9872. char *savedDestTable;
  9873. int savedMode;
  9874. azCol = tableColumnList(p, zTable);
  9875. if( azCol==0 ){
  9876. p->nErr++;
  9877. return 0;
  9878. }
  9879. /* Always quote the table name, even if it appears to be pure ascii,
  9880. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  9881. initText(&sTable);
  9882. appendText(&sTable, zTable, quoteChar(zTable));
  9883. /* If preserving the rowid, add a column list after the table name.
  9884. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  9885. ** instead of the usual "INSERT INTO tab VALUES(...)".
  9886. */
  9887. if( azCol[0] ){
  9888. appendText(&sTable, "(", 0);
  9889. appendText(&sTable, azCol[0], 0);
  9890. for(i=1; azCol[i]; i++){
  9891. appendText(&sTable, ",", 0);
  9892. appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  9893. }
  9894. appendText(&sTable, ")", 0);
  9895. }
  9896. /* Build an appropriate SELECT statement */
  9897. initText(&sSelect);
  9898. appendText(&sSelect, "SELECT ", 0);
  9899. if( azCol[0] ){
  9900. appendText(&sSelect, azCol[0], 0);
  9901. appendText(&sSelect, ",", 0);
  9902. }
  9903. for(i=1; azCol[i]; i++){
  9904. appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  9905. if( azCol[i+1] ){
  9906. appendText(&sSelect, ",", 0);
  9907. }
  9908. }
  9909. freeColumnList(azCol);
  9910. appendText(&sSelect, " FROM ", 0);
  9911. appendText(&sSelect, zTable, quoteChar(zTable));
  9912. savedDestTable = p->zDestTable;
  9913. savedMode = p->mode;
  9914. p->zDestTable = sTable.z;
  9915. p->mode = p->cMode = MODE_Insert;
  9916. rc = shell_exec(p, sSelect.z, 0);
  9917. if( (rc&0xff)==SQLITE_CORRUPT ){
  9918. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  9919. toggleSelectOrder(p->db);
  9920. shell_exec(p, sSelect.z, 0);
  9921. toggleSelectOrder(p->db);
  9922. }
  9923. p->zDestTable = savedDestTable;
  9924. p->mode = savedMode;
  9925. freeText(&sTable);
  9926. freeText(&sSelect);
  9927. if( rc ) p->nErr++;
  9928. }
  9929. return 0;
  9930. }
  9931. /*
  9932. ** Run zQuery. Use dump_callback() as the callback routine so that
  9933. ** the contents of the query are output as SQL statements.
  9934. **
  9935. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  9936. ** "ORDER BY rowid DESC" to the end.
  9937. */
  9938. static int run_schema_dump_query(
  9939. ShellState *p,
  9940. const char *zQuery
  9941. ){
  9942. int rc;
  9943. char *zErr = 0;
  9944. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  9945. if( rc==SQLITE_CORRUPT ){
  9946. char *zQ2;
  9947. int len = strlen30(zQuery);
  9948. raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  9949. if( zErr ){
  9950. utf8_printf(p->out, "/****** %s ******/\n", zErr);
  9951. sqlite3_free(zErr);
  9952. zErr = 0;
  9953. }
  9954. zQ2 = malloc( len+100 );
  9955. if( zQ2==0 ) return rc;
  9956. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  9957. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  9958. if( rc ){
  9959. utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  9960. }else{
  9961. rc = SQLITE_CORRUPT;
  9962. }
  9963. sqlite3_free(zErr);
  9964. free(zQ2);
  9965. }
  9966. return rc;
  9967. }
  9968. /*
  9969. ** Text of a help message
  9970. */
  9971. static char zHelp[] =
  9972. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  9973. ".archive ... Manage SQL archives: \".archive --help\" for details\n"
  9974. #endif
  9975. #ifndef SQLITE_OMIT_AUTHORIZATION
  9976. ".auth ON|OFF Show authorizer callbacks\n"
  9977. #endif
  9978. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  9979. " Add \"--append\" to open using appendvfs.\n"
  9980. ".bail on|off Stop after hitting an error. Default OFF\n"
  9981. ".binary on|off Turn binary output on or off. Default OFF\n"
  9982. ".cd DIRECTORY Change the working directory to DIRECTORY\n"
  9983. ".changes on|off Show number of rows changed by SQL\n"
  9984. ".check GLOB Fail if output since .testcase does not match\n"
  9985. ".clone NEWDB Clone data into NEWDB from the existing database\n"
  9986. ".databases List names and files of attached databases\n"
  9987. ".dbconfig ?op? ?val? List or change sqlite3_db_config() options\n"
  9988. ".dbinfo ?DB? Show status information about the database\n"
  9989. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  9990. " If TABLE specified, only dump tables matching\n"
  9991. " LIKE pattern TABLE.\n"
  9992. ".echo on|off Turn command echo on or off\n"
  9993. ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
  9994. ".excel Display the output of next command in a spreadsheet\n"
  9995. ".exit Exit this program\n"
  9996. ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
  9997. /* Because explain mode comes on automatically now, the ".explain" mode
  9998. ** is removed from the help screen. It is still supported for legacy, however */
  9999. /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
  10000. ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
  10001. ".headers on|off Turn display of headers on or off\n"
  10002. ".help Show this message\n"
  10003. ".import FILE TABLE Import data from FILE into TABLE\n"
  10004. #ifndef SQLITE_OMIT_TEST_CONTROL
  10005. ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
  10006. #endif
  10007. ".indexes ?TABLE? Show names of all indexes\n"
  10008. " If TABLE specified, only show indexes for tables\n"
  10009. " matching LIKE pattern TABLE.\n"
  10010. #ifdef SQLITE_ENABLE_IOTRACE
  10011. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  10012. #endif
  10013. ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
  10014. ".lint OPTIONS Report potential schema issues. Options:\n"
  10015. " fkey-indexes Find missing foreign key indexes\n"
  10016. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10017. ".load FILE ?ENTRY? Load an extension library\n"
  10018. #endif
  10019. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  10020. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  10021. " ascii Columns/rows delimited by 0x1F and 0x1E\n"
  10022. " csv Comma-separated values\n"
  10023. " column Left-aligned columns. (See .width)\n"
  10024. " html HTML <table> code\n"
  10025. " insert SQL insert statements for TABLE\n"
  10026. " line One value per line\n"
  10027. " list Values delimited by \"|\"\n"
  10028. " quote Escape answers as for SQL\n"
  10029. " tabs Tab-separated values\n"
  10030. " tcl TCL list elements\n"
  10031. ".nullvalue STRING Use STRING in place of NULL values\n"
  10032. ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
  10033. " or invoke system text editor (-e) or spreadsheet (-x)\n"
  10034. " on the output.\n"
  10035. ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
  10036. " The --new option starts with an empty file\n"
  10037. " Other options: --readonly --append --zip\n"
  10038. ".output ?FILE? Send output to FILE or stdout\n"
  10039. ".print STRING... Print literal STRING\n"
  10040. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  10041. ".quit Exit this program\n"
  10042. ".read FILENAME Execute SQL in FILENAME\n"
  10043. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  10044. ".save FILE Write in-memory database into FILE\n"
  10045. ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
  10046. ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
  10047. " Add --indent for pretty-printing\n"
  10048. ".selftest ?--init? Run tests defined in the SELFTEST table\n"
  10049. ".separator COL ?ROW? Change the column separator and optionally the row\n"
  10050. " separator for both the output mode and .import\n"
  10051. #if defined(SQLITE_ENABLE_SESSION)
  10052. ".session CMD ... Create or control sessions\n"
  10053. #endif
  10054. ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
  10055. #ifndef SQLITE_NOHAVE_SYSTEM
  10056. ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
  10057. #endif
  10058. ".show Show the current values for various settings\n"
  10059. ".stats ?on|off? Show stats or turn stats on or off\n"
  10060. #ifndef SQLITE_NOHAVE_SYSTEM
  10061. ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
  10062. #endif
  10063. ".tables ?TABLE? List names of tables\n"
  10064. " If TABLE specified, only list tables matching\n"
  10065. " LIKE pattern TABLE.\n"
  10066. ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
  10067. ".timeout MS Try opening locked tables for MS milliseconds\n"
  10068. ".timer on|off Turn SQL timer on or off\n"
  10069. ".trace FILE|off Output each SQL statement as it is run\n"
  10070. ".vfsinfo ?AUX? Information about the top-level VFS\n"
  10071. ".vfslist List all available VFSes\n"
  10072. ".vfsname ?AUX? Print the name of the VFS stack\n"
  10073. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  10074. " Negative values right-justify\n"
  10075. ;
  10076. #if defined(SQLITE_ENABLE_SESSION)
  10077. /*
  10078. ** Print help information for the ".sessions" command
  10079. */
  10080. void session_help(ShellState *p){
  10081. raw_printf(p->out,
  10082. ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
  10083. "If ?NAME? is omitted, the first defined session is used.\n"
  10084. "Subcommands:\n"
  10085. " attach TABLE Attach TABLE\n"
  10086. " changeset FILE Write a changeset into FILE\n"
  10087. " close Close one session\n"
  10088. " enable ?BOOLEAN? Set or query the enable bit\n"
  10089. " filter GLOB... Reject tables matching GLOBs\n"
  10090. " indirect ?BOOLEAN? Mark or query the indirect status\n"
  10091. " isempty Query whether the session is empty\n"
  10092. " list List currently open session names\n"
  10093. " open DB NAME Open a new session on DB\n"
  10094. " patchset FILE Write a patchset into FILE\n"
  10095. );
  10096. }
  10097. #endif
  10098. /* Forward reference */
  10099. static int process_input(ShellState *p, FILE *in);
  10100. /*
  10101. ** Read the content of file zName into memory obtained from sqlite3_malloc64()
  10102. ** and return a pointer to the buffer. The caller is responsible for freeing
  10103. ** the memory.
  10104. **
  10105. ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  10106. ** read.
  10107. **
  10108. ** For convenience, a nul-terminator byte is always appended to the data read
  10109. ** from the file before the buffer is returned. This byte is not included in
  10110. ** the final value of (*pnByte), if applicable.
  10111. **
  10112. ** NULL is returned if any error is encountered. The final value of *pnByte
  10113. ** is undefined in this case.
  10114. */
  10115. static char *readFile(const char *zName, int *pnByte){
  10116. FILE *in = fopen(zName, "rb");
  10117. long nIn;
  10118. size_t nRead;
  10119. char *pBuf;
  10120. if( in==0 ) return 0;
  10121. fseek(in, 0, SEEK_END);
  10122. nIn = ftell(in);
  10123. rewind(in);
  10124. pBuf = sqlite3_malloc64( nIn+1 );
  10125. if( pBuf==0 ) return 0;
  10126. nRead = fread(pBuf, nIn, 1, in);
  10127. fclose(in);
  10128. if( nRead!=1 ){
  10129. sqlite3_free(pBuf);
  10130. return 0;
  10131. }
  10132. pBuf[nIn] = 0;
  10133. if( pnByte ) *pnByte = nIn;
  10134. return pBuf;
  10135. }
  10136. #if defined(SQLITE_ENABLE_SESSION)
  10137. /*
  10138. ** Close a single OpenSession object and release all of its associated
  10139. ** resources.
  10140. */
  10141. static void session_close(OpenSession *pSession){
  10142. int i;
  10143. sqlite3session_delete(pSession->p);
  10144. sqlite3_free(pSession->zName);
  10145. for(i=0; i<pSession->nFilter; i++){
  10146. sqlite3_free(pSession->azFilter[i]);
  10147. }
  10148. sqlite3_free(pSession->azFilter);
  10149. memset(pSession, 0, sizeof(OpenSession));
  10150. }
  10151. #endif
  10152. /*
  10153. ** Close all OpenSession objects and release all associated resources.
  10154. */
  10155. #if defined(SQLITE_ENABLE_SESSION)
  10156. static void session_close_all(ShellState *p){
  10157. int i;
  10158. for(i=0; i<p->nSession; i++){
  10159. session_close(&p->aSession[i]);
  10160. }
  10161. p->nSession = 0;
  10162. }
  10163. #else
  10164. # define session_close_all(X)
  10165. #endif
  10166. /*
  10167. ** Implementation of the xFilter function for an open session. Omit
  10168. ** any tables named by ".session filter" but let all other table through.
  10169. */
  10170. #if defined(SQLITE_ENABLE_SESSION)
  10171. static int session_filter(void *pCtx, const char *zTab){
  10172. OpenSession *pSession = (OpenSession*)pCtx;
  10173. int i;
  10174. for(i=0; i<pSession->nFilter; i++){
  10175. if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  10176. }
  10177. return 1;
  10178. }
  10179. #endif
  10180. /*
  10181. ** Try to deduce the type of file for zName based on its content. Return
  10182. ** one of the SHELL_OPEN_* constants.
  10183. **
  10184. ** If the file does not exist or is empty but its name looks like a ZIP
  10185. ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
  10186. ** Otherwise, assume an ordinary database regardless of the filename if
  10187. ** the type cannot be determined from content.
  10188. */
  10189. int deduceDatabaseType(const char *zName, int dfltZip){
  10190. FILE *f = fopen(zName, "rb");
  10191. size_t n;
  10192. int rc = SHELL_OPEN_UNSPEC;
  10193. char zBuf[100];
  10194. if( f==0 ){
  10195. if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  10196. return SHELL_OPEN_ZIPFILE;
  10197. }else{
  10198. return SHELL_OPEN_NORMAL;
  10199. }
  10200. }
  10201. fseek(f, -25, SEEK_END);
  10202. n = fread(zBuf, 25, 1, f);
  10203. if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
  10204. rc = SHELL_OPEN_APPENDVFS;
  10205. }else{
  10206. fseek(f, -22, SEEK_END);
  10207. n = fread(zBuf, 22, 1, f);
  10208. if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
  10209. && zBuf[3]==0x06 ){
  10210. rc = SHELL_OPEN_ZIPFILE;
  10211. }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
  10212. rc = SHELL_OPEN_ZIPFILE;
  10213. }
  10214. }
  10215. fclose(f);
  10216. return rc;
  10217. }
  10218. /* Flags for open_db().
  10219. **
  10220. ** The default behavior of open_db() is to exit(1) if the database fails to
  10221. ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
  10222. ** but still returns without calling exit.
  10223. **
  10224. ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
  10225. ** ZIP archive if the file does not exist or is empty and its name matches
  10226. ** the *.zip pattern.
  10227. */
  10228. #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
  10229. #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
  10230. /*
  10231. ** Make sure the database is open. If it is not, then open it. If
  10232. ** the database fails to open, print an error message and exit.
  10233. */
  10234. static void open_db(ShellState *p, int openFlags){
  10235. if( p->db==0 ){
  10236. if( p->openMode==SHELL_OPEN_UNSPEC ){
  10237. if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
  10238. p->openMode = SHELL_OPEN_NORMAL;
  10239. }else{
  10240. p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
  10241. (openFlags & OPEN_DB_ZIPFILE)!=0);
  10242. }
  10243. }
  10244. switch( p->openMode ){
  10245. case SHELL_OPEN_APPENDVFS: {
  10246. sqlite3_open_v2(p->zDbFilename, &p->db,
  10247. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
  10248. break;
  10249. }
  10250. case SHELL_OPEN_ZIPFILE: {
  10251. sqlite3_open(":memory:", &p->db);
  10252. break;
  10253. }
  10254. case SHELL_OPEN_READONLY: {
  10255. sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
  10256. break;
  10257. }
  10258. case SHELL_OPEN_UNSPEC:
  10259. case SHELL_OPEN_NORMAL: {
  10260. sqlite3_open(p->zDbFilename, &p->db);
  10261. break;
  10262. }
  10263. }
  10264. globalDb = p->db;
  10265. if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  10266. utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  10267. p->zDbFilename, sqlite3_errmsg(p->db));
  10268. if( openFlags & OPEN_DB_KEEPALIVE ) return;
  10269. exit(1);
  10270. }
  10271. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10272. sqlite3_enable_load_extension(p->db, 1);
  10273. #endif
  10274. sqlite3_fileio_init(p->db, 0, 0);
  10275. sqlite3_shathree_init(p->db, 0, 0);
  10276. sqlite3_completion_init(p->db, 0, 0);
  10277. #ifdef SQLITE_HAVE_ZLIB
  10278. sqlite3_zipfile_init(p->db, 0, 0);
  10279. sqlite3_sqlar_init(p->db, 0, 0);
  10280. #endif
  10281. sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
  10282. shellAddSchemaName, 0, 0);
  10283. sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
  10284. shellModuleSchema, 0, 0);
  10285. sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
  10286. shellPutsFunc, 0, 0);
  10287. #ifndef SQLITE_NOHAVE_SYSTEM
  10288. sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
  10289. editFunc, 0, 0);
  10290. sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
  10291. editFunc, 0, 0);
  10292. #endif
  10293. if( p->openMode==SHELL_OPEN_ZIPFILE ){
  10294. char *zSql = sqlite3_mprintf(
  10295. "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
  10296. sqlite3_exec(p->db, zSql, 0, 0, 0);
  10297. sqlite3_free(zSql);
  10298. }
  10299. }
  10300. }
  10301. /*
  10302. ** Attempt to close the databaes connection. Report errors.
  10303. */
  10304. void close_db(sqlite3 *db){
  10305. int rc = sqlite3_close(db);
  10306. if( rc ){
  10307. utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
  10308. rc, sqlite3_errmsg(db));
  10309. }
  10310. }
  10311. #if HAVE_READLINE || HAVE_EDITLINE
  10312. /*
  10313. ** Readline completion callbacks
  10314. */
  10315. static char *readline_completion_generator(const char *text, int state){
  10316. static sqlite3_stmt *pStmt = 0;
  10317. char *zRet;
  10318. if( state==0 ){
  10319. char *zSql;
  10320. sqlite3_finalize(pStmt);
  10321. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  10322. " FROM completion(%Q) ORDER BY 1", text);
  10323. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  10324. sqlite3_free(zSql);
  10325. }
  10326. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  10327. zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
  10328. }else{
  10329. sqlite3_finalize(pStmt);
  10330. pStmt = 0;
  10331. zRet = 0;
  10332. }
  10333. return zRet;
  10334. }
  10335. static char **readline_completion(const char *zText, int iStart, int iEnd){
  10336. rl_attempted_completion_over = 1;
  10337. return rl_completion_matches(zText, readline_completion_generator);
  10338. }
  10339. #elif HAVE_LINENOISE
  10340. /*
  10341. ** Linenoise completion callback
  10342. */
  10343. static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  10344. int nLine = strlen30(zLine);
  10345. int i, iStart;
  10346. sqlite3_stmt *pStmt = 0;
  10347. char *zSql;
  10348. char zBuf[1000];
  10349. if( nLine>sizeof(zBuf)-30 ) return;
  10350. if( zLine[0]=='.' || zLine[0]=='#') return;
  10351. for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  10352. if( i==nLine-1 ) return;
  10353. iStart = i+1;
  10354. memcpy(zBuf, zLine, iStart);
  10355. zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  10356. " FROM completion(%Q,%Q) ORDER BY 1",
  10357. &zLine[iStart], zLine);
  10358. sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  10359. sqlite3_free(zSql);
  10360. sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  10361. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  10362. const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  10363. int nCompletion = sqlite3_column_bytes(pStmt, 0);
  10364. if( iStart+nCompletion < sizeof(zBuf)-1 ){
  10365. memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  10366. linenoiseAddCompletion(lc, zBuf);
  10367. }
  10368. }
  10369. sqlite3_finalize(pStmt);
  10370. }
  10371. #endif
  10372. /*
  10373. ** Do C-language style dequoting.
  10374. **
  10375. ** \a -> alarm
  10376. ** \b -> backspace
  10377. ** \t -> tab
  10378. ** \n -> newline
  10379. ** \v -> vertical tab
  10380. ** \f -> form feed
  10381. ** \r -> carriage return
  10382. ** \s -> space
  10383. ** \" -> "
  10384. ** \' -> '
  10385. ** \\ -> backslash
  10386. ** \NNN -> ascii character NNN in octal
  10387. */
  10388. static void resolve_backslashes(char *z){
  10389. int i, j;
  10390. char c;
  10391. while( *z && *z!='\\' ) z++;
  10392. for(i=j=0; (c = z[i])!=0; i++, j++){
  10393. if( c=='\\' && z[i+1]!=0 ){
  10394. c = z[++i];
  10395. if( c=='a' ){
  10396. c = '\a';
  10397. }else if( c=='b' ){
  10398. c = '\b';
  10399. }else if( c=='t' ){
  10400. c = '\t';
  10401. }else if( c=='n' ){
  10402. c = '\n';
  10403. }else if( c=='v' ){
  10404. c = '\v';
  10405. }else if( c=='f' ){
  10406. c = '\f';
  10407. }else if( c=='r' ){
  10408. c = '\r';
  10409. }else if( c=='"' ){
  10410. c = '"';
  10411. }else if( c=='\'' ){
  10412. c = '\'';
  10413. }else if( c=='\\' ){
  10414. c = '\\';
  10415. }else if( c>='0' && c<='7' ){
  10416. c -= '0';
  10417. if( z[i+1]>='0' && z[i+1]<='7' ){
  10418. i++;
  10419. c = (c<<3) + z[i] - '0';
  10420. if( z[i+1]>='0' && z[i+1]<='7' ){
  10421. i++;
  10422. c = (c<<3) + z[i] - '0';
  10423. }
  10424. }
  10425. }
  10426. }
  10427. z[j] = c;
  10428. }
  10429. if( j<i ) z[j] = 0;
  10430. }
  10431. /*
  10432. ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
  10433. ** for TRUE and FALSE. Return the integer value if appropriate.
  10434. */
  10435. static int booleanValue(const char *zArg){
  10436. int i;
  10437. if( zArg[0]=='0' && zArg[1]=='x' ){
  10438. for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  10439. }else{
  10440. for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  10441. }
  10442. if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  10443. if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  10444. return 1;
  10445. }
  10446. if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  10447. return 0;
  10448. }
  10449. utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  10450. zArg);
  10451. return 0;
  10452. }
  10453. /*
  10454. ** Set or clear a shell flag according to a boolean value.
  10455. */
  10456. static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  10457. if( booleanValue(zArg) ){
  10458. ShellSetFlag(p, mFlag);
  10459. }else{
  10460. ShellClearFlag(p, mFlag);
  10461. }
  10462. }
  10463. /*
  10464. ** Close an output file, assuming it is not stderr or stdout
  10465. */
  10466. static void output_file_close(FILE *f){
  10467. if( f && f!=stdout && f!=stderr ) fclose(f);
  10468. }
  10469. /*
  10470. ** Try to open an output file. The names "stdout" and "stderr" are
  10471. ** recognized and do the right thing. NULL is returned if the output
  10472. ** filename is "off".
  10473. */
  10474. static FILE *output_file_open(const char *zFile, int bTextMode){
  10475. FILE *f;
  10476. if( strcmp(zFile,"stdout")==0 ){
  10477. f = stdout;
  10478. }else if( strcmp(zFile, "stderr")==0 ){
  10479. f = stderr;
  10480. }else if( strcmp(zFile, "off")==0 ){
  10481. f = 0;
  10482. }else{
  10483. f = fopen(zFile, bTextMode ? "w" : "wb");
  10484. if( f==0 ){
  10485. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  10486. }
  10487. }
  10488. return f;
  10489. }
  10490. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  10491. /*
  10492. ** A routine for handling output from sqlite3_trace().
  10493. */
  10494. static int sql_trace_callback(
  10495. unsigned mType,
  10496. void *pArg,
  10497. void *pP,
  10498. void *pX
  10499. ){
  10500. FILE *f = (FILE*)pArg;
  10501. UNUSED_PARAMETER(mType);
  10502. UNUSED_PARAMETER(pP);
  10503. if( f ){
  10504. const char *z = (const char*)pX;
  10505. int i = strlen30(z);
  10506. while( i>0 && z[i-1]==';' ){ i--; }
  10507. utf8_printf(f, "%.*s;\n", i, z);
  10508. }
  10509. return 0;
  10510. }
  10511. #endif
  10512. /*
  10513. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  10514. ** a useful spot to set a debugger breakpoint.
  10515. */
  10516. static void test_breakpoint(void){
  10517. static int nCall = 0;
  10518. nCall++;
  10519. }
  10520. /*
  10521. ** An object used to read a CSV and other files for import.
  10522. */
  10523. typedef struct ImportCtx ImportCtx;
  10524. struct ImportCtx {
  10525. const char *zFile; /* Name of the input file */
  10526. FILE *in; /* Read the CSV text from this input stream */
  10527. char *z; /* Accumulated text for a field */
  10528. int n; /* Number of bytes in z */
  10529. int nAlloc; /* Space allocated for z[] */
  10530. int nLine; /* Current line number */
  10531. int bNotFirst; /* True if one or more bytes already read */
  10532. int cTerm; /* Character that terminated the most recent field */
  10533. int cColSep; /* The column separator character. (Usually ",") */
  10534. int cRowSep; /* The row separator character. (Usually "\n") */
  10535. };
  10536. /* Append a single byte to z[] */
  10537. static void import_append_char(ImportCtx *p, int c){
  10538. if( p->n+1>=p->nAlloc ){
  10539. p->nAlloc += p->nAlloc + 100;
  10540. p->z = sqlite3_realloc64(p->z, p->nAlloc);
  10541. if( p->z==0 ) shell_out_of_memory();
  10542. }
  10543. p->z[p->n++] = (char)c;
  10544. }
  10545. /* Read a single field of CSV text. Compatible with rfc4180 and extended
  10546. ** with the option of having a separator other than ",".
  10547. **
  10548. ** + Input comes from p->in.
  10549. ** + Store results in p->z of length p->n. Space to hold p->z comes
  10550. ** from sqlite3_malloc64().
  10551. ** + Use p->cSep as the column separator. The default is ",".
  10552. ** + Use p->rSep as the row separator. The default is "\n".
  10553. ** + Keep track of the line number in p->nLine.
  10554. ** + Store the character that terminates the field in p->cTerm. Store
  10555. ** EOF on end-of-file.
  10556. ** + Report syntax errors on stderr
  10557. */
  10558. static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  10559. int c;
  10560. int cSep = p->cColSep;
  10561. int rSep = p->cRowSep;
  10562. p->n = 0;
  10563. c = fgetc(p->in);
  10564. if( c==EOF || seenInterrupt ){
  10565. p->cTerm = EOF;
  10566. return 0;
  10567. }
  10568. if( c=='"' ){
  10569. int pc, ppc;
  10570. int startLine = p->nLine;
  10571. int cQuote = c;
  10572. pc = ppc = 0;
  10573. while( 1 ){
  10574. c = fgetc(p->in);
  10575. if( c==rSep ) p->nLine++;
  10576. if( c==cQuote ){
  10577. if( pc==cQuote ){
  10578. pc = 0;
  10579. continue;
  10580. }
  10581. }
  10582. if( (c==cSep && pc==cQuote)
  10583. || (c==rSep && pc==cQuote)
  10584. || (c==rSep && pc=='\r' && ppc==cQuote)
  10585. || (c==EOF && pc==cQuote)
  10586. ){
  10587. do{ p->n--; }while( p->z[p->n]!=cQuote );
  10588. p->cTerm = c;
  10589. break;
  10590. }
  10591. if( pc==cQuote && c!='\r' ){
  10592. utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  10593. p->zFile, p->nLine, cQuote);
  10594. }
  10595. if( c==EOF ){
  10596. utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  10597. p->zFile, startLine, cQuote);
  10598. p->cTerm = c;
  10599. break;
  10600. }
  10601. import_append_char(p, c);
  10602. ppc = pc;
  10603. pc = c;
  10604. }
  10605. }else{
  10606. /* If this is the first field being parsed and it begins with the
  10607. ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
  10608. if( (c&0xff)==0xef && p->bNotFirst==0 ){
  10609. import_append_char(p, c);
  10610. c = fgetc(p->in);
  10611. if( (c&0xff)==0xbb ){
  10612. import_append_char(p, c);
  10613. c = fgetc(p->in);
  10614. if( (c&0xff)==0xbf ){
  10615. p->bNotFirst = 1;
  10616. p->n = 0;
  10617. return csv_read_one_field(p);
  10618. }
  10619. }
  10620. }
  10621. while( c!=EOF && c!=cSep && c!=rSep ){
  10622. import_append_char(p, c);
  10623. c = fgetc(p->in);
  10624. }
  10625. if( c==rSep ){
  10626. p->nLine++;
  10627. if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  10628. }
  10629. p->cTerm = c;
  10630. }
  10631. if( p->z ) p->z[p->n] = 0;
  10632. p->bNotFirst = 1;
  10633. return p->z;
  10634. }
  10635. /* Read a single field of ASCII delimited text.
  10636. **
  10637. ** + Input comes from p->in.
  10638. ** + Store results in p->z of length p->n. Space to hold p->z comes
  10639. ** from sqlite3_malloc64().
  10640. ** + Use p->cSep as the column separator. The default is "\x1F".
  10641. ** + Use p->rSep as the row separator. The default is "\x1E".
  10642. ** + Keep track of the row number in p->nLine.
  10643. ** + Store the character that terminates the field in p->cTerm. Store
  10644. ** EOF on end-of-file.
  10645. ** + Report syntax errors on stderr
  10646. */
  10647. static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  10648. int c;
  10649. int cSep = p->cColSep;
  10650. int rSep = p->cRowSep;
  10651. p->n = 0;
  10652. c = fgetc(p->in);
  10653. if( c==EOF || seenInterrupt ){
  10654. p->cTerm = EOF;
  10655. return 0;
  10656. }
  10657. while( c!=EOF && c!=cSep && c!=rSep ){
  10658. import_append_char(p, c);
  10659. c = fgetc(p->in);
  10660. }
  10661. if( c==rSep ){
  10662. p->nLine++;
  10663. }
  10664. p->cTerm = c;
  10665. if( p->z ) p->z[p->n] = 0;
  10666. return p->z;
  10667. }
  10668. /*
  10669. ** Try to transfer data for table zTable. If an error is seen while
  10670. ** moving forward, try to go backwards. The backwards movement won't
  10671. ** work for WITHOUT ROWID tables.
  10672. */
  10673. static void tryToCloneData(
  10674. ShellState *p,
  10675. sqlite3 *newDb,
  10676. const char *zTable
  10677. ){
  10678. sqlite3_stmt *pQuery = 0;
  10679. sqlite3_stmt *pInsert = 0;
  10680. char *zQuery = 0;
  10681. char *zInsert = 0;
  10682. int rc;
  10683. int i, j, n;
  10684. int nTable = strlen30(zTable);
  10685. int k = 0;
  10686. int cnt = 0;
  10687. const int spinRate = 10000;
  10688. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  10689. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  10690. if( rc ){
  10691. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  10692. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  10693. zQuery);
  10694. goto end_data_xfer;
  10695. }
  10696. n = sqlite3_column_count(pQuery);
  10697. zInsert = sqlite3_malloc64(200 + nTable + n*3);
  10698. if( zInsert==0 ) shell_out_of_memory();
  10699. sqlite3_snprintf(200+nTable,zInsert,
  10700. "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  10701. i = strlen30(zInsert);
  10702. for(j=1; j<n; j++){
  10703. memcpy(zInsert+i, ",?", 2);
  10704. i += 2;
  10705. }
  10706. memcpy(zInsert+i, ");", 3);
  10707. rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  10708. if( rc ){
  10709. utf8_printf(stderr, "Error %d: %s on [%s]\n",
  10710. sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  10711. zQuery);
  10712. goto end_data_xfer;
  10713. }
  10714. for(k=0; k<2; k++){
  10715. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  10716. for(i=0; i<n; i++){
  10717. switch( sqlite3_column_type(pQuery, i) ){
  10718. case SQLITE_NULL: {
  10719. sqlite3_bind_null(pInsert, i+1);
  10720. break;
  10721. }
  10722. case SQLITE_INTEGER: {
  10723. sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  10724. break;
  10725. }
  10726. case SQLITE_FLOAT: {
  10727. sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  10728. break;
  10729. }
  10730. case SQLITE_TEXT: {
  10731. sqlite3_bind_text(pInsert, i+1,
  10732. (const char*)sqlite3_column_text(pQuery,i),
  10733. -1, SQLITE_STATIC);
  10734. break;
  10735. }
  10736. case SQLITE_BLOB: {
  10737. sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  10738. sqlite3_column_bytes(pQuery,i),
  10739. SQLITE_STATIC);
  10740. break;
  10741. }
  10742. }
  10743. } /* End for */
  10744. rc = sqlite3_step(pInsert);
  10745. if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  10746. utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  10747. sqlite3_errmsg(newDb));
  10748. }
  10749. sqlite3_reset(pInsert);
  10750. cnt++;
  10751. if( (cnt%spinRate)==0 ){
  10752. printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  10753. fflush(stdout);
  10754. }
  10755. } /* End while */
  10756. if( rc==SQLITE_DONE ) break;
  10757. sqlite3_finalize(pQuery);
  10758. sqlite3_free(zQuery);
  10759. zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  10760. zTable);
  10761. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  10762. if( rc ){
  10763. utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  10764. break;
  10765. }
  10766. } /* End for(k=0...) */
  10767. end_data_xfer:
  10768. sqlite3_finalize(pQuery);
  10769. sqlite3_finalize(pInsert);
  10770. sqlite3_free(zQuery);
  10771. sqlite3_free(zInsert);
  10772. }
  10773. /*
  10774. ** Try to transfer all rows of the schema that match zWhere. For
  10775. ** each row, invoke xForEach() on the object defined by that row.
  10776. ** If an error is encountered while moving forward through the
  10777. ** sqlite_master table, try again moving backwards.
  10778. */
  10779. static void tryToCloneSchema(
  10780. ShellState *p,
  10781. sqlite3 *newDb,
  10782. const char *zWhere,
  10783. void (*xForEach)(ShellState*,sqlite3*,const char*)
  10784. ){
  10785. sqlite3_stmt *pQuery = 0;
  10786. char *zQuery = 0;
  10787. int rc;
  10788. const unsigned char *zName;
  10789. const unsigned char *zSql;
  10790. char *zErrMsg = 0;
  10791. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  10792. " WHERE %s", zWhere);
  10793. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  10794. if( rc ){
  10795. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  10796. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  10797. zQuery);
  10798. goto end_schema_xfer;
  10799. }
  10800. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  10801. zName = sqlite3_column_text(pQuery, 0);
  10802. zSql = sqlite3_column_text(pQuery, 1);
  10803. printf("%s... ", zName); fflush(stdout);
  10804. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  10805. if( zErrMsg ){
  10806. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  10807. sqlite3_free(zErrMsg);
  10808. zErrMsg = 0;
  10809. }
  10810. if( xForEach ){
  10811. xForEach(p, newDb, (const char*)zName);
  10812. }
  10813. printf("done\n");
  10814. }
  10815. if( rc!=SQLITE_DONE ){
  10816. sqlite3_finalize(pQuery);
  10817. sqlite3_free(zQuery);
  10818. zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  10819. " WHERE %s ORDER BY rowid DESC", zWhere);
  10820. rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  10821. if( rc ){
  10822. utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  10823. sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  10824. zQuery);
  10825. goto end_schema_xfer;
  10826. }
  10827. while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  10828. zName = sqlite3_column_text(pQuery, 0);
  10829. zSql = sqlite3_column_text(pQuery, 1);
  10830. printf("%s... ", zName); fflush(stdout);
  10831. sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  10832. if( zErrMsg ){
  10833. utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  10834. sqlite3_free(zErrMsg);
  10835. zErrMsg = 0;
  10836. }
  10837. if( xForEach ){
  10838. xForEach(p, newDb, (const char*)zName);
  10839. }
  10840. printf("done\n");
  10841. }
  10842. }
  10843. end_schema_xfer:
  10844. sqlite3_finalize(pQuery);
  10845. sqlite3_free(zQuery);
  10846. }
  10847. /*
  10848. ** Open a new database file named "zNewDb". Try to recover as much information
  10849. ** as possible out of the main database (which might be corrupt) and write it
  10850. ** into zNewDb.
  10851. */
  10852. static void tryToClone(ShellState *p, const char *zNewDb){
  10853. int rc;
  10854. sqlite3 *newDb = 0;
  10855. if( access(zNewDb,0)==0 ){
  10856. utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  10857. return;
  10858. }
  10859. rc = sqlite3_open(zNewDb, &newDb);
  10860. if( rc ){
  10861. utf8_printf(stderr, "Cannot create output database: %s\n",
  10862. sqlite3_errmsg(newDb));
  10863. }else{
  10864. sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  10865. sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  10866. tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  10867. tryToCloneSchema(p, newDb, "type!='table'", 0);
  10868. sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  10869. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  10870. }
  10871. close_db(newDb);
  10872. }
  10873. /*
  10874. ** Change the output file back to stdout.
  10875. **
  10876. ** If the p->doXdgOpen flag is set, that means the output was being
  10877. ** redirected to a temporary file named by p->zTempFile. In that case,
  10878. ** launch start/open/xdg-open on that temporary file.
  10879. */
  10880. static void output_reset(ShellState *p){
  10881. if( p->outfile[0]=='|' ){
  10882. #ifndef SQLITE_OMIT_POPEN
  10883. pclose(p->out);
  10884. #endif
  10885. }else{
  10886. output_file_close(p->out);
  10887. #ifndef SQLITE_NOHAVE_SYSTEM
  10888. if( p->doXdgOpen ){
  10889. const char *zXdgOpenCmd =
  10890. #if defined(_WIN32)
  10891. "start";
  10892. #elif defined(__APPLE__)
  10893. "open";
  10894. #else
  10895. "xdg-open";
  10896. #endif
  10897. char *zCmd;
  10898. zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
  10899. if( system(zCmd) ){
  10900. utf8_printf(stderr, "Failed: [%s]\n", zCmd);
  10901. }
  10902. sqlite3_free(zCmd);
  10903. outputModePop(p);
  10904. p->doXdgOpen = 0;
  10905. }
  10906. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  10907. }
  10908. p->outfile[0] = 0;
  10909. p->out = stdout;
  10910. }
  10911. /*
  10912. ** Run an SQL command and return the single integer result.
  10913. */
  10914. static int db_int(ShellState *p, const char *zSql){
  10915. sqlite3_stmt *pStmt;
  10916. int res = 0;
  10917. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  10918. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  10919. res = sqlite3_column_int(pStmt,0);
  10920. }
  10921. sqlite3_finalize(pStmt);
  10922. return res;
  10923. }
  10924. /*
  10925. ** Convert a 2-byte or 4-byte big-endian integer into a native integer
  10926. */
  10927. static unsigned int get2byteInt(unsigned char *a){
  10928. return (a[0]<<8) + a[1];
  10929. }
  10930. static unsigned int get4byteInt(unsigned char *a){
  10931. return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  10932. }
  10933. /*
  10934. ** Implementation of the ".info" command.
  10935. **
  10936. ** Return 1 on error, 2 to exit, and 0 otherwise.
  10937. */
  10938. static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  10939. static const struct { const char *zName; int ofst; } aField[] = {
  10940. { "file change counter:", 24 },
  10941. { "database page count:", 28 },
  10942. { "freelist page count:", 36 },
  10943. { "schema cookie:", 40 },
  10944. { "schema format:", 44 },
  10945. { "default cache size:", 48 },
  10946. { "autovacuum top root:", 52 },
  10947. { "incremental vacuum:", 64 },
  10948. { "text encoding:", 56 },
  10949. { "user version:", 60 },
  10950. { "application id:", 68 },
  10951. { "software version:", 96 },
  10952. };
  10953. static const struct { const char *zName; const char *zSql; } aQuery[] = {
  10954. { "number of tables:",
  10955. "SELECT count(*) FROM %s WHERE type='table'" },
  10956. { "number of indexes:",
  10957. "SELECT count(*) FROM %s WHERE type='index'" },
  10958. { "number of triggers:",
  10959. "SELECT count(*) FROM %s WHERE type='trigger'" },
  10960. { "number of views:",
  10961. "SELECT count(*) FROM %s WHERE type='view'" },
  10962. { "schema size:",
  10963. "SELECT total(length(sql)) FROM %s" },
  10964. };
  10965. int i;
  10966. unsigned iDataVersion;
  10967. char *zSchemaTab;
  10968. char *zDb = nArg>=2 ? azArg[1] : "main";
  10969. sqlite3_stmt *pStmt = 0;
  10970. unsigned char aHdr[100];
  10971. open_db(p, 0);
  10972. if( p->db==0 ) return 1;
  10973. sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
  10974. -1, &pStmt, 0);
  10975. sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
  10976. if( sqlite3_step(pStmt)==SQLITE_ROW
  10977. && sqlite3_column_bytes(pStmt,0)>100
  10978. ){
  10979. memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
  10980. sqlite3_finalize(pStmt);
  10981. }else{
  10982. raw_printf(stderr, "unable to read database header\n");
  10983. sqlite3_finalize(pStmt);
  10984. return 1;
  10985. }
  10986. i = get2byteInt(aHdr+16);
  10987. if( i==1 ) i = 65536;
  10988. utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  10989. utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  10990. utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  10991. utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  10992. for(i=0; i<ArraySize(aField); i++){
  10993. int ofst = aField[i].ofst;
  10994. unsigned int val = get4byteInt(aHdr + ofst);
  10995. utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  10996. switch( ofst ){
  10997. case 56: {
  10998. if( val==1 ) raw_printf(p->out, " (utf8)");
  10999. if( val==2 ) raw_printf(p->out, " (utf16le)");
  11000. if( val==3 ) raw_printf(p->out, " (utf16be)");
  11001. }
  11002. }
  11003. raw_printf(p->out, "\n");
  11004. }
  11005. if( zDb==0 ){
  11006. zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  11007. }else if( strcmp(zDb,"temp")==0 ){
  11008. zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  11009. }else{
  11010. zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  11011. }
  11012. for(i=0; i<ArraySize(aQuery); i++){
  11013. char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  11014. int val = db_int(p, zSql);
  11015. sqlite3_free(zSql);
  11016. utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  11017. }
  11018. sqlite3_free(zSchemaTab);
  11019. sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
  11020. utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
  11021. return 0;
  11022. }
  11023. /*
  11024. ** Print the current sqlite3_errmsg() value to stderr and return 1.
  11025. */
  11026. static int shellDatabaseError(sqlite3 *db){
  11027. const char *zErr = sqlite3_errmsg(db);
  11028. utf8_printf(stderr, "Error: %s\n", zErr);
  11029. return 1;
  11030. }
  11031. /*
  11032. ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
  11033. ** if they match and FALSE (0) if they do not match.
  11034. **
  11035. ** Globbing rules:
  11036. **
  11037. ** '*' Matches any sequence of zero or more characters.
  11038. **
  11039. ** '?' Matches exactly one character.
  11040. **
  11041. ** [...] Matches one character from the enclosed list of
  11042. ** characters.
  11043. **
  11044. ** [^...] Matches one character not in the enclosed list.
  11045. **
  11046. ** '#' Matches any sequence of one or more digits with an
  11047. ** optional + or - sign in front
  11048. **
  11049. ** ' ' Any span of whitespace matches any other span of
  11050. ** whitespace.
  11051. **
  11052. ** Extra whitespace at the end of z[] is ignored.
  11053. */
  11054. static int testcase_glob(const char *zGlob, const char *z){
  11055. int c, c2;
  11056. int invert;
  11057. int seen;
  11058. while( (c = (*(zGlob++)))!=0 ){
  11059. if( IsSpace(c) ){
  11060. if( !IsSpace(*z) ) return 0;
  11061. while( IsSpace(*zGlob) ) zGlob++;
  11062. while( IsSpace(*z) ) z++;
  11063. }else if( c=='*' ){
  11064. while( (c=(*(zGlob++))) == '*' || c=='?' ){
  11065. if( c=='?' && (*(z++))==0 ) return 0;
  11066. }
  11067. if( c==0 ){
  11068. return 1;
  11069. }else if( c=='[' ){
  11070. while( *z && testcase_glob(zGlob-1,z)==0 ){
  11071. z++;
  11072. }
  11073. return (*z)!=0;
  11074. }
  11075. while( (c2 = (*(z++)))!=0 ){
  11076. while( c2!=c ){
  11077. c2 = *(z++);
  11078. if( c2==0 ) return 0;
  11079. }
  11080. if( testcase_glob(zGlob,z) ) return 1;
  11081. }
  11082. return 0;
  11083. }else if( c=='?' ){
  11084. if( (*(z++))==0 ) return 0;
  11085. }else if( c=='[' ){
  11086. int prior_c = 0;
  11087. seen = 0;
  11088. invert = 0;
  11089. c = *(z++);
  11090. if( c==0 ) return 0;
  11091. c2 = *(zGlob++);
  11092. if( c2=='^' ){
  11093. invert = 1;
  11094. c2 = *(zGlob++);
  11095. }
  11096. if( c2==']' ){
  11097. if( c==']' ) seen = 1;
  11098. c2 = *(zGlob++);
  11099. }
  11100. while( c2 && c2!=']' ){
  11101. if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  11102. c2 = *(zGlob++);
  11103. if( c>=prior_c && c<=c2 ) seen = 1;
  11104. prior_c = 0;
  11105. }else{
  11106. if( c==c2 ){
  11107. seen = 1;
  11108. }
  11109. prior_c = c2;
  11110. }
  11111. c2 = *(zGlob++);
  11112. }
  11113. if( c2==0 || (seen ^ invert)==0 ) return 0;
  11114. }else if( c=='#' ){
  11115. if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  11116. if( !IsDigit(z[0]) ) return 0;
  11117. z++;
  11118. while( IsDigit(z[0]) ){ z++; }
  11119. }else{
  11120. if( c!=(*(z++)) ) return 0;
  11121. }
  11122. }
  11123. while( IsSpace(*z) ){ z++; }
  11124. return *z==0;
  11125. }
  11126. /*
  11127. ** Compare the string as a command-line option with either one or two
  11128. ** initial "-" characters.
  11129. */
  11130. static int optionMatch(const char *zStr, const char *zOpt){
  11131. if( zStr[0]!='-' ) return 0;
  11132. zStr++;
  11133. if( zStr[0]=='-' ) zStr++;
  11134. return strcmp(zStr, zOpt)==0;
  11135. }
  11136. /*
  11137. ** Delete a file.
  11138. */
  11139. int shellDeleteFile(const char *zFilename){
  11140. int rc;
  11141. #ifdef _WIN32
  11142. wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  11143. rc = _wunlink(z);
  11144. sqlite3_free(z);
  11145. #else
  11146. rc = unlink(zFilename);
  11147. #endif
  11148. return rc;
  11149. }
  11150. /*
  11151. ** Try to delete the temporary file (if there is one) and free the
  11152. ** memory used to hold the name of the temp file.
  11153. */
  11154. static void clearTempFile(ShellState *p){
  11155. if( p->zTempFile==0 ) return;
  11156. if( p->doXdgOpen ) return;
  11157. if( shellDeleteFile(p->zTempFile) ) return;
  11158. sqlite3_free(p->zTempFile);
  11159. p->zTempFile = 0;
  11160. }
  11161. /*
  11162. ** Create a new temp file name with the given suffix.
  11163. */
  11164. static void newTempFile(ShellState *p, const char *zSuffix){
  11165. clearTempFile(p);
  11166. sqlite3_free(p->zTempFile);
  11167. p->zTempFile = 0;
  11168. if( p->db ){
  11169. sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
  11170. }
  11171. if( p->zTempFile==0 ){
  11172. sqlite3_uint64 r;
  11173. sqlite3_randomness(sizeof(r), &r);
  11174. p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
  11175. }else{
  11176. p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
  11177. }
  11178. if( p->zTempFile==0 ){
  11179. raw_printf(stderr, "out of memory\n");
  11180. exit(1);
  11181. }
  11182. }
  11183. /*
  11184. ** The implementation of SQL scalar function fkey_collate_clause(), used
  11185. ** by the ".lint fkey-indexes" command. This scalar function is always
  11186. ** called with four arguments - the parent table name, the parent column name,
  11187. ** the child table name and the child column name.
  11188. **
  11189. ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  11190. **
  11191. ** If either of the named tables or columns do not exist, this function
  11192. ** returns an empty string. An empty string is also returned if both tables
  11193. ** and columns exist but have the same default collation sequence. Or,
  11194. ** if both exist but the default collation sequences are different, this
  11195. ** function returns the string " COLLATE <parent-collation>", where
  11196. ** <parent-collation> is the default collation sequence of the parent column.
  11197. */
  11198. static void shellFkeyCollateClause(
  11199. sqlite3_context *pCtx,
  11200. int nVal,
  11201. sqlite3_value **apVal
  11202. ){
  11203. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  11204. const char *zParent;
  11205. const char *zParentCol;
  11206. const char *zParentSeq;
  11207. const char *zChild;
  11208. const char *zChildCol;
  11209. const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
  11210. int rc;
  11211. assert( nVal==4 );
  11212. zParent = (const char*)sqlite3_value_text(apVal[0]);
  11213. zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  11214. zChild = (const char*)sqlite3_value_text(apVal[2]);
  11215. zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  11216. sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  11217. rc = sqlite3_table_column_metadata(
  11218. db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  11219. );
  11220. if( rc==SQLITE_OK ){
  11221. rc = sqlite3_table_column_metadata(
  11222. db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  11223. );
  11224. }
  11225. if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  11226. char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  11227. sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  11228. sqlite3_free(z);
  11229. }
  11230. }
  11231. /*
  11232. ** The implementation of dot-command ".lint fkey-indexes".
  11233. */
  11234. static int lintFkeyIndexes(
  11235. ShellState *pState, /* Current shell tool state */
  11236. char **azArg, /* Array of arguments passed to dot command */
  11237. int nArg /* Number of entries in azArg[] */
  11238. ){
  11239. sqlite3 *db = pState->db; /* Database handle to query "main" db of */
  11240. FILE *out = pState->out; /* Stream to write non-error output to */
  11241. int bVerbose = 0; /* If -verbose is present */
  11242. int bGroupByParent = 0; /* If -groupbyparent is present */
  11243. int i; /* To iterate through azArg[] */
  11244. const char *zIndent = ""; /* How much to indent CREATE INDEX by */
  11245. int rc; /* Return code */
  11246. sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
  11247. /*
  11248. ** This SELECT statement returns one row for each foreign key constraint
  11249. ** in the schema of the main database. The column values are:
  11250. **
  11251. ** 0. The text of an SQL statement similar to:
  11252. **
  11253. ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
  11254. **
  11255. ** This SELECT is similar to the one that the foreign keys implementation
  11256. ** needs to run internally on child tables. If there is an index that can
  11257. ** be used to optimize this query, then it can also be used by the FK
  11258. ** implementation to optimize DELETE or UPDATE statements on the parent
  11259. ** table.
  11260. **
  11261. ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  11262. ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  11263. ** contains an index that can be used to optimize the query.
  11264. **
  11265. ** 2. Human readable text that describes the child table and columns. e.g.
  11266. **
  11267. ** "child_table(child_key1, child_key2)"
  11268. **
  11269. ** 3. Human readable text that describes the parent table and columns. e.g.
  11270. **
  11271. ** "parent_table(parent_key1, parent_key2)"
  11272. **
  11273. ** 4. A full CREATE INDEX statement for an index that could be used to
  11274. ** optimize DELETE or UPDATE statements on the parent table. e.g.
  11275. **
  11276. ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
  11277. **
  11278. ** 5. The name of the parent table.
  11279. **
  11280. ** These six values are used by the C logic below to generate the report.
  11281. */
  11282. const char *zSql =
  11283. "SELECT "
  11284. " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
  11285. " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  11286. " || fkey_collate_clause("
  11287. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  11288. ", "
  11289. " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
  11290. " || group_concat('*=?', ' AND ') || ')'"
  11291. ", "
  11292. " s.name || '(' || group_concat(f.[from], ', ') || ')'"
  11293. ", "
  11294. " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  11295. ", "
  11296. " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  11297. " || ' ON ' || quote(s.name) || '('"
  11298. " || group_concat(quote(f.[from]) ||"
  11299. " fkey_collate_clause("
  11300. " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  11301. " || ');'"
  11302. ", "
  11303. " f.[table] "
  11304. "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
  11305. "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  11306. "GROUP BY s.name, f.id "
  11307. "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  11308. ;
  11309. const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
  11310. for(i=2; i<nArg; i++){
  11311. int n = strlen30(azArg[i]);
  11312. if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  11313. bVerbose = 1;
  11314. }
  11315. else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  11316. bGroupByParent = 1;
  11317. zIndent = " ";
  11318. }
  11319. else{
  11320. raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  11321. azArg[0], azArg[1]
  11322. );
  11323. return SQLITE_ERROR;
  11324. }
  11325. }
  11326. /* Register the fkey_collate_clause() SQL function */
  11327. rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  11328. 0, shellFkeyCollateClause, 0, 0
  11329. );
  11330. if( rc==SQLITE_OK ){
  11331. rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  11332. }
  11333. if( rc==SQLITE_OK ){
  11334. sqlite3_bind_int(pSql, 1, bGroupByParent);
  11335. }
  11336. if( rc==SQLITE_OK ){
  11337. int rc2;
  11338. char *zPrev = 0;
  11339. while( SQLITE_ROW==sqlite3_step(pSql) ){
  11340. int res = -1;
  11341. sqlite3_stmt *pExplain = 0;
  11342. const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  11343. const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  11344. const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  11345. const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  11346. const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  11347. const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  11348. rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  11349. if( rc!=SQLITE_OK ) break;
  11350. if( SQLITE_ROW==sqlite3_step(pExplain) ){
  11351. const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  11352. res = (
  11353. 0==sqlite3_strglob(zGlob, zPlan)
  11354. || 0==sqlite3_strglob(zGlobIPK, zPlan)
  11355. );
  11356. }
  11357. rc = sqlite3_finalize(pExplain);
  11358. if( rc!=SQLITE_OK ) break;
  11359. if( res<0 ){
  11360. raw_printf(stderr, "Error: internal error");
  11361. break;
  11362. }else{
  11363. if( bGroupByParent
  11364. && (bVerbose || res==0)
  11365. && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  11366. ){
  11367. raw_printf(out, "-- Parent table %s\n", zParent);
  11368. sqlite3_free(zPrev);
  11369. zPrev = sqlite3_mprintf("%s", zParent);
  11370. }
  11371. if( res==0 ){
  11372. raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  11373. }else if( bVerbose ){
  11374. raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  11375. zIndent, zFrom, zTarget
  11376. );
  11377. }
  11378. }
  11379. }
  11380. sqlite3_free(zPrev);
  11381. if( rc!=SQLITE_OK ){
  11382. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  11383. }
  11384. rc2 = sqlite3_finalize(pSql);
  11385. if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  11386. rc = rc2;
  11387. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  11388. }
  11389. }else{
  11390. raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  11391. }
  11392. return rc;
  11393. }
  11394. /*
  11395. ** Implementation of ".lint" dot command.
  11396. */
  11397. static int lintDotCommand(
  11398. ShellState *pState, /* Current shell tool state */
  11399. char **azArg, /* Array of arguments passed to dot command */
  11400. int nArg /* Number of entries in azArg[] */
  11401. ){
  11402. int n;
  11403. n = (nArg>=2 ? strlen30(azArg[1]) : 0);
  11404. if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  11405. return lintFkeyIndexes(pState, azArg, nArg);
  11406. usage:
  11407. raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  11408. raw_printf(stderr, "Where sub-commands are:\n");
  11409. raw_printf(stderr, " fkey-indexes\n");
  11410. return SQLITE_ERROR;
  11411. }
  11412. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  11413. /*********************************************************************************
  11414. ** The ".archive" or ".ar" command.
  11415. */
  11416. static void shellPrepare(
  11417. sqlite3 *db,
  11418. int *pRc,
  11419. const char *zSql,
  11420. sqlite3_stmt **ppStmt
  11421. ){
  11422. *ppStmt = 0;
  11423. if( *pRc==SQLITE_OK ){
  11424. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  11425. if( rc!=SQLITE_OK ){
  11426. raw_printf(stderr, "sql error: %s (%d)\n",
  11427. sqlite3_errmsg(db), sqlite3_errcode(db)
  11428. );
  11429. *pRc = rc;
  11430. }
  11431. }
  11432. }
  11433. static void shellPreparePrintf(
  11434. sqlite3 *db,
  11435. int *pRc,
  11436. sqlite3_stmt **ppStmt,
  11437. const char *zFmt,
  11438. ...
  11439. ){
  11440. *ppStmt = 0;
  11441. if( *pRc==SQLITE_OK ){
  11442. va_list ap;
  11443. char *z;
  11444. va_start(ap, zFmt);
  11445. z = sqlite3_vmprintf(zFmt, ap);
  11446. if( z==0 ){
  11447. *pRc = SQLITE_NOMEM;
  11448. }else{
  11449. shellPrepare(db, pRc, z, ppStmt);
  11450. sqlite3_free(z);
  11451. }
  11452. }
  11453. }
  11454. static void shellFinalize(
  11455. int *pRc,
  11456. sqlite3_stmt *pStmt
  11457. ){
  11458. if( pStmt ){
  11459. sqlite3 *db = sqlite3_db_handle(pStmt);
  11460. int rc = sqlite3_finalize(pStmt);
  11461. if( *pRc==SQLITE_OK ){
  11462. if( rc!=SQLITE_OK ){
  11463. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  11464. }
  11465. *pRc = rc;
  11466. }
  11467. }
  11468. }
  11469. static void shellReset(
  11470. int *pRc,
  11471. sqlite3_stmt *pStmt
  11472. ){
  11473. int rc = sqlite3_reset(pStmt);
  11474. if( *pRc==SQLITE_OK ){
  11475. if( rc!=SQLITE_OK ){
  11476. sqlite3 *db = sqlite3_db_handle(pStmt);
  11477. raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
  11478. }
  11479. *pRc = rc;
  11480. }
  11481. }
  11482. /*
  11483. ** Structure representing a single ".ar" command.
  11484. */
  11485. typedef struct ArCommand ArCommand;
  11486. struct ArCommand {
  11487. u8 eCmd; /* An AR_CMD_* value */
  11488. u8 bVerbose; /* True if --verbose */
  11489. u8 bZip; /* True if the archive is a ZIP */
  11490. u8 bDryRun; /* True if --dry-run */
  11491. u8 bAppend; /* True if --append */
  11492. u8 fromCmdLine; /* Run from -A instead of .archive */
  11493. int nArg; /* Number of command arguments */
  11494. char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
  11495. const char *zFile; /* --file argument, or NULL */
  11496. const char *zDir; /* --directory argument, or NULL */
  11497. char **azArg; /* Array of command arguments */
  11498. ShellState *p; /* Shell state */
  11499. sqlite3 *db; /* Database containing the archive */
  11500. };
  11501. /*
  11502. ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
  11503. */
  11504. static int arUsage(FILE *f){
  11505. raw_printf(f,
  11506. "\n"
  11507. "Usage: .ar [OPTION...] [FILE...]\n"
  11508. "The .ar command manages sqlar archives.\n"
  11509. "\n"
  11510. "Examples:\n"
  11511. " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
  11512. " .ar -tf archive.sar # List members of archive.sar\n"
  11513. " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
  11514. "\n"
  11515. "Each command line must feature exactly one command option:\n"
  11516. " -c, --create Create a new archive\n"
  11517. " -u, --update Update or add files to an existing archive\n"
  11518. " -t, --list List contents of archive\n"
  11519. " -x, --extract Extract files from archive\n"
  11520. "\n"
  11521. "And zero or more optional options:\n"
  11522. " -v, --verbose Print each filename as it is processed\n"
  11523. " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
  11524. " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
  11525. " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
  11526. " -n, --dryrun Show the SQL that would have occurred\n"
  11527. "\n"
  11528. "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
  11529. "\n"
  11530. );
  11531. return SQLITE_ERROR;
  11532. }
  11533. /*
  11534. ** Print an error message for the .ar command to stderr and return
  11535. ** SQLITE_ERROR.
  11536. */
  11537. static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
  11538. va_list ap;
  11539. char *z;
  11540. va_start(ap, zFmt);
  11541. z = sqlite3_vmprintf(zFmt, ap);
  11542. va_end(ap);
  11543. utf8_printf(stderr, "Error: %s\n", z);
  11544. if( pAr->fromCmdLine ){
  11545. utf8_printf(stderr, "Use \"-A\" for more help\n");
  11546. }else{
  11547. utf8_printf(stderr, "Use \".archive --help\" for more help\n");
  11548. }
  11549. sqlite3_free(z);
  11550. return SQLITE_ERROR;
  11551. }
  11552. /*
  11553. ** Values for ArCommand.eCmd.
  11554. */
  11555. #define AR_CMD_CREATE 1
  11556. #define AR_CMD_EXTRACT 2
  11557. #define AR_CMD_LIST 3
  11558. #define AR_CMD_UPDATE 4
  11559. #define AR_CMD_HELP 5
  11560. /*
  11561. ** Other (non-command) switches.
  11562. */
  11563. #define AR_SWITCH_VERBOSE 6
  11564. #define AR_SWITCH_FILE 7
  11565. #define AR_SWITCH_DIRECTORY 8
  11566. #define AR_SWITCH_APPEND 9
  11567. #define AR_SWITCH_DRYRUN 10
  11568. static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
  11569. switch( eSwitch ){
  11570. case AR_CMD_CREATE:
  11571. case AR_CMD_EXTRACT:
  11572. case AR_CMD_LIST:
  11573. case AR_CMD_UPDATE:
  11574. case AR_CMD_HELP:
  11575. if( pAr->eCmd ){
  11576. return arErrorMsg(pAr, "multiple command options");
  11577. }
  11578. pAr->eCmd = eSwitch;
  11579. break;
  11580. case AR_SWITCH_DRYRUN:
  11581. pAr->bDryRun = 1;
  11582. break;
  11583. case AR_SWITCH_VERBOSE:
  11584. pAr->bVerbose = 1;
  11585. break;
  11586. case AR_SWITCH_APPEND:
  11587. pAr->bAppend = 1;
  11588. /* Fall thru into --file */
  11589. case AR_SWITCH_FILE:
  11590. pAr->zFile = zArg;
  11591. break;
  11592. case AR_SWITCH_DIRECTORY:
  11593. pAr->zDir = zArg;
  11594. break;
  11595. }
  11596. return SQLITE_OK;
  11597. }
  11598. /*
  11599. ** Parse the command line for an ".ar" command. The results are written into
  11600. ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
  11601. ** successfully, otherwise an error message is written to stderr and
  11602. ** SQLITE_ERROR returned.
  11603. */
  11604. static int arParseCommand(
  11605. char **azArg, /* Array of arguments passed to dot command */
  11606. int nArg, /* Number of entries in azArg[] */
  11607. ArCommand *pAr /* Populate this object */
  11608. ){
  11609. struct ArSwitch {
  11610. const char *zLong;
  11611. char cShort;
  11612. u8 eSwitch;
  11613. u8 bArg;
  11614. } aSwitch[] = {
  11615. { "create", 'c', AR_CMD_CREATE, 0 },
  11616. { "extract", 'x', AR_CMD_EXTRACT, 0 },
  11617. { "list", 't', AR_CMD_LIST, 0 },
  11618. { "update", 'u', AR_CMD_UPDATE, 0 },
  11619. { "help", 'h', AR_CMD_HELP, 0 },
  11620. { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
  11621. { "file", 'f', AR_SWITCH_FILE, 1 },
  11622. { "append", 'a', AR_SWITCH_APPEND, 1 },
  11623. { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
  11624. { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
  11625. };
  11626. int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
  11627. struct ArSwitch *pEnd = &aSwitch[nSwitch];
  11628. if( nArg<=1 ){
  11629. return arUsage(stderr);
  11630. }else{
  11631. char *z = azArg[1];
  11632. if( z[0]!='-' ){
  11633. /* Traditional style [tar] invocation */
  11634. int i;
  11635. int iArg = 2;
  11636. for(i=0; z[i]; i++){
  11637. const char *zArg = 0;
  11638. struct ArSwitch *pOpt;
  11639. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  11640. if( z[i]==pOpt->cShort ) break;
  11641. }
  11642. if( pOpt==pEnd ){
  11643. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  11644. }
  11645. if( pOpt->bArg ){
  11646. if( iArg>=nArg ){
  11647. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  11648. }
  11649. zArg = azArg[iArg++];
  11650. }
  11651. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  11652. }
  11653. pAr->nArg = nArg-iArg;
  11654. if( pAr->nArg>0 ){
  11655. pAr->azArg = &azArg[iArg];
  11656. }
  11657. }else{
  11658. /* Non-traditional invocation */
  11659. int iArg;
  11660. for(iArg=1; iArg<nArg; iArg++){
  11661. int n;
  11662. z = azArg[iArg];
  11663. if( z[0]!='-' ){
  11664. /* All remaining command line words are command arguments. */
  11665. pAr->azArg = &azArg[iArg];
  11666. pAr->nArg = nArg-iArg;
  11667. break;
  11668. }
  11669. n = strlen30(z);
  11670. if( z[1]!='-' ){
  11671. int i;
  11672. /* One or more short options */
  11673. for(i=1; i<n; i++){
  11674. const char *zArg = 0;
  11675. struct ArSwitch *pOpt;
  11676. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  11677. if( z[i]==pOpt->cShort ) break;
  11678. }
  11679. if( pOpt==pEnd ){
  11680. return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
  11681. }
  11682. if( pOpt->bArg ){
  11683. if( i<(n-1) ){
  11684. zArg = &z[i+1];
  11685. i = n;
  11686. }else{
  11687. if( iArg>=(nArg-1) ){
  11688. return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
  11689. }
  11690. zArg = azArg[++iArg];
  11691. }
  11692. }
  11693. if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
  11694. }
  11695. }else if( z[2]=='\0' ){
  11696. /* A -- option, indicating that all remaining command line words
  11697. ** are command arguments. */
  11698. pAr->azArg = &azArg[iArg+1];
  11699. pAr->nArg = nArg-iArg-1;
  11700. break;
  11701. }else{
  11702. /* A long option */
  11703. const char *zArg = 0; /* Argument for option, if any */
  11704. struct ArSwitch *pMatch = 0; /* Matching option */
  11705. struct ArSwitch *pOpt; /* Iterator */
  11706. for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
  11707. const char *zLong = pOpt->zLong;
  11708. if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
  11709. if( pMatch ){
  11710. return arErrorMsg(pAr, "ambiguous option: %s",z);
  11711. }else{
  11712. pMatch = pOpt;
  11713. }
  11714. }
  11715. }
  11716. if( pMatch==0 ){
  11717. return arErrorMsg(pAr, "unrecognized option: %s", z);
  11718. }
  11719. if( pMatch->bArg ){
  11720. if( iArg>=(nArg-1) ){
  11721. return arErrorMsg(pAr, "option requires an argument: %s", z);
  11722. }
  11723. zArg = azArg[++iArg];
  11724. }
  11725. if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
  11726. }
  11727. }
  11728. }
  11729. }
  11730. return SQLITE_OK;
  11731. }
  11732. /*
  11733. ** This function assumes that all arguments within the ArCommand.azArg[]
  11734. ** array refer to archive members, as for the --extract or --list commands.
  11735. ** It checks that each of them are present. If any specified file is not
  11736. ** present in the archive, an error is printed to stderr and an error
  11737. ** code returned. Otherwise, if all specified arguments are present in
  11738. ** the archive, SQLITE_OK is returned.
  11739. **
  11740. ** This function strips any trailing '/' characters from each argument.
  11741. ** This is consistent with the way the [tar] command seems to work on
  11742. ** Linux.
  11743. */
  11744. static int arCheckEntries(ArCommand *pAr){
  11745. int rc = SQLITE_OK;
  11746. if( pAr->nArg ){
  11747. int i, j;
  11748. sqlite3_stmt *pTest = 0;
  11749. shellPreparePrintf(pAr->db, &rc, &pTest,
  11750. "SELECT name FROM %s WHERE name=$name",
  11751. pAr->zSrcTable
  11752. );
  11753. j = sqlite3_bind_parameter_index(pTest, "$name");
  11754. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  11755. char *z = pAr->azArg[i];
  11756. int n = strlen30(z);
  11757. int bOk = 0;
  11758. while( n>0 && z[n-1]=='/' ) n--;
  11759. z[n] = '\0';
  11760. sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
  11761. if( SQLITE_ROW==sqlite3_step(pTest) ){
  11762. bOk = 1;
  11763. }
  11764. shellReset(&rc, pTest);
  11765. if( rc==SQLITE_OK && bOk==0 ){
  11766. utf8_printf(stderr, "not found in archive: %s\n", z);
  11767. rc = SQLITE_ERROR;
  11768. }
  11769. }
  11770. shellFinalize(&rc, pTest);
  11771. }
  11772. return rc;
  11773. }
  11774. /*
  11775. ** Format a WHERE clause that can be used against the "sqlar" table to
  11776. ** identify all archive members that match the command arguments held
  11777. ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
  11778. ** The caller is responsible for eventually calling sqlite3_free() on
  11779. ** any non-NULL (*pzWhere) value.
  11780. */
  11781. static void arWhereClause(
  11782. int *pRc,
  11783. ArCommand *pAr,
  11784. char **pzWhere /* OUT: New WHERE clause */
  11785. ){
  11786. char *zWhere = 0;
  11787. if( *pRc==SQLITE_OK ){
  11788. if( pAr->nArg==0 ){
  11789. zWhere = sqlite3_mprintf("1");
  11790. }else{
  11791. int i;
  11792. const char *zSep = "";
  11793. for(i=0; i<pAr->nArg; i++){
  11794. const char *z = pAr->azArg[i];
  11795. zWhere = sqlite3_mprintf(
  11796. "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
  11797. zWhere, zSep, z, strlen30(z)+1, z
  11798. );
  11799. if( zWhere==0 ){
  11800. *pRc = SQLITE_NOMEM;
  11801. break;
  11802. }
  11803. zSep = " OR ";
  11804. }
  11805. }
  11806. }
  11807. *pzWhere = zWhere;
  11808. }
  11809. /*
  11810. ** Implementation of .ar "lisT" command.
  11811. */
  11812. static int arListCommand(ArCommand *pAr){
  11813. const char *zSql = "SELECT %s FROM %s WHERE %s";
  11814. const char *azCols[] = {
  11815. "name",
  11816. "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
  11817. };
  11818. char *zWhere = 0;
  11819. sqlite3_stmt *pSql = 0;
  11820. int rc;
  11821. rc = arCheckEntries(pAr);
  11822. arWhereClause(&rc, pAr, &zWhere);
  11823. shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
  11824. pAr->zSrcTable, zWhere);
  11825. if( pAr->bDryRun ){
  11826. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  11827. }else{
  11828. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  11829. if( pAr->bVerbose ){
  11830. utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
  11831. sqlite3_column_text(pSql, 0),
  11832. sqlite3_column_int(pSql, 1),
  11833. sqlite3_column_text(pSql, 2),
  11834. sqlite3_column_text(pSql, 3)
  11835. );
  11836. }else{
  11837. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  11838. }
  11839. }
  11840. }
  11841. shellFinalize(&rc, pSql);
  11842. sqlite3_free(zWhere);
  11843. return rc;
  11844. }
  11845. /*
  11846. ** Implementation of .ar "eXtract" command.
  11847. */
  11848. static int arExtractCommand(ArCommand *pAr){
  11849. const char *zSql1 =
  11850. "SELECT "
  11851. " ($dir || name),"
  11852. " writefile(($dir || name), %s, mode, mtime) "
  11853. "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
  11854. " AND name NOT GLOB '*..[/\\]*'";
  11855. const char *azExtraArg[] = {
  11856. "sqlar_uncompress(data, sz)",
  11857. "data"
  11858. };
  11859. sqlite3_stmt *pSql = 0;
  11860. int rc = SQLITE_OK;
  11861. char *zDir = 0;
  11862. char *zWhere = 0;
  11863. int i, j;
  11864. /* If arguments are specified, check that they actually exist within
  11865. ** the archive before proceeding. And formulate a WHERE clause to
  11866. ** match them. */
  11867. rc = arCheckEntries(pAr);
  11868. arWhereClause(&rc, pAr, &zWhere);
  11869. if( rc==SQLITE_OK ){
  11870. if( pAr->zDir ){
  11871. zDir = sqlite3_mprintf("%s/", pAr->zDir);
  11872. }else{
  11873. zDir = sqlite3_mprintf("");
  11874. }
  11875. if( zDir==0 ) rc = SQLITE_NOMEM;
  11876. }
  11877. shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
  11878. azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
  11879. );
  11880. if( rc==SQLITE_OK ){
  11881. j = sqlite3_bind_parameter_index(pSql, "$dir");
  11882. sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
  11883. /* Run the SELECT statement twice. The first time, writefile() is called
  11884. ** for all archive members that should be extracted. The second time,
  11885. ** only for the directories. This is because the timestamps for
  11886. ** extracted directories must be reset after they are populated (as
  11887. ** populating them changes the timestamp). */
  11888. for(i=0; i<2; i++){
  11889. j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
  11890. sqlite3_bind_int(pSql, j, i);
  11891. if( pAr->bDryRun ){
  11892. utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
  11893. }else{
  11894. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
  11895. if( i==0 && pAr->bVerbose ){
  11896. utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
  11897. }
  11898. }
  11899. }
  11900. shellReset(&rc, pSql);
  11901. }
  11902. shellFinalize(&rc, pSql);
  11903. }
  11904. sqlite3_free(zDir);
  11905. sqlite3_free(zWhere);
  11906. return rc;
  11907. }
  11908. /*
  11909. ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
  11910. */
  11911. static int arExecSql(ArCommand *pAr, const char *zSql){
  11912. int rc;
  11913. if( pAr->bDryRun ){
  11914. utf8_printf(pAr->p->out, "%s\n", zSql);
  11915. rc = SQLITE_OK;
  11916. }else{
  11917. char *zErr = 0;
  11918. rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
  11919. if( zErr ){
  11920. utf8_printf(stdout, "ERROR: %s\n", zErr);
  11921. sqlite3_free(zErr);
  11922. }
  11923. }
  11924. return rc;
  11925. }
  11926. /*
  11927. ** Implementation of .ar "create" and "update" commands.
  11928. **
  11929. ** Create the "sqlar" table in the database if it does not already exist.
  11930. ** Then add each file in the azFile[] array to the archive. Directories
  11931. ** are added recursively. If argument bVerbose is non-zero, a message is
  11932. ** printed on stdout for each file archived.
  11933. **
  11934. ** The create command is the same as update, except that it drops
  11935. ** any existing "sqlar" table before beginning.
  11936. */
  11937. static int arCreateOrUpdateCommand(
  11938. ArCommand *pAr, /* Command arguments and options */
  11939. int bUpdate /* true for a --create. false for --update */
  11940. ){
  11941. const char *zCreate =
  11942. "CREATE TABLE IF NOT EXISTS sqlar(\n"
  11943. " name TEXT PRIMARY KEY, -- name of the file\n"
  11944. " mode INT, -- access permissions\n"
  11945. " mtime INT, -- last modification time\n"
  11946. " sz INT, -- original file size\n"
  11947. " data BLOB -- compressed content\n"
  11948. ")";
  11949. const char *zDrop = "DROP TABLE IF EXISTS sqlar";
  11950. const char *zInsertFmt[2] = {
  11951. "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
  11952. " SELECT\n"
  11953. " %s,\n"
  11954. " mode,\n"
  11955. " mtime,\n"
  11956. " CASE substr(lsmode(mode),1,1)\n"
  11957. " WHEN '-' THEN length(data)\n"
  11958. " WHEN 'd' THEN 0\n"
  11959. " ELSE -1 END,\n"
  11960. " sqlar_compress(data)\n"
  11961. " FROM fsdir(%Q,%Q)\n"
  11962. " WHERE lsmode(mode) NOT LIKE '?%%';",
  11963. "REPLACE INTO %s(name,mode,mtime,data)\n"
  11964. " SELECT\n"
  11965. " %s,\n"
  11966. " mode,\n"
  11967. " mtime,\n"
  11968. " data\n"
  11969. " FROM fsdir(%Q,%Q)\n"
  11970. " WHERE lsmode(mode) NOT LIKE '?%%';"
  11971. };
  11972. int i; /* For iterating through azFile[] */
  11973. int rc; /* Return code */
  11974. const char *zTab = 0; /* SQL table into which to insert */
  11975. char *zSql;
  11976. char zTemp[50];
  11977. arExecSql(pAr, "PRAGMA page_size=512");
  11978. rc = arExecSql(pAr, "SAVEPOINT ar;");
  11979. if( rc!=SQLITE_OK ) return rc;
  11980. zTemp[0] = 0;
  11981. if( pAr->bZip ){
  11982. /* Initialize the zipfile virtual table, if necessary */
  11983. if( pAr->zFile ){
  11984. sqlite3_uint64 r;
  11985. sqlite3_randomness(sizeof(r),&r);
  11986. sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
  11987. zTab = zTemp;
  11988. zSql = sqlite3_mprintf(
  11989. "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
  11990. zTab, pAr->zFile
  11991. );
  11992. rc = arExecSql(pAr, zSql);
  11993. sqlite3_free(zSql);
  11994. }else{
  11995. zTab = "zip";
  11996. }
  11997. }else{
  11998. /* Initialize the table for an SQLAR */
  11999. zTab = "sqlar";
  12000. if( bUpdate==0 ){
  12001. rc = arExecSql(pAr, zDrop);
  12002. if( rc!=SQLITE_OK ) goto end_ar_transaction;
  12003. }
  12004. rc = arExecSql(pAr, zCreate);
  12005. }
  12006. for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
  12007. char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
  12008. pAr->bVerbose ? "shell_putsnl(name)" : "name",
  12009. pAr->azArg[i], pAr->zDir);
  12010. rc = arExecSql(pAr, zSql2);
  12011. sqlite3_free(zSql2);
  12012. }
  12013. end_ar_transaction:
  12014. if( rc!=SQLITE_OK ){
  12015. arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
  12016. }else{
  12017. rc = arExecSql(pAr, "RELEASE ar;");
  12018. if( pAr->bZip && pAr->zFile ){
  12019. zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
  12020. arExecSql(pAr, zSql);
  12021. sqlite3_free(zSql);
  12022. }
  12023. }
  12024. return rc;
  12025. }
  12026. /*
  12027. ** Implementation of ".ar" dot command.
  12028. */
  12029. static int arDotCommand(
  12030. ShellState *pState, /* Current shell tool state */
  12031. int fromCmdLine, /* True if -A command-line option, not .ar cmd */
  12032. char **azArg, /* Array of arguments passed to dot command */
  12033. int nArg /* Number of entries in azArg[] */
  12034. ){
  12035. ArCommand cmd;
  12036. int rc;
  12037. memset(&cmd, 0, sizeof(cmd));
  12038. cmd.fromCmdLine = fromCmdLine;
  12039. rc = arParseCommand(azArg, nArg, &cmd);
  12040. if( rc==SQLITE_OK ){
  12041. int eDbType = SHELL_OPEN_UNSPEC;
  12042. cmd.p = pState;
  12043. cmd.db = pState->db;
  12044. if( cmd.zFile ){
  12045. eDbType = deduceDatabaseType(cmd.zFile, 1);
  12046. }else{
  12047. eDbType = pState->openMode;
  12048. }
  12049. if( eDbType==SHELL_OPEN_ZIPFILE ){
  12050. if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
  12051. if( cmd.zFile==0 ){
  12052. cmd.zSrcTable = sqlite3_mprintf("zip");
  12053. }else{
  12054. cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
  12055. }
  12056. }
  12057. cmd.bZip = 1;
  12058. }else if( cmd.zFile ){
  12059. int flags;
  12060. if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
  12061. if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
  12062. flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  12063. }else{
  12064. flags = SQLITE_OPEN_READONLY;
  12065. }
  12066. cmd.db = 0;
  12067. if( cmd.bDryRun ){
  12068. utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
  12069. eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
  12070. }
  12071. rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
  12072. eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
  12073. if( rc!=SQLITE_OK ){
  12074. utf8_printf(stderr, "cannot open file: %s (%s)\n",
  12075. cmd.zFile, sqlite3_errmsg(cmd.db)
  12076. );
  12077. goto end_ar_command;
  12078. }
  12079. sqlite3_fileio_init(cmd.db, 0, 0);
  12080. sqlite3_sqlar_init(cmd.db, 0, 0);
  12081. sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
  12082. shellPutsFunc, 0, 0);
  12083. }
  12084. if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
  12085. if( cmd.eCmd!=AR_CMD_CREATE
  12086. && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
  12087. ){
  12088. utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
  12089. rc = SQLITE_ERROR;
  12090. goto end_ar_command;
  12091. }
  12092. cmd.zSrcTable = sqlite3_mprintf("sqlar");
  12093. }
  12094. switch( cmd.eCmd ){
  12095. case AR_CMD_CREATE:
  12096. rc = arCreateOrUpdateCommand(&cmd, 0);
  12097. break;
  12098. case AR_CMD_EXTRACT:
  12099. rc = arExtractCommand(&cmd);
  12100. break;
  12101. case AR_CMD_LIST:
  12102. rc = arListCommand(&cmd);
  12103. break;
  12104. case AR_CMD_HELP:
  12105. arUsage(pState->out);
  12106. break;
  12107. default:
  12108. assert( cmd.eCmd==AR_CMD_UPDATE );
  12109. rc = arCreateOrUpdateCommand(&cmd, 1);
  12110. break;
  12111. }
  12112. }
  12113. end_ar_command:
  12114. if( cmd.db!=pState->db ){
  12115. close_db(cmd.db);
  12116. }
  12117. sqlite3_free(cmd.zSrcTable);
  12118. return rc;
  12119. }
  12120. /* End of the ".archive" or ".ar" command logic
  12121. **********************************************************************************/
  12122. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
  12123. /*
  12124. ** If an input line begins with "." then invoke this routine to
  12125. ** process that line.
  12126. **
  12127. ** Return 1 on error, 2 to exit, and 0 otherwise.
  12128. */
  12129. static int do_meta_command(char *zLine, ShellState *p){
  12130. int h = 1;
  12131. int nArg = 0;
  12132. int n, c;
  12133. int rc = 0;
  12134. char *azArg[50];
  12135. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12136. if( p->expert.pExpert ){
  12137. expertFinish(p, 1, 0);
  12138. }
  12139. #endif
  12140. /* Parse the input line into tokens.
  12141. */
  12142. while( zLine[h] && nArg<ArraySize(azArg) ){
  12143. while( IsSpace(zLine[h]) ){ h++; }
  12144. if( zLine[h]==0 ) break;
  12145. if( zLine[h]=='\'' || zLine[h]=='"' ){
  12146. int delim = zLine[h++];
  12147. azArg[nArg++] = &zLine[h];
  12148. while( zLine[h] && zLine[h]!=delim ){
  12149. if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  12150. h++;
  12151. }
  12152. if( zLine[h]==delim ){
  12153. zLine[h++] = 0;
  12154. }
  12155. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  12156. }else{
  12157. azArg[nArg++] = &zLine[h];
  12158. while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  12159. if( zLine[h] ) zLine[h++] = 0;
  12160. resolve_backslashes(azArg[nArg-1]);
  12161. }
  12162. }
  12163. /* Process the input line.
  12164. */
  12165. if( nArg==0 ) return 0; /* no tokens, no error */
  12166. n = strlen30(azArg[0]);
  12167. c = azArg[0][0];
  12168. clearTempFile(p);
  12169. #ifndef SQLITE_OMIT_AUTHORIZATION
  12170. if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  12171. if( nArg!=2 ){
  12172. raw_printf(stderr, "Usage: .auth ON|OFF\n");
  12173. rc = 1;
  12174. goto meta_command_exit;
  12175. }
  12176. open_db(p, 0);
  12177. if( booleanValue(azArg[1]) ){
  12178. sqlite3_set_authorizer(p->db, shellAuth, p);
  12179. }else{
  12180. sqlite3_set_authorizer(p->db, 0, 0);
  12181. }
  12182. }else
  12183. #endif
  12184. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  12185. if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
  12186. open_db(p, 0);
  12187. rc = arDotCommand(p, 0, azArg, nArg);
  12188. }else
  12189. #endif
  12190. if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  12191. || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  12192. ){
  12193. const char *zDestFile = 0;
  12194. const char *zDb = 0;
  12195. sqlite3 *pDest;
  12196. sqlite3_backup *pBackup;
  12197. int j;
  12198. const char *zVfs = 0;
  12199. for(j=1; j<nArg; j++){
  12200. const char *z = azArg[j];
  12201. if( z[0]=='-' ){
  12202. if( z[1]=='-' ) z++;
  12203. if( strcmp(z, "-append")==0 ){
  12204. zVfs = "apndvfs";
  12205. }else
  12206. {
  12207. utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  12208. return 1;
  12209. }
  12210. }else if( zDestFile==0 ){
  12211. zDestFile = azArg[j];
  12212. }else if( zDb==0 ){
  12213. zDb = zDestFile;
  12214. zDestFile = azArg[j];
  12215. }else{
  12216. raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
  12217. return 1;
  12218. }
  12219. }
  12220. if( zDestFile==0 ){
  12221. raw_printf(stderr, "missing FILENAME argument on .backup\n");
  12222. return 1;
  12223. }
  12224. if( zDb==0 ) zDb = "main";
  12225. rc = sqlite3_open_v2(zDestFile, &pDest,
  12226. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
  12227. if( rc!=SQLITE_OK ){
  12228. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  12229. close_db(pDest);
  12230. return 1;
  12231. }
  12232. open_db(p, 0);
  12233. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  12234. if( pBackup==0 ){
  12235. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  12236. close_db(pDest);
  12237. return 1;
  12238. }
  12239. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  12240. sqlite3_backup_finish(pBackup);
  12241. if( rc==SQLITE_DONE ){
  12242. rc = 0;
  12243. }else{
  12244. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  12245. rc = 1;
  12246. }
  12247. close_db(pDest);
  12248. }else
  12249. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  12250. if( nArg==2 ){
  12251. bail_on_error = booleanValue(azArg[1]);
  12252. }else{
  12253. raw_printf(stderr, "Usage: .bail on|off\n");
  12254. rc = 1;
  12255. }
  12256. }else
  12257. if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  12258. if( nArg==2 ){
  12259. if( booleanValue(azArg[1]) ){
  12260. setBinaryMode(p->out, 1);
  12261. }else{
  12262. setTextMode(p->out, 1);
  12263. }
  12264. }else{
  12265. raw_printf(stderr, "Usage: .binary on|off\n");
  12266. rc = 1;
  12267. }
  12268. }else
  12269. if( c=='c' && strcmp(azArg[0],"cd")==0 ){
  12270. if( nArg==2 ){
  12271. #if defined(_WIN32) || defined(WIN32)
  12272. wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  12273. rc = !SetCurrentDirectoryW(z);
  12274. sqlite3_free(z);
  12275. #else
  12276. rc = chdir(azArg[1]);
  12277. #endif
  12278. if( rc ){
  12279. utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  12280. rc = 1;
  12281. }
  12282. }else{
  12283. raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  12284. rc = 1;
  12285. }
  12286. }else
  12287. /* The undocumented ".breakpoint" command causes a call to the no-op
  12288. ** routine named test_breakpoint().
  12289. */
  12290. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  12291. test_breakpoint();
  12292. }else
  12293. if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  12294. if( nArg==2 ){
  12295. setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  12296. }else{
  12297. raw_printf(stderr, "Usage: .changes on|off\n");
  12298. rc = 1;
  12299. }
  12300. }else
  12301. /* Cancel output redirection, if it is currently set (by .testcase)
  12302. ** Then read the content of the testcase-out.txt file and compare against
  12303. ** azArg[1]. If there are differences, report an error and exit.
  12304. */
  12305. if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  12306. char *zRes = 0;
  12307. output_reset(p);
  12308. if( nArg!=2 ){
  12309. raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  12310. rc = 2;
  12311. }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  12312. raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  12313. rc = 2;
  12314. }else if( testcase_glob(azArg[1],zRes)==0 ){
  12315. utf8_printf(stderr,
  12316. "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
  12317. p->zTestcase, azArg[1], zRes);
  12318. rc = 1;
  12319. }else{
  12320. utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  12321. p->nCheck++;
  12322. }
  12323. sqlite3_free(zRes);
  12324. }else
  12325. if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  12326. if( nArg==2 ){
  12327. tryToClone(p, azArg[1]);
  12328. }else{
  12329. raw_printf(stderr, "Usage: .clone FILENAME\n");
  12330. rc = 1;
  12331. }
  12332. }else
  12333. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  12334. ShellState data;
  12335. char *zErrMsg = 0;
  12336. open_db(p, 0);
  12337. memcpy(&data, p, sizeof(data));
  12338. data.showHeader = 0;
  12339. data.cMode = data.mode = MODE_List;
  12340. sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
  12341. data.cnt = 0;
  12342. sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
  12343. callback, &data, &zErrMsg);
  12344. if( zErrMsg ){
  12345. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  12346. sqlite3_free(zErrMsg);
  12347. rc = 1;
  12348. }
  12349. }else
  12350. if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
  12351. static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
  12352. { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
  12353. { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
  12354. { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
  12355. { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
  12356. { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
  12357. { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
  12358. { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
  12359. { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
  12360. };
  12361. int ii, v;
  12362. open_db(p, 0);
  12363. for(ii=0; ii<ArraySize(aDbConfig); ii++){
  12364. if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
  12365. if( nArg>=3 ){
  12366. sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
  12367. }
  12368. sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
  12369. utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
  12370. if( nArg>1 ) break;
  12371. }
  12372. if( nArg>1 && ii==ArraySize(aDbConfig) ){
  12373. utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
  12374. utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
  12375. }
  12376. }else
  12377. if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
  12378. rc = shell_dbinfo_command(p, nArg, azArg);
  12379. }else
  12380. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  12381. const char *zLike = 0;
  12382. int i;
  12383. int savedShowHeader = p->showHeader;
  12384. int savedShellFlags = p->shellFlgs;
  12385. ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
  12386. for(i=1; i<nArg; i++){
  12387. if( azArg[i][0]=='-' ){
  12388. const char *z = azArg[i]+1;
  12389. if( z[0]=='-' ) z++;
  12390. if( strcmp(z,"preserve-rowids")==0 ){
  12391. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12392. raw_printf(stderr, "The --preserve-rowids option is not compatible"
  12393. " with SQLITE_OMIT_VIRTUALTABLE\n");
  12394. rc = 1;
  12395. goto meta_command_exit;
  12396. #else
  12397. ShellSetFlag(p, SHFLG_PreserveRowid);
  12398. #endif
  12399. }else
  12400. if( strcmp(z,"newlines")==0 ){
  12401. ShellSetFlag(p, SHFLG_Newlines);
  12402. }else
  12403. {
  12404. raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  12405. rc = 1;
  12406. goto meta_command_exit;
  12407. }
  12408. }else if( zLike ){
  12409. raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
  12410. "?--newlines? ?LIKE-PATTERN?\n");
  12411. rc = 1;
  12412. goto meta_command_exit;
  12413. }else{
  12414. zLike = azArg[i];
  12415. }
  12416. }
  12417. open_db(p, 0);
  12418. /* When playing back a "dump", the content might appear in an order
  12419. ** which causes immediate foreign key constraints to be violated.
  12420. ** So disable foreign-key constraint enforcement to prevent problems. */
  12421. raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  12422. raw_printf(p->out, "BEGIN TRANSACTION;\n");
  12423. p->writableSchema = 0;
  12424. p->showHeader = 0;
  12425. /* Set writable_schema=ON since doing so forces SQLite to initialize
  12426. ** as much of the schema as it can even if the sqlite_master table is
  12427. ** corrupt. */
  12428. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  12429. p->nErr = 0;
  12430. if( zLike==0 ){
  12431. run_schema_dump_query(p,
  12432. "SELECT name, type, sql FROM sqlite_master "
  12433. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  12434. );
  12435. run_schema_dump_query(p,
  12436. "SELECT name, type, sql FROM sqlite_master "
  12437. "WHERE name=='sqlite_sequence'"
  12438. );
  12439. run_table_dump_query(p,
  12440. "SELECT sql FROM sqlite_master "
  12441. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  12442. );
  12443. }else{
  12444. char *zSql;
  12445. zSql = sqlite3_mprintf(
  12446. "SELECT name, type, sql FROM sqlite_master "
  12447. "WHERE tbl_name LIKE %Q AND type=='table'"
  12448. " AND sql NOT NULL", zLike);
  12449. run_schema_dump_query(p,zSql);
  12450. sqlite3_free(zSql);
  12451. zSql = sqlite3_mprintf(
  12452. "SELECT sql FROM sqlite_master "
  12453. "WHERE sql NOT NULL"
  12454. " AND type IN ('index','trigger','view')"
  12455. " AND tbl_name LIKE %Q", zLike);
  12456. run_table_dump_query(p, zSql, 0);
  12457. sqlite3_free(zSql);
  12458. }
  12459. if( p->writableSchema ){
  12460. raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  12461. p->writableSchema = 0;
  12462. }
  12463. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  12464. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  12465. raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  12466. p->showHeader = savedShowHeader;
  12467. p->shellFlgs = savedShellFlags;
  12468. }else
  12469. if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  12470. if( nArg==2 ){
  12471. setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  12472. }else{
  12473. raw_printf(stderr, "Usage: .echo on|off\n");
  12474. rc = 1;
  12475. }
  12476. }else
  12477. if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  12478. if( nArg==2 ){
  12479. p->autoEQPtest = 0;
  12480. if( strcmp(azArg[1],"full")==0 ){
  12481. p->autoEQP = AUTOEQP_full;
  12482. }else if( strcmp(azArg[1],"trigger")==0 ){
  12483. p->autoEQP = AUTOEQP_trigger;
  12484. }else if( strcmp(azArg[1],"test")==0 ){
  12485. p->autoEQP = AUTOEQP_on;
  12486. p->autoEQPtest = 1;
  12487. }else{
  12488. p->autoEQP = (u8)booleanValue(azArg[1]);
  12489. }
  12490. }else{
  12491. raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
  12492. rc = 1;
  12493. }
  12494. }else
  12495. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  12496. if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  12497. rc = 2;
  12498. }else
  12499. /* The ".explain" command is automatic now. It is largely pointless. It
  12500. ** retained purely for backwards compatibility */
  12501. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  12502. int val = 1;
  12503. if( nArg>=2 ){
  12504. if( strcmp(azArg[1],"auto")==0 ){
  12505. val = 99;
  12506. }else{
  12507. val = booleanValue(azArg[1]);
  12508. }
  12509. }
  12510. if( val==1 && p->mode!=MODE_Explain ){
  12511. p->normalMode = p->mode;
  12512. p->mode = MODE_Explain;
  12513. p->autoExplain = 0;
  12514. }else if( val==0 ){
  12515. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  12516. p->autoExplain = 0;
  12517. }else if( val==99 ){
  12518. if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  12519. p->autoExplain = 1;
  12520. }
  12521. }else
  12522. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12523. if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
  12524. open_db(p, 0);
  12525. expertDotCommand(p, azArg, nArg);
  12526. }else
  12527. #endif
  12528. if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  12529. ShellState data;
  12530. char *zErrMsg = 0;
  12531. int doStats = 0;
  12532. memcpy(&data, p, sizeof(data));
  12533. data.showHeader = 0;
  12534. data.cMode = data.mode = MODE_Semi;
  12535. if( nArg==2 && optionMatch(azArg[1], "indent") ){
  12536. data.cMode = data.mode = MODE_Pretty;
  12537. nArg = 1;
  12538. }
  12539. if( nArg!=1 ){
  12540. raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  12541. rc = 1;
  12542. goto meta_command_exit;
  12543. }
  12544. open_db(p, 0);
  12545. rc = sqlite3_exec(p->db,
  12546. "SELECT sql FROM"
  12547. " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  12548. " FROM sqlite_master UNION ALL"
  12549. " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  12550. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  12551. "ORDER BY rowid",
  12552. callback, &data, &zErrMsg
  12553. );
  12554. if( rc==SQLITE_OK ){
  12555. sqlite3_stmt *pStmt;
  12556. rc = sqlite3_prepare_v2(p->db,
  12557. "SELECT rowid FROM sqlite_master"
  12558. " WHERE name GLOB 'sqlite_stat[134]'",
  12559. -1, &pStmt, 0);
  12560. doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  12561. sqlite3_finalize(pStmt);
  12562. }
  12563. if( doStats==0 ){
  12564. raw_printf(p->out, "/* No STAT tables available */\n");
  12565. }else{
  12566. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  12567. sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  12568. callback, &data, &zErrMsg);
  12569. data.cMode = data.mode = MODE_Insert;
  12570. data.zDestTable = "sqlite_stat1";
  12571. shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
  12572. data.zDestTable = "sqlite_stat3";
  12573. shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
  12574. data.zDestTable = "sqlite_stat4";
  12575. shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
  12576. raw_printf(p->out, "ANALYZE sqlite_master;\n");
  12577. }
  12578. }else
  12579. if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  12580. if( nArg==2 ){
  12581. p->showHeader = booleanValue(azArg[1]);
  12582. }else{
  12583. raw_printf(stderr, "Usage: .headers on|off\n");
  12584. rc = 1;
  12585. }
  12586. }else
  12587. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  12588. utf8_printf(p->out, "%s", zHelp);
  12589. }else
  12590. if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  12591. char *zTable; /* Insert data into this table */
  12592. char *zFile; /* Name of file to extra content from */
  12593. sqlite3_stmt *pStmt = NULL; /* A statement */
  12594. int nCol; /* Number of columns in the table */
  12595. int nByte; /* Number of bytes in an SQL string */
  12596. int i, j; /* Loop counters */
  12597. int needCommit; /* True to COMMIT or ROLLBACK at end */
  12598. int nSep; /* Number of bytes in p->colSeparator[] */
  12599. char *zSql; /* An SQL statement */
  12600. ImportCtx sCtx; /* Reader context */
  12601. char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  12602. int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
  12603. if( nArg!=3 ){
  12604. raw_printf(stderr, "Usage: .import FILE TABLE\n");
  12605. goto meta_command_exit;
  12606. }
  12607. zFile = azArg[1];
  12608. zTable = azArg[2];
  12609. seenInterrupt = 0;
  12610. memset(&sCtx, 0, sizeof(sCtx));
  12611. open_db(p, 0);
  12612. nSep = strlen30(p->colSeparator);
  12613. if( nSep==0 ){
  12614. raw_printf(stderr,
  12615. "Error: non-null column separator required for import\n");
  12616. return 1;
  12617. }
  12618. if( nSep>1 ){
  12619. raw_printf(stderr, "Error: multi-character column separators not allowed"
  12620. " for import\n");
  12621. return 1;
  12622. }
  12623. nSep = strlen30(p->rowSeparator);
  12624. if( nSep==0 ){
  12625. raw_printf(stderr, "Error: non-null row separator required for import\n");
  12626. return 1;
  12627. }
  12628. if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  12629. /* When importing CSV (only), if the row separator is set to the
  12630. ** default output row separator, change it to the default input
  12631. ** row separator. This avoids having to maintain different input
  12632. ** and output row separators. */
  12633. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  12634. nSep = strlen30(p->rowSeparator);
  12635. }
  12636. if( nSep>1 ){
  12637. raw_printf(stderr, "Error: multi-character row separators not allowed"
  12638. " for import\n");
  12639. return 1;
  12640. }
  12641. sCtx.zFile = zFile;
  12642. sCtx.nLine = 1;
  12643. if( sCtx.zFile[0]=='|' ){
  12644. #ifdef SQLITE_OMIT_POPEN
  12645. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  12646. return 1;
  12647. #else
  12648. sCtx.in = popen(sCtx.zFile+1, "r");
  12649. sCtx.zFile = "<pipe>";
  12650. xCloser = pclose;
  12651. #endif
  12652. }else{
  12653. sCtx.in = fopen(sCtx.zFile, "rb");
  12654. xCloser = fclose;
  12655. }
  12656. if( p->mode==MODE_Ascii ){
  12657. xRead = ascii_read_one_field;
  12658. }else{
  12659. xRead = csv_read_one_field;
  12660. }
  12661. if( sCtx.in==0 ){
  12662. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  12663. return 1;
  12664. }
  12665. sCtx.cColSep = p->colSeparator[0];
  12666. sCtx.cRowSep = p->rowSeparator[0];
  12667. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  12668. if( zSql==0 ){
  12669. xCloser(sCtx.in);
  12670. shell_out_of_memory();
  12671. }
  12672. nByte = strlen30(zSql);
  12673. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12674. import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
  12675. if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  12676. char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  12677. char cSep = '(';
  12678. while( xRead(&sCtx) ){
  12679. zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
  12680. cSep = ',';
  12681. if( sCtx.cTerm!=sCtx.cColSep ) break;
  12682. }
  12683. if( cSep=='(' ){
  12684. sqlite3_free(zCreate);
  12685. sqlite3_free(sCtx.z);
  12686. xCloser(sCtx.in);
  12687. utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  12688. return 1;
  12689. }
  12690. zCreate = sqlite3_mprintf("%z\n)", zCreate);
  12691. rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  12692. sqlite3_free(zCreate);
  12693. if( rc ){
  12694. utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  12695. sqlite3_errmsg(p->db));
  12696. sqlite3_free(sCtx.z);
  12697. xCloser(sCtx.in);
  12698. return 1;
  12699. }
  12700. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12701. }
  12702. sqlite3_free(zSql);
  12703. if( rc ){
  12704. if (pStmt) sqlite3_finalize(pStmt);
  12705. utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  12706. xCloser(sCtx.in);
  12707. return 1;
  12708. }
  12709. nCol = sqlite3_column_count(pStmt);
  12710. sqlite3_finalize(pStmt);
  12711. pStmt = 0;
  12712. if( nCol==0 ) return 0; /* no columns, no error */
  12713. zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  12714. if( zSql==0 ){
  12715. xCloser(sCtx.in);
  12716. shell_out_of_memory();
  12717. }
  12718. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  12719. j = strlen30(zSql);
  12720. for(i=1; i<nCol; i++){
  12721. zSql[j++] = ',';
  12722. zSql[j++] = '?';
  12723. }
  12724. zSql[j++] = ')';
  12725. zSql[j] = 0;
  12726. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12727. sqlite3_free(zSql);
  12728. if( rc ){
  12729. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  12730. if (pStmt) sqlite3_finalize(pStmt);
  12731. xCloser(sCtx.in);
  12732. return 1;
  12733. }
  12734. needCommit = sqlite3_get_autocommit(p->db);
  12735. if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  12736. do{
  12737. int startLine = sCtx.nLine;
  12738. for(i=0; i<nCol; i++){
  12739. char *z = xRead(&sCtx);
  12740. /*
  12741. ** Did we reach end-of-file before finding any columns?
  12742. ** If so, stop instead of NULL filling the remaining columns.
  12743. */
  12744. if( z==0 && i==0 ) break;
  12745. /*
  12746. ** Did we reach end-of-file OR end-of-line before finding any
  12747. ** columns in ASCII mode? If so, stop instead of NULL filling
  12748. ** the remaining columns.
  12749. */
  12750. if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  12751. sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  12752. if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  12753. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  12754. "filling the rest with NULL\n",
  12755. sCtx.zFile, startLine, nCol, i+1);
  12756. i += 2;
  12757. while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  12758. }
  12759. }
  12760. if( sCtx.cTerm==sCtx.cColSep ){
  12761. do{
  12762. xRead(&sCtx);
  12763. i++;
  12764. }while( sCtx.cTerm==sCtx.cColSep );
  12765. utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  12766. "extras ignored\n",
  12767. sCtx.zFile, startLine, nCol, i);
  12768. }
  12769. if( i>=nCol ){
  12770. sqlite3_step(pStmt);
  12771. rc = sqlite3_reset(pStmt);
  12772. if( rc!=SQLITE_OK ){
  12773. utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  12774. startLine, sqlite3_errmsg(p->db));
  12775. }
  12776. }
  12777. }while( sCtx.cTerm!=EOF );
  12778. xCloser(sCtx.in);
  12779. sqlite3_free(sCtx.z);
  12780. sqlite3_finalize(pStmt);
  12781. if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  12782. }else
  12783. #ifndef SQLITE_UNTESTABLE
  12784. if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
  12785. char *zSql;
  12786. char *zCollist = 0;
  12787. sqlite3_stmt *pStmt;
  12788. int tnum = 0;
  12789. int i;
  12790. if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
  12791. utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
  12792. " .imposter off\n");
  12793. rc = 1;
  12794. goto meta_command_exit;
  12795. }
  12796. open_db(p, 0);
  12797. if( nArg==2 ){
  12798. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
  12799. goto meta_command_exit;
  12800. }
  12801. zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
  12802. " WHERE name='%q' AND type='index'", azArg[1]);
  12803. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12804. sqlite3_free(zSql);
  12805. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  12806. tnum = sqlite3_column_int(pStmt, 0);
  12807. }
  12808. sqlite3_finalize(pStmt);
  12809. if( tnum==0 ){
  12810. utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  12811. rc = 1;
  12812. goto meta_command_exit;
  12813. }
  12814. zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  12815. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  12816. sqlite3_free(zSql);
  12817. i = 0;
  12818. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  12819. char zLabel[20];
  12820. const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  12821. i++;
  12822. if( zCol==0 ){
  12823. if( sqlite3_column_int(pStmt,1)==-1 ){
  12824. zCol = "_ROWID_";
  12825. }else{
  12826. sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  12827. zCol = zLabel;
  12828. }
  12829. }
  12830. if( zCollist==0 ){
  12831. zCollist = sqlite3_mprintf("\"%w\"", zCol);
  12832. }else{
  12833. zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  12834. }
  12835. }
  12836. sqlite3_finalize(pStmt);
  12837. zSql = sqlite3_mprintf(
  12838. "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
  12839. azArg[2], zCollist, zCollist);
  12840. sqlite3_free(zCollist);
  12841. rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  12842. if( rc==SQLITE_OK ){
  12843. rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  12844. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  12845. if( rc ){
  12846. utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  12847. }else{
  12848. utf8_printf(stdout, "%s;\n", zSql);
  12849. raw_printf(stdout,
  12850. "WARNING: writing to an imposter table will corrupt the index!\n"
  12851. );
  12852. }
  12853. }else{
  12854. raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  12855. rc = 1;
  12856. }
  12857. sqlite3_free(zSql);
  12858. }else
  12859. #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  12860. #ifdef SQLITE_ENABLE_IOTRACE
  12861. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  12862. SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  12863. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  12864. iotrace = 0;
  12865. if( nArg<2 ){
  12866. sqlite3IoTrace = 0;
  12867. }else if( strcmp(azArg[1], "-")==0 ){
  12868. sqlite3IoTrace = iotracePrintf;
  12869. iotrace = stdout;
  12870. }else{
  12871. iotrace = fopen(azArg[1], "w");
  12872. if( iotrace==0 ){
  12873. utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  12874. sqlite3IoTrace = 0;
  12875. rc = 1;
  12876. }else{
  12877. sqlite3IoTrace = iotracePrintf;
  12878. }
  12879. }
  12880. }else
  12881. #endif
  12882. if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  12883. static const struct {
  12884. const char *zLimitName; /* Name of a limit */
  12885. int limitCode; /* Integer code for that limit */
  12886. } aLimit[] = {
  12887. { "length", SQLITE_LIMIT_LENGTH },
  12888. { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
  12889. { "column", SQLITE_LIMIT_COLUMN },
  12890. { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
  12891. { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
  12892. { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
  12893. { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
  12894. { "attached", SQLITE_LIMIT_ATTACHED },
  12895. { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
  12896. { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
  12897. { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
  12898. { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
  12899. };
  12900. int i, n2;
  12901. open_db(p, 0);
  12902. if( nArg==1 ){
  12903. for(i=0; i<ArraySize(aLimit); i++){
  12904. printf("%20s %d\n", aLimit[i].zLimitName,
  12905. sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  12906. }
  12907. }else if( nArg>3 ){
  12908. raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  12909. rc = 1;
  12910. goto meta_command_exit;
  12911. }else{
  12912. int iLimit = -1;
  12913. n2 = strlen30(azArg[1]);
  12914. for(i=0; i<ArraySize(aLimit); i++){
  12915. if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  12916. if( iLimit<0 ){
  12917. iLimit = i;
  12918. }else{
  12919. utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  12920. rc = 1;
  12921. goto meta_command_exit;
  12922. }
  12923. }
  12924. }
  12925. if( iLimit<0 ){
  12926. utf8_printf(stderr, "unknown limit: \"%s\"\n"
  12927. "enter \".limits\" with no arguments for a list.\n",
  12928. azArg[1]);
  12929. rc = 1;
  12930. goto meta_command_exit;
  12931. }
  12932. if( nArg==3 ){
  12933. sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  12934. (int)integerValue(azArg[2]));
  12935. }
  12936. printf("%20s %d\n", aLimit[iLimit].zLimitName,
  12937. sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  12938. }
  12939. }else
  12940. if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
  12941. open_db(p, 0);
  12942. lintDotCommand(p, azArg, nArg);
  12943. }else
  12944. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  12945. if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  12946. const char *zFile, *zProc;
  12947. char *zErrMsg = 0;
  12948. if( nArg<2 ){
  12949. raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  12950. rc = 1;
  12951. goto meta_command_exit;
  12952. }
  12953. zFile = azArg[1];
  12954. zProc = nArg>=3 ? azArg[2] : 0;
  12955. open_db(p, 0);
  12956. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  12957. if( rc!=SQLITE_OK ){
  12958. utf8_printf(stderr, "Error: %s\n", zErrMsg);
  12959. sqlite3_free(zErrMsg);
  12960. rc = 1;
  12961. }
  12962. }else
  12963. #endif
  12964. if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  12965. if( nArg!=2 ){
  12966. raw_printf(stderr, "Usage: .log FILENAME\n");
  12967. rc = 1;
  12968. }else{
  12969. const char *zFile = azArg[1];
  12970. output_file_close(p->pLog);
  12971. p->pLog = output_file_open(zFile, 0);
  12972. }
  12973. }else
  12974. if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  12975. const char *zMode = nArg>=2 ? azArg[1] : "";
  12976. int n2 = strlen30(zMode);
  12977. int c2 = zMode[0];
  12978. if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  12979. p->mode = MODE_Line;
  12980. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  12981. }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  12982. p->mode = MODE_Column;
  12983. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  12984. }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  12985. p->mode = MODE_List;
  12986. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  12987. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  12988. }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  12989. p->mode = MODE_Html;
  12990. }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  12991. p->mode = MODE_Tcl;
  12992. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  12993. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  12994. }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  12995. p->mode = MODE_Csv;
  12996. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  12997. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  12998. }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  12999. p->mode = MODE_List;
  13000. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  13001. }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  13002. p->mode = MODE_Insert;
  13003. set_table_name(p, nArg>=3 ? azArg[2] : "table");
  13004. }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
  13005. p->mode = MODE_Quote;
  13006. }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  13007. p->mode = MODE_Ascii;
  13008. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  13009. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  13010. }else if( nArg==1 ){
  13011. raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  13012. }else{
  13013. raw_printf(stderr, "Error: mode should be one of: "
  13014. "ascii column csv html insert line list quote tabs tcl\n");
  13015. rc = 1;
  13016. }
  13017. p->cMode = p->mode;
  13018. }else
  13019. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  13020. if( nArg==2 ){
  13021. sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  13022. "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  13023. }else{
  13024. raw_printf(stderr, "Usage: .nullvalue STRING\n");
  13025. rc = 1;
  13026. }
  13027. }else
  13028. if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  13029. char *zNewFilename; /* Name of the database file to open */
  13030. int iName = 1; /* Index in azArg[] of the filename */
  13031. int newFlag = 0; /* True to delete file before opening */
  13032. /* Close the existing database */
  13033. session_close_all(p);
  13034. close_db(p->db);
  13035. p->db = 0;
  13036. p->zDbFilename = 0;
  13037. sqlite3_free(p->zFreeOnClose);
  13038. p->zFreeOnClose = 0;
  13039. p->openMode = SHELL_OPEN_UNSPEC;
  13040. /* Check for command-line arguments */
  13041. for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  13042. const char *z = azArg[iName];
  13043. if( optionMatch(z,"new") ){
  13044. newFlag = 1;
  13045. #ifdef SQLITE_HAVE_ZLIB
  13046. }else if( optionMatch(z, "zip") ){
  13047. p->openMode = SHELL_OPEN_ZIPFILE;
  13048. #endif
  13049. }else if( optionMatch(z, "append") ){
  13050. p->openMode = SHELL_OPEN_APPENDVFS;
  13051. }else if( optionMatch(z, "readonly") ){
  13052. p->openMode = SHELL_OPEN_READONLY;
  13053. }else if( z[0]=='-' ){
  13054. utf8_printf(stderr, "unknown option: %s\n", z);
  13055. rc = 1;
  13056. goto meta_command_exit;
  13057. }
  13058. }
  13059. /* If a filename is specified, try to open it first */
  13060. zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  13061. if( zNewFilename ){
  13062. if( newFlag ) shellDeleteFile(zNewFilename);
  13063. p->zDbFilename = zNewFilename;
  13064. open_db(p, OPEN_DB_KEEPALIVE);
  13065. if( p->db==0 ){
  13066. utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  13067. sqlite3_free(zNewFilename);
  13068. }else{
  13069. p->zFreeOnClose = zNewFilename;
  13070. }
  13071. }
  13072. if( p->db==0 ){
  13073. /* As a fall-back open a TEMP database */
  13074. p->zDbFilename = 0;
  13075. open_db(p, 0);
  13076. }
  13077. }else
  13078. if( (c=='o'
  13079. && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
  13080. || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
  13081. ){
  13082. const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  13083. int bTxtMode = 0;
  13084. if( azArg[0][0]=='e' ){
  13085. /* Transform the ".excel" command into ".once -x" */
  13086. nArg = 2;
  13087. azArg[0] = "once";
  13088. zFile = azArg[1] = "-x";
  13089. n = 4;
  13090. }
  13091. if( nArg>2 ){
  13092. utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
  13093. rc = 1;
  13094. goto meta_command_exit;
  13095. }
  13096. if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  13097. if( nArg<2 ){
  13098. raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
  13099. rc = 1;
  13100. goto meta_command_exit;
  13101. }
  13102. p->outCount = 2;
  13103. }else{
  13104. p->outCount = 0;
  13105. }
  13106. output_reset(p);
  13107. if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
  13108. #ifndef SQLITE_NOHAVE_SYSTEM
  13109. if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
  13110. p->doXdgOpen = 1;
  13111. outputModePush(p);
  13112. if( zFile[1]=='x' ){
  13113. newTempFile(p, "csv");
  13114. p->mode = MODE_Csv;
  13115. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  13116. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  13117. }else{
  13118. newTempFile(p, "txt");
  13119. bTxtMode = 1;
  13120. }
  13121. zFile = p->zTempFile;
  13122. }
  13123. #endif /* SQLITE_NOHAVE_SYSTEM */
  13124. if( zFile[0]=='|' ){
  13125. #ifdef SQLITE_OMIT_POPEN
  13126. raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  13127. rc = 1;
  13128. p->out = stdout;
  13129. #else
  13130. p->out = popen(zFile + 1, "w");
  13131. if( p->out==0 ){
  13132. utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  13133. p->out = stdout;
  13134. rc = 1;
  13135. }else{
  13136. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  13137. }
  13138. #endif
  13139. }else{
  13140. p->out = output_file_open(zFile, bTxtMode);
  13141. if( p->out==0 ){
  13142. if( strcmp(zFile,"off")!=0 ){
  13143. utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  13144. }
  13145. p->out = stdout;
  13146. rc = 1;
  13147. } else {
  13148. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  13149. }
  13150. }
  13151. }else
  13152. if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  13153. int i;
  13154. for(i=1; i<nArg; i++){
  13155. if( i>1 ) raw_printf(p->out, " ");
  13156. utf8_printf(p->out, "%s", azArg[i]);
  13157. }
  13158. raw_printf(p->out, "\n");
  13159. }else
  13160. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  13161. if( nArg >= 2) {
  13162. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  13163. }
  13164. if( nArg >= 3) {
  13165. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  13166. }
  13167. }else
  13168. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  13169. rc = 2;
  13170. }else
  13171. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  13172. FILE *alt;
  13173. if( nArg!=2 ){
  13174. raw_printf(stderr, "Usage: .read FILE\n");
  13175. rc = 1;
  13176. goto meta_command_exit;
  13177. }
  13178. alt = fopen(azArg[1], "rb");
  13179. if( alt==0 ){
  13180. utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  13181. rc = 1;
  13182. }else{
  13183. rc = process_input(p, alt);
  13184. fclose(alt);
  13185. }
  13186. }else
  13187. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  13188. const char *zSrcFile;
  13189. const char *zDb;
  13190. sqlite3 *pSrc;
  13191. sqlite3_backup *pBackup;
  13192. int nTimeout = 0;
  13193. if( nArg==2 ){
  13194. zSrcFile = azArg[1];
  13195. zDb = "main";
  13196. }else if( nArg==3 ){
  13197. zSrcFile = azArg[2];
  13198. zDb = azArg[1];
  13199. }else{
  13200. raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  13201. rc = 1;
  13202. goto meta_command_exit;
  13203. }
  13204. rc = sqlite3_open(zSrcFile, &pSrc);
  13205. if( rc!=SQLITE_OK ){
  13206. utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  13207. close_db(pSrc);
  13208. return 1;
  13209. }
  13210. open_db(p, 0);
  13211. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  13212. if( pBackup==0 ){
  13213. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  13214. close_db(pSrc);
  13215. return 1;
  13216. }
  13217. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  13218. || rc==SQLITE_BUSY ){
  13219. if( rc==SQLITE_BUSY ){
  13220. if( nTimeout++ >= 3 ) break;
  13221. sqlite3_sleep(100);
  13222. }
  13223. }
  13224. sqlite3_backup_finish(pBackup);
  13225. if( rc==SQLITE_DONE ){
  13226. rc = 0;
  13227. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  13228. raw_printf(stderr, "Error: source database is busy\n");
  13229. rc = 1;
  13230. }else{
  13231. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  13232. rc = 1;
  13233. }
  13234. close_db(pSrc);
  13235. }else
  13236. if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  13237. if( nArg==2 ){
  13238. p->scanstatsOn = (u8)booleanValue(azArg[1]);
  13239. #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  13240. raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  13241. #endif
  13242. }else{
  13243. raw_printf(stderr, "Usage: .scanstats on|off\n");
  13244. rc = 1;
  13245. }
  13246. }else
  13247. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  13248. ShellText sSelect;
  13249. ShellState data;
  13250. char *zErrMsg = 0;
  13251. const char *zDiv = "(";
  13252. const char *zName = 0;
  13253. int iSchema = 0;
  13254. int bDebug = 0;
  13255. int ii;
  13256. open_db(p, 0);
  13257. memcpy(&data, p, sizeof(data));
  13258. data.showHeader = 0;
  13259. data.cMode = data.mode = MODE_Semi;
  13260. initText(&sSelect);
  13261. for(ii=1; ii<nArg; ii++){
  13262. if( optionMatch(azArg[ii],"indent") ){
  13263. data.cMode = data.mode = MODE_Pretty;
  13264. }else if( optionMatch(azArg[ii],"debug") ){
  13265. bDebug = 1;
  13266. }else if( zName==0 ){
  13267. zName = azArg[ii];
  13268. }else{
  13269. raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  13270. rc = 1;
  13271. goto meta_command_exit;
  13272. }
  13273. }
  13274. if( zName!=0 ){
  13275. int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
  13276. if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
  13277. char *new_argv[2], *new_colv[2];
  13278. new_argv[0] = sqlite3_mprintf(
  13279. "CREATE TABLE %s (\n"
  13280. " type text,\n"
  13281. " name text,\n"
  13282. " tbl_name text,\n"
  13283. " rootpage integer,\n"
  13284. " sql text\n"
  13285. ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
  13286. new_argv[1] = 0;
  13287. new_colv[0] = "sql";
  13288. new_colv[1] = 0;
  13289. callback(&data, 1, new_argv, new_colv);
  13290. sqlite3_free(new_argv[0]);
  13291. }
  13292. }
  13293. if( zDiv ){
  13294. sqlite3_stmt *pStmt = 0;
  13295. rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  13296. -1, &pStmt, 0);
  13297. if( rc ){
  13298. utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  13299. sqlite3_finalize(pStmt);
  13300. rc = 1;
  13301. goto meta_command_exit;
  13302. }
  13303. appendText(&sSelect, "SELECT sql FROM", 0);
  13304. iSchema = 0;
  13305. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  13306. const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  13307. char zScNum[30];
  13308. sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  13309. appendText(&sSelect, zDiv, 0);
  13310. zDiv = " UNION ALL ";
  13311. appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  13312. if( sqlite3_stricmp(zDb, "main")!=0 ){
  13313. appendText(&sSelect, zDb, '"');
  13314. }else{
  13315. appendText(&sSelect, "NULL", 0);
  13316. }
  13317. appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
  13318. appendText(&sSelect, zScNum, 0);
  13319. appendText(&sSelect, " AS snum, ", 0);
  13320. appendText(&sSelect, zDb, '\'');
  13321. appendText(&sSelect, " AS sname FROM ", 0);
  13322. appendText(&sSelect, zDb, '"');
  13323. appendText(&sSelect, ".sqlite_master", 0);
  13324. }
  13325. sqlite3_finalize(pStmt);
  13326. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  13327. if( zName ){
  13328. appendText(&sSelect,
  13329. " UNION ALL SELECT shell_module_schema(name),"
  13330. " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
  13331. }
  13332. #endif
  13333. appendText(&sSelect, ") WHERE ", 0);
  13334. if( zName ){
  13335. char *zQarg = sqlite3_mprintf("%Q", zName);
  13336. int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
  13337. strchr(zName, '[') != 0;
  13338. if( strchr(zName, '.') ){
  13339. appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  13340. }else{
  13341. appendText(&sSelect, "lower(tbl_name)", 0);
  13342. }
  13343. appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
  13344. appendText(&sSelect, zQarg, 0);
  13345. if( !bGlob ){
  13346. appendText(&sSelect, " ESCAPE '\\' ", 0);
  13347. }
  13348. appendText(&sSelect, " AND ", 0);
  13349. sqlite3_free(zQarg);
  13350. }
  13351. appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
  13352. " ORDER BY snum, rowid", 0);
  13353. if( bDebug ){
  13354. utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
  13355. }else{
  13356. rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  13357. }
  13358. freeText(&sSelect);
  13359. }
  13360. if( zErrMsg ){
  13361. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  13362. sqlite3_free(zErrMsg);
  13363. rc = 1;
  13364. }else if( rc != SQLITE_OK ){
  13365. raw_printf(stderr,"Error: querying schema information\n");
  13366. rc = 1;
  13367. }else{
  13368. rc = 0;
  13369. }
  13370. }else
  13371. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  13372. if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  13373. sqlite3SelectTrace = (int)integerValue(azArg[1]);
  13374. }else
  13375. #endif
  13376. #if defined(SQLITE_ENABLE_SESSION)
  13377. if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  13378. OpenSession *pSession = &p->aSession[0];
  13379. char **azCmd = &azArg[1];
  13380. int iSes = 0;
  13381. int nCmd = nArg - 1;
  13382. int i;
  13383. if( nArg<=1 ) goto session_syntax_error;
  13384. open_db(p, 0);
  13385. if( nArg>=3 ){
  13386. for(iSes=0; iSes<p->nSession; iSes++){
  13387. if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  13388. }
  13389. if( iSes<p->nSession ){
  13390. pSession = &p->aSession[iSes];
  13391. azCmd++;
  13392. nCmd--;
  13393. }else{
  13394. pSession = &p->aSession[0];
  13395. iSes = 0;
  13396. }
  13397. }
  13398. /* .session attach TABLE
  13399. ** Invoke the sqlite3session_attach() interface to attach a particular
  13400. ** table so that it is never filtered.
  13401. */
  13402. if( strcmp(azCmd[0],"attach")==0 ){
  13403. if( nCmd!=2 ) goto session_syntax_error;
  13404. if( pSession->p==0 ){
  13405. session_not_open:
  13406. raw_printf(stderr, "ERROR: No sessions are open\n");
  13407. }else{
  13408. rc = sqlite3session_attach(pSession->p, azCmd[1]);
  13409. if( rc ){
  13410. raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  13411. rc = 0;
  13412. }
  13413. }
  13414. }else
  13415. /* .session changeset FILE
  13416. ** .session patchset FILE
  13417. ** Write a changeset or patchset into a file. The file is overwritten.
  13418. */
  13419. if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  13420. FILE *out = 0;
  13421. if( nCmd!=2 ) goto session_syntax_error;
  13422. if( pSession->p==0 ) goto session_not_open;
  13423. out = fopen(azCmd[1], "wb");
  13424. if( out==0 ){
  13425. utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
  13426. }else{
  13427. int szChng;
  13428. void *pChng;
  13429. if( azCmd[0][0]=='c' ){
  13430. rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  13431. }else{
  13432. rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  13433. }
  13434. if( rc ){
  13435. printf("Error: error code %d\n", rc);
  13436. rc = 0;
  13437. }
  13438. if( pChng
  13439. && fwrite(pChng, szChng, 1, out)!=1 ){
  13440. raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  13441. szChng);
  13442. }
  13443. sqlite3_free(pChng);
  13444. fclose(out);
  13445. }
  13446. }else
  13447. /* .session close
  13448. ** Close the identified session
  13449. */
  13450. if( strcmp(azCmd[0], "close")==0 ){
  13451. if( nCmd!=1 ) goto session_syntax_error;
  13452. if( p->nSession ){
  13453. session_close(pSession);
  13454. p->aSession[iSes] = p->aSession[--p->nSession];
  13455. }
  13456. }else
  13457. /* .session enable ?BOOLEAN?
  13458. ** Query or set the enable flag
  13459. */
  13460. if( strcmp(azCmd[0], "enable")==0 ){
  13461. int ii;
  13462. if( nCmd>2 ) goto session_syntax_error;
  13463. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  13464. if( p->nSession ){
  13465. ii = sqlite3session_enable(pSession->p, ii);
  13466. utf8_printf(p->out, "session %s enable flag = %d\n",
  13467. pSession->zName, ii);
  13468. }
  13469. }else
  13470. /* .session filter GLOB ....
  13471. ** Set a list of GLOB patterns of table names to be excluded.
  13472. */
  13473. if( strcmp(azCmd[0], "filter")==0 ){
  13474. int ii, nByte;
  13475. if( nCmd<2 ) goto session_syntax_error;
  13476. if( p->nSession ){
  13477. for(ii=0; ii<pSession->nFilter; ii++){
  13478. sqlite3_free(pSession->azFilter[ii]);
  13479. }
  13480. sqlite3_free(pSession->azFilter);
  13481. nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  13482. pSession->azFilter = sqlite3_malloc( nByte );
  13483. if( pSession->azFilter==0 ){
  13484. raw_printf(stderr, "Error: out or memory\n");
  13485. exit(1);
  13486. }
  13487. for(ii=1; ii<nCmd; ii++){
  13488. pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  13489. }
  13490. pSession->nFilter = ii-1;
  13491. }
  13492. }else
  13493. /* .session indirect ?BOOLEAN?
  13494. ** Query or set the indirect flag
  13495. */
  13496. if( strcmp(azCmd[0], "indirect")==0 ){
  13497. int ii;
  13498. if( nCmd>2 ) goto session_syntax_error;
  13499. ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  13500. if( p->nSession ){
  13501. ii = sqlite3session_indirect(pSession->p, ii);
  13502. utf8_printf(p->out, "session %s indirect flag = %d\n",
  13503. pSession->zName, ii);
  13504. }
  13505. }else
  13506. /* .session isempty
  13507. ** Determine if the session is empty
  13508. */
  13509. if( strcmp(azCmd[0], "isempty")==0 ){
  13510. int ii;
  13511. if( nCmd!=1 ) goto session_syntax_error;
  13512. if( p->nSession ){
  13513. ii = sqlite3session_isempty(pSession->p);
  13514. utf8_printf(p->out, "session %s isempty flag = %d\n",
  13515. pSession->zName, ii);
  13516. }
  13517. }else
  13518. /* .session list
  13519. ** List all currently open sessions
  13520. */
  13521. if( strcmp(azCmd[0],"list")==0 ){
  13522. for(i=0; i<p->nSession; i++){
  13523. utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  13524. }
  13525. }else
  13526. /* .session open DB NAME
  13527. ** Open a new session called NAME on the attached database DB.
  13528. ** DB is normally "main".
  13529. */
  13530. if( strcmp(azCmd[0],"open")==0 ){
  13531. char *zName;
  13532. if( nCmd!=3 ) goto session_syntax_error;
  13533. zName = azCmd[2];
  13534. if( zName[0]==0 ) goto session_syntax_error;
  13535. for(i=0; i<p->nSession; i++){
  13536. if( strcmp(p->aSession[i].zName,zName)==0 ){
  13537. utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  13538. goto meta_command_exit;
  13539. }
  13540. }
  13541. if( p->nSession>=ArraySize(p->aSession) ){
  13542. raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  13543. goto meta_command_exit;
  13544. }
  13545. pSession = &p->aSession[p->nSession];
  13546. rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  13547. if( rc ){
  13548. raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  13549. rc = 0;
  13550. goto meta_command_exit;
  13551. }
  13552. pSession->nFilter = 0;
  13553. sqlite3session_table_filter(pSession->p, session_filter, pSession);
  13554. p->nSession++;
  13555. pSession->zName = sqlite3_mprintf("%s", zName);
  13556. }else
  13557. /* If no command name matches, show a syntax error */
  13558. session_syntax_error:
  13559. session_help(p);
  13560. }else
  13561. #endif
  13562. #ifdef SQLITE_DEBUG
  13563. /* Undocumented commands for internal testing. Subject to change
  13564. ** without notice. */
  13565. if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  13566. if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  13567. int i, v;
  13568. for(i=1; i<nArg; i++){
  13569. v = booleanValue(azArg[i]);
  13570. utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  13571. }
  13572. }
  13573. if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  13574. int i; sqlite3_int64 v;
  13575. for(i=1; i<nArg; i++){
  13576. char zBuf[200];
  13577. v = integerValue(azArg[i]);
  13578. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  13579. utf8_printf(p->out, "%s", zBuf);
  13580. }
  13581. }
  13582. }else
  13583. #endif
  13584. if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
  13585. int bIsInit = 0; /* True to initialize the SELFTEST table */
  13586. int bVerbose = 0; /* Verbose output */
  13587. int bSelftestExists; /* True if SELFTEST already exists */
  13588. int i, k; /* Loop counters */
  13589. int nTest = 0; /* Number of tests runs */
  13590. int nErr = 0; /* Number of errors seen */
  13591. ShellText str; /* Answer for a query */
  13592. sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  13593. open_db(p,0);
  13594. for(i=1; i<nArg; i++){
  13595. const char *z = azArg[i];
  13596. if( z[0]=='-' && z[1]=='-' ) z++;
  13597. if( strcmp(z,"-init")==0 ){
  13598. bIsInit = 1;
  13599. }else
  13600. if( strcmp(z,"-v")==0 ){
  13601. bVerbose++;
  13602. }else
  13603. {
  13604. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  13605. azArg[i], azArg[0]);
  13606. raw_printf(stderr, "Should be one of: --init -v\n");
  13607. rc = 1;
  13608. goto meta_command_exit;
  13609. }
  13610. }
  13611. if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  13612. != SQLITE_OK ){
  13613. bSelftestExists = 0;
  13614. }else{
  13615. bSelftestExists = 1;
  13616. }
  13617. if( bIsInit ){
  13618. createSelftestTable(p);
  13619. bSelftestExists = 1;
  13620. }
  13621. initText(&str);
  13622. appendText(&str, "x", 0);
  13623. for(k=bSelftestExists; k>=0; k--){
  13624. if( k==1 ){
  13625. rc = sqlite3_prepare_v2(p->db,
  13626. "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  13627. -1, &pStmt, 0);
  13628. }else{
  13629. rc = sqlite3_prepare_v2(p->db,
  13630. "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  13631. " (1,'run','PRAGMA integrity_check','ok')",
  13632. -1, &pStmt, 0);
  13633. }
  13634. if( rc ){
  13635. raw_printf(stderr, "Error querying the selftest table\n");
  13636. rc = 1;
  13637. sqlite3_finalize(pStmt);
  13638. goto meta_command_exit;
  13639. }
  13640. for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  13641. int tno = sqlite3_column_int(pStmt, 0);
  13642. const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  13643. const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  13644. const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  13645. k = 0;
  13646. if( bVerbose>0 ){
  13647. char *zQuote = sqlite3_mprintf("%q", zSql);
  13648. printf("%d: %s %s\n", tno, zOp, zSql);
  13649. sqlite3_free(zQuote);
  13650. }
  13651. if( strcmp(zOp,"memo")==0 ){
  13652. utf8_printf(p->out, "%s\n", zSql);
  13653. }else
  13654. if( strcmp(zOp,"run")==0 ){
  13655. char *zErrMsg = 0;
  13656. str.n = 0;
  13657. str.z[0] = 0;
  13658. rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  13659. nTest++;
  13660. if( bVerbose ){
  13661. utf8_printf(p->out, "Result: %s\n", str.z);
  13662. }
  13663. if( rc || zErrMsg ){
  13664. nErr++;
  13665. rc = 1;
  13666. utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  13667. sqlite3_free(zErrMsg);
  13668. }else if( strcmp(zAns,str.z)!=0 ){
  13669. nErr++;
  13670. rc = 1;
  13671. utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  13672. utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
  13673. }
  13674. }else
  13675. {
  13676. utf8_printf(stderr,
  13677. "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  13678. rc = 1;
  13679. break;
  13680. }
  13681. } /* End loop over rows of content from SELFTEST */
  13682. sqlite3_finalize(pStmt);
  13683. } /* End loop over k */
  13684. freeText(&str);
  13685. utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  13686. }else
  13687. if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  13688. if( nArg<2 || nArg>3 ){
  13689. raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  13690. rc = 1;
  13691. }
  13692. if( nArg>=2 ){
  13693. sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  13694. "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  13695. }
  13696. if( nArg>=3 ){
  13697. sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  13698. "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  13699. }
  13700. }else
  13701. if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
  13702. const char *zLike = 0; /* Which table to checksum. 0 means everything */
  13703. int i; /* Loop counter */
  13704. int bSchema = 0; /* Also hash the schema */
  13705. int bSeparate = 0; /* Hash each table separately */
  13706. int iSize = 224; /* Hash algorithm to use */
  13707. int bDebug = 0; /* Only show the query that would have run */
  13708. sqlite3_stmt *pStmt; /* For querying tables names */
  13709. char *zSql; /* SQL to be run */
  13710. char *zSep; /* Separator */
  13711. ShellText sSql; /* Complete SQL for the query to run the hash */
  13712. ShellText sQuery; /* Set of queries used to read all content */
  13713. open_db(p, 0);
  13714. for(i=1; i<nArg; i++){
  13715. const char *z = azArg[i];
  13716. if( z[0]=='-' ){
  13717. z++;
  13718. if( z[0]=='-' ) z++;
  13719. if( strcmp(z,"schema")==0 ){
  13720. bSchema = 1;
  13721. }else
  13722. if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
  13723. || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
  13724. ){
  13725. iSize = atoi(&z[5]);
  13726. }else
  13727. if( strcmp(z,"debug")==0 ){
  13728. bDebug = 1;
  13729. }else
  13730. {
  13731. utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  13732. azArg[i], azArg[0]);
  13733. raw_printf(stderr, "Should be one of: --schema"
  13734. " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
  13735. rc = 1;
  13736. goto meta_command_exit;
  13737. }
  13738. }else if( zLike ){
  13739. raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  13740. rc = 1;
  13741. goto meta_command_exit;
  13742. }else{
  13743. zLike = z;
  13744. bSeparate = 1;
  13745. if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
  13746. }
  13747. }
  13748. if( bSchema ){
  13749. zSql = "SELECT lower(name) FROM sqlite_master"
  13750. " WHERE type='table' AND coalesce(rootpage,0)>1"
  13751. " UNION ALL SELECT 'sqlite_master'"
  13752. " ORDER BY 1 collate nocase";
  13753. }else{
  13754. zSql = "SELECT lower(name) FROM sqlite_master"
  13755. " WHERE type='table' AND coalesce(rootpage,0)>1"
  13756. " AND name NOT LIKE 'sqlite_%'"
  13757. " ORDER BY 1 collate nocase";
  13758. }
  13759. sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  13760. initText(&sQuery);
  13761. initText(&sSql);
  13762. appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  13763. zSep = "VALUES(";
  13764. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  13765. const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  13766. if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  13767. if( strncmp(zTab, "sqlite_",7)!=0 ){
  13768. appendText(&sQuery,"SELECT * FROM ", 0);
  13769. appendText(&sQuery,zTab,'"');
  13770. appendText(&sQuery," NOT INDEXED;", 0);
  13771. }else if( strcmp(zTab, "sqlite_master")==0 ){
  13772. appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
  13773. " ORDER BY name;", 0);
  13774. }else if( strcmp(zTab, "sqlite_sequence")==0 ){
  13775. appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  13776. " ORDER BY name;", 0);
  13777. }else if( strcmp(zTab, "sqlite_stat1")==0 ){
  13778. appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  13779. " ORDER BY tbl,idx;", 0);
  13780. }else if( strcmp(zTab, "sqlite_stat3")==0
  13781. || strcmp(zTab, "sqlite_stat4")==0 ){
  13782. appendText(&sQuery, "SELECT * FROM ", 0);
  13783. appendText(&sQuery, zTab, 0);
  13784. appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  13785. }
  13786. appendText(&sSql, zSep, 0);
  13787. appendText(&sSql, sQuery.z, '\'');
  13788. sQuery.n = 0;
  13789. appendText(&sSql, ",", 0);
  13790. appendText(&sSql, zTab, '\'');
  13791. zSep = "),(";
  13792. }
  13793. sqlite3_finalize(pStmt);
  13794. if( bSeparate ){
  13795. zSql = sqlite3_mprintf(
  13796. "%s))"
  13797. " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  13798. " FROM [sha3sum$query]",
  13799. sSql.z, iSize);
  13800. }else{
  13801. zSql = sqlite3_mprintf(
  13802. "%s))"
  13803. " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  13804. " FROM [sha3sum$query]",
  13805. sSql.z, iSize);
  13806. }
  13807. freeText(&sQuery);
  13808. freeText(&sSql);
  13809. if( bDebug ){
  13810. utf8_printf(p->out, "%s\n", zSql);
  13811. }else{
  13812. shell_exec(p, zSql, 0);
  13813. }
  13814. sqlite3_free(zSql);
  13815. }else
  13816. #ifndef SQLITE_NOHAVE_SYSTEM
  13817. if( c=='s'
  13818. && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  13819. ){
  13820. char *zCmd;
  13821. int i, x;
  13822. if( nArg<2 ){
  13823. raw_printf(stderr, "Usage: .system COMMAND\n");
  13824. rc = 1;
  13825. goto meta_command_exit;
  13826. }
  13827. zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  13828. for(i=2; i<nArg; i++){
  13829. zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  13830. zCmd, azArg[i]);
  13831. }
  13832. x = system(zCmd);
  13833. sqlite3_free(zCmd);
  13834. if( x ) raw_printf(stderr, "System command returns %d\n", x);
  13835. }else
  13836. #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
  13837. if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  13838. static const char *azBool[] = { "off", "on", "trigger", "full"};
  13839. int i;
  13840. if( nArg!=1 ){
  13841. raw_printf(stderr, "Usage: .show\n");
  13842. rc = 1;
  13843. goto meta_command_exit;
  13844. }
  13845. utf8_printf(p->out, "%12.12s: %s\n","echo",
  13846. azBool[ShellHasFlag(p, SHFLG_Echo)]);
  13847. utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  13848. utf8_printf(p->out, "%12.12s: %s\n","explain",
  13849. p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  13850. utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  13851. utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  13852. utf8_printf(p->out, "%12.12s: ", "nullvalue");
  13853. output_c_string(p->out, p->nullValue);
  13854. raw_printf(p->out, "\n");
  13855. utf8_printf(p->out,"%12.12s: %s\n","output",
  13856. strlen30(p->outfile) ? p->outfile : "stdout");
  13857. utf8_printf(p->out,"%12.12s: ", "colseparator");
  13858. output_c_string(p->out, p->colSeparator);
  13859. raw_printf(p->out, "\n");
  13860. utf8_printf(p->out,"%12.12s: ", "rowseparator");
  13861. output_c_string(p->out, p->rowSeparator);
  13862. raw_printf(p->out, "\n");
  13863. utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  13864. utf8_printf(p->out, "%12.12s: ", "width");
  13865. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  13866. raw_printf(p->out, "%d ", p->colWidth[i]);
  13867. }
  13868. raw_printf(p->out, "\n");
  13869. utf8_printf(p->out, "%12.12s: %s\n", "filename",
  13870. p->zDbFilename ? p->zDbFilename : "");
  13871. }else
  13872. if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  13873. if( nArg==2 ){
  13874. p->statsOn = (u8)booleanValue(azArg[1]);
  13875. }else if( nArg==1 ){
  13876. display_stats(p->db, p, 0);
  13877. }else{
  13878. raw_printf(stderr, "Usage: .stats ?on|off?\n");
  13879. rc = 1;
  13880. }
  13881. }else
  13882. if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
  13883. || (c=='i' && (strncmp(azArg[0], "indices", n)==0
  13884. || strncmp(azArg[0], "indexes", n)==0) )
  13885. ){
  13886. sqlite3_stmt *pStmt;
  13887. char **azResult;
  13888. int nRow, nAlloc;
  13889. int ii;
  13890. ShellText s;
  13891. initText(&s);
  13892. open_db(p, 0);
  13893. rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  13894. if( rc ){
  13895. sqlite3_finalize(pStmt);
  13896. return shellDatabaseError(p->db);
  13897. }
  13898. if( nArg>2 && c=='i' ){
  13899. /* It is an historical accident that the .indexes command shows an error
  13900. ** when called with the wrong number of arguments whereas the .tables
  13901. ** command does not. */
  13902. raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  13903. rc = 1;
  13904. sqlite3_finalize(pStmt);
  13905. goto meta_command_exit;
  13906. }
  13907. for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  13908. const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  13909. if( zDbName==0 ) continue;
  13910. if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  13911. if( sqlite3_stricmp(zDbName, "main")==0 ){
  13912. appendText(&s, "SELECT name FROM ", 0);
  13913. }else{
  13914. appendText(&s, "SELECT ", 0);
  13915. appendText(&s, zDbName, '\'');
  13916. appendText(&s, "||'.'||name FROM ", 0);
  13917. }
  13918. appendText(&s, zDbName, '"');
  13919. appendText(&s, ".sqlite_master ", 0);
  13920. if( c=='t' ){
  13921. appendText(&s," WHERE type IN ('table','view')"
  13922. " AND name NOT LIKE 'sqlite_%'"
  13923. " AND name LIKE ?1", 0);
  13924. }else{
  13925. appendText(&s," WHERE type='index'"
  13926. " AND tbl_name LIKE ?1", 0);
  13927. }
  13928. }
  13929. rc = sqlite3_finalize(pStmt);
  13930. appendText(&s, " ORDER BY 1", 0);
  13931. rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  13932. freeText(&s);
  13933. if( rc ) return shellDatabaseError(p->db);
  13934. /* Run the SQL statement prepared by the above block. Store the results
  13935. ** as an array of nul-terminated strings in azResult[]. */
  13936. nRow = nAlloc = 0;
  13937. azResult = 0;
  13938. if( nArg>1 ){
  13939. sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  13940. }else{
  13941. sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  13942. }
  13943. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  13944. if( nRow>=nAlloc ){
  13945. char **azNew;
  13946. int n2 = nAlloc*2 + 10;
  13947. azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  13948. if( azNew==0 ) shell_out_of_memory();
  13949. nAlloc = n2;
  13950. azResult = azNew;
  13951. }
  13952. azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  13953. if( 0==azResult[nRow] ) shell_out_of_memory();
  13954. nRow++;
  13955. }
  13956. if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  13957. rc = shellDatabaseError(p->db);
  13958. }
  13959. /* Pretty-print the contents of array azResult[] to the output */
  13960. if( rc==0 && nRow>0 ){
  13961. int len, maxlen = 0;
  13962. int i, j;
  13963. int nPrintCol, nPrintRow;
  13964. for(i=0; i<nRow; i++){
  13965. len = strlen30(azResult[i]);
  13966. if( len>maxlen ) maxlen = len;
  13967. }
  13968. nPrintCol = 80/(maxlen+2);
  13969. if( nPrintCol<1 ) nPrintCol = 1;
  13970. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  13971. for(i=0; i<nPrintRow; i++){
  13972. for(j=i; j<nRow; j+=nPrintRow){
  13973. char *zSp = j<nPrintRow ? "" : " ";
  13974. utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  13975. azResult[j] ? azResult[j]:"");
  13976. }
  13977. raw_printf(p->out, "\n");
  13978. }
  13979. }
  13980. for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  13981. sqlite3_free(azResult);
  13982. }else
  13983. /* Begin redirecting output to the file "testcase-out.txt" */
  13984. if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  13985. output_reset(p);
  13986. p->out = output_file_open("testcase-out.txt", 0);
  13987. if( p->out==0 ){
  13988. raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  13989. }
  13990. if( nArg>=2 ){
  13991. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  13992. }else{
  13993. sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  13994. }
  13995. }else
  13996. #ifndef SQLITE_UNTESTABLE
  13997. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
  13998. static const struct {
  13999. const char *zCtrlName; /* Name of a test-control option */
  14000. int ctrlCode; /* Integer code for that option */
  14001. const char *zUsage; /* Usage notes */
  14002. } aCtrl[] = {
  14003. { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
  14004. { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
  14005. /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
  14006. /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
  14007. { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
  14008. /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
  14009. { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
  14010. { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
  14011. { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
  14012. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
  14013. #ifdef YYCOVERAGE
  14014. { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
  14015. #endif
  14016. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
  14017. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
  14018. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
  14019. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
  14020. { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
  14021. };
  14022. int testctrl = -1;
  14023. int iCtrl = -1;
  14024. int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
  14025. int isOk = 0;
  14026. int i, n2;
  14027. const char *zCmd = 0;
  14028. open_db(p, 0);
  14029. zCmd = nArg>=2 ? azArg[1] : "help";
  14030. /* The argument can optionally begin with "-" or "--" */
  14031. if( zCmd[0]=='-' && zCmd[1] ){
  14032. zCmd++;
  14033. if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
  14034. }
  14035. /* --help lists all test-controls */
  14036. if( strcmp(zCmd,"help")==0 ){
  14037. utf8_printf(p->out, "Available test-controls:\n");
  14038. for(i=0; i<ArraySize(aCtrl); i++){
  14039. utf8_printf(p->out, " .testctrl %s %s\n",
  14040. aCtrl[i].zCtrlName, aCtrl[i].zUsage);
  14041. }
  14042. rc = 1;
  14043. goto meta_command_exit;
  14044. }
  14045. /* convert testctrl text option to value. allow any unique prefix
  14046. ** of the option name, or a numerical value. */
  14047. n2 = strlen30(zCmd);
  14048. for(i=0; i<ArraySize(aCtrl); i++){
  14049. if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
  14050. if( testctrl<0 ){
  14051. testctrl = aCtrl[i].ctrlCode;
  14052. iCtrl = i;
  14053. }else{
  14054. utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
  14055. "Use \".testctrl --help\" for help\n", zCmd);
  14056. rc = 1;
  14057. goto meta_command_exit;
  14058. }
  14059. }
  14060. }
  14061. if( testctrl<0 ){
  14062. utf8_printf(stderr,"Error: unknown test-control: %s\n"
  14063. "Use \".testctrl --help\" for help\n", zCmd);
  14064. }else{
  14065. switch(testctrl){
  14066. /* sqlite3_test_control(int, db, int) */
  14067. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  14068. case SQLITE_TESTCTRL_RESERVE:
  14069. if( nArg==3 ){
  14070. int opt = (int)strtol(azArg[2], 0, 0);
  14071. rc2 = sqlite3_test_control(testctrl, p->db, opt);
  14072. isOk = 3;
  14073. }
  14074. break;
  14075. /* sqlite3_test_control(int) */
  14076. case SQLITE_TESTCTRL_PRNG_SAVE:
  14077. case SQLITE_TESTCTRL_PRNG_RESTORE:
  14078. case SQLITE_TESTCTRL_PRNG_RESET:
  14079. case SQLITE_TESTCTRL_BYTEORDER:
  14080. if( nArg==2 ){
  14081. rc2 = sqlite3_test_control(testctrl);
  14082. isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
  14083. }
  14084. break;
  14085. /* sqlite3_test_control(int, uint) */
  14086. case SQLITE_TESTCTRL_PENDING_BYTE:
  14087. if( nArg==3 ){
  14088. unsigned int opt = (unsigned int)integerValue(azArg[2]);
  14089. rc2 = sqlite3_test_control(testctrl, opt);
  14090. isOk = 3;
  14091. }
  14092. break;
  14093. /* sqlite3_test_control(int, int) */
  14094. case SQLITE_TESTCTRL_ASSERT:
  14095. case SQLITE_TESTCTRL_ALWAYS:
  14096. if( nArg==3 ){
  14097. int opt = booleanValue(azArg[2]);
  14098. rc2 = sqlite3_test_control(testctrl, opt);
  14099. isOk = 1;
  14100. }
  14101. break;
  14102. /* sqlite3_test_control(int, int) */
  14103. case SQLITE_TESTCTRL_LOCALTIME_FAULT:
  14104. case SQLITE_TESTCTRL_NEVER_CORRUPT:
  14105. if( nArg==3 ){
  14106. int opt = booleanValue(azArg[2]);
  14107. rc2 = sqlite3_test_control(testctrl, opt);
  14108. isOk = 3;
  14109. }
  14110. break;
  14111. case SQLITE_TESTCTRL_IMPOSTER:
  14112. if( nArg==5 ){
  14113. rc2 = sqlite3_test_control(testctrl, p->db,
  14114. azArg[2],
  14115. integerValue(azArg[3]),
  14116. integerValue(azArg[4]));
  14117. isOk = 3;
  14118. }
  14119. break;
  14120. #ifdef YYCOVERAGE
  14121. case SQLITE_TESTCTRL_PARSER_COVERAGE:
  14122. if( nArg==2 ){
  14123. sqlite3_test_control(testctrl, p->out);
  14124. isOk = 3;
  14125. }
  14126. #endif
  14127. }
  14128. }
  14129. if( isOk==0 && iCtrl>=0 ){
  14130. utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
  14131. rc = 1;
  14132. }else if( isOk==1 ){
  14133. raw_printf(p->out, "%d\n", rc2);
  14134. }else if( isOk==2 ){
  14135. raw_printf(p->out, "0x%08x\n", rc2);
  14136. }
  14137. }else
  14138. #endif /* !defined(SQLITE_UNTESTABLE) */
  14139. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  14140. open_db(p, 0);
  14141. sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  14142. }else
  14143. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  14144. if( nArg==2 ){
  14145. enableTimer = booleanValue(azArg[1]);
  14146. if( enableTimer && !HAS_TIMER ){
  14147. raw_printf(stderr, "Error: timer not available on this system.\n");
  14148. enableTimer = 0;
  14149. }
  14150. }else{
  14151. raw_printf(stderr, "Usage: .timer on|off\n");
  14152. rc = 1;
  14153. }
  14154. }else
  14155. if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  14156. open_db(p, 0);
  14157. if( nArg!=2 ){
  14158. raw_printf(stderr, "Usage: .trace FILE|off\n");
  14159. rc = 1;
  14160. goto meta_command_exit;
  14161. }
  14162. output_file_close(p->traceOut);
  14163. p->traceOut = output_file_open(azArg[1], 0);
  14164. #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  14165. if( p->traceOut==0 ){
  14166. sqlite3_trace_v2(p->db, 0, 0, 0);
  14167. }else{
  14168. sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
  14169. }
  14170. #endif
  14171. }else
  14172. #if SQLITE_USER_AUTHENTICATION
  14173. if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  14174. if( nArg<2 ){
  14175. raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  14176. rc = 1;
  14177. goto meta_command_exit;
  14178. }
  14179. open_db(p, 0);
  14180. if( strcmp(azArg[1],"login")==0 ){
  14181. if( nArg!=4 ){
  14182. raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  14183. rc = 1;
  14184. goto meta_command_exit;
  14185. }
  14186. rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
  14187. if( rc ){
  14188. utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  14189. rc = 1;
  14190. }
  14191. }else if( strcmp(azArg[1],"add")==0 ){
  14192. if( nArg!=5 ){
  14193. raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  14194. rc = 1;
  14195. goto meta_command_exit;
  14196. }
  14197. rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  14198. booleanValue(azArg[4]));
  14199. if( rc ){
  14200. raw_printf(stderr, "User-Add failed: %d\n", rc);
  14201. rc = 1;
  14202. }
  14203. }else if( strcmp(azArg[1],"edit")==0 ){
  14204. if( nArg!=5 ){
  14205. raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  14206. rc = 1;
  14207. goto meta_command_exit;
  14208. }
  14209. rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
  14210. booleanValue(azArg[4]));
  14211. if( rc ){
  14212. raw_printf(stderr, "User-Edit failed: %d\n", rc);
  14213. rc = 1;
  14214. }
  14215. }else if( strcmp(azArg[1],"delete")==0 ){
  14216. if( nArg!=3 ){
  14217. raw_printf(stderr, "Usage: .user delete USER\n");
  14218. rc = 1;
  14219. goto meta_command_exit;
  14220. }
  14221. rc = sqlite3_user_delete(p->db, azArg[2]);
  14222. if( rc ){
  14223. raw_printf(stderr, "User-Delete failed: %d\n", rc);
  14224. rc = 1;
  14225. }
  14226. }else{
  14227. raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  14228. rc = 1;
  14229. goto meta_command_exit;
  14230. }
  14231. }else
  14232. #endif /* SQLITE_USER_AUTHENTICATION */
  14233. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  14234. utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  14235. sqlite3_libversion(), sqlite3_sourceid());
  14236. #if SQLITE_HAVE_ZLIB
  14237. utf8_printf(p->out, "zlib version %s\n", zlibVersion());
  14238. #endif
  14239. #define CTIMEOPT_VAL_(opt) #opt
  14240. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  14241. #if defined(__clang__) && defined(__clang_major__)
  14242. utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
  14243. CTIMEOPT_VAL(__clang_minor__) "."
  14244. CTIMEOPT_VAL(__clang_patchlevel__) "\n");
  14245. #elif defined(_MSC_VER)
  14246. utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
  14247. #elif defined(__GNUC__) && defined(__VERSION__)
  14248. utf8_printf(p->out, "gcc-" __VERSION__ "\n");
  14249. #endif
  14250. }else
  14251. if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  14252. const char *zDbName = nArg==2 ? azArg[1] : "main";
  14253. sqlite3_vfs *pVfs = 0;
  14254. if( p->db ){
  14255. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  14256. if( pVfs ){
  14257. utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
  14258. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  14259. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  14260. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  14261. }
  14262. }
  14263. }else
  14264. if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  14265. sqlite3_vfs *pVfs;
  14266. sqlite3_vfs *pCurrent = 0;
  14267. if( p->db ){
  14268. sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  14269. }
  14270. for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  14271. utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
  14272. pVfs==pCurrent ? " <--- CURRENT" : "");
  14273. raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
  14274. raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
  14275. raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  14276. if( pVfs->pNext ){
  14277. raw_printf(p->out, "-----------------------------------\n");
  14278. }
  14279. }
  14280. }else
  14281. if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  14282. const char *zDbName = nArg==2 ? azArg[1] : "main";
  14283. char *zVfsName = 0;
  14284. if( p->db ){
  14285. sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  14286. if( zVfsName ){
  14287. utf8_printf(p->out, "%s\n", zVfsName);
  14288. sqlite3_free(zVfsName);
  14289. }
  14290. }
  14291. }else
  14292. #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  14293. if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  14294. sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  14295. }else
  14296. #endif
  14297. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  14298. int j;
  14299. assert( nArg<=ArraySize(azArg) );
  14300. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  14301. p->colWidth[j-1] = (int)integerValue(azArg[j]);
  14302. }
  14303. }else
  14304. {
  14305. utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  14306. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  14307. rc = 1;
  14308. }
  14309. meta_command_exit:
  14310. if( p->outCount ){
  14311. p->outCount--;
  14312. if( p->outCount==0 ) output_reset(p);
  14313. }
  14314. return rc;
  14315. }
  14316. /*
  14317. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  14318. ** of string z[].
  14319. */
  14320. static int line_contains_semicolon(const char *z, int N){
  14321. int i;
  14322. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  14323. return 0;
  14324. }
  14325. /*
  14326. ** Test to see if a line consists entirely of whitespace.
  14327. */
  14328. static int _all_whitespace(const char *z){
  14329. for(; *z; z++){
  14330. if( IsSpace(z[0]) ) continue;
  14331. if( *z=='/' && z[1]=='*' ){
  14332. z += 2;
  14333. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  14334. if( *z==0 ) return 0;
  14335. z++;
  14336. continue;
  14337. }
  14338. if( *z=='-' && z[1]=='-' ){
  14339. z += 2;
  14340. while( *z && *z!='\n' ){ z++; }
  14341. if( *z==0 ) return 1;
  14342. continue;
  14343. }
  14344. return 0;
  14345. }
  14346. return 1;
  14347. }
  14348. /*
  14349. ** Return TRUE if the line typed in is an SQL command terminator other
  14350. ** than a semi-colon. The SQL Server style "go" command is understood
  14351. ** as is the Oracle "/".
  14352. */
  14353. static int line_is_command_terminator(const char *zLine){
  14354. while( IsSpace(zLine[0]) ){ zLine++; };
  14355. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  14356. return 1; /* Oracle */
  14357. }
  14358. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  14359. && _all_whitespace(&zLine[2]) ){
  14360. return 1; /* SQL Server */
  14361. }
  14362. return 0;
  14363. }
  14364. /*
  14365. ** We need a default sqlite3_complete() implementation to use in case
  14366. ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
  14367. ** any arbitrary text is a complete SQL statement. This is not very
  14368. ** user-friendly, but it does seem to work.
  14369. */
  14370. #ifdef SQLITE_OMIT_COMPLETE
  14371. int sqlite3_complete(const char *zSql){ return 1; }
  14372. #endif
  14373. /*
  14374. ** Return true if zSql is a complete SQL statement. Return false if it
  14375. ** ends in the middle of a string literal or C-style comment.
  14376. */
  14377. static int line_is_complete(char *zSql, int nSql){
  14378. int rc;
  14379. if( zSql==0 ) return 1;
  14380. zSql[nSql] = ';';
  14381. zSql[nSql+1] = 0;
  14382. rc = sqlite3_complete(zSql);
  14383. zSql[nSql] = 0;
  14384. return rc;
  14385. }
  14386. /*
  14387. ** Run a single line of SQL. Return the number of errors.
  14388. */
  14389. static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  14390. int rc;
  14391. char *zErrMsg = 0;
  14392. open_db(p, 0);
  14393. if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  14394. BEGIN_TIMER;
  14395. rc = shell_exec(p, zSql, &zErrMsg);
  14396. END_TIMER;
  14397. if( rc || zErrMsg ){
  14398. char zPrefix[100];
  14399. if( in!=0 || !stdin_is_interactive ){
  14400. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  14401. "Error: near line %d:", startline);
  14402. }else{
  14403. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  14404. }
  14405. if( zErrMsg!=0 ){
  14406. utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  14407. sqlite3_free(zErrMsg);
  14408. zErrMsg = 0;
  14409. }else{
  14410. utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  14411. }
  14412. return 1;
  14413. }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  14414. raw_printf(p->out, "changes: %3d total_changes: %d\n",
  14415. sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  14416. }
  14417. return 0;
  14418. }
  14419. /*
  14420. ** Read input from *in and process it. If *in==0 then input
  14421. ** is interactive - the user is typing it it. Otherwise, input
  14422. ** is coming from a file or device. A prompt is issued and history
  14423. ** is saved only if input is interactive. An interrupt signal will
  14424. ** cause this routine to exit immediately, unless input is interactive.
  14425. **
  14426. ** Return the number of errors.
  14427. */
  14428. static int process_input(ShellState *p, FILE *in){
  14429. char *zLine = 0; /* A single input line */
  14430. char *zSql = 0; /* Accumulated SQL text */
  14431. int nLine; /* Length of current line */
  14432. int nSql = 0; /* Bytes of zSql[] used */
  14433. int nAlloc = 0; /* Allocated zSql[] space */
  14434. int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
  14435. int rc; /* Error code */
  14436. int errCnt = 0; /* Number of errors seen */
  14437. int lineno = 0; /* Current line number */
  14438. int startline = 0; /* Line number for start of current input */
  14439. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  14440. fflush(p->out);
  14441. zLine = one_input_line(in, zLine, nSql>0);
  14442. if( zLine==0 ){
  14443. /* End of input */
  14444. if( in==0 && stdin_is_interactive ) printf("\n");
  14445. break;
  14446. }
  14447. if( seenInterrupt ){
  14448. if( in!=0 ) break;
  14449. seenInterrupt = 0;
  14450. }
  14451. lineno++;
  14452. if( nSql==0 && _all_whitespace(zLine) ){
  14453. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  14454. continue;
  14455. }
  14456. if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
  14457. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  14458. if( zLine[0]=='.' ){
  14459. rc = do_meta_command(zLine, p);
  14460. if( rc==2 ){ /* exit requested */
  14461. break;
  14462. }else if( rc ){
  14463. errCnt++;
  14464. }
  14465. }
  14466. continue;
  14467. }
  14468. if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  14469. memcpy(zLine,";",2);
  14470. }
  14471. nLine = strlen30(zLine);
  14472. if( nSql+nLine+2>=nAlloc ){
  14473. nAlloc = nSql+nLine+100;
  14474. zSql = realloc(zSql, nAlloc);
  14475. if( zSql==0 ) shell_out_of_memory();
  14476. }
  14477. nSqlPrior = nSql;
  14478. if( nSql==0 ){
  14479. int i;
  14480. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  14481. assert( nAlloc>0 && zSql!=0 );
  14482. memcpy(zSql, zLine+i, nLine+1-i);
  14483. startline = lineno;
  14484. nSql = nLine-i;
  14485. }else{
  14486. zSql[nSql++] = '\n';
  14487. memcpy(zSql+nSql, zLine, nLine+1);
  14488. nSql += nLine;
  14489. }
  14490. if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  14491. && sqlite3_complete(zSql) ){
  14492. errCnt += runOneSqlLine(p, zSql, in, startline);
  14493. nSql = 0;
  14494. if( p->outCount ){
  14495. output_reset(p);
  14496. p->outCount = 0;
  14497. }else{
  14498. clearTempFile(p);
  14499. }
  14500. }else if( nSql && _all_whitespace(zSql) ){
  14501. if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
  14502. nSql = 0;
  14503. }
  14504. }
  14505. if( nSql && !_all_whitespace(zSql) ){
  14506. errCnt += runOneSqlLine(p, zSql, in, startline);
  14507. }
  14508. free(zSql);
  14509. free(zLine);
  14510. return errCnt>0;
  14511. }
  14512. /*
  14513. ** Return a pathname which is the user's home directory. A
  14514. ** 0 return indicates an error of some kind.
  14515. */
  14516. static char *find_home_dir(int clearFlag){
  14517. static char *home_dir = NULL;
  14518. if( clearFlag ){
  14519. free(home_dir);
  14520. home_dir = 0;
  14521. return 0;
  14522. }
  14523. if( home_dir ) return home_dir;
  14524. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  14525. && !defined(__RTP__) && !defined(_WRS_KERNEL)
  14526. {
  14527. struct passwd *pwent;
  14528. uid_t uid = getuid();
  14529. if( (pwent=getpwuid(uid)) != NULL) {
  14530. home_dir = pwent->pw_dir;
  14531. }
  14532. }
  14533. #endif
  14534. #if defined(_WIN32_WCE)
  14535. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  14536. */
  14537. home_dir = "/";
  14538. #else
  14539. #if defined(_WIN32) || defined(WIN32)
  14540. if (!home_dir) {
  14541. home_dir = getenv("USERPROFILE");
  14542. }
  14543. #endif
  14544. if (!home_dir) {
  14545. home_dir = getenv("HOME");
  14546. }
  14547. #if defined(_WIN32) || defined(WIN32)
  14548. if (!home_dir) {
  14549. char *zDrive, *zPath;
  14550. int n;
  14551. zDrive = getenv("HOMEDRIVE");
  14552. zPath = getenv("HOMEPATH");
  14553. if( zDrive && zPath ){
  14554. n = strlen30(zDrive) + strlen30(zPath) + 1;
  14555. home_dir = malloc( n );
  14556. if( home_dir==0 ) return 0;
  14557. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  14558. return home_dir;
  14559. }
  14560. home_dir = "c:\\";
  14561. }
  14562. #endif
  14563. #endif /* !_WIN32_WCE */
  14564. if( home_dir ){
  14565. int n = strlen30(home_dir) + 1;
  14566. char *z = malloc( n );
  14567. if( z ) memcpy(z, home_dir, n);
  14568. home_dir = z;
  14569. }
  14570. return home_dir;
  14571. }
  14572. /*
  14573. ** Read input from the file given by sqliterc_override. Or if that
  14574. ** parameter is NULL, take input from ~/.sqliterc
  14575. **
  14576. ** Returns the number of errors.
  14577. */
  14578. static void process_sqliterc(
  14579. ShellState *p, /* Configuration data */
  14580. const char *sqliterc_override /* Name of config file. NULL to use default */
  14581. ){
  14582. char *home_dir = NULL;
  14583. const char *sqliterc = sqliterc_override;
  14584. char *zBuf = 0;
  14585. FILE *in = NULL;
  14586. if (sqliterc == NULL) {
  14587. home_dir = find_home_dir(0);
  14588. if( home_dir==0 ){
  14589. raw_printf(stderr, "-- warning: cannot find home directory;"
  14590. " cannot read ~/.sqliterc\n");
  14591. return;
  14592. }
  14593. zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  14594. sqliterc = zBuf;
  14595. }
  14596. in = fopen(sqliterc,"rb");
  14597. if( in ){
  14598. if( stdin_is_interactive ){
  14599. utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  14600. }
  14601. process_input(p,in);
  14602. fclose(in);
  14603. }
  14604. sqlite3_free(zBuf);
  14605. }
  14606. /*
  14607. ** Show available command line options
  14608. */
  14609. static const char zOptions[] =
  14610. #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  14611. " -A ARGS... run \".archive ARGS\" and exit\n"
  14612. #endif
  14613. " -append append the database to the end of the file\n"
  14614. " -ascii set output mode to 'ascii'\n"
  14615. " -bail stop after hitting an error\n"
  14616. " -batch force batch I/O\n"
  14617. " -column set output mode to 'column'\n"
  14618. " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
  14619. " -csv set output mode to 'csv'\n"
  14620. " -echo print commands before execution\n"
  14621. " -init FILENAME read/process named file\n"
  14622. " -[no]header turn headers on or off\n"
  14623. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  14624. " -heap SIZE Size of heap for memsys3 or memsys5\n"
  14625. #endif
  14626. " -help show this message\n"
  14627. " -html set output mode to HTML\n"
  14628. " -interactive force interactive I/O\n"
  14629. " -line set output mode to 'line'\n"
  14630. " -list set output mode to 'list'\n"
  14631. " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
  14632. " -mmap N default mmap size set to N\n"
  14633. #ifdef SQLITE_ENABLE_MULTIPLEX
  14634. " -multiplex enable the multiplexor VFS\n"
  14635. #endif
  14636. " -newline SEP set output row separator. Default: '\\n'\n"
  14637. " -nullvalue TEXT set text string for NULL values. Default ''\n"
  14638. " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
  14639. " -quote set output mode to 'quote'\n"
  14640. " -readonly open the database read-only\n"
  14641. " -separator SEP set output column separator. Default: '|'\n"
  14642. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  14643. " -sorterref SIZE sorter references threshold size\n"
  14644. #endif
  14645. " -stats print memory stats before each finalize\n"
  14646. " -version show SQLite version\n"
  14647. " -vfs NAME use NAME as the default VFS\n"
  14648. #ifdef SQLITE_ENABLE_VFSTRACE
  14649. " -vfstrace enable tracing of all VFS calls\n"
  14650. #endif
  14651. #ifdef SQLITE_HAVE_ZLIB
  14652. " -zip open the file as a ZIP Archive\n"
  14653. #endif
  14654. ;
  14655. static void usage(int showDetail){
  14656. utf8_printf(stderr,
  14657. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  14658. "FILENAME is the name of an SQLite database. A new database is created\n"
  14659. "if the file does not previously exist.\n", Argv0);
  14660. if( showDetail ){
  14661. utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  14662. }else{
  14663. raw_printf(stderr, "Use the -help option for additional information\n");
  14664. }
  14665. exit(1);
  14666. }
  14667. /*
  14668. ** Internal check: Verify that the SQLite is uninitialized. Print a
  14669. ** error message if it is initialized.
  14670. */
  14671. static void verify_uninitialized(void){
  14672. if( sqlite3_config(-1)==SQLITE_MISUSE ){
  14673. utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
  14674. " initialization.\n");
  14675. }
  14676. }
  14677. /*
  14678. ** Initialize the state information in data
  14679. */
  14680. static void main_init(ShellState *data) {
  14681. memset(data, 0, sizeof(*data));
  14682. data->normalMode = data->cMode = data->mode = MODE_List;
  14683. data->autoExplain = 1;
  14684. memcpy(data->colSeparator,SEP_Column, 2);
  14685. memcpy(data->rowSeparator,SEP_Row, 2);
  14686. data->showHeader = 0;
  14687. data->shellFlgs = SHFLG_Lookaside;
  14688. verify_uninitialized();
  14689. sqlite3_config(SQLITE_CONFIG_URI, 1);
  14690. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  14691. sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  14692. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  14693. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  14694. }
  14695. /*
  14696. ** Output text to the console in a font that attracts extra attention.
  14697. */
  14698. #ifdef _WIN32
  14699. static void printBold(const char *zText){
  14700. HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  14701. CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  14702. GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  14703. SetConsoleTextAttribute(out,
  14704. FOREGROUND_RED|FOREGROUND_INTENSITY
  14705. );
  14706. printf("%s", zText);
  14707. SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  14708. }
  14709. #else
  14710. static void printBold(const char *zText){
  14711. printf("\033[1m%s\033[0m", zText);
  14712. }
  14713. #endif
  14714. /*
  14715. ** Get the argument to an --option. Throw an error and die if no argument
  14716. ** is available.
  14717. */
  14718. static char *cmdline_option_value(int argc, char **argv, int i){
  14719. if( i==argc ){
  14720. utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  14721. argv[0], argv[argc-1]);
  14722. exit(1);
  14723. }
  14724. return argv[i];
  14725. }
  14726. #ifndef SQLITE_SHELL_IS_UTF8
  14727. # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  14728. # define SQLITE_SHELL_IS_UTF8 (0)
  14729. # else
  14730. # define SQLITE_SHELL_IS_UTF8 (1)
  14731. # endif
  14732. #endif
  14733. #if SQLITE_SHELL_IS_UTF8
  14734. int SQLITE_CDECL main(int argc, char **argv){
  14735. #else
  14736. int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  14737. char **argv;
  14738. #endif
  14739. char *zErrMsg = 0;
  14740. ShellState data;
  14741. const char *zInitFile = 0;
  14742. int i;
  14743. int rc = 0;
  14744. int warnInmemoryDb = 0;
  14745. int readStdin = 1;
  14746. int nCmd = 0;
  14747. char **azCmd = 0;
  14748. const char *zVfs = 0; /* Value of -vfs command-line option */
  14749. #if !SQLITE_SHELL_IS_UTF8
  14750. char **argvToFree = 0;
  14751. int argcToFree = 0;
  14752. #endif
  14753. setBinaryMode(stdin, 0);
  14754. setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  14755. stdin_is_interactive = isatty(0);
  14756. stdout_is_console = isatty(1);
  14757. #if !defined(_WIN32_WCE)
  14758. if( getenv("SQLITE_DEBUG_BREAK") ){
  14759. if( isatty(0) && isatty(2) ){
  14760. fprintf(stderr,
  14761. "attach debugger to process %d and press any key to continue.\n",
  14762. GETPID());
  14763. fgetc(stdin);
  14764. }else{
  14765. #if defined(_WIN32) || defined(WIN32)
  14766. DebugBreak();
  14767. #elif defined(SIGTRAP)
  14768. raise(SIGTRAP);
  14769. #endif
  14770. }
  14771. }
  14772. #endif
  14773. #if USE_SYSTEM_SQLITE+0!=1
  14774. if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  14775. utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  14776. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  14777. exit(1);
  14778. }
  14779. #endif
  14780. main_init(&data);
  14781. /* On Windows, we must translate command-line arguments into UTF-8.
  14782. ** The SQLite memory allocator subsystem has to be enabled in order to
  14783. ** do this. But we want to run an sqlite3_shutdown() afterwards so that
  14784. ** subsequent sqlite3_config() calls will work. So copy all results into
  14785. ** memory that does not come from the SQLite memory allocator.
  14786. */
  14787. #if !SQLITE_SHELL_IS_UTF8
  14788. sqlite3_initialize();
  14789. argvToFree = malloc(sizeof(argv[0])*argc*2);
  14790. argcToFree = argc;
  14791. argv = argvToFree + argc;
  14792. if( argv==0 ) shell_out_of_memory();
  14793. for(i=0; i<argc; i++){
  14794. char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
  14795. int n;
  14796. if( z==0 ) shell_out_of_memory();
  14797. n = (int)strlen(z);
  14798. argv[i] = malloc( n+1 );
  14799. if( argv[i]==0 ) shell_out_of_memory();
  14800. memcpy(argv[i], z, n+1);
  14801. argvToFree[i] = argv[i];
  14802. sqlite3_free(z);
  14803. }
  14804. sqlite3_shutdown();
  14805. #endif
  14806. assert( argc>=1 && argv && argv[0] );
  14807. Argv0 = argv[0];
  14808. /* Make sure we have a valid signal handler early, before anything
  14809. ** else is done.
  14810. */
  14811. #ifdef SIGINT
  14812. signal(SIGINT, interrupt_handler);
  14813. #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
  14814. SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
  14815. #endif
  14816. #ifdef SQLITE_SHELL_DBNAME_PROC
  14817. {
  14818. /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  14819. ** of a C-function that will provide the name of the database file. Use
  14820. ** this compile-time option to embed this shell program in larger
  14821. ** applications. */
  14822. extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  14823. SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  14824. warnInmemoryDb = 0;
  14825. }
  14826. #endif
  14827. /* Do an initial pass through the command-line argument to locate
  14828. ** the name of the database file, the name of the initialization file,
  14829. ** the size of the alternative malloc heap,
  14830. ** and the first command to execute.
  14831. */
  14832. verify_uninitialized();
  14833. for(i=1; i<argc; i++){
  14834. char *z;
  14835. z = argv[i];
  14836. if( z[0]!='-' ){
  14837. if( data.zDbFilename==0 ){
  14838. data.zDbFilename = z;
  14839. }else{
  14840. /* Excesss arguments are interpreted as SQL (or dot-commands) and
  14841. ** mean that nothing is read from stdin */
  14842. readStdin = 0;
  14843. nCmd++;
  14844. azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  14845. if( azCmd==0 ) shell_out_of_memory();
  14846. azCmd[nCmd-1] = z;
  14847. }
  14848. }
  14849. if( z[1]=='-' ) z++;
  14850. if( strcmp(z,"-separator")==0
  14851. || strcmp(z,"-nullvalue")==0
  14852. || strcmp(z,"-newline")==0
  14853. || strcmp(z,"-cmd")==0
  14854. ){
  14855. (void)cmdline_option_value(argc, argv, ++i);
  14856. }else if( strcmp(z,"-init")==0 ){
  14857. zInitFile = cmdline_option_value(argc, argv, ++i);
  14858. }else if( strcmp(z,"-batch")==0 ){
  14859. /* Need to check for batch mode here to so we can avoid printing
  14860. ** informational messages (like from process_sqliterc) before
  14861. ** we do the actual processing of arguments later in a second pass.
  14862. */
  14863. stdin_is_interactive = 0;
  14864. }else if( strcmp(z,"-heap")==0 ){
  14865. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  14866. const char *zSize;
  14867. sqlite3_int64 szHeap;
  14868. zSize = cmdline_option_value(argc, argv, ++i);
  14869. szHeap = integerValue(zSize);
  14870. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  14871. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  14872. #else
  14873. (void)cmdline_option_value(argc, argv, ++i);
  14874. #endif
  14875. }else if( strcmp(z,"-pagecache")==0 ){
  14876. int n, sz;
  14877. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  14878. if( sz>70000 ) sz = 70000;
  14879. if( sz<0 ) sz = 0;
  14880. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  14881. sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  14882. (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  14883. data.shellFlgs |= SHFLG_Pagecache;
  14884. }else if( strcmp(z,"-lookaside")==0 ){
  14885. int n, sz;
  14886. sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  14887. if( sz<0 ) sz = 0;
  14888. n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  14889. if( n<0 ) n = 0;
  14890. sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  14891. if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  14892. #ifdef SQLITE_ENABLE_VFSTRACE
  14893. }else if( strcmp(z,"-vfstrace")==0 ){
  14894. extern int vfstrace_register(
  14895. const char *zTraceName,
  14896. const char *zOldVfsName,
  14897. int (*xOut)(const char*,void*),
  14898. void *pOutArg,
  14899. int makeDefault
  14900. );
  14901. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  14902. #endif
  14903. #ifdef SQLITE_ENABLE_MULTIPLEX
  14904. }else if( strcmp(z,"-multiplex")==0 ){
  14905. extern int sqlite3_multiple_initialize(const char*,int);
  14906. sqlite3_multiplex_initialize(0, 1);
  14907. #endif
  14908. }else if( strcmp(z,"-mmap")==0 ){
  14909. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  14910. sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  14911. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  14912. }else if( strcmp(z,"-sorterref")==0 ){
  14913. sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  14914. sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
  14915. #endif
  14916. }else if( strcmp(z,"-vfs")==0 ){
  14917. zVfs = cmdline_option_value(argc, argv, ++i);
  14918. #ifdef SQLITE_HAVE_ZLIB
  14919. }else if( strcmp(z,"-zip")==0 ){
  14920. data.openMode = SHELL_OPEN_ZIPFILE;
  14921. #endif
  14922. }else if( strcmp(z,"-append")==0 ){
  14923. data.openMode = SHELL_OPEN_APPENDVFS;
  14924. }else if( strcmp(z,"-readonly")==0 ){
  14925. data.openMode = SHELL_OPEN_READONLY;
  14926. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  14927. }else if( strncmp(z, "-A",2)==0 ){
  14928. /* All remaining command-line arguments are passed to the ".archive"
  14929. ** command, so ignore them */
  14930. break;
  14931. #endif
  14932. }
  14933. }
  14934. verify_uninitialized();
  14935. #ifdef SQLITE_SHELL_INIT_PROC
  14936. {
  14937. /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
  14938. ** of a C-function that will perform initialization actions on SQLite that
  14939. ** occur just before or after sqlite3_initialize(). Use this compile-time
  14940. ** option to embed this shell program in larger applications. */
  14941. extern void SQLITE_SHELL_INIT_PROC(void);
  14942. SQLITE_SHELL_INIT_PROC();
  14943. }
  14944. #else
  14945. /* All the sqlite3_config() calls have now been made. So it is safe
  14946. ** to call sqlite3_initialize() and process any command line -vfs option. */
  14947. sqlite3_initialize();
  14948. #endif
  14949. if( zVfs ){
  14950. sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
  14951. if( pVfs ){
  14952. sqlite3_vfs_register(pVfs, 1);
  14953. }else{
  14954. utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  14955. exit(1);
  14956. }
  14957. }
  14958. if( data.zDbFilename==0 ){
  14959. #ifndef SQLITE_OMIT_MEMORYDB
  14960. data.zDbFilename = ":memory:";
  14961. warnInmemoryDb = argc==1;
  14962. #else
  14963. utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  14964. return 1;
  14965. #endif
  14966. }
  14967. data.out = stdout;
  14968. sqlite3_appendvfs_init(0,0,0);
  14969. /* Go ahead and open the database file if it already exists. If the
  14970. ** file does not exist, delay opening it. This prevents empty database
  14971. ** files from being created if a user mistypes the database name argument
  14972. ** to the sqlite command-line tool.
  14973. */
  14974. if( access(data.zDbFilename, 0)==0 ){
  14975. open_db(&data, 0);
  14976. }
  14977. /* Process the initialization file if there is one. If no -init option
  14978. ** is given on the command line, look for a file named ~/.sqliterc and
  14979. ** try to process it.
  14980. */
  14981. process_sqliterc(&data,zInitFile);
  14982. /* Make a second pass through the command-line argument and set
  14983. ** options. This second pass is delayed until after the initialization
  14984. ** file is processed so that the command-line arguments will override
  14985. ** settings in the initialization file.
  14986. */
  14987. for(i=1; i<argc; i++){
  14988. char *z = argv[i];
  14989. if( z[0]!='-' ) continue;
  14990. if( z[1]=='-' ){ z++; }
  14991. if( strcmp(z,"-init")==0 ){
  14992. i++;
  14993. }else if( strcmp(z,"-html")==0 ){
  14994. data.mode = MODE_Html;
  14995. }else if( strcmp(z,"-list")==0 ){
  14996. data.mode = MODE_List;
  14997. }else if( strcmp(z,"-quote")==0 ){
  14998. data.mode = MODE_Quote;
  14999. }else if( strcmp(z,"-line")==0 ){
  15000. data.mode = MODE_Line;
  15001. }else if( strcmp(z,"-column")==0 ){
  15002. data.mode = MODE_Column;
  15003. }else if( strcmp(z,"-csv")==0 ){
  15004. data.mode = MODE_Csv;
  15005. memcpy(data.colSeparator,",",2);
  15006. #ifdef SQLITE_HAVE_ZLIB
  15007. }else if( strcmp(z,"-zip")==0 ){
  15008. data.openMode = SHELL_OPEN_ZIPFILE;
  15009. #endif
  15010. }else if( strcmp(z,"-append")==0 ){
  15011. data.openMode = SHELL_OPEN_APPENDVFS;
  15012. }else if( strcmp(z,"-readonly")==0 ){
  15013. data.openMode = SHELL_OPEN_READONLY;
  15014. }else if( strcmp(z,"-ascii")==0 ){
  15015. data.mode = MODE_Ascii;
  15016. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  15017. SEP_Unit);
  15018. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  15019. SEP_Record);
  15020. }else if( strcmp(z,"-separator")==0 ){
  15021. sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  15022. "%s",cmdline_option_value(argc,argv,++i));
  15023. }else if( strcmp(z,"-newline")==0 ){
  15024. sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  15025. "%s",cmdline_option_value(argc,argv,++i));
  15026. }else if( strcmp(z,"-nullvalue")==0 ){
  15027. sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  15028. "%s",cmdline_option_value(argc,argv,++i));
  15029. }else if( strcmp(z,"-header")==0 ){
  15030. data.showHeader = 1;
  15031. }else if( strcmp(z,"-noheader")==0 ){
  15032. data.showHeader = 0;
  15033. }else if( strcmp(z,"-echo")==0 ){
  15034. ShellSetFlag(&data, SHFLG_Echo);
  15035. }else if( strcmp(z,"-eqp")==0 ){
  15036. data.autoEQP = AUTOEQP_on;
  15037. }else if( strcmp(z,"-eqpfull")==0 ){
  15038. data.autoEQP = AUTOEQP_full;
  15039. }else if( strcmp(z,"-stats")==0 ){
  15040. data.statsOn = 1;
  15041. }else if( strcmp(z,"-scanstats")==0 ){
  15042. data.scanstatsOn = 1;
  15043. }else if( strcmp(z,"-backslash")==0 ){
  15044. /* Undocumented command-line option: -backslash
  15045. ** Causes C-style backslash escapes to be evaluated in SQL statements
  15046. ** prior to sending the SQL into SQLite. Useful for injecting
  15047. ** crazy bytes in the middle of SQL statements for testing and debugging.
  15048. */
  15049. ShellSetFlag(&data, SHFLG_Backslash);
  15050. }else if( strcmp(z,"-bail")==0 ){
  15051. bail_on_error = 1;
  15052. }else if( strcmp(z,"-version")==0 ){
  15053. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  15054. return 0;
  15055. }else if( strcmp(z,"-interactive")==0 ){
  15056. stdin_is_interactive = 1;
  15057. }else if( strcmp(z,"-batch")==0 ){
  15058. stdin_is_interactive = 0;
  15059. }else if( strcmp(z,"-heap")==0 ){
  15060. i++;
  15061. }else if( strcmp(z,"-pagecache")==0 ){
  15062. i+=2;
  15063. }else if( strcmp(z,"-lookaside")==0 ){
  15064. i+=2;
  15065. }else if( strcmp(z,"-mmap")==0 ){
  15066. i++;
  15067. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  15068. }else if( strcmp(z,"-sorterref")==0 ){
  15069. i++;
  15070. #endif
  15071. }else if( strcmp(z,"-vfs")==0 ){
  15072. i++;
  15073. #ifdef SQLITE_ENABLE_VFSTRACE
  15074. }else if( strcmp(z,"-vfstrace")==0 ){
  15075. i++;
  15076. #endif
  15077. #ifdef SQLITE_ENABLE_MULTIPLEX
  15078. }else if( strcmp(z,"-multiplex")==0 ){
  15079. i++;
  15080. #endif
  15081. }else if( strcmp(z,"-help")==0 ){
  15082. usage(1);
  15083. }else if( strcmp(z,"-cmd")==0 ){
  15084. /* Run commands that follow -cmd first and separately from commands
  15085. ** that simply appear on the command-line. This seems goofy. It would
  15086. ** be better if all commands ran in the order that they appear. But
  15087. ** we retain the goofy behavior for historical compatibility. */
  15088. if( i==argc-1 ) break;
  15089. z = cmdline_option_value(argc,argv,++i);
  15090. if( z[0]=='.' ){
  15091. rc = do_meta_command(z, &data);
  15092. if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  15093. }else{
  15094. open_db(&data, 0);
  15095. rc = shell_exec(&data, z, &zErrMsg);
  15096. if( zErrMsg!=0 ){
  15097. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  15098. if( bail_on_error ) return rc!=0 ? rc : 1;
  15099. }else if( rc!=0 ){
  15100. utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  15101. if( bail_on_error ) return rc;
  15102. }
  15103. }
  15104. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
  15105. }else if( strncmp(z, "-A", 2)==0 ){
  15106. if( nCmd>0 ){
  15107. utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
  15108. " with \"%s\"\n", z);
  15109. return 1;
  15110. }
  15111. open_db(&data, OPEN_DB_ZIPFILE);
  15112. if( z[2] ){
  15113. argv[i] = &z[2];
  15114. arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
  15115. }else{
  15116. arDotCommand(&data, 1, argv+i, argc-i);
  15117. }
  15118. readStdin = 0;
  15119. break;
  15120. #endif
  15121. }else{
  15122. utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  15123. raw_printf(stderr,"Use -help for a list of options.\n");
  15124. return 1;
  15125. }
  15126. data.cMode = data.mode;
  15127. }
  15128. if( !readStdin ){
  15129. /* Run all arguments that do not begin with '-' as if they were separate
  15130. ** command-line inputs, except for the argToSkip argument which contains
  15131. ** the database filename.
  15132. */
  15133. for(i=0; i<nCmd; i++){
  15134. if( azCmd[i][0]=='.' ){
  15135. rc = do_meta_command(azCmd[i], &data);
  15136. if( rc ) return rc==2 ? 0 : rc;
  15137. }else{
  15138. open_db(&data, 0);
  15139. rc = shell_exec(&data, azCmd[i], &zErrMsg);
  15140. if( zErrMsg!=0 ){
  15141. utf8_printf(stderr,"Error: %s\n", zErrMsg);
  15142. return rc!=0 ? rc : 1;
  15143. }else if( rc!=0 ){
  15144. utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  15145. return rc;
  15146. }
  15147. }
  15148. }
  15149. free(azCmd);
  15150. }else{
  15151. /* Run commands received from standard input
  15152. */
  15153. if( stdin_is_interactive ){
  15154. char *zHome;
  15155. char *zHistory = 0;
  15156. int nHistory;
  15157. printf(
  15158. "SQLite version %s %.19s\n" /*extra-version-info*/
  15159. "Enter \".help\" for usage hints.\n",
  15160. sqlite3_libversion(), sqlite3_sourceid()
  15161. );
  15162. if( warnInmemoryDb ){
  15163. printf("Connected to a ");
  15164. printBold("transient in-memory database");
  15165. printf(".\nUse \".open FILENAME\" to reopen on a "
  15166. "persistent database.\n");
  15167. }
  15168. zHome = find_home_dir(0);
  15169. if( zHome ){
  15170. nHistory = strlen30(zHome) + 20;
  15171. if( (zHistory = malloc(nHistory))!=0 ){
  15172. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  15173. }
  15174. }
  15175. if( zHistory ){ shell_read_history(zHistory); }
  15176. #if HAVE_READLINE || HAVE_EDITLINE
  15177. rl_attempted_completion_function = readline_completion;
  15178. #elif HAVE_LINENOISE
  15179. linenoiseSetCompletionCallback(linenoise_completion);
  15180. #endif
  15181. rc = process_input(&data, 0);
  15182. if( zHistory ){
  15183. shell_stifle_history(2000);
  15184. shell_write_history(zHistory);
  15185. free(zHistory);
  15186. }
  15187. }else{
  15188. rc = process_input(&data, stdin);
  15189. }
  15190. }
  15191. set_table_name(&data, 0);
  15192. if( data.db ){
  15193. session_close_all(&data);
  15194. close_db(data.db);
  15195. }
  15196. sqlite3_free(data.zFreeOnClose);
  15197. find_home_dir(1);
  15198. output_reset(&data);
  15199. data.doXdgOpen = 0;
  15200. clearTempFile(&data);
  15201. #if !SQLITE_SHELL_IS_UTF8
  15202. for(i=0; i<argcToFree; i++) free(argvToFree[i]);
  15203. free(argvToFree);
  15204. #endif
  15205. /* Clear the global data structure so that valgrind will detect memory
  15206. ** leaks */
  15207. memset(&data, 0, sizeof(data));
  15208. return rc;
  15209. }