Deleted Added
full compact
shell.c (251886) shell.c (269851)
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.

--- 31 unchanged lines hidden (view full) ---

40# include <signal.h>
41# if !defined(__RTP__) && !defined(_WRS_KERNEL)
42# include <pwd.h>
43# endif
44# include <unistd.h>
45# include <sys/types.h>
46#endif
47
1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.

--- 31 unchanged lines hidden (view full) ---

40# include <signal.h>
41# if !defined(__RTP__) && !defined(_WRS_KERNEL)
42# include <pwd.h>
43# endif
44# include <unistd.h>
45# include <sys/types.h>
46#endif
47
48#ifdef HAVE_EDITLINE
49# include <editline/editline.h>
50#endif
51#if defined(HAVE_READLINE) && HAVE_READLINE==1
48#if defined(HAVE_READLINE) && HAVE_READLINE!=0
52# include <readline/readline.h>
53# include <readline/history.h>
49# include <readline/readline.h>
50# include <readline/history.h>
51#else
52# undef HAVE_READLINE
54#endif
53#endif
55#if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1)
56# define readline(p) local_getline(p,stdin,0)
54#if defined(HAVE_EDITLINE) && !defined(HAVE_READLINE)
55# define HAVE_READLINE 1
56# include <editline/readline.h>
57#endif
58#if !defined(HAVE_READLINE)
57# define add_history(X)
58# define read_history(X)
59# define write_history(X)
60# define stifle_history(X)
61#endif
62
63#if defined(_WIN32) || defined(WIN32)
64# include <io.h>
65#define isatty(h) _isatty(h)
59# define add_history(X)
60# define read_history(X)
61# define write_history(X)
62# define stifle_history(X)
63#endif
64
65#if defined(_WIN32) || defined(WIN32)
66# include <io.h>
67#define isatty(h) _isatty(h)
66#define access(f,m) _access((f),(m))
68#ifndef access
69# define access(f,m) _access((f),(m))
70#endif
67#undef popen
71#undef popen
68#define popen(a,b) _popen((a),(b))
72#define popen _popen
69#undef pclose
73#undef pclose
70#define pclose(x) _pclose(x)
74#define pclose _pclose
71#else
72/* Make sure isatty() has a prototype.
73*/
74extern int isatty(int);
75#else
76/* Make sure isatty() has a prototype.
77*/
78extern int isatty(int);
79
80/* popen and pclose are not C89 functions and so are sometimes omitted from
81** the <stdio.h> header */
82extern FILE *popen(const char*,const char*);
83extern int pclose(FILE*);
75#endif
76
77#if defined(_WIN32_WCE)
78/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
79 * thus we always assume that we have a console. That can be
80 * overridden with the -batch command line option.
81 */
82#define isatty(x) 1
83#endif
84
84#endif
85
86#if defined(_WIN32_WCE)
87/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
88 * thus we always assume that we have a console. That can be
89 * overridden with the -batch command line option.
90 */
91#define isatty(x) 1
92#endif
93
85/* True if the timer is enabled */
86static int enableTimer = 0;
87
88/* ctype macros that work with signed characters */
89#define IsSpace(X) isspace((unsigned char)X)
90#define IsDigit(X) isdigit((unsigned char)X)
91#define ToLower(X) (char)tolower((unsigned char)X)
92
94/* ctype macros that work with signed characters */
95#define IsSpace(X) isspace((unsigned char)X)
96#define IsDigit(X) isdigit((unsigned char)X)
97#define ToLower(X) (char)tolower((unsigned char)X)
98
99
100/* True if the timer is enabled */
101static int enableTimer = 0;
102
103/* Return the current wall-clock time */
104static sqlite3_int64 timeOfDay(void){
105 static sqlite3_vfs *clockVfs = 0;
106 sqlite3_int64 t;
107 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
108 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
109 clockVfs->xCurrentTimeInt64(clockVfs, &t);
110 }else{
111 double r;
112 clockVfs->xCurrentTime(clockVfs, &r);
113 t = (sqlite3_int64)(r*86400000.0);
114 }
115 return t;
116}
117
93#if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \
94 && !defined(__minux)
95#include <sys/time.h>
96#include <sys/resource.h>
97
98/* Saved resource information for the beginning of an operation */
118#if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \
119 && !defined(__minux)
120#include <sys/time.h>
121#include <sys/resource.h>
122
123/* Saved resource information for the beginning of an operation */
99static struct rusage sBegin;
124static struct rusage sBegin; /* CPU time at start */
125static sqlite3_int64 iBegin; /* Wall-clock time at start */
100
101/*
102** Begin timing an operation
103*/
104static void beginTimer(void){
105 if( enableTimer ){
106 getrusage(RUSAGE_SELF, &sBegin);
126
127/*
128** Begin timing an operation
129*/
130static void beginTimer(void){
131 if( enableTimer ){
132 getrusage(RUSAGE_SELF, &sBegin);
133 iBegin = timeOfDay();
107 }
108}
109
110/* Return the difference of two time_structs in seconds */
111static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
112 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
113 (double)(pEnd->tv_sec - pStart->tv_sec);
114}
115
116/*
117** Print the timing results.
118*/
119static void endTimer(void){
120 if( enableTimer ){
121 struct rusage sEnd;
134 }
135}
136
137/* Return the difference of two time_structs in seconds */
138static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
139 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
140 (double)(pEnd->tv_sec - pStart->tv_sec);
141}
142
143/*
144** Print the timing results.
145*/
146static void endTimer(void){
147 if( enableTimer ){
148 struct rusage sEnd;
149 sqlite3_int64 iEnd = timeOfDay();
122 getrusage(RUSAGE_SELF, &sEnd);
150 getrusage(RUSAGE_SELF, &sEnd);
123 printf("CPU Time: user %f sys %f\n",
151 printf("Run Time: real %.3f user %f sys %f\n",
152 (iEnd - iBegin)*0.001,
124 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
125 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
126 }
127}
128
129#define BEGIN_TIMER beginTimer()
130#define END_TIMER endTimer()
131#define HAS_TIMER 1
132
133#elif (defined(_WIN32) || defined(WIN32))
134
135#include <windows.h>
136
137/* Saved resource information for the beginning of an operation */
138static HANDLE hProcess;
139static FILETIME ftKernelBegin;
140static FILETIME ftUserBegin;
153 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
154 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
155 }
156}
157
158#define BEGIN_TIMER beginTimer()
159#define END_TIMER endTimer()
160#define HAS_TIMER 1
161
162#elif (defined(_WIN32) || defined(WIN32))
163
164#include <windows.h>
165
166/* Saved resource information for the beginning of an operation */
167static HANDLE hProcess;
168static FILETIME ftKernelBegin;
169static FILETIME ftUserBegin;
170static sqlite3_int64 ftWallBegin;
141typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
142static GETPROCTIMES getProcessTimesAddr = NULL;
143
144/*
145** Check to see if we have timer support. Return 1 if necessary
146** support found (or found previously).
147*/
148static int hasTimer(void){

--- 21 unchanged lines hidden (view full) ---

170
171/*
172** Begin timing an operation
173*/
174static void beginTimer(void){
175 if( enableTimer && getProcessTimesAddr ){
176 FILETIME ftCreation, ftExit;
177 getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
171typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
172static GETPROCTIMES getProcessTimesAddr = NULL;
173
174/*
175** Check to see if we have timer support. Return 1 if necessary
176** support found (or found previously).
177*/
178static int hasTimer(void){

--- 21 unchanged lines hidden (view full) ---

200
201/*
202** Begin timing an operation
203*/
204static void beginTimer(void){
205 if( enableTimer && getProcessTimesAddr ){
206 FILETIME ftCreation, ftExit;
207 getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin);
208 ftWallBegin = timeOfDay();
178 }
179}
180
181/* Return the difference of two FILETIME structs in seconds */
182static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
183 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
184 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
185 return (double) ((i64End - i64Start) / 10000000.0);
186}
187
188/*
189** Print the timing results.
190*/
191static void endTimer(void){
192 if( enableTimer && getProcessTimesAddr){
193 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
209 }
210}
211
212/* Return the difference of two FILETIME structs in seconds */
213static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
214 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
215 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
216 return (double) ((i64End - i64Start) / 10000000.0);
217}
218
219/*
220** Print the timing results.
221*/
222static void endTimer(void){
223 if( enableTimer && getProcessTimesAddr){
224 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
225 sqlite3_int64 ftWallEnd = timeOfDay();
194 getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
226 getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd);
195 printf("CPU Time: user %f sys %f\n",
227 printf("Run Time: real %.3f user %f sys %f\n",
228 (ftWallEnd - ftWallBegin)*0.001,
196 timeDiff(&ftUserBegin, &ftUserEnd),
197 timeDiff(&ftKernelBegin, &ftKernelEnd));
198 }
199}
200
201#define BEGIN_TIMER beginTimer()
202#define END_TIMER endTimer()
203#define HAS_TIMER hasTimer()

--- 123 unchanged lines hidden (view full) ---

327
328
329/*
330** This routine reads a line of text from FILE in, stores
331** the text in memory obtained from malloc() and returns a pointer
332** to the text. NULL is returned at end of file, or if malloc()
333** fails.
334**
229 timeDiff(&ftUserBegin, &ftUserEnd),
230 timeDiff(&ftKernelBegin, &ftKernelEnd));
231 }
232}
233
234#define BEGIN_TIMER beginTimer()
235#define END_TIMER endTimer()
236#define HAS_TIMER hasTimer()

--- 123 unchanged lines hidden (view full) ---

360
361
362/*
363** This routine reads a line of text from FILE in, stores
364** the text in memory obtained from malloc() and returns a pointer
365** to the text. NULL is returned at end of file, or if malloc()
366** fails.
367**
335** The interface is like "readline" but no command-line editing
336** is done.
368** If zLine is not NULL then it is a malloced buffer returned from
369** a previous call to this routine that may be reused.
337*/
370*/
338static char *local_getline(char *zPrompt, FILE *in, int csvFlag){
339 char *zLine;
340 int nLine;
341 int n;
342 int inQuote = 0;
371static char *local_getline(char *zLine, FILE *in){
372 int nLine = zLine==0 ? 0 : 100;
373 int n = 0;
343
374
344 if( zPrompt && *zPrompt ){
345 printf("%s",zPrompt);
346 fflush(stdout);
347 }
348 nLine = 100;
349 zLine = malloc( nLine );
350 if( zLine==0 ) return 0;
351 n = 0;
352 while( 1 ){
353 if( n+100>nLine ){
354 nLine = nLine*2 + 100;
355 zLine = realloc(zLine, nLine);
356 if( zLine==0 ) return 0;
357 }
358 if( fgets(&zLine[n], nLine - n, in)==0 ){
359 if( n==0 ){
360 free(zLine);
361 return 0;
362 }
363 zLine[n] = 0;
364 break;
365 }
375 while( 1 ){
376 if( n+100>nLine ){
377 nLine = nLine*2 + 100;
378 zLine = realloc(zLine, nLine);
379 if( zLine==0 ) return 0;
380 }
381 if( fgets(&zLine[n], nLine - n, in)==0 ){
382 if( n==0 ){
383 free(zLine);
384 return 0;
385 }
386 zLine[n] = 0;
387 break;
388 }
366 while( zLine[n] ){
367 if( zLine[n]=='"' ) inQuote = !inQuote;
368 n++;
369 }
370 if( n>0 && zLine[n-1]=='\n' && (!inQuote || !csvFlag) ){
389 while( zLine[n] ) n++;
390 if( n>0 && zLine[n-1]=='\n' ){
371 n--;
372 if( n>0 && zLine[n-1]=='\r' ) n--;
373 zLine[n] = 0;
374 break;
375 }
376 }
391 n--;
392 if( n>0 && zLine[n-1]=='\r' ) n--;
393 zLine[n] = 0;
394 break;
395 }
396 }
377 zLine = realloc( zLine, n+1 );
378 return zLine;
379}
380
381/*
382** Retrieve a single line of input text.
383**
397 return zLine;
398}
399
400/*
401** Retrieve a single line of input text.
402**
384** zPrior is a string of prior text retrieved. If not the empty
385** string, then issue a continuation prompt.
403** If in==0 then read from standard input and prompt before each line.
404** If isContinuation is true, then a continuation prompt is appropriate.
405** If isContinuation is zero, then the main prompt should be used.
406**
407** If zPrior is not NULL then it is a buffer from a prior call to this
408** routine that can be reused.
409**
410** The result is stored in space obtained from malloc() and must either
411** be freed by the caller or else passed back into this routine via the
412** zPrior argument for reuse.
386*/
413*/
387static char *one_input_line(const char *zPrior, FILE *in){
414static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
388 char *zPrompt;
389 char *zResult;
390 if( in!=0 ){
415 char *zPrompt;
416 char *zResult;
417 if( in!=0 ){
391 return local_getline(0, in, 0);
392 }
393 if( zPrior && zPrior[0] ){
394 zPrompt = continuePrompt;
418 zResult = local_getline(zPrior, in);
395 }else{
419 }else{
396 zPrompt = mainPrompt;
397 }
398 zResult = readline(zPrompt);
399#if defined(HAVE_READLINE) && HAVE_READLINE==1
400 if( zResult && *zResult ) add_history(zResult);
420 zPrompt = isContinuation ? continuePrompt : mainPrompt;
421#if defined(HAVE_READLINE)
422 free(zPrior);
423 zResult = readline(zPrompt);
424 if( zResult && *zResult ) add_history(zResult);
425#else
426 printf("%s", zPrompt);
427 fflush(stdout);
428 zResult = local_getline(zPrior, stdin);
401#endif
429#endif
430 }
402 return zResult;
403}
404
405struct previous_mode_data {
406 int valid; /* Is there legit data in here? */
407 int mode;
408 int showHeader;
409 int colWidth[100];
410};
411
412/*
413** An pointer to an instance of this structure is passed from
414** the main program to the callback. This is used to communicate
415** state and mode information.
416*/
417struct callback_data {
418 sqlite3 *db; /* The database */
419 int echoOn; /* True to echo input commands */
431 return zResult;
432}
433
434struct previous_mode_data {
435 int valid; /* Is there legit data in here? */
436 int mode;
437 int showHeader;
438 int colWidth[100];
439};
440
441/*
442** An pointer to an instance of this structure is passed from
443** the main program to the callback. This is used to communicate
444** state and mode information.
445*/
446struct callback_data {
447 sqlite3 *db; /* The database */
448 int echoOn; /* True to echo input commands */
449 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
420 int statsOn; /* True to display memory stats before each finalize */
450 int statsOn; /* True to display memory stats before each finalize */
451 int outCount; /* Revert to stdout when reaching zero */
421 int cnt; /* Number of records displayed so far */
422 FILE *out; /* Write results here */
423 FILE *traceOut; /* Output for sqlite3_trace() */
424 int nErr; /* Number of errors seen */
425 int mode; /* An output mode setting */
426 int writableSchema; /* True if PRAGMA writable_schema=ON */
427 int showHeader; /* True to show column names in List or Column mode */
428 char *zDestTable; /* Name of destination table when MODE_Insert */
429 char separator[20]; /* Separator character for MODE_List */
430 int colWidth[100]; /* Requested width of each column when in column mode*/
431 int actualWidth[100]; /* Actual width of each column */
432 char nullvalue[20]; /* The text to print when a NULL comes back from
433 ** the database */
434 struct previous_mode_data explainPrev;
435 /* Holds the mode information just before
436 ** .explain ON */
437 char outfile[FILENAME_MAX]; /* Filename for *out */
438 const char *zDbFilename; /* name of the database file */
452 int cnt; /* Number of records displayed so far */
453 FILE *out; /* Write results here */
454 FILE *traceOut; /* Output for sqlite3_trace() */
455 int nErr; /* Number of errors seen */
456 int mode; /* An output mode setting */
457 int writableSchema; /* True if PRAGMA writable_schema=ON */
458 int showHeader; /* True to show column names in List or Column mode */
459 char *zDestTable; /* Name of destination table when MODE_Insert */
460 char separator[20]; /* Separator character for MODE_List */
461 int colWidth[100]; /* Requested width of each column when in column mode*/
462 int actualWidth[100]; /* Actual width of each column */
463 char nullvalue[20]; /* The text to print when a NULL comes back from
464 ** the database */
465 struct previous_mode_data explainPrev;
466 /* Holds the mode information just before
467 ** .explain ON */
468 char outfile[FILENAME_MAX]; /* Filename for *out */
469 const char *zDbFilename; /* name of the database file */
470 char *zFreeOnClose; /* Filename to free when closing */
439 const char *zVfs; /* Name of VFS to use */
440 sqlite3_stmt *pStmt; /* Current statement if any. */
441 FILE *pLog; /* Write log output here */
471 const char *zVfs; /* Name of VFS to use */
472 sqlite3_stmt *pStmt; /* Current statement if any. */
473 FILE *pLog; /* Write log output here */
474 int *aiIndent; /* Array of indents used in MODE_Explain */
475 int nIndent; /* Size of array aiIndent[] */
476 int iIndent; /* Index of current op in aiIndent[] */
442};
443
444/*
445** These are the allowed modes.
446*/
447#define MODE_Line 0 /* One column per line. Blank line between records */
448#define MODE_Column 1 /* One record per line in neat columns */
449#define MODE_List 2 /* One record per line with a separator */

--- 99 unchanged lines hidden (view full) ---

549 fputc('\\', out);
550 fputc('t', out);
551 }else if( c=='\n' ){
552 fputc('\\', out);
553 fputc('n', out);
554 }else if( c=='\r' ){
555 fputc('\\', out);
556 fputc('r', out);
477};
478
479/*
480** These are the allowed modes.
481*/
482#define MODE_Line 0 /* One column per line. Blank line between records */
483#define MODE_Column 1 /* One record per line in neat columns */
484#define MODE_List 2 /* One record per line with a separator */

--- 99 unchanged lines hidden (view full) ---

584 fputc('\\', out);
585 fputc('t', out);
586 }else if( c=='\n' ){
587 fputc('\\', out);
588 fputc('n', out);
589 }else if( c=='\r' ){
590 fputc('\\', out);
591 fputc('r', out);
557 }else if( !isprint(c) ){
592 }else if( !isprint(c&0xff) ){
558 fprintf(out, "\\%03o", c&0xff);
559 }else{
560 fputc(c, out);
561 }
562 }
563 fputc('"', out);
564}
565
566/*
567** Output the given string with characters that are special to
568** HTML escaped.
569*/
570static void output_html_string(FILE *out, const char *z){
571 int i;
593 fprintf(out, "\\%03o", c&0xff);
594 }else{
595 fputc(c, out);
596 }
597 }
598 fputc('"', out);
599}
600
601/*
602** Output the given string with characters that are special to
603** HTML escaped.
604*/
605static void output_html_string(FILE *out, const char *z){
606 int i;
607 if( z==0 ) z = "";
572 while( *z ){
573 for(i=0; z[i]
574 && z[i]!='<'
575 && z[i]!='&'
576 && z[i]!='>'
577 && z[i]!='\"'
578 && z[i]!='\'';
579 i++){}

--- 77 unchanged lines hidden (view full) ---

657}
658
659#ifdef SIGINT
660/*
661** This routine runs when the user presses Ctrl-C
662*/
663static void interrupt_handler(int NotUsed){
664 UNUSED_PARAMETER(NotUsed);
608 while( *z ){
609 for(i=0; z[i]
610 && z[i]!='<'
611 && z[i]!='&'
612 && z[i]!='>'
613 && z[i]!='\"'
614 && z[i]!='\'';
615 i++){}

--- 77 unchanged lines hidden (view full) ---

693}
694
695#ifdef SIGINT
696/*
697** This routine runs when the user presses Ctrl-C
698*/
699static void interrupt_handler(int NotUsed){
700 UNUSED_PARAMETER(NotUsed);
665 seenInterrupt = 1;
701 seenInterrupt++;
702 if( seenInterrupt>2 ) exit(1);
666 if( db ) sqlite3_interrupt(db);
667}
668#endif
669
670/*
671** This is the callback routine that the shell
672** invokes for each row of a query result.
673*/

--- 61 unchanged lines hidden (view full) ---

735 if( azArg==0 ) break;
736 for(i=0; i<nArg; i++){
737 int w;
738 if( i<ArraySize(p->actualWidth) ){
739 w = p->actualWidth[i];
740 }else{
741 w = 10;
742 }
703 if( db ) sqlite3_interrupt(db);
704}
705#endif
706
707/*
708** This is the callback routine that the shell
709** invokes for each row of a query result.
710*/

--- 61 unchanged lines hidden (view full) ---

772 if( azArg==0 ) break;
773 for(i=0; i<nArg; i++){
774 int w;
775 if( i<ArraySize(p->actualWidth) ){
776 w = p->actualWidth[i];
777 }else{
778 w = 10;
779 }
743 if( p->mode==MODE_Explain && azArg[i] &&
744 strlen30(azArg[i])>w ){
780 if( p->mode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
745 w = strlen30(azArg[i]);
746 }
781 w = strlen30(azArg[i]);
782 }
783 if( i==1 && p->aiIndent && p->pStmt ){
784 if( p->iIndent<p->nIndent ){
785 fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
786 }
787 p->iIndent++;
788 }
747 if( w<0 ){
748 fprintf(p->out,"%*.*s%s",-w,-w,
749 azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
750 }else{
751 fprintf(p->out,"%-*.*s%s",w,w,
752 azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
753 }
754 }

--- 77 unchanged lines hidden (view full) ---

832 fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
833 for(i=0; i<nArg; i++){
834 char *zSep = i>0 ? ",": "";
835 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
836 fprintf(p->out,"%sNULL",zSep);
837 }else if( aiType && aiType[i]==SQLITE_TEXT ){
838 if( zSep[0] ) fprintf(p->out,"%s",zSep);
839 output_quoted_string(p->out, azArg[i]);
789 if( w<0 ){
790 fprintf(p->out,"%*.*s%s",-w,-w,
791 azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
792 }else{
793 fprintf(p->out,"%-*.*s%s",w,w,
794 azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " ");
795 }
796 }

--- 77 unchanged lines hidden (view full) ---

874 fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable);
875 for(i=0; i<nArg; i++){
876 char *zSep = i>0 ? ",": "";
877 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
878 fprintf(p->out,"%sNULL",zSep);
879 }else if( aiType && aiType[i]==SQLITE_TEXT ){
880 if( zSep[0] ) fprintf(p->out,"%s",zSep);
881 output_quoted_string(p->out, azArg[i]);
840 }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){
882 }else if( aiType && (aiType[i]==SQLITE_INTEGER
883 || aiType[i]==SQLITE_FLOAT) ){
841 fprintf(p->out,"%s%s",zSep, azArg[i]);
842 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
843 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
844 int nBlob = sqlite3_column_bytes(p->pStmt, i);
845 if( zSep[0] ) fprintf(p->out,"%s",zSep);
846 output_hex_blob(p->out, pBlob, nBlob);
847 }else if( isNumber(azArg[i], 0) ){
848 fprintf(p->out,"%s%s",zSep, azArg[i]);

--- 117 unchanged lines hidden (view full) ---

966 const char *zSelect, /* SELECT statement to extract content */
967 const char *zFirstRow /* Print before first row, if not NULL */
968){
969 sqlite3_stmt *pSelect;
970 int rc;
971 int nResult;
972 int i;
973 const char *z;
884 fprintf(p->out,"%s%s",zSep, azArg[i]);
885 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
886 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
887 int nBlob = sqlite3_column_bytes(p->pStmt, i);
888 if( zSep[0] ) fprintf(p->out,"%s",zSep);
889 output_hex_blob(p->out, pBlob, nBlob);
890 }else if( isNumber(azArg[i], 0) ){
891 fprintf(p->out,"%s%s",zSep, azArg[i]);

--- 117 unchanged lines hidden (view full) ---

1009 const char *zSelect, /* SELECT statement to extract content */
1010 const char *zFirstRow /* Print before first row, if not NULL */
1011){
1012 sqlite3_stmt *pSelect;
1013 int rc;
1014 int nResult;
1015 int i;
1016 const char *z;
974 rc = sqlite3_prepare(p->db, zSelect, -1, &pSelect, 0);
1017 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
975 if( rc!=SQLITE_OK || !pSelect ){
976 fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
1018 if( rc!=SQLITE_OK || !pSelect ){
1019 fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
977 p->nErr++;
1020 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
978 return rc;
979 }
980 rc = sqlite3_step(pSelect);
981 nResult = sqlite3_column_count(pSelect);
982 while( rc==SQLITE_ROW ){
983 if( zFirstRow ){
984 fprintf(p->out, "%s", zFirstRow);
985 zFirstRow = 0;

--- 10 unchanged lines hidden (view full) ---

996 }else{
997 fprintf(p->out, ";\n");
998 }
999 rc = sqlite3_step(pSelect);
1000 }
1001 rc = sqlite3_finalize(pSelect);
1002 if( rc!=SQLITE_OK ){
1003 fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
1021 return rc;
1022 }
1023 rc = sqlite3_step(pSelect);
1024 nResult = sqlite3_column_count(pSelect);
1025 while( rc==SQLITE_ROW ){
1026 if( zFirstRow ){
1027 fprintf(p->out, "%s", zFirstRow);
1028 zFirstRow = 0;

--- 10 unchanged lines hidden (view full) ---

1039 }else{
1040 fprintf(p->out, ";\n");
1041 }
1042 rc = sqlite3_step(pSelect);
1043 }
1044 rc = sqlite3_finalize(pSelect);
1045 if( rc!=SQLITE_OK ){
1046 fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
1004 p->nErr++;
1047 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
1005 }
1006 return rc;
1007}
1008
1009/*
1010** Allocate space and save off current error string.
1011*/
1012static char *save_err_msg(

--- 91 unchanged lines hidden (view full) ---

1104
1105 if( pArg && pArg->out && db && pArg->pStmt ){
1106 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
1107 fprintf(pArg->out, "Fullscan Steps: %d\n", iCur);
1108 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1109 fprintf(pArg->out, "Sort Operations: %d\n", iCur);
1110 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
1111 fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur);
1048 }
1049 return rc;
1050}
1051
1052/*
1053** Allocate space and save off current error string.
1054*/
1055static char *save_err_msg(

--- 91 unchanged lines hidden (view full) ---

1147
1148 if( pArg && pArg->out && db && pArg->pStmt ){
1149 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset);
1150 fprintf(pArg->out, "Fullscan Steps: %d\n", iCur);
1151 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
1152 fprintf(pArg->out, "Sort Operations: %d\n", iCur);
1153 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset);
1154 fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur);
1155 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
1156 fprintf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
1112 }
1113
1114 return 0;
1115}
1116
1117/*
1157 }
1158
1159 return 0;
1160}
1161
1162/*
1163** Parameter azArray points to a zero-terminated array of strings. zStr
1164** points to a single nul-terminated string. Return non-zero if zStr
1165** is equal, according to strcmp(), to any of the strings in the array.
1166** Otherwise, return zero.
1167*/
1168static int str_in_array(const char *zStr, const char **azArray){
1169 int i;
1170 for(i=0; azArray[i]; i++){
1171 if( 0==strcmp(zStr, azArray[i]) ) return 1;
1172 }
1173 return 0;
1174}
1175
1176/*
1177** If compiled statement pSql appears to be an EXPLAIN statement, allocate
1178** and populate the callback_data.aiIndent[] array with the number of
1179** spaces each opcode should be indented before it is output.
1180**
1181** The indenting rules are:
1182**
1183** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
1184** all opcodes that occur between the p2 jump destination and the opcode
1185** itself by 2 spaces.
1186**
1187** * For each "Goto", if the jump destination is earlier in the program
1188** and ends on one of:
1189** Yield SeekGt SeekLt RowSetRead Rewind
1190** or if the P1 parameter is one instead of zero,
1191** then indent all opcodes between the earlier instruction
1192** and "Goto" by 2 spaces.
1193*/
1194static void explain_data_prepare(struct callback_data *p, sqlite3_stmt *pSql){
1195 const char *zSql; /* The text of the SQL statement */
1196 const char *z; /* Used to check if this is an EXPLAIN */
1197 int *abYield = 0; /* True if op is an OP_Yield */
1198 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
1199 int iOp; /* Index of operation in p->aiIndent[] */
1200
1201 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
1202 "NextIfOpen", "PrevIfOpen", 0 };
1203 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", "Rewind", 0 };
1204 const char *azGoto[] = { "Goto", 0 };
1205
1206 /* Try to figure out if this is really an EXPLAIN statement. If this
1207 ** cannot be verified, return early. */
1208 zSql = sqlite3_sql(pSql);
1209 if( zSql==0 ) return;
1210 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
1211 if( sqlite3_strnicmp(z, "explain", 7) ) return;
1212
1213 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
1214 int i;
1215 int iAddr = sqlite3_column_int(pSql, 0);
1216 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
1217
1218 /* Set p2 to the P2 field of the current opcode. Then, assuming that
1219 ** p2 is an instruction address, set variable p2op to the index of that
1220 ** instruction in the aiIndent[] array. p2 and p2op may be different if
1221 ** the current instruction is part of a sub-program generated by an
1222 ** SQL trigger or foreign key. */
1223 int p2 = sqlite3_column_int(pSql, 3);
1224 int p2op = (p2 + (iOp-iAddr));
1225
1226 /* Grow the p->aiIndent array as required */
1227 if( iOp>=nAlloc ){
1228 nAlloc += 100;
1229 p->aiIndent = (int*)sqlite3_realloc(p->aiIndent, nAlloc*sizeof(int));
1230 abYield = (int*)sqlite3_realloc(abYield, nAlloc*sizeof(int));
1231 }
1232 abYield[iOp] = str_in_array(zOp, azYield);
1233 p->aiIndent[iOp] = 0;
1234 p->nIndent = iOp+1;
1235
1236 if( str_in_array(zOp, azNext) ){
1237 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
1238 }
1239 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
1240 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
1241 ){
1242 for(i=p2op+1; i<iOp; i++) p->aiIndent[i] += 2;
1243 }
1244 }
1245
1246 p->iIndent = 0;
1247 sqlite3_free(abYield);
1248 sqlite3_reset(pSql);
1249}
1250
1251/*
1252** Free the array allocated by explain_data_prepare().
1253*/
1254static void explain_data_delete(struct callback_data *p){
1255 sqlite3_free(p->aiIndent);
1256 p->aiIndent = 0;
1257 p->nIndent = 0;
1258 p->iIndent = 0;
1259}
1260
1261/*
1118** Execute a statement or set of statements. Print
1119** any result rows/columns depending on the current mode
1120** set via the supplied callback.
1121**
1122** This is very similar to SQLite's built-in sqlite3_exec()
1123** function except it takes a slightly different callback
1124** and callback data argument.
1125*/

