PageRenderTime 55ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/pdo_sqlite/sqlite/src/shell.c

http://php52-backports.googlecode.com/
C | 1997 lines | 1688 code | 94 blank | 215 comment | 365 complexity | 69b680b8c97fc453090f728016b9fb39 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause

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

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