PageRenderTime 85ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/lib_sqlite/shell.c

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