--- 35 unchanged lines hidden (view full) ---

1161 }
1162
1163 /* echo the sql statement if echo on */
1164 if( pArg && pArg->echoOn ){
1165 const char *zStmtSql = sqlite3_sql(pStmt);
1166 fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
1167 }
1168
1262** Execute a statement or set of statements. Print
1263** any result rows/columns depending on the current mode
1264** set via the supplied callback.
1265**
1266** This is very similar to SQLite's built-in sqlite3_exec()
1267** function except it takes a slightly different callback
1268** and callback data argument.
1269*/

--- 35 unchanged lines hidden (view full) ---

1305 }
1306
1307 /* echo the sql statement if echo on */
1308 if( pArg && pArg->echoOn ){
1309 const char *zStmtSql = sqlite3_sql(pStmt);
1310 fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
1311 }
1312
1313 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
1314 if( pArg && pArg->autoEQP ){
1315 sqlite3_stmt *pExplain;
1316 char *zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", sqlite3_sql(pStmt));
1317 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
1318 if( rc==SQLITE_OK ){
1319 while( sqlite3_step(pExplain)==SQLITE_ROW ){
1320 fprintf(pArg->out,"--EQP-- %d,", sqlite3_column_int(pExplain, 0));
1321 fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
1322 fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
1323 fprintf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
1324 }
1325 }
1326 sqlite3_finalize(pExplain);
1327 sqlite3_free(zEQP);
1328 }
1329
1169 /* Output TESTCTRL_EXPLAIN text of requested */
1170 if( pArg && pArg->mode==MODE_Explain ){
1171 const char *zExplain = 0;
1172 sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
1173 if( zExplain && zExplain[0] ){
1174 fprintf(pArg->out, "%s", zExplain);
1175 }
1176 }
1177
1330 /* Output TESTCTRL_EXPLAIN text of requested */
1331 if( pArg && pArg->mode==MODE_Explain ){
1332 const char *zExplain = 0;
1333 sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
1334 if( zExplain && zExplain[0] ){
1335 fprintf(pArg->out, "%s", zExplain);
1336 }
1337 }
1338
1339 /* If the shell is currently in ".explain" mode, gather the extra
1340 ** data required to add indents to the output.*/
1341 if( pArg && pArg->mode==MODE_Explain ){
1342 explain_data_prepare(pArg, pStmt);
1343 }
1344
1178 /* perform the first step. this will tell us if we
1179 ** have a result set or not and how wide it is.
1180 */
1181 rc = sqlite3_step(pStmt);
1182 /* if we have a result set... */
1183 if( SQLITE_ROW == rc ){
1184 /* if we have a callback... */
1185 if( xCallback ){
1186 /* allocate space for col name ptr, value ptr, and type */
1187 int nCol = sqlite3_column_count(pStmt);
1188 void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
1189 if( !pData ){
1190 rc = SQLITE_NOMEM;
1191 }else{
1192 char **azCols = (char **)pData; /* Names of result columns */
1193 char **azVals = &azCols[nCol]; /* Results */
1194 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
1345 /* perform the first step. this will tell us if we
1346 ** have a result set or not and how wide it is.
1347 */
1348 rc = sqlite3_step(pStmt);
1349 /* if we have a result set... */
1350 if( SQLITE_ROW == rc ){
1351 /* if we have a callback... */
1352 if( xCallback ){
1353 /* allocate space for col name ptr, value ptr, and type */
1354 int nCol = sqlite3_column_count(pStmt);
1355 void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
1356 if( !pData ){
1357 rc = SQLITE_NOMEM;
1358 }else{
1359 char **azCols = (char **)pData; /* Names of result columns */
1360 char **azVals = &azCols[nCol]; /* Results */
1361 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
1195 int i;
1362 int i, x;
1196 assert(sizeof(int) <= sizeof(char *));
1197 /* save off ptrs to column names */
1198 for(i=0; i<nCol; i++){
1199 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
1200 }
1201 do{
1202 /* extract the data and data types */
1203 for(i=0; i<nCol; i++){
1363 assert(sizeof(int) <= sizeof(char *));
1364 /* save off ptrs to column names */
1365 for(i=0; i<nCol; i++){
1366 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
1367 }
1368 do{
1369 /* extract the data and data types */
1370 for(i=0; i<nCol; i++){
1204 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
1205 aiTypes[i] = sqlite3_column_type(pStmt, i);
1371 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
1372 if( x==SQLITE_BLOB && pArg && pArg->mode==MODE_Insert ){
1373 azVals[i] = "";
1374 }else{
1375 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
1376 }
1206 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
1207 rc = SQLITE_NOMEM;
1208 break; /* from for */
1209 }
1210 } /* end for */
1211
1212 /* if data and types extracted successfully... */
1213 if( SQLITE_ROW == rc ){

--- 9 unchanged lines hidden (view full) ---

1223 }
1224 }else{
1225 do{
1226 rc = sqlite3_step(pStmt);
1227 } while( rc == SQLITE_ROW );
1228 }
1229 }
1230
1377 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
1378 rc = SQLITE_NOMEM;
1379 break; /* from for */
1380 }
1381 } /* end for */
1382
1383 /* if data and types extracted successfully... */
1384 if( SQLITE_ROW == rc ){

--- 9 unchanged lines hidden (view full) ---

1394 }
1395 }else{
1396 do{
1397 rc = sqlite3_step(pStmt);
1398 } while( rc == SQLITE_ROW );
1399 }
1400 }
1401
1402 explain_data_delete(pArg);
1403
1231 /* print usage stats if stats on */
1232 if( pArg && pArg->statsOn ){
1233 display_stats(db, pArg, 0);
1234 }
1235
1236 /* Finalize the statement just executed. If this fails, save a
1237 ** copy of the error message. Otherwise, set zSql to point to the
1238 ** next statement to execute. */

--- 34 unchanged lines hidden (view full) ---

1273 UNUSED_PARAMETER(azCol);
1274 if( nArg!=3 ) return 1;
1275 zTable = azArg[0];
1276 zType = azArg[1];
1277 zSql = azArg[2];
1278
1279 if( strcmp(zTable, "sqlite_sequence")==0 ){
1280 zPrepStmt = "DELETE FROM sqlite_sequence;\n";
1404 /* print usage stats if stats on */
1405 if( pArg && pArg->statsOn ){
1406 display_stats(db, pArg, 0);
1407 }
1408
1409 /* Finalize the statement just executed. If this fails, save a
1410 ** copy of the error message. Otherwise, set zSql to point to the
1411 ** next statement to execute. */

--- 34 unchanged lines hidden (view full) ---

1446 UNUSED_PARAMETER(azCol);
1447 if( nArg!=3 ) return 1;
1448 zTable = azArg[0];
1449 zType = azArg[1];
1450 zSql = azArg[2];
1451
1452 if( strcmp(zTable, "sqlite_sequence")==0 ){
1453 zPrepStmt = "DELETE FROM sqlite_sequence;\n";
1281 }else if( strcmp(zTable, "sqlite_stat1")==0 ){
1454 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
1282 fprintf(p->out, "ANALYZE sqlite_master;\n");
1283 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
1284 return 0;
1285 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
1286 char *zIns;
1287 if( !p->writableSchema ){
1288 fprintf(p->out, "PRAGMA writable_schema=ON;\n");
1289 p->writableSchema = 1;

--- 15 unchanged lines hidden (view full) ---

1305 char *zTableInfo = 0;
1306 char *zTmp = 0;
1307 int nRow = 0;
1308
1309 zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
1310 zTableInfo = appendText(zTableInfo, zTable, '"');
1311 zTableInfo = appendText(zTableInfo, ");", 0);
1312
1455 fprintf(p->out, "ANALYZE sqlite_master;\n");
1456 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
1457 return 0;
1458 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
1459 char *zIns;
1460 if( !p->writableSchema ){
1461 fprintf(p->out, "PRAGMA writable_schema=ON;\n");
1462 p->writableSchema = 1;

--- 15 unchanged lines hidden (view full) ---

1478 char *zTableInfo = 0;
1479 char *zTmp = 0;
1480 int nRow = 0;
1481
1482 zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
1483 zTableInfo = appendText(zTableInfo, zTable, '"');
1484 zTableInfo = appendText(zTableInfo, ");", 0);
1485
1313 rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
1486 rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
1314 free(zTableInfo);
1315 if( rc!=SQLITE_OK || !pTableInfo ){
1316 return 1;
1317 }
1318
1319 zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
1320 /* Always quote the table name, even if it appears to be pure ascii,
1321 ** in case it is a keyword. Ex: INSERT INTO "table" ... */

--- 72 unchanged lines hidden (view full) ---

1394 return rc;
1395}
1396
1397/*
1398** Text of a help message
1399*/
1400static char zHelp[] =
1401 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
1487 free(zTableInfo);
1488 if( rc!=SQLITE_OK || !pTableInfo ){
1489 return 1;
1490 }
1491
1492 zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
1493 /* Always quote the table name, even if it appears to be pure ascii,
1494 ** in case it is a keyword. Ex: INSERT INTO "table" ... */

--- 72 unchanged lines hidden (view full) ---

1567 return rc;
1568}
1569
1570/*
1571** Text of a help message
1572*/
1573static char zHelp[] =
1574 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
1402 ".bail ON|OFF Stop after hitting an error. Default OFF\n"
1575 ".bail on|off Stop after hitting an error. Default OFF\n"
1576 ".clone NEWDB Clone data into NEWDB from the existing database\n"
1403 ".databases List names and files of attached databases\n"
1404 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
1405 " If TABLE specified, only dump tables matching\n"
1406 " LIKE pattern TABLE.\n"
1577 ".databases List names and files of attached databases\n"
1578 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
1579 " If TABLE specified, only dump tables matching\n"
1580 " LIKE pattern TABLE.\n"
1407 ".echo ON|OFF Turn command echo on or off\n"
1581 ".echo on|off Turn command echo on or off\n"
1408 ".exit Exit this program\n"
1582 ".exit Exit this program\n"
1409 ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n"
1583 ".explain ?on|off? Turn output mode suitable for EXPLAIN on or off.\n"
1410 " With no args, it turns EXPLAIN on.\n"
1584 " With no args, it turns EXPLAIN on.\n"
1411 ".header(s) ON|OFF Turn display of headers on or off\n"
1585 ".headers on|off Turn display of headers on or off\n"
1412 ".help Show this message\n"
1413 ".import FILE TABLE Import data from FILE into TABLE\n"
1414 ".indices ?TABLE? Show names of all indices\n"
1415 " If TABLE specified, only show indices for tables\n"
1416 " matching LIKE pattern TABLE.\n"
1417#ifdef SQLITE_ENABLE_IOTRACE
1418 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
1419#endif

--- 6 unchanged lines hidden (view full) ---

1426 " column Left-aligned columns. (See .width)\n"
1427 " html HTML <table> code\n"
1428 " insert SQL insert statements for TABLE\n"
1429 " line One value per line\n"
1430 " list Values delimited by .separator string\n"
1431 " tabs Tab-separated values\n"
1432 " tcl TCL list elements\n"
1433 ".nullvalue STRING Use STRING in place of NULL values\n"
1586 ".help Show this message\n"
1587 ".import FILE TABLE Import data from FILE into TABLE\n"
1588 ".indices ?TABLE? Show names of all indices\n"
1589 " If TABLE specified, only show indices for tables\n"
1590 " matching LIKE pattern TABLE.\n"
1591#ifdef SQLITE_ENABLE_IOTRACE
1592 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
1593#endif

--- 6 unchanged lines hidden (view full) ---

1600 " column Left-aligned columns. (See .width)\n"
1601 " html HTML <table> code\n"
1602 " insert SQL insert statements for TABLE\n"
1603 " line One value per line\n"
1604 " list Values delimited by .separator string\n"
1605 " tabs Tab-separated values\n"
1606 " tcl TCL list elements\n"
1607 ".nullvalue STRING Use STRING in place of NULL values\n"
1434 ".output FILENAME Send output to FILENAME\n"
1435 ".output stdout Send output to the screen\n"
1608 ".once FILENAME Output for the next SQL command only to FILENAME\n"
1609 ".open ?FILENAME? Close existing database and reopen FILENAME\n"
1610 ".output ?FILENAME? Send output to FILENAME or stdout\n"
1436 ".print STRING... Print literal STRING\n"
1437 ".prompt MAIN CONTINUE Replace the standard prompts\n"
1438 ".quit Exit this program\n"
1439 ".read FILENAME Execute SQL in FILENAME\n"
1440 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
1611 ".print STRING... Print literal STRING\n"
1612 ".prompt MAIN CONTINUE Replace the standard prompts\n"
1613 ".quit Exit this program\n"
1614 ".read FILENAME Execute SQL in FILENAME\n"
1615 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
1616 ".save FILE Write in-memory database into FILE\n"
1441 ".schema ?TABLE? Show the CREATE statements\n"
1442 " If TABLE specified, only show tables matching\n"
1443 " LIKE pattern TABLE.\n"
1444 ".separator STRING Change separator used by output mode and .import\n"
1617 ".schema ?TABLE? Show the CREATE statements\n"
1618 " If TABLE specified, only show tables matching\n"
1619 " LIKE pattern TABLE.\n"
1620 ".separator STRING Change separator used by output mode and .import\n"
1621 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
1445 ".show Show the current values for various settings\n"
1622 ".show Show the current values for various settings\n"
1446 ".stats ON|OFF Turn stats on or off\n"
1623 ".stats on|off Turn stats on or off\n"
1624 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
1447 ".tables ?TABLE? List names of tables\n"
1448 " If TABLE specified, only list tables matching\n"
1449 " LIKE pattern TABLE.\n"
1450 ".timeout MS Try opening locked tables for MS milliseconds\n"
1625 ".tables ?TABLE? List names of tables\n"
1626 " If TABLE specified, only list tables matching\n"
1627 " LIKE pattern TABLE.\n"
1628 ".timeout MS Try opening locked tables for MS milliseconds\n"
1629 ".timer on|off Turn SQL timer on or off\n"
1451 ".trace FILE|off Output each SQL statement as it is run\n"
1452 ".vfsname ?AUX? Print the name of the VFS stack\n"
1453 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
1630 ".trace FILE|off Output each SQL statement as it is run\n"
1631 ".vfsname ?AUX? Print the name of the VFS stack\n"
1632 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
1633 " Negative values right-justify\n"
1454;
1455
1634;
1635
1456static char zTimerHelp[] =
1457 ".timer ON|OFF Turn the CPU timer measurement on or off\n"
1458;
1459
1460/* Forward reference */
1461static int process_input(struct callback_data *p, FILE *in);
1462
1463/*
1464** Make sure the database is open. If it is not, then open it. If
1465** the database fails to open, print an error message and exit.
1466*/
1636/* Forward reference */
1637static int process_input(struct callback_data *p, FILE *in);
1638
1639/*
1640** Make sure the database is open. If it is not, then open it. If
1641** the database fails to open, print an error message and exit.
1642*/
1467static void open_db(struct callback_data *p){
1643static void open_db(struct callback_data *p, int keepAlive){
1468 if( p->db==0 ){
1469 sqlite3_initialize();
1470 sqlite3_open(p->zDbFilename, &p->db);
1471 db = p->db;
1472 if( db && sqlite3_errcode(db)==SQLITE_OK ){
1473 sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
1474 shellstaticFunc, 0, 0);
1475 }
1476 if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
1477 fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
1478 p->zDbFilename, sqlite3_errmsg(db));
1644 if( p->db==0 ){
1645 sqlite3_initialize();
1646 sqlite3_open(p->zDbFilename, &p->db);
1647 db = p->db;
1648 if( db && sqlite3_errcode(db)==SQLITE_OK ){
1649 sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0,
1650 shellstaticFunc, 0, 0);
1651 }
1652 if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){
1653 fprintf(stderr,"Error: unable to open database \"%s\": %s\n",
1654 p->zDbFilename, sqlite3_errmsg(db));
1655 if( keepAlive ) return;
1479 exit(1);
1480 }
1481#ifndef SQLITE_OMIT_LOAD_EXTENSION
1482 sqlite3_enable_load_extension(p->db, 1);
1483#endif
1484 }
1485}
1486
1487/*
1488** Do C-language style dequoting.
1489**
1490** \t -> tab
1491** \n -> newline
1492** \r -> carriage return
1656 exit(1);
1657 }
1658#ifndef SQLITE_OMIT_LOAD_EXTENSION
1659 sqlite3_enable_load_extension(p->db, 1);
1660#endif
1661 }
1662}
1663
1664/*
1665** Do C-language style dequoting.
1666**
1667** \t -> tab
1668** \n -> newline
1669** \r -> carriage return
1670** \" -> "
1493** \NNN -> ascii character NNN in octal
1494** \\ -> backslash
1495*/
1496static void resolve_backslashes(char *z){
1497 int i, j;
1498 char c;
1671** \NNN -> ascii character NNN in octal
1672** \\ -> backslash
1673*/
1674static void resolve_backslashes(char *z){
1675 int i, j;
1676 char c;
1677 while( *z && *z!='\\' ) z++;
1499 for(i=j=0; (c = z[i])!=0; i++, j++){
1500 if( c=='\\' ){
1501 c = z[++i];
1502 if( c=='n' ){
1503 c = '\n';
1504 }else if( c=='t' ){
1505 c = '\t';
1506 }else if( c=='r' ){
1507 c = '\r';
1678 for(i=j=0; (c = z[i])!=0; i++, j++){
1679 if( c=='\\' ){
1680 c = z[++i];
1681 if( c=='n' ){
1682 c = '\n';
1683 }else if( c=='t' ){
1684 c = '\t';
1685 }else if( c=='r' ){
1686 c = '\r';
1687 }else if( c=='\\' ){
1688 c = '\\';
1508 }else if( c>='0' && c<='7' ){
1509 c -= '0';
1510 if( z[i+1]>='0' && z[i+1]<='7' ){
1511 i++;
1512 c = (c<<3) + z[i] - '0';
1513 if( z[i+1]>='0' && z[i+1]<='7' ){
1514 i++;
1515 c = (c<<3) + z[i] - '0';
1516 }
1517 }
1518 }
1519 }
1520 z[j] = c;
1521 }
1689 }else if( c>='0' && c<='7' ){
1690 c -= '0';
1691 if( z[i+1]>='0' && z[i+1]<='7' ){
1692 i++;
1693 c = (c<<3) + z[i] - '0';
1694 if( z[i+1]>='0' && z[i+1]<='7' ){
1695 i++;
1696 c = (c<<3) + z[i] - '0';
1697 }
1698 }
1699 }
1700 }
1701 z[j] = c;
1702 }
1522 z[j] = 0;
1703 if( j<i ) z[j] = 0;
1523}
1524
1525/*
1704}
1705
1706/*
1526** Interpret zArg as a boolean value. Return either 0 or 1.
1707** Return the value of a hexadecimal digit. Return -1 if the input
1708** is not a hex digit.
1527*/
1709*/
1528static int booleanValue(char *zArg){
1529 int i;
1530 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
1531 if( i>0 && zArg[i]==0 ) return atoi(zArg);
1532 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
1533 return 1;
1534 }
1535 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
1536 return 0;
1537 }
1538 fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
1539 zArg);
1540 return 0;
1710static int hexDigitValue(char c){
1711 if( c>='0' && c<='9' ) return c - '0';
1712 if( c>='a' && c<='f' ) return c - 'a' + 10;
1713 if( c>='A' && c<='F' ) return c - 'A' + 10;
1714 return -1;
1541}
1542
1543/*
1544** Interpret zArg as an integer value, possibly with suffixes.
1545*/
1546static sqlite3_int64 integerValue(const char *zArg){
1547 sqlite3_int64 v = 0;
1548 static const struct { char *zSuffix; int iMult; } aMult[] = {

--- 10 unchanged lines hidden (view full) ---

1559 int i;
1560 int isNeg = 0;
1561 if( zArg[0]=='-' ){
1562 isNeg = 1;
1563 zArg++;
1564 }else if( zArg[0]=='+' ){
1565 zArg++;
1566 }
1715}
1716
1717/*
1718** Interpret zArg as an integer value, possibly with suffixes.
1719*/
1720static sqlite3_int64 integerValue(const char *zArg){
1721 sqlite3_int64 v = 0;
1722 static const struct { char *zSuffix; int iMult; } aMult[] = {

--- 10 unchanged lines hidden (view full) ---

1733 int i;
1734 int isNeg = 0;
1735 if( zArg[0]=='-' ){
1736 isNeg = 1;
1737 zArg++;
1738 }else if( zArg[0]=='+' ){
1739 zArg++;
1740 }
1567 while( isdigit(zArg[0]) ){
1568 v = v*10 + zArg[0] - '0';
1569 zArg++;
1741 if( zArg[0]=='0' && zArg[1]=='x' ){
1742 int x;
1743 zArg += 2;
1744 while( (x = hexDigitValue(zArg[0]))>=0 ){
1745 v = (v<<4) + x;
1746 zArg++;
1747 }
1748 }else{
1749 while( IsDigit(zArg[0]) ){
1750 v = v*10 + zArg[0] - '0';
1751 zArg++;
1752 }
1570 }
1753 }
1571 for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
1754 for(i=0; i<ArraySize(aMult); i++){
1572 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1573 v *= aMult[i].iMult;
1574 break;
1575 }
1576 }
1577 return isNeg? -v : v;
1578}
1579
1580/*
1755 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
1756 v *= aMult[i].iMult;
1757 break;
1758 }
1759 }
1760 return isNeg? -v : v;
1761}
1762
1763/*
1764** Interpret zArg as either an integer or a boolean value. Return 1 or 0
1765** for TRUE and FALSE. Return the integer value if appropriate.
1766*/
1767static int booleanValue(char *zArg){
1768 int i;
1769 if( zArg[0]=='0' && zArg[1]=='x' ){
1770 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
1771 }else{
1772 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
1773 }
1774 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
1775 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
1776 return 1;
1777 }
1778 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
1779 return 0;
1780 }
1781 fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
1782 zArg);
1783 return 0;
1784}
1785
1786/*
1581** Close an output file, assuming it is not stderr or stdout
1582*/
1583static void output_file_close(FILE *f){
1584 if( f && f!=stdout && f!=stderr ) fclose(f);
1585}
1586
1587/*
1588** Try to open an output file. The names "stdout" and "stderr" are

--- 30 unchanged lines hidden (view full) ---

1619** a useful spot to set a debugger breakpoint.
1620*/
1621static void test_breakpoint(void){
1622 static int nCall = 0;
1623 nCall++;
1624}
1625
1626/*
1787** Close an output file, assuming it is not stderr or stdout
1788*/
1789static void output_file_close(FILE *f){
1790 if( f && f!=stdout && f!=stderr ) fclose(f);
1791}
1792
1793/*
1794** Try to open an output file. The names "stdout" and "stderr" are

--- 30 unchanged lines hidden (view full) ---

1825** a useful spot to set a debugger breakpoint.
1826*/
1827static void test_breakpoint(void){
1828 static int nCall = 0;
1829 nCall++;
1830}
1831
1832/*
1833** An object used to read a CSV file
1834*/
1835typedef struct CSVReader CSVReader;
1836struct CSVReader {
1837 const char *zFile; /* Name of the input file */
1838 FILE *in; /* Read the CSV text from this input stream */
1839 char *z; /* Accumulated text for a field */
1840 int n; /* Number of bytes in z */
1841 int nAlloc; /* Space allocated for z[] */
1842 int nLine; /* Current line number */
1843 int cTerm; /* Character that terminated the most recent field */
1844 int cSeparator; /* The separator character. (Usually ",") */
1845};
1846
1847/* Append a single byte to z[] */
1848static void csv_append_char(CSVReader *p, int c){
1849 if( p->n+1>=p->nAlloc ){
1850 p->nAlloc += p->nAlloc + 100;
1851 p->z = sqlite3_realloc(p->z, p->nAlloc);
1852 if( p->z==0 ){
1853 fprintf(stderr, "out of memory\n");
1854 exit(1);
1855 }
1856 }
1857 p->z[p->n++] = (char)c;
1858}
1859
1860/* Read a single field of CSV text. Compatible with rfc4180 and extended
1861** with the option of having a separator other than ",".
1862**
1863** + Input comes from p->in.
1864** + Store results in p->z of length p->n. Space to hold p->z comes
1865** from sqlite3_malloc().
1866** + Use p->cSep as the separator. The default is ",".
1867** + Keep track of the line number in p->nLine.
1868** + Store the character that terminates the field in p->cTerm. Store
1869** EOF on end-of-file.
1870** + Report syntax errors on stderr
1871*/
1872static char *csv_read_one_field(CSVReader *p){
1873 int c, pc, ppc;
1874 int cSep = p->cSeparator;
1875 p->n = 0;
1876 c = fgetc(p->in);
1877 if( c==EOF || seenInterrupt ){
1878 p->cTerm = EOF;
1879 return 0;
1880 }
1881 if( c=='"' ){
1882 int startLine = p->nLine;
1883 int cQuote = c;
1884 pc = ppc = 0;
1885 while( 1 ){
1886 c = fgetc(p->in);
1887 if( c=='\n' ) p->nLine++;
1888 if( c==cQuote ){
1889 if( pc==cQuote ){
1890 pc = 0;
1891 continue;
1892 }
1893 }
1894 if( (c==cSep && pc==cQuote)
1895 || (c=='\n' && pc==cQuote)
1896 || (c=='\n' && pc=='\r' && ppc==cQuote)
1897 || (c==EOF && pc==cQuote)
1898 ){
1899 do{ p->n--; }while( p->z[p->n]!=cQuote );
1900 p->cTerm = c;
1901 break;
1902 }
1903 if( pc==cQuote && c!='\r' ){
1904 fprintf(stderr, "%s:%d: unescaped %c character\n",
1905 p->zFile, p->nLine, cQuote);
1906 }
1907 if( c==EOF ){
1908 fprintf(stderr, "%s:%d: unterminated %c-quoted field\n",
1909 p->zFile, startLine, cQuote);
1910 p->cTerm = EOF;
1911 break;
1912 }
1913 csv_append_char(p, c);
1914 ppc = pc;
1915 pc = c;
1916 }
1917 }else{
1918 while( c!=EOF && c!=cSep && c!='\n' ){
1919 csv_append_char(p, c);
1920 c = fgetc(p->in);
1921 }
1922 if( c=='\n' ){
1923 p->nLine++;
1924 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
1925 }
1926 p->cTerm = c;
1927 }
1928 if( p->z ) p->z[p->n] = 0;
1929 return p->z;
1930}
1931
1932/*
1933** Try to transfer data for table zTable. If an error is seen while
1934** moving forward, try to go backwards. The backwards movement won't
1935** work for WITHOUT ROWID tables.
1936*/
1937static void tryToCloneData(
1938 struct callback_data *p,
1939 sqlite3 *newDb,
1940 const char *zTable
1941){
1942 sqlite3_stmt *pQuery = 0;
1943 sqlite3_stmt *pInsert = 0;
1944 char *zQuery = 0;
1945 char *zInsert = 0;
1946 int rc;
1947 int i, j, n;
1948 int nTable = (int)strlen(zTable);
1949 int k = 0;
1950 int cnt = 0;
1951 const int spinRate = 10000;
1952
1953 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
1954 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
1955 if( rc ){
1956 fprintf(stderr, "Error %d: %s on [%s]\n",
1957 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
1958 zQuery);
1959 goto end_data_xfer;
1960 }
1961 n = sqlite3_column_count(pQuery);
1962 zInsert = sqlite3_malloc(200 + nTable + n*3);
1963 if( zInsert==0 ){
1964 fprintf(stderr, "out of memory\n");
1965 goto end_data_xfer;
1966 }
1967 sqlite3_snprintf(200+nTable,zInsert,
1968 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
1969 i = (int)strlen(zInsert);
1970 for(j=1; j<n; j++){
1971 memcpy(zInsert+i, ",?", 2);
1972 i += 2;
1973 }
1974 memcpy(zInsert+i, ");", 3);
1975 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
1976 if( rc ){
1977 fprintf(stderr, "Error %d: %s on [%s]\n",
1978 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
1979 zQuery);
1980 goto end_data_xfer;
1981 }
1982 for(k=0; k<2; k++){
1983 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
1984 for(i=0; i<n; i++){
1985 switch( sqlite3_column_type(pQuery, i) ){
1986 case SQLITE_NULL: {
1987 sqlite3_bind_null(pInsert, i+1);
1988 break;
1989 }
1990 case SQLITE_INTEGER: {
1991 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
1992 break;
1993 }
1994 case SQLITE_FLOAT: {
1995 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
1996 break;
1997 }
1998 case SQLITE_TEXT: {
1999 sqlite3_bind_text(pInsert, i+1,
2000 (const char*)sqlite3_column_text(pQuery,i),
2001 -1, SQLITE_STATIC);
2002 break;
2003 }
2004 case SQLITE_BLOB: {
2005 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
2006 sqlite3_column_bytes(pQuery,i),
2007 SQLITE_STATIC);
2008 break;
2009 }
2010 }
2011 } /* End for */
2012 rc = sqlite3_step(pInsert);
2013 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
2014 fprintf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
2015 sqlite3_errmsg(newDb));
2016 }
2017 sqlite3_reset(pInsert);
2018 cnt++;
2019 if( (cnt%spinRate)==0 ){
2020 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
2021 fflush(stdout);
2022 }
2023 } /* End while */
2024 if( rc==SQLITE_DONE ) break;
2025 sqlite3_finalize(pQuery);
2026 sqlite3_free(zQuery);
2027 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
2028 zTable);
2029 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2030 if( rc ){
2031 fprintf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
2032 break;
2033 }
2034 } /* End for(k=0...) */
2035
2036end_data_xfer:
2037 sqlite3_finalize(pQuery);
2038 sqlite3_finalize(pInsert);
2039 sqlite3_free(zQuery);
2040 sqlite3_free(zInsert);
2041}
2042
2043
2044/*
2045** Try to transfer all rows of the schema that match zWhere. For
2046** each row, invoke xForEach() on the object defined by that row.
2047** If an error is encountered while moving forward through the
2048** sqlite_master table, try again moving backwards.
2049*/
2050static void tryToCloneSchema(
2051 struct callback_data *p,
2052 sqlite3 *newDb,
2053 const char *zWhere,
2054 void (*xForEach)(struct callback_data*,sqlite3*,const char*)
2055){
2056 sqlite3_stmt *pQuery = 0;
2057 char *zQuery = 0;
2058 int rc;
2059 const unsigned char *zName;
2060 const unsigned char *zSql;
2061 char *zErrMsg = 0;
2062
2063 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
2064 " WHERE %s", zWhere);
2065 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2066 if( rc ){
2067 fprintf(stderr, "Error: (%d) %s on [%s]\n",
2068 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
2069 zQuery);
2070 goto end_schema_xfer;
2071 }
2072 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
2073 zName = sqlite3_column_text(pQuery, 0);
2074 zSql = sqlite3_column_text(pQuery, 1);
2075 printf("%s... ", zName); fflush(stdout);
2076 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
2077 if( zErrMsg ){
2078 fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
2079 sqlite3_free(zErrMsg);
2080 zErrMsg = 0;
2081 }
2082 if( xForEach ){
2083 xForEach(p, newDb, (const char*)zName);
2084 }
2085 printf("done\n");
2086 }
2087 if( rc!=SQLITE_DONE ){
2088 sqlite3_finalize(pQuery);
2089 sqlite3_free(zQuery);
2090 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
2091 " WHERE %s ORDER BY rowid DESC", zWhere);
2092 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
2093 if( rc ){
2094 fprintf(stderr, "Error: (%d) %s on [%s]\n",
2095 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
2096 zQuery);
2097 goto end_schema_xfer;
2098 }
2099 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
2100 zName = sqlite3_column_text(pQuery, 0);
2101 zSql = sqlite3_column_text(pQuery, 1);
2102 printf("%s... ", zName); fflush(stdout);
2103 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
2104 if( zErrMsg ){
2105 fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
2106 sqlite3_free(zErrMsg);
2107 zErrMsg = 0;
2108 }
2109 if( xForEach ){
2110 xForEach(p, newDb, (const char*)zName);
2111 }
2112 printf("done\n");
2113 }
2114 }
2115end_schema_xfer:
2116 sqlite3_finalize(pQuery);
2117 sqlite3_free(zQuery);
2118}
2119
2120/*
2121** Open a new database file named "zNewDb". Try to recover as much information
2122** as possible out of the main database (which might be corrupt) and write it
2123** into zNewDb.
2124*/
2125static void tryToClone(struct callback_data *p, const char *zNewDb){
2126 int rc;
2127 sqlite3 *newDb = 0;
2128 if( access(zNewDb,0)==0 ){
2129 fprintf(stderr, "File \"%s\" already exists.\n", zNewDb);
2130 return;
2131 }
2132 rc = sqlite3_open(zNewDb, &newDb);
2133 if( rc ){
2134 fprintf(stderr, "Cannot create output database: %s\n",
2135 sqlite3_errmsg(newDb));
2136 }else{
2137 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
2138 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
2139 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
2140 tryToCloneSchema(p, newDb, "type!='table'", 0);
2141 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
2142 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
2143 }
2144 sqlite3_close(newDb);
2145}
2146
2147/*
2148** Change the output file back to stdout
2149*/
2150static void output_reset(struct callback_data *p){
2151 if( p->outfile[0]=='|' ){
2152 pclose(p->out);
2153 }else{
2154 output_file_close(p->out);
2155 }
2156 p->outfile[0] = 0;
2157 p->out = stdout;
2158}
2159
2160/*
1627** If an input line begins with "." then invoke this routine to
1628** process that line.
1629**
1630** Return 1 on error, 2 to exit, and 0 otherwise.
1631*/
1632static int do_meta_command(char *zLine, struct callback_data *p){
1633 int i = 1;
1634 int nArg = 0;

--- 4 unchanged lines hidden (view full) ---

1639 /* Parse the input line into tokens.
1640 */
1641 while( zLine[i] && nArg<ArraySize(azArg) ){
1642 while( IsSpace(zLine[i]) ){ i++; }
1643 if( zLine[i]==0 ) break;
1644 if( zLine[i]=='\'' || zLine[i]=='"' ){
1645 int delim = zLine[i++];
1646 azArg[nArg++] = &zLine[i];
2161** If an input line begins with "." then invoke this routine to
2162** process that line.
2163**
2164** Return 1 on error, 2 to exit, and 0 otherwise.
2165*/
2166static int do_meta_command(char *zLine, struct callback_data *p){
2167 int i = 1;
2168 int nArg = 0;

--- 4 unchanged lines hidden (view full) ---

2173 /* Parse the input line into tokens.
2174 */
2175 while( zLine[i] && nArg<ArraySize(azArg) ){
2176 while( IsSpace(zLine[i]) ){ i++; }
2177 if( zLine[i]==0 ) break;
2178 if( zLine[i]=='\'' || zLine[i]=='"' ){
2179 int delim = zLine[i++];
2180 azArg[nArg++] = &zLine[i];
1647 while( zLine[i] && zLine[i]!=delim ){ i++; }
2181 while( zLine[i] && zLine[i]!=delim ){
2182 if( zLine[i]=='\\' && delim=='"' && zLine[i+1]!=0 ) i++;
2183 i++;
2184 }
1648 if( zLine[i]==delim ){
1649 zLine[i++] = 0;
1650 }
1651 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
1652 }else{
1653 azArg[nArg++] = &zLine[i];
1654 while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
1655 if( zLine[i] ) zLine[i++] = 0;
1656 resolve_backslashes(azArg[nArg-1]);
1657 }
1658 }
1659
1660 /* Process the input line.
1661 */
1662 if( nArg==0 ) return 0; /* no tokens, no error */
1663 n = strlen30(azArg[0]);
1664 c = azArg[0][0];
2185 if( zLine[i]==delim ){
2186 zLine[i++] = 0;
2187 }
2188 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
2189 }else{
2190 azArg[nArg++] = &zLine[i];
2191 while( zLine[i] && !IsSpace(zLine[i]) ){ i++; }
2192 if( zLine[i] ) zLine[i++] = 0;
2193 resolve_backslashes(azArg[nArg-1]);
2194 }
2195 }
2196
2197 /* Process the input line.
2198 */
2199 if( nArg==0 ) return 0; /* no tokens, no error */
2200 n = strlen30(azArg[0]);
2201 c = azArg[0][0];
1665 if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 ){
2202 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
2203 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
2204 ){
1666 const char *zDestFile = 0;
1667 const char *zDb = 0;
2205 const char *zDestFile = 0;
2206 const char *zDb = 0;
1668 const char *zKey = 0;
1669 sqlite3 *pDest;
1670 sqlite3_backup *pBackup;
1671 int j;
1672 for(j=1; j<nArg; j++){
1673 const char *z = azArg[j];
1674 if( z[0]=='-' ){
1675 while( z[0]=='-' ) z++;
2207 sqlite3 *pDest;
2208 sqlite3_backup *pBackup;
2209 int j;
2210 for(j=1; j<nArg; j++){
2211 const char *z = azArg[j];
2212 if( z[0]=='-' ){
2213 while( z[0]=='-' ) z++;
1676 if( strcmp(z,"key")==0 && j<nArg-1 ){
1677 zKey = azArg[++j];
1678 }else
2214 /* No options to process at this time */
1679 {
1680 fprintf(stderr, "unknown option: %s\n", azArg[j]);
1681 return 1;
1682 }
1683 }else if( zDestFile==0 ){
1684 zDestFile = azArg[j];
1685 }else if( zDb==0 ){
1686 zDb = zDestFile;

--- 9 unchanged lines hidden (view full) ---

1696 }
1697 if( zDb==0 ) zDb = "main";
1698 rc = sqlite3_open(zDestFile, &pDest);
1699 if( rc!=SQLITE_OK ){
1700 fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
1701 sqlite3_close(pDest);
1702 return 1;
1703 }
2215 {
2216 fprintf(stderr, "unknown option: %s\n", azArg[j]);
2217 return 1;
2218 }
2219 }else if( zDestFile==0 ){
2220 zDestFile = azArg[j];
2221 }else if( zDb==0 ){
2222 zDb = zDestFile;

--- 9 unchanged lines hidden (view full) ---

2232 }
2233 if( zDb==0 ) zDb = "main";
2234 rc = sqlite3_open(zDestFile, &pDest);
2235 if( rc!=SQLITE_OK ){
2236 fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
2237 sqlite3_close(pDest);
2238 return 1;
2239 }
1704#ifdef SQLITE_HAS_CODEC
1705 sqlite3_key(pDest, zKey, (int)strlen(zKey));
1706#else
1707 (void)zKey;
1708#endif
1709 open_db(p);
2240 open_db(p, 0);
1710 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
1711 if( pBackup==0 ){
1712 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
1713 sqlite3_close(pDest);
1714 return 1;
1715 }
1716 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
1717 sqlite3_backup_finish(pBackup);
1718 if( rc==SQLITE_DONE ){
1719 rc = 0;
1720 }else{
1721 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
1722 rc = 1;
1723 }
1724 sqlite3_close(pDest);
1725 }else
1726
2241 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
2242 if( pBackup==0 ){
2243 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
2244 sqlite3_close(pDest);
2245 return 1;
2246 }
2247 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
2248 sqlite3_backup_finish(pBackup);
2249 if( rc==SQLITE_DONE ){
2250 rc = 0;
2251 }else{
2252 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
2253 rc = 1;
2254 }
2255 sqlite3_close(pDest);
2256 }else
2257
1727 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){
1728 bail_on_error = booleanValue(azArg[1]);
2258 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
2259 if( nArg==2 ){
2260 bail_on_error = booleanValue(azArg[1]);
2261 }else{
2262 fprintf(stderr, "Usage: .bail on|off\n");
2263 rc = 1;
2264 }
1729 }else
1730
1731 /* The undocumented ".breakpoint" command causes a call to the no-op
1732 ** routine named test_breakpoint().
1733 */
1734 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
1735 test_breakpoint();
1736 }else
1737
2265 }else
2266
2267 /* The undocumented ".breakpoint" command causes a call to the no-op
2268 ** routine named test_breakpoint().
2269 */
2270 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
2271 test_breakpoint();
2272 }else
2273
1738 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){
2274 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
2275 if( nArg==2 ){
2276 tryToClone(p, azArg[1]);
2277 }else{
2278 fprintf(stderr, "Usage: .clone FILENAME\n");
2279 rc = 1;
2280 }
2281 }else
2282
2283 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
1739 struct callback_data data;
1740 char *zErrMsg = 0;
2284 struct callback_data data;
2285 char *zErrMsg = 0;
1741 open_db(p);
2286 open_db(p, 0);
1742 memcpy(&data, p, sizeof(data));
1743 data.showHeader = 1;
1744 data.mode = MODE_Column;
1745 data.colWidth[0] = 3;
1746 data.colWidth[1] = 15;
1747 data.colWidth[2] = 58;
1748 data.cnt = 0;
1749 sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
1750 if( zErrMsg ){
1751 fprintf(stderr,"Error: %s\n", zErrMsg);
1752 sqlite3_free(zErrMsg);
1753 rc = 1;
1754 }
1755 }else
1756
2287 memcpy(&data, p, sizeof(data));
2288 data.showHeader = 1;
2289 data.mode = MODE_Column;
2290 data.colWidth[0] = 3;
2291 data.colWidth[1] = 15;
2292 data.colWidth[2] = 58;
2293 data.cnt = 0;
2294 sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
2295 if( zErrMsg ){
2296 fprintf(stderr,"Error: %s\n", zErrMsg);
2297 sqlite3_free(zErrMsg);
2298 rc = 1;
2299 }
2300 }else
2301
1757 if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){
1758 open_db(p);
2302 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
2303 open_db(p, 0);
1759 /* When playing back a "dump", the content might appear in an order
1760 ** which causes immediate foreign key constraints to be violated.
1761 ** So disable foreign-key constraint enforcement to prevent problems. */
2304 /* When playing back a "dump", the content might appear in an order
2305 ** which causes immediate foreign key constraints to be violated.
2306 ** So disable foreign-key constraint enforcement to prevent problems. */
2307 if( nArg!=1 && nArg!=2 ){
2308 fprintf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
2309 rc = 1;
2310 goto meta_command_exit;
2311 }
1762 fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
1763 fprintf(p->out, "BEGIN TRANSACTION;\n");
1764 p->writableSchema = 0;
1765 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
1766 p->nErr = 0;
1767 if( nArg==1 ){
1768 run_schema_dump_query(p,
1769 "SELECT name, type, sql FROM sqlite_master "

--- 28 unchanged lines hidden (view full) ---

1798 fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
1799 p->writableSchema = 0;
1800 }
1801 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
1802 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
1803 fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
1804 }else
1805
2312 fprintf(p->out, "PRAGMA foreign_keys=OFF;\n");
2313 fprintf(p->out, "BEGIN TRANSACTION;\n");
2314 p->writableSchema = 0;
2315 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
2316 p->nErr = 0;
2317 if( nArg==1 ){
2318 run_schema_dump_query(p,
2319 "SELECT name, type, sql FROM sqlite_master "

--- 28 unchanged lines hidden (view full) ---

2348 fprintf(p->out, "PRAGMA writable_schema=OFF;\n");
2349 p->writableSchema = 0;
2350 }
2351 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
2352 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
2353 fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
2354 }else
2355
1806 if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
1807 p->echoOn = booleanValue(azArg[1]);
2356 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
2357 if( nArg==2 ){
2358 p->echoOn = booleanValue(azArg[1]);
2359 }else{
2360 fprintf(stderr, "Usage: .echo on|off\n");
2361 rc = 1;
2362 }
1808 }else
1809
2363 }else
2364
2365 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
2366 if( nArg==2 ){
2367 p->autoEQP = booleanValue(azArg[1]);
2368 }else{
2369 fprintf(stderr, "Usage: .eqp on|off\n");
2370 rc = 1;
2371 }
2372 }else
2373
1810 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
2374 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
1811 if( nArg>1 && (rc = atoi(azArg[1]))!=0 ) exit(rc);
2375 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
1812 rc = 2;
1813 }else
1814
2376 rc = 2;
2377 }else
2378
1815 if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
2379 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
1816 int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
1817 if(val == 1) {
1818 if(!p->explainPrev.valid) {
1819 p->explainPrev.valid = 1;
1820 p->explainPrev.mode = p->mode;
1821 p->explainPrev.showHeader = p->showHeader;
1822 memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
1823 }
1824 /* We could put this code under the !p->explainValid
1825 ** condition so that it does not execute if we are already in
1826 ** explain mode. However, always executing it allows us an easy
1827 ** was to reset to explain mode in case the user previously
1828 ** did an .explain followed by a .width, .mode or .header
1829 ** command.
1830 */
1831 p->mode = MODE_Explain;
1832 p->showHeader = 1;
2380 int val = nArg>=2 ? booleanValue(azArg[1]) : 1;
2381 if(val == 1) {
2382 if(!p->explainPrev.valid) {
2383 p->explainPrev.valid = 1;
2384 p->explainPrev.mode = p->mode;
2385 p->explainPrev.showHeader = p->showHeader;
2386 memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth));
2387 }
2388 /* We could put this code under the !p->explainValid
2389 ** condition so that it does not execute if we are already in
2390 ** explain mode. However, always executing it allows us an easy
2391 ** was to reset to explain mode in case the user previously
2392 ** did an .explain followed by a .width, .mode or .header
2393 ** command.
2394 */
2395 p->mode = MODE_Explain;
2396 p->showHeader = 1;
1833 memset(p->colWidth,0,ArraySize(p->colWidth));
2397 memset(p->colWidth,0,sizeof(p->colWidth));
1834 p->colWidth[0] = 4; /* addr */
1835 p->colWidth[1] = 13; /* opcode */
1836 p->colWidth[2] = 4; /* P1 */
1837 p->colWidth[3] = 4; /* P2 */
1838 p->colWidth[4] = 4; /* P3 */
1839 p->colWidth[5] = 13; /* P4 */
1840 p->colWidth[6] = 2; /* P5 */
1841 p->colWidth[7] = 13; /* Comment */
1842 }else if (p->explainPrev.valid) {
1843 p->explainPrev.valid = 0;
1844 p->mode = p->explainPrev.mode;
1845 p->showHeader = p->explainPrev.showHeader;
1846 memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
1847 }
1848 }else
1849
2398 p->colWidth[0] = 4; /* addr */
2399 p->colWidth[1] = 13; /* opcode */
2400 p->colWidth[2] = 4; /* P1 */
2401 p->colWidth[3] = 4; /* P2 */
2402 p->colWidth[4] = 4; /* P3 */
2403 p->colWidth[5] = 13; /* P4 */
2404 p->colWidth[6] = 2; /* P5 */
2405 p->colWidth[7] = 13; /* Comment */
2406 }else if (p->explainPrev.valid) {
2407 p->explainPrev.valid = 0;
2408 p->mode = p->explainPrev.mode;
2409 p->showHeader = p->explainPrev.showHeader;
2410 memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth));
2411 }
2412 }else
2413
1850 if( c=='h' && (strncmp(azArg[0], "header", n)==0 ||
1851 strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){
1852 p->showHeader = booleanValue(azArg[1]);
2414 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
2415 if( nArg==2 ){
2416 p->showHeader = booleanValue(azArg[1]);
2417 }else{
2418 fprintf(stderr, "Usage: .headers on|off\n");
2419 rc = 1;
2420 }
1853 }else
1854
1855 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
2421 }else
2422
2423 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
1856 fprintf(stderr,"%s",zHelp);
1857 if( HAS_TIMER ){
1858 fprintf(stderr,"%s",zTimerHelp);
1859 }
2424 fprintf(p->out, "%s", zHelp);
1860 }else
1861
2425 }else
2426
1862 if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
1863 char *zTable = azArg[2]; /* Insert data into this table */
1864 char *zFile = azArg[1]; /* The file from which to extract data */
2427 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
2428 char *zTable; /* Insert data into this table */
2429 char *zFile; /* Name of file to extra content from */
1865 sqlite3_stmt *pStmt = NULL; /* A statement */
1866 int nCol; /* Number of columns in the table */
1867 int nByte; /* Number of bytes in an SQL string */
1868 int i, j; /* Loop counters */
2430 sqlite3_stmt *pStmt = NULL; /* A statement */
2431 int nCol; /* Number of columns in the table */
2432 int nByte; /* Number of bytes in an SQL string */
2433 int i, j; /* Loop counters */
2434 int needCommit; /* True to COMMIT or ROLLBACK at end */
1869 int nSep; /* Number of bytes in p->separator[] */
1870 char *zSql; /* An SQL statement */
2435 int nSep; /* Number of bytes in p->separator[] */
2436 char *zSql; /* An SQL statement */
1871 char *zLine; /* A single line of input from the file */
1872 char **azCol; /* zLine[] broken up into columns */
1873 char *zCommit; /* How to commit changes */
1874 FILE *in; /* The input file */
1875 int lineno = 0; /* Line number of input file */
2437 CSVReader sCsv; /* Reader context */
2438 int (*xCloser)(FILE*); /* Procedure to close th3 connection */
1876
2439
1877 open_db(p);
2440 if( nArg!=3 ){
2441 fprintf(stderr, "Usage: .import FILE TABLE\n");
2442 goto meta_command_exit;
2443 }
2444 zFile = azArg[1];
2445 zTable = azArg[2];
2446 seenInterrupt = 0;
2447 memset(&sCsv, 0, sizeof(sCsv));
2448 open_db(p, 0);
1878 nSep = strlen30(p->separator);
1879 if( nSep==0 ){
1880 fprintf(stderr, "Error: non-null separator required for import\n");
1881 return 1;
1882 }
2449 nSep = strlen30(p->separator);
2450 if( nSep==0 ){
2451 fprintf(stderr, "Error: non-null separator required for import\n");
2452 return 1;
2453 }
2454 if( nSep>1 ){
2455 fprintf(stderr, "Error: multi-character separators not allowed"
2456 " for import\n");
2457 return 1;
2458 }
2459 sCsv.zFile = zFile;
2460 sCsv.nLine = 1;
2461 if( sCsv.zFile[0]=='|' ){
2462 sCsv.in = popen(sCsv.zFile+1, "r");
2463 sCsv.zFile = "<pipe>";
2464 xCloser = pclose;
2465 }else{
2466 sCsv.in = fopen(sCsv.zFile, "rb");
2467 xCloser = fclose;
2468 }
2469 if( sCsv.in==0 ){
2470 fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
2471 return 1;
2472 }
2473 sCsv.cSeparator = p->separator[0];
1883 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
1884 if( zSql==0 ){
1885 fprintf(stderr, "Error: out of memory\n");
2474 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
2475 if( zSql==0 ){
2476 fprintf(stderr, "Error: out of memory\n");
2477 xCloser(sCsv.in);
1886 return 1;
1887 }
1888 nByte = strlen30(zSql);
2478 return 1;
2479 }
2480 nByte = strlen30(zSql);
1889 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
2481 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2482 csv_append_char(&sCsv, 0); /* To ensure sCsv.z is allocated */
2483 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(db))==0 ){
2484 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
2485 char cSep = '(';
2486 while( csv_read_one_field(&sCsv) ){
2487 zCreate = sqlite3_mprintf("%z%c\n \"%s\" TEXT", zCreate, cSep, sCsv.z);
2488 cSep = ',';
2489 if( sCsv.cTerm!=sCsv.cSeparator ) break;
2490 }
2491 if( cSep=='(' ){
2492 sqlite3_free(zCreate);
2493 sqlite3_free(sCsv.z);
2494 xCloser(sCsv.in);
2495 fprintf(stderr,"%s: empty file\n", sCsv.zFile);
2496 return 1;
2497 }
2498 zCreate = sqlite3_mprintf("%z\n)", zCreate);
2499 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
2500 sqlite3_free(zCreate);
2501 if( rc ){
2502 fprintf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
2503 sqlite3_errmsg(db));
2504 sqlite3_free(sCsv.z);
2505 xCloser(sCsv.in);
2506 return 1;
2507 }
2508 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2509 }
1890 sqlite3_free(zSql);
1891 if( rc ){
1892 if (pStmt) sqlite3_finalize(pStmt);
1893 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
2510 sqlite3_free(zSql);
2511 if( rc ){
2512 if (pStmt) sqlite3_finalize(pStmt);
2513 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
2514 xCloser(sCsv.in);
1894 return 1;
1895 }
1896 nCol = sqlite3_column_count(pStmt);
1897 sqlite3_finalize(pStmt);
1898 pStmt = 0;
1899 if( nCol==0 ) return 0; /* no columns, no error */
2515 return 1;
2516 }
2517 nCol = sqlite3_column_count(pStmt);
2518 sqlite3_finalize(pStmt);
2519 pStmt = 0;
2520 if( nCol==0 ) return 0; /* no columns, no error */
1900 zSql = malloc( nByte + 20 + nCol*2 );
2521 zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 );
1901 if( zSql==0 ){
1902 fprintf(stderr, "Error: out of memory\n");
2522 if( zSql==0 ){
2523 fprintf(stderr, "Error: out of memory\n");
2524 xCloser(sCsv.in);
1903 return 1;
1904 }
2525 return 1;
2526 }
1905 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO %s VALUES(?", zTable);
2527 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
1906 j = strlen30(zSql);
1907 for(i=1; i<nCol; i++){
1908 zSql[j++] = ',';
1909 zSql[j++] = '?';
1910 }
1911 zSql[j++] = ')';
1912 zSql[j] = 0;
2528 j = strlen30(zSql);
2529 for(i=1; i<nCol; i++){
2530 zSql[j++] = ',';
2531 zSql[j++] = '?';
2532 }
2533 zSql[j++] = ')';
2534 zSql[j] = 0;
1913 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
1914 free(zSql);
2535 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2536 sqlite3_free(zSql);
1915 if( rc ){
1916 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
1917 if (pStmt) sqlite3_finalize(pStmt);
2537 if( rc ){
2538 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
2539 if (pStmt) sqlite3_finalize(pStmt);
2540 xCloser(sCsv.in);
1918 return 1;
1919 }
2541 return 1;
2542 }
1920 in = fopen(zFile, "rb");
1921 if( in==0 ){
1922 fprintf(stderr, "Error: cannot open \"%s\"\n", zFile);
1923 sqlite3_finalize(pStmt);
1924 return 1;
1925 }
1926 azCol = malloc( sizeof(azCol[0])*(nCol+1) );
1927 if( azCol==0 ){
1928 fprintf(stderr, "Error: out of memory\n");
1929 fclose(in);
1930 sqlite3_finalize(pStmt);
1931 return 1;
1932 }
1933 sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
1934 zCommit = "COMMIT";
1935 while( (zLine = local_getline(0, in, 1))!=0 ){
1936 char *z, c;
1937 int inQuote = 0;
1938 lineno++;
1939 azCol[0] = zLine;
1940 for(i=0, z=zLine; (c = *z)!=0; z++){
1941 if( c=='"' ) inQuote = !inQuote;
1942 if( c=='\n' ) lineno++;
1943 if( !inQuote && c==p->separator[0] && strncmp(z,p->separator,nSep)==0 ){
1944 *z = 0;
2543 needCommit = sqlite3_get_autocommit(db);
2544 if( needCommit ) sqlite3_exec(db, "BEGIN", 0, 0, 0);
2545 do{
2546 int startLine = sCsv.nLine;
2547 for(i=0; i<nCol; i++){
2548 char *z = csv_read_one_field(&sCsv);
2549 if( z==0 && i==0 ) break;
2550 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
2551 if( i<nCol-1 && sCsv.cTerm!=sCsv.cSeparator ){
2552 fprintf(stderr, "%s:%d: expected %d columns but found %d - "
2553 "filling the rest with NULL\n",
2554 sCsv.zFile, startLine, nCol, i+1);
1945 i++;
2555 i++;
1946 if( i<nCol ){
1947 azCol[i] = &z[nSep];
1948 z += nSep-1;
1949 }
2556 while( i<nCol ){ sqlite3_bind_null(pStmt, i); i++; }
1950 }
2557 }
1951 } /* end for */
1952 *z = 0;
1953 if( i+1!=nCol ){
1954 fprintf(stderr,
1955 "Error: %s line %d: expected %d columns of data but found %d\n",
1956 zFile, lineno, nCol, i+1);
1957 zCommit = "ROLLBACK";
1958 free(zLine);
1959 rc = 1;
1960 break; /* from while */
1961 }
2558 }
1962 for(i=0; i<nCol; i++){
1963 if( azCol[i][0]=='"' ){
1964 int k;
1965 for(z=azCol[i], j=1, k=0; z[j]; j++){
1966 if( z[j]=='"' ){ j++; if( z[j]==0 ) break; }
1967 z[k++] = z[j];
1968 }
1969 z[k] = 0;
2559 if( sCsv.cTerm==sCsv.cSeparator ){
2560 do{
2561 csv_read_one_field(&sCsv);
2562 i++;
2563 }while( sCsv.cTerm==sCsv.cSeparator );
2564 fprintf(stderr, "%s:%d: expected %d columns but found %d - "
2565 "extras ignored\n",
2566 sCsv.zFile, startLine, nCol, i);
2567 }
2568 if( i>=nCol ){
2569 sqlite3_step(pStmt);
2570 rc = sqlite3_reset(pStmt);
2571 if( rc!=SQLITE_OK ){
2572 fprintf(stderr, "%s:%d: INSERT failed: %s\n", sCsv.zFile, startLine,
2573 sqlite3_errmsg(db));
1970 }
2574 }
1971 sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC);
1972 }
2575 }
1973 sqlite3_step(pStmt);
1974 rc = sqlite3_reset(pStmt);
1975 free(zLine);
1976 if( rc!=SQLITE_OK ){
1977 fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
1978 zCommit = "ROLLBACK";
1979 rc = 1;
1980 break; /* from while */
1981 }
1982 } /* end while */
1983 free(azCol);
1984 fclose(in);
2576 }while( sCsv.cTerm!=EOF );
2577
2578 xCloser(sCsv.in);
2579 sqlite3_free(sCsv.z);
1985 sqlite3_finalize(pStmt);
2580 sqlite3_finalize(pStmt);
1986 sqlite3_exec(p->db, zCommit, 0, 0, 0);
2581 if( needCommit ) sqlite3_exec(db, "COMMIT", 0, 0, 0);
1987 }else
1988
2582 }else
2583
1989 if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
2584 if( c=='i' && strncmp(azArg[0], "indices", n)==0 ){
1990 struct callback_data data;
1991 char *zErrMsg = 0;
2585 struct callback_data data;
2586 char *zErrMsg = 0;
1992 open_db(p);
2587 open_db(p, 0);
1993 memcpy(&data, p, sizeof(data));
1994 data.showHeader = 0;
1995 data.mode = MODE_List;
1996 if( nArg==1 ){
1997 rc = sqlite3_exec(p->db,
1998 "SELECT name FROM sqlite_master "
1999 "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
2000 "UNION ALL "
2001 "SELECT name FROM sqlite_temp_master "
2002 "WHERE type='index' "
2003 "ORDER BY 1",
2004 callback, &data, &zErrMsg
2005 );
2588 memcpy(&data, p, sizeof(data));
2589 data.showHeader = 0;
2590 data.mode = MODE_List;
2591 if( nArg==1 ){
2592 rc = sqlite3_exec(p->db,
2593 "SELECT name FROM sqlite_master "
2594 "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
2595 "UNION ALL "
2596 "SELECT name FROM sqlite_temp_master "
2597 "WHERE type='index' "
2598 "ORDER BY 1",
2599 callback, &data, &zErrMsg
2600 );
2006 }else{
2601 }else if( nArg==2 ){
2007 zShellStatic = azArg[1];
2008 rc = sqlite3_exec(p->db,
2009 "SELECT name FROM sqlite_master "
2010 "WHERE type='index' AND tbl_name LIKE shellstatic() "
2011 "UNION ALL "
2012 "SELECT name FROM sqlite_temp_master "
2013 "WHERE type='index' AND tbl_name LIKE shellstatic() "
2014 "ORDER BY 1",
2015 callback, &data, &zErrMsg
2016 );
2017 zShellStatic = 0;
2602 zShellStatic = azArg[1];
2603 rc = sqlite3_exec(p->db,
2604 "SELECT name FROM sqlite_master "
2605 "WHERE type='index' AND tbl_name LIKE shellstatic() "
2606 "UNION ALL "
2607 "SELECT name FROM sqlite_temp_master "
2608 "WHERE type='index' AND tbl_name LIKE shellstatic() "
2609 "ORDER BY 1",
2610 callback, &data, &zErrMsg
2611 );
2612 zShellStatic = 0;
2613 }else{
2614 fprintf(stderr, "Usage: .indices ?LIKE-PATTERN?\n");
2615 rc = 1;
2616 goto meta_command_exit;
2018 }
2019 if( zErrMsg ){
2020 fprintf(stderr,"Error: %s\n", zErrMsg);
2021 sqlite3_free(zErrMsg);
2022 rc = 1;
2023 }else if( rc != SQLITE_OK ){
2024 fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
2025 rc = 1;

--- 19 unchanged lines hidden (view full) ---

2045 }else{
2046 sqlite3IoTrace = iotracePrintf;
2047 }
2048 }
2049 }else
2050#endif
2051
2052#ifndef SQLITE_OMIT_LOAD_EXTENSION
2617 }
2618 if( zErrMsg ){
2619 fprintf(stderr,"Error: %s\n", zErrMsg);
2620 sqlite3_free(zErrMsg);
2621 rc = 1;
2622 }else if( rc != SQLITE_OK ){
2623 fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n");
2624 rc = 1;

--- 19 unchanged lines hidden (view full) ---

2644 }else{
2645 sqlite3IoTrace = iotracePrintf;
2646 }
2647 }
2648 }else
2649#endif
2650
2651#ifndef SQLITE_OMIT_LOAD_EXTENSION
2053 if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){
2652 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
2054 const char *zFile, *zProc;
2055 char *zErrMsg = 0;
2653 const char *zFile, *zProc;
2654 char *zErrMsg = 0;
2655 if( nArg<2 ){
2656 fprintf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
2657 rc = 1;
2658 goto meta_command_exit;
2659 }
2056 zFile = azArg[1];
2057 zProc = nArg>=3 ? azArg[2] : 0;
2660 zFile = azArg[1];
2661 zProc = nArg>=3 ? azArg[2] : 0;
2058 open_db(p);
2662 open_db(p, 0);
2059 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
2060 if( rc!=SQLITE_OK ){
2061 fprintf(stderr, "Error: %s\n", zErrMsg);
2062 sqlite3_free(zErrMsg);
2063 rc = 1;
2064 }
2065 }else
2066#endif
2067
2663 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
2664 if( rc!=SQLITE_OK ){
2665 fprintf(stderr, "Error: %s\n", zErrMsg);
2666 sqlite3_free(zErrMsg);
2667 rc = 1;
2668 }
2669 }else
2670#endif
2671
2068 if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){
2069 const char *zFile = azArg[1];
2070 output_file_close(p->pLog);
2071 p->pLog = output_file_open(zFile);
2672 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
2673 if( nArg!=2 ){
2674 fprintf(stderr, "Usage: .log FILENAME\n");
2675 rc = 1;
2676 }else{
2677 const char *zFile = azArg[1];
2678 output_file_close(p->pLog);
2679 p->pLog = output_file_open(zFile);
2680 }
2072 }else
2073
2681 }else
2682
2074 if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){
2075 int n2 = strlen30(azArg[1]);
2076 if( (n2==4 && strncmp(azArg[1],"line",n2)==0)
2077 ||
2078 (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){
2683 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
2684 const char *zMode = nArg>=2 ? azArg[1] : "";
2685 int n2 = (int)strlen(zMode);
2686 int c2 = zMode[0];
2687 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
2079 p->mode = MODE_Line;
2688 p->mode = MODE_Line;
2080 }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0)
2081 ||
2082 (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){
2689 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
2083 p->mode = MODE_Column;
2690 p->mode = MODE_Column;
2084 }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){
2691 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
2085 p->mode = MODE_List;
2692 p->mode = MODE_List;
2086 }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){
2693 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
2087 p->mode = MODE_Html;
2694 p->mode = MODE_Html;
2088 }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){
2695 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
2089 p->mode = MODE_Tcl;
2090 sqlite3_snprintf(sizeof(p->separator), p->separator, " ");
2696 p->mode = MODE_Tcl;
2697 sqlite3_snprintf(sizeof(p->separator), p->separator, " ");
2091 }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){
2698 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
2092 p->mode = MODE_Csv;
2093 sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
2699 p->mode = MODE_Csv;
2700 sqlite3_snprintf(sizeof(p->separator), p->separator, ",");
2094 }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){
2701 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
2095 p->mode = MODE_List;
2096 sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
2702 p->mode = MODE_List;
2703 sqlite3_snprintf(sizeof(p->separator), p->separator, "\t");
2097 }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
2704 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
2098 p->mode = MODE_Insert;
2705 p->mode = MODE_Insert;
2099 set_table_name(p, "table");
2706 set_table_name(p, nArg>=3 ? azArg[2] : "table");
2100 }else {
2101 fprintf(stderr,"Error: mode should be one of: "
2102 "column csv html insert line list tabs tcl\n");
2103 rc = 1;
2104 }
2105 }else
2106
2707 }else {
2708 fprintf(stderr,"Error: mode should be one of: "
2709 "column csv html insert line list tabs tcl\n");
2710 rc = 1;
2711 }
2712 }else
2713
2107 if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){
2108 int n2 = strlen30(azArg[1]);
2109 if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){
2110 p->mode = MODE_Insert;
2111 set_table_name(p, azArg[2]);
2112 }else {
2113 fprintf(stderr, "Error: invalid arguments: "
2114 " \"%s\". Enter \".help\" for help\n", azArg[2]);
2714 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
2715 if( nArg==2 ){
2716 sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
2717 "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
2718 }else{
2719 fprintf(stderr, "Usage: .nullvalue STRING\n");
2115 rc = 1;
2116 }
2117 }else
2118
2720 rc = 1;
2721 }
2722 }else
2723
2119 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 && nArg==2 ) {
2120 sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue,
2121 "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]);
2724 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
2725 sqlite3 *savedDb = p->db;
2726 const char *zSavedFilename = p->zDbFilename;
2727 char *zNewFilename = 0;
2728 p->db = 0;
2729 if( nArg>=2 ){
2730 p->zDbFilename = zNewFilename = sqlite3_mprintf("%s", azArg[1]);
2731 }
2732 open_db(p, 1);
2733 if( p->db!=0 ){
2734 sqlite3_close(savedDb);
2735 sqlite3_free(p->zFreeOnClose);
2736 p->zFreeOnClose = zNewFilename;
2737 }else{
2738 sqlite3_free(zNewFilename);
2739 p->db = savedDb;
2740 p->zDbFilename = zSavedFilename;
2741 }
2122 }else
2123
2742 }else
2743
2124 if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
2125 if( p->outfile[0]=='|' ){
2126 pclose(p->out);
2744 if( c=='o'
2745 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
2746 ){
2747 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
2748 if( nArg>2 ){
2749 fprintf(stderr, "Usage: .%s FILE\n", azArg[0]);
2750 rc = 1;
2751 goto meta_command_exit;
2752 }
2753 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
2754 if( nArg<2 ){
2755 fprintf(stderr, "Usage: .once FILE\n");
2756 rc = 1;
2757 goto meta_command_exit;
2758 }
2759 p->outCount = 2;
2127 }else{
2760 }else{
2128 output_file_close(p->out);
2761 p->outCount = 0;
2129 }
2762 }
2130 p->outfile[0] = 0;
2131 if( azArg[1][0]=='|' ){
2132 p->out = popen(&azArg[1][1], "w");
2763 output_reset(p);
2764 if( zFile[0]=='|' ){
2765 p->out = popen(zFile + 1, "w");
2133 if( p->out==0 ){
2766 if( p->out==0 ){
2134 fprintf(stderr,"Error: cannot open pipe \"%s\"\n", &azArg[1][1]);
2767 fprintf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
2135 p->out = stdout;
2136 rc = 1;
2137 }else{
2768 p->out = stdout;
2769 rc = 1;
2770 }else{
2138 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
2771 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
2139 }
2140 }else{
2772 }
2773 }else{
2141 p->out = output_file_open(azArg[1]);
2774 p->out = output_file_open(zFile);
2142 if( p->out==0 ){
2775 if( p->out==0 ){
2143 if( strcmp(azArg[1],"off")!=0 ){
2144 fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]);
2776 if( strcmp(zFile,"off")!=0 ){
2777 fprintf(stderr,"Error: cannot write to \"%s\"\n", zFile);
2145 }
2146 p->out = stdout;
2147 rc = 1;
2148 } else {
2778 }
2779 p->out = stdout;
2780 rc = 1;
2781 } else {
2149 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]);
2782 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
2150 }
2151 }
2152 }else
2153
2154 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
2155 int i;
2156 for(i=1; i<nArg; i++){
2157 if( i>1 ) fprintf(p->out, " ");
2158 fprintf(p->out, "%s", azArg[i]);
2159 }
2160 fprintf(p->out, "\n");
2161 }else
2162
2783 }
2784 }
2785 }else
2786
2787 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
2788 int i;
2789 for(i=1; i<nArg; i++){
2790 if( i>1 ) fprintf(p->out, " ");
2791 fprintf(p->out, "%s", azArg[i]);
2792 }
2793 fprintf(p->out, "\n");
2794 }else
2795
2163 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 && (nArg==2 || nArg==3)){
2796 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
2164 if( nArg >= 2) {
2165 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
2166 }
2167 if( nArg >= 3) {
2168 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
2169 }
2170 }else
2171
2797 if( nArg >= 2) {
2798 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
2799 }
2800 if( nArg >= 3) {
2801 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
2802 }
2803 }else
2804
2172 if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){
2805 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
2173 rc = 2;
2174 }else
2175
2806 rc = 2;
2807 }else
2808
2176 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
2177 FILE *alt = fopen(azArg[1], "rb");
2809 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
2810 FILE *alt;
2811 if( nArg!=2 ){
2812 fprintf(stderr, "Usage: .read FILE\n");
2813 rc = 1;
2814 goto meta_command_exit;
2815 }
2816 alt = fopen(azArg[1], "rb");
2178 if( alt==0 ){
2179 fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
2180 rc = 1;
2181 }else{
2182 rc = process_input(p, alt);
2183 fclose(alt);
2184 }
2185 }else
2186
2817 if( alt==0 ){
2818 fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
2819 rc = 1;
2820 }else{
2821 rc = process_input(p, alt);
2822 fclose(alt);
2823 }
2824 }else
2825
2187 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){
2826 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
2188 const char *zSrcFile;
2189 const char *zDb;
2190 sqlite3 *pSrc;
2191 sqlite3_backup *pBackup;
2192 int nTimeout = 0;
2193
2194 if( nArg==2 ){
2195 zSrcFile = azArg[1];
2196 zDb = "main";
2827 const char *zSrcFile;
2828 const char *zDb;
2829 sqlite3 *pSrc;
2830 sqlite3_backup *pBackup;
2831 int nTimeout = 0;
2832
2833 if( nArg==2 ){
2834 zSrcFile = azArg[1];
2835 zDb = "main";
2197 }else{
2836 }else if( nArg==3 ){
2198 zSrcFile = azArg[2];
2199 zDb = azArg[1];
2837 zSrcFile = azArg[2];
2838 zDb = azArg[1];
2839 }else{
2840 fprintf(stderr, "Usage: .restore ?DB? FILE\n");
2841 rc = 1;
2842 goto meta_command_exit;
2200 }
2201 rc = sqlite3_open(zSrcFile, &pSrc);
2202 if( rc!=SQLITE_OK ){
2203 fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
2204 sqlite3_close(pSrc);
2205 return 1;
2206 }
2843 }
2844 rc = sqlite3_open(zSrcFile, &pSrc);
2845 if( rc!=SQLITE_OK ){
2846 fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
2847 sqlite3_close(pSrc);
2848 return 1;
2849 }
2207 open_db(p);
2850 open_db(p, 0);
2208 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
2209 if( pBackup==0 ){
2210 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2211 sqlite3_close(pSrc);
2212 return 1;
2213 }
2214 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2215 || rc==SQLITE_BUSY ){

--- 10 unchanged lines hidden (view full) ---

2226 rc = 1;
2227 }else{
2228 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2229 rc = 1;
2230 }
2231 sqlite3_close(pSrc);
2232 }else
2233
2851 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
2852 if( pBackup==0 ){
2853 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2854 sqlite3_close(pSrc);
2855 return 1;
2856 }
2857 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
2858 || rc==SQLITE_BUSY ){

--- 10 unchanged lines hidden (view full) ---

2869 rc = 1;
2870 }else{
2871 fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2872 rc = 1;
2873 }
2874 sqlite3_close(pSrc);
2875 }else
2876
2234 if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){
2877 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
2235 struct callback_data data;
2236 char *zErrMsg = 0;
2878 struct callback_data data;
2879 char *zErrMsg = 0;
2237 open_db(p);
2880 open_db(p, 0);
2238 memcpy(&data, p, sizeof(data));
2239 data.showHeader = 0;
2240 data.mode = MODE_Semi;
2881 memcpy(&data, p, sizeof(data));
2882 data.showHeader = 0;
2883 data.mode = MODE_Semi;
2241 if( nArg>1 ){
2884 if( nArg==2 ){
2242 int i;
2243 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
2244 if( strcmp(azArg[1],"sqlite_master")==0 ){
2245 char *new_argv[2], *new_colv[2];
2246 new_argv[0] = "CREATE TABLE sqlite_master (\n"
2247 " type text,\n"
2248 " name text,\n"
2249 " tbl_name text,\n"

--- 27 unchanged lines hidden (view full) ---

2277 " FROM sqlite_master UNION ALL"
2278 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2279 "WHERE lower(tbl_name) LIKE shellstatic()"
2280 " AND type!='meta' AND sql NOTNULL "
2281 "ORDER BY rowid",
2282 callback, &data, &zErrMsg);
2283 zShellStatic = 0;
2284 }
2885 int i;
2886 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
2887 if( strcmp(azArg[1],"sqlite_master")==0 ){
2888 char *new_argv[2], *new_colv[2];
2889 new_argv[0] = "CREATE TABLE sqlite_master (\n"
2890 " type text,\n"
2891 " name text,\n"
2892 " tbl_name text,\n"

--- 27 unchanged lines hidden (view full) ---

2920 " FROM sqlite_master UNION ALL"
2921 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2922 "WHERE lower(tbl_name) LIKE shellstatic()"
2923 " AND type!='meta' AND sql NOTNULL "
2924 "ORDER BY rowid",
2925 callback, &data, &zErrMsg);
2926 zShellStatic = 0;
2927 }
2285 }else{
2928 }else if( nArg==1 ){
2286 rc = sqlite3_exec(p->db,
2287 "SELECT sql FROM "
2288 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
2289 " FROM sqlite_master UNION ALL"
2290 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2291 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
2292 "ORDER BY rowid",
2293 callback, &data, &zErrMsg
2294 );
2929 rc = sqlite3_exec(p->db,
2930 "SELECT sql FROM "
2931 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
2932 " FROM sqlite_master UNION ALL"
2933 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2934 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'"
2935 "ORDER BY rowid",
2936 callback, &data, &zErrMsg
2937 );
2938 }else{
2939 fprintf(stderr, "Usage: .schema ?LIKE-PATTERN?\n");
2940 rc = 1;
2941 goto meta_command_exit;
2295 }
2296 if( zErrMsg ){
2297 fprintf(stderr,"Error: %s\n", zErrMsg);
2298 sqlite3_free(zErrMsg);
2299 rc = 1;
2300 }else if( rc != SQLITE_OK ){
2301 fprintf(stderr,"Error: querying schema information\n");
2302 rc = 1;
2303 }else{
2304 rc = 0;
2305 }
2306 }else
2307
2942 }
2943 if( zErrMsg ){
2944 fprintf(stderr,"Error: %s\n", zErrMsg);
2945 sqlite3_free(zErrMsg);
2946 rc = 1;
2947 }else if( rc != SQLITE_OK ){
2948 fprintf(stderr,"Error: querying schema information\n");
2949 rc = 1;
2950 }else{
2951 rc = 0;
2952 }
2953 }else
2954
2308 if( c=='s' && strncmp(azArg[0], "separator", n)==0 && nArg==2 ){
2309 sqlite3_snprintf(sizeof(p->separator), p->separator,
2310 "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
2955#ifdef SQLITE_DEBUG
2956 /* Undocumented commands for internal testing. Subject to change
2957 ** without notice. */
2958 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
2959 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
2960 int i, v;
2961 for(i=1; i<nArg; i++){
2962 v = booleanValue(azArg[i]);
2963 fprintf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
2964 }
2965 }
2966 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
2967 int i; sqlite3_int64 v;
2968 for(i=1; i<nArg; i++){
2969 char zBuf[200];
2970 v = integerValue(azArg[i]);
2971 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
2972 fprintf(p->out, "%s", zBuf);
2973 }
2974 }
2311 }else
2975 }else
2976#endif
2312
2977
2313 if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
2978 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
2979 if( nArg==2 ){
2980 sqlite3_snprintf(sizeof(p->separator), p->separator,
2981 "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
2982 }else{
2983 fprintf(stderr, "Usage: .separator STRING\n");
2984 rc = 1;
2985 }
2986 }else
2987
2988 if( c=='s'
2989 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
2990 ){
2991 char *zCmd;
2314 int i;
2992 int i;
2993 if( nArg<2 ){
2994 fprintf(stderr, "Usage: .system COMMAND\n");
2995 rc = 1;
2996 goto meta_command_exit;
2997 }
2998 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
2999 for(i=2; i<nArg; i++){
3000 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
3001 zCmd, azArg[i]);
3002 }
3003 (void)system(zCmd);
3004 sqlite3_free(zCmd);
3005 }else
3006
3007 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
3008 int i;
3009 if( nArg!=1 ){
3010 fprintf(stderr, "Usage: .show\n");
3011 rc = 1;
3012 goto meta_command_exit;
3013 }
2315 fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
3014 fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
3015 fprintf(p->out,"%9.9s: %s\n","eqp", p->autoEQP ? "on" : "off");
2316 fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
2317 fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
2318 fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
2319 fprintf(p->out,"%9.9s: ", "nullvalue");
2320 output_c_string(p->out, p->nullvalue);
2321 fprintf(p->out, "\n");
2322 fprintf(p->out,"%9.9s: %s\n","output",
2323 strlen30(p->outfile) ? p->outfile : "stdout");
2324 fprintf(p->out,"%9.9s: ", "separator");
2325 output_c_string(p->out, p->separator);
2326 fprintf(p->out, "\n");
2327 fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
2328 fprintf(p->out,"%9.9s: ","width");
2329 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
2330 fprintf(p->out,"%d ",p->colWidth[i]);
2331 }
2332 fprintf(p->out,"\n");
2333 }else
2334
3016 fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
3017 fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
3018 fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
3019 fprintf(p->out,"%9.9s: ", "nullvalue");
3020 output_c_string(p->out, p->nullvalue);
3021 fprintf(p->out, "\n");
3022 fprintf(p->out,"%9.9s: %s\n","output",
3023 strlen30(p->outfile) ? p->outfile : "stdout");
3024 fprintf(p->out,"%9.9s: ", "separator");
3025 output_c_string(p->out, p->separator);
3026 fprintf(p->out, "\n");
3027 fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off");
3028 fprintf(p->out,"%9.9s: ","width");
3029 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
3030 fprintf(p->out,"%d ",p->colWidth[i]);
3031 }
3032 fprintf(p->out,"\n");
3033 }else
3034
2335 if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){
2336 p->statsOn = booleanValue(azArg[1]);
3035 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
3036 if( nArg==2 ){
3037 p->statsOn = booleanValue(azArg[1]);
3038 }else{
3039 fprintf(stderr, "Usage: .stats on|off\n");
3040 rc = 1;
3041 }
2337 }else
2338
3042 }else
3043
2339 if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){
3044 if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
2340 sqlite3_stmt *pStmt;
2341 char **azResult;
2342 int nRow, nAlloc;
2343 char *zSql = 0;
2344 int ii;
3045 sqlite3_stmt *pStmt;
3046 char **azResult;
3047 int nRow, nAlloc;
3048 char *zSql = 0;
3049 int ii;
2345 open_db(p);
3050 open_db(p, 0);
2346 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
2347 if( rc ) return rc;
2348 zSql = sqlite3_mprintf(
2349 "SELECT name FROM sqlite_master"
2350 " WHERE type IN ('table','view')"
2351 " AND name NOT LIKE 'sqlite_%%'"
2352 " AND name LIKE ?1");
2353 while( sqlite3_step(pStmt)==SQLITE_ROW ){

--- 79 unchanged lines hidden (view full) ---

2433 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
2434 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
2435 { "assert", SQLITE_TESTCTRL_ASSERT },
2436 { "always", SQLITE_TESTCTRL_ALWAYS },
2437 { "reserve", SQLITE_TESTCTRL_RESERVE },
2438 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
2439 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
2440 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
3051 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
3052 if( rc ) return rc;
3053 zSql = sqlite3_mprintf(
3054 "SELECT name FROM sqlite_master"
3055 " WHERE type IN ('table','view')"
3056 " AND name NOT LIKE 'sqlite_%%'"
3057 " AND name LIKE ?1");
3058 while( sqlite3_step(pStmt)==SQLITE_ROW ){

--- 79 unchanged lines hidden (view full) ---

3138 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
3139 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
3140 { "assert", SQLITE_TESTCTRL_ASSERT },
3141 { "always", SQLITE_TESTCTRL_ALWAYS },
3142 { "reserve", SQLITE_TESTCTRL_RESERVE },
3143 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
3144 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
3145 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
3146 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
2441 };
2442 int testctrl = -1;
2443 int rc = 0;
2444 int i, n;
3147 };
3148 int testctrl = -1;
3149 int rc = 0;
3150 int i, n;
2445 open_db(p);
3151 open_db(p, 0);
2446
2447 /* convert testctrl text option to value. allow any unique prefix
2448 ** of the option name, or a numerical value. */
2449 n = strlen30(azArg[1]);
2450 for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
2451 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
2452 if( testctrl<0 ){
2453 testctrl = aCtrl[i].ctrlCode;
2454 }else{
2455 fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
2456 testctrl = -1;
2457 break;
2458 }
2459 }
2460 }
3152
3153 /* convert testctrl text option to value. allow any unique prefix
3154 ** of the option name, or a numerical value. */
3155 n = strlen30(azArg[1]);
3156 for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){
3157 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){
3158 if( testctrl<0 ){
3159 testctrl = aCtrl[i].ctrlCode;
3160 }else{
3161 fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
3162 testctrl = -1;
3163 break;
3164 }
3165 }
3166 }
2461 if( testctrl<0 ) testctrl = atoi(azArg[1]);
3167 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
2462 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
2463 fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
2464 }else{
2465 switch(testctrl){
2466
2467 /* sqlite3_test_control(int, db, int) */
2468 case SQLITE_TESTCTRL_OPTIMIZATIONS:
2469 case SQLITE_TESTCTRL_RESERVE:
2470 if( nArg==3 ){
2471 int opt = (int)strtol(azArg[2], 0, 0);
2472 rc = sqlite3_test_control(testctrl, p->db, opt);
2473 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
2474 } else {
2475 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
2476 azArg[1]);
2477 }
2478 break;
2479
2480 /* sqlite3_test_control(int) */
3168 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
3169 fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
3170 }else{
3171 switch(testctrl){
3172
3173 /* sqlite3_test_control(int, db, int) */
3174 case SQLITE_TESTCTRL_OPTIMIZATIONS:
3175 case SQLITE_TESTCTRL_RESERVE:
3176 if( nArg==3 ){
3177 int opt = (int)strtol(azArg[2], 0, 0);
3178 rc = sqlite3_test_control(testctrl, p->db, opt);
3179 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
3180 } else {
3181 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
3182 azArg[1]);
3183 }
3184 break;
3185
3186 /* sqlite3_test_control(int) */
2481 case SQLITE_TESTCTRL_PRNG_SAVE:
2482 case SQLITE_TESTCTRL_PRNG_RESTORE:
3187 case SQLITE_TESTCTRL_PRNG_SAVE:
3188 case SQLITE_TESTCTRL_PRNG_RESTORE:
2483 case SQLITE_TESTCTRL_PRNG_RESET:
3189 case SQLITE_TESTCTRL_PRNG_RESET:
3190 case SQLITE_TESTCTRL_BYTEORDER:
2484 if( nArg==2 ){
2485 rc = sqlite3_test_control(testctrl);
2486 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
2487 } else {
2488 fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
2489 }
2490 break;
2491
2492 /* sqlite3_test_control(int, uint) */
2493 case SQLITE_TESTCTRL_PENDING_BYTE:
2494 if( nArg==3 ){
3191 if( nArg==2 ){
3192 rc = sqlite3_test_control(testctrl);
3193 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
3194 } else {
3195 fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
3196 }
3197 break;
3198
3199 /* sqlite3_test_control(int, uint) */
3200 case SQLITE_TESTCTRL_PENDING_BYTE:
3201 if( nArg==3 ){
2495 unsigned int opt = (unsigned int)integerValue(azArg[2]);
3202 unsigned int opt = (unsigned int)integerValue(azArg[2]);
2496 rc = sqlite3_test_control(testctrl, opt);
2497 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
2498 } else {
2499 fprintf(stderr,"Error: testctrl %s takes a single unsigned"
2500 " int option\n", azArg[1]);
2501 }
2502 break;
2503
2504 /* sqlite3_test_control(int, int) */
2505 case SQLITE_TESTCTRL_ASSERT:
2506 case SQLITE_TESTCTRL_ALWAYS:
2507 if( nArg==3 ){
3203 rc = sqlite3_test_control(testctrl, opt);
3204 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
3205 } else {
3206 fprintf(stderr,"Error: testctrl %s takes a single unsigned"
3207 " int option\n", azArg[1]);
3208 }
3209 break;
3210
3211 /* sqlite3_test_control(int, int) */
3212 case SQLITE_TESTCTRL_ASSERT:
3213 case SQLITE_TESTCTRL_ALWAYS:
3214 if( nArg==3 ){
2508 int opt = atoi(azArg[2]);
3215 int opt = booleanValue(azArg[2]);
2509 rc = sqlite3_test_control(testctrl, opt);
2510 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
2511 } else {
2512 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
2513 azArg[1]);
2514 }
2515 break;
2516

--- 18 unchanged lines hidden (view full) ---

2535 default:
2536 fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
2537 azArg[1]);
2538 break;
2539 }
2540 }
2541 }else
2542
3216 rc = sqlite3_test_control(testctrl, opt);
3217 fprintf(p->out, "%d (0x%08x)\n", rc, rc);
3218 } else {
3219 fprintf(stderr,"Error: testctrl %s takes a single int option\n",
3220 azArg[1]);
3221 }
3222 break;
3223

