PageRenderTime 44ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/src/sqlite/src/shell.c

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