PageRenderTime 69ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/libdb/sqlite/sqlite-amalgamation/shell.c

https://bitbucket.org/arrowdodger/lineage
C | 2733 lines | 2271 code | 145 blank | 317 comment | 543 complexity | 60acccd46008a48e26b2f1f34fa9195e MD5 | raw file

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

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