--- 18 unchanged lines hidden (view full) ---

3242 default:
3243 fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
3244 azArg[1]);
3245 break;
3246 }
3247 }
3248 }else
3249
2543 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){
2544 open_db(p);
2545 sqlite3_busy_timeout(p->db, atoi(azArg[1]));
3250 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
3251 open_db(p, 0);
3252 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
2546 }else
2547
3253 }else
3254
2548 if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
2549 && nArg==2
2550 ){
2551 enableTimer = booleanValue(azArg[1]);
3255 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
3256 if( nArg==2 ){
3257 enableTimer = booleanValue(azArg[1]);
3258 if( enableTimer && !HAS_TIMER ){
3259 fprintf(stderr, "Error: timer not available on this system.\n");
3260 enableTimer = 0;
3261 }
3262 }else{
3263 fprintf(stderr, "Usage: .timer on|off\n");
3264 rc = 1;
3265 }
2552 }else
2553
3266 }else
3267
2554 if( c=='t' && strncmp(azArg[0], "trace", n)==0 && nArg>1 ){
2555 open_db(p);
3268 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
3269 open_db(p, 0);
2556 output_file_close(p->traceOut);
3270 output_file_close(p->traceOut);
3271 if( nArg!=2 ){
3272 fprintf(stderr, "Usage: .trace FILE|off\n");
3273 rc = 1;
3274 goto meta_command_exit;
3275 }
2557 p->traceOut = output_file_open(azArg[1]);
2558#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2559 if( p->traceOut==0 ){
2560 sqlite3_trace(p->db, 0, 0);
2561 }else{
2562 sqlite3_trace(p->db, sql_trace_callback, p->traceOut);
2563 }
2564#endif

