PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/shell.c

https://github.com/qiuping/sqlcipher
C | 2233 lines | 1882 code | 109 blank | 242 comment | 412 complexity | e42b06762b4d8f30279ec27d951d4d2e MD5 | raw 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.201 2009/02/04 22:46:47 drh Exp $
  16. */
  17. #if defined(_WIN32) || defined(WIN32)
  18. /* This needs to come before any includes for MSVC compiler */
  19. #define _CRT_SECURE_NO_WARNINGS
  20. #endif
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <stdio.h>
  24. #include <assert.h>
  25. #include "sqlite3.h"
  26. #include <ctype.h>
  27. #include <stdarg.h>
  28. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
  29. # include <signal.h>
  30. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  31. # include <pwd.h>
  32. # endif
  33. # include <unistd.h>
  34. # include <sys/types.h>
  35. #endif
  36. #ifdef __OS2__
  37. # include <unistd.h>
  38. #endif
  39. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  40. # include <readline/readline.h>
  41. # include <readline/history.h>
  42. #else
  43. # define readline(p) local_getline(p,stdin)
  44. # define add_history(X)
  45. # define read_history(X)
  46. # define write_history(X)
  47. # define stifle_history(X)
  48. #endif
  49. #if defined(_WIN32) || defined(WIN32)
  50. # include <io.h>
  51. #define isatty(h) _isatty(h)
  52. #define access(f,m) _access((f),(m))
  53. #else
  54. /* Make sure isatty() has a prototype.
  55. */
  56. extern int isatty();
  57. #endif
  58. #if defined(_WIN32_WCE)
  59. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  60. * thus we always assume that we have a console. That can be
  61. * overridden with the -batch command line option.
  62. */
  63. #define isatty(x) 1
  64. #endif
  65. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  66. #include <sys/time.h>
  67. #include <sys/resource.h>
  68. /* Saved resource information for the beginning of an operation */
  69. static struct rusage sBegin;
  70. /* True if the timer is enabled */
  71. static int enableTimer = 0;
  72. /*
  73. ** Begin timing an operation
  74. */
  75. static void beginTimer(void){
  76. if( enableTimer ){
  77. getrusage(RUSAGE_SELF, &sBegin);
  78. }
  79. }
  80. /* Return the difference of two time_structs in seconds */
  81. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  82. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  83. (double)(pEnd->tv_sec - pStart->tv_sec);
  84. }
  85. /*
  86. ** Print the timing results.
  87. */
  88. static void endTimer(void){
  89. if( enableTimer ){
  90. struct rusage sEnd;
  91. getrusage(RUSAGE_SELF, &sEnd);
  92. printf("CPU Time: user %f sys %f\n",
  93. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  94. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  95. }
  96. }
  97. #define BEGIN_TIMER beginTimer()
  98. #define END_TIMER endTimer()
  99. #define HAS_TIMER 1
  100. #else
  101. #define BEGIN_TIMER
  102. #define END_TIMER
  103. #define HAS_TIMER 0
  104. #endif
  105. /*
  106. ** Used to prevent warnings about unused parameters
  107. */
  108. #define UNUSED_PARAMETER(x) (void)(x)
  109. /*
  110. ** If the following flag is set, then command execution stops
  111. ** at an error if we are not interactive.
  112. */
  113. static int bail_on_error = 0;
  114. /*
  115. ** Threat stdin as an interactive input if the following variable
  116. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  117. */
  118. static int stdin_is_interactive = 1;
  119. /*
  120. ** The following is the open SQLite database. We make a pointer
  121. ** to this database a static variable so that it can be accessed
  122. ** by the SIGINT handler to interrupt database processing.
  123. */
  124. static sqlite3 *db = 0;
  125. /*
  126. ** True if an interrupt (Control-C) has been received.
  127. */
  128. static volatile int seenInterrupt = 0;
  129. /*
  130. ** This is the name of our program. It is set in main(), used
  131. ** in a number of other places, mostly for error messages.
  132. */
  133. static char *Argv0;
  134. /*
  135. ** Prompt strings. Initialized in main. Settable with
  136. ** .prompt main continue
  137. */
  138. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  139. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  140. /*
  141. ** Write I/O traces to the following stream.
  142. */
  143. #ifdef SQLITE_ENABLE_IOTRACE
  144. static FILE *iotrace = 0;
  145. #endif
  146. /*
  147. ** This routine works like printf in that its first argument is a
  148. ** format string and subsequent arguments are values to be substituted
  149. ** in place of % fields. The result of formatting this string
  150. ** is written to iotrace.
  151. */
  152. #ifdef SQLITE_ENABLE_IOTRACE
  153. static void iotracePrintf(const char *zFormat, ...){
  154. va_list ap;
  155. char *z;
  156. if( iotrace==0 ) return;
  157. va_start(ap, zFormat);
  158. z = sqlite3_vmprintf(zFormat, ap);
  159. va_end(ap);
  160. fprintf(iotrace, "%s", z);
  161. sqlite3_free(z);
  162. }
  163. #endif
  164. /*
  165. ** Determines if a string is a number of not.
  166. */
  167. static int isNumber(const char *z, int *realnum){
  168. if( *z=='-' || *z=='+' ) z++;
  169. if( !isdigit(*z) ){
  170. return 0;
  171. }
  172. z++;
  173. if( realnum ) *realnum = 0;
  174. while( isdigit(*z) ){ z++; }
  175. if( *z=='.' ){
  176. z++;
  177. if( !isdigit(*z) ) return 0;
  178. while( isdigit(*z) ){ z++; }
  179. if( realnum ) *realnum = 1;
  180. }
  181. if( *z=='e' || *z=='E' ){
  182. z++;
  183. if( *z=='+' || *z=='-' ) z++;
  184. if( !isdigit(*z) ) return 0;
  185. while( isdigit(*z) ){ z++; }
  186. if( realnum ) *realnum = 1;
  187. }
  188. return *z==0;
  189. }
  190. /*
  191. ** A global char* and an SQL function to access its current value
  192. ** from within an SQL statement. This program used to use the
  193. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  194. ** The correct way to do this with sqlite3 is to use the bind API, but
  195. ** since the shell is built around the callback paradigm it would be a lot
  196. ** of work. Instead just use this hack, which is quite harmless.
  197. */
  198. static const char *zShellStatic = 0;
  199. static void shellstaticFunc(
  200. sqlite3_context *context,
  201. int argc,
  202. sqlite3_value **argv
  203. ){
  204. assert( 0==argc );
  205. assert( zShellStatic );
  206. UNUSED_PARAMETER(argc);
  207. UNUSED_PARAMETER(argv);
  208. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  209. }
  210. /*
  211. ** This routine reads a line of text from FILE in, stores
  212. ** the text in memory obtained from malloc() and returns a pointer
  213. ** to the text. NULL is returned at end of file, or if malloc()
  214. ** fails.
  215. **
  216. ** The interface is like "readline" but no command-line editing
  217. ** is done.
  218. */
  219. static char *local_getline(char *zPrompt, FILE *in){
  220. char *zLine;
  221. int nLine;
  222. int n;
  223. int eol;
  224. if( zPrompt && *zPrompt ){
  225. printf("%s",zPrompt);
  226. fflush(stdout);
  227. }
  228. nLine = 100;
  229. zLine = malloc( nLine );
  230. if( zLine==0 ) return 0;
  231. n = 0;
  232. eol = 0;
  233. while( !eol ){
  234. if( n+100>nLine ){
  235. nLine = nLine*2 + 100;
  236. zLine = realloc(zLine, nLine);
  237. if( zLine==0 ) return 0;
  238. }
  239. if( fgets(&zLine[n], nLine - n, in)==0 ){
  240. if( n==0 ){
  241. free(zLine);
  242. return 0;
  243. }
  244. zLine[n] = 0;
  245. eol = 1;
  246. break;
  247. }
  248. while( zLine[n] ){ n++; }
  249. if( n>0 && zLine[n-1]=='\n' ){
  250. n--;
  251. zLine[n] = 0;
  252. eol = 1;
  253. }
  254. }
  255. zLine = realloc( zLine, n+1 );
  256. return zLine;
  257. }
  258. /*
  259. ** Retrieve a single line of input text.
  260. **
  261. ** zPrior is a string of prior text retrieved. If not the empty
  262. ** string, then issue a continuation prompt.
  263. */
  264. static char *one_input_line(const char *zPrior, FILE *in){
  265. char *zPrompt;
  266. char *zResult;
  267. if( in!=0 ){
  268. return local_getline(0, in);
  269. }
  270. if( zPrior && zPrior[0] ){
  271. zPrompt = continuePrompt;
  272. }else{
  273. zPrompt = mainPrompt;
  274. }
  275. zResult = readline(zPrompt);
  276. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  277. if( zResult && *zResult ) add_history(zResult);
  278. #endif
  279. return zResult;
  280. }
  281. struct previous_mode_data {
  282. int valid; /* Is there legit data in here? */
  283. int mode;
  284. int showHeader;
  285. int colWidth[100];
  286. };
  287. /*
  288. ** An pointer to an instance of this structure is passed from
  289. ** the main program to the callback. This is used to communicate
  290. ** state and mode information.
  291. */
  292. struct callback_data {
  293. sqlite3 *db; /* The database */
  294. int echoOn; /* True to echo input commands */
  295. int cnt; /* Number of records displayed so far */
  296. FILE *out; /* Write results here */
  297. int mode; /* An output mode setting */
  298. int writableSchema; /* True if PRAGMA writable_schema=ON */
  299. int showHeader; /* True to show column names in List or Column mode */
  300. char *zDestTable; /* Name of destination table when MODE_Insert */
  301. char separator[20]; /* Separator character for MODE_List */
  302. int colWidth[100]; /* Requested width of each column when in column mode*/
  303. int actualWidth[100]; /* Actual width of each column */
  304. char nullvalue[20]; /* The text to print when a NULL comes back from
  305. ** the database */
  306. struct previous_mode_data explainPrev;
  307. /* Holds the mode information just before
  308. ** .explain ON */
  309. char outfile[FILENAME_MAX]; /* Filename for *out */
  310. const char *zDbFilename; /* name of the database file */
  311. };
  312. /*
  313. ** These are the allowed modes.
  314. */
  315. #define MODE_Line 0 /* One column per line. Blank line between records */
  316. #define MODE_Column 1 /* One record per line in neat columns */
  317. #define MODE_List 2 /* One record per line with a separator */
  318. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  319. #define MODE_Html 4 /* Generate an XHTML table */
  320. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  321. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  322. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  323. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  324. static const char *modeDescr[] = {
  325. "line",
  326. "column",
  327. "list",
  328. "semi",
  329. "html",
  330. "insert",
  331. "tcl",
  332. "csv",
  333. "explain",
  334. };
  335. /*
  336. ** Number of elements in an array
  337. */
  338. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  339. /*
  340. ** Compute a string length that is limited to what can be stored in
  341. ** lower 30 bits of a 32-bit signed integer.
  342. */
  343. static int strlen30(const char *z){
  344. const char *z2 = z;
  345. while( *z2 ){ z2++; }
  346. return 0x3fffffff & (int)(z2 - z);
  347. }
  348. /*
  349. ** Output the given string as a quoted string using SQL quoting conventions.
  350. */
  351. static void output_quoted_string(FILE *out, const char *z){
  352. int i;
  353. int nSingle = 0;
  354. for(i=0; z[i]; i++){
  355. if( z[i]=='\'' ) nSingle++;
  356. }
  357. if( nSingle==0 ){
  358. fprintf(out,"'%s'",z);
  359. }else{
  360. fprintf(out,"'");
  361. while( *z ){
  362. for(i=0; z[i] && z[i]!='\''; i++){}
  363. if( i==0 ){
  364. fprintf(out,"''");
  365. z++;
  366. }else if( z[i]=='\'' ){
  367. fprintf(out,"%.*s''",i,z);
  368. z += i+1;
  369. }else{
  370. fprintf(out,"%s",z);
  371. break;
  372. }
  373. }
  374. fprintf(out,"'");
  375. }
  376. }
  377. /*
  378. ** Output the given string as a quoted according to C or TCL quoting rules.
  379. */
  380. static void output_c_string(FILE *out, const char *z){
  381. unsigned int c;
  382. fputc('"', out);
  383. while( (c = *(z++))!=0 ){
  384. if( c=='\\' ){
  385. fputc(c, out);
  386. fputc(c, out);
  387. }else if( c=='\t' ){
  388. fputc('\\', out);
  389. fputc('t', out);
  390. }else if( c=='\n' ){
  391. fputc('\\', out);
  392. fputc('n', out);
  393. }else if( c=='\r' ){
  394. fputc('\\', out);
  395. fputc('r', out);
  396. }else if( !isprint(c) ){
  397. fprintf(out, "\\%03o", c&0xff);
  398. }else{
  399. fputc(c, out);
  400. }
  401. }
  402. fputc('"', out);
  403. }
  404. /*
  405. ** Output the given string with characters that are special to
  406. ** HTML escaped.
  407. */
  408. static void output_html_string(FILE *out, const char *z){
  409. int i;
  410. while( *z ){
  411. for(i=0; z[i] && z[i]!='<' && z[i]!='&'; i++){}
  412. if( i>0 ){
  413. fprintf(out,"%.*s",i,z);
  414. }
  415. if( z[i]=='<' ){
  416. fprintf(out,"&lt;");
  417. }else if( z[i]=='&' ){
  418. fprintf(out,"&amp;");
  419. }else{
  420. break;
  421. }
  422. z += i + 1;
  423. }
  424. }
  425. /*
  426. ** If a field contains any character identified by a 1 in the following
  427. ** array, then the string must be quoted for CSV.
  428. */
  429. static const char needCsvQuote[] = {
  430. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  431. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  432. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  438. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  439. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  440. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  441. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  442. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  443. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  444. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  445. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  446. };
  447. /*
  448. ** Output a single term of CSV. Actually, p->separator is used for
  449. ** the separator, which may or may not be a comma. p->nullvalue is
  450. ** the null value. Strings are quoted using ANSI-C rules. Numbers
  451. ** appear outside of quotes.
  452. */
  453. static void output_csv(struct callback_data *p, const char *z, int bSep){
  454. FILE *out = p->out;
  455. if( z==0 ){
  456. fprintf(out,"%s",p->nullvalue);
  457. }else{
  458. int i;
  459. int nSep = strlen30(p->separator);
  460. for(i=0; z[i]; i++){
  461. if( needCsvQuote[((unsigned char*)z)[i]]
  462. || (z[i]==p->separator[0] &&
  463. (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
  464. i = 0;
  465. break;
  466. }
  467. }
  468. if( i==0 ){
  469. putc('"', out);
  470. for(i=0; z[i]; i++){
  471. if( z[i]=='"' ) putc('"', out);
  472. putc(z[i], out);
  473. }
  474. putc('"', out);
  475. }else{
  476. fprintf(out, "%s", z);
  477. }
  478. }
  479. if( bSep ){
  480. fprintf(p->out, "%s", p->separator);
  481. }
  482. }
  483. #ifdef SIGINT
  484. /*
  485. ** This routine runs when the user presses Ctrl-C
  486. */
  487. static void interrupt_handler(int NotUsed){
  488. UNUSED_PARAMETER(NotUsed);
  489. seenInterrupt = 1;
  490. if( db ) sqlite3_interrupt(db);
  491. }
  492. #endif
  493. /*
  494. ** This is the callback routine that the SQLite library
  495. ** invokes for each row of a query result.
  496. */
  497. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  498. int i;
  499. struct callback_data *p = (struct callback_data*)pArg;
  500. switch( p->mode ){
  501. case MODE_Line: {
  502. int w = 5;
  503. if( azArg==0 ) break;
  504. for(i=0; i<nArg; i++){
  505. int len = strlen30(azCol[i] ? azCol[i] : "");
  506. if( len>w ) w = len;
  507. }
  508. if( p->cnt++>0 ) fprintf(p->out,"\n");
  509. for(i=0; i<nArg; i++){
  510. fprintf(p->out,"%*s = %s\n", w, azCol[i],
  511. azArg[i] ? azArg[i] : p->nullvalue);
  512. }
  513. break;
  514. }
  515. case MODE_Explain:
  516. case MODE_Column: {
  517. if( p->cnt++==0 ){
  518. for(i=0; i<nArg; i++){
  519. int w, n;
  520. if( i<ArraySize(p->colWidth) ){
  521. w = p->colWidth[i];
  522. }else{
  523. w = 0;
  524. }
  525. if( w<=0 ){
  526. w = strlen30(azCol[i] ? azCol[i] : "");
  527. if( w<10 ) w = 10;
  528. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  529. if( w<n ) w = n;
  530. }
  531. if( i<ArraySize(p->actualWidth) ){
  532. p->actualWidth[i] = w;
  533. }
  534. if( p->showHeader ){
  535. fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
  536. }
  537. }
  538. if( p->showHeader ){
  539. for(i=0; i<nArg; i++){
  540. int w;
  541. if( i<ArraySize(p->actualWidth) ){
  542. w = p->actualWidth[i];
  543. }else{
  544. w = 10;
  545. }
  546. fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  547. "----------------------------------------------------------",
  548. i==nArg-1 ? "\n": " ");
  549. }
  550. }
  551. }
  552. if( azArg==0 ) break;
  553. for(i=0; i<nArg; i++){
  554. int w;
  555. if( i<ArraySize(p->actualWidth) ){
  556. w = p->actualWidth[i];
  557. }else{
  558. w = 10;
  559. }
  560. if( p->mode==MODE_Explain && azArg[i] &&
  561. strlen30(azArg[i])>w ){
  562. w = strlen30(azArg[i]);
  563. }
  564. fprintf(p->out,"%-*.*s%s",w,w,
  565. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  566. }
  567. break;
  568. }
  569. case MODE_Semi:
  570. case MODE_List: {
  571. if( p->cnt++==0 && p->showHeader ){
  572. for(i=0; i<nArg; i++){
  573. fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  574. }
  575. }
  576. if( azArg==0 ) break;
  577. for(i=0; i<nArg; i++){
  578. char *z = azArg[i];
  579. if( z==0 ) z = p->nullvalue;
  580. fprintf(p->out, "%s", z);
  581. if( i<nArg-1 ){
  582. fprintf(p->out, "%s", p->separator);
  583. }else if( p->mode==MODE_Semi ){
  584. fprintf(p->out, ";\n");
  585. }else{
  586. fprintf(p->out, "\n");
  587. }
  588. }
  589. break;
  590. }
  591. case MODE_Html: {
  592. if( p->cnt++==0 && p->showHeader ){
  593. fprintf(p->out,"<TR>");
  594. for(i=0; i<nArg; i++){
  595. fprintf(p->out,"<TH>%s</TH>",azCol[i]);
  596. }
  597. fprintf(p->out,"</TR>\n");
  598. }
  599. if( azArg==0 ) break;
  600. fprintf(p->out,"<TR>");
  601. for(i=0; i<nArg; i++){
  602. fprintf(p->out,"<TD>");
  603. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  604. fprintf(p->out,"</TD>\n");
  605. }
  606. fprintf(p->out,"</TR>\n");
  607. break;
  608. }
  609. case MODE_Tcl: {
  610. if( p->cnt++==0 && p->showHeader ){
  611. for(i=0; i<nArg; i++){
  612. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  613. fprintf(p->out, "%s", p->separator);
  614. }
  615. fprintf(p->out,"\n");
  616. }
  617. if( azArg==0 ) break;
  618. for(i=0; i<nArg; i++){
  619. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  620. fprintf(p->out, "%s", p->separator);
  621. }
  622. fprintf(p->out,"\n");
  623. break;
  624. }
  625. case MODE_Csv: {
  626. if( p->cnt++==0 && p->showHeader ){
  627. for(i=0; i<nArg; i++){
  628. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  629. }
  630. fprintf(p->out,"\n");
  631. }
  632. if( azArg==0 ) break;
  633. for(i=0; i<nArg; i++){
  634. output_csv(p, azArg[i], i<nArg-1);
  635. }
  636. fprintf(p->out,"\n");
  637. break;
  638. }
  639. case MODE_Insert: {
  640. if( azArg==0 ) break;
  641. fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  642. for(i=0; i<nArg; i++){
  643. char *zSep = i>0 ? ",": "";
  644. if( azArg[i]==0 ){
  645. fprintf(p->out,"%sNULL",zSep);
  646. }else if( isNumber(azArg[i], 0) ){
  647. fprintf(p->out,"%s%s",zSep, azArg[i]);
  648. }else{
  649. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  650. output_quoted_string(p->out, azArg[i]);
  651. }
  652. }
  653. fprintf(p->out,");\n");
  654. break;
  655. }
  656. }
  657. return 0;
  658. }
  659. /*
  660. ** Set the destination table field of the callback_data structure to
  661. ** the name of the table given. Escape any quote characters in the
  662. ** table name.
  663. */
  664. static void set_table_name(struct callback_data *p, const char *zName){
  665. int i, n;
  666. int needQuote;
  667. char *z;
  668. if( p->zDestTable ){
  669. free(p->zDestTable);
  670. p->zDestTable = 0;
  671. }
  672. if( zName==0 ) return;
  673. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  674. for(i=n=0; zName[i]; i++, n++){
  675. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  676. needQuote = 1;
  677. if( zName[i]=='\'' ) n++;
  678. }
  679. }
  680. if( needQuote ) n += 2;
  681. z = p->zDestTable = malloc( n+1 );
  682. if( z==0 ){
  683. fprintf(stderr,"Out of memory!\n");
  684. exit(1);
  685. }
  686. n = 0;
  687. if( needQuote ) z[n++] = '\'';
  688. for(i=0; zName[i]; i++){
  689. z[n++] = zName[i];
  690. if( zName[i]=='\'' ) z[n++] = '\'';
  691. }
  692. if( needQuote ) z[n++] = '\'';
  693. z[n] = 0;
  694. }
  695. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  696. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  697. ** added to zIn, and the result returned in memory obtained from malloc().
  698. ** zIn, if it was not NULL, is freed.
  699. **
  700. ** If the third argument, quote, is not '\0', then it is used as a
  701. ** quote character for zAppend.
  702. */
  703. static char *appendText(char *zIn, char const *zAppend, char quote){
  704. int len;
  705. int i;
  706. int nAppend = strlen30(zAppend);
  707. int nIn = (zIn?strlen30(zIn):0);
  708. len = nAppend+nIn+1;
  709. if( quote ){
  710. len += 2;
  711. for(i=0; i<nAppend; i++){
  712. if( zAppend[i]==quote ) len++;
  713. }
  714. }
  715. zIn = (char *)realloc(zIn, len);
  716. if( !zIn ){
  717. return 0;
  718. }
  719. if( quote ){
  720. char *zCsr = &zIn[nIn];
  721. *zCsr++ = quote;
  722. for(i=0; i<nAppend; i++){
  723. *zCsr++ = zAppend[i];
  724. if( zAppend[i]==quote ) *zCsr++ = quote;
  725. }
  726. *zCsr++ = quote;
  727. *zCsr++ = '\0';
  728. assert( (zCsr-zIn)==len );
  729. }else{
  730. memcpy(&zIn[nIn], zAppend, nAppend);
  731. zIn[len-1] = '\0';
  732. }
  733. return zIn;
  734. }
  735. /*
  736. ** Execute a query statement that has a single result column. Print
  737. ** that result column on a line by itself with a semicolon terminator.
  738. **
  739. ** This is used, for example, to show the schema of the database by
  740. ** querying the SQLITE_MASTER table.
  741. */
  742. static int run_table_dump_query(FILE *out, sqlite3 *db, const char *zSelect){
  743. sqlite3_stmt *pSelect;
  744. int rc;
  745. rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0);
  746. if( rc!=SQLITE_OK || !pSelect ){
  747. return rc;
  748. }
  749. rc = sqlite3_step(pSelect);
  750. while( rc==SQLITE_ROW ){
  751. fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0));
  752. rc = sqlite3_step(pSelect);
  753. }
  754. return sqlite3_finalize(pSelect);
  755. }
  756. /*
  757. ** This is a different callback routine used for dumping the database.
  758. ** Each row received by this callback consists of a table name,
  759. ** the table type ("index" or "table") and SQL to create the table.
  760. ** This routine should print text sufficient to recreate the table.
  761. */
  762. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  763. int rc;
  764. const char *zTable;
  765. const char *zType;
  766. const char *zSql;
  767. struct callback_data *p = (struct callback_data *)pArg;
  768. UNUSED_PARAMETER(azCol);
  769. if( nArg!=3 ) return 1;
  770. zTable = azArg[0];
  771. zType = azArg[1];
  772. zSql = azArg[2];
  773. if( strcmp(zTable, "sqlite_sequence")==0 ){
  774. fprintf(p->out, "DELETE FROM sqlite_sequence;\n");
  775. }else if( strcmp(zTable, "sqlite_stat1")==0 ){
  776. fprintf(p->out, "ANALYZE sqlite_master;\n");
  777. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  778. return 0;
  779. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  780. char *zIns;
  781. if( !p->writableSchema ){
  782. fprintf(p->out, "PRAGMA writable_schema=ON;\n");
  783. p->writableSchema = 1;
  784. }
  785. zIns = sqlite3_mprintf(
  786. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  787. "VALUES('table','%q','%q',0,'%q');",
  788. zTable, zTable, zSql);
  789. fprintf(p->out, "%s\n", zIns);
  790. sqlite3_free(zIns);
  791. return 0;
  792. }else{
  793. fprintf(p->out, "%s;\n", zSql);
  794. }
  795. if( strcmp(zType, "table")==0 ){
  796. sqlite3_stmt *pTableInfo = 0;
  797. char *zSelect = 0;
  798. char *zTableInfo = 0;
  799. char *zTmp = 0;
  800. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  801. zTableInfo = appendText(zTableInfo, zTable, '"');
  802. zTableInfo = appendText(zTableInfo, ");", 0);
  803. rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
  804. if( zTableInfo ) free(zTableInfo);
  805. if( rc!=SQLITE_OK || !pTableInfo ){
  806. return 1;
  807. }
  808. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  809. zTmp = appendText(zTmp, zTable, '"');
  810. if( zTmp ){
  811. zSelect = appendText(zSelect, zTmp, '\'');
  812. }
  813. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  814. rc = sqlite3_step(pTableInfo);
  815. while( rc==SQLITE_ROW ){
  816. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  817. zSelect = appendText(zSelect, "quote(", 0);
  818. zSelect = appendText(zSelect, zText, '"');
  819. rc = sqlite3_step(pTableInfo);
  820. if( rc==SQLITE_ROW ){
  821. zSelect = appendText(zSelect, ") || ',' || ", 0);
  822. }else{
  823. zSelect = appendText(zSelect, ") ", 0);
  824. }
  825. }
  826. rc = sqlite3_finalize(pTableInfo);
  827. if( rc!=SQLITE_OK ){
  828. if( zSelect ) free(zSelect);
  829. return 1;
  830. }
  831. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  832. zSelect = appendText(zSelect, zTable, '"');
  833. rc = run_table_dump_query(p->out, p->db, zSelect);
  834. if( rc==SQLITE_CORRUPT ){
  835. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  836. rc = run_table_dump_query(p->out, p->db, zSelect);
  837. }
  838. if( zSelect ) free(zSelect);
  839. }
  840. return 0;
  841. }
  842. /*
  843. ** Run zQuery. Use dump_callback() as the callback routine so that
  844. ** the contents of the query are output as SQL statements.
  845. **
  846. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  847. ** "ORDER BY rowid DESC" to the end.
  848. */
  849. static int run_schema_dump_query(
  850. struct callback_data *p,
  851. const char *zQuery,
  852. char **pzErrMsg
  853. ){
  854. int rc;
  855. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg);
  856. if( rc==SQLITE_CORRUPT ){
  857. char *zQ2;
  858. int len = strlen30(zQuery);
  859. if( pzErrMsg ) sqlite3_free(*pzErrMsg);
  860. zQ2 = malloc( len+100 );
  861. if( zQ2==0 ) return rc;
  862. sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
  863. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, pzErrMsg);
  864. free(zQ2);
  865. }
  866. return rc;
  867. }
  868. /*
  869. ** Text of a help message
  870. */
  871. static char zHelp[] =
  872. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  873. ".bail ON|OFF Stop after hitting an error. Default OFF\n"
  874. ".databases List names and files of attached databases\n"
  875. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  876. ".echo ON|OFF Turn command echo on or off\n"
  877. ".exit Exit this program\n"
  878. ".explain ON|OFF Turn output mode suitable for EXPLAIN on or off.\n"
  879. ".header(s) ON|OFF Turn display of headers on or off\n"
  880. ".help Show this message\n"
  881. ".import FILE TABLE Import data from FILE into TABLE\n"
  882. ".indices TABLE Show names of all indices on TABLE\n"
  883. #ifdef SQLITE_ENABLE_IOTRACE
  884. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  885. #endif
  886. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  887. ".load FILE ?ENTRY? Load an extension library\n"
  888. #endif
  889. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  890. " csv Comma-separated values\n"
  891. " column Left-aligned columns. (See .width)\n"
  892. " html HTML <table> code\n"
  893. " insert SQL insert statements for TABLE\n"
  894. " line One value per line\n"
  895. " list Values delimited by .separator string\n"
  896. " tabs Tab-separated values\n"
  897. " tcl TCL list elements\n"
  898. ".nullvalue STRING Print STRING in place of NULL values\n"
  899. ".output FILENAME Send output to FILENAME\n"
  900. ".output stdout Send output to the screen\n"
  901. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  902. ".quit Exit this program\n"
  903. ".read FILENAME Execute SQL in FILENAME\n"
  904. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  905. ".schema ?TABLE? Show the CREATE statements\n"
  906. ".separator STRING Change separator used by output mode and .import\n"
  907. ".show Show the current values for various settings\n"
  908. ".tables ?PATTERN? List names of tables matching a LIKE pattern\n"
  909. ".timeout MS Try opening locked tables for MS milliseconds\n"
  910. #if HAS_TIMER
  911. ".timer ON|OFF Turn the CPU timer measurement on or off\n"
  912. #endif
  913. ".width NUM NUM ... Set column widths for \"column\" mode\n"
  914. ;
  915. /* Forward reference */
  916. static int process_input(struct callback_data *p, FILE *in);
  917. /*
  918. ** Make sure the database is open. If it is not, then open it. If
  919. ** the database fails to open, print an error message and exit.
  920. */
  921. static void open_db(struct callback_data *p){
  922. if( p->db==0 ){
  923. sqlite3_open(p->zDbFilename, &p->db);
  924. db = p->db;
  925. if( db && sqlite3_errcode(db)==SQLITE_OK ){
  926. sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  927. shellstaticFunc, 0, 0);
  928. }
  929. if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  930. fprintf(stderr,"Unable to open database \"%s\": %s\n",
  931. p->zDbFilename, sqlite3_errmsg(db));
  932. exit(1);
  933. }
  934. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  935. sqlite3_enable_load_extension(p->db, 1);
  936. #endif
  937. }
  938. }
  939. /*
  940. ** Do C-language style dequoting.
  941. **
  942. ** \t -> tab
  943. ** \n -> newline
  944. ** \r -> carriage return
  945. ** \NNN -> ascii character NNN in octal
  946. ** \\ -> backslash
  947. */
  948. static void resolve_backslashes(char *z){
  949. int i, j;
  950. char c;
  951. for(i=j=0; (c = z[i])!=0; i++, j++){
  952. if( c=='\\' ){
  953. c = z[++i];
  954. if( c=='n' ){
  955. c = '\n';
  956. }else if( c=='t' ){
  957. c = '\t';
  958. }else if( c=='r' ){
  959. c = '\r';
  960. }else if( c>='0' && c<='7' ){
  961. c -= '0';
  962. if( z[i+1]>='0' && z[i+1]<='7' ){
  963. i++;
  964. c = (c<<3) + z[i] - '0';
  965. if( z[i+1]>='0' && z[i+1]<='7' ){
  966. i++;
  967. c = (c<<3) + z[i] - '0';
  968. }
  969. }
  970. }
  971. }
  972. z[j] = c;
  973. }
  974. z[j] = 0;
  975. }
  976. /*
  977. ** Interpret zArg as a boolean value. Return either 0 or 1.
  978. */
  979. static int booleanValue(char *zArg){
  980. int val = atoi(zArg);
  981. int j;
  982. for(j=0; zArg[j]; j++){
  983. zArg[j] = (char)tolower(zArg[j]);
  984. }
  985. if( strcmp(zArg,"on")==0 ){
  986. val = 1;
  987. }else if( strcmp(zArg,"yes")==0 ){
  988. val = 1;
  989. }
  990. return val;
  991. }
  992. /*
  993. ** If an input line begins with "." then invoke this routine to
  994. ** process that line.
  995. **
  996. ** Return 1 on error, 2 to exit, and 0 otherwise.
  997. */
  998. static int do_meta_command(char *zLine, struct callback_data *p){
  999. int i = 1;
  1000. int nArg = 0;
  1001. int n, c;
  1002. int rc = 0;
  1003. char *azArg[50];
  1004. /* Parse the input line into tokens.
  1005. */
  1006. while( zLine[i] && nArg<ArraySize(azArg) ){
  1007. while( isspace((unsigned char)zLine[i]) ){ i++; }
  1008. if( zLine[i]==0 ) break;
  1009. if( zLine[i]=='\'' || zLine[i]=='"' ){
  1010. int delim = zLine[i++];
  1011. azArg[nArg++] = &zLine[i];
  1012. while( zLine[i] && zLine[i]!=delim ){ i++; }
  1013. if( zLine[i]==delim ){
  1014. zLine[i++] = 0;
  1015. }
  1016. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  1017. }else{
  1018. azArg[nArg++] = &zLine[i];
  1019. while( zLine[i] && !isspace((unsigned char)zLine[i]) ){ i++; }
  1020. if( zLine[i] ) zLine[i++] = 0;
  1021. resolve_backslashes(azArg[nArg-1]);
  1022. }
  1023. }
  1024. /* Process the input line.
  1025. */
  1026. if( nArg==0 ) return rc;
  1027. n = strlen30(azArg[0]);
  1028. c = azArg[0][0];
  1029. if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 ){
  1030. const char *zDestFile;
  1031. const char *zDb;
  1032. sqlite3 *pDest;
  1033. sqlite3_backup *pBackup;
  1034. int rc;
  1035. if( nArg==2 ){
  1036. zDestFile = azArg[1];
  1037. zDb = "main";
  1038. }else{
  1039. zDestFile = azArg[2];
  1040. zDb = azArg[1];
  1041. }
  1042. rc = sqlite3_open(zDestFile, &pDest);
  1043. if( rc!=SQLITE_OK ){
  1044. fprintf(stderr, "Error: cannot open %s\n", zDestFile);
  1045. sqlite3_close(pDest);
  1046. return 1;
  1047. }
  1048. open_db(p);
  1049. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  1050. if( pBackup==0 ){
  1051. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1052. sqlite3_close(pDest);
  1053. return 1;
  1054. }
  1055. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  1056. sqlite3_backup_finish(pBackup);
  1057. if( rc==SQLITE_DONE ){
  1058. rc = SQLITE_OK;
  1059. }else{
  1060. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1061. }
  1062. sqlite3_close(pDest);
  1063. }else
  1064. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 ){
  1065. bail_on_error = booleanValue(azArg[1]);
  1066. }else
  1067. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  1068. struct callback_data data;
  1069. char *zErrMsg = 0;
  1070. open_db(p);
  1071. memcpy(&data, p, sizeof(data));
  1072. data.showHeader = 1;
  1073. data.mode = MODE_Column;
  1074. data.colWidth[0] = 3;
  1075. data.colWidth[1] = 15;
  1076. data.colWidth[2] = 58;
  1077. data.cnt = 0;
  1078. sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  1079. if( zErrMsg ){
  1080. fprintf(stderr,"Error: %s\n", zErrMsg);
  1081. sqlite3_free(zErrMsg);
  1082. }
  1083. }else
  1084. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  1085. char *zErrMsg = 0;
  1086. open_db(p);
  1087. fprintf(p->out, "BEGIN TRANSACTION;\n");
  1088. p->writableSchema = 0;
  1089. sqlite3_exec(p->db, "PRAGMA writable_schema=ON", 0, 0, 0);
  1090. if( nArg==1 ){
  1091. run_schema_dump_query(p,
  1092. "SELECT name, type, sql FROM sqlite_master "
  1093. "WHERE sql NOT NULL AND type=='table'", 0
  1094. );
  1095. run_table_dump_query(p->out, p->db,
  1096. "SELECT sql FROM sqlite_master "
  1097. "WHERE sql NOT NULL AND type IN ('index','trigger','view')"
  1098. );
  1099. }else{
  1100. int i;
  1101. for(i=1; i<nArg; i++){
  1102. zShellStatic = azArg[i];
  1103. run_schema_dump_query(p,
  1104. "SELECT name, type, sql FROM sqlite_master "
  1105. "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  1106. " AND sql NOT NULL", 0);
  1107. run_table_dump_query(p->out, p->db,
  1108. "SELECT sql FROM sqlite_master "
  1109. "WHERE sql NOT NULL"
  1110. " AND type IN ('index','trigger','view')"
  1111. " AND tbl_name LIKE shellstatic()"
  1112. );
  1113. zShellStatic = 0;
  1114. }
  1115. }
  1116. if( p->writableSchema ){
  1117. fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
  1118. p->writableSchema = 0;
  1119. }
  1120. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF", 0, 0, 0);
  1121. if( zErrMsg ){
  1122. fprintf(stderr,"Error: %s\n", zErrMsg);
  1123. sqlite3_free(zErrMsg);
  1124. }else{
  1125. fprintf(p->out, "COMMIT;\n");
  1126. }
  1127. }else
  1128. if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){
  1129. p->echoOn = booleanValue(azArg[1]);
  1130. }else
  1131. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  1132. rc = 2;
  1133. }else
  1134. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  1135. int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
  1136. if(val == 1) {
  1137. if(!p->explainPrev.valid) {
  1138. p->explainPrev.valid = 1;
  1139. p->explainPrev.mode = p->mode;
  1140. p->explainPrev.showHeader = p->showHeader;
  1141. memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
  1142. }
  1143. /* We could put this code under the !p->explainValid
  1144. ** condition so that it does not execute if we are already in
  1145. ** explain mode. However, always executing it allows us an easy
  1146. ** was to reset to explain mode in case the user previously
  1147. ** did an .explain followed by a .width, .mode or .header
  1148. ** command.
  1149. */
  1150. p->mode = MODE_Explain;
  1151. p->showHeader = 1;
  1152. memset(p->colWidth,0,ArraySize(p->colWidth));
  1153. p->colWidth[0] = 4; /* addr */
  1154. p->colWidth[1] = 13; /* opcode */
  1155. p->colWidth[2] = 4; /* P1 */
  1156. p->colWidth[3] = 4; /* P2 */
  1157. p->colWidth[4] = 4; /* P3 */
  1158. p->colWidth[5] = 13; /* P4 */
  1159. p->colWidth[6] = 2; /* P5 */
  1160. p->colWidth[7] = 13; /* Comment */
  1161. }else if (p->explainPrev.valid) {
  1162. p->explainPrev.valid = 0;
  1163. p->mode = p->explainPrev.mode;
  1164. p->showHeader = p->explainPrev.showHeader;
  1165. memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
  1166. }
  1167. }else
  1168. if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
  1169. strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){
  1170. p->showHeader = booleanValue(azArg[1]);
  1171. }else
  1172. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  1173. fprintf(stderr,"%s",zHelp);
  1174. }else
  1175. if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg>=3 ){
  1176. char *zTable = azArg[2]; /* Insert data into this table */
  1177. char *zFile = azArg[1]; /* The file from which to extract data */
  1178. sqlite3_stmt *pStmt; /* A statement */
  1179. int rc; /* Result code */
  1180. int nCol; /* Number of columns in the table */
  1181. int nByte; /* Number of bytes in an SQL string */
  1182. int i, j; /* Loop counters */
  1183. int nSep; /* Number of bytes in p->separator[] */
  1184. char *zSql; /* An SQL statement */
  1185. char *zLine; /* A single line of input from the file */
  1186. char **azCol; /* zLine[] broken up into columns */
  1187. char *zCommit; /* How to commit changes */
  1188. FILE *in; /* The input file */
  1189. int lineno = 0; /* Line number of input file */
  1190. open_db(p);
  1191. nSep = strlen30(p->separator);
  1192. if( nSep==0 ){
  1193. fprintf(stderr, "non-null separator required for import\n");
  1194. return 0;
  1195. }
  1196. zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable);
  1197. if( zSql==0 ) return 0;
  1198. nByte = strlen30(zSql);
  1199. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  1200. sqlite3_free(zSql);
  1201. if( rc ){
  1202. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  1203. nCol = 0;
  1204. rc = 1;
  1205. }else{
  1206. nCol = sqlite3_column_count(pStmt);
  1207. }
  1208. sqlite3_finalize(pStmt);
  1209. if( nCol==0 ) return 0;
  1210. zSql = malloc( nByte + 20 + nCol*2 );
  1211. if( zSql==0 ) return 0;
  1212. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable);
  1213. j = strlen30(zSql);
  1214. for(i=1; i<nCol; i++){
  1215. zSql[j++] = ',';
  1216. zSql[j++] = '?';
  1217. }
  1218. zSql[j++] = ')';
  1219. zSql[j] = 0;
  1220. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  1221. free(zSql);
  1222. if( rc ){
  1223. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  1224. sqlite3_finalize(pStmt);
  1225. return 1;
  1226. }
  1227. in = fopen(zFile, "rb");
  1228. if( in==0 ){
  1229. fprintf(stderr, "cannot open file: %s\n", zFile);
  1230. sqlite3_finalize(pStmt);
  1231. return 0;
  1232. }
  1233. azCol = malloc( sizeof(azCol[0])*(nCol+1) );
  1234. if( azCol==0 ){
  1235. fclose(in);
  1236. return 0;
  1237. }
  1238. sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  1239. zCommit = "COMMIT";
  1240. while( (zLine = local_getline(0, in))!=0 ){
  1241. char *z;
  1242. i = 0;
  1243. lineno++;
  1244. azCol[0] = zLine;
  1245. for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){
  1246. if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){
  1247. *z = 0;
  1248. i++;
  1249. if( i<nCol ){
  1250. azCol[i] = &z[nSep];
  1251. z += nSep-1;
  1252. }
  1253. }
  1254. }
  1255. *z = 0;
  1256. if( i+1!=nCol ){
  1257. fprintf(stderr,"%s line %d: expected %d columns of data but found %d\n",
  1258. zFile, lineno, nCol, i+1);
  1259. zCommit = "ROLLBACK";
  1260. free(zLine);
  1261. break;
  1262. }
  1263. for(i=0; i<nCol; i++){
  1264. sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
  1265. }
  1266. sqlite3_step(pStmt);
  1267. rc = sqlite3_reset(pStmt);
  1268. free(zLine);
  1269. if( rc!=SQLITE_OK ){
  1270. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  1271. zCommit = "ROLLBACK";
  1272. rc = 1;
  1273. break;
  1274. }
  1275. }
  1276. free(azCol);
  1277. fclose(in);
  1278. sqlite3_finalize(pStmt);
  1279. sqlite3_exec(p->db, zCommit, 0, 0, 0);
  1280. }else
  1281. if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){
  1282. struct callback_data data;
  1283. char *zErrMsg = 0;
  1284. open_db(p);
  1285. memcpy(&data, p, sizeof(data));
  1286. data.showHeader = 0;
  1287. data.mode = MODE_List;
  1288. zShellStatic = azArg[1];
  1289. sqlite3_exec(p->db,
  1290. "SELECT name FROM sqlite_master "
  1291. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  1292. "UNION ALL "
  1293. "SELECT name FROM sqlite_temp_master "
  1294. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  1295. "ORDER BY 1",
  1296. callback, &data, &zErrMsg
  1297. );
  1298. zShellStatic = 0;
  1299. if( zErrMsg ){
  1300. fprintf(stderr,"Error: %s\n", zErrMsg);
  1301. sqlite3_free(zErrMsg);
  1302. }
  1303. }else
  1304. #ifdef SQLITE_ENABLE_IOTRACE
  1305. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  1306. extern void (*sqlite3IoTrace)(const char*, ...);
  1307. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  1308. iotrace = 0;
  1309. if( nArg<2 ){
  1310. sqlite3IoTrace = 0;
  1311. }else if( strcmp(azArg[1], "-")==0 ){
  1312. sqlite3IoTrace = iotracePrintf;
  1313. iotrace = stdout;
  1314. }else{
  1315. iotrace = fopen(azArg[1], "w");
  1316. if( iotrace==0 ){
  1317. fprintf(stderr, "cannot open \"%s\"\n", azArg[1]);
  1318. sqlite3IoTrace = 0;
  1319. }else{
  1320. sqlite3IoTrace = iotracePrintf;
  1321. }
  1322. }
  1323. }else
  1324. #endif
  1325. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1326. if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
  1327. const char *zFile, *zProc;
  1328. char *zErrMsg = 0;
  1329. int rc;
  1330. zFile = azArg[1];
  1331. zProc = nArg>=3 ? azArg[2] : 0;
  1332. open_db(p);
  1333. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  1334. if( rc!=SQLITE_OK ){
  1335. fprintf(stderr, "%s\n", zErrMsg);
  1336. sqlite3_free(zErrMsg);
  1337. rc = 1;
  1338. }
  1339. }else
  1340. #endif
  1341. if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){
  1342. int n2 = strlen30(azArg[1]);
  1343. if( strncmp(azArg[1],"line",n2)==0
  1344. ||
  1345. strncmp(azArg[1],"lines",n2)==0 ){
  1346. p->mode = MODE_Line;
  1347. }else if( strncmp(azArg[1],"column",n2)==0
  1348. ||
  1349. strncmp(azArg[1],"columns",n2)==0 ){
  1350. p->mode = MODE_Column;
  1351. }else if( strncmp(azArg[1],"list",n2)==0 ){
  1352. p->mode = MODE_List;
  1353. }else if( strncmp(azArg[1],"html",n2)==0 ){
  1354. p->mode = MODE_Html;
  1355. }else if( strncmp(azArg[1],"tcl",n2)==0 ){
  1356. p->mode = MODE_Tcl;
  1357. }else if( strncmp(azArg[1],"csv",n2)==0 ){
  1358. p->mode = MODE_Csv;
  1359. sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
  1360. }else if( strncmp(azArg[1],"tabs",n2)==0 ){
  1361. p->mode = MODE_List;
  1362. sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
  1363. }else if( strncmp(azArg[1],"insert",n2)==0 ){
  1364. p->mode = MODE_Insert;
  1365. if( nArg>=3 ){
  1366. set_table_name(p, azArg[2]);
  1367. }else{
  1368. set_table_name(p, "table");
  1369. }
  1370. }else {
  1371. fprintf(stderr,"mode should be one of: "
  1372. "column csv html insert line list tabs tcl\n");
  1373. }
  1374. }else
  1375. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
  1376. sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
  1377. "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  1378. }else
  1379. if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
  1380. if( p->out!=stdout ){
  1381. fclose(p->out);
  1382. }
  1383. if( strcmp(azArg[1],"stdout")==0 ){
  1384. p->out = stdout;
  1385. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout");
  1386. }else{
  1387. p->out = fopen(azArg[1], "wb");
  1388. if( p->out==0 ){
  1389. fprintf(stderr,"can't write to \"%s\"\n", azArg[1]);
  1390. p->out = stdout;
  1391. } else {
  1392. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
  1393. }
  1394. }
  1395. }else
  1396. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
  1397. if( nArg >= 2) {
  1398. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  1399. }
  1400. if( nArg >= 3) {
  1401. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  1402. }
  1403. }else
  1404. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  1405. rc = 2;
  1406. }else
  1407. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
  1408. FILE *alt = fopen(azArg[1], "rb");
  1409. if( alt==0 ){
  1410. fprintf(stderr,"can't open \"%s\"\n", azArg[1]);
  1411. }else{
  1412. process_input(p, alt);
  1413. fclose(alt);
  1414. }
  1415. }else
  1416. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 ){
  1417. const char *zSrcFile;
  1418. const char *zDb;
  1419. sqlite3 *pSrc;
  1420. sqlite3_backup *pBackup;
  1421. int rc;
  1422. int nTimeout = 0;
  1423. if( nArg==2 ){
  1424. zSrcFile = azArg[1];
  1425. zDb = "main";
  1426. }else{
  1427. zSrcFile = azArg[2];
  1428. zDb = azArg[1];
  1429. }
  1430. rc = sqlite3_open(zSrcFile, &pSrc);
  1431. if( rc!=SQLITE_OK ){
  1432. fprintf(stderr, "Error: cannot open %s\n", zSrcFile);
  1433. sqlite3_close(pSrc);
  1434. return 1;
  1435. }
  1436. open_db(p);
  1437. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  1438. if( pBackup==0 ){
  1439. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  1440. sqlite3_close(pSrc);
  1441. return 1;
  1442. }
  1443. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  1444. || rc==SQLITE_BUSY ){
  1445. if( rc==SQLITE_BUSY ){
  1446. if( nTimeout++ >= 3 ) break;
  1447. sqlite3_sleep(100);
  1448. }
  1449. }
  1450. sqlite3_backup_finish(pBackup);
  1451. if( rc==SQLITE_DONE ){
  1452. rc = SQLITE_OK;
  1453. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  1454. fprintf(stderr, "source database is busy\n");
  1455. }else{
  1456. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  1457. }
  1458. sqlite3_close(pSrc);
  1459. }else
  1460. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  1461. struct callback_data data;
  1462. char *zErrMsg = 0;
  1463. open_db(p);
  1464. memcpy(&data, p, sizeof(data));
  1465. data.showHeader = 0;
  1466. data.mode = MODE_Semi;
  1467. if( nArg>1 ){
  1468. int i;
  1469. for(i=0; azArg[1][i]; i++) azArg[1][i] = (char)tolower(azArg[1][i]);
  1470. if( strcmp(azArg[1],"sqlite_master")==0 ){
  1471. char *new_argv[2], *new_colv[2];
  1472. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  1473. " type text,\n"
  1474. " name text,\n"
  1475. " tbl_name text,\n"
  1476. " rootpage integer,\n"
  1477. " sql text\n"
  1478. ")";
  1479. new_argv[1] = 0;
  1480. new_colv[0] = "sql";
  1481. new_colv[1] = 0;
  1482. callback(&data, 1, new_argv, new_colv);
  1483. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  1484. char *new_argv[2], *new_colv[2];
  1485. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  1486. " type text,\n"
  1487. " name text,\n"
  1488. " tbl_name text,\n"
  1489. " rootpage integer,\n"
  1490. " sql text\n"
  1491. ")";
  1492. new_argv[1] = 0;
  1493. new_colv[0] = "sql";
  1494. new_colv[1] = 0;
  1495. callback(&data, 1, new_argv, new_colv);
  1496. }else{
  1497. zShellStatic = azArg[1];
  1498. sqlite3_exec(p->db,
  1499. "SELECT sql FROM "
  1500. " (SELECT sql sql, type type, tbl_name tbl_name, name name"
  1501. " FROM sqlite_master UNION ALL"
  1502. " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  1503. "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
  1504. "ORDER BY substr(type,2,1), name",
  1505. callback, &data, &zErrMsg);
  1506. zShellStatic = 0;
  1507. }
  1508. }else{
  1509. sqlite3_exec(p->db,
  1510. "SELECT sql FROM "
  1511. " (SELECT sql sql, type type, tbl_name tbl_name, name name"
  1512. " FROM sqlite_master UNION ALL"
  1513. " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  1514. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
  1515. "ORDER BY substr(type,2,1), name",
  1516. callback, &data, &zErrMsg
  1517. );
  1518. }
  1519. if( zErrMsg ){
  1520. fprintf(stderr,"Error: %s\n", zErrMsg);
  1521. sqlite3_free(zErrMsg);
  1522. }
  1523. }else
  1524. if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
  1525. sqlite3_snprintf(sizeof(p->separator), p->separator,
  1526. "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  1527. }else
  1528. if( c=='s' && strncmp(azArg[0], "show", n)==0){
  1529. int i;
  1530. fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
  1531. fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
  1532. fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  1533. fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  1534. fprintf(p->out,"%9.9s: ", "nullvalue");
  1535. output_c_string(p->out, p->nullvalue);
  1536. fprintf(p->out, "\n");
  1537. fprintf(p->out,"%9.9s: %s\n","output",
  1538. strlen30(p->outfile) ? p->outfile : "stdout");
  1539. fprintf(p->out,"%9.9s: ", "separator");
  1540. output_c_string(p->out, p->separator);
  1541. fprintf(p->out, "\n");
  1542. fprintf(p->out,"%9.9s: ","width");
  1543. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  1544. fprintf(p->out,"%d ",p->colWidth[i]);
  1545. }
  1546. fprintf(p->out,"\n");
  1547. }else
  1548. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
  1549. char **azResult;
  1550. int nRow, rc;
  1551. char *zErrMsg;
  1552. open_db(p);
  1553. if( nArg==1 ){
  1554. rc = sqlite3_get_table(p->db,
  1555. "SELECT name FROM sqlite_master "
  1556. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'"
  1557. "UNION ALL "
  1558. "SELECT name FROM sqlite_temp_master "
  1559. "WHERE type IN ('table','view') "
  1560. "ORDER BY 1",
  1561. &azResult, &nRow, 0, &zErrMsg
  1562. );
  1563. }else{
  1564. zShellStatic = azArg[1];
  1565. rc = sqlite3_get_table(p->db,
  1566. "SELECT name FROM sqlite_master "
  1567. "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' "
  1568. "UNION ALL "
  1569. "SELECT name FROM sqlite_temp_master "
  1570. "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' "
  1571. "ORDER BY 1",
  1572. &azResult, &nRow, 0, &zErrMsg
  1573. );
  1574. zShellStatic = 0;
  1575. }
  1576. if( zErrMsg ){
  1577. fprintf(stderr,"Error: %s\n", zErrMsg);
  1578. sqlite3_free(zErrMsg);
  1579. }
  1580. if( rc==SQLITE_OK ){
  1581. int len, maxlen = 0;
  1582. int i, j;
  1583. int nPrintCol, nPrintRow;
  1584. for(i=1; i<=nRow; i++){
  1585. if( azResult[i]==0 ) continue;
  1586. len = strlen30(azResult[i]);
  1587. if( len>maxlen ) maxlen = len;
  1588. }
  1589. nPrintCol = 80/(maxlen+2);
  1590. if( nPrintCol<1 ) nPrintCol = 1;
  1591. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  1592. for(i=0; i<nPrintRow; i++){
  1593. for(j=i+1; j<=nRow; j+=nPrintRow){
  1594. char *zSp = j<=nPrintRow ? "" : " ";
  1595. printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
  1596. }
  1597. printf("\n");
  1598. }
  1599. }else{
  1600. rc = 1;
  1601. }
  1602. sqlite3_free_table(azResult);
  1603. }else
  1604. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){
  1605. open_db(p);
  1606. sqlite3_busy_timeout(p->db, atoi(azArg[1]));
  1607. }else
  1608. #if HAS_TIMER
  1609. if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg>1 ){
  1610. enableTimer = booleanValue(azArg[1]);
  1611. }else
  1612. #endif
  1613. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  1614. int j;
  1615. assert( nArg<=ArraySize(azArg) );
  1616. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  1617. p->colWidth[j-1] = atoi(azArg[j]);
  1618. }
  1619. }else
  1620. {
  1621. fprintf(stderr, "unknown command or invalid arguments: "
  1622. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  1623. }
  1624. return rc;
  1625. }
  1626. /*
  1627. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  1628. ** of string z[].
  1629. */
  1630. static int _contains_semicolon(const char *z, int N){
  1631. int i;
  1632. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  1633. return 0;
  1634. }
  1635. /*
  1636. ** Test to see if a line consists entirely of whitespace.
  1637. */
  1638. static int _all_whitespace(const char *z){
  1639. for(; *z; z++){
  1640. if( isspace(*(unsigned char*)z) ) continue;
  1641. if( *z=='/' && z[1]=='*' ){
  1642. z += 2;
  1643. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  1644. if( *z==0 ) return 0;
  1645. z++;
  1646. continue;
  1647. }
  1648. if( *z=='-' && z[1]=='-' ){
  1649. z += 2;
  1650. while( *z && *z!='\n' ){ z++; }
  1651. if( *z==0 ) return 1;
  1652. continue;
  1653. }
  1654. return 0;
  1655. }
  1656. return 1;
  1657. }
  1658. /*
  1659. ** Return TRUE if the line typed in is an SQL command terminator other
  1660. ** than a semi-colon. The SQL Server style "go" command is understood
  1661. ** as is the Oracle "/".
  1662. */
  1663. static int _is_command_terminator(const char *zLine){
  1664. while( isspace(*(unsigned char*)zLine) ){ zLine++; };
  1665. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  1666. return 1; /* Oracle */
  1667. }
  1668. if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o'
  1669. && _all_whitespace(&zLine[2]) ){
  1670. return 1; /* SQL Server */
  1671. }
  1672. return 0;
  1673. }
  1674. /*
  1675. ** Return true if zSql is a complete SQL statement. Return false if it
  1676. ** ends in the middle of a string literal or C-style comment.
  1677. */
  1678. static int _is_complete(char *zSql, int nSql){
  1679. int rc;
  1680. if( zSql==0 ) return 1;
  1681. zSql[nSql] = ';';
  1682. zSql[nSql+1] = 0;
  1683. rc = sqlite3_complete(zSql);
  1684. zSql[nSql] = 0;
  1685. return rc;
  1686. }
  1687. /*
  1688. ** Read input from *in and process it. If *in==0 then input
  1689. ** is interactive - the user is typing it it. Otherwise, input
  1690. ** is coming from a file or device. A prompt is issued and history
  1691. ** is saved only if input is interactive. An interrupt signal will
  1692. ** cause this routine to exit immediately, unless input is interactive.
  1693. **
  1694. ** Return the number of errors.
  1695. */
  1696. static int process_input(struct callback_data *p, FILE *in){
  1697. char *zLine = 0;
  1698. char *zSql = 0;
  1699. int nSql = 0;
  1700. int nSqlPrior = 0;
  1701. char *zErrMsg;
  1702. int rc;
  1703. int errCnt = 0;
  1704. int lineno = 0;
  1705. int startline = 0;
  1706. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  1707. fflush(p->out);
  1708. free(zLine);
  1709. zLine = one_input_line(zSql, in);
  1710. if( zLine==0 ){
  1711. break; /* We have reached EOF */
  1712. }
  1713. if( seenInterrupt ){
  1714. if( in!=0 ) break;
  1715. seenInterrupt = 0;
  1716. }
  1717. lineno++;
  1718. if( p->echoOn ) printf("%s\n", zLine);
  1719. if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
  1720. if( zLine && zLine[0]=='.' && nSql==0 ){
  1721. rc = do_meta_command(zLine, p);
  1722. if( rc==2 ){
  1723. break;
  1724. }else if( rc ){
  1725. errCnt++;
  1726. }
  1727. continue;
  1728. }
  1729. if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
  1730. memcpy(zLine,";",2);
  1731. }
  1732. nSqlPrior = nSql;
  1733. if( zSql==0 ){
  1734. int i;
  1735. for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){}
  1736. if( zLine[i]!=0 ){
  1737. nSql = strlen30(zLine);
  1738. zSql = malloc( nSql+3 );
  1739. if( zSql==0 ){
  1740. fprintf(stderr, "out of memory\n");
  1741. exit(1);
  1742. }
  1743. memcpy(zSql, zLine, nSql+1);
  1744. startline = lineno;
  1745. }
  1746. }else{
  1747. int len = strlen30(zLine);
  1748. zSql = realloc( zSql, nSql + len + 4 );
  1749. if( zSql==0 ){
  1750. fprintf(stderr,"%s: out of memory!\n", Argv0);
  1751. exit(1);
  1752. }
  1753. zSql[nSql++] = '\n';
  1754. memcpy(&zSql[nSql], zLine, len+1);
  1755. nSql += len;
  1756. }
  1757. if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  1758. && sqlite3_complete(zSql) ){
  1759. p->cnt = 0;
  1760. open_db(p);
  1761. BEGIN_TIMER;
  1762. rc = sqlite3_exec(p->db, zSql, callback, p, &zErrMsg);
  1763. END_TIMER;
  1764. if( rc || zErrMsg ){
  1765. char zPrefix[100];
  1766. if( in!=0 || !stdin_is_interactive ){
  1767. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  1768. "SQL error near line %d:", startline);
  1769. }else{
  1770. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "SQL error:");
  1771. }
  1772. if( zErrMsg!=0 ){
  1773. printf("%s %s\n", zPrefix, zErrMsg);
  1774. sqlite3_free(zErrMsg);
  1775. zErrMsg = 0;
  1776. }else{
  1777. printf("%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  1778. }
  1779. errCnt++;
  1780. }
  1781. free(zSql);
  1782. zSql = 0;
  1783. nSql = 0;
  1784. }
  1785. }
  1786. if( zSql ){
  1787. if( !_all_whitespace(zSql) ) fprintf(stderr, "Incomplete SQL: %s\n", zSql);
  1788. free(zSql);
  1789. }
  1790. free(zLine);
  1791. return errCnt;
  1792. }
  1793. /*
  1794. ** Return a pathname which is the user's home directory. A
  1795. ** 0 return indicates an error of some kind. Space to hold the
  1796. ** resulting string is obtained from malloc(). The calling
  1797. ** function should free the result.
  1798. */
  1799. static char *find_home_dir(void){
  1800. char *home_dir = NULL;
  1801. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  1802. struct passwd *pwent;
  1803. uid_t uid = getuid();
  1804. if( (pwent=getpwuid(uid)) != NULL) {
  1805. home_dir = pwent->pw_dir;
  1806. }
  1807. #endif
  1808. #if defined(_WIN32_WCE)
  1809. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  1810. */
  1811. home_dir = strdup("/");
  1812. #else
  1813. #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  1814. if (!home_dir) {
  1815. home_dir = getenv("USERPROFILE");
  1816. }
  1817. #endif
  1818. if (!home_dir) {
  1819. home_dir = getenv("HOME");
  1820. }
  1821. #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  1822. if (!home_dir) {
  1823. char *zDrive, *zPath;
  1824. int n;
  1825. zDrive = getenv("HOMEDRIVE");
  1826. zPath = getenv("HOMEPATH");
  1827. if( zDrive && zPath ){
  1828. n = strlen30(zDrive) + strlen30(zPath) + 1;
  1829. home_dir = malloc( n );
  1830. if( home_dir==0 ) return 0;
  1831. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  1832. return home_dir;
  1833. }
  1834. home_dir = "c:\\";
  1835. }
  1836. #endif
  1837. #endif /* !_WIN32_WCE */
  1838. if( home_dir ){
  1839. int n = strlen30(home_dir) + 1;
  1840. char *z = malloc( n );
  1841. if( z ) memcpy(z, home_dir, n);
  1842. home_dir = z;
  1843. }
  1844. return home_dir;
  1845. }
  1846. /*
  1847. ** Read input from the file given by sqliterc_override. Or if that
  1848. ** parameter is NULL, take input from ~/.sqliterc
  1849. */
  1850. static void process_sqliterc(
  1851. struct callback_data *p, /* Configuration data */
  1852. const char *sqliterc_override /* Name of config file. NULL to use default */
  1853. ){
  1854. char *home_dir = NULL;
  1855. const char *sqliterc = sqliterc_override;
  1856. char *zBuf = 0;
  1857. FILE *in = NULL;
  1858. int nBuf;
  1859. if (sqliterc == NULL) {
  1860. home_dir = find_home_dir();
  1861. if( home_dir==0 ){
  1862. #if !defined(__RTP__) && !defined(_WRS_KERNEL)
  1863. fprintf(stderr,"%s: cannot locate your home directory!\n", Argv0);
  1864. #endif
  1865. return;
  1866. }
  1867. nBuf = strlen30(home_dir) + 16;
  1868. zBuf = malloc( nBuf );
  1869. if( zBuf==0 ){
  1870. fprintf(stderr,"%s: out of memory!\n", Argv0);
  1871. exit(1);
  1872. }
  1873. sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
  1874. free(home_dir);
  1875. sqliterc = (const char*)zBuf;
  1876. }
  1877. in = fopen(sqliterc,"rb");
  1878. if( in ){
  1879. if( stdin_is_interactive ){
  1880. printf("-- Loading resources from %s\n",sqliterc);
  1881. }
  1882. process_input(p,in);
  1883. fclose(in);
  1884. }
  1885. free(zBuf);
  1886. return;
  1887. }
  1888. /*
  1889. ** Show available command line options
  1890. */
  1891. static const char zOptions[] =
  1892. " -init filename read/process named file\n"
  1893. " -echo print commands before execution\n"
  1894. " -[no]header turn headers on or off\n"
  1895. " -bail stop after hitting an error\n"
  1896. " -interactive force interactive I/O\n"
  1897. " -batch force batch I/O\n"
  1898. " -column set output mode to 'column'\n"
  1899. " -csv set output mode to 'csv'\n"
  1900. " -html set output mode to HTML\n"
  1901. " -line set output mode to 'line'\n"
  1902. " -list set output mode to 'list'\n"
  1903. " -separator 'x' set output field separator (|)\n"
  1904. " -nullvalue 'text' set text string for NULL values\n"
  1905. " -version show SQLite version\n"
  1906. ;
  1907. static void usage(int showDetail){
  1908. fprintf(stderr,
  1909. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  1910. "FILENAME is the name of an SQLite database. A new database is created\n"
  1911. "if the file does not previously exist.\n", Argv0);
  1912. if( showDetail ){
  1913. fprintf(stderr, "OPTIONS include:\n%s", zOptions);
  1914. }else{
  1915. fprintf(stderr, "Use the -help option for additional information\n");
  1916. }
  1917. exit(1);
  1918. }
  1919. /*
  1920. ** Initialize the state information in data
  1921. */
  1922. static void main_init(struct callback_data *data) {
  1923. memset(data, 0, sizeof(*data));
  1924. data->mode = MODE_List;
  1925. memcpy(data->separator,"|", 2);
  1926. data->showHeader = 0;
  1927. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  1928. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  1929. }
  1930. int main(int argc, char **argv){
  1931. char *zErrMsg = 0;
  1932. struct callback_data data;
  1933. const char *zInitFile = 0;
  1934. char *zFirstCmd = 0;
  1935. int i;
  1936. int rc = 0;
  1937. Argv0 = argv[0];
  1938. main_init(&data);
  1939. stdin_is_interactive = isatty(0);
  1940. /* Make sure we have a valid signal handler early, before anything
  1941. ** else is done.
  1942. */
  1943. #ifdef SIGINT
  1944. signal(SIGINT, interrupt_handler);
  1945. #endif
  1946. /* Do an initial pass through the command-line argument to locate
  1947. ** the name of the database file, the name of the initialization file,
  1948. ** and the first command to execute.
  1949. */
  1950. for(i=1; i<argc-1; i++){
  1951. char *z;
  1952. if( argv[i][0]!='-' ) break;
  1953. z = argv[i];
  1954. if( z[0]=='-' && z[1]=='-' ) z++;
  1955. if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
  1956. i++;
  1957. }else if( strcmp(argv[i],"-init")==0 ){
  1958. i++;
  1959. zInitFile = argv[i];
  1960. }
  1961. }
  1962. if( i<argc ){
  1963. #if defined(SQLITE_OS_OS2) && SQLITE_OS_OS2
  1964. data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] );
  1965. #else
  1966. data.zDbFilename = argv[i++];
  1967. #endif
  1968. }else{
  1969. #ifndef SQLITE_OMIT_MEMORYDB
  1970. data.zDbFilename = ":memory:";
  1971. #else
  1972. data.zDbFilename = 0;
  1973. #endif
  1974. }
  1975. if( i<argc ){
  1976. zFirstCmd = argv[i++];
  1977. }
  1978. data.out = stdout;
  1979. #ifdef SQLITE_OMIT_MEMORYDB
  1980. if( data.zDbFilename==0 ){
  1981. fprintf(stderr,"%s: no database filename specified\n", argv[0]);
  1982. exit(1);
  1983. }
  1984. #endif
  1985. /* Go ahead and open the database file if it already exists. If the
  1986. ** file does not exist, delay opening it. This prevents empty database
  1987. ** files from being created if a user mistypes the database name argument
  1988. ** to the sqlite command-line tool.
  1989. */
  1990. if( access(data.zDbFilename, 0)==0 ){
  1991. open_db(&data);
  1992. }
  1993. /* Process the initialization file if there is one. If no -init option
  1994. ** is given on the command line, look for a file named ~/.sqliterc and
  1995. ** try to process it.
  1996. */
  1997. process_sqliterc(&data,zInitFile);
  1998. /* Make a second pass through the command-line argument and set
  1999. ** options. This second pass is delayed until after the initialization
  2000. ** file is processed so that the command-line arguments will override
  2001. ** settings in the initialization file.
  2002. */
  2003. for(i=1; i<argc && argv[i][0]=='-'; i++){
  2004. char *z = argv[i];
  2005. if( z[1]=='-' ){ z++; }
  2006. if( strcmp(z,"-init")==0 ){
  2007. i++;
  2008. }else if( strcmp(z,"-html")==0 ){
  2009. data.mode = MODE_Html;
  2010. }else if( strcmp(z,"-list")==0 ){
  2011. data.mode = MODE_List;
  2012. }else if( strcmp(z,"-line")==0 ){
  2013. data.mode = MODE_Line;
  2014. }else if( strcmp(z,"-column")==0 ){
  2015. data.mode = MODE_Column;
  2016. }else if( strcmp(z,"-csv")==0 ){
  2017. data.mode = MODE_Csv;
  2018. memcpy(data.separator,",",2);
  2019. }else if( strcmp(z,"-separator")==0 ){
  2020. i++;
  2021. sqlite3_snprintf(sizeof(data.separator), data.separator,
  2022. "%.*s",(int)sizeof(data.separator)-1,argv[i]);
  2023. }else if( strcmp(z,"-nullvalue")==0 ){
  2024. i++;
  2025. sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
  2026. "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
  2027. }else if( strcmp(z,"-header")==0 ){
  2028. data.showHeader = 1;
  2029. }else if( strcmp(z,"-noheader")==0 ){
  2030. data.showHeader = 0;
  2031. }else if( strcmp(z,"-echo")==0 ){
  2032. data.echoOn = 1;
  2033. }else if( strcmp(z,"-bail")==0 ){
  2034. bail_on_error = 1;
  2035. }else if( strcmp(z,"-version")==0 ){
  2036. printf("%s\n", sqlite3_libversion());
  2037. return 0;
  2038. }else if( strcmp(z,"-interactive")==0 ){
  2039. stdin_is_interactive = 1;
  2040. }else if( strcmp(z,"-batch")==0 ){
  2041. stdin_is_interactive = 0;
  2042. }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){
  2043. usage(1);
  2044. }else{
  2045. fprintf(stderr,"%s: unknown option: %s\n", Argv0, z);
  2046. fprintf(stderr,"Use -help for a list of options.\n");
  2047. return 1;
  2048. }
  2049. }
  2050. if( zFirstCmd ){
  2051. /* Run just the command that follows the database name
  2052. */
  2053. if( zFirstCmd[0]=='.' ){
  2054. do_meta_command(zFirstCmd, &data);
  2055. exit(0);
  2056. }else{
  2057. int rc;
  2058. open_db(&data);
  2059. rc = sqlite3_exec(data.db, zFirstCmd, callback, &data, &zErrMsg);
  2060. if( rc!=0 && zErrMsg!=0 ){
  2061. fprintf(stderr,"SQL error: %s\n", zErrMsg);
  2062. exit(1);
  2063. }
  2064. }
  2065. }else{
  2066. /* Run commands received from standard input
  2067. */
  2068. if( stdin_is_interactive ){
  2069. char *zHome;
  2070. char *zHistory = 0;
  2071. int nHistory;
  2072. printf(
  2073. "SQLite version %s\n"
  2074. "Enter \".help\" for instructions\n"
  2075. "Enter SQL statements terminated with a \";\"\n",
  2076. sqlite3_libversion()
  2077. );
  2078. zHome = find_home_dir();
  2079. if( zHome ){
  2080. nHistory = strlen30(zHome) + 20;
  2081. if( (zHistory = malloc(nHistory))!=0 ){
  2082. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  2083. }
  2084. }
  2085. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  2086. if( zHistory ) read_history(zHistory);
  2087. #endif
  2088. rc = process_input(&data, 0);
  2089. if( zHistory ){
  2090. stifle_history(100);
  2091. write_history(zHistory);
  2092. free(zHistory);
  2093. }
  2094. free(zHome);
  2095. }else{
  2096. rc = process_input(&data, stdin);
  2097. }
  2098. }
  2099. set_table_name(&data, 0);
  2100. if( db ){
  2101. if( sqlite3_close(db)!=SQLITE_OK ){
  2102. fprintf(stderr,"error closing database: %s\n", sqlite3_errmsg(db));
  2103. }
  2104. }
  2105. return rc;
  2106. }