PageRenderTime 65ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/sqlite-src-3070900/src/shell.c

#
C | 2967 lines | 2485 code | 155 blank | 327 comment | 570 complexity | 2179c34e6fc6ceb30d31d0fb6e569d04 MD5 | raw file
  1. /*
  2. ** 2001 September 15
  3. **
  4. ** The author disclaims copyright to this source code. In place of
  5. ** a legal notice, here is a blessing:
  6. **
  7. ** May you do good and not evil.
  8. ** May you find forgiveness for yourself and forgive others.
  9. ** May you share freely, never taking more than you give.
  10. **
  11. *************************************************************************
  12. ** This file contains code to implement the "sqlite" command line
  13. ** utility for accessing SQLite databases.
  14. */
  15. #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
  16. /* This needs to come before any includes for MSVC compiler */
  17. #define _CRT_SECURE_NO_WARNINGS
  18. #endif
  19. /*
  20. ** Enable large-file support for fopen() and friends on unix.
  21. */
  22. #ifndef SQLITE_DISABLE_LFS
  23. # define _LARGE_FILE 1
  24. # ifndef _FILE_OFFSET_BITS
  25. # define _FILE_OFFSET_BITS 64
  26. # endif
  27. # define _LARGEFILE_SOURCE 1
  28. #endif
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <stdio.h>
  32. #include <assert.h>
  33. #include "sqlite3.h"
  34. #include <ctype.h>
  35. #include <stdarg.h>
  36. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
  37. # include <signal.h>
  38. # if !defined(__RTP__) && !defined(_WRS_KERNEL)
  39. # include <pwd.h>
  40. # endif
  41. # include <unistd.h>
  42. # include <sys/types.h>
  43. #endif
  44. #ifdef __OS2__
  45. # include <unistd.h>
  46. #endif
  47. #ifdef HAVE_EDITLINE
  48. # include <editline/editline.h>
  49. #endif
  50. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  51. # include <readline/readline.h>
  52. # include <readline/history.h>
  53. #endif
  54. #if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1)
  55. # define readline(p) local_getline(p,stdin)
  56. # define add_history(X)
  57. # define read_history(X)
  58. # define write_history(X)
  59. # define stifle_history(X)
  60. #endif
  61. #if defined(_WIN32) || defined(WIN32)
  62. # include <io.h>
  63. #define isatty(h) _isatty(h)
  64. #define access(f,m) _access((f),(m))
  65. #else
  66. /* Make sure isatty() has a prototype.
  67. */
  68. extern int isatty(int);
  69. #endif
  70. #if defined(_WIN32_WCE)
  71. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
  72. * thus we always assume that we have a console. That can be
  73. * overridden with the -batch command line option.
  74. */
  75. #define isatty(x) 1
  76. #endif
  77. /* True if the timer is enabled */
  78. static int enableTimer = 0;
  79. /* ctype macros that work with signed characters */
  80. #define IsSpace(X) isspace((unsigned char)X)
  81. #define IsDigit(X) isdigit((unsigned char)X)
  82. #define ToLower(X) (char)tolower((unsigned char)X)
  83. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  84. #include <sys/time.h>
  85. #include <sys/resource.h>
  86. /* Saved resource information for the beginning of an operation */
  87. static struct rusage sBegin;
  88. /*
  89. ** Begin timing an operation
  90. */
  91. static void beginTimer(void){
  92. if( enableTimer ){
  93. getrusage(RUSAGE_SELF, &sBegin);
  94. }
  95. }
  96. /* Return the difference of two time_structs in seconds */
  97. static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
  98. return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
  99. (double)(pEnd->tv_sec - pStart->tv_sec);
  100. }
  101. /*
  102. ** Print the timing results.
  103. */
  104. static void endTimer(void){
  105. if( enableTimer ){
  106. struct rusage sEnd;
  107. getrusage(RUSAGE_SELF, &sEnd);
  108. printf("CPU Time: user %f sys %f\n",
  109. timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
  110. timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
  111. }
  112. }
  113. #define BEGIN_TIMER beginTimer()
  114. #define END_TIMER endTimer()
  115. #define HAS_TIMER 1
  116. #elif (defined(_WIN32) || defined(WIN32))
  117. #include <windows.h>
  118. /* Saved resource information for the beginning of an operation */
  119. static HANDLE hProcess;
  120. static FILETIME ftKernelBegin;
  121. static FILETIME ftUserBegin;
  122. typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
  123. static GETPROCTIMES getProcessTimesAddr = NULL;
  124. /*
  125. ** Check to see if we have timer support. Return 1 if necessary
  126. ** support found (or found previously).
  127. */
  128. static int hasTimer(void){
  129. if( getProcessTimesAddr ){
  130. return 1;
  131. } else {
  132. /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions.
  133. ** See if the version we are running on has it, and if it does, save off
  134. ** a pointer to it and the current process handle.
  135. */
  136. hProcess = GetCurrentProcess();
  137. if( hProcess ){
  138. HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
  139. if( NULL != hinstLib ){
  140. getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
  141. if( NULL != getProcessTimesAddr ){
  142. return 1;
  143. }
  144. FreeLibrary(hinstLib);
  145. }
  146. }
  147. }
  148. return 0;
  149. }
  150. /*
  151. ** Begin timing an operation
  152. */
  153. static void beginTimer(void){
  154. if( enableTimer && getProcessTimesAddr ){
  155. FILETIME ftCreation, ftExit;
  156. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
  157. }
  158. }
  159. /* Return the difference of two FILETIME structs in seconds */
  160. static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
  161. sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
  162. sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
  163. return (double) ((i64End - i64Start) / 10000000.0);
  164. }
  165. /*
  166. ** Print the timing results.
  167. */
  168. static void endTimer(void){
  169. if( enableTimer && getProcessTimesAddr){
  170. FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
  171. getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
  172. printf("CPU Time: user %f sys %f\n",
  173. timeDiff(&ftUserBegin, &ftUserEnd),
  174. timeDiff(&ftKernelBegin, &ftKernelEnd));
  175. }
  176. }
  177. #define BEGIN_TIMER beginTimer()
  178. #define END_TIMER endTimer()
  179. #define HAS_TIMER hasTimer()
  180. #else
  181. #define BEGIN_TIMER
  182. #define END_TIMER
  183. #define HAS_TIMER 0
  184. #endif
  185. /*
  186. ** Used to prevent warnings about unused parameters
  187. */
  188. #define UNUSED_PARAMETER(x) (void)(x)
  189. /*
  190. ** If the following flag is set, then command execution stops
  191. ** at an error if we are not interactive.
  192. */
  193. static int bail_on_error = 0;
  194. /*
  195. ** Threat stdin as an interactive input if the following variable
  196. ** is true. Otherwise, assume stdin is connected to a file or pipe.
  197. */
  198. static int stdin_is_interactive = 1;
  199. /*
  200. ** The following is the open SQLite database. We make a pointer
  201. ** to this database a static variable so that it can be accessed
  202. ** by the SIGINT handler to interrupt database processing.
  203. */
  204. static sqlite3 *db = 0;
  205. /*
  206. ** True if an interrupt (Control-C) has been received.
  207. */
  208. static volatile int seenInterrupt = 0;
  209. /*
  210. ** This is the name of our program. It is set in main(), used
  211. ** in a number of other places, mostly for error messages.
  212. */
  213. static char *Argv0;
  214. /*
  215. ** Prompt strings. Initialized in main. Settable with
  216. ** .prompt main continue
  217. */
  218. static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
  219. static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
  220. /*
  221. ** Write I/O traces to the following stream.
  222. */
  223. #ifdef SQLITE_ENABLE_IOTRACE
  224. static FILE *iotrace = 0;
  225. #endif
  226. /*
  227. ** This routine works like printf in that its first argument is a
  228. ** format string and subsequent arguments are values to be substituted
  229. ** in place of % fields. The result of formatting this string
  230. ** is written to iotrace.
  231. */
  232. #ifdef SQLITE_ENABLE_IOTRACE
  233. static void iotracePrintf(const char *zFormat, ...){
  234. va_list ap;
  235. char *z;
  236. if( iotrace==0 ) return;
  237. va_start(ap, zFormat);
  238. z = sqlite3_vmprintf(zFormat, ap);
  239. va_end(ap);
  240. fprintf(iotrace, "%s", z);
  241. sqlite3_free(z);
  242. }
  243. #endif
  244. /*
  245. ** Determines if a string is a number of not.
  246. */
  247. static int isNumber(const char *z, int *realnum){
  248. if( *z=='-' || *z=='+' ) z++;
  249. if( !IsDigit(*z) ){
  250. return 0;
  251. }
  252. z++;
  253. if( realnum ) *realnum = 0;
  254. while( IsDigit(*z) ){ z++; }
  255. if( *z=='.' ){
  256. z++;
  257. if( !IsDigit(*z) ) return 0;
  258. while( IsDigit(*z) ){ z++; }
  259. if( realnum ) *realnum = 1;
  260. }
  261. if( *z=='e' || *z=='E' ){
  262. z++;
  263. if( *z=='+' || *z=='-' ) z++;
  264. if( !IsDigit(*z) ) return 0;
  265. while( IsDigit(*z) ){ z++; }
  266. if( realnum ) *realnum = 1;
  267. }
  268. return *z==0;
  269. }
  270. /*
  271. ** A global char* and an SQL function to access its current value
  272. ** from within an SQL statement. This program used to use the
  273. ** sqlite_exec_printf() API to substitue a string into an SQL statement.
  274. ** The correct way to do this with sqlite3 is to use the bind API, but
  275. ** since the shell is built around the callback paradigm it would be a lot
  276. ** of work. Instead just use this hack, which is quite harmless.
  277. */
  278. static const char *zShellStatic = 0;
  279. static void shellstaticFunc(
  280. sqlite3_context *context,
  281. int argc,
  282. sqlite3_value **argv
  283. ){
  284. assert( 0==argc );
  285. assert( zShellStatic );
  286. UNUSED_PARAMETER(argc);
  287. UNUSED_PARAMETER(argv);
  288. sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
  289. }
  290. /*
  291. ** This routine reads a line of text from FILE in, stores
  292. ** the text in memory obtained from malloc() and returns a pointer
  293. ** to the text. NULL is returned at end of file, or if malloc()
  294. ** fails.
  295. **
  296. ** The interface is like "readline" but no command-line editing
  297. ** is done.
  298. */
  299. static char *local_getline(char *zPrompt, FILE *in){
  300. char *zLine;
  301. int nLine;
  302. int n;
  303. if( zPrompt && *zPrompt ){
  304. printf("%s",zPrompt);
  305. fflush(stdout);
  306. }
  307. nLine = 100;
  308. zLine = malloc( nLine );
  309. if( zLine==0 ) return 0;
  310. n = 0;
  311. while( 1 ){
  312. if( n+100>nLine ){
  313. nLine = nLine*2 + 100;
  314. zLine = realloc(zLine, nLine);
  315. if( zLine==0 ) return 0;
  316. }
  317. if( fgets(&zLine[n], nLine - n, in)==0 ){
  318. if( n==0 ){
  319. free(zLine);
  320. return 0;
  321. }
  322. zLine[n] = 0;
  323. break;
  324. }
  325. while( zLine[n] ){ n++; }
  326. if( n>0 && zLine[n-1]=='\n' ){
  327. n--;
  328. if( n>0 && zLine[n-1]=='\r' ) n--;
  329. zLine[n] = 0;
  330. break;
  331. }
  332. }
  333. zLine = realloc( zLine, n+1 );
  334. return zLine;
  335. }
  336. /*
  337. ** Retrieve a single line of input text.
  338. **
  339. ** zPrior is a string of prior text retrieved. If not the empty
  340. ** string, then issue a continuation prompt.
  341. */
  342. static char *one_input_line(const char *zPrior, FILE *in){
  343. char *zPrompt;
  344. char *zResult;
  345. if( in!=0 ){
  346. return local_getline(0, in);
  347. }
  348. if( zPrior && zPrior[0] ){
  349. zPrompt = continuePrompt;
  350. }else{
  351. zPrompt = mainPrompt;
  352. }
  353. zResult = readline(zPrompt);
  354. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  355. if( zResult && *zResult ) add_history(zResult);
  356. #endif
  357. return zResult;
  358. }
  359. struct previous_mode_data {
  360. int valid; /* Is there legit data in here? */
  361. int mode;
  362. int showHeader;
  363. int colWidth[100];
  364. };
  365. /*
  366. ** An pointer to an instance of this structure is passed from
  367. ** the main program to the callback. This is used to communicate
  368. ** state and mode information.
  369. */
  370. struct callback_data {
  371. sqlite3 *db; /* The database */
  372. int echoOn; /* True to echo input commands */
  373. int statsOn; /* True to display memory stats before each finalize */
  374. int cnt; /* Number of records displayed so far */
  375. FILE *out; /* Write results here */
  376. int nErr; /* Number of errors seen */
  377. int mode; /* An output mode setting */
  378. int writableSchema; /* True if PRAGMA writable_schema=ON */
  379. int showHeader; /* True to show column names in List or Column mode */
  380. char *zDestTable; /* Name of destination table when MODE_Insert */
  381. char separator[20]; /* Separator character for MODE_List */
  382. int colWidth[100]; /* Requested width of each column when in column mode*/
  383. int actualWidth[100]; /* Actual width of each column */
  384. char nullvalue[20]; /* The text to print when a NULL comes back from
  385. ** the database */
  386. struct previous_mode_data explainPrev;
  387. /* Holds the mode information just before
  388. ** .explain ON */
  389. char outfile[FILENAME_MAX]; /* Filename for *out */
  390. const char *zDbFilename; /* name of the database file */
  391. const char *zVfs; /* Name of VFS to use */
  392. sqlite3_stmt *pStmt; /* Current statement if any. */
  393. FILE *pLog; /* Write log output here */
  394. };
  395. /*
  396. ** These are the allowed modes.
  397. */
  398. #define MODE_Line 0 /* One column per line. Blank line between records */
  399. #define MODE_Column 1 /* One record per line in neat columns */
  400. #define MODE_List 2 /* One record per line with a separator */
  401. #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
  402. #define MODE_Html 4 /* Generate an XHTML table */
  403. #define MODE_Insert 5 /* Generate SQL "insert" statements */
  404. #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
  405. #define MODE_Csv 7 /* Quote strings, numbers are plain */
  406. #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
  407. static const char *modeDescr[] = {
  408. "line",
  409. "column",
  410. "list",
  411. "semi",
  412. "html",
  413. "insert",
  414. "tcl",
  415. "csv",
  416. "explain",
  417. };
  418. /*
  419. ** Number of elements in an array
  420. */
  421. #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
  422. /*
  423. ** Compute a string length that is limited to what can be stored in
  424. ** lower 30 bits of a 32-bit signed integer.
  425. */
  426. static int strlen30(const char *z){
  427. const char *z2 = z;
  428. while( *z2 ){ z2++; }
  429. return 0x3fffffff & (int)(z2 - z);
  430. }
  431. /*
  432. ** A callback for the sqlite3_log() interface.
  433. */
  434. static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  435. struct callback_data *p = (struct callback_data*)pArg;
  436. if( p->pLog==0 ) return;
  437. fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  438. fflush(p->pLog);
  439. }
  440. /*
  441. ** Output the given string as a hex-encoded blob (eg. X'1234' )
  442. */
  443. static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  444. int i;
  445. char *zBlob = (char *)pBlob;
  446. fprintf(out,"X'");
  447. for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]); }
  448. fprintf(out,"'");
  449. }
  450. /*
  451. ** Output the given string as a quoted string using SQL quoting conventions.
  452. */
  453. static void output_quoted_string(FILE *out, const char *z){
  454. int i;
  455. int nSingle = 0;
  456. for(i=0; z[i]; i++){
  457. if( z[i]=='\'' ) nSingle++;
  458. }
  459. if( nSingle==0 ){
  460. fprintf(out,"'%s'",z);
  461. }else{
  462. fprintf(out,"'");
  463. while( *z ){
  464. for(i=0; z[i] && z[i]!='\''; i++){}
  465. if( i==0 ){
  466. fprintf(out,"''");
  467. z++;
  468. }else if( z[i]=='\'' ){
  469. fprintf(out,"%.*s''",i,z);
  470. z += i+1;
  471. }else{
  472. fprintf(out,"%s",z);
  473. break;
  474. }
  475. }
  476. fprintf(out,"'");
  477. }
  478. }
  479. /*
  480. ** Output the given string as a quoted according to C or TCL quoting rules.
  481. */
  482. static void output_c_string(FILE *out, const char *z){
  483. unsigned int c;
  484. fputc('"', out);
  485. while( (c = *(z++))!=0 ){
  486. if( c=='\\' ){
  487. fputc(c, out);
  488. fputc(c, out);
  489. }else if( c=='\t' ){
  490. fputc('\\', out);
  491. fputc('t', out);
  492. }else if( c=='\n' ){
  493. fputc('\\', out);
  494. fputc('n', out);
  495. }else if( c=='\r' ){
  496. fputc('\\', out);
  497. fputc('r', out);
  498. }else if( !isprint(c) ){
  499. fprintf(out, "\\%03o", c&0xff);
  500. }else{
  501. fputc(c, out);
  502. }
  503. }
  504. fputc('"', out);
  505. }
  506. /*
  507. ** Output the given string with characters that are special to
  508. ** HTML escaped.
  509. */
  510. static void output_html_string(FILE *out, const char *z){
  511. int i;
  512. while( *z ){
  513. for(i=0; z[i]
  514. && z[i]!='<'
  515. && z[i]!='&'
  516. && z[i]!='>'
  517. && z[i]!='\"'
  518. && z[i]!='\'';
  519. i++){}
  520. if( i>0 ){
  521. fprintf(out,"%.*s",i,z);
  522. }
  523. if( z[i]=='<' ){
  524. fprintf(out,"&lt;");
  525. }else if( z[i]=='&' ){
  526. fprintf(out,"&amp;");
  527. }else if( z[i]=='>' ){
  528. fprintf(out,"&gt;");
  529. }else if( z[i]=='\"' ){
  530. fprintf(out,"&quot;");
  531. }else if( z[i]=='\'' ){
  532. fprintf(out,"&#39;");
  533. }else{
  534. break;
  535. }
  536. z += i + 1;
  537. }
  538. }
  539. /*
  540. ** If a field contains any character identified by a 1 in the following
  541. ** array, then the string must be quoted for CSV.
  542. */
  543. static const char needCsvQuote[] = {
  544. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  545. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  546. 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
  547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
  552. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  553. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  554. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  555. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  556. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  557. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  558. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  559. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  560. };
  561. /*
  562. ** Output a single term of CSV. Actually, p->separator is used for
  563. ** the separator, which may or may not be a comma. p->nullvalue is
  564. ** the null value. Strings are quoted using ANSI-C rules. Numbers
  565. ** appear outside of quotes.
  566. */
  567. static void output_csv(struct callback_data *p, const char *z, int bSep){
  568. FILE *out = p->out;
  569. if( z==0 ){
  570. fprintf(out,"%s",p->nullvalue);
  571. }else{
  572. int i;
  573. int nSep = strlen30(p->separator);
  574. for(i=0; z[i]; i++){
  575. if( needCsvQuote[((unsigned char*)z)[i]]
  576. || (z[i]==p->separator[0] &&
  577. (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){
  578. i = 0;
  579. break;
  580. }
  581. }
  582. if( i==0 ){
  583. putc('"', out);
  584. for(i=0; z[i]; i++){
  585. if( z[i]=='"' ) putc('"', out);
  586. putc(z[i], out);
  587. }
  588. putc('"', out);
  589. }else{
  590. fprintf(out, "%s", z);
  591. }
  592. }
  593. if( bSep ){
  594. fprintf(p->out, "%s", p->separator);
  595. }
  596. }
  597. #ifdef SIGINT
  598. /*
  599. ** This routine runs when the user presses Ctrl-C
  600. */
  601. static void interrupt_handler(int NotUsed){
  602. UNUSED_PARAMETER(NotUsed);
  603. seenInterrupt = 1;
  604. if( db ) sqlite3_interrupt(db);
  605. }
  606. #endif
  607. /*
  608. ** This is the callback routine that the shell
  609. ** invokes for each row of a query result.
  610. */
  611. static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){
  612. int i;
  613. struct callback_data *p = (struct callback_data*)pArg;
  614. switch( p->mode ){
  615. case MODE_Line: {
  616. int w = 5;
  617. if( azArg==0 ) break;
  618. for(i=0; i<nArg; i++){
  619. int len = strlen30(azCol[i] ? azCol[i] : "");
  620. if( len>w ) w = len;
  621. }
  622. if( p->cnt++>0 ) fprintf(p->out,"\n");
  623. for(i=0; i<nArg; i++){
  624. fprintf(p->out,"%*s = %s\n", w, azCol[i],
  625. azArg[i] ? azArg[i] : p->nullvalue);
  626. }
  627. break;
  628. }
  629. case MODE_Explain:
  630. case MODE_Column: {
  631. if( p->cnt++==0 ){
  632. for(i=0; i<nArg; i++){
  633. int w, n;
  634. if( i<ArraySize(p->colWidth) ){
  635. w = p->colWidth[i];
  636. }else{
  637. w = 0;
  638. }
  639. if( w<=0 ){
  640. w = strlen30(azCol[i] ? azCol[i] : "");
  641. if( w<10 ) w = 10;
  642. n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue);
  643. if( w<n ) w = n;
  644. }
  645. if( i<ArraySize(p->actualWidth) ){
  646. p->actualWidth[i] = w;
  647. }
  648. if( p->showHeader ){
  649. fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " ");
  650. }
  651. }
  652. if( p->showHeader ){
  653. for(i=0; i<nArg; i++){
  654. int w;
  655. if( i<ArraySize(p->actualWidth) ){
  656. w = p->actualWidth[i];
  657. }else{
  658. w = 10;
  659. }
  660. fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------"
  661. "----------------------------------------------------------",
  662. i==nArg-1 ? "\n": " ");
  663. }
  664. }
  665. }
  666. if( azArg==0 ) break;
  667. for(i=0; i<nArg; i++){
  668. int w;
  669. if( i<ArraySize(p->actualWidth) ){
  670. w = p->actualWidth[i];
  671. }else{
  672. w = 10;
  673. }
  674. if( p->mode==MODE_Explain && azArg[i] &&
  675. strlen30(azArg[i])>w ){
  676. w = strlen30(azArg[i]);
  677. }
  678. fprintf(p->out,"%-*.*s%s",w,w,
  679. azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
  680. }
  681. break;
  682. }
  683. case MODE_Semi:
  684. case MODE_List: {
  685. if( p->cnt++==0 && p->showHeader ){
  686. for(i=0; i<nArg; i++){
  687. fprintf(p->out,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator);
  688. }
  689. }
  690. if( azArg==0 ) break;
  691. for(i=0; i<nArg; i++){
  692. char *z = azArg[i];
  693. if( z==0 ) z = p->nullvalue;
  694. fprintf(p->out, "%s", z);
  695. if( i<nArg-1 ){
  696. fprintf(p->out, "%s", p->separator);
  697. }else if( p->mode==MODE_Semi ){
  698. fprintf(p->out, ";\n");
  699. }else{
  700. fprintf(p->out, "\n");
  701. }
  702. }
  703. break;
  704. }
  705. case MODE_Html: {
  706. if( p->cnt++==0 && p->showHeader ){
  707. fprintf(p->out,"<TR>");
  708. for(i=0; i<nArg; i++){
  709. fprintf(p->out,"<TH>");
  710. output_html_string(p->out, azCol[i]);
  711. fprintf(p->out,"</TH>\n");
  712. }
  713. fprintf(p->out,"</TR>\n");
  714. }
  715. if( azArg==0 ) break;
  716. fprintf(p->out,"<TR>");
  717. for(i=0; i<nArg; i++){
  718. fprintf(p->out,"<TD>");
  719. output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  720. fprintf(p->out,"</TD>\n");
  721. }
  722. fprintf(p->out,"</TR>\n");
  723. break;
  724. }
  725. case MODE_Tcl: {
  726. if( p->cnt++==0 && p->showHeader ){
  727. for(i=0; i<nArg; i++){
  728. output_c_string(p->out,azCol[i] ? azCol[i] : "");
  729. fprintf(p->out, "%s", p->separator);
  730. }
  731. fprintf(p->out,"\n");
  732. }
  733. if( azArg==0 ) break;
  734. for(i=0; i<nArg; i++){
  735. output_c_string(p->out, azArg[i] ? azArg[i] : p->nullvalue);
  736. fprintf(p->out, "%s", p->separator);
  737. }
  738. fprintf(p->out,"\n");
  739. break;
  740. }
  741. case MODE_Csv: {
  742. if( p->cnt++==0 && p->showHeader ){
  743. for(i=0; i<nArg; i++){
  744. output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  745. }
  746. fprintf(p->out,"\n");
  747. }
  748. if( azArg==0 ) break;
  749. for(i=0; i<nArg; i++){
  750. output_csv(p, azArg[i], i<nArg-1);
  751. }
  752. fprintf(p->out,"\n");
  753. break;
  754. }
  755. case MODE_Insert: {
  756. p->cnt++;
  757. if( azArg==0 ) break;
  758. fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
  759. for(i=0; i<nArg; i++){
  760. char *zSep = i>0 ? ",": "";
  761. if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  762. fprintf(p->out,"%sNULL",zSep);
  763. }else if( aiType && aiType[i]==SQLITE_TEXT ){
  764. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  765. output_quoted_string(p->out, azArg[i]);
  766. }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
  767. fprintf(p->out,"%s%s",zSep, azArg[i]);
  768. }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  769. const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  770. int nBlob = sqlite3_column_bytes(p->pStmt, i);
  771. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  772. output_hex_blob(p->out, pBlob, nBlob);
  773. }else if( isNumber(azArg[i], 0) ){
  774. fprintf(p->out,"%s%s",zSep, azArg[i]);
  775. }else{
  776. if( zSep[0] ) fprintf(p->out,"%s",zSep);
  777. output_quoted_string(p->out, azArg[i]);
  778. }
  779. }
  780. fprintf(p->out,");\n");
  781. break;
  782. }
  783. }
  784. return 0;
  785. }
  786. /*
  787. ** This is the callback routine that the SQLite library
  788. ** invokes for each row of a query result.
  789. */
  790. static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  791. /* since we don't have type info, call the shell_callback with a NULL value */
  792. return shell_callback(pArg, nArg, azArg, azCol, NULL);
  793. }
  794. /*
  795. ** Set the destination table field of the callback_data structure to
  796. ** the name of the table given. Escape any quote characters in the
  797. ** table name.
  798. */
  799. static void set_table_name(struct callback_data *p, const char *zName){
  800. int i, n;
  801. int needQuote;
  802. char *z;
  803. if( p->zDestTable ){
  804. free(p->zDestTable);
  805. p->zDestTable = 0;
  806. }
  807. if( zName==0 ) return;
  808. needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  809. for(i=n=0; zName[i]; i++, n++){
  810. if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  811. needQuote = 1;
  812. if( zName[i]=='\'' ) n++;
  813. }
  814. }
  815. if( needQuote ) n += 2;
  816. z = p->zDestTable = malloc( n+1 );
  817. if( z==0 ){
  818. fprintf(stderr,"Error: out of memory\n");
  819. exit(1);
  820. }
  821. n = 0;
  822. if( needQuote ) z[n++] = '\'';
  823. for(i=0; zName[i]; i++){
  824. z[n++] = zName[i];
  825. if( zName[i]=='\'' ) z[n++] = '\'';
  826. }
  827. if( needQuote ) z[n++] = '\'';
  828. z[n] = 0;
  829. }
  830. /* zIn is either a pointer to a NULL-terminated string in memory obtained
  831. ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  832. ** added to zIn, and the result returned in memory obtained from malloc().
  833. ** zIn, if it was not NULL, is freed.
  834. **
  835. ** If the third argument, quote, is not '\0', then it is used as a
  836. ** quote character for zAppend.
  837. */
  838. static char *appendText(char *zIn, char const *zAppend, char quote){
  839. int len;
  840. int i;
  841. int nAppend = strlen30(zAppend);
  842. int nIn = (zIn?strlen30(zIn):0);
  843. len = nAppend+nIn+1;
  844. if( quote ){
  845. len += 2;
  846. for(i=0; i<nAppend; i++){
  847. if( zAppend[i]==quote ) len++;
  848. }
  849. }
  850. zIn = (char *)realloc(zIn, len);
  851. if( !zIn ){
  852. return 0;
  853. }
  854. if( quote ){
  855. char *zCsr = &zIn[nIn];
  856. *zCsr++ = quote;
  857. for(i=0; i<nAppend; i++){
  858. *zCsr++ = zAppend[i];
  859. if( zAppend[i]==quote ) *zCsr++ = quote;
  860. }
  861. *zCsr++ = quote;
  862. *zCsr++ = '\0';
  863. assert( (zCsr-zIn)==len );
  864. }else{
  865. memcpy(&zIn[nIn], zAppend, nAppend);
  866. zIn[len-1] = '\0';
  867. }
  868. return zIn;
  869. }
  870. /*
  871. ** Execute a query statement that has a single result column. Print
  872. ** that result column on a line by itself with a semicolon terminator.
  873. **
  874. ** This is used, for example, to show the schema of the database by
  875. ** querying the SQLITE_MASTER table.
  876. */
  877. static int run_table_dump_query(
  878. struct callback_data *p, /* Query context */
  879. const char *zSelect, /* SELECT statement to extract content */
  880. const char *zFirstRow /* Print before first row, if not NULL */
  881. ){
  882. sqlite3_stmt *pSelect;
  883. int rc;
  884. rc = sqlite3_prepare(p->db, zSelect, -1, &pSelect, 0);
  885. if( rc!=SQLITE_OK || !pSelect ){
  886. fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  887. p->nErr++;
  888. return rc;
  889. }
  890. rc = sqlite3_step(pSelect);
  891. while( rc==SQLITE_ROW ){
  892. if( zFirstRow ){
  893. fprintf(p->out, "%s", zFirstRow);
  894. zFirstRow = 0;
  895. }
  896. fprintf(p->out, "%s;\n", sqlite3_column_text(pSelect, 0));
  897. rc = sqlite3_step(pSelect);
  898. }
  899. rc = sqlite3_finalize(pSelect);
  900. if( rc!=SQLITE_OK ){
  901. fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  902. p->nErr++;
  903. }
  904. return rc;
  905. }
  906. /*
  907. ** Allocate space and save off current error string.
  908. */
  909. static char *save_err_msg(
  910. sqlite3 *db /* Database to query */
  911. ){
  912. int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  913. char *zErrMsg = sqlite3_malloc(nErrMsg);
  914. if( zErrMsg ){
  915. memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  916. }
  917. return zErrMsg;
  918. }
  919. /*
  920. ** Display memory stats.
  921. */
  922. static int display_stats(
  923. sqlite3 *db, /* Database to query */
  924. struct callback_data *pArg, /* Pointer to struct callback_data */
  925. int bReset /* True to reset the stats */
  926. ){
  927. int iCur;
  928. int iHiwtr;
  929. if( pArg && pArg->out ){
  930. iHiwtr = iCur = -1;
  931. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  932. fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr);
  933. iHiwtr = iCur = -1;
  934. sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  935. fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr);
  936. /*
  937. ** Not currently used by the CLI.
  938. ** iHiwtr = iCur = -1;
  939. ** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  940. ** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr);
  941. */
  942. iHiwtr = iCur = -1;
  943. sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  944. fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
  945. /*
  946. ** Not currently used by the CLI.
  947. ** iHiwtr = iCur = -1;
  948. ** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  949. ** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr);
  950. */
  951. iHiwtr = iCur = -1;
  952. sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  953. fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr);
  954. iHiwtr = iCur = -1;
  955. sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  956. fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr);
  957. iHiwtr = iCur = -1;
  958. sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  959. fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr);
  960. iHiwtr = iCur = -1;
  961. sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  962. fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr);
  963. #ifdef YYTRACKMAXSTACKDEPTH
  964. iHiwtr = iCur = -1;
  965. sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  966. fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr);
  967. #endif
  968. }
  969. if( pArg && pArg->out && db ){
  970. iHiwtr = iCur = -1;
  971. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset);
  972. fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr);
  973. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset);
  974. fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr);
  975. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset);
  976. fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr);
  977. sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset);
  978. fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr);
  979. iHiwtr = iCur = -1;
  980. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  981. fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1;
  982. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  983. fprintf(pArg->out, "Page cache hits: %d\n", iCur);
  984. iHiwtr = iCur = -1;
  985. sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  986. fprintf(pArg->out, "Page cache misses: %d\n", iCur);
  987. iHiwtr = iCur = -1;
  988. sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  989. fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur);
  990. iHiwtr = iCur = -1;
  991. sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  992. fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur);
  993. }
  994. if( pArg && pArg->out && db && pArg->pStmt ){
  995. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
  996. fprintf(pArg->out, "Fullscan Steps: %d\n", iCur);
  997. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  998. fprintf(pArg->out, "Sort Operations: %d\n", iCur);
  999. iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
  1000. fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur);
  1001. }
  1002. return 0;
  1003. }
  1004. /*
  1005. ** Execute a statement or set of statements. Print
  1006. ** any result rows/columns depending on the current mode
  1007. ** set via the supplied callback.
  1008. **
  1009. ** This is very similar to SQLite's built-in sqlite3_exec()
  1010. ** function except it takes a slightly different callback
  1011. ** and callback data argument.
  1012. */
  1013. static int shell_exec(
  1014. sqlite3 *db, /* An open database */
  1015. const char *zSql, /* SQL to be evaluated */
  1016. int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
  1017. /* (not the same as sqlite3_exec) */
  1018. struct callback_data *pArg, /* Pointer to struct callback_data */
  1019. char **pzErrMsg /* Error msg written here */
  1020. ){
  1021. sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
  1022. int rc = SQLITE_OK; /* Return Code */
  1023. int rc2;
  1024. const char *zLeftover; /* Tail of unprocessed SQL */
  1025. if( pzErrMsg ){
  1026. *pzErrMsg = NULL;
  1027. }
  1028. while( zSql[0] && (SQLITE_OK == rc) ){
  1029. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1030. if( SQLITE_OK != rc ){
  1031. if( pzErrMsg ){
  1032. *pzErrMsg = save_err_msg(db);
  1033. }
  1034. }else{
  1035. if( !pStmt ){
  1036. /* this happens for a comment or white-space */
  1037. zSql = zLeftover;
  1038. while( IsSpace(zSql[0]) ) zSql++;
  1039. continue;
  1040. }
  1041. /* save off the prepared statment handle and reset row count */
  1042. if( pArg ){
  1043. pArg->pStmt = pStmt;
  1044. pArg->cnt = 0;
  1045. }
  1046. /* echo the sql statement if echo on */
  1047. if( pArg && pArg->echoOn ){
  1048. const char *zStmtSql = sqlite3_sql(pStmt);
  1049. fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1050. }
  1051. /* perform the first step. this will tell us if we
  1052. ** have a result set or not and how wide it is.
  1053. */
  1054. rc = sqlite3_step(pStmt);
  1055. /* if we have a result set... */
  1056. if( SQLITE_ROW == rc ){
  1057. /* if we have a callback... */
  1058. if( xCallback ){
  1059. /* allocate space for col name ptr, value ptr, and type */
  1060. int nCol = sqlite3_column_count(pStmt);
  1061. void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
  1062. if( !pData ){
  1063. rc = SQLITE_NOMEM;
  1064. }else{
  1065. char **azCols = (char **)pData; /* Names of result columns */
  1066. char **azVals = &azCols[nCol]; /* Results */
  1067. int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1068. int i;
  1069. assert(sizeof(int) <= sizeof(char *));
  1070. /* save off ptrs to column names */
  1071. for(i=0; i<nCol; i++){
  1072. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1073. }
  1074. do{
  1075. /* extract the data and data types */
  1076. for(i=0; i<nCol; i++){
  1077. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  1078. aiTypes[i] = sqlite3_column_type(pStmt, i);
  1079. if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1080. rc = SQLITE_NOMEM;
  1081. break; /* from for */
  1082. }
  1083. } /* end for */
  1084. /* if data and types extracted successfully... */
  1085. if( SQLITE_ROW == rc ){
  1086. /* call the supplied callback with the result row data */
  1087. if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1088. rc = SQLITE_ABORT;
  1089. }else{
  1090. rc = sqlite3_step(pStmt);
  1091. }
  1092. }
  1093. } while( SQLITE_ROW == rc );
  1094. sqlite3_free(pData);
  1095. }
  1096. }else{
  1097. do{
  1098. rc = sqlite3_step(pStmt);
  1099. } while( rc == SQLITE_ROW );
  1100. }
  1101. }
  1102. /* print usage stats if stats on */
  1103. if( pArg && pArg->statsOn ){
  1104. display_stats(db, pArg, 0);
  1105. }
  1106. /* Finalize the statement just executed. If this fails, save a
  1107. ** copy of the error message. Otherwise, set zSql to point to the
  1108. ** next statement to execute. */
  1109. rc2 = sqlite3_finalize(pStmt);
  1110. if( rc!=SQLITE_NOMEM ) rc = rc2;
  1111. if( rc==SQLITE_OK ){
  1112. zSql = zLeftover;
  1113. while( IsSpace(zSql[0]) ) zSql++;
  1114. }else if( pzErrMsg ){
  1115. *pzErrMsg = save_err_msg(db);
  1116. }
  1117. /* clear saved stmt handle */
  1118. if( pArg ){
  1119. pArg->pStmt = NULL;
  1120. }
  1121. }
  1122. } /* end while */
  1123. return rc;
  1124. }
  1125. /*
  1126. ** This is a different callback routine used for dumping the database.
  1127. ** Each row received by this callback consists of a table name,
  1128. ** the table type ("index" or "table") and SQL to create the table.
  1129. ** This routine should print text sufficient to recreate the table.
  1130. */
  1131. static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1132. int rc;
  1133. const char *zTable;
  1134. const char *zType;
  1135. const char *zSql;
  1136. const char *zPrepStmt = 0;
  1137. struct callback_data *p = (struct callback_data *)pArg;
  1138. UNUSED_PARAMETER(azCol);
  1139. if( nArg!=3 ) return 1;
  1140. zTable = azArg[0];
  1141. zType = azArg[1];
  1142. zSql = azArg[2];
  1143. if( strcmp(zTable, "sqlite_sequence")==0 ){
  1144. zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  1145. }else if( strcmp(zTable, "sqlite_stat1")==0 ){
  1146. fprintf(p->out, "ANALYZE sqlite_master;\n");
  1147. }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  1148. return 0;
  1149. }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  1150. char *zIns;
  1151. if( !p->writableSchema ){
  1152. fprintf(p->out, "PRAGMA writable_schema=ON;\n");
  1153. p->writableSchema = 1;
  1154. }
  1155. zIns = sqlite3_mprintf(
  1156. "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  1157. "VALUES('table','%q','%q',0,'%q');",
  1158. zTable, zTable, zSql);
  1159. fprintf(p->out, "%s\n", zIns);
  1160. sqlite3_free(zIns);
  1161. return 0;
  1162. }else{
  1163. fprintf(p->out, "%s;\n", zSql);
  1164. }
  1165. if( strcmp(zType, "table")==0 ){
  1166. sqlite3_stmt *pTableInfo = 0;
  1167. char *zSelect = 0;
  1168. char *zTableInfo = 0;
  1169. char *zTmp = 0;
  1170. int nRow = 0;
  1171. zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1172. zTableInfo = appendText(zTableInfo, zTable, '"');
  1173. zTableInfo = appendText(zTableInfo, ");", 0);
  1174. rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
  1175. free(zTableInfo);
  1176. if( rc!=SQLITE_OK || !pTableInfo ){
  1177. return 1;
  1178. }
  1179. zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1180. zTmp = appendText(zTmp, zTable, '"');
  1181. if( zTmp ){
  1182. zSelect = appendText(zSelect, zTmp, '\'');
  1183. }
  1184. zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  1185. rc = sqlite3_step(pTableInfo);
  1186. while( rc==SQLITE_ROW ){
  1187. const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  1188. zSelect = appendText(zSelect, "quote(", 0);
  1189. zSelect = appendText(zSelect, zText, '"');
  1190. rc = sqlite3_step(pTableInfo);
  1191. if( rc==SQLITE_ROW ){
  1192. zSelect = appendText(zSelect, ") || ',' || ", 0);
  1193. }else{
  1194. zSelect = appendText(zSelect, ") ", 0);
  1195. }
  1196. nRow++;
  1197. }
  1198. rc = sqlite3_finalize(pTableInfo);
  1199. if( rc!=SQLITE_OK || nRow==0 ){
  1200. free(zSelect);
  1201. return 1;
  1202. }
  1203. zSelect = appendText(zSelect, "|| ')' FROM ", 0);
  1204. zSelect = appendText(zSelect, zTable, '"');
  1205. rc = run_table_dump_query(p, zSelect, zPrepStmt);
  1206. if( rc==SQLITE_CORRUPT ){
  1207. zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  1208. run_table_dump_query(p, zSelect, 0);
  1209. }
  1210. if( zSelect ) free(zSelect);
  1211. }
  1212. return 0;
  1213. }
  1214. /*
  1215. ** Run zQuery. Use dump_callback() as the callback routine so that
  1216. ** the contents of the query are output as SQL statements.
  1217. **
  1218. ** If we get a SQLITE_CORRUPT error, rerun the query after appending
  1219. ** "ORDER BY rowid DESC" to the end.
  1220. */
  1221. static int run_schema_dump_query(
  1222. struct callback_data *p,
  1223. const char *zQuery
  1224. ){
  1225. int rc;
  1226. char *zErr = 0;
  1227. rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  1228. if( rc==SQLITE_CORRUPT ){
  1229. char *zQ2;
  1230. int len = strlen30(zQuery);
  1231. fprintf(p->out, "/****** CORRUPTION ERROR *******/\n");
  1232. if( zErr ){
  1233. fprintf(p->out, "/****** %s ******/\n", zErr);
  1234. sqlite3_free(zErr);
  1235. zErr = 0;
  1236. }
  1237. zQ2 = malloc( len+100 );
  1238. if( zQ2==0 ) return rc;
  1239. sqlite3_snprintf(sizeof(zQ2), zQ2, "%s ORDER BY rowid DESC", zQuery);
  1240. rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  1241. if( rc ){
  1242. fprintf(p->out, "/****** ERROR: %s ******/\n", zErr);
  1243. }else{
  1244. rc = SQLITE_CORRUPT;
  1245. }
  1246. sqlite3_free(zErr);
  1247. free(zQ2);
  1248. }
  1249. return rc;
  1250. }
  1251. /*
  1252. ** Text of a help message
  1253. */
  1254. static char zHelp[] =
  1255. ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
  1256. ".bail ON|OFF Stop after hitting an error. Default OFF\n"
  1257. ".databases List names and files of attached databases\n"
  1258. ".dump ?TABLE? ... Dump the database in an SQL text format\n"
  1259. " If TABLE specified, only dump tables matching\n"
  1260. " LIKE pattern TABLE.\n"
  1261. ".echo ON|OFF Turn command echo on or off\n"
  1262. ".exit Exit this program\n"
  1263. ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n"
  1264. " With no args, it turns EXPLAIN on.\n"
  1265. ".header(s) ON|OFF Turn display of headers on or off\n"
  1266. ".help Show this message\n"
  1267. ".import FILE TABLE Import data from FILE into TABLE\n"
  1268. ".indices ?TABLE? Show names of all indices\n"
  1269. " If TABLE specified, only show indices for tables\n"
  1270. " matching LIKE pattern TABLE.\n"
  1271. #ifdef SQLITE_ENABLE_IOTRACE
  1272. ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
  1273. #endif
  1274. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1275. ".load FILE ?ENTRY? Load an extension library\n"
  1276. #endif
  1277. ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
  1278. ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
  1279. " csv Comma-separated values\n"
  1280. " column Left-aligned columns. (See .width)\n"
  1281. " html HTML <table> code\n"
  1282. " insert SQL insert statements for TABLE\n"
  1283. " line One value per line\n"
  1284. " list Values delimited by .separator string\n"
  1285. " tabs Tab-separated values\n"
  1286. " tcl TCL list elements\n"
  1287. ".nullvalue STRING Print STRING in place of NULL values\n"
  1288. ".output FILENAME Send output to FILENAME\n"
  1289. ".output stdout Send output to the screen\n"
  1290. ".prompt MAIN CONTINUE Replace the standard prompts\n"
  1291. ".quit Exit this program\n"
  1292. ".read FILENAME Execute SQL in FILENAME\n"
  1293. ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
  1294. ".schema ?TABLE? Show the CREATE statements\n"
  1295. " If TABLE specified, only show tables matching\n"
  1296. " LIKE pattern TABLE.\n"
  1297. ".separator STRING Change separator used by output mode and .import\n"
  1298. ".show Show the current values for various settings\n"
  1299. ".stats ON|OFF Turn stats on or off\n"
  1300. ".tables ?TABLE? List names of tables\n"
  1301. " If TABLE specified, only list tables matching\n"
  1302. " LIKE pattern TABLE.\n"
  1303. ".timeout MS Try opening locked tables for MS milliseconds\n"
  1304. ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
  1305. ;
  1306. static char zTimerHelp[] =
  1307. ".timer ON|OFF Turn the CPU timer measurement on or off\n"
  1308. ;
  1309. /* Forward reference */
  1310. static int process_input(struct callback_data *p, FILE *in);
  1311. /*
  1312. ** Make sure the database is open. If it is not, then open it. If
  1313. ** the database fails to open, print an error message and exit.
  1314. */
  1315. static void open_db(struct callback_data *p){
  1316. if( p->db==0 ){
  1317. sqlite3_open(p->zDbFilename, &p->db);
  1318. db = p->db;
  1319. if( db && sqlite3_errcode(db)==SQLITE_OK ){
  1320. sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
  1321. shellstaticFunc, 0, 0);
  1322. }
  1323. if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
  1324. fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
  1325. p->zDbFilename, sqlite3_errmsg(db));
  1326. exit(1);
  1327. }
  1328. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1329. sqlite3_enable_load_extension(p->db, 1);
  1330. #endif
  1331. }
  1332. }
  1333. /*
  1334. ** Do C-language style dequoting.
  1335. **
  1336. ** \t -> tab
  1337. ** \n -> newline
  1338. ** \r -> carriage return
  1339. ** \NNN -> ascii character NNN in octal
  1340. ** \\ -> backslash
  1341. */
  1342. static void resolve_backslashes(char *z){
  1343. int i, j;
  1344. char c;
  1345. for(i=j=0; (c = z[i])!=0; i++, j++){
  1346. if( c=='\\' ){
  1347. c = z[++i];
  1348. if( c=='n' ){
  1349. c = '\n';
  1350. }else if( c=='t' ){
  1351. c = '\t';
  1352. }else if( c=='r' ){
  1353. c = '\r';
  1354. }else if( c>='0' && c<='7' ){
  1355. c -= '0';
  1356. if( z[i+1]>='0' && z[i+1]<='7' ){
  1357. i++;
  1358. c = (c<<3) + z[i] - '0';
  1359. if( z[i+1]>='0' && z[i+1]<='7' ){
  1360. i++;
  1361. c = (c<<3) + z[i] - '0';
  1362. }
  1363. }
  1364. }
  1365. }
  1366. z[j] = c;
  1367. }
  1368. z[j] = 0;
  1369. }
  1370. /*
  1371. ** Interpret zArg as a boolean value. Return either 0 or 1.
  1372. */
  1373. static int booleanValue(char *zArg){
  1374. int val = atoi(zArg);
  1375. int j;
  1376. for(j=0; zArg[j]; j++){
  1377. zArg[j] = ToLower(zArg[j]);
  1378. }
  1379. if( strcmp(zArg,"on")==0 ){
  1380. val = 1;
  1381. }else if( strcmp(zArg,"yes")==0 ){
  1382. val = 1;
  1383. }
  1384. return val;
  1385. }
  1386. /*
  1387. ** If an input line begins with "." then invoke this routine to
  1388. ** process that line.
  1389. **
  1390. ** Return 1 on error, 2 to exit, and 0 otherwise.
  1391. */
  1392. static int do_meta_command(char *zLine, struct callback_data *p){
  1393. int i = 1;
  1394. int nArg = 0;
  1395. int n, c;
  1396. int rc = 0;
  1397. char *azArg[50];
  1398. /* Parse the input line into tokens.
  1399. */
  1400. while( zLine[i] && nArg<ArraySize(azArg) ){
  1401. while( IsSpace(zLine[i]) ){ i++; }
  1402. if( zLine[i]==0 ) break;
  1403. if( zLine[i]=='\'' || zLine[i]=='"' ){
  1404. int delim = zLine[i++];
  1405. azArg[nArg++] = &zLine[i];
  1406. while( zLine[i] && zLine[i]!=delim ){ i++; }
  1407. if( zLine[i]==delim ){
  1408. zLine[i++] = 0;
  1409. }
  1410. if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  1411. }else{
  1412. azArg[nArg++] = &zLine[i];
  1413. while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
  1414. if( zLine[i] ) zLine[i++] = 0;
  1415. resolve_backslashes(azArg[nArg-1]);
  1416. }
  1417. }
  1418. /* Process the input line.
  1419. */
  1420. if( nArg==0 ) return 0; /* no tokens, no error */
  1421. n = strlen30(azArg[0]);
  1422. c = azArg[0][0];
  1423. if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){
  1424. const char *zDestFile;
  1425. const char *zDb;
  1426. sqlite3 *pDest;
  1427. sqlite3_backup *pBackup;
  1428. if( nArg==2 ){
  1429. zDestFile = azArg[1];
  1430. zDb = "main";
  1431. }else{
  1432. zDestFile = azArg[2];
  1433. zDb = azArg[1];
  1434. }
  1435. rc = sqlite3_open(zDestFile, &pDest);
  1436. if( rc!=SQLITE_OK ){
  1437. fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  1438. sqlite3_close(pDest);
  1439. return 1;
  1440. }
  1441. open_db(p);
  1442. pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  1443. if( pBackup==0 ){
  1444. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1445. sqlite3_close(pDest);
  1446. return 1;
  1447. }
  1448. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  1449. sqlite3_backup_finish(pBackup);
  1450. if( rc==SQLITE_DONE ){
  1451. rc = 0;
  1452. }else{
  1453. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  1454. rc = 1;
  1455. }
  1456. sqlite3_close(pDest);
  1457. }else
  1458. if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
  1459. bail_on_error = booleanValue(azArg[1]);
  1460. }else
  1461. if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
  1462. struct callback_data data;
  1463. char *zErrMsg = 0;
  1464. open_db(p);
  1465. memcpy(&data, p, sizeof(data));
  1466. data.showHeader = 1;
  1467. data.mode = MODE_Column;
  1468. data.colWidth[0] = 3;
  1469. data.colWidth[1] = 15;
  1470. data.colWidth[2] = 58;
  1471. data.cnt = 0;
  1472. sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  1473. if( zErrMsg ){
  1474. fprintf(stderr,"Error: %s\n", zErrMsg);
  1475. sqlite3_free(zErrMsg);
  1476. rc = 1;
  1477. }
  1478. }else
  1479. if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
  1480. open_db(p);
  1481. /* When playing back a "dump", the content might appear in an order
  1482. ** which causes immediate foreign key constraints to be violated.
  1483. ** So disable foreign-key constraint enforcement to prevent problems. */
  1484. fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
  1485. fprintf(p->out, "BEGIN TRANSACTION;\n");
  1486. p->writableSchema = 0;
  1487. sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  1488. p->nErr = 0;
  1489. if( nArg==1 ){
  1490. run_schema_dump_query(p,
  1491. "SELECT name, type, sql FROM sqlite_master "
  1492. "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  1493. );
  1494. run_schema_dump_query(p,
  1495. "SELECT name, type, sql FROM sqlite_master "
  1496. "WHERE name=='sqlite_sequence'"
  1497. );
  1498. run_table_dump_query(p,
  1499. "SELECT sql FROM sqlite_master "
  1500. "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  1501. );
  1502. }else{
  1503. int i;
  1504. for(i=1; i<nArg; i++){
  1505. zShellStatic = azArg[i];
  1506. run_schema_dump_query(p,
  1507. "SELECT name, type, sql FROM sqlite_master "
  1508. "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  1509. " AND sql NOT NULL");
  1510. run_table_dump_query(p,
  1511. "SELECT sql FROM sqlite_master "
  1512. "WHERE sql NOT NULL"
  1513. " AND type IN ('index','trigger','view')"
  1514. " AND tbl_name LIKE shellstatic()", 0
  1515. );
  1516. zShellStatic = 0;
  1517. }
  1518. }
  1519. if( p->writableSchema ){
  1520. fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
  1521. p->writableSchema = 0;
  1522. }
  1523. sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  1524. sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  1525. fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  1526. }else
  1527. if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
  1528. p->echoOn = booleanValue(azArg[1]);
  1529. }else
  1530. if( c=='e' && strncmp(azArg[0], "exit", n)==0 && nArg==1 ){
  1531. rc = 2;
  1532. }else
  1533. if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
  1534. int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
  1535. if(val == 1) {
  1536. if(!p->explainPrev.valid) {
  1537. p->explainPrev.valid = 1;
  1538. p->explainPrev.mode = p->mode;
  1539. p->explainPrev.showHeader = p->showHeader;
  1540. memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
  1541. }
  1542. /* We could put this code under the !p->explainValid
  1543. ** condition so that it does not execute if we are already in
  1544. ** explain mode. However, always executing it allows us an easy
  1545. ** was to reset to explain mode in case the user previously
  1546. ** did an .explain followed by a .width, .mode or .header
  1547. ** command.
  1548. */
  1549. p->mode = MODE_Explain;
  1550. p->showHeader = 1;
  1551. memset(p->colWidth,0,ArraySize(p->colWidth));
  1552. p->colWidth[0] = 4; /* addr */
  1553. p->colWidth[1] = 13; /* opcode */
  1554. p->colWidth[2] = 4; /* P1 */
  1555. p->colWidth[3] = 4; /* P2 */
  1556. p->colWidth[4] = 4; /* P3 */
  1557. p->colWidth[5] = 13; /* P4 */
  1558. p->colWidth[6] = 2; /* P5 */
  1559. p->colWidth[7] = 13; /* Comment */
  1560. }else if (p->explainPrev.valid) {
  1561. p->explainPrev.valid = 0;
  1562. p->mode = p->explainPrev.mode;
  1563. p->showHeader = p->explainPrev.showHeader;
  1564. memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
  1565. }
  1566. }else
  1567. if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
  1568. strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){
  1569. p->showHeader = booleanValue(azArg[1]);
  1570. }else
  1571. if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  1572. fprintf(stderr,"%s",zHelp);
  1573. if( HAS_TIMER ){
  1574. fprintf(stderr,"%s",zTimerHelp);
  1575. }
  1576. }else
  1577. if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
  1578. char *zTable = azArg[2]; /* Insert data into this table */
  1579. char *zFile = azArg[1]; /* The file from which to extract data */
  1580. sqlite3_stmt *pStmt = NULL; /* A statement */
  1581. int nCol; /* Number of columns in the table */
  1582. int nByte; /* Number of bytes in an SQL string */
  1583. int i, j; /* Loop counters */
  1584. int nSep; /* Number of bytes in p->separator[] */
  1585. char *zSql; /* An SQL statement */
  1586. char *zLine; /* A single line of input from the file */
  1587. char **azCol; /* zLine[] broken up into columns */
  1588. char *zCommit; /* How to commit changes */
  1589. FILE *in; /* The input file */
  1590. int lineno = 0; /* Line number of input file */
  1591. open_db(p);
  1592. nSep = strlen30(p->separator);
  1593. if( nSep==0 ){
  1594. fprintf(stderr, "Error: non-null separator required for import\n");
  1595. return 1;
  1596. }
  1597. zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  1598. if( zSql==0 ){
  1599. fprintf(stderr, "Error: out of memory\n");
  1600. return 1;
  1601. }
  1602. nByte = strlen30(zSql);
  1603. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  1604. sqlite3_free(zSql);
  1605. if( rc ){
  1606. if (pStmt) sqlite3_finalize(pStmt);
  1607. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  1608. return 1;
  1609. }
  1610. nCol = sqlite3_column_count(pStmt);
  1611. sqlite3_finalize(pStmt);
  1612. pStmt = 0;
  1613. if( nCol==0 ) return 0; /* no columns, no error */
  1614. zSql = malloc( nByte + 20 + nCol*2 );
  1615. if( zSql==0 ){
  1616. fprintf(stderr, "Error: out of memory\n");
  1617. return 1;
  1618. }
  1619. sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zTable);
  1620. j = strlen30(zSql);
  1621. for(i=1; i<nCol; i++){
  1622. zSql[j++] = ',';
  1623. zSql[j++] = '?';
  1624. }
  1625. zSql[j++] = ')';
  1626. zSql[j] = 0;
  1627. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  1628. free(zSql);
  1629. if( rc ){
  1630. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  1631. if (pStmt) sqlite3_finalize(pStmt);
  1632. return 1;
  1633. }
  1634. in = fopen(zFile, "rb");
  1635. if( in==0 ){
  1636. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  1637. sqlite3_finalize(pStmt);
  1638. return 1;
  1639. }
  1640. azCol = malloc( sizeof(azCol[0])*(nCol+1) );
  1641. if( azCol==0 ){
  1642. fprintf(stderr, "Error: out of memory\n");
  1643. fclose(in);
  1644. sqlite3_finalize(pStmt);
  1645. return 1;
  1646. }
  1647. sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  1648. zCommit = "COMMIT";
  1649. while( (zLine = local_getline(0, in))!=0 ){
  1650. char *z;
  1651. lineno++;
  1652. azCol[0] = zLine;
  1653. for(i=0, z=zLine; *z && *z!='\n' && *z!='\r'; z++){
  1654. if( *z==p->separator[0] && strncmp(z, p->separator, nSep)==0 ){
  1655. *z = 0;
  1656. i++;
  1657. if( i<nCol ){
  1658. azCol[i] = &z[nSep];
  1659. z += nSep-1;
  1660. }
  1661. }
  1662. } /* end for */
  1663. *z = 0;
  1664. if( i+1!=nCol ){
  1665. fprintf(stderr,
  1666. "Error: %s line %d: expected %d columns of data but found %d\n",
  1667. zFile, lineno, nCol, i+1);
  1668. zCommit = "ROLLBACK";
  1669. free(zLine);
  1670. rc = 1;
  1671. break; /* from while */
  1672. }
  1673. for(i=0; i<nCol; i++){
  1674. sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
  1675. }
  1676. sqlite3_step(pStmt);
  1677. rc = sqlite3_reset(pStmt);
  1678. free(zLine);
  1679. if( rc!=SQLITE_OK ){
  1680. fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  1681. zCommit = "ROLLBACK";
  1682. rc = 1;
  1683. break; /* from while */
  1684. }
  1685. } /* end while */
  1686. free(azCol);
  1687. fclose(in);
  1688. sqlite3_finalize(pStmt);
  1689. sqlite3_exec(p->db, zCommit, 0, 0, 0);
  1690. }else
  1691. if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
  1692. struct callback_data data;
  1693. char *zErrMsg = 0;
  1694. open_db(p);
  1695. memcpy(&data, p, sizeof(data));
  1696. data.showHeader = 0;
  1697. data.mode = MODE_List;
  1698. if( nArg==1 ){
  1699. rc = sqlite3_exec(p->db,
  1700. "SELECT name FROM sqlite_master "
  1701. "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  1702. "UNION ALL "
  1703. "SELECT name FROM sqlite_temp_master "
  1704. "WHERE type='index' "
  1705. "ORDER BY 1",
  1706. callback, &data, &zErrMsg
  1707. );
  1708. }else{
  1709. zShellStatic = azArg[1];
  1710. rc = sqlite3_exec(p->db,
  1711. "SELECT name FROM sqlite_master "
  1712. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  1713. "UNION ALL "
  1714. "SELECT name FROM sqlite_temp_master "
  1715. "WHERE type='index' AND tbl_name LIKE shellstatic() "
  1716. "ORDER BY 1",
  1717. callback, &data, &zErrMsg
  1718. );
  1719. zShellStatic = 0;
  1720. }
  1721. if( zErrMsg ){
  1722. fprintf(stderr,"Error: %s\n", zErrMsg);
  1723. sqlite3_free(zErrMsg);
  1724. rc = 1;
  1725. }else if( rc != SQLITE_OK ){
  1726. fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
  1727. rc = 1;
  1728. }
  1729. }else
  1730. #ifdef SQLITE_ENABLE_IOTRACE
  1731. if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  1732. extern void (*sqlite3IoTrace)(const char*, ...);
  1733. if( iotrace && iotrace!=stdout ) fclose(iotrace);
  1734. iotrace = 0;
  1735. if( nArg<2 ){
  1736. sqlite3IoTrace = 0;
  1737. }else if( strcmp(azArg[1], "-")==0 ){
  1738. sqlite3IoTrace = iotracePrintf;
  1739. iotrace = stdout;
  1740. }else{
  1741. iotrace = fopen(azArg[1], "w");
  1742. if( iotrace==0 ){
  1743. fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  1744. sqlite3IoTrace = 0;
  1745. rc = 1;
  1746. }else{
  1747. sqlite3IoTrace = iotracePrintf;
  1748. }
  1749. }
  1750. }else
  1751. #endif
  1752. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  1753. if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
  1754. const char *zFile, *zProc;
  1755. char *zErrMsg = 0;
  1756. zFile = azArg[1];
  1757. zProc = nArg>=3 ? azArg[2] : 0;
  1758. open_db(p);
  1759. rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  1760. if( rc!=SQLITE_OK ){
  1761. fprintf(stderr, "Error: %s\n", zErrMsg);
  1762. sqlite3_free(zErrMsg);
  1763. rc = 1;
  1764. }
  1765. }else
  1766. #endif
  1767. if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){
  1768. const char *zFile = azArg[1];
  1769. if( p->pLog && p->pLog!=stdout && p->pLog!=stderr ){
  1770. fclose(p->pLog);
  1771. p->pLog = 0;
  1772. }
  1773. if( strcmp(zFile,"stdout")==0 ){
  1774. p->pLog = stdout;
  1775. }else if( strcmp(zFile, "stderr")==0 ){
  1776. p->pLog = stderr;
  1777. }else if( strcmp(zFile, "off")==0 ){
  1778. p->pLog = 0;
  1779. }else{
  1780. p->pLog = fopen(zFile, "w");
  1781. if( p->pLog==0 ){
  1782. fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
  1783. }
  1784. }
  1785. }else
  1786. if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){
  1787. int n2 = strlen30(azArg[1]);
  1788. if( (n2==4 && strncmp(azArg[1],"line",n2)==0)
  1789. ||
  1790. (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){
  1791. p->mode = MODE_Line;
  1792. }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0)
  1793. ||
  1794. (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){
  1795. p->mode = MODE_Column;
  1796. }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){
  1797. p->mode = MODE_List;
  1798. }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
  1799. p->mode = MODE_Html;
  1800. }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
  1801. p->mode = MODE_Tcl;
  1802. }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
  1803. p->mode = MODE_Csv;
  1804. sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
  1805. }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
  1806. p->mode = MODE_List;
  1807. sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
  1808. }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
  1809. p->mode = MODE_Insert;
  1810. set_table_name(p, "table");
  1811. }else {
  1812. fprintf(stderr,"Error: mode should be one of: "
  1813. "column csv html insert line list tabs tcl\n");
  1814. rc = 1;
  1815. }
  1816. }else
  1817. if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){
  1818. int n2 = strlen30(azArg[1]);
  1819. if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
  1820. p->mode = MODE_Insert;
  1821. set_table_name(p, azArg[2]);
  1822. }else {
  1823. fprintf(stderr, "Error: invalid arguments: "
  1824. " \"%s\". Enter \".help\" for help\n", azArg[2]);
  1825. rc = 1;
  1826. }
  1827. }else
  1828. if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
  1829. sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
  1830. "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
  1831. }else
  1832. if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
  1833. if( p->out!=stdout ){
  1834. fclose(p->out);
  1835. }
  1836. if( strcmp(azArg[1],"stdout")==0 ){
  1837. p->out = stdout;
  1838. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "stdout");
  1839. }else{
  1840. p->out = fopen(azArg[1], "wb");
  1841. if( p->out==0 ){
  1842. fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
  1843. p->out = stdout;
  1844. rc = 1;
  1845. } else {
  1846. sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
  1847. }
  1848. }
  1849. }else
  1850. if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
  1851. if( nArg >= 2) {
  1852. strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  1853. }
  1854. if( nArg >= 3) {
  1855. strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  1856. }
  1857. }else
  1858. if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){
  1859. rc = 2;
  1860. }else
  1861. if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
  1862. FILE *alt = fopen(azArg[1], "rb");
  1863. if( alt==0 ){
  1864. fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  1865. rc = 1;
  1866. }else{
  1867. rc = process_input(p, alt);
  1868. fclose(alt);
  1869. }
  1870. }else
  1871. if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){
  1872. const char *zSrcFile;
  1873. const char *zDb;
  1874. sqlite3 *pSrc;
  1875. sqlite3_backup *pBackup;
  1876. int nTimeout = 0;
  1877. if( nArg==2 ){
  1878. zSrcFile = azArg[1];
  1879. zDb = "main";
  1880. }else{
  1881. zSrcFile = azArg[2];
  1882. zDb = azArg[1];
  1883. }
  1884. rc = sqlite3_open(zSrcFile, &pSrc);
  1885. if( rc!=SQLITE_OK ){
  1886. fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  1887. sqlite3_close(pSrc);
  1888. return 1;
  1889. }
  1890. open_db(p);
  1891. pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  1892. if( pBackup==0 ){
  1893. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  1894. sqlite3_close(pSrc);
  1895. return 1;
  1896. }
  1897. while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  1898. || rc==SQLITE_BUSY ){
  1899. if( rc==SQLITE_BUSY ){
  1900. if( nTimeout++ >= 3 ) break;
  1901. sqlite3_sleep(100);
  1902. }
  1903. }
  1904. sqlite3_backup_finish(pBackup);
  1905. if( rc==SQLITE_DONE ){
  1906. rc = 0;
  1907. }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  1908. fprintf(stderr, "Error: source database is busy\n");
  1909. rc = 1;
  1910. }else{
  1911. fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  1912. rc = 1;
  1913. }
  1914. sqlite3_close(pSrc);
  1915. }else
  1916. if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
  1917. struct callback_data data;
  1918. char *zErrMsg = 0;
  1919. open_db(p);
  1920. memcpy(&data, p, sizeof(data));
  1921. data.showHeader = 0;
  1922. data.mode = MODE_Semi;
  1923. if( nArg>1 ){
  1924. int i;
  1925. for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  1926. if( strcmp(azArg[1],"sqlite_master")==0 ){
  1927. char *new_argv[2], *new_colv[2];
  1928. new_argv[0] = "CREATE TABLE sqlite_master (\n"
  1929. " type text,\n"
  1930. " name text,\n"
  1931. " tbl_name text,\n"
  1932. " rootpage integer,\n"
  1933. " sql text\n"
  1934. ")";
  1935. new_argv[1] = 0;
  1936. new_colv[0] = "sql";
  1937. new_colv[1] = 0;
  1938. callback(&data, 1, new_argv, new_colv);
  1939. rc = SQLITE_OK;
  1940. }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  1941. char *new_argv[2], *new_colv[2];
  1942. new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  1943. " type text,\n"
  1944. " name text,\n"
  1945. " tbl_name text,\n"
  1946. " rootpage integer,\n"
  1947. " sql text\n"
  1948. ")";
  1949. new_argv[1] = 0;
  1950. new_colv[0] = "sql";
  1951. new_colv[1] = 0;
  1952. callback(&data, 1, new_argv, new_colv);
  1953. rc = SQLITE_OK;
  1954. }else{
  1955. zShellStatic = azArg[1];
  1956. rc = sqlite3_exec(p->db,
  1957. "SELECT sql FROM "
  1958. " (SELECT sql sql, type type, tbl_name tbl_name, name name"
  1959. " FROM sqlite_master UNION ALL"
  1960. " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  1961. "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
  1962. "ORDER BY substr(type,2,1), name",
  1963. callback, &data, &zErrMsg);
  1964. zShellStatic = 0;
  1965. }
  1966. }else{
  1967. rc = sqlite3_exec(p->db,
  1968. "SELECT sql FROM "
  1969. " (SELECT sql sql, type type, tbl_name tbl_name, name name"
  1970. " FROM sqlite_master UNION ALL"
  1971. " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  1972. "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
  1973. "ORDER BY substr(type,2,1), name",
  1974. callback, &data, &zErrMsg
  1975. );
  1976. }
  1977. if( zErrMsg ){
  1978. fprintf(stderr,"Error: %s\n", zErrMsg);
  1979. sqlite3_free(zErrMsg);
  1980. rc = 1;
  1981. }else if( rc != SQLITE_OK ){
  1982. fprintf(stderr,"Error: querying schema information\n");
  1983. rc = 1;
  1984. }else{
  1985. rc = 0;
  1986. }
  1987. }else
  1988. if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
  1989. sqlite3_snprintf(sizeof(p->separator), p->separator,
  1990. "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  1991. }else
  1992. if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
  1993. int i;
  1994. fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
  1995. fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
  1996. fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  1997. fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  1998. fprintf(p->out,"%9.9s: ", "nullvalue");
  1999. output_c_string(p->out, p->nullvalue);
  2000. fprintf(p->out, "\n");
  2001. fprintf(p->out,"%9.9s: %s\n","output",
  2002. strlen30(p->outfile) ? p->outfile : "stdout");
  2003. fprintf(p->out,"%9.9s: ", "separator");
  2004. output_c_string(p->out, p->separator);
  2005. fprintf(p->out, "\n");
  2006. fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
  2007. fprintf(p->out,"%9.9s: ","width");
  2008. for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  2009. fprintf(p->out,"%d ",p->colWidth[i]);
  2010. }
  2011. fprintf(p->out,"\n");
  2012. }else
  2013. if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){
  2014. p->statsOn = booleanValue(azArg[1]);
  2015. }else
  2016. if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
  2017. char **azResult;
  2018. int nRow;
  2019. char *zErrMsg;
  2020. open_db(p);
  2021. if( nArg==1 ){
  2022. rc = sqlite3_get_table(p->db,
  2023. "SELECT name FROM sqlite_master "
  2024. "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
  2025. "UNION ALL "
  2026. "SELECT name FROM sqlite_temp_master "
  2027. "WHERE type IN ('table','view') "
  2028. "ORDER BY 1",
  2029. &azResult, &nRow, 0, &zErrMsg
  2030. );
  2031. }else{
  2032. zShellStatic = azArg[1];
  2033. rc = sqlite3_get_table(p->db,
  2034. "SELECT name FROM sqlite_master "
  2035. "WHERE type IN ('table','view') AND name LIKE shellstatic() "
  2036. "UNION ALL "
  2037. "SELECT name FROM sqlite_temp_master "
  2038. "WHERE type IN ('table','view') AND name LIKE shellstatic() "
  2039. "ORDER BY 1",
  2040. &azResult, &nRow, 0, &zErrMsg
  2041. );
  2042. zShellStatic = 0;
  2043. }
  2044. if( zErrMsg ){
  2045. fprintf(stderr,"Error: %s\n", zErrMsg);
  2046. sqlite3_free(zErrMsg);
  2047. rc = 1;
  2048. }else if( rc != SQLITE_OK ){
  2049. fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
  2050. rc = 1;
  2051. }else{
  2052. int len, maxlen = 0;
  2053. int i, j;
  2054. int nPrintCol, nPrintRow;
  2055. for(i=1; i<=nRow; i++){
  2056. if( azResult[i]==0 ) continue;
  2057. len = strlen30(azResult[i]);
  2058. if( len>maxlen ) maxlen = len;
  2059. }
  2060. nPrintCol = 80/(maxlen+2);
  2061. if( nPrintCol<1 ) nPrintCol = 1;
  2062. nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  2063. for(i=0; i<nPrintRow; i++){
  2064. for(j=i+1; j<=nRow; j+=nPrintRow){
  2065. char *zSp = j<=nPrintRow ? "" : " ";
  2066. printf("%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : "");
  2067. }
  2068. printf("\n");
  2069. }
  2070. }
  2071. sqlite3_free_table(azResult);
  2072. }else
  2073. if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  2074. static const struct {
  2075. const char *zCtrlName; /* Name of a test-control option */
  2076. int ctrlCode; /* Integer code for that option */
  2077. } aCtrl[] = {
  2078. { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
  2079. { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
  2080. { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
  2081. { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
  2082. { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
  2083. { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
  2084. { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
  2085. { "assert", SQLITE_TESTCTRL_ASSERT },
  2086. { "always", SQLITE_TESTCTRL_ALWAYS },
  2087. { "reserve", SQLITE_TESTCTRL_RESERVE },
  2088. { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
  2089. { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
  2090. { "pghdrsz", SQLITE_TESTCTRL_PGHDRSZ },
  2091. { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
  2092. };
  2093. int testctrl = -1;
  2094. int rc = 0;
  2095. int i, n;
  2096. open_db(p);
  2097. /* convert testctrl text option to value. allow any unique prefix
  2098. ** of the option name, or a numerical value. */
  2099. n = strlen30(azArg[1]);
  2100. for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
  2101. if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
  2102. if( testctrl<0 ){
  2103. testctrl = aCtrl[i].ctrlCode;
  2104. }else{
  2105. fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  2106. testctrl = -1;
  2107. break;
  2108. }
  2109. }
  2110. }
  2111. if( testctrl<0 ) testctrl = atoi(azArg[1]);
  2112. if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  2113. fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  2114. }else{
  2115. switch(testctrl){
  2116. /* sqlite3_test_control(int, db, int) */
  2117. case SQLITE_TESTCTRL_OPTIMIZATIONS:
  2118. case SQLITE_TESTCTRL_RESERVE:
  2119. if( nArg==3 ){
  2120. int opt = (int)strtol(azArg[2], 0, 0);
  2121. rc = sqlite3_test_control(testctrl, p->db, opt);
  2122. printf("%d (0x%08x)\n", rc, rc);
  2123. } else {
  2124. fprintf(stderr,"Error: testctrl %s takes a single int option\n",
  2125. azArg[1]);
  2126. }
  2127. break;
  2128. /* sqlite3_test_control(int) */
  2129. case SQLITE_TESTCTRL_PRNG_SAVE:
  2130. case SQLITE_TESTCTRL_PRNG_RESTORE:
  2131. case SQLITE_TESTCTRL_PRNG_RESET:
  2132. case SQLITE_TESTCTRL_PGHDRSZ:
  2133. if( nArg==2 ){
  2134. rc = sqlite3_test_control(testctrl);
  2135. printf("%d (0x%08x)\n", rc, rc);
  2136. } else {
  2137. fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
  2138. }
  2139. break;
  2140. /* sqlite3_test_control(int, uint) */
  2141. case SQLITE_TESTCTRL_PENDING_BYTE:
  2142. if( nArg==3 ){
  2143. unsigned int opt = (unsigned int)atoi(azArg[2]);
  2144. rc = sqlite3_test_control(testctrl, opt);
  2145. printf("%d (0x%08x)\n", rc, rc);
  2146. } else {
  2147. fprintf(stderr,"Error: testctrl %s takes a single unsigned"
  2148. " int option\n", azArg[1]);
  2149. }
  2150. break;
  2151. /* sqlite3_test_control(int, int) */
  2152. case SQLITE_TESTCTRL_ASSERT:
  2153. case SQLITE_TESTCTRL_ALWAYS:
  2154. if( nArg==3 ){
  2155. int opt = atoi(azArg[2]);
  2156. rc = sqlite3_test_control(testctrl, opt);
  2157. printf("%d (0x%08x)\n", rc, rc);
  2158. } else {
  2159. fprintf(stderr,"Error: testctrl %s takes a single int option\n",
  2160. azArg[1]);
  2161. }
  2162. break;
  2163. /* sqlite3_test_control(int, char *) */
  2164. #ifdef SQLITE_N_KEYWORD
  2165. case SQLITE_TESTCTRL_ISKEYWORD:
  2166. if( nArg==3 ){
  2167. const char *opt = azArg[2];
  2168. rc = sqlite3_test_control(testctrl, opt);
  2169. printf("%d (0x%08x)\n", rc, rc);
  2170. } else {
  2171. fprintf(stderr,"Error: testctrl %s takes a single char * option\n",
  2172. azArg[1]);
  2173. }
  2174. break;
  2175. #endif
  2176. case SQLITE_TESTCTRL_BITVEC_TEST:
  2177. case SQLITE_TESTCTRL_FAULT_INSTALL:
  2178. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  2179. case SQLITE_TESTCTRL_SCRATCHMALLOC:
  2180. default:
  2181. fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
  2182. azArg[1]);
  2183. break;
  2184. }
  2185. }
  2186. }else
  2187. if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
  2188. open_db(p);
  2189. sqlite3_busy_timeout(p->db, atoi(azArg[1]));
  2190. }else
  2191. if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
  2192. && nArg==2
  2193. ){
  2194. enableTimer = booleanValue(azArg[1]);
  2195. }else
  2196. if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  2197. printf("SQLite %s %s\n",
  2198. sqlite3_libversion(), sqlite3_sourceid());
  2199. }else
  2200. if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
  2201. int j;
  2202. assert( nArg<=ArraySize(azArg) );
  2203. for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  2204. p->colWidth[j-1] = atoi(azArg[j]);
  2205. }
  2206. }else
  2207. {
  2208. fprintf(stderr, "Error: unknown command or invalid arguments: "
  2209. " \"%s\". Enter \".help\" for help\n", azArg[0]);
  2210. rc = 1;
  2211. }
  2212. return rc;
  2213. }
  2214. /*
  2215. ** Return TRUE if a semicolon occurs anywhere in the first N characters
  2216. ** of string z[].
  2217. */
  2218. static int _contains_semicolon(const char *z, int N){
  2219. int i;
  2220. for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
  2221. return 0;
  2222. }
  2223. /*
  2224. ** Test to see if a line consists entirely of whitespace.
  2225. */
  2226. static int _all_whitespace(const char *z){
  2227. for(; *z; z++){
  2228. if( IsSpace(z[0]) ) continue;
  2229. if( *z=='/' && z[1]=='*' ){
  2230. z += 2;
  2231. while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  2232. if( *z==0 ) return 0;
  2233. z++;
  2234. continue;
  2235. }
  2236. if( *z=='-' && z[1]=='-' ){
  2237. z += 2;
  2238. while( *z && *z!='\n' ){ z++; }
  2239. if( *z==0 ) return 1;
  2240. continue;
  2241. }
  2242. return 0;
  2243. }
  2244. return 1;
  2245. }
  2246. /*
  2247. ** Return TRUE if the line typed in is an SQL command terminator other
  2248. ** than a semi-colon. The SQL Server style "go" command is understood
  2249. ** as is the Oracle "/".
  2250. */
  2251. static int _is_command_terminator(const char *zLine){
  2252. while( IsSpace(zLine[0]) ){ zLine++; };
  2253. if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  2254. return 1; /* Oracle */
  2255. }
  2256. if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  2257. && _all_whitespace(&zLine[2]) ){
  2258. return 1; /* SQL Server */
  2259. }
  2260. return 0;
  2261. }
  2262. /*
  2263. ** Return true if zSql is a complete SQL statement. Return false if it
  2264. ** ends in the middle of a string literal or C-style comment.
  2265. */
  2266. static int _is_complete(char *zSql, int nSql){
  2267. int rc;
  2268. if( zSql==0 ) return 1;
  2269. zSql[nSql] = ';';
  2270. zSql[nSql+1] = 0;
  2271. rc = sqlite3_complete(zSql);
  2272. zSql[nSql] = 0;
  2273. return rc;
  2274. }
  2275. /*
  2276. ** Read input from *in and process it. If *in==0 then input
  2277. ** is interactive - the user is typing it it. Otherwise, input
  2278. ** is coming from a file or device. A prompt is issued and history
  2279. ** is saved only if input is interactive. An interrupt signal will
  2280. ** cause this routine to exit immediately, unless input is interactive.
  2281. **
  2282. ** Return the number of errors.
  2283. */
  2284. static int process_input(struct callback_data *p, FILE *in){
  2285. char *zLine = 0;
  2286. char *zSql = 0;
  2287. int nSql = 0;
  2288. int nSqlPrior = 0;
  2289. char *zErrMsg;
  2290. int rc;
  2291. int errCnt = 0;
  2292. int lineno = 0;
  2293. int startline = 0;
  2294. while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  2295. fflush(p->out);
  2296. free(zLine);
  2297. zLine = one_input_line(zSql, in);
  2298. if( zLine==0 ){
  2299. break; /* We have reached EOF */
  2300. }
  2301. if( seenInterrupt ){
  2302. if( in!=0 ) break;
  2303. seenInterrupt = 0;
  2304. }
  2305. lineno++;
  2306. if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
  2307. if( zLine && zLine[0]=='.' && nSql==0 ){
  2308. if( p->echoOn ) printf("%s\n", zLine);
  2309. rc = do_meta_command(zLine, p);
  2310. if( rc==2 ){ /* exit requested */
  2311. break;
  2312. }else if( rc ){
  2313. errCnt++;
  2314. }
  2315. continue;
  2316. }
  2317. if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
  2318. memcpy(zLine,";",2);
  2319. }
  2320. nSqlPrior = nSql;
  2321. if( zSql==0 ){
  2322. int i;
  2323. for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  2324. if( zLine[i]!=0 ){
  2325. nSql = strlen30(zLine);
  2326. zSql = malloc( nSql+3 );
  2327. if( zSql==0 ){
  2328. fprintf(stderr, "Error: out of memory\n");
  2329. exit(1);
  2330. }
  2331. memcpy(zSql, zLine, nSql+1);
  2332. startline = lineno;
  2333. }
  2334. }else{
  2335. int len = strlen30(zLine);
  2336. zSql = realloc( zSql, nSql + len + 4 );
  2337. if( zSql==0 ){
  2338. fprintf(stderr,"Error: out of memory\n");
  2339. exit(1);
  2340. }
  2341. zSql[nSql++] = '\n';
  2342. memcpy(&zSql[nSql], zLine, len+1);
  2343. nSql += len;
  2344. }
  2345. if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  2346. && sqlite3_complete(zSql) ){
  2347. p->cnt = 0;
  2348. open_db(p);
  2349. BEGIN_TIMER;
  2350. rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  2351. END_TIMER;
  2352. if( rc || zErrMsg ){
  2353. char zPrefix[100];
  2354. if( in!=0 || !stdin_is_interactive ){
  2355. sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  2356. "Error: near line %d:", startline);
  2357. }else{
  2358. sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  2359. }
  2360. if( zErrMsg!=0 ){
  2361. fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
  2362. sqlite3_free(zErrMsg);
  2363. zErrMsg = 0;
  2364. }else{
  2365. fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  2366. }
  2367. errCnt++;
  2368. }
  2369. free(zSql);
  2370. zSql = 0;
  2371. nSql = 0;
  2372. }
  2373. }
  2374. if( zSql ){
  2375. if( !_all_whitespace(zSql) ){
  2376. fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
  2377. }
  2378. free(zSql);
  2379. }
  2380. free(zLine);
  2381. return errCnt;
  2382. }
  2383. /*
  2384. ** Return a pathname which is the user's home directory. A
  2385. ** 0 return indicates an error of some kind. Space to hold the
  2386. ** resulting string is obtained from malloc(). The calling
  2387. ** function should free the result.
  2388. */
  2389. static char *find_home_dir(void){
  2390. char *home_dir = NULL;
  2391. #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL)
  2392. struct passwd *pwent;
  2393. uid_t uid = getuid();
  2394. if( (pwent=getpwuid(uid)) != NULL) {
  2395. home_dir = pwent->pw_dir;
  2396. }
  2397. #endif
  2398. #if defined(_WIN32_WCE)
  2399. /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  2400. */
  2401. home_dir = strdup("/");
  2402. #else
  2403. #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  2404. if (!home_dir) {
  2405. home_dir = getenv("USERPROFILE");
  2406. }
  2407. #endif
  2408. if (!home_dir) {
  2409. home_dir = getenv("HOME");
  2410. }
  2411. #if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
  2412. if (!home_dir) {
  2413. char *zDrive, *zPath;
  2414. int n;
  2415. zDrive = getenv("HOMEDRIVE");
  2416. zPath = getenv("HOMEPATH");
  2417. if( zDrive && zPath ){
  2418. n = strlen30(zDrive) + strlen30(zPath) + 1;
  2419. home_dir = malloc( n );
  2420. if( home_dir==0 ) return 0;
  2421. sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  2422. return home_dir;
  2423. }
  2424. home_dir = "c:\\";
  2425. }
  2426. #endif
  2427. #endif /* !_WIN32_WCE */
  2428. if( home_dir ){
  2429. int n = strlen30(home_dir) + 1;
  2430. char *z = malloc( n );
  2431. if( z ) memcpy(z, home_dir, n);
  2432. home_dir = z;
  2433. }
  2434. return home_dir;
  2435. }
  2436. /*
  2437. ** Read input from the file given by sqliterc_override. Or if that
  2438. ** parameter is NULL, take input from ~/.sqliterc
  2439. **
  2440. ** Returns the number of errors.
  2441. */
  2442. static int process_sqliterc(
  2443. struct callback_data *p, /* Configuration data */
  2444. const char *sqliterc_override /* Name of config file. NULL to use default */
  2445. ){
  2446. char *home_dir = NULL;
  2447. const char *sqliterc = sqliterc_override;
  2448. char *zBuf = 0;
  2449. FILE *in = NULL;
  2450. int nBuf;
  2451. int rc = 0;
  2452. if (sqliterc == NULL) {
  2453. home_dir = find_home_dir();
  2454. if( home_dir==0 ){
  2455. #if !defined(__RTP__) && !defined(_WRS_KERNEL)
  2456. fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0);
  2457. #endif
  2458. return 1;
  2459. }
  2460. nBuf = strlen30(home_dir) + 16;
  2461. zBuf = malloc( nBuf );
  2462. if( zBuf==0 ){
  2463. fprintf(stderr,"%s: Error: out of memory\n",Argv0);
  2464. return 1;
  2465. }
  2466. sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir);
  2467. free(home_dir);
  2468. sqliterc = (const char*)zBuf;
  2469. }
  2470. in = fopen(sqliterc,"rb");
  2471. if( in ){
  2472. if( stdin_is_interactive ){
  2473. fprintf(stderr,"-- Loading resources from %s\n",sqliterc);
  2474. }
  2475. rc = process_input(p,in);
  2476. fclose(in);
  2477. }
  2478. free(zBuf);
  2479. return rc;
  2480. }
  2481. /*
  2482. ** Show available command line options
  2483. */
  2484. static const char zOptions[] =
  2485. " -help show this message\n"
  2486. " -init filename read/process named file\n"
  2487. " -echo print commands before execution\n"
  2488. " -[no]header turn headers on or off\n"
  2489. " -bail stop after hitting an error\n"
  2490. " -interactive force interactive I/O\n"
  2491. " -batch force batch I/O\n"
  2492. " -column set output mode to 'column'\n"
  2493. " -csv set output mode to 'csv'\n"
  2494. " -html set output mode to HTML\n"
  2495. " -line set output mode to 'line'\n"
  2496. " -list set output mode to 'list'\n"
  2497. " -separator 'x' set output field separator (|)\n"
  2498. " -stats print memory stats before each finalize\n"
  2499. " -nullvalue 'text' set text string for NULL values\n"
  2500. " -version show SQLite version\n"
  2501. " -vfs NAME use NAME as the default VFS\n"
  2502. #ifdef SQLITE_ENABLE_VFSTRACE
  2503. " -vfstrace enable tracing of all VFS calls\n"
  2504. #endif
  2505. #ifdef SQLITE_ENABLE_MULTIPLEX
  2506. " -multiplex enable the multiplexor VFS\n"
  2507. #endif
  2508. ;
  2509. static void usage(int showDetail){
  2510. fprintf(stderr,
  2511. "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  2512. "FILENAME is the name of an SQLite database. A new database is created\n"
  2513. "if the file does not previously exist.\n", Argv0);
  2514. if( showDetail ){
  2515. fprintf(stderr, "OPTIONS include:\n%s", zOptions);
  2516. }else{
  2517. fprintf(stderr, "Use the -help option for additional information\n");
  2518. }
  2519. exit(1);
  2520. }
  2521. /*
  2522. ** Initialize the state information in data
  2523. */
  2524. static void main_init(struct callback_data *data) {
  2525. memset(data, 0, sizeof(*data));
  2526. data->mode = MODE_List;
  2527. memcpy(data->separator,"|", 2);
  2528. data->showHeader = 0;
  2529. sqlite3_config(SQLITE_CONFIG_URI, 1);
  2530. sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  2531. sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  2532. sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
  2533. sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
  2534. }
  2535. int main(int argc, char **argv){
  2536. char *zErrMsg = 0;
  2537. struct callback_data data;
  2538. const char *zInitFile = 0;
  2539. char *zFirstCmd = 0;
  2540. int i;
  2541. int rc = 0;
  2542. if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  2543. fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  2544. sqlite3_sourceid(), SQLITE_SOURCE_ID);
  2545. exit(1);
  2546. }
  2547. Argv0 = argv[0];
  2548. main_init(&data);
  2549. stdin_is_interactive = isatty(0);
  2550. /* Make sure we have a valid signal handler early, before anything
  2551. ** else is done.
  2552. */
  2553. #ifdef SIGINT
  2554. signal(SIGINT, interrupt_handler);
  2555. #endif
  2556. /* Do an initial pass through the command-line argument to locate
  2557. ** the name of the database file, the name of the initialization file,
  2558. ** the size of the alternative malloc heap,
  2559. ** and the first command to execute.
  2560. */
  2561. for(i=1; i<argc-1; i++){
  2562. char *z;
  2563. if( argv[i][0]!='-' ) break;
  2564. z = argv[i];
  2565. if( z[0]=='-' && z[1]=='-' ) z++;
  2566. if( strcmp(argv[i],"-separator")==0 || strcmp(argv[i],"-nullvalue")==0 ){
  2567. i++;
  2568. }else if( strcmp(argv[i],"-init")==0 ){
  2569. i++;
  2570. zInitFile = argv[i];
  2571. /* Need to check for batch mode here to so we can avoid printing
  2572. ** informational messages (like from process_sqliterc) before
  2573. ** we do the actual processing of arguments later in a second pass.
  2574. */
  2575. }else if( strcmp(argv[i],"-batch")==0 ){
  2576. stdin_is_interactive = 0;
  2577. }else if( strcmp(argv[i],"-heap")==0 ){
  2578. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  2579. int j, c;
  2580. const char *zSize;
  2581. sqlite3_int64 szHeap;
  2582. zSize = argv[++i];
  2583. szHeap = atoi(zSize);
  2584. for(j=0; (c = zSize[j])!=0; j++){
  2585. if( c=='M' ){ szHeap *= 1000000; break; }
  2586. if( c=='K' ){ szHeap *= 1000; break; }
  2587. if( c=='G' ){ szHeap *= 1000000000; break; }
  2588. }
  2589. if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  2590. sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  2591. #endif
  2592. #ifdef SQLITE_ENABLE_VFSTRACE
  2593. }else if( strcmp(argv[i],"-vfstrace")==0 ){
  2594. extern int vfstrace_register(
  2595. const char *zTraceName,
  2596. const char *zOldVfsName,
  2597. int (*xOut)(const char*,void*),
  2598. void *pOutArg,
  2599. int makeDefault
  2600. );
  2601. vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  2602. #endif
  2603. #ifdef SQLITE_ENABLE_MULTIPLEX
  2604. }else if( strcmp(argv[i],"-multiplex")==0 ){
  2605. extern int sqlite3_multiple_initialize(const char*,int);
  2606. sqlite3_multiplex_initialize(0, 1);
  2607. #endif
  2608. }else if( strcmp(argv[i],"-vfs")==0 ){
  2609. sqlite3_vfs *pVfs = sqlite3_vfs_find(argv[++i]);
  2610. if( pVfs ){
  2611. sqlite3_vfs_register(pVfs, 1);
  2612. }else{
  2613. fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  2614. exit(1);
  2615. }
  2616. }
  2617. }
  2618. if( i<argc ){
  2619. #if defined(SQLITE_OS_OS2) && SQLITE_OS_OS2
  2620. data.zDbFilename = (const char *)convertCpPathToUtf8( argv[i++] );
  2621. #else
  2622. data.zDbFilename = argv[i++];
  2623. #endif
  2624. }else{
  2625. #ifndef SQLITE_OMIT_MEMORYDB
  2626. data.zDbFilename = ":memory:";
  2627. #else
  2628. data.zDbFilename = 0;
  2629. #endif
  2630. }
  2631. if( i<argc ){
  2632. zFirstCmd = argv[i++];
  2633. }
  2634. if( i<argc ){
  2635. fprintf(stderr,"%s: Error: too many options: \"%s\"\n", Argv0, argv[i]);
  2636. fprintf(stderr,"Use -help for a list of options.\n");
  2637. return 1;
  2638. }
  2639. data.out = stdout;
  2640. #ifdef SQLITE_OMIT_MEMORYDB
  2641. if( data.zDbFilename==0 ){
  2642. fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
  2643. return 1;
  2644. }
  2645. #endif
  2646. /* Go ahead and open the database file if it already exists. If the
  2647. ** file does not exist, delay opening it. This prevents empty database
  2648. ** files from being created if a user mistypes the database name argument
  2649. ** to the sqlite command-line tool.
  2650. */
  2651. if( access(data.zDbFilename, 0)==0 ){
  2652. open_db(&data);
  2653. }
  2654. /* Process the initialization file if there is one. If no -init option
  2655. ** is given on the command line, look for a file named ~/.sqliterc and
  2656. ** try to process it.
  2657. */
  2658. rc = process_sqliterc(&data,zInitFile);
  2659. if( rc>0 ){
  2660. return rc;
  2661. }
  2662. /* Make a second pass through the command-line argument and set
  2663. ** options. This second pass is delayed until after the initialization
  2664. ** file is processed so that the command-line arguments will override
  2665. ** settings in the initialization file.
  2666. */
  2667. for(i=1; i<argc && argv[i][0]=='-'; i++){
  2668. char *z = argv[i];
  2669. if( z[1]=='-' ){ z++; }
  2670. if( strcmp(z,"-init")==0 ){
  2671. i++;
  2672. }else if( strcmp(z,"-html")==0 ){
  2673. data.mode = MODE_Html;
  2674. }else if( strcmp(z,"-list")==0 ){
  2675. data.mode = MODE_List;
  2676. }else if( strcmp(z,"-line")==0 ){
  2677. data.mode = MODE_Line;
  2678. }else if( strcmp(z,"-column")==0 ){
  2679. data.mode = MODE_Column;
  2680. }else if( strcmp(z,"-csv")==0 ){
  2681. data.mode = MODE_Csv;
  2682. memcpy(data.separator,",",2);
  2683. }else if( strcmp(z,"-separator")==0 ){
  2684. i++;
  2685. if(i>=argc){
  2686. fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
  2687. fprintf(stderr,"Use -help for a list of options.\n");
  2688. return 1;
  2689. }
  2690. sqlite3_snprintf(sizeof(data.separator), data.separator,
  2691. "%.*s",(int)sizeof(data.separator)-1,argv[i]);
  2692. }else if( strcmp(z,"-nullvalue")==0 ){
  2693. i++;
  2694. if(i>=argc){
  2695. fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z);
  2696. fprintf(stderr,"Use -help for a list of options.\n");
  2697. return 1;
  2698. }
  2699. sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
  2700. "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]);
  2701. }else if( strcmp(z,"-header")==0 ){
  2702. data.showHeader = 1;
  2703. }else if( strcmp(z,"-noheader")==0 ){
  2704. data.showHeader = 0;
  2705. }else if( strcmp(z,"-echo")==0 ){
  2706. data.echoOn = 1;
  2707. }else if( strcmp(z,"-stats")==0 ){
  2708. data.statsOn = 1;
  2709. }else if( strcmp(z,"-bail")==0 ){
  2710. bail_on_error = 1;
  2711. }else if( strcmp(z,"-version")==0 ){
  2712. printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  2713. return 0;
  2714. }else if( strcmp(z,"-interactive")==0 ){
  2715. stdin_is_interactive = 1;
  2716. }else if( strcmp(z,"-batch")==0 ){
  2717. stdin_is_interactive = 0;
  2718. }else if( strcmp(z,"-heap")==0 ){
  2719. i++;
  2720. }else if( strcmp(z,"-vfs")==0 ){
  2721. i++;
  2722. #ifdef SQLITE_ENABLE_VFSTRACE
  2723. }else if( strcmp(z,"-vfstrace")==0 ){
  2724. i++;
  2725. #endif
  2726. #ifdef SQLITE_ENABLE_MULTIPLEX
  2727. }else if( strcmp(z,"-multiplex")==0 ){
  2728. i++;
  2729. #endif
  2730. }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){
  2731. usage(1);
  2732. }else{
  2733. fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  2734. fprintf(stderr,"Use -help for a list of options.\n");
  2735. return 1;
  2736. }
  2737. }
  2738. if( zFirstCmd ){
  2739. /* Run just the command that follows the database name
  2740. */
  2741. if( zFirstCmd[0]=='.' ){
  2742. rc = do_meta_command(zFirstCmd, &data);
  2743. }else{
  2744. open_db(&data);
  2745. rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
  2746. if( zErrMsg!=0 ){
  2747. fprintf(stderr,"Error: %s\n", zErrMsg);
  2748. return rc!=0 ? rc : 1;
  2749. }else if( rc!=0 ){
  2750. fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
  2751. return rc;
  2752. }
  2753. }
  2754. }else{
  2755. /* Run commands received from standard input
  2756. */
  2757. if( stdin_is_interactive ){
  2758. char *zHome;
  2759. char *zHistory = 0;
  2760. int nHistory;
  2761. printf(
  2762. "SQLite version %s %.19s\n"
  2763. "Enter \".help\" for instructions\n"
  2764. "Enter SQL statements terminated with a \";\"\n",
  2765. sqlite3_libversion(), sqlite3_sourceid()
  2766. );
  2767. zHome = find_home_dir();
  2768. if( zHome ){
  2769. nHistory = strlen30(zHome) + 20;
  2770. if( (zHistory = malloc(nHistory))!=0 ){
  2771. sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  2772. }
  2773. }
  2774. #if defined(HAVE_READLINE) && HAVE_READLINE==1
  2775. if( zHistory ) read_history(zHistory);
  2776. #endif
  2777. rc = process_input(&data, 0);
  2778. if( zHistory ){
  2779. stifle_history(100);
  2780. write_history(zHistory);
  2781. free(zHistory);
  2782. }
  2783. free(zHome);
  2784. }else{
  2785. rc = process_input(&data, stdin);
  2786. }
  2787. }
  2788. set_table_name(&data, 0);
  2789. if( data.db ){
  2790. sqlite3_close(data.db);
  2791. }
  2792. return rc;
  2793. }