PageRenderTime 60ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/usr/src/cmd/sqlite/shell.c

https://bitbucket.org/a3217055/illumos-gate
C | 1364 lines | 1219 code | 31 blank | 114 comment | 95 complexity | 37d10393f3881ec2c3e2bb34d75acc6b MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, LGPL-2.0, 0BSD, AGPL-3.0, GPL-2.0, GPL-3.0, LGPL-2.1, LGPL-3.0, BSD-3-Clause-No-Nuclear-License-2014, MPL-2.0-no-copyleft-exception, AGPL-1.0
  1. /*
  2. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  3. * Use is subject to license terms.
  4. */
  5. #pragma ident "%Z%%M% %I% %E% SMI"
  6. /*
  7. ** 2001 September 15
  8. **
  9. ** The author disclaims copyright to this source code. In place of
  10. ** a legal notice, here is a blessing:
  11. **
  12. ** May you do good and not evil.
  13. ** May you find forgiveness for yourself and forgive others.
  14. ** May you share freely, never taking more than you give.
  15. **
  16. *************************************************************************
  17. ** This file contains code to implement the "sqlite" command line
  18. ** utility for accessing SQLite databases.
  19. **
  20. ** $Id: shell.c,v 1.93 2004/03/17 23:42:13 drh Exp $
  21. */
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <stdio.h>
  25. #include "sqlite.h"
  26. #include "sqlite-misc.h" /* SUNW addition */
  27. #include <ctype.h>
  28. #if !defined(_WIN32) && !defined(WIN32) && !defined(__MACOS__)
  29. # include <signal.h>
  30. # include <pwd.h>
  31. # include <unistd.h>
  32. # include <sys/types.h>
  33. #endif
  34. #ifdef __MACOS__
  35. # include <console.h>
  36. # include <signal.h>
  37. # include <unistd.h>
  38. # include <extras.h>
  39. # include <Files.h>
  40. # include <Folders.h>
  41. #endif
  42. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  43. # include <readline/readline.h>
  44. # include <readline/history.h>
  45. #else
  46. # define readline(p) local_getline(p,stdin)
  47. # define add_history(X)
  48. # define read_history(X)
  49. # define write_history(X)
  50. # define stifle_history(X)
  51. #endif
  52. /* Make sure isatty() has a prototype.
  53. */
  54. extern int isatty();
  55. /*
  56. ** The following is the open SQLite database. We make a pointer
  57. ** to this database a static variable so that it can be accessed
  58. ** by the SIGINT handler to interrupt database processing.
  59. */
  60. static sqlite *db = 0;
  61. /*
  62. ** True if an interrupt (Control-C) has been received.
  63. */
  64. static int seenInterrupt = 0;
  65. /*
  66. ** This is the name of our program. It is set in main(), used
  67. ** in a number of other places, mostly for error messages.
  68. */
  69. static char *Argv0;
  70. /*
  71. ** Prompt strings. Initialized in main. Settable with
  72. ** .prompt main continue
  73. */
  74. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  75. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  76. /*
  77. ** Determines if a string is a number of not.
  78. */
  79. extern int sqliteIsNumber(const char*);
  80. /*
  81. ** This routine reads a line of text from standard input, stores
  82. ** the text in memory obtained from malloc() and returns a pointer
  83. ** to the text. NULL is returned at end of file, or if malloc()
  84. ** fails.
  85. **
  86. ** The interface is like "readline" but no command-line editing
  87. ** is done.
  88. */
  89. static char *local_getline(char *zPrompt, FILE *in){
  90. char *zLine;
  91. int nLine;
  92. int n;
  93. int eol;
  94. if( zPrompt && *zPrompt ){
  95. printf("%s",zPrompt);
  96. fflush(stdout);
  97. }
  98. nLine = 100;
  99. zLine = malloc( nLine );
  100. if( zLine==0 ) return 0;
  101. n = 0;
  102. eol = 0;
  103. while( !eol ){
  104. if( n+100>nLine ){
  105. nLine = nLine*2 + 100;
  106. zLine = realloc(zLine, nLine);
  107. if( zLine==0 ) return 0;
  108. }
  109. if( fgets(&zLine[n], nLine - n, in)==0 ){
  110. if( n==0 ){
  111. free(zLine);
  112. return 0;
  113. }
  114. zLine[n] = 0;
  115. eol = 1;
  116. break;
  117. }
  118. while( zLine[n] ){ n++; }
  119. if( n>0 && zLine[n-1]=='\n' ){
  120. n--;
  121. zLine[n] = 0;
  122. eol = 1;
  123. }
  124. }
  125. zLine = realloc( zLine, n+1 );
  126. return zLine;
  127. }
  128. /*
  129. ** Retrieve a single line of input text. "isatty" is true if text
  130. ** is coming from a terminal. In that case, we issue a prompt and
  131. ** attempt to use "readline" for command-line editing. If "isatty"
  132. ** is false, use "local_getline" instead of "readline" and issue no prompt.
  133. **
  134. ** zPrior is a string of prior text retrieved. If not the empty
  135. ** string, then issue a continuation prompt.
  136. */
  137. static char *one_input_line(const char *zPrior, FILE *in){
  138. char *zPrompt;
  139. char *zResult;
  140. if( in!=0 ){
  141. return local_getline(0, in);
  142. }
  143. if( zPrior && zPrior[0] ){
  144. zPrompt = continuePrompt;
  145. }else{
  146. zPrompt = mainPrompt;
  147. }
  148. zResult = readline(zPrompt);
  149. if( zResult ) add_history(zResult);
  150. return zResult;
  151. }
  152. struct previous_mode_data {
  153. int valid; /* Is there legit data in here? */
  154. int mode;
  155. int showHeader;
  156. int colWidth[100];
  157. };
  158. /*
  159. ** An pointer to an instance of this structure is passed from
  160. ** the main program to the callback. This is used to communicate
  161. ** state and mode information.
  162. */
  163. struct callback_data {
  164. sqlite *db; /* The database */
  165. int echoOn; /* True to echo input commands */
  166. int cnt; /* Number of records displayed so far */
  167. FILE *out; /* Write results here */
  168. int mode; /* An output mode setting */
  169. int showHeader; /* True to show column names in List or Column mode */
  170. char *zDestTable; /* Name of destination table when MODE_Insert */
  171. char separator[20]; /* Separator character for MODE_List */
  172. int colWidth[100]; /* Requested width of each column when in column mode*/
  173. int actualWidth[100]; /* Actual width of each column */
  174. char nullvalue[20]; /* The text to print when a NULL comes back from
  175. ** the database */
  176. struct previous_mode_data explainPrev;
  177. /* Holds the mode information just before
  178. ** .explain ON */
  179. char outfile[FILENAME_MAX]; /* Filename for *out */
  180. const char *zDbFilename; /* name of the database file */
  181. char *zKey; /* Encryption key */
  182. };
  183. /*
  184. ** These are the allowed modes.
  185. */
  186. #define MODE_Line 0 /* One column per line. Blank line between records */
  187. #define MODE_Column 1 /* One record per line in neat columns */
  188. #define MODE_List 2 /* One record per line with a separator */
  189. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  190. #define MODE_Html 4 /* Generate an XHTML table */
  191. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  192. #define MODE_NUM_OF 6 /* The number of modes (not a mode itself) */
  193. char *modeDescr[MODE_NUM_OF] = {
  194. "line",
  195. "column",
  196. "list",
  197. "semi",
  198. "html",
  199. "insert"
  200. };
  201. /*
  202. ** Number of elements in an array
  203. */
  204. #define ArraySize(X) (sizeof(X)/sizeof(X[0]))
  205. /*
  206. ** Output the given string as a quoted string using SQL quoting conventions.
  207. */
  208. static void output_quoted_string(FILE *out, const char *z){
  209. int i;
  210. int nSingle = 0;
  211. for(i=0; z[i]; i++){
  212. if( z[i]=='\'' ) nSingle++;
  213. }
  214. if( nSingle==0 ){
  215. fprintf(out,"'%s'",z);
  216. }else{
  217. fprintf(out,"'");
  218. while( *z ){
  219. for(i=0; z[i] && z[i]!='\''; i++){}
  220. if( i==0 ){
  221. fprintf(out,"''");
  222. z++;
  223. }else if( z[i]=='\'' ){
  224. fprintf(out,"%.*s''",i,z);
  225. z += i+1;
  226. }else{
  227. fprintf(out,"%s",z);
  228. break;
  229. }
  230. }
  231. fprintf(out,"'");
  232. }
  233. }
  234. /*
  235. ** Output the given string with characters that are special to
  236. ** HTML escaped.
  237. */
  238. static void output_html_string(FILE *out, const char *z){
  239. int i;
  240. while( *z ){
  241. for(i=0; z[i] && z[i]!='<' && z[i]!='&'; i++){}
  242. if( i>0 ){
  243. fprintf(out,"%.*s",i,z);
  244. }
  245. if( z[i]=='<' ){
  246. fprintf(out,"&lt;");
  247. }else if( z[i]=='&' ){
  248. fprintf(out,"&amp;");
  249. }else{
  250. break;
  251. }
  252. z += i + 1;
  253. }
  254. }
  255. /*
  256. ** This routine runs when the user presses Ctrl-C
  257. */
  258. static void interrupt_handler(int NotUsed){
  259. seenInterrupt = 1;
  260. if( db ) sqlite_interrupt(db);
  261. }
  262. /*
  263. ** This is the callback routine that the SQLite library
  264. ** invokes for each row of a query result.
  265. */
  266. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  267. int i;
  268. struct callback_data *p = (struct callback_data*)pArg;
  269. switch( p->mode ){
  270. case MODE_Line: {
  271. int w = 5;
  272. if( azArg==0 ) break;
  273. for(i=0; i<nArg; i++){
  274. int len = strlen(azCol[i]);
  275. if( len>w ) w = len;
  276. }
  277. if( p->cnt++>0 ) fprintf(p->out,"\n");
  278. for(i=0; i<nArg; i++){
  279. fprintf(p->out,"%*s = %s\n", w, azCol[i],
  280. azArg[i] ? azArg[i] : p->nullvalue);
  281. }
  282. break;
  283. }
  284. case MODE_Column: {
  285. if( p->cnt++==0 ){
  286. for(i=0; i<nArg; i++){
  287. int w, n;
  288. if( i<ArraySize(p->colWidth) ){
  289. w = p->colWidth[i];
  290. }else{
  291. w = 0;
  292. }
  293. if( w<=0 ){
  294. w = strlen(azCol[i] ? azCol[i] : "");
  295. if( w<10 ) w = 10;
  296. n = strlen(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  297. if( w<n ) w = n;
  298. }
  299. if( i<ArraySize(p->actualWidth) ){
  300. p->actualWidth[i] = w;
  301. }
  302. if( p->showHeader ){
  303. fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
  304. }
  305. }
  306. if( p->showHeader ){
  307. for(i=0; i<nArg; i++){
  308. int w;
  309. if( i<ArraySize(p->actualWidth) ){
  310. w = p->actualWidth[i];
  311. }else{
  312. w = 10;
  313. }
  314. fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  315. "----------------------------------------------------------",
  316. i==nArg-1 ? "\n": " ");
  317. }
  318. }
  319. }
  320. if( azArg==0 ) break;
  321. for(i=0; i<nArg; i++){
  322. int w;
  323. if( i<ArraySize(p->actualWidth) ){
  324. w = p->actualWidth[i];
  325. }else{
  326. w = 10;
  327. }
  328. fprintf(p->out,"%-*.*s%s",w,w,
  329. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  330. }
  331. break;
  332. }
  333. case MODE_Semi:
  334. case MODE_List: {
  335. if( p->cnt++==0 && p->showHeader ){
  336. for(i=0; i<nArg; i++){
  337. fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  338. }
  339. }
  340. if( azArg==0 ) break;
  341. for(i=0; i<nArg; i++){
  342. char *z = azArg[i];
  343. if( z==0 ) z = p->nullvalue;
  344. fprintf(p->out, "%s", z);
  345. if( i<nArg-1 ){
  346. fprintf(p->out, "%s", p->separator);
  347. }else if( p->mode==MODE_Semi ){
  348. fprintf(p->out, ";\n");
  349. }else{
  350. fprintf(p->out, "\n");
  351. }
  352. }
  353. break;
  354. }
  355. case MODE_Html: {
  356. if( p->cnt++==0 && p->showHeader ){
  357. fprintf(p->out,"<TR>");
  358. for(i=0; i<nArg; i++){
  359. fprintf(p->out,"<TH>%s</TH>",azCol[i]);
  360. }
  361. fprintf(p->out,"</TR>\n");
  362. }
  363. if( azArg==0 ) break;
  364. fprintf(p->out,"<TR>");
  365. for(i=0; i<nArg; i++){
  366. fprintf(p->out,"<TD>");
  367. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  368. fprintf(p->out,"</TD>\n");
  369. }
  370. fprintf(p->out,"</TR>\n");
  371. break;
  372. }
  373. case MODE_Insert: {
  374. if( azArg==0 ) break;
  375. fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  376. for(i=0; i<nArg; i++){
  377. char *zSep = i>0 ? ",": "";
  378. if( azArg[i]==0 ){
  379. fprintf(p->out,"%sNULL",zSep);
  380. }else if( sqliteIsNumber(azArg[i]) ){
  381. fprintf(p->out,"%s%s",zSep, azArg[i]);
  382. }else{
  383. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  384. output_quoted_string(p->out, azArg[i]);
  385. }
  386. }
  387. fprintf(p->out,");\n");
  388. break;
  389. }
  390. }
  391. return 0;
  392. }
  393. /*
  394. ** Set the destination table field of the callback_data structure to
  395. ** the name of the table given. Escape any quote characters in the
  396. ** table name.
  397. */
  398. static void set_table_name(struct callback_data *p, const char *zName){
  399. int i, n;
  400. int needQuote;
  401. char *z;
  402. if( p->zDestTable ){
  403. free(p->zDestTable);
  404. p->zDestTable = 0;
  405. }
  406. if( zName==0 ) return;
  407. needQuote = !isalpha(*zName) && *zName!='_';
  408. for(i=n=0; zName[i]; i++, n++){
  409. if( !isalnum(zName[i]) && zName[i]!='_' ){
  410. needQuote = 1;
  411. if( zName[i]=='\'' ) n++;
  412. }
  413. }
  414. if( needQuote ) n += 2;
  415. z = p->zDestTable = malloc( n+1 );
  416. if( z==0 ){
  417. fprintf(stderr,"Out of memory!\n");
  418. exit(1);
  419. }
  420. n = 0;
  421. if( needQuote ) z[n++] = '\'';
  422. for(i=0; zName[i]; i++){
  423. z[n++] = zName[i];
  424. if( zName[i]=='\'' ) z[n++] = '\'';
  425. }
  426. if( needQuote ) z[n++] = '\'';
  427. z[n] = 0;
  428. }
  429. /*
  430. ** This is a different callback routine used for dumping the database.
  431. ** Each row received by this callback consists of a table name,
  432. ** the table type ("index" or "table") and SQL to create the table.
  433. ** This routine should print text sufficient to recreate the table.
  434. */
  435. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  436. struct callback_data *p = (struct callback_data *)pArg;
  437. if( nArg!=3 ) return 1;
  438. fprintf(p->out, "%s;\n", azArg[2]);
  439. if( strcmp(azArg[1],"table")==0 ){
  440. struct callback_data d2;
  441. d2 = *p;
  442. d2.mode = MODE_Insert;
  443. d2.zDestTable = 0;
  444. set_table_name(&d2, azArg[0]);
  445. sqlite_exec_printf(p->db,
  446. "SELECT * FROM '%q'",
  447. callback, &d2, 0, azArg[0]
  448. );
  449. set_table_name(&d2, 0);
  450. }
  451. return 0;
  452. }
  453. /*
  454. ** Text of a help message
  455. */
  456. static char zHelp[] =
  457. ".databases List names and files of attached databases\n"
  458. ".dump ?TABLE? ... Dump the database in a text format\n"
  459. ".echo ON|OFF Turn command echo on or off\n"
  460. ".exit Exit this program\n"
  461. ".explain ON|OFF Turn output mode suitable for EXPLAIN on or off.\n"
  462. ".header(s) ON|OFF Turn display of headers on or off\n"
  463. ".help Show this message\n"
  464. ".indices TABLE Show names of all indices on TABLE\n"
  465. ".mode MODE Set mode to one of \"line(s)\", \"column(s)\", \n"
  466. " \"insert\", \"list\", or \"html\"\n"
  467. ".mode insert TABLE Generate SQL insert statements for TABLE\n"
  468. ".nullvalue STRING Print STRING instead of nothing for NULL data\n"
  469. ".output FILENAME Send output to FILENAME\n"
  470. ".output stdout Send output to the screen\n"
  471. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  472. ".quit Exit this program\n"
  473. ".read FILENAME Execute SQL in FILENAME\n"
  474. #ifdef SQLITE_HAS_CODEC
  475. ".rekey OLD NEW NEW Change the encryption key\n"
  476. #endif
  477. ".schema ?TABLE? Show the CREATE statements\n"
  478. ".separator STRING Change separator string for \"list\" mode\n"
  479. ".show Show the current values for various settings\n"
  480. ".tables ?PATTERN? List names of tables matching a pattern\n"
  481. ".timeout MS Try opening locked tables for MS milliseconds\n"
  482. ".width NUM NUM ... Set column widths for \"column\" mode\n"
  483. ;
  484. /* Forward reference */
  485. static void process_input(struct callback_data *p, FILE *in);
  486. /*
  487. ** Make sure the database is open. If it is not, then open it. If
  488. ** the database fails to open, print an error message and exit.
  489. */
  490. static void open_db(struct callback_data *p){
  491. if( p->db==0 ){
  492. char *zErrMsg = 0;
  493. #ifdef SQLITE_HAS_CODEC
  494. int n = p->zKey ? strlen(p->zKey) : 0;
  495. db = p->db = sqlite_open_encrypted(p->zDbFilename, p->zKey, n, 0, &zErrMsg);
  496. #else
  497. db = p->db = sqlite_open(p->zDbFilename, 0, &zErrMsg);
  498. #endif
  499. if( p->db==0 ){
  500. if( zErrMsg ){
  501. fprintf(stderr,"Unable to open database \"%s\": %s\n",
  502. p->zDbFilename, zErrMsg);
  503. }else{
  504. fprintf(stderr,"Unable to open database %s\n", p->zDbFilename);
  505. }
  506. exit(1);
  507. }
  508. }
  509. }
  510. /*
  511. ** If an input line begins with "." then invoke this routine to
  512. ** process that line.
  513. **
  514. ** Return 1 to exit and 0 to continue.
  515. */
  516. static int do_meta_command(char *zLine, struct callback_data *p){
  517. int i = 1;
  518. int nArg = 0;
  519. int n, c;
  520. int rc = 0;
  521. char *azArg[50];
  522. /* Parse the input line into tokens.
  523. */
  524. while( zLine[i] && nArg<ArraySize(azArg) ){
  525. while( isspace(zLine[i]) ){ i++; }
  526. if( zLine[i]==0 ) break;
  527. if( zLine[i]=='\'' || zLine[i]=='"' ){
  528. int delim = zLine[i++];
  529. azArg[nArg++] = &zLine[i];
  530. while( zLine[i] && zLine[i]!=delim ){ i++; }
  531. if( zLine[i]==delim ){
  532. zLine[i++] = 0;
  533. }
  534. }else{
  535. azArg[nArg++] = &zLine[i];
  536. while( zLine[i] && !isspace(zLine[i]) ){ i++; }
  537. if( zLine[i] ) zLine[i++] = 0;
  538. }
  539. }
  540. /* Process the input line.
  541. */
  542. if( nArg==0 ) return rc;
  543. n = strlen(azArg[0]);
  544. c = azArg[0][0];
  545. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  546. struct callback_data data;
  547. char *zErrMsg = 0;
  548. open_db(p);
  549. memcpy(&data, p, sizeof(data));
  550. data.showHeader = 1;
  551. data.mode = MODE_Column;
  552. data.colWidth[0] = 3;
  553. data.colWidth[1] = 15;
  554. data.colWidth[2] = 58;
  555. sqlite_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  556. if( zErrMsg ){
  557. fprintf(stderr,"Error: %s\n", zErrMsg);
  558. sqlite_freemem(zErrMsg);
  559. }
  560. }else
  561. if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  562. char *zErrMsg = 0;
  563. open_db(p);
  564. fprintf(p->out, "BEGIN TRANSACTION;\n");
  565. if( nArg==1 ){
  566. sqlite_exec(p->db,
  567. "SELECT name, type, sql FROM sqlite_master "
  568. "WHERE type!='meta' AND sql NOT NULL "
  569. "ORDER BY substr(type,2,1), name",
  570. dump_callback, p, &zErrMsg
  571. );
  572. }else{
  573. int i;
  574. for(i=1; i<nArg && zErrMsg==0; i++){
  575. sqlite_exec_printf(p->db,
  576. "SELECT name, type, sql FROM sqlite_master "
  577. "WHERE tbl_name LIKE '%q' AND type!='meta' AND sql NOT NULL "
  578. "ORDER BY substr(type,2,1), name",
  579. dump_callback, p, &zErrMsg, azArg[i]
  580. );
  581. }
  582. }
  583. if( zErrMsg ){
  584. fprintf(stderr,"Error: %s\n", zErrMsg);
  585. sqlite_freemem(zErrMsg);
  586. }else{
  587. fprintf(p->out, "COMMIT;\n");
  588. }
  589. }else
  590. if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){
  591. int j;
  592. char *z = azArg[1];
  593. int val = atoi(azArg[1]);
  594. for(j=0; z[j]; j++){
  595. if( isupper(z[j]) ) z[j] = tolower(z[j]);
  596. }
  597. if( strcmp(z,"on")==0 ){
  598. val = 1;
  599. }else if( strcmp(z,"yes")==0 ){
  600. val = 1;
  601. }
  602. p->echoOn = val;
  603. }else
  604. if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  605. rc = 1;
  606. }else
  607. if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  608. int j;
  609. char *z = nArg>=2 ? azArg[1] : "1";
  610. int val = atoi(z);
  611. for(j=0; z[j]; j++){
  612. if( isupper(z[j]) ) z[j] = tolower(z[j]);
  613. }
  614. if( strcmp(z,"on")==0 ){
  615. val = 1;
  616. }else if( strcmp(z,"yes")==0 ){
  617. val = 1;
  618. }
  619. if(val == 1) {
  620. if(!p->explainPrev.valid) {
  621. p->explainPrev.valid = 1;
  622. p->explainPrev.mode = p->mode;
  623. p->explainPrev.showHeader = p->showHeader;
  624. memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
  625. }
  626. /* We could put this code under the !p->explainValid
  627. ** condition so that it does not execute if we are already in
  628. ** explain mode. However, always executing it allows us an easy
  629. ** was to reset to explain mode in case the user previously
  630. ** did an .explain followed by a .width, .mode or .header
  631. ** command.
  632. */
  633. p->mode = MODE_Column;
  634. p->showHeader = 1;
  635. memset(p->colWidth,0,ArraySize(p->colWidth));
  636. p->colWidth[0] = 4;
  637. p->colWidth[1] = 12;
  638. p->colWidth[2] = 10;
  639. p->colWidth[3] = 10;
  640. p->colWidth[4] = 35;
  641. }else if (p->explainPrev.valid) {
  642. p->explainPrev.valid = 0;
  643. p->mode = p->explainPrev.mode;
  644. p->showHeader = p->explainPrev.showHeader;
  645. memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
  646. }
  647. }else
  648. if( c=='h' && (strncmp(azArg[0], "header", n)==0
  649. ||
  650. strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){
  651. int j;
  652. char *z = azArg[1];
  653. int val = atoi(azArg[1]);
  654. for(j=0; z[j]; j++){
  655. if( isupper(z[j]) ) z[j] = tolower(z[j]);
  656. }
  657. if( strcmp(z,"on")==0 ){
  658. val = 1;
  659. }else if( strcmp(z,"yes")==0 ){
  660. val = 1;
  661. }
  662. p->showHeader = val;
  663. }else
  664. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  665. fprintf(stderr,zHelp);
  666. }else
  667. if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){
  668. struct callback_data data;
  669. char *zErrMsg = 0;
  670. open_db(p);
  671. memcpy(&data, p, sizeof(data));
  672. data.showHeader = 0;
  673. data.mode = MODE_List;
  674. sqlite_exec_printf(p->db,
  675. "SELECT name FROM sqlite_master "
  676. "WHERE type='index' AND tbl_name LIKE '%q' "
  677. "UNION ALL "
  678. "SELECT name FROM sqlite_temp_master "
  679. "WHERE type='index' AND tbl_name LIKE '%q' "
  680. "ORDER BY 1",
  681. callback, &data, &zErrMsg, azArg[1], azArg[1]
  682. );
  683. if( zErrMsg ){
  684. fprintf(stderr,"Error: %s\n", zErrMsg);
  685. sqlite_freemem(zErrMsg);
  686. }
  687. }else
  688. if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){
  689. int n2 = strlen(azArg[1]);
  690. if( strncmp(azArg[1],"line",n2)==0
  691. ||
  692. strncmp(azArg[1],"lines",n2)==0 ){
  693. p->mode = MODE_Line;
  694. }else if( strncmp(azArg[1],"column",n2)==0
  695. ||
  696. strncmp(azArg[1],"columns",n2)==0 ){
  697. p->mode = MODE_Column;
  698. }else if( strncmp(azArg[1],"list",n2)==0 ){
  699. p->mode = MODE_List;
  700. }else if( strncmp(azArg[1],"html",n2)==0 ){
  701. p->mode = MODE_Html;
  702. }else if( strncmp(azArg[1],"insert",n2)==0 ){
  703. p->mode = MODE_Insert;
  704. if( nArg>=3 ){
  705. set_table_name(p, azArg[2]);
  706. }else{
  707. set_table_name(p, "table");
  708. }
  709. }else {
  710. fprintf(stderr,"mode should be on of: column html insert line list\n");
  711. }
  712. }else
  713. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
  714. sprintf(p->nullvalue, "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  715. }else
  716. if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
  717. if( p->out!=stdout ){
  718. fclose(p->out);
  719. }
  720. if( strcmp(azArg[1],"stdout")==0 ){
  721. p->out = stdout;
  722. strcpy(p->outfile,"stdout");
  723. }else{
  724. p->out = fopen(azArg[1], "wb");
  725. if( p->out==0 ){
  726. fprintf(stderr,"can't write to \"%s\"\n", azArg[1]);
  727. p->out = stdout;
  728. } else {
  729. strcpy(p->outfile,azArg[1]);
  730. }
  731. }
  732. }else
  733. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
  734. if( nArg >= 2) {
  735. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  736. }
  737. if( nArg >= 3) {
  738. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  739. }
  740. }else
  741. if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  742. rc = 1;
  743. }else
  744. if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
  745. FILE *alt = fopen(azArg[1], "rb");
  746. if( alt==0 ){
  747. fprintf(stderr,"can't open \"%s\"\n", azArg[1]);
  748. }else{
  749. process_input(p, alt);
  750. fclose(alt);
  751. }
  752. }else
  753. #ifdef SQLITE_HAS_CODEC
  754. if( c=='r' && strncmp(azArg[0],"rekey", n)==0 && nArg==4 ){
  755. char *zOld = p->zKey;
  756. if( zOld==0 ) zOld = "";
  757. if( strcmp(azArg[1],zOld) ){
  758. fprintf(stderr,"old key is incorrect\n");
  759. }else if( strcmp(azArg[2], azArg[3]) ){
  760. fprintf(stderr,"2nd copy of new key does not match the 1st\n");
  761. }else{
  762. sqlite_freemem(p->zKey);
  763. p->zKey = sqlite_mprintf("%s", azArg[2]);
  764. sqlite_rekey(p->db, p->zKey, strlen(p->zKey));
  765. }
  766. }else
  767. #endif
  768. if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  769. struct callback_data data;
  770. char *zErrMsg = 0;
  771. open_db(p);
  772. memcpy(&data, p, sizeof(data));
  773. data.showHeader = 0;
  774. data.mode = MODE_Semi;
  775. if( nArg>1 ){
  776. extern int sqliteStrICmp(const char*,const char*);
  777. if( sqliteStrICmp(azArg[1],"sqlite_master")==0 ){
  778. char *new_argv[2], *new_colv[2];
  779. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  780. " type text,\n"
  781. " name text,\n"
  782. " tbl_name text,\n"
  783. " rootpage integer,\n"
  784. " sql text\n"
  785. ")";
  786. new_argv[1] = 0;
  787. new_colv[0] = "sql";
  788. new_colv[1] = 0;
  789. callback(&data, 1, new_argv, new_colv);
  790. }else if( sqliteStrICmp(azArg[1],"sqlite_temp_master")==0 ){
  791. char *new_argv[2], *new_colv[2];
  792. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  793. " type text,\n"
  794. " name text,\n"
  795. " tbl_name text,\n"
  796. " rootpage integer,\n"
  797. " sql text\n"
  798. ")";
  799. new_argv[1] = 0;
  800. new_colv[0] = "sql";
  801. new_colv[1] = 0;
  802. callback(&data, 1, new_argv, new_colv);
  803. }else{
  804. sqlite_exec_printf(p->db,
  805. "SELECT sql FROM "
  806. " (SELECT * FROM sqlite_master UNION ALL"
  807. " SELECT * FROM sqlite_temp_master) "
  808. "WHERE tbl_name LIKE '%q' AND type!='meta' AND sql NOTNULL "
  809. "ORDER BY substr(type,2,1), name",
  810. callback, &data, &zErrMsg, azArg[1]);
  811. }
  812. }else{
  813. sqlite_exec(p->db,
  814. "SELECT sql FROM "
  815. " (SELECT * FROM sqlite_master UNION ALL"
  816. " SELECT * FROM sqlite_temp_master) "
  817. "WHERE type!='meta' AND sql NOTNULL "
  818. "ORDER BY substr(type,2,1), name",
  819. callback, &data, &zErrMsg
  820. );
  821. }
  822. if( zErrMsg ){
  823. fprintf(stderr,"Error: %s\n", zErrMsg);
  824. sqlite_freemem(zErrMsg);
  825. }
  826. }else
  827. if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
  828. sprintf(p->separator, "%.*s", (int)ArraySize(p->separator)-1, azArg[1]);
  829. }else
  830. if( c=='s' && strncmp(azArg[0], "show", n)==0){
  831. int i;
  832. fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
  833. fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
  834. fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  835. fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  836. fprintf(p->out,"%9.9s: %s\n","nullvalue", p->nullvalue);
  837. fprintf(p->out,"%9.9s: %s\n","output",
  838. strlen(p->outfile) ? p->outfile : "stdout");
  839. fprintf(p->out,"%9.9s: %s\n","separator", p->separator);
  840. fprintf(p->out,"%9.9s: ","width");
  841. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  842. fprintf(p->out,"%d ",p->colWidth[i]);
  843. }
  844. fprintf(p->out,"\n\n");
  845. }else
  846. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
  847. char **azResult;
  848. int nRow, rc;
  849. char *zErrMsg;
  850. open_db(p);
  851. if( nArg==1 ){
  852. rc = sqlite_get_table(p->db,
  853. "SELECT name FROM sqlite_master "
  854. "WHERE type IN ('table','view') "
  855. "UNION ALL "
  856. "SELECT name FROM sqlite_temp_master "
  857. "WHERE type IN ('table','view') "
  858. "ORDER BY 1",
  859. &azResult, &nRow, 0, &zErrMsg
  860. );
  861. }else{
  862. rc = sqlite_get_table_printf(p->db,
  863. "SELECT name FROM sqlite_master "
  864. "WHERE type IN ('table','view') AND name LIKE '%%%q%%' "
  865. "UNION ALL "
  866. "SELECT name FROM sqlite_temp_master "
  867. "WHERE type IN ('table','view') AND name LIKE '%%%q%%' "
  868. "ORDER BY 1",
  869. &azResult, &nRow, 0, &zErrMsg, azArg[1], azArg[1]
  870. );
  871. }
  872. if( zErrMsg ){
  873. fprintf(stderr,"Error: %s\n", zErrMsg);
  874. sqlite_freemem(zErrMsg);
  875. }
  876. if( rc==SQLITE_OK ){
  877. int len, maxlen = 0;
  878. int i, j;
  879. int nPrintCol, nPrintRow;
  880. for(i=1; i<=nRow; i++){
  881. if( azResult[i]==0 ) continue;
  882. len = strlen(azResult[i]);
  883. if( len>maxlen ) maxlen = len;
  884. }
  885. nPrintCol = 80/(maxlen+2);
  886. if( nPrintCol<1 ) nPrintCol = 1;
  887. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  888. for(i=0; i<nPrintRow; i++){
  889. for(j=i+1; j<=nRow; j+=nPrintRow){
  890. char *zSp = j<=nPrintRow ? "" : " ";
  891. printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
  892. }
  893. printf("\n");
  894. }
  895. }
  896. sqlite_free_table(azResult);
  897. }else
  898. if( c=='t' && n>1 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){
  899. open_db(p);
  900. sqlite_busy_timeout(p->db, atoi(azArg[1]));
  901. }else
  902. if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  903. int j;
  904. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  905. p->colWidth[j-1] = atoi(azArg[j]);
  906. }
  907. }else
  908. {
  909. fprintf(stderr, "unknown command or invalid arguments: "
  910. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  911. }
  912. return rc;
  913. }
  914. /*
  915. ** Return TRUE if the last non-whitespace character in z[] is a semicolon.
  916. ** z[] is N characters long.
  917. */
  918. static int _ends_with_semicolon(const char *z, int N){
  919. while( N>0 && isspace(z[N-1]) ){ N--; }
  920. return N>0 && z[N-1]==';';
  921. }
  922. /*
  923. ** Test to see if a line consists entirely of whitespace.
  924. */
  925. static int _all_whitespace(const char *z){
  926. for(; *z; z++){
  927. if( isspace(*z) ) continue;
  928. if( *z=='/' && z[1]=='*' ){
  929. z += 2;
  930. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  931. if( *z==0 ) return 0;
  932. z++;
  933. continue;
  934. }
  935. if( *z=='-' && z[1]=='-' ){
  936. z += 2;
  937. while( *z && *z!='\n' ){ z++; }
  938. if( *z==0 ) return 1;
  939. continue;
  940. }
  941. return 0;
  942. }
  943. return 1;
  944. }
  945. /*
  946. ** Return TRUE if the line typed in is an SQL command terminator other
  947. ** than a semi-colon. The SQL Server style "go" command is understood
  948. ** as is the Oracle "/".
  949. */
  950. static int _is_command_terminator(const char *zLine){
  951. extern int sqliteStrNICmp(const char*,const char*,int);
  952. while( isspace(*zLine) ){ zLine++; };
  953. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ) return 1; /* Oracle */
  954. if( sqliteStrNICmp(zLine,"go",2)==0 && _all_whitespace(&zLine[2]) ){
  955. return 1; /* SQL Server */
  956. }
  957. return 0;
  958. }
  959. /*
  960. ** Read input from *in and process it. If *in==0 then input
  961. ** is interactive - the user is typing it it. Otherwise, input
  962. ** is coming from a file or device. A prompt is issued and history
  963. ** is saved only if input is interactive. An interrupt signal will
  964. ** cause this routine to exit immediately, unless input is interactive.
  965. */
  966. static void process_input(struct callback_data *p, FILE *in){
  967. char *zLine;
  968. char *zSql = 0;
  969. int nSql = 0;
  970. char *zErrMsg;
  971. int rc;
  972. while( fflush(p->out), (zLine = one_input_line(zSql, in))!=0 ){
  973. if( seenInterrupt ){
  974. if( in!=0 ) break;
  975. seenInterrupt = 0;
  976. }
  977. if( p->echoOn ) printf("%s\n", zLine);
  978. if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
  979. if( zLine && zLine[0]=='.' && nSql==0 ){
  980. int rc = do_meta_command(zLine, p);
  981. free(zLine);
  982. if( rc ) break;
  983. continue;
  984. }
  985. if( _is_command_terminator(zLine) ){
  986. strcpy(zLine,";");
  987. }
  988. if( zSql==0 ){
  989. int i;
  990. for(i=0; zLine[i] && isspace(zLine[i]); i++){}
  991. if( zLine[i]!=0 ){
  992. nSql = strlen(zLine);
  993. zSql = malloc( nSql+1 );
  994. strcpy(zSql, zLine);
  995. }
  996. }else{
  997. int len = strlen(zLine);
  998. zSql = realloc( zSql, nSql + len + 2 );
  999. if( zSql==0 ){
  1000. fprintf(stderr,"%s: out of memory!\n", Argv0);
  1001. exit(1);
  1002. }
  1003. strcpy(&zSql[nSql++], "\n");
  1004. strcpy(&zSql[nSql], zLine);
  1005. nSql += len;
  1006. }
  1007. free(zLine);
  1008. if( zSql && _ends_with_semicolon(zSql, nSql) && sqlite_complete(zSql) ){
  1009. p->cnt = 0;
  1010. open_db(p);
  1011. rc = sqlite_exec(p->db, zSql, callback, p, &zErrMsg);
  1012. if( rc || zErrMsg ){
  1013. if( in!=0 && !p->echoOn ) printf("%s\n",zSql);
  1014. if( zErrMsg!=0 ){
  1015. printf("SQL error: %s\n", zErrMsg);
  1016. sqlite_freemem(zErrMsg);
  1017. zErrMsg = 0;
  1018. }else{
  1019. printf("SQL error: %s\n", sqlite_error_string(rc));
  1020. }
  1021. }
  1022. free(zSql);
  1023. zSql = 0;
  1024. nSql = 0;
  1025. }
  1026. }
  1027. if( zSql ){
  1028. if( !_all_whitespace(zSql) ) printf("Incomplete SQL: %s\n", zSql);
  1029. free(zSql);
  1030. }
  1031. }
  1032. /*
  1033. ** Return a pathname which is the user's home directory. A
  1034. ** 0 return indicates an error of some kind. Space to hold the
  1035. ** resulting string is obtained from malloc(). The calling
  1036. ** function should free the result.
  1037. */
  1038. static char *find_home_dir(void){
  1039. char *home_dir = NULL;
  1040. #if !defined(_WIN32) && !defined(WIN32) && !defined(__MACOS__)
  1041. struct passwd *pwent;
  1042. uid_t uid = getuid();
  1043. if( (pwent=getpwuid(uid)) != NULL) {
  1044. home_dir = pwent->pw_dir;
  1045. }
  1046. #endif
  1047. #ifdef __MACOS__
  1048. char home_path[_MAX_PATH+1];
  1049. home_dir = getcwd(home_path, _MAX_PATH);
  1050. #endif
  1051. if (!home_dir) {
  1052. home_dir = getenv("HOME");
  1053. if (!home_dir) {
  1054. home_dir = getenv("HOMEPATH"); /* Windows? */
  1055. }
  1056. }
  1057. #if defined(_WIN32) || defined(WIN32)
  1058. if (!home_dir) {
  1059. home_dir = "c:";
  1060. }
  1061. #endif
  1062. if( home_dir ){
  1063. char *z = malloc( strlen(home_dir)+1 );
  1064. if( z ) strcpy(z, home_dir);
  1065. home_dir = z;
  1066. }
  1067. return home_dir;
  1068. }
  1069. /*
  1070. ** Read input from the file given by sqliterc_override. Or if that
  1071. ** parameter is NULL, take input from ~/.sqliterc
  1072. */
  1073. static void process_sqliterc(
  1074. struct callback_data *p, /* Configuration data */
  1075. const char *sqliterc_override /* Name of config file. NULL to use default */
  1076. ){
  1077. char *home_dir = NULL;
  1078. const char *sqliterc = sqliterc_override;
  1079. char *zBuf;
  1080. FILE *in = NULL;
  1081. if (sqliterc == NULL) {
  1082. home_dir = find_home_dir();
  1083. if( home_dir==0 ){
  1084. fprintf(stderr,"%s: cannot locate your home directory!\n", Argv0);
  1085. return;
  1086. }
  1087. zBuf = malloc(strlen(home_dir) + 15);
  1088. if( zBuf==0 ){
  1089. fprintf(stderr,"%s: out of memory!\n", Argv0);
  1090. exit(1);
  1091. }
  1092. sprintf(zBuf,"%s/.sqliterc",home_dir);
  1093. free(home_dir);
  1094. sqliterc = (const char*)zBuf;
  1095. }
  1096. in = fopen(sqliterc,"rb");
  1097. if( in ){
  1098. if( isatty(fileno(stdout)) ){
  1099. printf("Loading resources from %s\n",sqliterc);
  1100. }
  1101. process_input(p,in);
  1102. fclose(in);
  1103. }
  1104. return;
  1105. }
  1106. /*
  1107. ** Show available command line options
  1108. */
  1109. static const char zOptions[] =
  1110. " -init filename read/process named file\n"
  1111. " -echo print commands before execution\n"
  1112. " -[no]header turn headers on or off\n"
  1113. " -column set output mode to 'column'\n"
  1114. " -html set output mode to HTML\n"
  1115. #ifdef SQLITE_HAS_CODEC
  1116. " -key KEY encryption key\n"
  1117. #endif
  1118. " -line set output mode to 'line'\n"
  1119. " -list set output mode to 'list'\n"
  1120. " -separator 'x' set output field separator (|)\n"
  1121. " -nullvalue 'text' set text string for NULL values\n"
  1122. " -version show SQLite version\n"
  1123. " -help show this text, also show dot-commands\n"
  1124. ;
  1125. static void usage(int showDetail){
  1126. fprintf(stderr, "Usage: %s [OPTIONS] FILENAME [SQL]\n", Argv0);
  1127. if( showDetail ){
  1128. fprintf(stderr, "Options are:\n%s", zOptions);
  1129. }else{
  1130. fprintf(stderr, "Use the -help option for additional information\n");
  1131. }
  1132. exit(1);
  1133. }
  1134. /*
  1135. ** Initialize the state information in data
  1136. */
  1137. void main_init(struct callback_data *data) {
  1138. memset(data, 0, sizeof(*data));
  1139. data->mode = MODE_List;
  1140. strcpy(data->separator,"|");
  1141. data->showHeader = 0;
  1142. strcpy(mainPrompt,"sqlite> ");
  1143. strcpy(continuePrompt," ...> ");
  1144. }
  1145. int main(int argc, char **argv){
  1146. char *zErrMsg = 0;
  1147. struct callback_data data;
  1148. const char *zInitFile = 0;
  1149. char *zFirstCmd = 0;
  1150. int i;
  1151. extern int sqliteOsFileExists(const char*);
  1152. sqlite_temp_directory = "/etc/svc/volatile"; /* SUNW addition */
  1153. #ifdef __MACOS__
  1154. argc = ccommand(&argv);
  1155. #endif
  1156. Argv0 = argv[0];
  1157. main_init(&data);
  1158. /* Make sure we have a valid signal handler early, before anything
  1159. ** else is done.
  1160. */
  1161. #ifdef SIGINT
  1162. signal(SIGINT, interrupt_handler);
  1163. #endif
  1164. /* Do an initial pass through the command-line argument to locate
  1165. ** the name of the database file, the name of the initialization file,
  1166. ** and the first command to execute.
  1167. */
  1168. for(i=1; i<argc-1; i++){
  1169. if( argv[i][0]!='-' ) break;
  1170. if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
  1171. i++;
  1172. }else if( strcmp(argv[i],"-init")==0 ){
  1173. i++;
  1174. zInitFile = argv[i];
  1175. }else if( strcmp(argv[i],"-key")==0 ){
  1176. i++;
  1177. data.zKey = sqlite_mprintf("%s",argv[i]);
  1178. }
  1179. }
  1180. if( i<argc ){
  1181. data.zDbFilename = argv[i++];
  1182. }else{
  1183. data.zDbFilename = ":memory:";
  1184. }
  1185. if( i<argc ){
  1186. zFirstCmd = argv[i++];
  1187. }
  1188. data.out = stdout;
  1189. /* Go ahead and open the database file if it already exists. If the
  1190. ** file does not exist, delay opening it. This prevents empty database
  1191. ** files from being created if a user mistypes the database name argument
  1192. ** to the sqlite command-line tool.
  1193. */
  1194. if( sqliteOsFileExists(data.zDbFilename) ){
  1195. open_db(&data);
  1196. }
  1197. /* Process the initialization file if there is one. If no -init option
  1198. ** is given on the command line, look for a file named ~/.sqliterc and
  1199. ** try to process it.
  1200. */
  1201. process_sqliterc(&data,zInitFile);
  1202. /* Make a second pass through the command-line argument and set
  1203. ** options. This second pass is delayed until after the initialization
  1204. ** file is processed so that the command-line arguments will override
  1205. ** settings in the initialization file.
  1206. */
  1207. for(i=1; i<argc && argv[i][0]=='-'; i++){
  1208. char *z = argv[i];
  1209. if( strcmp(z,"-init")==0 || strcmp(z,"-key")==0 ){
  1210. i++;
  1211. }else if( strcmp(z,"-html")==0 ){
  1212. data.mode = MODE_Html;
  1213. }else if( strcmp(z,"-list")==0 ){
  1214. data.mode = MODE_List;
  1215. }else if( strcmp(z,"-line")==0 ){
  1216. data.mode = MODE_Line;
  1217. }else if( strcmp(z,"-column")==0 ){
  1218. data.mode = MODE_Column;
  1219. }else if( strcmp(z,"-separator")==0 ){
  1220. i++;
  1221. sprintf(data.separator,"%.*s",(int)sizeof(data.separator)-1,argv[i]);
  1222. }else if( strcmp(z,"-nullvalue")==0 ){
  1223. i++;
  1224. sprintf(data.nullvalue,"%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
  1225. }else if( strcmp(z,"-header")==0 ){
  1226. data.showHeader = 1;
  1227. }else if( strcmp(z,"-noheader")==0 ){
  1228. data.showHeader = 0;
  1229. }else if( strcmp(z,"-echo")==0 ){
  1230. data.echoOn = 1;
  1231. }else if( strcmp(z,"-version")==0 ){
  1232. printf("%s\n", sqlite_version);
  1233. return 1;
  1234. }else if( strcmp(z,"-help")==0 ){
  1235. usage(1);
  1236. }else{
  1237. fprintf(stderr,"%s: unknown option: %s\n", Argv0, z);
  1238. fprintf(stderr,"Use -help for a list of options.\n");
  1239. return 1;
  1240. }
  1241. }
  1242. if( zFirstCmd ){
  1243. /* Run just the command that follows the database name
  1244. */
  1245. if( zFirstCmd[0]=='.' ){
  1246. do_meta_command(zFirstCmd, &data);
  1247. exit(0);
  1248. }else{
  1249. int rc;
  1250. open_db(&data);
  1251. rc = sqlite_exec(data.db, zFirstCmd, callback, &data, &zErrMsg);
  1252. if( rc!=0 && zErrMsg!=0 ){
  1253. fprintf(stderr,"SQL error: %s\n", zErrMsg);
  1254. exit(1);
  1255. }
  1256. }
  1257. }else{
  1258. /* Run commands received from standard input
  1259. */
  1260. if( isatty(fileno(stdout)) && isatty(fileno(stdin)) ){
  1261. char *zHome;
  1262. char *zHistory = 0;
  1263. printf(
  1264. "SQLite version %s\n"
  1265. "Enter \".help\" for instructions\n",
  1266. sqlite_version
  1267. );
  1268. zHome = find_home_dir();
  1269. if( zHome && (zHistory = malloc(strlen(zHome)+20))!=0 ){
  1270. sprintf(zHistory,"%s/.sqlite_history", zHome);
  1271. }
  1272. if( zHistory ) read_history(zHistory);
  1273. process_input(&data, 0);
  1274. if( zHistory ){
  1275. stifle_history(100);
  1276. write_history(zHistory);
  1277. }
  1278. }else{
  1279. process_input(&data, stdin);
  1280. }
  1281. }
  1282. set_table_name(&data, 0);
  1283. if( db ) sqlite_close(db);
  1284. return 0;
  1285. }