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

/MultiSource/Applications/sqlite3/shell.c

https://github.com/sandssss/test-suite
C | 2087 lines | 1754 code | 103 blank | 230 comment | 378 complexity | 916dc56fa77d1fc6be4f5a31b632b847 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception

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

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