PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/3rd_party/sqlite3/sqlite3/shell.c

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

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