--- 14 unchanged lines hidden (view full) ---

2579 sqlite3_free(zVfsName);
2580 }
2581 }
2582 }else
2583
2584#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2585 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
2586 extern int sqlite3WhereTrace;
3276 p->traceOut = output_file_open(azArg[1]);
3277#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
3278 if( p->traceOut==0 ){
3279 sqlite3_trace(p->db, 0, 0);
3280 }else{
3281 sqlite3_trace(p->db, sql_trace_callback, p->traceOut);
3282 }
3283#endif

--- 14 unchanged lines hidden (view full) ---

3298 sqlite3_free(zVfsName);
3299 }
3300 }
3301 }else
3302
3303#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
3304 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
3305 extern int sqlite3WhereTrace;
2587 sqlite3WhereTrace = booleanValue(azArg[1]);
3306 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
2588 }else
2589#endif
2590
3307 }else
3308#endif
3309
2591 if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
3310 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
2592 int j;
2593 assert( nArg<=ArraySize(azArg) );
2594 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
3311 int j;
3312 assert( nArg<=ArraySize(azArg) );
3313 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2595 p->colWidth[j-1] = atoi(azArg[j]);
3314 p->colWidth[j-1] = (int)integerValue(azArg[j]);
2596 }
2597 }else
2598
2599 {
2600 fprintf(stderr, "Error: unknown command or invalid arguments: "
2601 " \"%s\". Enter \".help\" for help\n", azArg[0]);
2602 rc = 1;
2603 }
2604
3315 }
3316 }else
3317
3318 {
3319 fprintf(stderr, "Error: unknown command or invalid arguments: "
3320 " \"%s\". Enter \".help\" for help\n", azArg[0]);
3321 rc = 1;
3322 }
3323
3324meta_command_exit:
3325 if( p->outCount ){
3326 p->outCount--;
3327 if( p->outCount==0 ) output_reset(p);
3328 }
2605 return rc;
2606}
2607
2608/*
2609** Return TRUE if a semicolon occurs anywhere in the first N characters
2610** of string z[].
2611*/
3329 return rc;
3330}
3331
3332/*
3333** Return TRUE if a semicolon occurs anywhere in the first N characters
3334** of string z[].
3335*/
2612static int _contains_semicolon(const char *z, int N){
3336static int line_contains_semicolon(const char *z, int N){
2613 int i;
2614 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
2615 return 0;
2616}
2617
2618/*
2619** Test to see if a line consists entirely of whitespace.
2620*/

--- 18 unchanged lines hidden (view full) ---

2639 return 1;
2640}
2641
2642/*
2643** Return TRUE if the line typed in is an SQL command terminator other
2644** than a semi-colon. The SQL Server style "go" command is understood
2645** as is the Oracle "/".
2646*/
3337 int i;
3338 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
3339 return 0;
3340}
3341
3342/*
3343** Test to see if a line consists entirely of whitespace.
3344*/

