PageRenderTime 248ms CodeModel.GetById 57ms RepoModel.GetById 0ms app.codeStats 1ms

/lib_sqlite/shell.c

https://bitbucket.org/xixs/lua
C | 3396 lines | 2849 code | 170 blank | 377 comment | 643 complexity | f6f6d7dc7d7d115f28ae5d032e646270 MD5 | raw file
Possible License(s): Zlib, BSD-3-Clause, CC0-1.0, GPL-3.0, GPL-2.0, CPL-1.0, MPL-2.0-no-copyleft-exception, LGPL-2.0, LGPL-2.1, LGPL-3.0, 0BSD, Cube

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

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