PageRenderTime 58ms CodeModel.GetById 25ms 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

Large files files are truncated, but you can click here to view the full file

  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 (zErrMs

Large files files are truncated, but you can click here to view the full file