--- 18 unchanged lines hidden (view full) ---

3363 return 1;
3364}
3365
3366/*
3367** Return TRUE if the line typed in is an SQL command terminator other
3368** than a semi-colon. The SQL Server style "go" command is understood
3369** as is the Oracle "/".
3370*/
2647static int _is_command_terminator(const char *zLine){
3371static int line_is_command_terminator(const char *zLine){
2648 while( IsSpace(zLine[0]) ){ zLine++; };
2649 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
2650 return 1; /* Oracle */
2651 }
2652 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
2653 && _all_whitespace(&zLine[2]) ){
2654 return 1; /* SQL Server */
2655 }
2656 return 0;
2657}
2658
2659/*
2660** Return true if zSql is a complete SQL statement. Return false if it
2661** ends in the middle of a string literal or C-style comment.
2662*/
3372 while( IsSpace(zLine[0]) ){ zLine++; };
3373 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
3374 return 1; /* Oracle */
3375 }
3376 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
3377 && _all_whitespace(&zLine[2]) ){
3378 return 1; /* SQL Server */
3379 }
3380 return 0;
3381}
3382
3383/*
3384** Return true if zSql is a complete SQL statement. Return false if it
3385** ends in the middle of a string literal or C-style comment.
3386*/
2663static int _is_complete(char *zSql, int nSql){
3387static int line_is_complete(char *zSql, int nSql){
2664 int rc;
2665 if( zSql==0 ) return 1;
2666 zSql[nSql] = ';';
2667 zSql[nSql+1] = 0;
2668 rc = sqlite3_complete(zSql);
2669 zSql[nSql] = 0;
2670 return rc;
2671}
2672
2673/*
2674** Read input from *in and process it. If *in==0 then input
2675** is interactive - the user is typing it it. Otherwise, input
2676** is coming from a file or device. A prompt is issued and history
2677** is saved only if input is interactive. An interrupt signal will
2678** cause this routine to exit immediately, unless input is interactive.
2679**
2680** Return the number of errors.
2681*/
2682static int process_input(struct callback_data *p, FILE *in){
3388 int rc;
3389 if( zSql==0 ) return 1;
3390 zSql[nSql] = ';';
3391 zSql[nSql+1] = 0;
3392 rc = sqlite3_complete(zSql);
3393 zSql[nSql] = 0;
3394 return rc;
3395}
3396
3397/*
3398** Read input from *in and process it. If *in==0 then input
3399** is interactive - the user is typing it it. Otherwise, input
3400** is coming from a file or device. A prompt is issued and history
3401** is saved only if input is interactive. An interrupt signal will
3402** cause this routine to exit immediately, unless input is interactive.
3403**
3404** Return the number of errors.
3405*/
3406static int process_input(struct callback_data *p, FILE *in){
2683 char *zLine = 0;
2684 char *zSql = 0;
2685 int nSql = 0;
2686 int nSqlPrior = 0;
2687 char *zErrMsg;
2688 int rc;
2689 int errCnt = 0;
2690 int lineno = 0;
2691 int startline = 0;
3407 char *zLine = 0; /* A single input line */
3408 char *zSql = 0; /* Accumulated SQL text */
3409 int nLine; /* Length of current line */
3410 int nSql = 0; /* Bytes of zSql[] used */
3411 int nAlloc = 0; /* Allocated zSql[] space */
3412 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
3413 char *zErrMsg; /* Error message returned */
3414 int rc; /* Error code */
3415 int errCnt = 0; /* Number of errors seen */
3416 int lineno = 0; /* Current line number */
3417 int startline = 0; /* Line number for start of current input */
2692
2693 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
2694 fflush(p->out);
3418
3419 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
3420 fflush(p->out);
2695 free(zLine);
2696 zLine = one_input_line(zSql, in);
3421 zLine = one_input_line(in, zLine, nSql>0);
2697 if( zLine==0 ){
2698 /* End of input */
2699 if( stdin_is_interactive ) printf("\n");
2700 break;
2701 }
2702 if( seenInterrupt ){
2703 if( in!=0 ) break;
2704 seenInterrupt = 0;
2705 }
2706 lineno++;
3422 if( zLine==0 ){
3423 /* End of input */
3424 if( stdin_is_interactive ) printf("\n");
3425 break;
3426 }
3427 if( seenInterrupt ){
3428 if( in!=0 ) break;
3429 seenInterrupt = 0;
3430 }
3431 lineno++;
2707 if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
3432 if( nSql==0 && _all_whitespace(zLine) ){
3433 if( p->echoOn ) printf("%s\n", zLine);
3434 continue;
3435 }
2708 if( zLine && zLine[0]=='.' && nSql==0 ){
2709 if( p->echoOn ) printf("%s\n", zLine);
2710 rc = do_meta_command(zLine, p);
2711 if( rc==2 ){ /* exit requested */
2712 break;
2713 }else if( rc ){
2714 errCnt++;
2715 }
2716 continue;
2717 }
3436 if( zLine && zLine[0]=='.' && nSql==0 ){
3437 if( p->echoOn ) printf("%s\n", zLine);
3438 rc = do_meta_command(zLine, p);
3439 if( rc==2 ){ /* exit requested */
3440 break;
3441 }else if( rc ){
3442 errCnt++;
3443 }
3444 continue;
3445 }
2718 if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
3446 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
2719 memcpy(zLine,";",2);
2720 }
3447 memcpy(zLine,";",2);
3448 }
3449 nLine = strlen30(zLine);
3450 if( nSql+nLine+2>=nAlloc ){
3451 nAlloc = nSql+nLine+100;
3452 zSql = realloc(zSql, nAlloc);
3453 if( zSql==0 ){
3454 fprintf(stderr, "Error: out of memory\n");
3455 exit(1);
3456 }
3457 }
2721 nSqlPrior = nSql;
3458 nSqlPrior = nSql;
2722 if( zSql==0 ){
3459 if( nSql==0 ){
2723 int i;
2724 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
3460 int i;
3461 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
2725 if( zLine[i]!=0 ){
2726 nSql = strlen30(zLine);
2727 zSql = malloc( nSql+3 );
2728 if( zSql==0 ){
2729 fprintf(stderr, "Error: out of memory\n");
2730 exit(1);
2731 }
2732 memcpy(zSql, zLine, nSql+1);
2733 startline = lineno;
2734 }
3462 assert( nAlloc>0 && zSql!=0 );
3463 memcpy(zSql, zLine+i, nLine+1-i);
3464 startline = lineno;
3465 nSql = nLine-i;
2735 }else{
3466 }else{
2736 int len = strlen30(zLine);
2737 zSql = realloc( zSql, nSql + len + 4 );
2738 if( zSql==0 ){
2739 fprintf(stderr,"Error: out of memory\n");
2740 exit(1);
2741 }
2742 zSql[nSql++] = '\n';
3467 zSql[nSql++] = '\n';
2743 memcpy(&zSql[nSql], zLine, len+1);
2744 nSql += len;
3468 memcpy(zSql+nSql, zLine, nLine+1);
3469 nSql += nLine;
2745 }
3470 }
2746 if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
3471 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
2747 && sqlite3_complete(zSql) ){
2748 p->cnt = 0;
3472 && sqlite3_complete(zSql) ){
3473 p->cnt = 0;
2749 open_db(p);
3474 open_db(p, 0);
2750 BEGIN_TIMER;
2751 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
2752 END_TIMER;
2753 if( rc || zErrMsg ){
2754 char zPrefix[100];
2755 if( in!=0 || !stdin_is_interactive ){
2756 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
2757 "Error: near line %d:", startline);

--- 4 unchanged lines hidden (view full) ---

2762 fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
2763 sqlite3_free(zErrMsg);
2764 zErrMsg = 0;
2765 }else{
2766 fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
2767 }
2768 errCnt++;
2769 }
3475 BEGIN_TIMER;
3476 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
3477 END_TIMER;
3478 if( rc || zErrMsg ){
3479 char zPrefix[100];
3480 if( in!=0 || !stdin_is_interactive ){
3481 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
3482 "Error: near line %d:", startline);

--- 4 unchanged lines hidden (view full) ---

3487 fprintf(stderr, "%s %s\n", zPrefix, zErrMsg);
3488 sqlite3_free(zErrMsg);
3489 zErrMsg = 0;
3490 }else{
3491 fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
3492 }
3493 errCnt++;
3494 }
2770 free(zSql);
2771 zSql = 0;
2772 nSql = 0;
3495 nSql = 0;
2773 }else if( zSql && _all_whitespace(zSql) ){
2774 free(zSql);
2775 zSql = 0;
3496 if( p->outCount ){
3497 output_reset(p);
3498 p->outCount = 0;
3499 }
3500 }else if( nSql && _all_whitespace(zSql) ){
3501 if( p->echoOn ) printf("%s\n", zSql);
2776 nSql = 0;
2777 }
2778 }
3502 nSql = 0;
3503 }
3504 }
2779 if( zSql ){
3505 if( nSql ){
2780 if( !_all_whitespace(zSql) ){
2781 fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
2782 }
2783 free(zSql);
2784 }
2785 free(zLine);
2786 return errCnt>0;
2787}

