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

/spatialite-tools-2.4.0/shell.c

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