PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/sqlcipher/src/shell.c

https://code.google.com/p/owasp-igoat/
C | 3135 lines | 2902 code | 86 blank | 147 comment | 333 complexity | 6449c5f2c0b5ec8d90bbbd05bfc493c9 MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains code to implement the "sqlite" command line
  13. ** utility for accessing SQLite databases.
  14. */
  15. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  16. /* This needs to come before any includes for MSVC compiler */
  17. #define _CRT_SECURE_NO_WARNINGS
  18. #endif
  19. /*
  20. ** Enable large-file support for fopen() and friends on unix.
  21. */
  22. #ifndef SQLITE_DISABLE_LFS
  23. # define _LARGE_FILE 1
  24. # ifndef _FILE_OFFSET_BITS
  25. # define _FILE_OFFSET_BITS 64
  26. # endif
  27. # define _LARGEFILE_SOURCE 1
  28. #endif
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <stdio.h>
  32. #include <assert.h>
  33. #include "sqlite3.h"
  34. #include <ctype.h>
  35. #include <stdarg.h>
  36. #if !defined(_WIN32) && !defined(WIN32)
  37. # include <signal.h>
  38. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  39. # include <pwd.h>
  40. # endif
  41. # include <unistd.h>
  42. # include <sys/types.h>
  43. #endif
  44. #ifdef HAVE_EDITLINE
  45. # include <editline/editline.h>
  46. #endif
  47. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  48. # include <readline/readline.h>
  49. # include <readline/history.h>
  50. #endif
  51. #if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1)
  52. # define readline(p) local_getline(p,stdin,0)
  53. # define add_history(X)
  54. # define read_history(X)
  55. # define write_history(X)
  56. # define stifle_history(X)
  57. #endif
  58. #if defined(_WIN32) || defined(WIN32)
  59. # include <io.h>
  60. #define isatty(h) _isatty(h)
  61. #define access(f,m) _access((f),(m))
  62. #undef popen
  63. #define popen(a,b) _popen((a),(b))
  64. #undef pclose
  65. #define pclose(x) _pclose(x)
  66. #else
  67. /* Make sure isatty() has a prototype.
  68. */
  69. extern int isatty(int);
  70. #endif
  71. #if defined(_WIN32_WCE)
  72. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  73. * thus we always assume that we have a console. That can be
  74. * overridden with the -batch command line option.
  75. */
  76. #define isatty(x) 1
  77. #endif
  78. /* True if the timer is enabled */
  79. static int enableTimer = 0;
  80. /* ctype macros that work with signed characters */
  81. #define IsSpace(X) isspace((unsigned char)X)
  82. #define IsDigit(X) isdigit((unsigned char)X)
  83. #define ToLower(X) (char)tolower((unsigned char)X)
  84. #if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL)
  85. #include <sys/time.h>
  86. #include <sys/resource.h>
  87. /* Saved resource information for the beginning of an operation */
  88. static struct rusage sBegin;
  89. /*
  90. ** Begin timing an operation
  91. */
  92. static void beginTimer(void){
  93. if( enableTimer ){
  94. getrusage(RUSAGE_SELF, &sBegin);
  95. }
  96. }
  97. /* Return the difference of two time_structs in seconds */
  98. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  99. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  100. (double)(pEnd->tv_sec - pStart->tv_sec);
  101. }
  102. /*
  103. ** Print the timing results.
  104. */
  105. static void endTimer(void){
  106. if( enableTimer ){
  107. struct rusage sEnd;
  108. getrusage(RUSAGE_SELF, &sEnd);
  109. printf("CPU Time: user %f sys %f\n",
  110. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  111. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  112. }
  113. }
  114. #define BEGIN_TIMER beginTimer()
  115. #define END_TIMER endTimer()
  116. #define HAS_TIMER 1
  117. #elif (defined(_WIN32) || defined(WIN32))
  118. #include <windows.h>
  119. /* Saved resource information for the beginning of an operation */
  120. static HANDLE hProcess;
  121. static FILETIME ftKernelBegin;
  122. static FILETIME ftUserBegin;
  123. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
  124. static GETPROCTIMES getProcessTimesAddr = NULL;
  125. /*
  126. ** Check to see if we have timer support. Return 1 if necessary
  127. ** support found (or found previously).
  128. */
  129. static int hasTimer(void){
  130. if( getProcessTimesAddr ){
  131. return 1;
  132. } else {
  133. /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
  134. ** See if the version we are running on has it, and if it does, save off
  135. ** a pointer to it and the current process handle.
  136. */
  137. hProcess = GetCurrentProcess();
  138. if( hProcess ){
  139. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  140. if( NULL != hinstLib ){
  141. getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  142. if( NULL != getProcessTimesAddr ){
  143. return 1;
  144. }
  145. FreeLibrary(hinstLib);
  146. }
  147. }
  148. }
  149. return 0;
  150. }
  151. /*
  152. ** Begin timing an operation
  153. */
  154. static void beginTimer(void){
  155. if( enableTimer && getProcessTimesAddr ){
  156. FILETIME ftCreation, ftExit;
  157. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
  158. }
  159. }
  160. /* Return the difference of two FILETIME structs in seconds */
  161. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  162. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  163. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  164. return (double) ((i64End - i64Start) / 10000000.0);
  165. }
  166. /*
  167. ** Print the timing results.
  168. */
  169. static void endTimer(void){
  170. if( enableTimer && getProcessTimesAddr){
  171. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  172. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
  173. printf("CPU Time: user %f sys %f\n",
  174. timeDiff(&ftUserBegin, &ftUserEnd),
  175. timeDiff(&ftKernelBegin, &ftKernelEnd));
  176. }
  177. }
  178. #define BEGIN_TIMER beginTimer()
  179. #define END_TIMER endTimer()
  180. #define HAS_TIMER hasTimer()
  181. #else
  182. #define BEGIN_TIMER
  183. #define END_TIMER
  184. #define HAS_TIMER 0
  185. #endif
  186. /*
  187. ** Used to prevent warnings about unused parameters
  188. */
  189. #define UNUSED_PARAMETER(x) (void)(x)
  190. /*
  191. ** If the following flag is set, then command execution stops
  192. ** at an error if we are not interactive.
  193. */
  194. static int bail_on_error = 0;
  195. /*
  196. ** Threat stdin as an interactive input if the following variable
  197. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  198. */
  199. static int stdin_is_interactive = 1;
  200. /*
  201. ** The following is the open SQLite database. We make a pointer
  202. ** to this database a static variable so that it can be accessed
  203. ** by the SIGINT handler to interrupt database processing.
  204. */
  205. static sqlite3 *db = 0;
  206. /*
  207. ** True if an interrupt (Control-C) has been received.
  208. */
  209. static volatile int seenInterrupt = 0;
  210. /*
  211. ** This is the name of our program. It is set in main(), used
  212. ** in a number of other places, mostly for error messages.
  213. */
  214. static char *Argv0;
  215. /*
  216. ** Prompt strings. Initialized in main. Settable with
  217. ** .prompt main continue
  218. */
  219. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  220. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  221. /*
  222. ** Write I/O traces to the following stream.
  223. */
  224. #ifdef SQLITE_ENABLE_IOTRACE
  225. static FILE *iotrace = 0;
  226. #endif
  227. /*
  228. ** This routine works like printf in that its first argument is a
  229. ** format string and subsequent arguments are values to be substituted
  230. ** in place of % fields. The result of formatting this string
  231. ** is written to iotrace.
  232. */
  233. #ifdef SQLITE_ENABLE_IOTRACE
  234. static void iotracePrintf(const char *zFormat, ...){
  235. va_list ap;
  236. char *z;
  237. if( iotrace==0 ) return;
  238. va_start(ap, zFormat);
  239. z = sqlite3_vmprintf(zFormat, ap);
  240. va_end(ap);
  241. fprintf(iotrace, "%s", z);
  242. sqlite3_free(z);
  243. }
  244. #endif
  245. /*
  246. ** Determines if a string is a number of not.
  247. */
  248. static int isNumber(const char *z, int *realnum){
  249. if( *z=='-' || *z=='+' ) z++;
  250. if( !IsDigit(*z) ){
  251. return 0;
  252. }
  253. z++;
  254. if( realnum ) *realnum = 0;
  255. while( IsDigit(*z) ){ z++; }
  256. if( *z=='.' ){
  257. z++;
  258. if( !IsDigit(*z) ) return 0;
  259. while( IsDigit(*z) ){ z++; }
  260. if( realnum ) *realnum = 1;
  261. }
  262. if( *z=='e' || *z=='E' ){
  263. z++;
  264. if( *z=='+' || *z=='-' ) z++;
  265. if( !IsDigit(*z) ) return 0;
  266. while( IsDigit(*z) ){ z++; }
  267. if( realnum ) *realnum = 1;
  268. }
  269. return *z==0;
  270. }
  271. /*
  272. ** A global char* and an SQL function to access its current value
  273. ** from within an SQL statement. This program used to use the
  274. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  275. ** The correct way to do this with sqlite3 is to use the bind API, but
  276. ** since the shell is built around the callback paradigm it would be a lot
  277. ** of work. Instead just use this hack, which is quite harmless.
  278. */
  279. static const char *zShellStatic = 0;
  280. static void shellstaticFunc(
  281. sqlite3_context *context,
  282. int argc,
  283. sqlite3_value **argv
  284. ){
  285. assert( 0==argc );
  286. assert( zShellStatic );
  287. UNUSED_PARAMETER(argc);
  288. UNUSED_PARAMETER(argv);
  289. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  290. }
  291. /*
  292. ** This routine reads a line of text from FILE in, stores
  293. ** the text in memory obtained from malloc() and returns a pointer
  294. ** to the text. NULL is returned at end of file, or if malloc()
  295. ** fails.
  296. **
  297. ** The interface is like "readline" but no command-line editing
  298. ** is done.
  299. */
  300. static char *local_getline(char *zPrompt, FILE *in, int csvFlag){
  301. char *zLine;
  302. int nLine;
  303. int n;
  304. int inQuote = 0;
  305. if( zPrompt && *zPrompt ){
  306. printf("%s",zPrompt);
  307. fflush(stdout);
  308. }
  309. nLine = 100;
  310. zLine = malloc( nLine );
  311. if( zLine==0 ) return 0;
  312. n = 0;
  313. while( 1 ){
  314. if( n+100>nLine ){
  315. nLine = nLine*2 + 100;
  316. zLine = realloc(zLine, nLine);
  317. if( zLine==0 ) return 0;
  318. }
  319. if( fgets(&zLine[n], nLine - n, in)==0 ){
  320. if( n==0 ){
  321. free(zLine);
  322. return 0;
  323. }
  324. zLine[n] = 0;
  325. break;
  326. }
  327. while( zLine[n] ){
  328. if( zLine[n]=='"' ) inQuote = !inQuote;
  329. n++;
  330. }
  331. if( n>0 && zLine[n-1]=='\n' && (!inQuote || !csvFlag) ){
  332. n--;
  333. if( n>0 && zLine[n-1]=='\r' ) n--;
  334. zLine[n] = 0;
  335. break;
  336. }
  337. }
  338. zLine = realloc( zLine, n+1 );
  339. return zLine;
  340. }
  341. /*
  342. ** Retrieve a single line of input text.
  343. **
  344. ** zPrior is a string of prior text retrieved. If not the empty
  345. ** string, then issue a continuation prompt.
  346. */
  347. static char *one_input_line(const char *zPrior, FILE *in){
  348. char *zPrompt;
  349. char *zResult;
  350. if( in!=0 ){
  351. return local_getline(0, in, 0);
  352. }
  353. if( zPrior && zPrior[0] ){
  354. zPrompt = continuePrompt;
  355. }else{
  356. zPrompt = mainPrompt;
  357. }
  358. zResult = readline(zPrompt);
  359. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  360. if( zResult && *zResult ) add_history(zResult);
  361. #endif
  362. return zResult;
  363. }
  364. struct previous_mode_data {
  365. int valid; /* Is there legit data in here? */
  366. int mode;
  367. int showHeader;
  368. int colWidth[100];
  369. };
  370. /*
  371. ** An pointer to an instance of this structure is passed from
  372. ** the main program to the callback. This is used to communicate
  373. ** state and mode information.
  374. */
  375. struct callback_data {
  376. sqlite3 *db; /* The database */
  377. int echoOn; /* True to echo input commands */
  378. int statsOn; /* True to display memory stats before each finalize */
  379. int cnt; /* Number of records displayed so far */
  380. FILE *out; /* Write results here */
  381. FILE *traceOut; /* Output for sqlite3_trace() */
  382. int nErr; /* Number of errors seen */
  383. int mode; /* An output mode setting */
  384. int writableSchema; /* True if PRAGMA writable_schema=ON */
  385. int showHeader; /* True to show column names in List or Column mode */
  386. char *zDestTable; /* Name of destination table when MODE_Insert */
  387. char separator[20]; /* Separator character for MODE_List */
  388. int colWidth[100]; /* Requested width of each column when in column mode*/
  389. int actualWidth[100]; /* Actual width of each column */
  390. char nullvalue[20]; /* The text to print when a NULL comes back from
  391. ** the database */
  392. struct previous_mode_data explainPrev;
  393. /* Holds the mode information just before
  394. ** .explain ON */
  395. char outfile[FILENAME_MAX]; /* Filename for *out */
  396. const char *zDbFilename; /* name of the database file */
  397. const char *zVfs; /* Name of VFS to use */
  398. sqlite3_stmt *pStmt; /* Current statement if any. */
  399. FILE *pLog; /* Write log output here */
  400. };
  401. /*
  402. ** These are the allowed modes.
  403. */
  404. #define MODE_Line 0 /* One column per line. Blank line between records */
  405. #define MODE_Column 1 /* One record per line in neat columns */
  406. #define MODE_List 2 /* One record per line with a separator */
  407. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  408. #define MODE_Html 4 /* Generate an XHTML table */
  409. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  410. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  411. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  412. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  413. static const char *modeDescr[] = {
  414. "line",
  415. "column",
  416. "list",
  417. "semi",
  418. "html",
  419. "insert",
  420. "tcl",
  421. "csv",
  422. "explain",
  423. };
  424. /*
  425. ** Number of elements in an array
  426. */
  427. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  428. /*
  429. ** Compute a string length that is limited to what can be stored in
  430. ** lower 30 bits of a 32-bit signed integer.
  431. */
  432. static int strlen30(const char *z){
  433. const char *z2 = z;
  434. while( *z2 ){ z2++; }
  435. return 0x3fffffff & (int)(z2 - z);
  436. }
  437. /*
  438. ** A callback for the sqlite3_log() interface.
  439. */
  440. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  441. struct callback_data *p = (struct callback_data*)pArg;
  442. if( p->pLog==0 ) return;
  443. fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  444. fflush(p->pLog);
  445. }
  446. /*
  447. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  448. */
  449. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  450. int i;
  451. char *zBlob = (char *)pBlob;
  452. fprintf(out,"X'");
  453. for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]&0xff); }
  454. fprintf(out,"'");
  455. }
  456. /*
  457. ** Output the given string as a quoted string using SQL quoting conventions.
  458. */
  459. static void output_quoted_string(FILE *out, const char *z){
  460. int i;
  461. int nSingle = 0;
  462. for(i=0; z[i]; i++){
  463. if( z[i]=='\'' ) nSingle++;
  464. }
  465. if( nSingle==0 ){
  466. fprintf(out,"'%s'",z);
  467. }else{
  468. fprintf(out,"'");
  469. while( *z ){
  470. for(i=0; z[i] && z[i]!='\''; i++){}
  471. if( i==0 ){
  472. fprintf(out,"''");
  473. z++;
  474. }else if( z[i]=='\'' ){
  475. fprintf(out,"%.*s''",i,z);
  476. z += i+1;
  477. }else{
  478. fprintf(out,"%s",z);
  479. break;
  480. }
  481. }
  482. fprintf(out,"'");
  483. }
  484. }
  485. /*
  486. ** Output the given string as a quoted according to C or TCL quoting rules.
  487. */
  488. static void output_c_string(FILE *out, const char *z){
  489. unsigned int c;
  490. fputc('"', out);
  491. while( (c = *(z++))!=0 ){
  492. if( c=='\\' ){
  493. fputc(c, out);
  494. fputc(c, out);
  495. }else if( c=='\t' ){
  496. fputc('\\', out);
  497. fputc('t', out);
  498. }else if( c=='\n' ){
  499. fputc('\\', out);
  500. fputc('n', out);
  501. }else if( c=='\r' ){
  502. fputc('\\', out);
  503. fputc('r', out);
  504. }else if( !isprint(c) ){
  505. fprintf(out, "\\%03o", c&0xff);
  506. }else{
  507. fputc(c, out);
  508. }
  509. }
  510. fputc('"', out);
  511. }
  512. /*
  513. ** Output the given string with characters that are special to
  514. ** HTML escaped.
  515. */
  516. static void output_html_string(FILE *out, const char *z){
  517. int i;
  518. while( *z ){
  519. for(i=0; z[i]
  520. && z[i]!='<'
  521. && z[i]!='&'
  522. && z[i]!='>'
  523. && z[i]!='\"'
  524. && z[i]!='\'';
  525. i++){}
  526. if( i>0 ){
  527. fprintf(out,"%.*s",i,z);
  528. }
  529. if( z[i]=='<' ){
  530. fprintf(out,"&lt;");
  531. }else if( z[i]=='&' ){
  532. fprintf(out,"&amp;");
  533. }else if( z[i]=='>' ){
  534. fprintf(out,"&gt;");
  535. }else if( z[i]=='\"' ){
  536. fprintf(out,"&quot;");
  537. }else if( z[i]=='\'' ){
  538. fprintf(out,"&#39;");
  539. }else{
  540. break;
  541. }
  542. z += i + 1;
  543. }
  544. }
  545. /*
  546. ** If a field contains any character identified by a 1 in the following
  547. ** array, then the string must be quoted for CSV.
  548. */
  549. static const char needCsvQuote[] = {
  550. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  551. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  552. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  558. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  559. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  560. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  561. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  562. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  563. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  564. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  565. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  566. };
  567. /*
  568. ** Output a single term of CSV. Actually, p->separator is used for
  569. ** the separator, which may or may not be a comma. p->nullvalue is
  570. ** the null value. Strings are quoted if necessary.
  571. */
  572. static void output_csv(struct callback_data *p, const char *z, int bSep){
  573. FILE *out = p->out;
  574. if( z==0 ){
  575. fprintf(out,"%s",p->nullvalue);
  576. }else{
  577. int i;
  578. int nSep = strlen30(p->separator);
  579. for(i=0; z[i]; i++){
  580. if( needCsvQuote[((unsigned char*)z)[i]]
  581. || (z[i]==p->separator[0] &&
  582. (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
  583. i = 0;
  584. break;
  585. }
  586. }
  587. if( i==0 ){
  588. putc('"', out);
  589. for(i=0; z[i]; i++){
  590. if( z[i]=='"' ) putc('"', out);
  591. putc(z[i], out);
  592. }
  593. putc('"', out);
  594. }else{
  595. fprintf(out, "%s", z);
  596. }
  597. }
  598. if( bSep ){
  599. fprintf(p->out, "%s", p->separator);
  600. }
  601. }
  602. #ifdef SIGINT
  603. /*
  604. ** This routine runs when the user presses Ctrl-C
  605. */
  606. static void interrupt_handler(int NotUsed){
  607. UNUSED_PARAMETER(NotUsed);
  608. seenInterrupt = 1;
  609. if( db ) sqlite3_interrupt(db);
  610. }
  611. #endif
  612. /*
  613. ** This is the callback routine that the shell
  614. ** invokes for each row of a query result.
  615. */
  616. static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
  617. int i;
  618. struct callback_data *p = (struct callback_data*)pArg;
  619. switch( p->mode ){
  620. case MODE_Line: {
  621. int w = 5;
  622. if( azArg==0 ) break;
  623. for(i=0; i<nArg; i++){
  624. int len = strlen30(azCol[i] ? azCol[i] : "");
  625. if( len>w ) w = len;
  626. }
  627. if( p->cnt++>0 ) fprintf(p->out,"\n");
  628. for(i=0; i<nArg; i++){
  629. fprintf(p->out,"%*s = %s\n", w, azCol[i],
  630. azArg[i] ? azArg[i] : p->nullvalue);
  631. }
  632. break;
  633. }
  634. case MODE_Explain:
  635. case MODE_Column: {
  636. if( p->cnt++==0 ){
  637. for(i=0; i<nArg; i++){
  638. int w, n;
  639. if( i<ArraySize(p->colWidth) ){
  640. w = p->colWidth[i];
  641. }else{
  642. w = 0;
  643. }
  644. if( w<=0 ){
  645. w = strlen30(azCol[i] ? azCol[i] : "");
  646. if( w<10 ) w = 10;
  647. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  648. if( w<n ) w = n;
  649. }
  650. if( i<ArraySize(p->actualWidth) ){
  651. p->actualWidth[i] = w;
  652. }
  653. if( p->showHeader ){
  654. fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
  655. }
  656. }
  657. if( p->showHeader ){
  658. for(i=0; i<nArg; i++){
  659. int w;
  660. if( i<ArraySize(p->actualWidth) ){
  661. w = p->actualWidth[i];
  662. }else{
  663. w = 10;
  664. }
  665. fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  666. "----------------------------------------------------------",
  667. i==nArg-1 ? "\n": " ");
  668. }
  669. }
  670. }
  671. if( azArg==0 ) break;
  672. for(i=0; i<nArg; i++){
  673. int w;
  674. if( i<ArraySize(p->actualWidth) ){
  675. w = p->actualWidth[i];
  676. }else{
  677. w = 10;
  678. }
  679. if( p->mode==MODE_Explain && azArg[i] &&
  680. strlen30(azArg[i])>w ){
  681. w = strlen30(azArg[i]);
  682. }
  683. fprintf(p->out,"%-*.*s%s",w,w,
  684. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  685. }
  686. break;
  687. }
  688. case MODE_Semi:
  689. case MODE_List: {
  690. if( p->cnt++==0 && p->showHeader ){
  691. for(i=0; i<nArg; i++){
  692. fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  693. }
  694. }
  695. if( azArg==0 ) break;
  696. for(i=0; i<nArg; i++){
  697. char *z = azArg[i];
  698. if( z==0 ) z = p->nullvalue;
  699. fprintf(p->out, "%s", z);
  700. if( i<nArg-1 ){
  701. fprintf(p->out, "%s", p->separator);
  702. }else if( p->mode==MODE_Semi ){
  703. fprintf(p->out, ";\n");
  704. }else{
  705. fprintf(p->out, "\n");
  706. }
  707. }
  708. break;
  709. }
  710. case MODE_Html: {
  711. if( p->cnt++==0 && p->showHeader ){
  712. fprintf(p->out,"<TR>");
  713. for(i=0; i<nArg; i++){
  714. fprintf(p->out,"<TH>");
  715. output_html_string(p->out, azCol[i]);
  716. fprintf(p->out,"</TH>\n");
  717. }
  718. fprintf(p->out,"</TR>\n");
  719. }
  720. if( azArg==0 ) break;
  721. fprintf(p->out,"<TR>");
  722. for(i=0; i<nArg; i++){
  723. fprintf(p->out,"<TD>");
  724. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  725. fprintf(p->out,"</TD>\n");
  726. }
  727. fprintf(p->out,"</TR>\n");
  728. break;
  729. }
  730. case MODE_Tcl: {
  731. if( p->cnt++==0 && p->showHeader ){
  732. for(i=0; i<nArg; i++){
  733. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  734. fprintf(p->out, "%s", p->separator);
  735. }
  736. fprintf(p->out,"\n");
  737. }
  738. if( azArg==0 ) break;
  739. for(i=0; i<nArg; i++){
  740. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  741. fprintf(p->out, "%s", p->separator);
  742. }
  743. fprintf(p->out,"\n");
  744. break;
  745. }
  746. case MODE_Csv: {
  747. if( p->cnt++==0 && p->showHeader ){
  748. for(i=0; i<nArg; i++){
  749. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  750. }
  751. fprintf(p->out,"\n");
  752. }
  753. if( azArg==0 ) break;
  754. for(i=0; i<nArg; i++){
  755. output_csv(p, azArg[i], i<nArg-1);
  756. }
  757. fprintf(p->out,"\n");
  758. break;
  759. }
  760. case MODE_Insert: {
  761. p->cnt++;
  762. if( azArg==0 ) break;
  763. fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  764. for(i=0; i<nArg; i++){
  765. char *zSep = i>0 ? ",": "";
  766. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  767. fprintf(p->out,"%sNULL",zSep);
  768. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  769. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  770. output_quoted_string(p->out, azArg[i]);
  771. }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
  772. fprintf(p->out,"%s%s",zSep, azArg[i]);
  773. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  774. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  775. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  776. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  777. output_hex_blob(p->out, pBlob, nBlob);
  778. }else if( isNumber(azArg[i], 0) ){
  779. fprintf(p->out,"%s%s",zSep, azArg[i]);
  780. }else{
  781. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  782. output_quoted_string(p->out, azArg[i]);
  783. }
  784. }
  785. fprintf(p->out,");\n");
  786. break;
  787. }
  788. }
  789. return 0;
  790. }
  791. /*
  792. ** This is the callback routine that the SQLite library
  793. ** invokes for each row of a query result.
  794. */
  795. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  796. /* since we don't have type info, call the shell_callback with a NULL value */
  797. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  798. }
  799. /*
  800. ** Set the destination table field of the callback_data structure to
  801. ** the name of the table given. Escape any quote characters in the
  802. ** table name.
  803. */
  804. static void set_table_name(struct callback_data *p, const char *zName){
  805. int i, n;
  806. int needQuote;
  807. char *z;
  808. if( p->zDestTable ){
  809. free(p->zDestTable);
  810. p->zDestTable = 0;
  811. }
  812. if( zName==0 ) return;
  813. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  814. for(i=n=0; zName[i]; i++, n++){
  815. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  816. needQuote = 1;
  817. if( zName[i]=='\'' ) n++;
  818. }
  819. }
  820. if( needQuote ) n += 2;
  821. z = p->zDestTable = malloc( n+1 );
  822. if( z==0 ){
  823. fprintf(stderr,"Error: out of memory\n");
  824. exit(1);
  825. }
  826. n = 0;
  827. if( needQuote ) z[n++] = '\'';
  828. for(i=0; zName[i]; i++){
  829. z[n++] = zName[i];
  830. if( zName[i]=='\'' ) z[n++] = '\'';
  831. }
  832. if( needQuote ) z[n++] = '\'';
  833. z[n] = 0;
  834. }
  835. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  836. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  837. ** added to zIn, and the result returned in memory obtained from malloc().
  838. ** zIn, if it was not NULL, is freed.
  839. **
  840. ** If the third argument, quote, is not '\0', then it is used as a
  841. ** quote character for zAppend.
  842. */
  843. static char *appendText(char *zIn, char const *zAppend, char quote){
  844. int len;
  845. int i;
  846. int nAppend = strlen30(zAppend);
  847. int nIn = (zIn?strlen30(zIn):0);
  848. len = nAppend+nIn+1;
  849. if( quote ){
  850. len += 2;
  851. for(i=0; i<nAppend; i++){
  852. if( zAppend[i]==quote ) len++;
  853. }
  854. }
  855. zIn = (char *)realloc(zIn, len);
  856. if( !zIn ){
  857. return 0;
  858. }
  859. if( quote ){
  860. char *zCsr = &zIn[nIn];
  861. *zCsr++ = quote;
  862. for(i=0; i<nAppend; i++){
  863. *zCsr++ = zAppend[i];
  864. if( zAppend[i]==quote ) *zCsr++ = quote;
  865. }
  866. *zCsr++ = quote;
  867. *zCsr++ = '\0';
  868. assert( (zCsr-zIn)==len );
  869. }else{
  870. memcpy(&zIn[nIn], zAppend, nAppend);
  871. zIn[len-1] = '\0';
  872. }
  873. return zIn;
  874. }
  875. /*
  876. ** Execute a query statement that will generate SQL output. Print
  877. ** the result columns, comma-separated, on a line and then add a
  878. ** semicolon terminator to the end of that line.
  879. **
  880. ** If the number of columns is 1 and that column contains text "--"
  881. ** then write the semicolon on a separate line. That way, if a
  882. ** "--" comment occurs at the end of the statement, the comment
  883. ** won't consume the semicolon terminator.
  884. */
  885. static int run_table_dump_query(
  886. struct callback_data *p, /* Query context */
  887. const char *zSelect, /* SELECT statement to extract content */
  888. const char *zFirstRow /* Print before first row, if not NULL */
  889. ){
  890. sqlite3_stmt *pSelect;
  891. int rc;
  892. int nResult;
  893. int i;
  894. const char *z;
  895. rc = sqlite3_prepare(p->db, zSelect, -1, &pSelect, 0);
  896. if( rc!=SQLITE_OK || !pSelect ){
  897. fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  898. p->nErr++;
  899. return rc;
  900. }
  901. rc = sqlite3_step(pSelect);
  902. nResult = sqlite3_column_count(pSelect);
  903. while( rc==SQLITE_ROW ){
  904. if( zFirstRow ){
  905. fprintf(p->out, "%s", zFirstRow);
  906. zFirstRow = 0;
  907. }
  908. z = (const char*)sqlite3_column_text(pSelect, 0);
  909. fprintf(p->out, "%s", z);
  910. for(i=1; i<nResult; i++){
  911. fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  912. }
  913. if( z==0 ) z = "";
  914. while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  915. if( z[0] ){
  916. fprintf(p->out, "\n;\n");
  917. }else{
  918. fprintf(p->out, ";\n");
  919. }
  920. rc = sqlite3_step(pSelect);
  921. }
  922. rc = sqlite3_finalize(pSelect);
  923. if( rc!=SQLITE_OK ){
  924. fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  925. p->nErr++;
  926. }
  927. return rc;
  928. }
  929. /*
  930. ** Allocate space and save off current error string.
  931. */
  932. static char *save_err_msg(
  933. sqlite3 *db /* Database to query */
  934. ){
  935. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  936. char *zErrMsg = sqlite3_malloc(nErrMsg);
  937. if( zErrMsg ){
  938. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  939. }
  940. return zErrMsg;
  941. }
  942. /*
  943. ** Display memory stats.
  944. */
  945. static int display_stats(
  946. sqlite3 *db, /* Database to query */
  947. struct callback_data *pArg, /* Pointer to struct callback_data */
  948. int bReset /* True to reset the stats */
  949. ){
  950. int iCur;
  951. int iHiwtr;
  952. if( pArg && pArg->out ){
  953. iHiwtr = iCur = -1;
  954. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  955. fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr);
  956. iHiwtr = iCur = -1;
  957. sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  958. fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr);
  959. /*
  960. ** Not currently used by the CLI.
  961. ** iHiwtr = iCur = -1;
  962. ** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  963. ** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr);
  964. */
  965. iHiwtr = iCur = -1;
  966. sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  967. fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
  968. /*
  969. ** Not currently used by the CLI.
  970. ** iHiwtr = iCur = -1;
  971. ** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  972. ** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr);
  973. */
  974. iHiwtr = iCur = -1;
  975. sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  976. fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
  977. iHiwtr = iCur = -1;
  978. sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  979. fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr);
  980. iHiwtr = iCur = -1;
  981. sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  982. fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr);
  983. iHiwtr = iCur = -1;
  984. sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  985. fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr);
  986. #ifdef YYTRACKMAXSTACKDEPTH
  987. iHiwtr = iCur = -1;
  988. sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  989. fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr);
  990. #endif
  991. }
  992. if( pArg && pArg->out && db ){
  993. iHiwtr = iCur = -1;
  994. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset);
  995. fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
  996. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset);
  997. fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr);
  998. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset);
  999. fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr);
  1000. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset);
  1001. fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr);
  1002. iHiwtr = iCur = -1;
  1003. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  1004. fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1;
  1005. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  1006. fprintf(pArg->out, "Page cache hits: %d\n", iCur);
  1007. iHiwtr = iCur = -1;
  1008. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  1009. fprintf(pArg->out, "Page cache misses: %d\n", iCur);
  1010. iHiwtr = iCur = -1;
  1011. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  1012. fprintf(pArg->out, "Page cache writes: %d\n", iCur);
  1013. iHiwtr = iCur = -1;
  1014. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  1015. fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur);
  1016. iHiwtr = iCur = -1;
  1017. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  1018. fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur);
  1019. }
  1020. if( pArg && pArg->out && db && pArg->pStmt ){
  1021. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
  1022. fprintf(pArg->out, "Fullscan Steps: %d\n", iCur);
  1023. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  1024. fprintf(pArg->out, "Sort Operations: %d\n", iCur);
  1025. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
  1026. fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  1027. }
  1028. return 0;
  1029. }
  1030. /*
  1031. ** Execute a statement or set of statements. Print
  1032. ** any result rows/columns depending on the current mode
  1033. ** set via the supplied callback.
  1034. **
  1035. ** This is very similar to SQLite's built-in sqlite3_exec()
  1036. ** function except it takes a slightly different callback
  1037. ** and callback data argument.
  1038. */
  1039. static int shell_exec(
  1040. sqlite3 *db, /* An open database */
  1041. const char *zSql, /* SQL to be evaluated */
  1042. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  1043. /* (not the same as sqlite3_exec) */
  1044. struct callback_data *pArg, /* Pointer to struct callback_data */
  1045. char **pzErrMsg /* Error msg written here */
  1046. ){
  1047. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  1048. int rc = SQLITE_OK; /* Return Code */
  1049. int rc2;
  1050. const char *zLeftover; /* Tail of unprocessed SQL */
  1051. if( pzErrMsg ){
  1052. *pzErrMsg = NULL;
  1053. }
  1054. while( zSql[0] && (SQLITE_OK == rc) ){
  1055. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1056. if( SQLITE_OK != rc ){
  1057. if( pzErrMsg ){
  1058. *pzErrMsg = save_err_msg(db);
  1059. }
  1060. }else{
  1061. if( !pStmt ){
  1062. /* this happens for a comment or white-space */
  1063. zSql = zLeftover;
  1064. while( IsSpace(zSql[0]) ) zSql++;
  1065. continue;
  1066. }
  1067. /* save off the prepared statment handle and reset row count */
  1068. if( pArg ){
  1069. pArg->pStmt = pStmt;
  1070. pArg->cnt = 0;
  1071. }
  1072. /* echo the sql statement if echo on */
  1073. if( pArg && pArg->echoOn ){
  1074. const char *zStmtSql = sqlite3_sql(pStmt);
  1075. fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1076. }
  1077. /* Output TESTCTRL_EXPLAIN text of requested */
  1078. if( pArg && pArg->mode==MODE_Explain ){
  1079. const char *zExplain = 0;
  1080. sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
  1081. if( zExplain && zExplain[0] ){
  1082. fprintf(pArg->out, "%s", zExplain);
  1083. }
  1084. }
  1085. /* perform the first step. this will tell us if we
  1086. ** have a result set or not and how wide it is.
  1087. */
  1088. rc = sqlite3_step(pStmt);
  1089. /* if we have a result set... */
  1090. if( SQLITE_ROW == rc ){
  1091. /* if we have a callback... */
  1092. if( xCallback ){
  1093. /* allocate space for col name ptr, value ptr, and type */
  1094. int nCol = sqlite3_column_count(pStmt);
  1095. void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
  1096. if( !pData ){
  1097. rc = SQLITE_NOMEM;
  1098. }else{
  1099. char **azCols = (char **)pData; /* Names of result columns */
  1100. char **azVals = &azCols[nCol]; /* Results */
  1101. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1102. int i;
  1103. assert(sizeof(int) <= sizeof(char *));
  1104. /* save off ptrs to column names */
  1105. for(i=0; i<nCol; i++){
  1106. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1107. }
  1108. do{
  1109. /* extract the data and data types */
  1110. for(i=0; i<nCol; i++){
  1111. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  1112. aiTypes[i] = sqlite3_column_type(pStmt, i);
  1113. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1114. rc = SQLITE_NOMEM;
  1115. break; /* from for */
  1116. }
  1117. } /* end for */
  1118. /* if data and types extracted successfully... */
  1119. if( SQLITE_ROW == rc ){
  1120. /* call the supplied callback with the result row data */
  1121. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1122. rc = SQLITE_ABORT;
  1123. }else{
  1124. rc = sqlite3_step(pStmt);
  1125. }
  1126. }
  1127. } while( SQLITE_ROW == rc );
  1128. sqlite3_free(pData);
  1129. }
  1130. }else{
  1131. do{
  1132. rc = sqlite3_step(pStmt);
  1133. } while( rc == SQLITE_ROW );
  1134. }
  1135. }
  1136. /* print usage stats if stats on */
  1137. if( pArg && pArg->statsOn ){
  1138. display_stats(db, pArg, 0);
  1139. }
  1140. /* Finalize the statement just executed. If this fails, save a
  1141. ** copy of the error message. Otherwise, set zSql to point to the
  1142. ** next statement to execute. */
  1143. rc2 = sqlite3_finalize(pStmt);
  1144. if( rc!=SQLITE_NOMEM ) rc = rc2;
  1145. if( rc==SQLITE_OK ){
  1146. zSql = zLeftover;
  1147. while( IsSpace(zSql[0]) ) zSql++;
  1148. }else if( pzErrMsg ){
  1149. *pzErrMsg = save_err_msg(db);
  1150. }
  1151. /* clear saved stmt handle */
  1152. if( pArg ){
  1153. pArg->pStmt = NULL;
  1154. }
  1155. }
  1156. } /* end while */
  1157. return rc;
  1158. }
  1159. /*
  1160. ** This is a different callback routine used for dumping the database.
  1161. ** Each row received by this callback consists of a table name,
  1162. ** the table type ("index" or "table") and SQL to create the table.
  1163. ** This routine should print text sufficient to recreate the table.
  1164. */
  1165. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1166. int rc;
  1167. const char *zTable;
  1168. const char *zType;
  1169. const char *zSql;
  1170. const char *zPrepStmt = 0;
  1171. struct callback_data *p = (struct callback_data *)pArg;
  1172. UNUSED_PARAMETER(azCol);
  1173. if( nArg!=3 ) return 1;
  1174. zTable = azArg[0];
  1175. zType = azArg[1];
  1176. zSql = azArg[2];
  1177. if( strcmp(zTable, "sqlite_sequence")==0 ){
  1178. zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1179. }else if( strcmp(zTable, "sqlite_stat1")==0 ){
  1180. fprintf(p->out, "ANALYZE sqlite_master;\n");
  1181. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1182. return 0;
  1183. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1184. char *zIns;
  1185. if( !p->writableSchema ){
  1186. fprintf(p->out, "PRAGMA writable_schema=ON;\n");
  1187. p->writableSchema = 1;
  1188. }
  1189. zIns = sqlite3_mprintf(
  1190. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1191. "VALUES('table','%q','%q',0,'%q');",
  1192. zTable, zTable, zSql);
  1193. fprintf(p->out, "%s\n", zIns);
  1194. sqlite3_free(zIns);
  1195. return 0;
  1196. }else{
  1197. fprintf(p->out, "%s;\n", zSql);
  1198. }
  1199. if( strcmp(zType, "table")==0 ){
  1200. sqlite3_stmt *pTableInfo = 0;
  1201. char *zSelect = 0;
  1202. char *zTableInfo = 0;
  1203. char *zTmp = 0;
  1204. int nRow = 0;
  1205. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1206. zTableInfo = appendText(zTableInfo, zTable, '"');
  1207. zTableInfo = appendText(zTableInfo, ");", 0);
  1208. rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
  1209. free(zTableInfo);
  1210. if( rc!=SQLITE_OK || !pTableInfo ){
  1211. return 1;
  1212. }
  1213. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1214. /* Always quote the table name, even if it appears to be pure ascii,
  1215. ** in case it is a keyword. Ex: INSERT INTO "table" ... */
  1216. zTmp = appendText(zTmp, zTable, '"');
  1217. if( zTmp ){
  1218. zSelect = appendText(zSelect, zTmp, '\'');
  1219. free(zTmp);
  1220. }
  1221. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  1222. rc = sqlite3_step(pTableInfo);
  1223. while( rc==SQLITE_ROW ){
  1224. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  1225. zSelect = appendText(zSelect, "quote(", 0);
  1226. zSelect = appendText(zSelect, zText, '"');
  1227. rc = sqlite3_step(pTableInfo);
  1228. if( rc==SQLITE_ROW ){
  1229. zSelect = appendText(zSelect, "), ", 0);
  1230. }else{
  1231. zSelect = appendText(zSelect, ") ", 0);
  1232. }
  1233. nRow++;
  1234. }
  1235. rc = sqlite3_finalize(pTableInfo);
  1236. if( rc!=SQLITE_OK || nRow==0 ){
  1237. free(zSelect);
  1238. return 1;
  1239. }
  1240. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  1241. zSelect = appendText(zSelect, zTable, '"');
  1242. rc = run_table_dump_query(p, zSelect, zPrepStmt);
  1243. if( rc==SQLITE_CORRUPT ){
  1244. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  1245. run_table_dump_query(p, zSelect, 0);
  1246. }
  1247. free(zSelect);
  1248. }
  1249. return 0;
  1250. }
  1251. /*
  1252. ** Run zQuery. Use dump_callback() as the callback routine so that
  1253. ** the contents of the query are output as SQL statements.
  1254. **
  1255. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  1256. ** "ORDER BY rowid DESC" to the end.
  1257. */
  1258. static int run_schema_dump_query(
  1259. struct callback_data *p,
  1260. const char *zQuery
  1261. ){
  1262. int rc;
  1263. char *zErr = 0;
  1264. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  1265. if( rc==SQLITE_CORRUPT ){
  1266. char *zQ2;
  1267. int len = strlen30(zQuery);
  1268. fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
  1269. if( zErr ){
  1270. fprintf(p->out, "/****** %s ******/\n", zErr);
  1271. sqlite3_free(zErr);
  1272. zErr = 0;
  1273. }
  1274. zQ2 = malloc( len+100 );
  1275. if( zQ2==0 ) return rc;
  1276. sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  1277. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  1278. if( rc ){
  1279. fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
  1280. }else{
  1281. rc = SQLITE_CORRUPT;
  1282. }
  1283. sqlite3_free(zErr);
  1284. free(zQ2);
  1285. }
  1286. return rc;
  1287. }
  1288. /*
  1289. ** Text of a help message
  1290. */
  1291. static char zHelp[] =
  1292. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  1293. ".bail ON|OFF Stop after hitting an error. Default OFF\n"
  1294. ".databases List names and files of attached databases\n"
  1295. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  1296. " If TABLE specified, only dump tables matching\n"
  1297. " LIKE pattern TABLE.\n"
  1298. ".echo ON|OFF Turn command echo on or off\n"
  1299. ".exit Exit this program\n"
  1300. ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n"
  1301. " With no args, it turns EXPLAIN on.\n"
  1302. ".header(s) ON|OFF Turn display of headers on or off\n"
  1303. ".help Show this message\n"
  1304. ".import FILE TABLE Import data from FILE into TABLE\n"
  1305. ".indices ?TABLE? Show names of all indices\n"
  1306. " If TABLE specified, only show indices for tables\n"
  1307. " matching LIKE pattern TABLE.\n"
  1308. #ifdef SQLITE_ENABLE_IOTRACE
  1309. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  1310. #endif
  1311. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1312. ".load FILE ?ENTRY? Load an extension library\n"
  1313. #endif
  1314. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  1315. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  1316. " csv Comma-separated values\n"
  1317. " column Left-aligned columns. (See .width)\n"
  1318. " html HTML <table> code\n"
  1319. " insert SQL insert statements for TABLE\n"
  1320. " line One value per line\n"
  1321. " list Values delimited by .separator string\n"
  1322. " tabs Tab-separated values\n"
  1323. " tcl TCL list elements\n"
  1324. ".nullvalue STRING Print STRING in place of NULL values\n"
  1325. ".output FILENAME Send output to FILENAME\n"
  1326. ".output stdout Send output to the screen\n"
  1327. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  1328. ".quit Exit this program\n"
  1329. ".read FILENAME Execute SQL in FILENAME\n"
  1330. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  1331. ".schema ?TABLE? Show the CREATE statements\n"
  1332. " If TABLE specified, only show tables matching\n"
  1333. " LIKE pattern TABLE.\n"
  1334. ".separator STRING Change separator used by output mode and .import\n"
  1335. ".show Show the current values for various settings\n"
  1336. ".stats ON|OFF Turn stats on or off\n"
  1337. ".tables ?TABLE? List names of tables\n"
  1338. " If TABLE specified, only list tables matching\n"
  1339. " LIKE pattern TABLE.\n"
  1340. ".timeout MS Try opening locked tables for MS milliseconds\n"
  1341. ".trace FILE|off Output each SQL statement as it is run\n"
  1342. ".vfsname ?AUX? Print the name of the VFS stack\n"
  1343. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  1344. ;
  1345. static char zTimerHelp[] =
  1346. ".timer ON|OFF Turn the CPU timer measurement on or off\n"
  1347. ;
  1348. /* Forward reference */
  1349. static int process_input(struct callback_data *p, FILE *in);
  1350. /*
  1351. ** Make sure the database is open. If it is not, then open it. If
  1352. ** the database fails to open, print an error message and exit.
  1353. */
  1354. static void open_db(struct callback_data *p){
  1355. if( p->db==0 ){
  1356. sqlite3_initialize();
  1357. sqlite3_open(p->zDbFilename, &p->db);
  1358. db = p->db;
  1359. if( db && sqlite3_errcode(db)==SQLITE_OK ){
  1360. sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  1361. shellstaticFunc, 0, 0);
  1362. }
  1363. if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  1364. fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
  1365. p->zDbFilename, sqlite3_errmsg(db));
  1366. exit(1);
  1367. }
  1368. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1369. sqlite3_enable_load_extension(p->db, 1);
  1370. #endif
  1371. }
  1372. }
  1373. /*
  1374. ** Do C-language style dequoting.
  1375. **
  1376. ** \t -> tab
  1377. ** \n -> newline
  1378. ** \r -> carriage return
  1379. ** \NNN -> ascii character NNN in octal
  1380. ** \\ -> backslash
  1381. */
  1382. static void resolve_backslashes(char *z){
  1383. int i, j;
  1384. char c;
  1385. for(i=j=0; (c = z[i])!=0; i++, j++){
  1386. if( c=='\\' ){
  1387. c = z[++i];
  1388. if( c=='n' ){
  1389. c = '\n';
  1390. }else if( c=='t' ){
  1391. c = '\t';
  1392. }else if( c=='r' ){
  1393. c = '\r';
  1394. }else if( c>='0' && c<='7' ){
  1395. c -= '0';
  1396. if( z[i+1]>='0' && z[i+1]<='7' ){
  1397. i++;
  1398. c = (c<<3) + z[i] - '0';
  1399. if( z[i+1]>='0' && z[i+1]<='7' ){
  1400. i++;
  1401. c = (c<<3) + z[i] - '0';
  1402. }
  1403. }
  1404. }
  1405. }
  1406. z[j] = c;
  1407. }
  1408. z[j] = 0;
  1409. }
  1410. /*
  1411. ** Interpret zArg as a boolean value. Return either 0 or 1.
  1412. */
  1413. static int booleanValue(char *zArg){
  1414. int val = atoi(zArg);
  1415. int j;
  1416. for(j=0; zArg[j]; j++){
  1417. zArg[j] = ToLower(zArg[j]);
  1418. }
  1419. if( strcmp(zArg,"on")==0 ){
  1420. val = 1;
  1421. }else if( strcmp(zArg,"yes")==0 ){
  1422. val = 1;
  1423. }
  1424. return val;
  1425. }
  1426. /*
  1427. ** Close an output file, assuming it is not stderr or stdout
  1428. */
  1429. static void output_file_close(FILE *f){
  1430. if( f && f!=stdout && f!=stderr ) fclose(f);
  1431. }
  1432. /*
  1433. ** Try to open an output file. The names "stdout" and "stderr" are
  1434. ** recognized and do the right thing. NULL is returned if the output
  1435. ** filename is "off".
  1436. */
  1437. static FILE *output_file_open(const char *zFile){
  1438. FILE *f;
  1439. if( strcmp(zFile,"stdout")==0 ){
  1440. f = stdout;
  1441. }else if( strcmp(zFile, "stderr")==0 ){
  1442. f = stderr;
  1443. }else if( strcmp(zFile, "off")==0 ){
  1444. f = 0;
  1445. }else{
  1446. f = fopen(zFile, "wb");
  1447. if( f==0 ){
  1448. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  1449. }
  1450. }
  1451. return f;
  1452. }
  1453. /*
  1454. ** A routine for handling output from sqlite3_trace().
  1455. */
  1456. static void sql_trace_callback(void *pArg, const char *z){
  1457. FILE *f = (FILE*)pArg;
  1458. if( f ) fprintf(f, "%s\n", z);
  1459. }
  1460. /*
  1461. ** A no-op routine that runs with the ".breakpoint" doc-command. This is
  1462. ** a useful spot to set a debugger breakpoint.
  1463. */
  1464. static void test_breakpoint(void){
  1465. static int nCall = 0;
  1466. nCall++;
  1467. }
  1468. /*
  1469. ** If an input line begins with "." then invoke this routine to
  1470. ** process that line.
  1471. **
  1472. ** Return 1 on error, 2 to exit, and 0 otherwise.
  1473. */
  1474. static int do_meta_command(char *zLine, struct callback_data *p){
  1475. int i = 1;
  1476. int nArg = 0;
  1477. int n, c;
  1478. int rc = 0;
  1479. char *azArg[50];
  1480. /* Parse the input line into tokens.
  1481. */
  1482. while( zLine[i] && nArg<ArraySize(azArg) ){
  1483. while( IsSpace(zLine[i]) ){ i++; }
  1484. if( zLine[i]==0 ) break;
  1485. if( zLine[i]=='\'' || zLine[i]=='"' ){
  1486. int delim = zLine[i++];
  1487. azArg[nArg++] = &zLine[i];
  1488. while( zLine[i] && zLine[i]!=delim ){ i++; }
  1489. if( zLine[i]==delim ){
  1490. zLine[i++] = 0;
  1491. }
  1492. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  1493. }else{
  1494. azArg[nArg++] = &zLine[i];
  1495. while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
  1496. if( zLine[i] ) zLine[i++] = 0;
  1497. resolve_backslashes(azArg[nArg-1]);
  1498. }
  1499. }
  1500. /* Process the input line.
  1501. */
  1502. if( nArg==0 ) return 0; /* no tokens, no error */
  1503. n = strlen30(azArg[0]);
  1504. c = azArg[0][0];
  1505. if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){
  1506. const char *zDestFile;
  1507. const char *zDb;
  1508. sqlite3 *pDest;
  1509. sqlite3_backup *pBackup;
  1510. if( nArg==2 ){
  1511. zDestFile = azArg[1];
  1512. zDb = "main";
  1513. }else{
  1514. zDestFile = azArg[2];
  1515. zDb = azArg[1];
  1516. }
  1517. rc = sqlite3_open(zDestFile, &pDest);
  1518. if( rc!=SQLITE_OK ){
  1519. fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  1520. sqlite3_close(pDest);
  1521. return 1;
  1522. }
  1523. open_db(p);
  1524. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  1525. if( pBackup==0 ){
  1526. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1527. sqlite3_close(pDest);
  1528. return 1;
  1529. }
  1530. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  1531. sqlite3_backup_finish(pBackup);
  1532. if( rc==SQLITE_DONE ){
  1533. rc = 0;
  1534. }else{
  1535. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1536. rc = 1;
  1537. }
  1538. sqlite3_close(pDest);
  1539. }else
  1540. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
  1541. bail_on_error = booleanValue(azArg[1]);
  1542. }else
  1543. /* The undocumented ".breakpoint" command causes a call to the no-op
  1544. ** routine named test_breakpoint().
  1545. */
  1546. if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  1547. test_breakpoint();
  1548. }else
  1549. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
  1550. struct callback_data data;
  1551. char *zErrMsg = 0;
  1552. open_db(p);
  1553. memcpy(&data, p, size

Large files files are truncated, but you can click here to view the full file