--- 158 unchanged lines hidden (view full) ---

2946 sqlite3_config(SQLITE_CONFIG_URI, 1);
2947 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
2948 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
2949 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
2950 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
2951}
2952
2953/*
3506 if( !_all_whitespace(zSql) ){
3507 fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
3508 }
3509 free(zSql);
3510 }
3511 free(zLine);
3512 return errCnt>0;
3513}

--- 158 unchanged lines hidden (view full) ---

3672 sqlite3_config(SQLITE_CONFIG_URI, 1);
3673 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
3674 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
3675 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
3676 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
3677}
3678
3679/*
3680** Output text to the console in a font that attracts extra attention.
3681*/
3682#ifdef _WIN32
3683static void printBold(const char *zText){
3684 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
3685 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
3686 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
3687 SetConsoleTextAttribute(out,
3688 FOREGROUND_RED|FOREGROUND_INTENSITY
3689 );
3690 printf("%s", zText);
3691 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
3692}
3693#else
3694static void printBold(const char *zText){
3695 printf("\033[1m%s\033[0m", zText);
3696}
3697#endif
3698
3699/*
2954** Get the argument to an --option. Throw an error and die if no argument
2955** is available.
2956*/
2957static char *cmdline_option_value(int argc, char **argv, int i){
2958 if( i==argc ){
2959 fprintf(stderr, "%s: Error: missing argument to %s\n",
2960 argv[0], argv[argc-1]);
2961 exit(1);
2962 }
2963 return argv[i];
2964}
2965
2966int main(int argc, char **argv){
2967 char *zErrMsg = 0;
2968 struct callback_data data;
2969 const char *zInitFile = 0;
2970 char *zFirstCmd = 0;
2971 int i;
2972 int rc = 0;
3700** Get the argument to an --option. Throw an error and die if no argument
3701** is available.
3702*/
3703static char *cmdline_option_value(int argc, char **argv, int i){
3704 if( i==argc ){
3705 fprintf(stderr, "%s: Error: missing argument to %s\n",
3706 argv[0], argv[argc-1]);
3707 exit(1);
3708 }
3709 return argv[i];
3710}
3711
3712int main(int argc, char **argv){
3713 char *zErrMsg = 0;
3714 struct callback_data data;
3715 const char *zInitFile = 0;
3716 char *zFirstCmd = 0;
3717 int i;
3718 int rc = 0;
3719 int warnInmemoryDb = 0;
2973
3720
3721#if USE_SYSTEM_SQLITE+0!=1
2974 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
2975 fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
2976 sqlite3_sourceid(), SQLITE_SOURCE_ID);
2977 exit(1);
2978 }
3722 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
3723 fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
3724 sqlite3_sourceid(), SQLITE_SOURCE_ID);
3725 exit(1);
3726 }
3727#endif
2979 Argv0 = argv[0];
2980 main_init(&data);
2981 stdin_is_interactive = isatty(0);
2982
2983 /* Make sure we have a valid signal handler early, before anything
2984 ** else is done.
2985 */
2986#ifdef SIGINT

