4
/ a CLI backend for SpatiaLite
6
/ version 1.0, 2008 Decmber 11
8
/ Author: Sandro Furieri a.furieri@lqt.it
10
/ Copyright (C) 2008 Alessandro Furieri
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.
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.
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/>.
32
This file is the original SQLite command-line backend
33
slightly modified by Alessandro Furieri in order to
34
fully support the SpatiaLite extensions
38
/* Sandro Furieri 30 May 2008
39
/ #include "sqlite3.h"
41
#ifdef SPATIALITE_AMALGAMATION
42
#include <spatialite/sqlite3.h>
47
#include <spatialite.h>
49
#define LIBICONV_STATIC
52
/* end Sandro Furieri 30 May 2008 */
60
#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
64
#include <sys/types.h>
71
#if defined(HAVE_READLINE) && HAVE_READLINE==1
72
#include <readline/readline.h>
73
#include <readline/history.h>
75
#define readline(p) local_getline(p,stdin)
76
#define add_history(X)
77
#define read_history(X)
78
#define write_history(X)
79
#define stifle_history(X)
82
#if defined(_WIN32) || defined(WIN32)
84
#define isatty _isatty
85
#define access _access
87
/* Make sure isatty() has a prototype.
92
#if defined(_WIN32_WCE)
93
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
94
* thus we always assume that we have a console. That can be
95
* overridden with the -batch command line option.
100
#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__)
101
#include <sys/time.h>
102
#include <sys/resource.h>
104
/* Saved resource information for the beginning of an operation */
105
static struct rusage sBegin;
107
/* True if the timer is enabled */
108
static int enableTimer = 0;
111
** Begin timing an operation
118
getrusage (RUSAGE_SELF, &sBegin);
122
/* Return the difference of two time_structs in microseconds */
124
timeDiff (struct timeval *pStart, struct timeval *pEnd)
126
return (pEnd->tv_usec - pStart->tv_usec) +
127
1000000 * (pEnd->tv_sec - pStart->tv_sec);
131
** Print the timing results.
139
getrusage (RUSAGE_SELF, &sEnd);
140
printf ("CPU Time: user %f sys %f\n",
141
0.000001 * timeDiff (&sBegin.ru_utime, &sEnd.ru_utime),
142
0.000001 * timeDiff (&sBegin.ru_stime, &sEnd.ru_stime));
146
#define BEGIN_TIMER beginTimer()
147
#define END_TIMER endTimer()
157
** If the following flag is set, then command execution stops
158
** at an error if we are not interactive.
160
static int bail_on_error = 0;
163
** Threat stdin as an interactive input if the following variable
164
** is true. Otherwise, assume stdin is connected to a file or pipe.
166
static int stdin_is_interactive = 1;
169
** The following is the open SQLite database. We make a pointer
170
** to this database a static variable so that it can be accessed
171
** by the SIGINT handler to interrupt database processing.
173
static sqlite3 *db = 0;
176
** True if an interrupt (Control-C) has been received.
178
static volatile int seenInterrupt = 0;
181
** This is the name of our program. It is set in main(), used
182
** in a number of other places, mostly for error messages.
187
** Prompt strings. Initialized in main. Settable with
188
** .prompt main continue
190
static char mainPrompt[20]; /* First line prompt. default: "sqlite> " */
191
static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
194
** Write I/O traces to the following stream.
196
#ifdef SQLITE_ENABLE_IOTRACE
197
static FILE *iotrace = 0;
201
** This routine works like printf in that its first argument is a
202
** format string and subsequent arguments are values to be substituted
203
** in place of % fields. The result of formatting this string
204
** is written to iotrace.
206
#ifdef SQLITE_ENABLE_IOTRACE
208
iotracePrintf (const char *zFormat, ...)
214
va_start (ap, zFormat);
215
z = sqlite3_vmprintf (zFormat, ap);
217
fprintf (iotrace, "%s", z);
225
Sandro Furieri 2008-11-20
226
implementing AUTO FDO
229
struct auto_fdo_table
232
struct auto_fdo_table *next;
235
struct auto_fdo_tables
237
struct auto_fdo_table *first;
238
struct auto_fdo_table *last;
241
static struct auto_fdo_tables *
244
struct auto_fdo_tables *p = malloc (sizeof (struct auto_fdo_tables));
251
fdo_tables_free (struct auto_fdo_tables *p)
253
struct auto_fdo_table *pt;
254
struct auto_fdo_table *ptn;
269
add_to_fdo_tables (struct auto_fdo_tables *pt, const char *name, int len)
271
struct auto_fdo_table *p = malloc (sizeof (struct auto_fdo_table));
272
p->name = malloc (len + 1);
273
strcpy (p->name, name);
283
auto_fdo_start (sqlite3 * db)
285
/* trying to start the FDO-OGR auto-wrapper */
295
int spatial_type = 0;
296
struct auto_fdo_tables *tables;
297
struct auto_fdo_table *p;
300
strcpy (sql, "SELECT CheckSpatialMetadata()");
301
ret = sqlite3_get_table (db, sql, &results, &rows, &columns, NULL);
302
if (ret != SQLITE_OK)
308
for (i = 1; i <= rows; i++)
309
spatial_type = atoi (results[(i * columns) + 0]);
311
sqlite3_free_table (results);
313
if (spatial_type == 2)
315
/* ok, creating VirtualFDO tables */
316
tables = fdo_tables_alloc ();
317
strcpy (sql, "SELECT DISTINCT f_table_name FROM geometry_columns");
318
ret = sqlite3_get_table (db, sql, &results, &rows, &columns, NULL);
319
if (ret != SQLITE_OK)
325
for (i = 1; i <= rows; i++)
327
name = results[(i * columns) + 0];
331
add_to_fdo_tables (tables, name, len);
335
sqlite3_free_table (results);
339
("\n================ FDO-OGR Spatial Metadata detected ===============\n");
342
/* destroying the VirtualFDO table [if existing] */
343
sprintf (sql, "DROP TABLE IF EXISTS fdo_%s", p->name);
344
ret = sqlite3_exec (db, sql, NULL, 0, NULL);
345
if (ret != SQLITE_OK)
347
/* creating the VirtualFDO table */
349
"CREATE VIRTUAL TABLE fdo_%s USING VirtualFDO(%s)",
351
ret = sqlite3_exec (db, sql, NULL, 0, NULL);
352
if (ret != SQLITE_OK)
354
printf ("\tcreated VirtualFDO table 'fdo_%s'\n", p->name);
362
("Accessing these fdo_XX tables you can take full advantage of\n");
363
printf ("FDO-OGR auto-wrapping facility\n");
365
("This allows you to access any specific FDO-OGR Geometry as if it\n");
367
("where native SpatiaLite ones in a completely transparent way\n");
369
("==================================================================\n\n");
370
fdo_tables_free (tables);
377
auto_fdo_stop (sqlite3 * db)
379
/* trying to stop the FDO-OGR auto-wrapper */
389
int spatial_type = 0;
390
struct auto_fdo_tables *tables;
391
struct auto_fdo_table *p;
394
strcpy (sql, "SELECT CheckSpatialMetadata()");
395
ret = sqlite3_get_table (db, sql, &results, &rows, &columns, NULL);
396
if (ret != SQLITE_OK)
402
for (i = 1; i <= rows; i++)
403
spatial_type = atoi (results[(i * columns) + 0]);
405
sqlite3_free_table (results);
407
if (spatial_type == 2)
409
/* ok, destroying VirtualFDO tables */
410
tables = fdo_tables_alloc ();
411
strcpy (sql, "SELECT DISTINCT f_table_name FROM geometry_columns");
412
ret = sqlite3_get_table (db, sql, &results, &rows, &columns, NULL);
413
if (ret != SQLITE_OK)
419
for (i = 1; i <= rows; i++)
421
name = results[(i * columns) + 0];
425
add_to_fdo_tables (tables, name, len);
429
sqlite3_free_table (results);
433
/* destroying the VirtualFDO table [if existing] */
434
sprintf (sql, "DROP TABLE IF EXISTS fdo_%s", p->name);
435
ret = sqlite3_exec (db, sql, NULL, 0, NULL);
436
if (ret != SQLITE_OK)
443
printf ("\n*** FDO-OGR auto-wrapping shutdown done ***\n");
444
fdo_tables_free (tables);
449
/* end Sandro Furieri 11 July 2008 */
455
Sandro Furieri 11 July 2008
456
implementing full UNICODE support
459
static iconv_t locale_to_utf8 = NULL;
460
static iconv_t utf8_to_locale = NULL;
461
static iconv_t in_charset_to_utf8 = NULL;
462
static char spatialite_charset[1024] = "";
465
create_utf8_converter (char *charset)
467
/* creating the UTF8 structs */
468
*spatialite_charset = '\0';
471
/* destroying old converter, if exists */
472
iconv_close (locale_to_utf8);
473
locale_to_utf8 = NULL;
477
/* destroying old converter, if exists */
478
iconv_close (utf8_to_locale);
479
utf8_to_locale = NULL;
481
/* creating new converters */
482
locale_to_utf8 = iconv_open ("UTF-8", charset);
483
if (locale_to_utf8 == (iconv_t) (-1))
485
locale_to_utf8 = NULL;
487
"*** charset ERROR *** cannot convert from '%s' to 'UTF-8'\n",
492
utf8_to_locale = iconv_open (charset, "UTF-8");
493
if (utf8_to_locale == (iconv_t) (-1))
495
utf8_to_locale = NULL;
497
"*** charset ERROR *** cannot convert from 'UTF-8' to '%s'\n",
502
strncpy (spatialite_charset, charset, sizeof (spatialite_charset) - 1);
503
spatialite_charset[sizeof (spatialite_charset) - 1] = '\0';
507
create_input_utf8_converter (char *charset)
509
/* creating the UTF8 structs */
510
if (in_charset_to_utf8)
512
/* destroying old converter, if exists */
513
iconv_close (in_charset_to_utf8);
514
in_charset_to_utf8 = NULL;
516
/* creating new converter */
517
in_charset_to_utf8 = iconv_open ("UTF-8", charset);
518
if (in_charset_to_utf8 == (iconv_t) (-1))
520
in_charset_to_utf8 = NULL;
522
"*** charset ERROR *** cannot convert from '%s' to 'UTF-8'\n",
530
convert_from_utf8 (char *buf, int maxlen)
532
/* converting from UTF8 to locale charset */
544
utf8buf = malloc (maxlen);
547
fprintf (stderr, "out of memory!\n");
554
if (iconv (utf8_to_locale, &pBuf, &len, &pUtf8buf, &utf8len) ==
557
fprintf (stderr, "\n*** ILLEGAL CHARACTER SEQUENCE ***\n\n");
562
utf8buf[maxlen - utf8len] = '\0';
563
memcpy (buf, utf8buf, (maxlen - utf8len) + 1);
568
convert_to_utf8 (char *buf, int maxlen)
570
/* converting from locale charset to UTF8 */
582
utf8buf = malloc (maxlen);
585
fprintf (stderr, "out of memory!\n");
592
if (iconv (locale_to_utf8, &pBuf, &len, &pUtf8buf, &utf8len) ==
595
fprintf (stderr, "\n*** ILLEGAL CHARACTER SEQUENCE ***\n\n");
600
utf8buf[maxlen - utf8len] = '\0';
601
memcpy (buf, utf8buf, (maxlen - utf8len) + 1);
606
convert_input_to_utf8 (char *buf, int maxlen)
608
/* converting from required charset to UTF8 */
618
if (!in_charset_to_utf8)
620
utf8buf = malloc (maxlen);
623
fprintf (stderr, "out of memory!\n");
630
if (iconv (in_charset_to_utf8, &pBuf, &len, &pUtf8buf, &utf8len) ==
633
fprintf (stderr, "\n*** ILLEGAL CHARACTER SEQUENCE ***\n\n");
638
utf8buf[maxlen - utf8len] = '\0';
639
memcpy (buf, utf8buf, (maxlen - utf8len) + 1);
643
/* end Sandro Furieri 11 July 2008 */
648
** Determines if a string is a number of not.
651
isNumber (const char *z, int *realnum)
653
if (*z == '-' || *z == '+')
678
if (*z == 'e' || *z == 'E')
681
if (*z == '+' || *z == '-')
696
** A global char* and an SQL function to access its current value
697
** from within an SQL statement. This program used to use the
698
** sqlite_exec_printf() API to substitue a string into an SQL statement.
699
** The correct way to do this with sqlite3 is to use the bind API, but
700
** since the shell is built around the callback paradigm it would be a lot
701
** of work. Instead just use this hack, which is quite harmless.
703
static const char *zShellStatic = 0;
705
shellstaticFunc (sqlite3_context * context, int argc, sqlite3_value ** argv)
708
argv = NULL; /* suppressing stupid compiler warnings [unused] */
710
assert (zShellStatic);
711
sqlite3_result_text (context, zShellStatic, -1, SQLITE_STATIC);
716
** This routine reads a line of text from FILE in, stores
717
** the text in memory obtained from malloc() and returns a pointer
718
** to the text. NULL is returned at end of file, or if malloc()
721
** The interface is like "readline" but no command-line editing
725
local_getline (char *zPrompt, FILE * in)
732
if (zPrompt && *zPrompt)
734
printf ("%s", zPrompt);
738
zLine = malloc (nLine);
747
nLine = nLine * 2 + 100;
748
zLine = realloc (zLine, nLine);
752
if (fgets (&zLine[n], nLine - n, in) == 0)
767
if (n > 0 && zLine[n - 1] == '\n')
774
zLine = realloc (zLine, n + 1);
779
** Retrieve a single line of input text.
781
** zPrior is a string of prior text retrieved. If not the empty
782
** string, then issue a continuation prompt.
785
one_input_line (const char *zPrior, FILE * in)
791
return local_getline (0, in);
793
if (zPrior && zPrior[0])
795
zPrompt = continuePrompt;
799
zPrompt = mainPrompt;
801
zResult = readline (zPrompt);
802
#if defined(HAVE_READLINE) && HAVE_READLINE==1
803
if (zResult && *zResult)
804
add_history (zResult);
809
struct previous_mode_data
811
int valid; /* Is there legit data in here? */
818
** An pointer to an instance of this structure is passed from
819
** the main program to the callback. This is used to communicate
820
** state and mode information.
824
sqlite3 *db; /* The database */
825
int echoOn; /* True to echo input commands */
826
int cnt; /* Number of records displayed so far */
827
FILE *out; /* Write results here */
828
int mode; /* An output mode setting */
829
int writableSchema; /* True if PRAGMA writable_schema=ON */
830
int showHeader; /* True to show column names in List or Column mode */
831
char *zDestTable; /* Name of destination table when MODE_Insert */
832
char separator[20]; /* Separator character for MODE_List */
833
int colWidth[100]; /* Requested width of each column when in column mode */
834
int actualWidth[100]; /* Actual width of each column */
835
char nullvalue[20]; /* The text to print when a NULL comes back from
837
struct previous_mode_data explainPrev;
838
/* Holds the mode information just before
840
char outfile[FILENAME_MAX]; /* Filename for *out */
841
const char *zDbFilename; /* name of the database file */
845
** These are the allowed modes.
847
#define MODE_Line 0 /* One column per line. Blank line between records */
848
#define MODE_Column 1 /* One record per line in neat columns */
849
#define MODE_List 2 /* One record per line with a separator */
850
#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
851
#define MODE_Html 4 /* Generate an XHTML table */
852
#define MODE_Insert 5 /* Generate SQL "insert" statements */
853
#define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
854
#define MODE_Csv 7 /* Quote strings, numbers are plain */
855
#define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
857
static const char *modeDescr[] = {
870
** Number of elements in an array
872
#define ArraySize(X) (sizeof(X)/sizeof(X[0]))
875
** Output the given string as a quoted string using SQL quoting conventions.
878
output_quoted_string (FILE * out, const char *z)
882
for (i = 0; z[i]; i++)
889
fprintf (out, "'%s'", z);
896
for (i = 0; z[i] && z[i] != '\''; i++)
904
else if (z[i] == '\'')
906
fprintf (out, "%.*s''", i, z);
911
fprintf (out, "%s", z);
920
** Output the given string as a quoted according to C or TCL quoting rules.
923
output_c_string (FILE * out, const char *z)
927
while ((c = *(z++)) != 0)
949
else if (!isprint (c))
951
fprintf (out, "\\%03o", c & 0xff);
962
** Output the given string with characters that are special to
966
output_html_string (FILE * out, const char *z)
971
for (i = 0; z[i] && z[i] != '<' && z[i] != '&'; i++)
976
fprintf (out, "%.*s", i, z);
980
fprintf (out, "<");
982
else if (z[i] == '&')
984
fprintf (out, "&");
995
** If a field contains any character identified by a 1 in the following
996
** array, then the string must be quoted for CSV.
998
static const char needCsvQuote[] = {
999
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1000
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1001
1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1002
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1003
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1004
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1005
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1006
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1007
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1008
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1009
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1010
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1011
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1012
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1013
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1014
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1018
** Output a single term of CSV. Actually, p->separator is used for
1019
** the separator, which may or may not be a comma. p->nullvalue is
1020
** the null value. Strings are quoted using ANSI-C rules. Numbers
1021
** appear outside of quotes.
1024
output_csv (struct callback_data *p, const char *z, int bSep)
1029
fprintf (out, "%s", p->nullvalue);
1034
int nSep = strlen (p->separator);
1035
for (i = 0; z[i]; i++)
1037
if (needCsvQuote[((unsigned char *) z)[i]]
1038
|| (z[i] == p->separator[0] &&
1039
(nSep == 1 || memcmp (z, p->separator, nSep) == 0)))
1048
for (i = 0; z[i]; i++)
1058
fprintf (out, "%s", z);
1063
fprintf (p->out, "%s", p->separator);
1069
** This routine runs when the user presses Ctrl-C
1072
interrupt_handler (int NotUsed)
1076
sqlite3_interrupt (db);
1081
** This is the callback routine that the SQLite library
1082
** invokes for each row of a query result.
1085
callback (void *pArg, int nArg, char **azArg, char **azCol)
1088
/* Sandro Furieri 11 July 2008 - supporting full UNICODE */
1091
/* end Sandro Furieri 11 July 2008 */
1092
struct callback_data *p = (struct callback_data *) pArg;
1100
for (i = 0; i < nArg; i++)
1102
int len = strlen (azCol[i] ? azCol[i] : "");
1107
fprintf (p->out, "\n");
1108
for (i = 0; i < nArg; i++)
1110
/* Sandro Furieri 11 July 2008
1111
fprintf (p->out, "%*s = %s\n", w, azCol[i],
1112
azArg[i] ? azArg[i] : p->nullvalue);
1115
fprintf (p->out, "%*s = %s\n", w, azCol[i],
1119
len = strlen (azArg[i]) + 1;
1122
buf = malloc (len * 4);
1123
strcpy (buf, azArg[i]);
1124
convert_from_utf8 (buf, len * 4);
1125
fprintf (p->out, "%*s = %s\n", w, azCol[i],
1126
azArg[i] ? buf : p->nullvalue);
1128
/* end Sandro Furieri 11 July 2008 */
1137
for (i = 0; i < nArg; i++)
1140
if (i < (int) ArraySize (p->colWidth))
1150
w = strlen (azCol[i] ? azCol[i] : "");
1154
&& azArg[i] ? azArg[i] :
1159
if (i < (int) ArraySize (p->actualWidth))
1161
p->actualWidth[i] = w;
1165
fprintf (p->out, "%-*.*s%s", w, w, azCol[i],
1166
i == nArg - 1 ? "\n" : " ");
1171
for (i = 0; i < nArg; i++)
1174
if (i < (int) ArraySize (p->actualWidth))
1176
w = p->actualWidth[i];
1182
fprintf (p->out, "%-*.*s%s", w, w,
1183
"-----------------------------------"
1184
"----------------------------------------------------------",
1185
i == nArg - 1 ? "\n" : " ");
1191
for (i = 0; i < nArg; i++)
1194
if (i < (int) ArraySize (p->actualWidth))
1196
w = p->actualWidth[i];
1202
if (p->mode == MODE_Explain && azArg[i]
1203
&& (int) strlen (azArg[i]) > w)
1205
w = strlen (azArg[i]);
1207
/* Sandro Furieri 11 July 2008
1208
fprintf (p->out, "%-*.*s%s", w, w,
1209
azArg[i] ? azArg[i] : p->nullvalue,
1210
i == nArg - 1 ? "\n" : " ");
1213
fprintf (p->out, "%-*.*s%s", w, w, p->nullvalue,
1214
i == nArg - 1 ? "\n" : " ");
1217
len = strlen (azArg[i]) + 1;
1220
buf = malloc (len * 4);
1221
strcpy (buf, azArg[i]);
1222
convert_from_utf8 (buf, len * 4);
1223
fprintf (p->out, "%-*.*s%s", w, w,
1224
azArg[i] ? buf : p->nullvalue,
1225
i == nArg - 1 ? "\n" : " ");
1227
/* end Sandro Furieri 11 July 2008 */
1234
if (p->cnt++ == 0 && p->showHeader)
1236
for (i = 0; i < nArg; i++)
1238
fprintf (p->out, "%s%s", azCol[i],
1239
i == nArg - 1 ? "\n" : p->separator);
1244
for (i = 0; i < nArg; i++)
1246
/* Sandro Furieri 11 July 2008
1256
len = strlen (azArg[i]) + 1;
1259
buf = malloc (len * 4);
1261
strcpy (buf, azArg[i]);
1262
convert_from_utf8 (buf, len * 4);
1264
/* end Sandro Furieri 11 July 2008 */
1265
fprintf (p->out, "%s", z);
1268
fprintf (p->out, "%s", p->separator);
1270
else if (p->mode == MODE_Semi)
1272
fprintf (p->out, ";\n");
1276
fprintf (p->out, "\n");
1283
if (p->cnt++ == 0 && p->showHeader)
1285
fprintf (p->out, "<TR>");
1286
for (i = 0; i < nArg; i++)
1288
fprintf (p->out, "<TH>%s</TH>", azCol[i]);
1290
fprintf (p->out, "</TR>\n");
1294
fprintf (p->out, "<TR>");
1295
for (i = 0; i < nArg; i++)
1297
fprintf (p->out, "<TD>");
1298
/* Sandro Furieri 11 July 2008
1299
output_html_string (p->out,
1300
azArg[i] ? azArg[i] : p->nullvalue);
1303
output_html_string (p->out, p->nullvalue);
1306
len = strlen (azArg[i]) + 1;
1309
buf = malloc (len * 4);
1310
strcpy (buf, azArg[i]);
1311
convert_from_utf8 (buf, len * 4);
1312
output_html_string (p->out,
1313
azArg[i] ? buf : p->nullvalue);
1315
/* end Sandro Furieri 11 July 2008 */
1316
fprintf (p->out, "</TD>\n");
1318
fprintf (p->out, "</TR>\n");
1323
if (p->cnt++ == 0 && p->showHeader)
1325
for (i = 0; i < nArg; i++)
1327
output_c_string (p->out, azCol[i] ? azCol[i] : "");
1328
fprintf (p->out, "%s", p->separator);
1330
fprintf (p->out, "\n");
1334
for (i = 0; i < nArg; i++)
1336
/* Sandro Furieri 11 July 2008
1337
output_c_string (p->out,
1338
azArg[i] ? azArg[i] : p->nullvalue);
1341
output_c_string (p->out, p->nullvalue);
1344
len = strlen (azArg[i]) + 1;
1347
buf = malloc (len * 4);
1348
strcpy (buf, azArg[i]);
1349
convert_from_utf8 (buf, len * 4);
1350
output_c_string (p->out,
1351
azArg[i] ? buf : p->nullvalue);
1353
/* end Sandro Furieri 11 July 2008 */
1354
fprintf (p->out, "%s", p->separator);
1356
fprintf (p->out, "\n");
1361
if (p->cnt++ == 0 && p->showHeader)
1363
for (i = 0; i < nArg; i++)
1365
output_csv (p, azCol[i] ? azCol[i] : "",
1368
fprintf (p->out, "\n");
1372
for (i = 0; i < nArg; i++)
1374
/* Sandro Furieri 11 July 2008
1375
output_csv (p, azArg[i], i < nArg - 1);
1378
output_csv (p, azArg[i], i < nArg - 1);
1381
len = strlen (azArg[i]) + 1;
1384
buf = malloc (len * 4);
1385
strcpy (buf, azArg[i]);
1386
convert_from_utf8 (buf, len * 4);
1387
output_csv (p, buf, i < nArg - 1);
1389
/* end Sandro Furieri 11 July 2008 */
1391
fprintf (p->out, "\n");
1398
fprintf (p->out, "INSERT INTO %s VALUES(", p->zDestTable);
1399
for (i = 0; i < nArg; i++)
1401
char *zSep = i > 0 ? "," : "";
1404
fprintf (p->out, "%sNULL", zSep);
1406
else if (isNumber (azArg[i], 0))
1408
fprintf (p->out, "%s%s", zSep, azArg[i]);
1413
fprintf (p->out, "%s", zSep);
1414
/* Sandro Furieri 11 July 2008
1415
output_quoted_string (p->out, azArg[i]);
1418
output_quoted_string (p->out, azArg[i]);
1421
len = strlen (azArg[i]) + 1;
1424
buf = malloc (len * 4);
1425
strcpy (buf, azArg[i]);
1426
convert_from_utf8 (buf, len * 4);
1427
output_quoted_string (p->out, buf);
1429
/* end Sandro Furieri 11 July 2008 */
1432
fprintf (p->out, ");\n");
1442
** Set the destination table field of the callback_data structure to
1443
** the name of the table given. Escape any quote characters in the
1447
set_table_name (struct callback_data *p, const char *zName)
1455
free (p->zDestTable);
1460
needQuote = !isalpha ((unsigned char) *zName) && *zName != '_';
1461
for (i = n = 0; zName[i]; i++, n++)
1463
if (!isalnum ((unsigned char) zName[i]) && zName[i] != '_')
1466
if (zName[i] == '\'')
1472
z = p->zDestTable = malloc (n + 1);
1475
fprintf (stderr, "Out of memory!\n");
1481
for (i = 0; zName[i]; i++)
1484
if (zName[i] == '\'')
1492
/* zIn is either a pointer to a NULL-terminated string in memory obtained
1493
** from malloc(), or a NULL pointer. The string pointed to by zAppend is
1494
** added to zIn, and the result returned in memory obtained from malloc().
1495
** zIn, if it was not NULL, is freed.
1497
** If the third argument, quote, is not '\0', then it is used as a
1498
** quote character for zAppend.
1501
appendText (char *zIn, char const *zAppend, char quote)
1505
int nAppend = strlen (zAppend);
1506
int nIn = (zIn ? strlen (zIn) : 0);
1508
len = nAppend + nIn + 1;
1512
for (i = 0; i < nAppend; i++)
1514
if (zAppend[i] == quote)
1519
zIn = (char *) realloc (zIn, len);
1527
char *zCsr = &zIn[nIn];
1529
for (i = 0; i < nAppend; i++)
1531
*zCsr++ = zAppend[i];
1532
if (zAppend[i] == quote)
1537
assert ((zCsr - zIn) == len);
1541
memcpy (&zIn[nIn], zAppend, nAppend);
1542
zIn[len - 1] = '\0';
1550
** Execute a query statement that has a single result column. Print
1551
** that result column on a line by itself with a semicolon terminator.
1553
** This is used, for example, to show the schema of the database by
1554
** querying the SQLITE_MASTER table.
1557
run_table_dump_query (FILE * out, sqlite3 * db, const char *zSelect)
1559
sqlite3_stmt *pSelect;
1561
rc = sqlite3_prepare (db, zSelect, -1, &pSelect, 0);
1562
if (rc != SQLITE_OK || !pSelect)
1566
rc = sqlite3_step (pSelect);
1567
while (rc == SQLITE_ROW)
1569
fprintf (out, "%s;\n", sqlite3_column_text (pSelect, 0));
1570
rc = sqlite3_step (pSelect);
1572
return sqlite3_finalize (pSelect);
1577
** This is a different callback routine used for dumping the database.
1578
** Each row received by this callback consists of a table name,
1579
** the table type ("index" or "table") and SQL to create the table.
1580
** This routine should print text sufficient to recreate the table.
1583
dump_callback (void *pArg, int nArg, char **azArg, char **azCol)
1589
struct callback_data *p = (struct callback_data *) pArg;
1592
azCol = NULL; /* suppressing stupid compiler warnings [unused] */
1599
if (strcmp (zTable, "sqlite_sequence") == 0)
1601
fprintf (p->out, "DELETE FROM sqlite_sequence;\n");
1603
else if (strcmp (zTable, "sqlite_stat1") == 0)
1605
fprintf (p->out, "ANALYZE sqlite_master;\n");
1607
else if (strncmp (zTable, "sqlite_", 7) == 0)
1611
else if (strncmp (zSql, "CREATE VIRTUAL TABLE", 20) == 0)
1614
if (!p->writableSchema)
1616
fprintf (p->out, "PRAGMA writable_schema=ON;\n");
1617
p->writableSchema = 1;
1621
("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
1622
"VALUES('table','%q','%q',0,'%q');", zTable, zTable, zSql);
1623
fprintf (p->out, "%s\n", zIns);
1624
sqlite3_free (zIns);
1629
fprintf (p->out, "%s;\n", zSql);
1632
if (strcmp (zType, "table") == 0)
1634
sqlite3_stmt *pTableInfo = 0;
1636
char *zTableInfo = 0;
1639
zTableInfo = appendText (zTableInfo, "PRAGMA table_info(", 0);
1640
zTableInfo = appendText (zTableInfo, zTable, '"');
1641
zTableInfo = appendText (zTableInfo, ");", 0);
1643
rc = sqlite3_prepare (p->db, zTableInfo, -1, &pTableInfo, 0);
1646
if (rc != SQLITE_OK || !pTableInfo)
1651
zSelect = appendText (zSelect, "SELECT 'INSERT INTO ' || ", 0);
1652
zTmp = appendText (zTmp, zTable, '"');
1655
zSelect = appendText (zSelect, zTmp, '\'');
1658
zSelect = appendText (zSelect, " || ' VALUES(' || ", 0);
1659
rc = sqlite3_step (pTableInfo);
1660
while (rc == SQLITE_ROW)
1663
(const char *) sqlite3_column_text (pTableInfo, 1);
1664
zSelect = appendText (zSelect, "quote(", 0);
1665
zSelect = appendText (zSelect, zText, '"');
1666
rc = sqlite3_step (pTableInfo);
1667
if (rc == SQLITE_ROW)
1669
zSelect = appendText (zSelect, ") || ',' || ", 0);
1673
zSelect = appendText (zSelect, ") ", 0);
1676
rc = sqlite3_finalize (pTableInfo);
1677
if (rc != SQLITE_OK)
1683
zSelect = appendText (zSelect, "|| ')' FROM ", 0);
1684
zSelect = appendText (zSelect, zTable, '"');
1686
rc = run_table_dump_query (p->out, p->db, zSelect);
1687
if (rc == SQLITE_CORRUPT)
1689
zSelect = appendText (zSelect, " ORDER BY rowid DESC", 0);
1690
rc = run_table_dump_query (p->out, p->db, zSelect);
1699
spatialite_autocreate (sqlite3 * db)
1701
/* attempting to perform self-initialization for a newly created DB */
1704
char *err_msg = NULL;
1711
/* checking if this DB is really empty */
1712
strcpy (sql, "SELECT Count(*) from sqlite_master");
1713
ret = sqlite3_get_table (db, sql, &results, &rows, &columns, NULL);
1714
if (ret != SQLITE_OK)
1720
for (i = 1; i <= rows; i++)
1721
count = atoi (results[(i * columns) + 0]);
1723
sqlite3_free_table (results);
1728
/* all right, it's empty: proceding to initialize */
1729
strcpy (sql, "SELECT InitSpatialMetadata()");
1730
ret = sqlite3_exec (db, sql, NULL, NULL, &err_msg);
1731
if (ret != SQLITE_OK)
1733
fprintf (stderr, "InitSpatialMetadata() error: %s\n", err_msg);
1734
sqlite3_free (err_msg);
1737
spatial_ref_sys_init (db, 1);
1741
** Run zQuery. Use dump_callback() as the callback routine so that
1742
** the contents of the query are output as SQL statements.
1744
** If we get a SQLITE_CORRUPT error, rerun the query after appending
1745
** "ORDER BY rowid DESC" to the end.
1748
run_schema_dump_query (struct callback_data *p,
1749
const char *zQuery, char **pzErrMsg)
1752
rc = sqlite3_exec (p->db, zQuery, dump_callback, p, pzErrMsg);
1753
if (rc == SQLITE_CORRUPT)
1756
int len = strlen (zQuery);
1758
sqlite3_free (*pzErrMsg);
1759
zQ2 = malloc (len + 100);
1762
sqlite3_snprintf (sizeof (zQ2), zQ2, "%s ORDER BY rowid DESC",
1764
rc = sqlite3_exec (p->db, zQ2, dump_callback, p, pzErrMsg);
1771
** Text of a help message
1773
static char zHelp[] =
1774
".bail ON|OFF Stop after hitting an error. Default OFF\n"
1775
".databases List names and files of attached databases\n"
1776
".dump ?TABLE? ... Dump the database in an SQL text format\n"
1777
".echo ON|OFF Turn command echo on or off\n"
1778
".exit Exit this program\n"
1779
".explain ON|OFF Turn output mode suitable for EXPLAIN on or off.\n"
1780
".header(s) ON|OFF Turn display of headers on or off\n"
1781
".help Show this message\n"
1782
".import FILE TABLE Import data from FILE into TABLE\n"
1783
".indices TABLE Show names of all indices on TABLE\n"
1784
#ifdef SQLITE_ENABLE_IOTRACE
1785
".iotrace FILE Enable I/O diagnostic logging to FILE\n"
1787
#ifndef SQLITE_OMIT_LOAD_EXTENSION
1788
".load FILE ?ENTRY? Load an extension library\n"
1790
".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
1791
" csv Comma-separated values\n"
1792
" column Left-aligned columns. (See .width)\n"
1793
" html HTML <table> code\n"
1794
" insert SQL insert statements for TABLE\n"
1795
" line One value per line\n"
1796
" list Values delimited by .separator string\n"
1797
" tabs Tab-separated values\n"
1798
" tcl TCL list elements\n"
1799
".nullvalue STRING Print STRING in place of NULL values\n"
1800
".output FILENAME Send output to FILENAME\n"
1801
".output stdout Send output to the screen\n"
1802
".prompt MAIN CONTINUE Replace the standard prompts\n"
1803
".quit Exit this program\n"
1804
".schema ?TABLE? Show the CREATE statements\n"
1805
".separator STRING Change separator used by output mode and .import\n"
1806
".show Show the current values for various settings\n"
1807
".tables ?PATTERN? List names of tables matching a LIKE pattern\n"
1808
".timeout MS Try opening locked tables for MS milliseconds\n"
1810
".timer ON|OFF Turn the CPU timer measurement on or off\n"
1812
".width NUM NUM ... Set column widths for \"column\" mode\n"
1813
/* Sandro Furieri 2008-06-20 */
1814
"\n====================== SpatiaLite ========================================\n\n"
1815
".charset Report the current locale charset setting\n\n"
1816
".charset <charset-name>\n"
1817
" Set the charset encoding according to the command shell\n"
1818
" e.g.: when working on Windows Command Prompt, if you notice\n"
1819
" 'strange' chars, a very good idea may be to type\n"
1820
" the following command:\n"
1822
" [use the Windows CHCP command in order to check better\n"
1823
" which one charset is used on your Command Prompt]\n\n"
1824
".chkdupl <table> Check a TABLE for duplicated rows\n\n"
1825
".remdupl <table> Removes any duplicated row from a TABLE\n\n"
1826
".loadshp <args> Loads a SHAPEFILE into a SpatiaLite table\n"
1827
" arg_list: shp_path table_name charset [SRID] [column_name]\n"
1828
" [2d | 3d] [compressed]\n\n"
1829
".dumpshp <args> Dumps a SpatiaLite table into a SHAPEFILE\n"
1830
" arg_list: table_name column_name shp_path charset [geom_type]\n"
1831
" geom_type={ POINT | LINESTRING | POLYGON | MULTIPOINT }\n\n"
1832
".loaddbf <args> Loads a DBF into a SpatiaLite table\n"
1833
" arg_list: dbf_path table_name charset\n\n"
1834
".dumpdbf <args> Dumps a SpatiaLite table into a DBF\n"
1835
" arg_list: table_name dbf_path charset\n\n"
1836
".loadxl <args> Loads a XL spreadsheet (.xls) into a SpatiaLite table\n"
1837
" arg_list: xl_path table_name \n"
1838
" [worksheet_index [first_line_titles{0/1}]]\n\n"
1839
".dumpkml <args> Dumps a SpatiaLite table as a KML file\n"
1840
" arg_list: table_name geom_column kml_path\n"
1841
" [precision] [name_column] [desc_column]\n\n"
1842
".read <args> Execute an SQL script\n"
1843
" arg_list: script_path charset\n"
1844
/* end Sandro Furieri 2008-06-20 */
1847
/* Forward reference */
1848
static int process_input (struct callback_data *p, FILE * in, char *in_charset);
1851
** Make sure the database is open. If it is not, then open it. If
1852
** the database fails to open, print an error message and exit.
1855
open_db (struct callback_data *p)
1859
sqlite3_open (p->zDbFilename, &p->db);
1861
if (db && sqlite3_errcode (db) == SQLITE_OK)
1863
sqlite3_create_function (db, "shellstatic", 0, SQLITE_UTF8, 0,
1864
shellstaticFunc, 0, 0);
1866
if (db == 0 || SQLITE_OK != sqlite3_errcode (db))
1868
fprintf (stderr, "Unable to open database \"%s\": %s\n",
1869
p->zDbFilename, sqlite3_errmsg (db));
1872
#ifndef SQLITE_OMIT_LOAD_EXTENSION
1873
sqlite3_enable_load_extension (p->db, 1);
1876
/* Sandro Furieri 2009-11-08 */
1877
sqlite3_exec (p->db, "PRAGMA foreign_keys = 1", NULL, 0, NULL);
1878
/* end Sandro Furieri 2008-11-08 */
1879
/* Sandro Furieri 2010-08-07 */
1880
spatialite_autocreate (p->db);
1881
/* end Sandro Furieri 2010-08-07 */
1886
** Do C-language style dequoting.
1890
** \r -> carriage return
1891
** \NNN -> ascii character NNN in octal
1895
resolve_backslashes (char *z)
1898
for (i = j = 0; (c = z[i]) != 0; i++, j++)
1915
else if (c >= '0' && c <= '7')
1918
if (z[i + 1] >= '0' && z[i + 1] <= '7')
1921
c = (c << 3) + z[i] - '0';
1922
if (z[i + 1] >= '0' && z[i + 1] <= '7')
1925
c = (c << 3) + z[i] - '0';
1936
** Interpret zArg as a boolean value. Return either 0 or 1.
1939
booleanValue (char *zArg)
1941
int val = atoi (zArg);
1943
for (j = 0; zArg[j]; j++)
1945
zArg[j] = tolower (zArg[j]);
1947
if (strcmp (zArg, "on") == 0)
1951
else if (strcmp (zArg, "yes") == 0)
1959
** If an input line begins with "." then invoke this routine to
1960
** process that line.
1962
** Return 1 on error, 2 to exit, and 0 otherwise.
1965
do_meta_command (char *zLine, struct callback_data *p)
1973
/* Parse the input line into tokens.
1975
while (zLine[i] && nArg < (int) ArraySize (azArg))
1977
while (isspace ((unsigned char) zLine[i]))
1983
if (zLine[i] == '\'' || zLine[i] == '"')
1985
int delim = zLine[i++];
1986
azArg[nArg++] = &zLine[i];
1987
while (zLine[i] && zLine[i] != delim)
1991
if (zLine[i] == delim)
1996
resolve_backslashes (azArg[nArg - 1]);
2000
azArg[nArg++] = &zLine[i];
2001
while (zLine[i] && !isspace ((unsigned char) zLine[i]))
2007
resolve_backslashes (azArg[nArg - 1]);
2011
/* Process the input line.
2015
n = strlen (azArg[0]);
2018
/* Sandro Furieri 2008-06-20 */
2019
if (c == 'c' && n > 1 && strncmp (azArg[0], "charset", n) == 0 && nArg == 1)
2021
/* reporting the charset */
2022
if (*spatialite_charset == '\0')
2025
("the shell's default LOCALE CHARSET is currently in use\n");
2030
printf ("the %s charset is currently used as LOCALE CHARSET\n",
2031
spatialite_charset);
2035
else if (c == 'c' && n > 1 && strncmp (azArg[0], "charset", n) == 0
2038
/* setting the charset */
2039
create_utf8_converter (azArg[1]);
2041
else if (c == 'd' && n > 1 && strncmp (azArg[0], "dumpshp", n) == 0
2042
&& (nArg == 5 || nArg == 6))
2044
/* dumping a spatial table to SHAPEFILE */
2045
char *table = azArg[1];
2046
char *column = azArg[2];
2047
char *shp_path = azArg[3];
2048
char *outCS = azArg[4];
2053
dump_shapefile (p->db, table, column, shp_path, outCS, type, 1, NULL);
2055
else if (c == 'd' && n > 1 && strncmp (azArg[0], "dumpdbf", n) == 0
2058
/* dumping a spatial table to DBF */
2059
char *table = azArg[1];
2060
char *dbf_path = azArg[2];
2061
char *outCS = azArg[3];
2063
dump_dbf (p->db, table, dbf_path, outCS);
2065
else if (c == 'd' && n > 1 && strncmp (azArg[0], "dumpkml", n) == 0
2066
&& (nArg == 4 || nArg == 5 || nArg == 6 || nArg == 7))
2068
/* dumping a spatial table as KML file */
2069
char *table = azArg[1];
2070
char *geom = azArg[2];
2071
char *kml_path = azArg[3];
2076
precision = atoi (azArg[4]);
2082
dump_kml (p->db, table, geom, kml_path, name, desc, precision);
2084
else if (c == 'l' && n > 1 && strncmp (azArg[0], "loadshp", n) == 0
2085
&& (nArg == 4 || nArg == 5 || nArg == 6 || nArg == 7 || nArg == 8))
2087
char *shp_path = azArg[1];
2088
char *table = azArg[2];
2089
char *inCS = azArg[3];
2093
char *column = NULL;
2095
srid = atoi (azArg[4]);
2100
if (strcasecmp (azArg[6], "2d") == 0)
2106
load_shapefile (p->db, shp_path, table, inCS, srid, column, coerce2d,
2107
compressed, 1, NULL);
2109
else if (c == 'l' && n > 1 && strncmp (azArg[0], "loaddbf", n) == 0
2112
char *dbf_path = azArg[1];
2113
char *table = azArg[2];
2114
char *inCS = azArg[3];
2116
load_dbf (p->db, dbf_path, table, inCS, 1, NULL);
2118
else if (c == 'l' && n > 1 && strncmp (azArg[0], "loadxl", n) == 0
2119
&& (nArg == 3 || nArg == 4 || nArg == 5))
2121
char *xl_path = azArg[1];
2122
char *table = azArg[2];
2123
unsigned int worksheet = 0;
2125
if (nArg == 4 || nArg == 5)
2126
worksheet = atoi (azArg[3]);
2129
if (atoi (azArg[4]) == 1)
2133
load_XL (p->db, xl_path, table, worksheet, firstLine);
2135
else if (c == 'r' && strncmp (azArg[0], "read", n) == 0)
2141
"invalid arguments: .read script_path charset\n");
2144
alt = fopen (azArg[1], "rb");
2147
fprintf (stderr, "can't open \"%s\"\n", azArg[1]);
2151
process_input (p, alt, azArg[2]);
2155
else if (c == 'c' && strncmp (azArg[0], "chkdupl", n) == 0 && nArg == 2)
2157
char *table = azArg[1];
2159
check_duplicated_rows (p->db, table);
2161
else if (c == 'r' && strncmp (azArg[0], "remdupl", n) == 0 && nArg == 2)
2163
char *table = azArg[1];
2165
remove_duplicated_rows (p->db, table);
2167
else if (c == 'b' && n > 1 && strncmp (azArg[0], "bail", n) == 0
2170
bail_on_error = booleanValue (azArg[1]);
2172
else if (c == 'd' && n > 1 && strncmp (azArg[0], "databases", n) == 0)
2174
struct callback_data data;
2177
memcpy (&data, p, sizeof (data));
2178
data.showHeader = 1;
2179
data.mode = MODE_Column;
2180
data.colWidth[0] = 3;
2181
data.colWidth[1] = 15;
2182
data.colWidth[2] = 58;
2184
sqlite3_exec (p->db, "PRAGMA database_list; ", callback, &data,
2188
fprintf (stderr, "Error: %s\n", zErrMsg);
2189
sqlite3_free (zErrMsg);
2192
else if (c == 'd' && strncmp (azArg[0], "dump", n) == 0)
2196
fprintf (p->out, "BEGIN TRANSACTION;\n");
2197
p->writableSchema = 0;
2200
run_schema_dump_query (p,
2201
"SELECT name, type, sql FROM sqlite_master "
2202
"WHERE sql NOT NULL AND type=='table'",
2204
run_table_dump_query (p->out, p->db,
2205
"SELECT sql FROM sqlite_master "
2206
"WHERE sql NOT NULL AND type IN ('index','trigger','view')");
2211
for (i = 1; i < nArg; i++)
2213
zShellStatic = azArg[i];
2214
run_schema_dump_query (p,
2215
"SELECT name, type, sql FROM sqlite_master "
2216
"WHERE tbl_name LIKE shellstatic() AND type=='table'"
2217
" AND sql NOT NULL", 0);
2218
run_table_dump_query (p->out, p->db,
2219
"SELECT sql FROM sqlite_master "
2220
"WHERE sql NOT NULL"
2221
" AND type IN ('index','trigger','view')"
2222
" AND tbl_name LIKE shellstatic()");
2226
if (p->writableSchema)
2228
fprintf (p->out, "PRAGMA writable_schema=OFF;\n");
2229
p->writableSchema = 0;
2233
fprintf (stderr, "Error: %s\n", zErrMsg);
2234
sqlite3_free (zErrMsg);
2238
fprintf (p->out, "COMMIT;\n");
2241
else if (c == 'e' && strncmp (azArg[0], "echo", n) == 0 && nArg > 1)
2243
p->echoOn = booleanValue (azArg[1]);
2245
else if (c == 'e' && strncmp (azArg[0], "exit", n) == 0)
2249
else if (c == 'e' && strncmp (azArg[0], "explain", n) == 0)
2251
int val = nArg >= 2 ? booleanValue (azArg[1]) : 1;
2254
if (!p->explainPrev.valid)
2256
p->explainPrev.valid = 1;
2257
p->explainPrev.mode = p->mode;
2258
p->explainPrev.showHeader = p->showHeader;
2259
memcpy (p->explainPrev.colWidth, p->colWidth,
2260
sizeof (p->colWidth));
2262
/* We could put this code under the !p->explainValid
2263
** condition so that it does not execute if we are already in
2264
** explain mode. However, always executing it allows us an easy
2265
** was to reset to explain mode in case the user previously
2266
** did an .explain followed by a .width, .mode or .header
2269
p->mode = MODE_Explain;
2271
memset (p->colWidth, 0, ArraySize (p->colWidth));
2272
p->colWidth[0] = 4; /* addr */
2273
p->colWidth[1] = 13; /* opcode */
2274
p->colWidth[2] = 4; /* P1 */
2275
p->colWidth[3] = 4; /* P2 */
2276
p->colWidth[4] = 4; /* P3 */
2277
p->colWidth[5] = 13; /* P4 */
2278
p->colWidth[6] = 2; /* P5 */
2279
p->colWidth[7] = 13; /* Comment */
2281
else if (p->explainPrev.valid)
2283
p->explainPrev.valid = 0;
2284
p->mode = p->explainPrev.mode;
2285
p->showHeader = p->explainPrev.showHeader;
2286
memcpy (p->colWidth, p->explainPrev.colWidth,
2287
sizeof (p->colWidth));
2290
else if (c == 'h' && (strncmp (azArg[0], "header", n) == 0 ||
2291
strncmp (azArg[0], "headers", n) == 0) && nArg > 1)
2293
p->showHeader = booleanValue (azArg[1]);
2295
else if (c == 'h' && strncmp (azArg[0], "help", n) == 0)
2297
fprintf (stderr, zHelp);
2299
else if (c == 'i' && strncmp (azArg[0], "import", n) == 0 && nArg >= 3)
2301
char *zTable = azArg[2]; /* Insert data into this table */
2302
char *zFile = azArg[1]; /* The file from which to extract data */
2303
sqlite3_stmt *pStmt; /* A statement */
2304
int rc; /* Result code */
2305
int nCol; /* Number of columns in the table */
2306
int nByte; /* Number of bytes in an SQL string */
2307
int i, j; /* Loop counters */
2308
int nSep; /* Number of bytes in p->separator[] */
2309
char *zSql; /* An SQL statement */
2310
char *zLine; /* A single line of input from the file */
2311
char **azCol; /* zLine[] broken up into columns */
2312
char *zCommit; /* How to commit changes */
2313
FILE *in; /* The input file */
2314
int lineno = 0; /* Line number of input file */
2317
nSep = strlen (p->separator);
2320
fprintf (stderr, "non-null separator required for import\n");
2323
zSql = sqlite3_mprintf ("SELECT * FROM '%q'", zTable);
2326
nByte = strlen (zSql);
2327
rc = sqlite3_prepare (p->db, zSql, -1, &pStmt, 0);
2328
sqlite3_free (zSql);
2331
fprintf (stderr, "Error: %s\n", sqlite3_errmsg (db));
2337
nCol = sqlite3_column_count (pStmt);
2339
sqlite3_finalize (pStmt);
2342
zSql = malloc (nByte + 20 + nCol * 2);
2345
sqlite3_snprintf (nByte + 20, zSql, "INSERT INTO '%q' VALUES(?",
2348
for (i = 1; i < nCol; i++)
2355
rc = sqlite3_prepare (p->db, zSql, -1, &pStmt, 0);
2359
fprintf (stderr, "Error: %s\n", sqlite3_errmsg (db));
2360
sqlite3_finalize (pStmt);
2363
in = fopen (zFile, "rb");
2366
fprintf (stderr, "cannot open file: %s\n", zFile);
2367
sqlite3_finalize (pStmt);
2370
azCol = malloc (sizeof (azCol[0]) * (nCol + 1));
2376
sqlite3_exec (p->db, "BEGIN", 0, 0, 0);
2378
while ((zLine = local_getline (0, in)) != 0)
2384
for (i = 0, z = zLine; *z && *z != '\n' && *z != '\r'; z++)
2386
if (*z == p->separator[0]
2387
&& strncmp (z, p->separator, nSep) == 0)
2393
azCol[i] = &z[nSep];
2402
"%s line %d: expected %d columns of data but found %d\n",
2403
zFile, lineno, nCol, i + 1);
2404
zCommit = "ROLLBACK";
2407
for (i = 0; i < nCol; i++)
2409
sqlite3_bind_text (pStmt, i + 1, azCol[i], -1,
2412
sqlite3_step (pStmt);
2413
rc = sqlite3_reset (pStmt);
2415
if (rc != SQLITE_OK)
2417
fprintf (stderr, "Error: %s\n", sqlite3_errmsg (db));
2418
zCommit = "ROLLBACK";
2425
sqlite3_finalize (pStmt);
2426
sqlite3_exec (p->db, zCommit, 0, 0, 0);
2428
else if (c == 'i' && strncmp (azArg[0], "indices", n) == 0 && nArg > 1)
2430
struct callback_data data;
2433
memcpy (&data, p, sizeof (data));
2434
data.showHeader = 0;
2435
data.mode = MODE_List;
2436
zShellStatic = azArg[1];
2437
sqlite3_exec (p->db,
2438
"SELECT name FROM sqlite_master "
2439
"WHERE type='index' AND tbl_name LIKE shellstatic() "
2441
"SELECT name FROM sqlite_temp_master "
2442
"WHERE type='index' AND tbl_name LIKE shellstatic() "
2443
"ORDER BY 1", callback, &data, &zErrMsg);
2447
fprintf (stderr, "Error: %s\n", zErrMsg);
2448
sqlite3_free (zErrMsg);
2452
#ifdef SQLITE_ENABLE_IOTRACE
2453
if (c == 'i' && strncmp (azArg[0], "iotrace", n) == 0)
2455
extern void (*sqlite3IoTrace) (const char *, ...);
2456
if (iotrace && iotrace != stdout)
2463
else if (strcmp (azArg[1], "-") == 0)
2465
sqlite3IoTrace = iotracePrintf;
2470
iotrace = fopen (azArg[1], "w");
2473
fprintf (stderr, "cannot open \"%s\"\n", azArg[1]);
2478
sqlite3IoTrace = iotracePrintf;
2485
#ifndef SQLITE_OMIT_LOAD_EXTENSION
2486
if (c == 'l' && strncmp (azArg[0], "load", n) == 0 && nArg >= 2)
2488
const char *zFile, *zProc;
2492
zProc = nArg >= 3 ? azArg[2] : 0;
2494
rc = sqlite3_load_extension (p->db, zFile, zProc, &zErrMsg);
2495
if (rc != SQLITE_OK)
2497
fprintf (stderr, "%s\n", zErrMsg);
2498
sqlite3_free (zErrMsg);
2505
if (c == 'm' && strncmp (azArg[0], "mode", n) == 0 && nArg >= 2)
2507
int n2 = strlen (azArg[1]);
2508
if (strncmp (azArg[1], "line", n2) == 0
2509
|| strncmp (azArg[1], "lines", n2) == 0)
2511
p->mode = MODE_Line;
2513
else if (strncmp (azArg[1], "column", n2) == 0
2514
|| strncmp (azArg[1], "columns", n2) == 0)
2516
p->mode = MODE_Column;
2518
else if (strncmp (azArg[1], "list", n2) == 0)
2520
p->mode = MODE_List;
2522
else if (strncmp (azArg[1], "html", n2) == 0)
2524
p->mode = MODE_Html;
2526
else if (strncmp (azArg[1], "tcl", n2) == 0)
2530
else if (strncmp (azArg[1], "csv", n2) == 0)
2533
sqlite3_snprintf (sizeof (p->separator), p->separator, ",");
2535
else if (strncmp (azArg[1], "tabs", n2) == 0)
2537
p->mode = MODE_List;
2538
sqlite3_snprintf (sizeof (p->separator), p->separator, "\t");
2540
else if (strncmp (azArg[1], "insert", n2) == 0)
2542
p->mode = MODE_Insert;
2545
set_table_name (p, azArg[2]);
2549
set_table_name (p, "table");
2554
fprintf (stderr, "mode should be one of: "
2555
"column csv html insert line list tabs tcl\n");
2558
else if (c == 'n' && strncmp (azArg[0], "nullvalue", n) == 0 && nArg == 2)
2560
sqlite3_snprintf (sizeof (p->nullvalue), p->nullvalue,
2561
"%.*s", (int) ArraySize (p->nullvalue) - 1,
2564
else if (c == 'o' && strncmp (azArg[0], "output", n) == 0 && nArg == 2)
2566
if (p->out != stdout)
2570
if (strcmp (azArg[1], "stdout") == 0)
2573
sqlite3_snprintf (sizeof (p->outfile), p->outfile, "stdout");
2577
p->out = fopen (azArg[1], "wb");
2580
fprintf (stderr, "can't write to \"%s\"\n", azArg[1]);
2585
sqlite3_snprintf (sizeof (p->outfile), p->outfile, "%s",
2590
else if (c == 'p' && strncmp (azArg[0], "prompt", n) == 0
2591
&& (nArg == 2 || nArg == 3))
2595
strncpy (mainPrompt, azArg[1],
2596
(int) ArraySize (mainPrompt) - 1);
2600
strncpy (continuePrompt, azArg[2],
2601
(int) ArraySize (continuePrompt) - 1);
2604
else if (c == 'q' && strncmp (azArg[0], "quit", n) == 0)
2608
else if (c == 's' && strncmp (azArg[0], "schema", n) == 0)
2610
struct callback_data data;
2613
memcpy (&data, p, sizeof (data));
2614
data.showHeader = 0;
2615
data.mode = MODE_Semi;
2619
for (i = 0; azArg[1][i]; i++)
2620
azArg[1][i] = tolower (azArg[1][i]);
2621
if (strcmp (azArg[1], "sqlite_master") == 0)
2623
char *new_argv[2], *new_colv[2];
2624
new_argv[0] = "CREATE TABLE sqlite_master (\n"
2628
" rootpage integer,\n" " sql text\n" ")";
2630
new_colv[0] = "sql";
2632
callback (&data, 1, new_argv, new_colv);
2634
else if (strcmp (azArg[1], "sqlite_temp_master") == 0)
2636
char *new_argv[2], *new_colv[2];
2637
new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
2641
" rootpage integer,\n" " sql text\n" ")";
2643
new_colv[0] = "sql";
2645
callback (&data, 1, new_argv, new_colv);
2649
zShellStatic = azArg[1];
2650
sqlite3_exec (p->db,
2652
" (SELECT * FROM sqlite_master UNION ALL"
2653
" SELECT * FROM sqlite_temp_master) "
2654
"WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
2655
"ORDER BY substr(type,2,1), name",
2656
callback, &data, &zErrMsg);
2662
sqlite3_exec (p->db,
2664
" (SELECT * FROM sqlite_master UNION ALL"
2665
" SELECT * FROM sqlite_temp_master) "
2666
"WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
2667
"ORDER BY substr(type,2,1), name",
2668
callback, &data, &zErrMsg);
2672
fprintf (stderr, "Error: %s\n", zErrMsg);
2673
sqlite3_free (zErrMsg);
2676
else if (c == 's' && strncmp (azArg[0], "separator", n) == 0 && nArg == 2)
2678
sqlite3_snprintf (sizeof (p->separator), p->separator,
2679
"%.*s", (int) sizeof (p->separator) - 1, azArg[1]);
2681
else if (c == 's' && strncmp (azArg[0], "show", n) == 0)
2684
fprintf (p->out, "%9.9s: %s\n", "echo", p->echoOn ? "on" : "off");
2685
fprintf (p->out, "%9.9s: %s\n", "explain",
2686
p->explainPrev.valid ? "on" : "off");
2687
fprintf (p->out, "%9.9s: %s\n", "headers",
2688
p->showHeader ? "on" : "off");
2689
fprintf (p->out, "%9.9s: %s\n", "mode", modeDescr[p->mode]);
2690
fprintf (p->out, "%9.9s: ", "nullvalue");
2691
output_c_string (p->out, p->nullvalue);
2692
fprintf (p->out, "\n");
2693
fprintf (p->out, "%9.9s: %s\n", "output",
2694
strlen (p->outfile) ? p->outfile : "stdout");
2695
fprintf (p->out, "%9.9s: ", "separator");
2696
output_c_string (p->out, p->separator);
2697
fprintf (p->out, "\n");
2698
fprintf (p->out, "%9.9s: ", "width");
2699
for (i = 0; i < (int) ArraySize (p->colWidth) && p->colWidth[i] != 0;
2702
fprintf (p->out, "%d ", p->colWidth[i]);
2704
fprintf (p->out, "\n");
2706
else if (c == 't' && n > 1 && strncmp (azArg[0], "tables", n) == 0)
2714
rc = sqlite3_get_table (p->db,
2715
"SELECT name FROM sqlite_master "
2716
"WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'"
2718
"SELECT name FROM sqlite_temp_master "
2719
"WHERE type IN ('table','view') "
2721
&azResult, &nRow, 0, &zErrMsg);
2725
zShellStatic = azArg[1];
2726
rc = sqlite3_get_table (p->db,
2727
"SELECT name FROM sqlite_master "
2728
"WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' "
2730
"SELECT name FROM sqlite_temp_master "
2731
"WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' "
2733
&azResult, &nRow, 0, &zErrMsg);
2738
fprintf (stderr, "Error: %s\n", zErrMsg);
2739
sqlite3_free (zErrMsg);
2741
if (rc == SQLITE_OK)
2743
int len, maxlen = 0;
2745
int nPrintCol, nPrintRow;
2746
for (i = 1; i <= nRow; i++)
2748
if (azResult[i] == 0)
2750
len = strlen (azResult[i]);
2754
nPrintCol = 80 / (maxlen + 2);
2757
nPrintRow = (nRow + nPrintCol - 1) / nPrintCol;
2758
for (i = 0; i < nPrintRow; i++)
2760
for (j = i + 1; j <= nRow; j += nPrintRow)
2762
char *zSp = j <= nPrintRow ? "" : " ";
2763
printf ("%s%-*s", zSp, maxlen,
2764
azResult[j] ? azResult[j] : "");
2773
sqlite3_free_table (azResult);
2775
else if (c == 't' && n > 4 && strncmp (azArg[0], "timeout", n) == 0
2779
sqlite3_busy_timeout (p->db, atoi (azArg[1]));
2783
if (c == 't' && n >= 5 && strncmp (azArg[0], "timer", n) == 0 && nArg > 1)
2785
enableTimer = booleanValue (azArg[1]);
2790
if (c == 'w' && strncmp (azArg[0], "width", n) == 0)
2793
assert (nArg <= (int) ArraySize (azArg));
2794
for (j = 1; j < nArg && j < (int) ArraySize (p->colWidth); j++)
2796
p->colWidth[j - 1] = atoi (azArg[j]);
2803
fprintf (stderr, "unknown command or invalid arguments: "
2804
" \"%s\". Enter \".help\" for help\n", azArg[0]);
2811
** Return TRUE if a semicolon occurs anywhere in the first N characters
2815
_contains_semicolon (const char *z, int N)
2818
for (i = 0; i < N; i++)
2827
** Test to see if a line consists entirely of whitespace.
2830
_all_whitespace (const char *z)
2834
if (isspace (*(unsigned char *) z))
2836
if (*z == '/' && z[1] == '*')
2839
while (*z && (*z != '*' || z[1] != '/'))
2848
if (*z == '-' && z[1] == '-')
2851
while (*z && *z != '\n')
2865
** Return TRUE if the line typed in is an SQL command terminator other
2866
** than a semi-colon. The SQL Server style "go" command is understood
2867
** as is the Oracle "/".
2870
_is_command_terminator (const char *zLine)
2872
while (isspace (*(unsigned char *) zLine))
2876
if (zLine[0] == '/' && _all_whitespace (&zLine[1]))
2877
return 1; /* Oracle */
2878
if (tolower (zLine[0]) == 'g' && tolower (zLine[1]) == 'o'
2879
&& _all_whitespace (&zLine[2]))
2881
return 1; /* SQL Server */
2887
** Read input from *in and process it. If *in==0 then input
2888
** is interactive - the user is typing it it. Otherwise, input
2889
** is coming from a file or device. A prompt is issued and history
2890
** is saved only if input is interactive. An interrupt signal will
2891
** cause this routine to exit immediately, unless input is interactive.
2893
** Return the number of errors.
2896
process_input (struct callback_data *p, FILE * in, char *in_charset)
2900
/* Sandro Furieri - 11 July 2008 - supporting UNICODE */
2903
/* End Sandro Furieri - 11 July 2008 */
2912
/* Sandro Furieri - 11 July 2008 - supporting UNICODE */
2914
create_input_utf8_converter (in_charset);
2915
/* End Sandro Furieri - 11 July 2008 */
2917
while (errCnt == 0 || !bail_on_error || (in == 0 && stdin_is_interactive))
2921
zLine = one_input_line (zSql, in);
2924
break; /* We have reached EOF */
2934
printf ("%s\n", zLine);
2935
if ((zSql == 0 || zSql[0] == 0) && _all_whitespace (zLine))
2937
if (zLine && zLine[0] == '.' && nSql == 0)
2939
rc = do_meta_command (zLine, p);
2950
if (_is_command_terminator (zLine))
2952
memcpy (zLine, ";", 2);
2958
for (i = 0; zLine[i] && isspace ((unsigned char) zLine[i]); i++)
2963
nSql = strlen (zLine);
2964
zSql = malloc (nSql + 1);
2967
fprintf (stderr, "out of memory\n");
2970
memcpy (zSql, zLine, nSql + 1);
2976
int len = strlen (zLine);
2977
zSql = realloc (zSql, nSql + len + 2);
2980
fprintf (stderr, "%s: out of memory!\n", Argv0);
2983
zSql[nSql++] = '\n';
2984
memcpy (&zSql[nSql], zLine, len + 1);
2987
if (zSql && _contains_semicolon (&zSql[nSqlPrior], nSql - nSqlPrior)
2988
&& sqlite3_complete (zSql))
2992
/* Sandro Furieri - 11 July 2008
2994
rc = sqlite3_exec (p->db, zSql, callback, p, &zErrMsg);
2997
utf8len = strlen (zSql) * 4;
2998
utf8Sql = malloc (utf8len);
3001
fprintf (stderr, "%s: out of memory!\n", Argv0);
3004
strncpy (utf8Sql, zSql, utf8len - 1);
3005
utf8Sql[utf8len - 1] = '\0';
3008
/* assuming input is locale_charset encoded */
3009
convert_to_utf8 (utf8Sql, utf8len);
3013
/* input has an explicit charset */
3014
convert_input_to_utf8 (utf8Sql, utf8len);
3017
rc = sqlite3_exec (p->db, utf8Sql, callback, p, &zErrMsg);
3020
/* End Sandro Furieri - 11 July 2008 */
3024
if (in != 0 || !stdin_is_interactive)
3026
sqlite3_snprintf (sizeof (zPrefix), zPrefix,
3027
"SQL error near line %d:",
3032
sqlite3_snprintf (sizeof (zPrefix), zPrefix,
3037
printf ("%s %s\n", zPrefix, zErrMsg);
3038
sqlite3_free (zErrMsg);
3043
printf ("%s %s\n", zPrefix, sqlite3_errmsg (p->db));
3054
if (!_all_whitespace (zSql))
3055
printf ("Incomplete SQL: %s\n", zSql);
3060
/* Sandro Furieri - 11 July 2008 */
3061
if (in_charset_to_utf8)
3063
/* destroying input converter, if exists */
3064
iconv_close (in_charset_to_utf8);
3065
in_charset_to_utf8 = NULL;
3067
/* End Sandro Furieri - 11 July 2008 */
3073
** Return a pathname which is the user's home directory. A
3074
** 0 return indicates an error of some kind. Space to hold the
3075
** resulting string is obtained from malloc(). The calling
3076
** function should free the result.
3079
find_home_dir (void)
3081
char *home_dir = NULL;
3083
#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE)
3084
struct passwd *pwent;
3085
uid_t uid = getuid ();
3086
if ((pwent = getpwuid (uid)) != NULL)
3088
home_dir = pwent->pw_dir;
3092
#if defined(_WIN32_WCE)
3093
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
3095
home_dir = strdup ("/");
3098
#if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
3101
home_dir = getenv ("USERPROFILE");
3107
home_dir = getenv ("HOME");
3110
#if defined(_WIN32) || defined(WIN32) || defined(__OS2__)
3113
char *zDrive, *zPath;
3115
zDrive = getenv ("HOMEDRIVE");
3116
zPath = getenv ("HOMEPATH");
3117
if (zDrive && zPath)
3119
n = strlen (zDrive) + strlen (zPath) + 1;
3120
home_dir = malloc (n);
3123
sqlite3_snprintf (n, home_dir, "%s%s", zDrive, zPath);
3130
#endif /* !_WIN32_WCE */
3134
int n = strlen (home_dir) + 1;
3135
char *z = malloc (n);
3137
memcpy (z, home_dir, n);
3145
** Read input from the file given by sqliterc_override. Or if that
3146
** parameter is NULL, take input from ~/.sqliterc
3149
process_sqliterc (struct callback_data *p, /* Configuration data */
3150
const char *sqliterc_override /* Name of config file. NULL to use default */
3153
char *home_dir = NULL;
3154
const char *sqliterc = sqliterc_override;
3159
if (sqliterc == NULL)
3161
home_dir = find_home_dir ();
3164
fprintf (stderr, "%s: cannot locate your home directory!\n",
3168
nBuf = strlen (home_dir) + 16;
3169
zBuf = malloc (nBuf);
3172
fprintf (stderr, "%s: out of memory!\n", Argv0);
3175
sqlite3_snprintf (nBuf, zBuf, "%s/.sqliterc", home_dir);
3177
sqliterc = (const char *) zBuf;
3179
in = fopen (sqliterc, "rb");
3182
if (stdin_is_interactive)
3184
printf ("-- Loading resources from %s\n", sqliterc);
3186
process_input (p, in, 0);
3194
** Show available command line options
3196
static const char zOptions[] =
3197
" -init filename read/process named file\n"
3198
" -echo print commands before execution\n"
3199
" -[no]header turn headers on or off\n"
3200
" -bail stop after hitting an error\n"
3201
" -interactive force interactive I/O\n"
3202
" -batch force batch I/O\n"
3203
" -column set output mode to 'column'\n"
3204
" -csv set output mode to 'csv'\n"
3205
" -html set output mode to HTML\n"
3206
" -line set output mode to 'line'\n"
3207
" -list set output mode to 'list'\n"
3208
" -separator 'x' set output field separator (|)\n"
3209
" -nullvalue 'text' set text string for NULL values\n"
3210
" -version show SQLite version\n";
3212
usage (int showDetail)
3215
"Usage: %s [OPTIONS] FILENAME [SQL]\n"
3216
"FILENAME is the name of an SQLite database. A new database is created\n"
3217
"if the file does not previously exist.\n", Argv0);
3220
fprintf (stderr, "OPTIONS include:\n%s", zOptions);
3224
fprintf (stderr, "Use the -help option for additional information\n");
3230
** Initialize the state information in data
3233
main_init (struct callback_data *data)
3235
memset (data, 0, sizeof (*data));
3236
data->mode = MODE_List;
3237
memcpy (data->separator, "|", 2);
3238
data->showHeader = 0;
3239
sqlite3_snprintf (sizeof (mainPrompt), mainPrompt, "spatialite> ");
3240
sqlite3_snprintf (sizeof (continuePrompt), continuePrompt, " ...> ");
3244
main (int argc, char **argv)
3247
struct callback_data data;
3248
const char *zInitFile = 0;
3249
char *zFirstCmd = 0;
3257
Sandro Furieri 30 May 2008
3258
===========================
3259
registering the SpatiaLite extension
3261
spatialite_init (1);
3263
stdin_is_interactive = isatty (0);
3265
/* Make sure we have a valid signal handler early, before anything
3269
signal (SIGINT, interrupt_handler);
3272
/* Do an initial pass through the command-line argument to locate
3273
** the name of the database file, the name of the initialization file,
3274
** and the first command to execute.
3276
for (i = 1; i < argc - 1; i++)
3279
if (argv[i][0] != '-')
3282
if (z[0] == '-' && z[1] == '-')
3284
if (strcmp (argv[i], "-separator") == 0
3285
|| strcmp (argv[i], "-nullvalue") == 0)
3289
else if (strcmp (argv[i], "-init") == 0)
3292
zInitFile = argv[i];
3298
data.zDbFilename = (const char *) convertCpPathToUtf8 (argv[i++]);
3300
data.zDbFilename = argv[i++];
3305
#ifndef SQLITE_OMIT_MEMORYDB
3306
data.zDbFilename = ":memory:";
3308
data.zDbFilename = 0;
3313
zFirstCmd = argv[i++];
3317
#ifdef SQLITE_OMIT_MEMORYDB
3318
if (data.zDbFilename == 0)
3320
fprintf (stderr, "%s: no database filename specified\n", argv[0]);
3325
/* Go ahead and open the database file if it already exists. If the
3326
** file does not exist, delay opening it. This prevents empty database
3327
** files from being created if a user mistypes the database name argument
3328
** to the sqlite command-line tool.
3330
if (access (data.zDbFilename, 0) == 0)
3335
/* Process the initialization file if there is one. If no -init option
3336
** is given on the command line, look for a file named ~/.sqliterc and
3337
** try to process it.
3339
process_sqliterc (&data, zInitFile);
3341
/* Make a second pass through the command-line argument and set
3342
** options. This second pass is delayed until after the initialization
3343
** file is processed so that the command-line arguments will override
3344
** settings in the initialization file.
3346
for (i = 1; i < argc && argv[i][0] == '-'; i++)
3353
if (strcmp (z, "-init") == 0)
3357
else if (strcmp (z, "-html") == 0)
3359
data.mode = MODE_Html;
3361
else if (strcmp (z, "-list") == 0)
3363
data.mode = MODE_List;
3365
else if (strcmp (z, "-line") == 0)
3367
data.mode = MODE_Line;
3369
else if (strcmp (z, "-column") == 0)
3371
data.mode = MODE_Column;
3373
else if (strcmp (z, "-csv") == 0)
3375
data.mode = MODE_Csv;
3376
memcpy (data.separator, ",", 2);
3378
else if (strcmp (z, "-separator") == 0)
3381
sqlite3_snprintf (sizeof (data.separator), data.separator,
3382
"%.*s", (int) sizeof (data.separator) - 1,
3385
else if (strcmp (z, "-nullvalue") == 0)
3388
sqlite3_snprintf (sizeof (data.nullvalue), data.nullvalue,
3389
"%.*s", (int) sizeof (data.nullvalue) - 1,
3392
else if (strcmp (z, "-header") == 0)
3394
data.showHeader = 1;
3396
else if (strcmp (z, "-noheader") == 0)
3398
data.showHeader = 0;
3400
else if (strcmp (z, "-echo") == 0)
3404
else if (strcmp (z, "-bail") == 0)
3408
else if (strcmp (z, "-version") == 0)
3410
printf ("%s\n", sqlite3_libversion ());
3413
else if (strcmp (z, "-interactive") == 0)
3415
stdin_is_interactive = 1;
3417
else if (strcmp (z, "-batch") == 0)
3419
stdin_is_interactive = 0;
3421
else if (strcmp (z, "-help") == 0 || strcmp (z, "--help") == 0)
3427
fprintf (stderr, "%s: unknown option: %s\n", Argv0, z);
3428
fprintf (stderr, "Use -help for a list of options.\n");
3435
/* Run just the command that follows the database name
3437
if (zFirstCmd[0] == '.')
3439
do_meta_command (zFirstCmd, &data);
3446
rc = sqlite3_exec (data.db, zFirstCmd, callback, &data,
3448
if (rc != 0 && zErrMsg != 0)
3450
fprintf (stderr, "SQL error: %s\n", zErrMsg);
3457
/* Run commands received from standard input
3459
if (stdin_is_interactive)
3464
/* Sandro Furieri 2008-11-20
3465
printf ("SQLite version ......: %s\n"
3466
"Enter \".help\" for instructions\n",
3467
sqlite3_libversion ());
3470
printf ("SQLite version ......: %s\n",
3471
sqlite3_libversion ());
3472
auto_fdo_start (data.db);
3474
printf ("Enter \".help\" for instructions\n");
3475
/* end Sandro Furieri 2008-11-20 */
3476
zHome = find_home_dir ();
3479
malloc (nHistory = strlen (zHome) + 20)) != 0)
3481
sqlite3_snprintf (nHistory, zHistory,
3482
"%s/.sqlite_history", zHome);
3484
#if defined(HAVE_READLINE) && HAVE_READLINE==1
3486
read_history (zHistory);
3488
rc = process_input (&data, 0, 0);
3491
stifle_history (100);
3492
write_history (zHistory);
3499
rc = process_input (&data, stdin, 0);
3502
set_table_name (&data, 0);
3505
/* Sandro Furieri 2008-11-20 */
3507
/* end Sandro Furieri 2008-11-20 */
3508
if (sqlite3_close (db) != SQLITE_OK)
3510
fprintf (stderr, "error closing database: %s\n",
3511
sqlite3_errmsg (db));
3517
Sandro Furieri 30 May 2008
3518
===========================
3519
memory cleanup for SpatiaLite extension
3521
sqlite3_reset_auto_extension ();