--- 32 unchanged lines hidden (view full) ---

3019 }else if( strcmp(z,"-batch")==0 ){
3020 /* Need to check for batch mode here to so we can avoid printing
3021 ** informational messages (like from process_sqliterc) before
3022 ** we do the actual processing of arguments later in a second pass.
3023 */
3024 stdin_is_interactive = 0;
3025 }else if( strcmp(z,"-heap")==0 ){
3026#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
3728 Argv0 = argv[0];
3729 main_init(&data);
3730 stdin_is_interactive = isatty(0);
3731
3732 /* Make sure we have a valid signal handler early, before anything
3733 ** else is done.
3734 */
3735#ifdef SIGINT

--- 32 unchanged lines hidden (view full) ---

3768 }else if( strcmp(z,"-batch")==0 ){
3769 /* Need to check for batch mode here to so we can avoid printing
3770 ** informational messages (like from process_sqliterc) before
3771 ** we do the actual processing of arguments later in a second pass.
3772 */
3773 stdin_is_interactive = 0;
3774 }else if( strcmp(z,"-heap")==0 ){
3775#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
3027 int j, c;
3028 const char *zSize;
3029 sqlite3_int64 szHeap;
3030
3031 zSize = cmdline_option_value(argc, argv, ++i);
3032 szHeap = integerValue(zSize);
3033 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
3034 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
3035#endif

--- 24 unchanged lines hidden (view full) ---

3060 fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]);
3061 exit(1);
3062 }
3063 }
3064 }
3065 if( data.zDbFilename==0 ){
3066#ifndef SQLITE_OMIT_MEMORYDB
3067 data.zDbFilename = ":memory:";
3776 const char *zSize;
3777 sqlite3_int64 szHeap;
3778
3779 zSize = cmdline_option_value(argc, argv, ++i);
3780 szHeap = integerValue(zSize);
3781 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
3782 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
3783#endif

--- 24 unchanged lines hidden (view full) ---

3808 fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]);
3809 exit(1);
3810 }
3811 }
3812 }
3813 if( data.zDbFilename==0 ){
3814#ifndef SQLITE_OMIT_MEMORYDB
3815 data.zDbFilename = ":memory:";
3816 warnInmemoryDb = argc==1;
3068#else
3069 fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
3070 return 1;
3071#endif
3817#else
3818 fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
3819 return 1;
3820#endif
3821#ifdef SQLITE_SHELL_DBNAME_PROC
3822 { extern void SQLITE_SHELL_DBNAME_PROC(const char**);
3823 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
3824 warnInmemoryDb = 0; }
3825#endif
3072 }
3073 data.out = stdout;
3074
3075 /* Go ahead and open the database file if it already exists. If the
3076 ** file does not exist, delay opening it. This prevents empty database
3077 ** files from being created if a user mistypes the database name argument
3078 ** to the sqlite command-line tool.
3079 */
3080 if( access(data.zDbFilename, 0)==0 ){
3826 }
3827 data.out = stdout;
3828
3829 /* Go ahead and open the database file if it already exists. If the
3830 ** file does not exist, delay opening it. This prevents empty database
3831 ** files from being created if a user mistypes the database name argument
3832 ** to the sqlite command-line tool.
3833 */
3834 if( access(data.zDbFilename, 0)==0 ){
3081 open_db(&data);
3835 open_db(&data, 0);
3082 }
3083
3084 /* Process the initialization file if there is one. If no -init option
3085 ** is given on the command line, look for a file named ~/.sqliterc and
3086 ** try to process it.
3087 */
3088 rc = process_sqliterc(&data,zInitFile);
3089 if( rc>0 ){

--- 29 unchanged lines hidden (view full) ---

3119 sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
3120 "%s",cmdline_option_value(argc,argv,++i));
3121 }else if( strcmp(z,"-header")==0 ){
3122 data.showHeader = 1;
3123 }else if( strcmp(z,"-noheader")==0 ){
3124 data.showHeader = 0;
3125 }else if( strcmp(z,"-echo")==0 ){
3126 data.echoOn = 1;
3836 }
3837
3838 /* Process the initialization file if there is one. If no -init option
3839 ** is given on the command line, look for a file named ~/.sqliterc and
3840 ** try to process it.
3841 */
3842 rc = process_sqliterc(&data,zInitFile);
3843 if( rc>0 ){

--- 29 unchanged lines hidden (view full) ---

3873 sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue,
3874 "%s",cmdline_option_value(argc,argv,++i));
3875 }else if( strcmp(z,"-header")==0 ){
3876 data.showHeader = 1;
3877 }else if( strcmp(z,"-noheader")==0 ){
3878 data.showHeader = 0;
3879 }else if( strcmp(z,"-echo")==0 ){
3880 data.echoOn = 1;
3881 }else if( strcmp(z,"-eqp")==0 ){
3882 data.autoEQP = 1;
3127 }else if( strcmp(z,"-stats")==0 ){
3128 data.statsOn = 1;
3129 }else if( strcmp(z,"-bail")==0 ){
3130 bail_on_error = 1;
3131 }else if( strcmp(z,"-version")==0 ){
3132 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
3133 return 0;
3134 }else if( strcmp(z,"-interactive")==0 ){

--- 18 unchanged lines hidden (view full) ---

3153 usage(1);
3154 }else if( strcmp(z,"-cmd")==0 ){
3155 if( i==argc-1 ) break;
3156 z = cmdline_option_value(argc,argv,++i);
3157 if( z[0]=='.' ){
3158 rc = do_meta_command(z, &data);
3159 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
3160 }else{
3883 }else if( strcmp(z,"-stats")==0 ){
3884 data.statsOn = 1;
3885 }else if( strcmp(z,"-bail")==0 ){
3886 bail_on_error = 1;
3887 }else if( strcmp(z,"-version")==0 ){
3888 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
3889 return 0;
3890 }else if( strcmp(z,"-interactive")==0 ){

--- 18 unchanged lines hidden (view full) ---

3909 usage(1);
3910 }else if( strcmp(z,"-cmd")==0 ){
3911 if( i==argc-1 ) break;
3912 z = cmdline_option_value(argc,argv,++i);
3913 if( z[0]=='.' ){
3914 rc = do_meta_command(z, &data);
3915 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
3916 }else{
3161 open_db(&data);
3917 open_db(&data, 0);
3162 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
3163 if( zErrMsg!=0 ){
3164 fprintf(stderr,"Error: %s\n", zErrMsg);
3165 if( bail_on_error ) return rc!=0 ? rc : 1;
3166 }else if( rc!=0 ){
3167 fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
3168 if( bail_on_error ) return rc;
3169 }

--- 7 unchanged lines hidden (view full) ---

3177
3178 if( zFirstCmd ){
3179 /* Run just the command that follows the database name
3180 */
3181 if( zFirstCmd[0]=='.' ){
3182 rc = do_meta_command(zFirstCmd, &data);
3183 if( rc==2 ) rc = 0;
3184 }else{
3918 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
3919 if( zErrMsg!=0 ){
3920 fprintf(stderr,"Error: %s\n", zErrMsg);
3921 if( bail_on_error ) return rc!=0 ? rc : 1;
3922 }else if( rc!=0 ){
3923 fprintf(stderr,"Error: unable to process SQL \"%s\"\n", z);
3924 if( bail_on_error ) return rc;
3925 }

--- 7 unchanged lines hidden (view full) ---

3933
3934 if( zFirstCmd ){
3935 /* Run just the command that follows the database name
3936 */
3937 if( zFirstCmd[0]=='.' ){
3938 rc = do_meta_command(zFirstCmd, &data);
3939 if( rc==2 ) rc = 0;
3940 }else{
3185 open_db(&data);
3941 open_db(&data, 0);
3186 rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
3187 if( zErrMsg!=0 ){
3188 fprintf(stderr,"Error: %s\n", zErrMsg);
3189 return rc!=0 ? rc : 1;
3190 }else if( rc!=0 ){
3191 fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
3192 return rc;
3193 }
3194 }
3195 }else{
3196 /* Run commands received from standard input
3197 */
3198 if( stdin_is_interactive ){
3199 char *zHome;
3200 char *zHistory = 0;
3201 int nHistory;
3202 printf(
3203 "SQLite version %s %.19s\n" /*extra-version-info*/
3942 rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg);
3943 if( zErrMsg!=0 ){
3944 fprintf(stderr,"Error: %s\n", zErrMsg);
3945 return rc!=0 ? rc : 1;
3946 }else if( rc!=0 ){
3947 fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd);
3948 return rc;
3949 }
3950 }
3951 }else{
3952 /* Run commands received from standard input
3953 */
3954 if( stdin_is_interactive ){
3955 char *zHome;
3956 char *zHistory = 0;
3957 int nHistory;
3958 printf(
3959 "SQLite version %s %.19s\n" /*extra-version-info*/
3204 "Enter \".help\" for instructions\n"
3205 "Enter SQL statements terminated with a \";\"\n",
3960 "Enter \".help\" for usage hints.\n",
3206 sqlite3_libversion(), sqlite3_sourceid()
3207 );
3961 sqlite3_libversion(), sqlite3_sourceid()
3962 );
3963 if( warnInmemoryDb ){
3964 printf("Connected to a ");
3965 printBold("transient in-memory database");
3966 printf(".\nUse \".open FILENAME\" to reopen on a "
3967 "persistent database.\n");
3968 }
3208 zHome = find_home_dir();
3209 if( zHome ){
3210 nHistory = strlen30(zHome) + 20;
3211 if( (zHistory = malloc(nHistory))!=0 ){
3212 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
3213 }
3214 }
3969 zHome = find_home_dir();
3970 if( zHome ){
3971 nHistory = strlen30(zHome) + 20;
3972 if( (zHistory = malloc(nHistory))!=0 ){
3973 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
3974 }
3975 }
3215#if defined(HAVE_READLINE) && HAVE_READLINE==1
3976#if defined(HAVE_READLINE)
3216 if( zHistory ) read_history(zHistory);
3217#endif
3218 rc = process_input(&data, 0);
3219 if( zHistory ){
3220 stifle_history(100);
3221 write_history(zHistory);
3222 free(zHistory);
3223 }
3224 }else{
3225 rc = process_input(&data, stdin);
3226 }
3227 }
3228 set_table_name(&data, 0);
3229 if( data.db ){
3230 sqlite3_close(data.db);
3231 }
3977 if( zHistory ) read_history(zHistory);
3978#endif
3979 rc = process_input(&data, 0);
3980 if( zHistory ){
3981 stifle_history(100);
3982 write_history(zHistory);
3983 free(zHistory);
3984 }
3985 }else{
3986 rc = process_input(&data, stdin);
3987 }
3988 }
3989 set_table_name(&data, 0);
3990 if( data.db ){
3991 sqlite3_close(data.db);
3992 }
3993 sqlite3_free(data.zFreeOnClose);
3232 return rc;
3233}
3994 return rc;
3995}