4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains code to implement the "sqlite" command line
13 ** utility for accessing SQLite databases.
15 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
16 /* This needs to come before any includes for MSVC compiler */
17 #define _CRT_SECURE_NO_WARNINGS
21 ** Warning pragmas copied from msvc.h in the core.
24 #pragma warning(disable : 4054)
25 #pragma warning(disable : 4055)
26 #pragma warning(disable : 4100)
27 #pragma warning(disable : 4127)
28 #pragma warning(disable : 4130)
29 #pragma warning(disable : 4152)
30 #pragma warning(disable : 4189)
31 #pragma warning(disable : 4206)
32 #pragma warning(disable : 4210)
33 #pragma warning(disable : 4232)
34 #pragma warning(disable : 4244)
35 #pragma warning(disable : 4305)
36 #pragma warning(disable : 4306)
37 #pragma warning(disable : 4702)
38 #pragma warning(disable : 4706)
39 #endif /* defined(_MSC_VER) */
42 ** No support for loadable extensions in VxWorks.
44 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
45 # define SQLITE_OMIT_LOAD_EXTENSION 1
49 ** Enable large-file support for fopen() and friends on unix.
51 #ifndef SQLITE_DISABLE_LFS
52 # define _LARGE_FILE 1
53 # ifndef _FILE_OFFSET_BITS
54 # define _FILE_OFFSET_BITS 64
56 # define _LARGEFILE_SOURCE 1
64 typedef sqlite3_int64 i64
;
65 typedef sqlite3_uint64 u64
;
66 typedef unsigned char u8
;
67 #if SQLITE_USER_AUTHENTICATION
68 # include "sqlite3userauth.h"
73 #if !defined(_WIN32) && !defined(WIN32)
75 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
79 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
82 # define GETPID getpid
83 # if defined(__MINGW32__)
84 # define DIRENT dirent
86 # define S_ISLNK(mode) (0)
90 # define GETPID (int)GetCurrentProcessId
92 #include <sys/types.h>
96 # include <readline/readline.h>
97 # include <readline/history.h>
101 # include <editline/readline.h>
104 #if HAVE_EDITLINE || HAVE_READLINE
106 # define shell_add_history(X) add_history(X)
107 # define shell_read_history(X) read_history(X)
108 # define shell_write_history(X) write_history(X)
109 # define shell_stifle_history(X) stifle_history(X)
110 # define shell_readline(X) readline(X)
114 # include "linenoise.h"
115 # define shell_add_history(X) linenoiseHistoryAdd(X)
116 # define shell_read_history(X) linenoiseHistoryLoad(X)
117 # define shell_write_history(X) linenoiseHistorySave(X)
118 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
119 # define shell_readline(X) linenoise(X)
123 # define shell_read_history(X)
124 # define shell_write_history(X)
125 # define shell_stifle_history(X)
127 # define SHELL_USE_LOCAL_GETLINE 1
131 #if defined(_WIN32) || defined(WIN32)
134 # define isatty(h) _isatty(h)
136 # define access(f,m) _access((f),(m))
139 # define unlink _unlink
142 # define popen _popen
144 # define pclose _pclose
146 /* Make sure isatty() has a prototype. */
147 extern int isatty(int);
149 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
150 /* popen and pclose are not C89 functions and so are
151 ** sometimes omitted from the <stdio.h> header */
152 extern FILE *popen(const char*,const char*);
153 extern int pclose(FILE*);
155 # define SQLITE_OMIT_POPEN 1
159 #if defined(_WIN32_WCE)
160 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
161 * thus we always assume that we have a console. That can be
162 * overridden with the -batch command line option.
167 /* ctype macros that work with signed characters */
168 #define IsSpace(X) isspace((unsigned char)X)
169 #define IsDigit(X) isdigit((unsigned char)X)
170 #define ToLower(X) (char)tolower((unsigned char)X)
172 #if defined(_WIN32) || defined(WIN32)
175 /* string conversion routines only needed on Win32 */
176 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR
);
177 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
178 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
179 extern LPWSTR
sqlite3_win32_utf8_to_unicode(const char *zText
);
182 /* On Windows, we normally run with output mode of TEXT so that \n characters
183 ** are automatically translated into \r\n. However, this behavior needs
184 ** to be disabled in some cases (ex: when generating CSV output and when
185 ** rendering quoted strings that contain \n characters). The following
186 ** routines take care of that.
188 #if defined(_WIN32) || defined(WIN32)
189 static void setBinaryMode(FILE *file
, int isOutput
){
190 if( isOutput
) fflush(file
);
191 _setmode(_fileno(file
), _O_BINARY
);
193 static void setTextMode(FILE *file
, int isOutput
){
194 if( isOutput
) fflush(file
);
195 _setmode(_fileno(file
), _O_TEXT
);
198 # define setBinaryMode(X,Y)
199 # define setTextMode(X,Y)
203 /* True if the timer is enabled */
204 static int enableTimer
= 0;
206 /* Return the current wall-clock time */
207 static sqlite3_int64
timeOfDay(void){
208 static sqlite3_vfs
*clockVfs
= 0;
210 if( clockVfs
==0 ) clockVfs
= sqlite3_vfs_find(0);
211 if( clockVfs
->iVersion
>=2 && clockVfs
->xCurrentTimeInt64
!=0 ){
212 clockVfs
->xCurrentTimeInt64(clockVfs
, &t
);
215 clockVfs
->xCurrentTime(clockVfs
, &r
);
216 t
= (sqlite3_int64
)(r
*86400000.0);
221 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
222 #include <sys/time.h>
223 #include <sys/resource.h>
225 /* VxWorks does not support getrusage() as far as we can determine */
226 #if defined(_WRS_KERNEL) || defined(__RTP__)
228 struct timeval ru_utime
; /* user CPU time used */
229 struct timeval ru_stime
; /* system CPU time used */
231 #define getrusage(A,B) memset(B,0,sizeof(*B))
234 /* Saved resource information for the beginning of an operation */
235 static struct rusage sBegin
; /* CPU time at start */
236 static sqlite3_int64 iBegin
; /* Wall-clock time at start */
239 ** Begin timing an operation
241 static void beginTimer(void){
243 getrusage(RUSAGE_SELF
, &sBegin
);
244 iBegin
= timeOfDay();
248 /* Return the difference of two time_structs in seconds */
249 static double timeDiff(struct timeval
*pStart
, struct timeval
*pEnd
){
250 return (pEnd
->tv_usec
- pStart
->tv_usec
)*0.000001 +
251 (double)(pEnd
->tv_sec
- pStart
->tv_sec
);
255 ** Print the timing results.
257 static void endTimer(void){
259 sqlite3_int64 iEnd
= timeOfDay();
261 getrusage(RUSAGE_SELF
, &sEnd
);
262 printf("Run Time: real %.3f user %f sys %f\n",
263 (iEnd
- iBegin
)*0.001,
264 timeDiff(&sBegin
.ru_utime
, &sEnd
.ru_utime
),
265 timeDiff(&sBegin
.ru_stime
, &sEnd
.ru_stime
));
269 #define BEGIN_TIMER beginTimer()
270 #define END_TIMER endTimer()
273 #elif (defined(_WIN32) || defined(WIN32))
275 /* Saved resource information for the beginning of an operation */
276 static HANDLE hProcess
;
277 static FILETIME ftKernelBegin
;
278 static FILETIME ftUserBegin
;
279 static sqlite3_int64 ftWallBegin
;
280 typedef BOOL (WINAPI
*GETPROCTIMES
)(HANDLE
, LPFILETIME
, LPFILETIME
,
281 LPFILETIME
, LPFILETIME
);
282 static GETPROCTIMES getProcessTimesAddr
= NULL
;
285 ** Check to see if we have timer support. Return 1 if necessary
286 ** support found (or found previously).
288 static int hasTimer(void){
289 if( getProcessTimesAddr
){
292 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
293 ** versions. See if the version we are running on has it, and if it
294 ** does, save off a pointer to it and the current process handle.
296 hProcess
= GetCurrentProcess();
298 HINSTANCE hinstLib
= LoadLibrary(TEXT("Kernel32.dll"));
299 if( NULL
!= hinstLib
){
300 getProcessTimesAddr
=
301 (GETPROCTIMES
) GetProcAddress(hinstLib
, "GetProcessTimes");
302 if( NULL
!= getProcessTimesAddr
){
305 FreeLibrary(hinstLib
);
313 ** Begin timing an operation
315 static void beginTimer(void){
316 if( enableTimer
&& getProcessTimesAddr
){
317 FILETIME ftCreation
, ftExit
;
318 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,
319 &ftKernelBegin
,&ftUserBegin
);
320 ftWallBegin
= timeOfDay();
324 /* Return the difference of two FILETIME structs in seconds */
325 static double timeDiff(FILETIME
*pStart
, FILETIME
*pEnd
){
326 sqlite_int64 i64Start
= *((sqlite_int64
*) pStart
);
327 sqlite_int64 i64End
= *((sqlite_int64
*) pEnd
);
328 return (double) ((i64End
- i64Start
) / 10000000.0);
332 ** Print the timing results.
334 static void endTimer(void){
335 if( enableTimer
&& getProcessTimesAddr
){
336 FILETIME ftCreation
, ftExit
, ftKernelEnd
, ftUserEnd
;
337 sqlite3_int64 ftWallEnd
= timeOfDay();
338 getProcessTimesAddr(hProcess
,&ftCreation
,&ftExit
,&ftKernelEnd
,&ftUserEnd
);
339 printf("Run Time: real %.3f user %f sys %f\n",
340 (ftWallEnd
- ftWallBegin
)*0.001,
341 timeDiff(&ftUserBegin
, &ftUserEnd
),
342 timeDiff(&ftKernelBegin
, &ftKernelEnd
));
346 #define BEGIN_TIMER beginTimer()
347 #define END_TIMER endTimer()
348 #define HAS_TIMER hasTimer()
357 ** Used to prevent warnings about unused parameters
359 #define UNUSED_PARAMETER(x) (void)(x)
362 ** Number of elements in an array
364 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
367 ** If the following flag is set, then command execution stops
368 ** at an error if we are not interactive.
370 static int bail_on_error
= 0;
373 ** Threat stdin as an interactive input if the following variable
374 ** is true. Otherwise, assume stdin is connected to a file or pipe.
376 static int stdin_is_interactive
= 1;
379 ** On Windows systems we have to know if standard output is a console
380 ** in order to translate UTF-8 into MBCS. The following variable is
381 ** true if translation is required.
383 static int stdout_is_console
= 1;
386 ** The following is the open SQLite database. We make a pointer
387 ** to this database a static variable so that it can be accessed
388 ** by the SIGINT handler to interrupt database processing.
390 static sqlite3
*globalDb
= 0;
393 ** True if an interrupt (Control-C) has been received.
395 static volatile int seenInterrupt
= 0;
398 ** This is the name of our program. It is set in main(), used
399 ** in a number of other places, mostly for error messages.
404 ** Prompt strings. Initialized in main. Settable with
405 ** .prompt main continue
407 static char mainPrompt
[20]; /* First line prompt. default: "sqlite> "*/
408 static char continuePrompt
[20]; /* Continuation prompt. default: " ...> " */
411 ** Render output like fprintf(). Except, if the output is going to the
412 ** console and if this is running on a Windows machine, translate the
413 ** output from UTF-8 into MBCS.
415 #if defined(_WIN32) || defined(WIN32)
416 void utf8_printf(FILE *out
, const char *zFormat
, ...){
418 va_start(ap
, zFormat
);
419 if( stdout_is_console
&& (out
==stdout
|| out
==stderr
) ){
420 char *z1
= sqlite3_vmprintf(zFormat
, ap
);
421 char *z2
= sqlite3_win32_utf8_to_mbcs_v2(z1
, 0);
426 vfprintf(out
, zFormat
, ap
);
430 #elif !defined(utf8_printf)
431 # define utf8_printf fprintf
435 ** Render output like fprintf(). This should not be used on anything that
436 ** includes string formatting (e.g. "%s").
438 #if !defined(raw_printf)
439 # define raw_printf fprintf
442 /* Indicate out-of-memory and exit. */
443 static void shell_out_of_memory(void){
444 raw_printf(stderr
,"Error: out of memory\n");
449 ** Write I/O traces to the following stream.
451 #ifdef SQLITE_ENABLE_IOTRACE
452 static FILE *iotrace
= 0;
456 ** This routine works like printf in that its first argument is a
457 ** format string and subsequent arguments are values to be substituted
458 ** in place of % fields. The result of formatting this string
459 ** is written to iotrace.
461 #ifdef SQLITE_ENABLE_IOTRACE
462 static void SQLITE_CDECL
iotracePrintf(const char *zFormat
, ...){
465 if( iotrace
==0 ) return;
466 va_start(ap
, zFormat
);
467 z
= sqlite3_vmprintf(zFormat
, ap
);
469 utf8_printf(iotrace
, "%s", z
);
475 ** Output string zUtf to stream pOut as w characters. If w is negative,
476 ** then right-justify the text. W is the width in UTF-8 characters, not
477 ** in bytes. This is different from the %*.*s specification in printf
478 ** since with %*.*s the width is measured in bytes, not characters.
480 static void utf8_width_print(FILE *pOut
, int w
, const char *zUtf
){
483 int aw
= w
<0 ? -w
: w
;
485 if( aw
>(int)sizeof(zBuf
)/3 ) aw
= (int)sizeof(zBuf
)/3;
486 for(i
=n
=0; zUtf
[i
]; i
++){
487 if( (zUtf
[i
]&0xc0)!=0x80 ){
490 do{ i
++; }while( (zUtf
[i
]&0xc0)==0x80 );
496 utf8_printf(pOut
, "%.*s", i
, zUtf
);
498 utf8_printf(pOut
, "%*s%s", aw
-n
, "", zUtf
);
500 utf8_printf(pOut
, "%s%*s", zUtf
, aw
-n
, "");
506 ** Determines if a string is a number of not.
508 static int isNumber(const char *z
, int *realnum
){
509 if( *z
=='-' || *z
=='+' ) z
++;
514 if( realnum
) *realnum
= 0;
515 while( IsDigit(*z
) ){ z
++; }
518 if( !IsDigit(*z
) ) return 0;
519 while( IsDigit(*z
) ){ z
++; }
520 if( realnum
) *realnum
= 1;
522 if( *z
=='e' || *z
=='E' ){
524 if( *z
=='+' || *z
=='-' ) z
++;
525 if( !IsDigit(*z
) ) return 0;
526 while( IsDigit(*z
) ){ z
++; }
527 if( realnum
) *realnum
= 1;
533 ** Compute a string length that is limited to what can be stored in
534 ** lower 30 bits of a 32-bit signed integer.
536 static int strlen30(const char *z
){
538 while( *z2
){ z2
++; }
539 return 0x3fffffff & (int)(z2
- z
);
543 ** Return the length of a string in characters. Multibyte UTF8 characters
544 ** count as a single character.
546 static int strlenChar(const char *z
){
549 if( (0xc0&*(z
++))!=0x80 ) n
++;
555 ** This routine reads a line of text from FILE in, stores
556 ** the text in memory obtained from malloc() and returns a pointer
557 ** to the text. NULL is returned at end of file, or if malloc()
560 ** If zLine is not NULL then it is a malloced buffer returned from
561 ** a previous call to this routine that may be reused.
563 static char *local_getline(char *zLine
, FILE *in
){
564 int nLine
= zLine
==0 ? 0 : 100;
569 nLine
= nLine
*2 + 100;
570 zLine
= realloc(zLine
, nLine
);
571 if( zLine
==0 ) shell_out_of_memory();
573 if( fgets(&zLine
[n
], nLine
- n
, in
)==0 ){
581 while( zLine
[n
] ) n
++;
582 if( n
>0 && zLine
[n
-1]=='\n' ){
584 if( n
>0 && zLine
[n
-1]=='\r' ) n
--;
589 #if defined(_WIN32) || defined(WIN32)
590 /* For interactive input on Windows systems, translate the
591 ** multi-byte characterset characters into UTF-8. */
592 if( stdin_is_interactive
&& in
==stdin
){
593 char *zTrans
= sqlite3_win32_mbcs_to_utf8_v2(zLine
, 0);
595 int nTrans
= strlen30(zTrans
)+1;
597 zLine
= realloc(zLine
, nTrans
);
598 if( zLine
==0 ) shell_out_of_memory();
600 memcpy(zLine
, zTrans
, nTrans
);
601 sqlite3_free(zTrans
);
604 #endif /* defined(_WIN32) || defined(WIN32) */
609 ** Retrieve a single line of input text.
611 ** If in==0 then read from standard input and prompt before each line.
612 ** If isContinuation is true, then a continuation prompt is appropriate.
613 ** If isContinuation is zero, then the main prompt should be used.
615 ** If zPrior is not NULL then it is a buffer from a prior call to this
616 ** routine that can be reused.
618 ** The result is stored in space obtained from malloc() and must either
619 ** be freed by the caller or else passed back into this routine via the
620 ** zPrior argument for reuse.
622 static char *one_input_line(FILE *in
, char *zPrior
, int isContinuation
){
626 zResult
= local_getline(zPrior
, in
);
628 zPrompt
= isContinuation
? continuePrompt
: mainPrompt
;
629 #if SHELL_USE_LOCAL_GETLINE
630 printf("%s", zPrompt
);
632 zResult
= local_getline(zPrior
, stdin
);
635 zResult
= shell_readline(zPrompt
);
636 /* BEGIN SQLCIPHER */
637 #ifdef SQLITE_HAS_CODEC
638 /* Simplistic filtering of input lines to prevent PRAGKA key and
639 PRAGMA rekey statements from being stored in readline history.
640 Note that this will only prevent single line statements, but that
641 will be sufficient for common cases. */
642 if(zResult
&& *zResult
&& (
643 sqlite3_strlike("%pragma%key%=%", zResult
, 0)==0 ||
644 sqlite3_strlike("%attach%database%as%key%", zResult
, 0)==0
649 if( zResult
&& *zResult
) shell_add_history(zResult
);
657 ** Return the value of a hexadecimal digit. Return -1 if the input
658 ** is not a hex digit.
660 static int hexDigitValue(char c
){
661 if( c
>='0' && c
<='9' ) return c
- '0';
662 if( c
>='a' && c
<='f' ) return c
- 'a' + 10;
663 if( c
>='A' && c
<='F' ) return c
- 'A' + 10;
668 ** Interpret zArg as an integer value, possibly with suffixes.
670 static sqlite3_int64
integerValue(const char *zArg
){
672 static const struct { char *zSuffix
; int iMult
; } aMult
[] = {
674 { "MiB", 1024*1024 },
675 { "GiB", 1024*1024*1024 },
678 { "GB", 1000000000 },
688 }else if( zArg
[0]=='+' ){
691 if( zArg
[0]=='0' && zArg
[1]=='x' ){
694 while( (x
= hexDigitValue(zArg
[0]))>=0 ){
699 while( IsDigit(zArg
[0]) ){
700 v
= v
*10 + zArg
[0] - '0';
704 for(i
=0; i
<ArraySize(aMult
); i
++){
705 if( sqlite3_stricmp(aMult
[i
].zSuffix
, zArg
)==0 ){
710 return isNeg
? -v
: v
;
714 ** A variable length string to which one can append text.
716 typedef struct ShellText ShellText
;
724 ** Initialize and destroy a ShellText object
726 static void initText(ShellText
*p
){
727 memset(p
, 0, sizeof(*p
));
729 static void freeText(ShellText
*p
){
734 /* zIn is either a pointer to a NULL-terminated string in memory obtained
735 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
736 ** added to zIn, and the result returned in memory obtained from malloc().
737 ** zIn, if it was not NULL, is freed.
739 ** If the third argument, quote, is not '\0', then it is used as a
740 ** quote character for zAppend.
742 static void appendText(ShellText
*p
, char const *zAppend
, char quote
){
745 int nAppend
= strlen30(zAppend
);
747 len
= nAppend
+p
->n
+1;
750 for(i
=0; i
<nAppend
; i
++){
751 if( zAppend
[i
]==quote
) len
++;
755 if( p
->n
+len
>=p
->nAlloc
){
756 p
->nAlloc
= p
->nAlloc
*2 + len
+ 20;
757 p
->z
= realloc(p
->z
, p
->nAlloc
);
758 if( p
->z
==0 ) shell_out_of_memory();
762 char *zCsr
= p
->z
+p
->n
;
764 for(i
=0; i
<nAppend
; i
++){
765 *zCsr
++ = zAppend
[i
];
766 if( zAppend
[i
]==quote
) *zCsr
++ = quote
;
769 p
->n
= (int)(zCsr
- p
->z
);
772 memcpy(p
->z
+p
->n
, zAppend
, nAppend
);
779 ** Attempt to determine if identifier zName needs to be quoted, either
780 ** because it contains non-alphanumeric characters, or because it is an
781 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
782 ** that quoting is required.
784 ** Return '"' if quoting is required. Return 0 if no quoting is required.
786 static char quoteChar(const char *zName
){
788 if( !isalpha((unsigned char)zName
[0]) && zName
[0]!='_' ) return '"';
789 for(i
=0; zName
[i
]; i
++){
790 if( !isalnum((unsigned char)zName
[i
]) && zName
[i
]!='_' ) return '"';
792 return sqlite3_keyword_check(zName
, i
) ? '"' : 0;
796 ** Construct a fake object name and column list to describe the structure
797 ** of the view, virtual table, or table valued function zSchema.zName.
799 static char *shellFakeSchema(
800 sqlite3
*db
, /* The database connection containing the vtab */
801 const char *zSchema
, /* Schema of the database holding the vtab */
802 const char *zName
/* The name of the virtual table */
804 sqlite3_stmt
*pStmt
= 0;
811 zSql
= sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
812 zSchema
? zSchema
: "main", zName
);
813 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
817 cQuote
= quoteChar(zSchema
);
818 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")==0 ) cQuote
= 0;
819 appendText(&s
, zSchema
, cQuote
);
820 appendText(&s
, ".", 0);
822 cQuote
= quoteChar(zName
);
823 appendText(&s
, zName
, cQuote
);
824 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
825 const char *zCol
= (const char*)sqlite3_column_text(pStmt
, 1);
827 appendText(&s
, zDiv
, 0);
829 cQuote
= quoteChar(zCol
);
830 appendText(&s
, zCol
, cQuote
);
832 appendText(&s
, ")", 0);
833 sqlite3_finalize(pStmt
);
842 ** SQL function: shell_module_schema(X)
844 ** Return a fake schema for the table-valued function or eponymous virtual
847 static void shellModuleSchema(
848 sqlite3_context
*pCtx
,
850 sqlite3_value
**apVal
852 const char *zName
= (const char*)sqlite3_value_text(apVal
[0]);
853 char *zFake
= shellFakeSchema(sqlite3_context_db_handle(pCtx
), 0, zName
);
854 UNUSED_PARAMETER(nVal
);
856 sqlite3_result_text(pCtx
, sqlite3_mprintf("/* %s */", zFake
),
863 ** SQL function: shell_add_schema(S,X)
865 ** Add the schema name X to the CREATE statement in S and return the result.
868 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
873 ** CREATE UNIQUE INDEX
876 ** CREATE VIRTUAL TABLE
878 ** This UDF is used by the .schema command to insert the schema name of
879 ** attached databases into the middle of the sqlite_master.sql field.
881 static void shellAddSchemaName(
882 sqlite3_context
*pCtx
,
884 sqlite3_value
**apVal
886 static const char *aPrefix
[] = {
895 const char *zIn
= (const char*)sqlite3_value_text(apVal
[0]);
896 const char *zSchema
= (const char*)sqlite3_value_text(apVal
[1]);
897 const char *zName
= (const char*)sqlite3_value_text(apVal
[2]);
898 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
899 UNUSED_PARAMETER(nVal
);
900 if( zIn
!=0 && strncmp(zIn
, "CREATE ", 7)==0 ){
901 for(i
=0; i
<(int)(sizeof(aPrefix
)/sizeof(aPrefix
[0])); i
++){
902 int n
= strlen30(aPrefix
[i
]);
903 if( strncmp(zIn
+7, aPrefix
[i
], n
)==0 && zIn
[n
+7]==' ' ){
907 char cQuote
= quoteChar(zSchema
);
908 if( cQuote
&& sqlite3_stricmp(zSchema
,"temp")!=0 ){
909 z
= sqlite3_mprintf("%.*s \"%w\".%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
911 z
= sqlite3_mprintf("%.*s %s.%s", n
+7, zIn
, zSchema
, zIn
+n
+8);
915 && aPrefix
[i
][0]=='V'
916 && (zFake
= shellFakeSchema(db
, zSchema
, zName
))!=0
919 z
= sqlite3_mprintf("%s\n/* %s */", zIn
, zFake
);
921 z
= sqlite3_mprintf("%z\n/* %s */", z
, zFake
);
926 sqlite3_result_text(pCtx
, z
, -1, sqlite3_free
);
932 sqlite3_result_value(pCtx
, apVal
[0]);
936 ** The source code for several run-time loadable extensions is inserted
937 ** below by the ../tool/mkshellc.tcl script. Before processing that included
938 ** code, we need to override some macros to make the included program code
939 ** work here in the middle of this regular program.
941 #define SQLITE_EXTENSION_INIT1
942 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
944 #if defined(_WIN32) && defined(_MSC_VER)
945 INCLUDE test_windirent
.h
946 INCLUDE test_windirent
.c
947 #define dirent DIRENT
949 INCLUDE
../ext
/misc
/shathree
.c
950 INCLUDE
../ext
/misc
/fileio
.c
951 INCLUDE
../ext
/misc
/completion
.c
952 INCLUDE
../ext
/misc
/appendvfs
.c
953 #ifdef SQLITE_HAVE_ZLIB
954 INCLUDE
../ext
/misc
/zipfile
.c
955 INCLUDE
../ext
/misc
/sqlar
.c
957 INCLUDE
../ext
/expert
/sqlite3expert
.h
958 INCLUDE
../ext
/expert
/sqlite3expert
.c
960 #if defined(SQLITE_ENABLE_SESSION)
962 ** State information for a single open session
964 typedef struct OpenSession OpenSession
;
966 char *zName
; /* Symbolic name for this session */
967 int nFilter
; /* Number of xFilter rejection GLOB patterns */
968 char **azFilter
; /* Array of xFilter rejection GLOB patterns */
969 sqlite3_session
*p
; /* The open session */
974 ** Shell output mode information from before ".explain on",
975 ** saved so that it can be restored by ".explain off"
977 typedef struct SavedModeInfo SavedModeInfo
;
978 struct SavedModeInfo
{
979 int valid
; /* Is there legit data in here? */
980 int mode
; /* Mode prior to ".explain on" */
981 int showHeader
; /* The ".header" setting prior to ".explain on" */
982 int colWidth
[100]; /* Column widths prior to ".explain on" */
985 typedef struct ExpertInfo ExpertInfo
;
987 sqlite3expert
*pExpert
;
991 /* A single line in the EQP output */
992 typedef struct EQPGraphRow EQPGraphRow
;
994 int iEqpId
; /* ID for this row */
995 int iParentId
; /* ID of the parent row */
996 EQPGraphRow
*pNext
; /* Next row in sequence */
997 char zText
[1]; /* Text to display for this row */
1000 /* All EQP output is collected into an instance of the following */
1001 typedef struct EQPGraph EQPGraph
;
1003 EQPGraphRow
*pRow
; /* Linked list of all rows of the EQP output */
1004 EQPGraphRow
*pLast
; /* Last element of the pRow list */
1005 char zPrefix
[100]; /* Graph prefix */
1009 ** State information about the database connection is contained in an
1010 ** instance of the following structure.
1012 typedef struct ShellState ShellState
;
1014 sqlite3
*db
; /* The database */
1015 u8 autoExplain
; /* Automatically turn on .explain mode */
1016 u8 autoEQP
; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
1017 u8 autoEQPtest
; /* autoEQP is in test mode */
1018 u8 statsOn
; /* True to display memory stats before each finalize */
1019 u8 scanstatsOn
; /* True to display scan stats before each finalize */
1020 u8 openMode
; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
1021 u8 doXdgOpen
; /* Invoke start/open/xdg-open in output_reset() */
1022 u8 nEqpLevel
; /* Depth of the EQP output graph */
1023 unsigned mEqpLines
; /* Mask of veritical lines in the EQP output graph */
1024 int outCount
; /* Revert to stdout when reaching zero */
1025 int cnt
; /* Number of records displayed so far */
1026 FILE *out
; /* Write results here */
1027 FILE *traceOut
; /* Output for sqlite3_trace() */
1028 int nErr
; /* Number of errors seen */
1029 int mode
; /* An output mode setting */
1030 int modePrior
; /* Saved mode */
1031 int cMode
; /* temporary output mode for the current query */
1032 int normalMode
; /* Output mode before ".explain on" */
1033 int writableSchema
; /* True if PRAGMA writable_schema=ON */
1034 int showHeader
; /* True to show column names in List or Column mode */
1035 int nCheck
; /* Number of ".check" commands run */
1036 unsigned shellFlgs
; /* Various flags */
1037 char *zDestTable
; /* Name of destination table when MODE_Insert */
1038 char *zTempFile
; /* Temporary file that might need deleting */
1039 char zTestcase
[30]; /* Name of current test case */
1040 char colSeparator
[20]; /* Column separator character for several modes */
1041 char rowSeparator
[20]; /* Row separator character for MODE_Ascii */
1042 char colSepPrior
[20]; /* Saved column separator */
1043 char rowSepPrior
[20]; /* Saved row separator */
1044 int colWidth
[100]; /* Requested width of each column when in column mode*/
1045 int actualWidth
[100]; /* Actual width of each column */
1046 char nullValue
[20]; /* The text to print when a NULL comes back from
1048 char outfile
[FILENAME_MAX
]; /* Filename for *out */
1049 const char *zDbFilename
; /* name of the database file */
1050 char *zFreeOnClose
; /* Filename to free when closing */
1051 const char *zVfs
; /* Name of VFS to use */
1052 sqlite3_stmt
*pStmt
; /* Current statement if any. */
1053 FILE *pLog
; /* Write log output here */
1054 int *aiIndent
; /* Array of indents used in MODE_Explain */
1055 int nIndent
; /* Size of array aiIndent[] */
1056 int iIndent
; /* Index of current op in aiIndent[] */
1057 EQPGraph sGraph
; /* Information for the graphical EXPLAIN QUERY PLAN */
1058 #if defined(SQLITE_ENABLE_SESSION)
1059 int nSession
; /* Number of active sessions */
1060 OpenSession aSession
[4]; /* Array of sessions. [0] is in focus. */
1062 ExpertInfo expert
; /* Valid if previous command was ".expert OPT..." */
1066 /* Allowed values for ShellState.autoEQP
1068 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
1069 #define AUTOEQP_on 1 /* Automatic EQP is on */
1070 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
1071 #define AUTOEQP_full 3 /* Show full EXPLAIN */
1073 /* Allowed values for ShellState.openMode
1075 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
1076 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
1077 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
1078 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
1079 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
1080 #define SHELL_OPEN_DESERIALIZE 5 /* Open using sqlite3_deserialize() */
1083 ** These are the allowed shellFlgs values
1085 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
1086 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
1087 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
1088 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
1089 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
1090 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
1091 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1094 ** Macros for testing and setting shellFlgs
1096 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1097 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1098 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
1101 ** These are the allowed modes.
1103 #define MODE_Line 0 /* One column per line. Blank line between records */
1104 #define MODE_Column 1 /* One record per line in neat columns */
1105 #define MODE_List 2 /* One record per line with a separator */
1106 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1107 #define MODE_Html 4 /* Generate an XHTML table */
1108 #define MODE_Insert 5 /* Generate SQL "insert" statements */
1109 #define MODE_Quote 6 /* Quote values as for SQL */
1110 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1111 #define MODE_Csv 8 /* Quote strings, numbers are plain */
1112 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1113 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1114 #define MODE_Pretty 11 /* Pretty-print schemas */
1115 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
1117 static const char *modeDescr
[] = {
1134 ** These are the column/row/line separators used by the various
1135 ** import/export modes.
1137 #define SEP_Column "|"
1138 #define SEP_Row "\n"
1139 #define SEP_Tab "\t"
1140 #define SEP_Space " "
1141 #define SEP_Comma ","
1142 #define SEP_CrLf "\r\n"
1143 #define SEP_Unit "\x1F"
1144 #define SEP_Record "\x1E"
1147 ** A callback for the sqlite3_log() interface.
1149 static void shellLog(void *pArg
, int iErrCode
, const char *zMsg
){
1150 ShellState
*p
= (ShellState
*)pArg
;
1151 if( p
->pLog
==0 ) return;
1152 utf8_printf(p
->pLog
, "(%d) %s\n", iErrCode
, zMsg
);
1157 ** SQL function: shell_putsnl(X)
1159 ** Write the text X to the screen (or whatever output is being directed)
1160 ** adding a newline at the end, and then return X.
1162 static void shellPutsFunc(
1163 sqlite3_context
*pCtx
,
1165 sqlite3_value
**apVal
1167 ShellState
*p
= (ShellState
*)sqlite3_user_data(pCtx
);
1169 utf8_printf(p
->out
, "%s\n", sqlite3_value_text(apVal
[0]));
1170 sqlite3_result_value(pCtx
, apVal
[0]);
1174 ** SQL function: edit(VALUE)
1175 ** edit(VALUE,EDITOR)
1179 ** (1) Write VALUE into a temporary file.
1180 ** (2) Run program EDITOR on that temporary file.
1181 ** (3) Read the temporary file back and return its content as the result.
1182 ** (4) Delete the temporary file
1184 ** If the EDITOR argument is omitted, use the value in the VISUAL
1185 ** environment variable. If still there is no EDITOR, through an error.
1187 ** Also throw an error if the EDITOR program returns a non-zero exit code.
1189 #ifndef SQLITE_NOHAVE_SYSTEM
1190 static void editFunc(
1191 sqlite3_context
*context
,
1193 sqlite3_value
**argv
1195 const char *zEditor
;
1196 char *zTempFile
= 0;
1205 unsigned char *p
= 0;
1208 zEditor
= (const char*)sqlite3_value_text(argv
[1]);
1210 zEditor
= getenv("VISUAL");
1213 sqlite3_result_error(context
, "no editor for edit()", -1);
1216 if( sqlite3_value_type(argv
[0])==SQLITE_NULL
){
1217 sqlite3_result_error(context
, "NULL input to edit()", -1);
1220 db
= sqlite3_context_db_handle(context
);
1222 sqlite3_file_control(db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &zTempFile
);
1224 sqlite3_uint64 r
= 0;
1225 sqlite3_randomness(sizeof(r
), &r
);
1226 zTempFile
= sqlite3_mprintf("temp%llx", r
);
1228 sqlite3_result_error_nomem(context
);
1232 bBin
= sqlite3_value_type(argv
[0])==SQLITE_BLOB
;
1233 /* When writing the file to be edited, do \n to \r\n conversions on systems
1234 ** that want \r\n line endings */
1235 f
= fopen(zTempFile
, bBin
? "wb" : "w");
1237 sqlite3_result_error(context
, "edit() cannot open temp file", -1);
1240 sz
= sqlite3_value_bytes(argv
[0]);
1242 x
= fwrite(sqlite3_value_blob(argv
[0]), 1, sz
, f
);
1244 const char *z
= (const char*)sqlite3_value_text(argv
[0]);
1245 /* Remember whether or not the value originally contained \r\n */
1246 if( z
&& strstr(z
,"\r\n")!=0 ) hasCRNL
= 1;
1247 x
= fwrite(sqlite3_value_text(argv
[0]), 1, sz
, f
);
1252 sqlite3_result_error(context
, "edit() could not write the whole file", -1);
1255 zCmd
= sqlite3_mprintf("%s \"%s\"", zEditor
, zTempFile
);
1257 sqlite3_result_error_nomem(context
);
1263 sqlite3_result_error(context
, "EDITOR returned non-zero", -1);
1266 f
= fopen(zTempFile
, "rb");
1268 sqlite3_result_error(context
,
1269 "edit() cannot reopen temp file after edit", -1);
1272 fseek(f
, 0, SEEK_END
);
1275 p
= sqlite3_malloc64( sz
+(bBin
==0) );
1277 sqlite3_result_error_nomem(context
);
1280 x
= fread(p
, 1, sz
, f
);
1284 sqlite3_result_error(context
, "could not read back the whole file", -1);
1288 sqlite3_result_blob64(context
, p
, sz
, sqlite3_free
);
1292 /* If the original contains \r\n then do no conversions back to \n */
1295 /* If the file did not originally contain \r\n then convert any new
1296 ** \r\n back into \n */
1297 for(i
=j
=0; i
<sz
; i
++){
1298 if( p
[i
]=='\r' && p
[i
+1]=='\n' ) i
++;
1304 sqlite3_result_text64(context
, (const char*)p
, sz
,
1305 sqlite3_free
, SQLITE_UTF8
);
1312 sqlite3_free(zTempFile
);
1315 #endif /* SQLITE_NOHAVE_SYSTEM */
1318 ** Save or restore the current output mode
1320 static void outputModePush(ShellState
*p
){
1321 p
->modePrior
= p
->mode
;
1322 memcpy(p
->colSepPrior
, p
->colSeparator
, sizeof(p
->colSeparator
));
1323 memcpy(p
->rowSepPrior
, p
->rowSeparator
, sizeof(p
->rowSeparator
));
1325 static void outputModePop(ShellState
*p
){
1326 p
->mode
= p
->modePrior
;
1327 memcpy(p
->colSeparator
, p
->colSepPrior
, sizeof(p
->colSeparator
));
1328 memcpy(p
->rowSeparator
, p
->rowSepPrior
, sizeof(p
->rowSeparator
));
1332 ** Output the given string as a hex-encoded blob (eg. X'1234' )
1334 static void output_hex_blob(FILE *out
, const void *pBlob
, int nBlob
){
1336 char *zBlob
= (char *)pBlob
;
1337 raw_printf(out
,"X'");
1338 for(i
=0; i
<nBlob
; i
++){ raw_printf(out
,"%02x",zBlob
[i
]&0xff); }
1339 raw_printf(out
,"'");
1343 ** Find a string that is not found anywhere in z[]. Return a pointer
1346 ** Try to use zA and zB first. If both of those are already found in z[]
1347 ** then make up some string and store it in the buffer zBuf.
1349 static const char *unused_string(
1350 const char *z
, /* Result must not appear anywhere in z */
1351 const char *zA
, const char *zB
, /* Try these first */
1352 char *zBuf
/* Space to store a generated string */
1355 if( strstr(z
, zA
)==0 ) return zA
;
1356 if( strstr(z
, zB
)==0 ) return zB
;
1358 sqlite3_snprintf(20,zBuf
,"(%s%u)", zA
, i
++);
1359 }while( strstr(z
,zBuf
)!=0 );
1364 ** Output the given string as a quoted string using SQL quoting conventions.
1366 ** See also: output_quoted_escaped_string()
1368 static void output_quoted_string(FILE *out
, const char *z
){
1371 setBinaryMode(out
, 1);
1372 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1374 utf8_printf(out
,"'%s'",z
);
1376 raw_printf(out
, "'");
1378 for(i
=0; (c
= z
[i
])!=0 && c
!='\''; i
++){}
1381 utf8_printf(out
, "%.*s", i
, z
);
1385 raw_printf(out
, "'");
1393 raw_printf(out
, "'");
1395 setTextMode(out
, 1);
1399 ** Output the given string as a quoted string using SQL quoting conventions.
1400 ** Additionallly , escape the "\n" and "\r" characters so that they do not
1401 ** get corrupted by end-of-line translation facilities in some operating
1404 ** This is like output_quoted_string() but with the addition of the \r\n
1405 ** escape mechanism.
1407 static void output_quoted_escaped_string(FILE *out
, const char *z
){
1410 setBinaryMode(out
, 1);
1411 for(i
=0; (c
= z
[i
])!=0 && c
!='\'' && c
!='\n' && c
!='\r'; i
++){}
1413 utf8_printf(out
,"'%s'",z
);
1415 const char *zNL
= 0;
1416 const char *zCR
= 0;
1419 char zBuf1
[20], zBuf2
[20];
1420 for(i
=0; z
[i
]; i
++){
1421 if( z
[i
]=='\n' ) nNL
++;
1422 if( z
[i
]=='\r' ) nCR
++;
1425 raw_printf(out
, "replace(");
1426 zNL
= unused_string(z
, "\\n", "\\012", zBuf1
);
1429 raw_printf(out
, "replace(");
1430 zCR
= unused_string(z
, "\\r", "\\015", zBuf2
);
1432 raw_printf(out
, "'");
1434 for(i
=0; (c
= z
[i
])!=0 && c
!='\n' && c
!='\r' && c
!='\''; i
++){}
1437 utf8_printf(out
, "%.*s", i
, z
);
1441 raw_printf(out
, "'");
1449 raw_printf(out
, "%s", zNL
);
1452 raw_printf(out
, "%s", zCR
);
1454 raw_printf(out
, "'");
1456 raw_printf(out
, ",'%s',char(13))", zCR
);
1459 raw_printf(out
, ",'%s',char(10))", zNL
);
1462 setTextMode(out
, 1);
1466 ** Output the given string as a quoted according to C or TCL quoting rules.
1468 static void output_c_string(FILE *out
, const char *z
){
1471 while( (c
= *(z
++))!=0 ){
1478 }else if( c
=='\t' ){
1481 }else if( c
=='\n' ){
1484 }else if( c
=='\r' ){
1487 }else if( !isprint(c
&0xff) ){
1488 raw_printf(out
, "\\%03o", c
&0xff);
1497 ** Output the given string with characters that are special to
1500 static void output_html_string(FILE *out
, const char *z
){
1512 utf8_printf(out
,"%.*s",i
,z
);
1515 raw_printf(out
,"<");
1516 }else if( z
[i
]=='&' ){
1517 raw_printf(out
,"&");
1518 }else if( z
[i
]=='>' ){
1519 raw_printf(out
,">");
1520 }else if( z
[i
]=='\"' ){
1521 raw_printf(out
,""");
1522 }else if( z
[i
]=='\'' ){
1523 raw_printf(out
,"'");
1532 ** If a field contains any character identified by a 1 in the following
1533 ** array, then the string must be quoted for CSV.
1535 static const char needCsvQuote
[] = {
1536 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1537 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1538 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1539 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1540 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1542 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1544 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1545 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1546 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1547 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1548 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1549 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1550 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1551 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1555 ** Output a single term of CSV. Actually, p->colSeparator is used for
1556 ** the separator, which may or may not be a comma. p->nullValue is
1557 ** the null value. Strings are quoted if necessary. The separator
1558 ** is only issued if bSep is true.
1560 static void output_csv(ShellState
*p
, const char *z
, int bSep
){
1563 utf8_printf(out
,"%s",p
->nullValue
);
1566 int nSep
= strlen30(p
->colSeparator
);
1567 for(i
=0; z
[i
]; i
++){
1568 if( needCsvQuote
[((unsigned char*)z
)[i
]]
1569 || (z
[i
]==p
->colSeparator
[0] &&
1570 (nSep
==1 || memcmp(z
, p
->colSeparator
, nSep
)==0)) ){
1576 char *zQuoted
= sqlite3_mprintf("\"%w\"", z
);
1577 utf8_printf(out
, "%s", zQuoted
);
1578 sqlite3_free(zQuoted
);
1580 utf8_printf(out
, "%s", z
);
1584 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1589 ** This routine runs when the user presses Ctrl-C
1591 static void interrupt_handler(int NotUsed
){
1592 UNUSED_PARAMETER(NotUsed
);
1594 if( seenInterrupt
>2 ) exit(1);
1595 if( globalDb
) sqlite3_interrupt(globalDb
);
1598 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
1600 ** This routine runs for console events (e.g. Ctrl-C) on Win32
1602 static BOOL WINAPI
ConsoleCtrlHandler(
1603 DWORD dwCtrlType
/* One of the CTRL_*_EVENT constants */
1605 if( dwCtrlType
==CTRL_C_EVENT
){
1606 interrupt_handler(0);
1613 #ifndef SQLITE_OMIT_AUTHORIZATION
1615 ** When the ".auth ON" is set, the following authorizer callback is
1616 ** invoked. It always returns SQLITE_OK.
1618 static int shellAuth(
1626 ShellState
*p
= (ShellState
*)pClientData
;
1627 static const char *azAction
[] = { 0,
1628 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1629 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1630 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1631 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1632 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1633 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1634 "PRAGMA", "READ", "SELECT",
1635 "TRANSACTION", "UPDATE", "ATTACH",
1636 "DETACH", "ALTER_TABLE", "REINDEX",
1637 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1638 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1646 utf8_printf(p
->out
, "authorizer: %s", azAction
[op
]);
1648 raw_printf(p
->out
, " ");
1650 output_c_string(p
->out
, az
[i
]);
1652 raw_printf(p
->out
, "NULL");
1655 raw_printf(p
->out
, "\n");
1661 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1663 ** This routine converts some CREATE TABLE statements for shadow tables
1664 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1666 static void printSchemaLine(FILE *out
, const char *z
, const char *zTail
){
1667 if( sqlite3_strglob("CREATE TABLE ['\"]*", z
)==0 ){
1668 utf8_printf(out
, "CREATE TABLE IF NOT EXISTS %s%s", z
+13, zTail
);
1670 utf8_printf(out
, "%s%s", z
, zTail
);
1673 static void printSchemaLineN(FILE *out
, char *z
, int n
, const char *zTail
){
1676 printSchemaLine(out
, z
, zTail
);
1681 ** Return true if string z[] has nothing but whitespace and comments to the
1682 ** end of the first line.
1684 static int wsToEol(const char *z
){
1686 for(i
=0; z
[i
]; i
++){
1687 if( z
[i
]=='\n' ) return 1;
1688 if( IsSpace(z
[i
]) ) continue;
1689 if( z
[i
]=='-' && z
[i
+1]=='-' ) return 1;
1696 ** Add a new entry to the EXPLAIN QUERY PLAN data
1698 static void eqp_append(ShellState
*p
, int iEqpId
, int p2
, const char *zText
){
1700 int nText
= strlen30(zText
);
1701 if( p
->autoEQPtest
){
1702 utf8_printf(p
->out
, "%d,%d,%s\n", iEqpId
, p2
, zText
);
1704 pNew
= sqlite3_malloc64( sizeof(*pNew
) + nText
);
1705 if( pNew
==0 ) shell_out_of_memory();
1706 pNew
->iEqpId
= iEqpId
;
1707 pNew
->iParentId
= p2
;
1708 memcpy(pNew
->zText
, zText
, nText
+1);
1710 if( p
->sGraph
.pLast
){
1711 p
->sGraph
.pLast
->pNext
= pNew
;
1713 p
->sGraph
.pRow
= pNew
;
1715 p
->sGraph
.pLast
= pNew
;
1719 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
1722 static void eqp_reset(ShellState
*p
){
1723 EQPGraphRow
*pRow
, *pNext
;
1724 for(pRow
= p
->sGraph
.pRow
; pRow
; pRow
= pNext
){
1725 pNext
= pRow
->pNext
;
1728 memset(&p
->sGraph
, 0, sizeof(p
->sGraph
));
1731 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
1732 ** pOld, or return the first such line if pOld is NULL
1734 static EQPGraphRow
*eqp_next_row(ShellState
*p
, int iEqpId
, EQPGraphRow
*pOld
){
1735 EQPGraphRow
*pRow
= pOld
? pOld
->pNext
: p
->sGraph
.pRow
;
1736 while( pRow
&& pRow
->iParentId
!=iEqpId
) pRow
= pRow
->pNext
;
1740 /* Render a single level of the graph that has iEqpId as its parent. Called
1741 ** recursively to render sublevels.
1743 static void eqp_render_level(ShellState
*p
, int iEqpId
){
1744 EQPGraphRow
*pRow
, *pNext
;
1745 int n
= strlen30(p
->sGraph
.zPrefix
);
1747 for(pRow
= eqp_next_row(p
, iEqpId
, 0); pRow
; pRow
= pNext
){
1748 pNext
= eqp_next_row(p
, iEqpId
, pRow
);
1750 utf8_printf(p
->out
, "%s%s%s\n", p
->sGraph
.zPrefix
, pNext
? "|--" : "`--", z
);
1751 if( n
<(int)sizeof(p
->sGraph
.zPrefix
)-7 ){
1752 memcpy(&p
->sGraph
.zPrefix
[n
], pNext
? "| " : " ", 4);
1753 eqp_render_level(p
, pRow
->iEqpId
);
1754 p
->sGraph
.zPrefix
[n
] = 0;
1760 ** Display and reset the EXPLAIN QUERY PLAN data
1762 static void eqp_render(ShellState
*p
){
1763 EQPGraphRow
*pRow
= p
->sGraph
.pRow
;
1765 if( pRow
->zText
[0]=='-' ){
1766 if( pRow
->pNext
==0 ){
1770 utf8_printf(p
->out
, "%s\n", pRow
->zText
+3);
1771 p
->sGraph
.pRow
= pRow
->pNext
;
1774 utf8_printf(p
->out
, "QUERY PLAN\n");
1776 p
->sGraph
.zPrefix
[0] = 0;
1777 eqp_render_level(p
, 0);
1783 ** This is the callback routine that the shell
1784 ** invokes for each row of a query result.
1786 static int shell_callback(
1788 int nArg
, /* Number of result columns */
1789 char **azArg
, /* Text of each result column */
1790 char **azCol
, /* Column names */
1791 int *aiType
/* Column types */
1794 ShellState
*p
= (ShellState
*)pArg
;
1796 if( azArg
==0 ) return 0;
1800 if( azArg
==0 ) break;
1801 for(i
=0; i
<nArg
; i
++){
1802 int len
= strlen30(azCol
[i
] ? azCol
[i
] : "");
1803 if( len
>w
) w
= len
;
1805 if( p
->cnt
++>0 ) utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1806 for(i
=0; i
<nArg
; i
++){
1807 utf8_printf(p
->out
,"%*s = %s%s", w
, azCol
[i
],
1808 azArg
[i
] ? azArg
[i
] : p
->nullValue
, p
->rowSeparator
);
1814 static const int aExplainWidths
[] = {4, 13, 4, 4, 4, 13, 2, 13};
1815 const int *colWidth
;
1818 if( p
->cMode
==MODE_Column
){
1819 colWidth
= p
->colWidth
;
1820 showHdr
= p
->showHeader
;
1821 rowSep
= p
->rowSeparator
;
1823 colWidth
= aExplainWidths
;
1828 for(i
=0; i
<nArg
; i
++){
1830 if( i
<ArraySize(p
->colWidth
) ){
1836 w
= strlenChar(azCol
[i
] ? azCol
[i
] : "");
1838 n
= strlenChar(azArg
&& azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1841 if( i
<ArraySize(p
->actualWidth
) ){
1842 p
->actualWidth
[i
] = w
;
1845 utf8_width_print(p
->out
, w
, azCol
[i
]);
1846 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1850 for(i
=0; i
<nArg
; i
++){
1852 if( i
<ArraySize(p
->actualWidth
) ){
1853 w
= p
->actualWidth
[i
];
1858 utf8_printf(p
->out
,"%-*.*s%s",w
,w
,
1859 "----------------------------------------------------------"
1860 "----------------------------------------------------------",
1861 i
==nArg
-1 ? rowSep
: " ");
1865 if( azArg
==0 ) break;
1866 for(i
=0; i
<nArg
; i
++){
1868 if( i
<ArraySize(p
->actualWidth
) ){
1869 w
= p
->actualWidth
[i
];
1873 if( p
->cMode
==MODE_Explain
&& azArg
[i
] && strlenChar(azArg
[i
])>w
){
1874 w
= strlenChar(azArg
[i
]);
1876 if( i
==1 && p
->aiIndent
&& p
->pStmt
){
1877 if( p
->iIndent
<p
->nIndent
){
1878 utf8_printf(p
->out
, "%*.s", p
->aiIndent
[p
->iIndent
], "");
1882 utf8_width_print(p
->out
, w
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1883 utf8_printf(p
->out
, "%s", i
==nArg
-1 ? rowSep
: " ");
1887 case MODE_Semi
: { /* .schema and .fullschema output */
1888 printSchemaLine(p
->out
, azArg
[0], ";\n");
1891 case MODE_Pretty
: { /* .schema and .fullschema with --indent */
1899 if( azArg
[0]==0 ) break;
1900 if( sqlite3_strlike("CREATE VIEW%", azArg
[0], 0)==0
1901 || sqlite3_strlike("CREATE TRIG%", azArg
[0], 0)==0
1903 utf8_printf(p
->out
, "%s;\n", azArg
[0]);
1906 z
= sqlite3_mprintf("%s", azArg
[0]);
1908 for(i
=0; IsSpace(z
[i
]); i
++){}
1909 for(; (c
= z
[i
])!=0; i
++){
1911 if( z
[j
-1]=='\r' ) z
[j
-1] = '\n';
1912 if( IsSpace(z
[j
-1]) || z
[j
-1]=='(' ) continue;
1913 }else if( (c
=='(' || c
==')') && j
>0 && IsSpace(z
[j
-1]) ){
1918 while( j
>0 && IsSpace(z
[j
-1]) ){ j
--; }
1920 if( strlen30(z
)>=79 ){
1921 for(i
=j
=0; (c
= z
[i
])!=0; i
++){ /* Copy changes from z[i] back to z[j] */
1924 }else if( c
=='"' || c
=='\'' || c
=='`' ){
1928 }else if( c
=='-' && z
[i
+1]=='-' ){
1934 if( nLine
>0 && nParen
==0 && j
>0 ){
1935 printSchemaLineN(p
->out
, z
, j
, "\n");
1940 if( nParen
==1 && cEnd
==0
1941 && (c
=='(' || c
=='\n' || (c
==',' && !wsToEol(z
+i
+1)))
1944 printSchemaLineN(p
->out
, z
, j
, "\n ");
1947 while( IsSpace(z
[i
+1]) ){ i
++; }
1952 printSchemaLine(p
->out
, z
, ";\n");
1957 if( p
->cnt
++==0 && p
->showHeader
){
1958 for(i
=0; i
<nArg
; i
++){
1959 utf8_printf(p
->out
,"%s%s",azCol
[i
],
1960 i
==nArg
-1 ? p
->rowSeparator
: p
->colSeparator
);
1963 if( azArg
==0 ) break;
1964 for(i
=0; i
<nArg
; i
++){
1966 if( z
==0 ) z
= p
->nullValue
;
1967 utf8_printf(p
->out
, "%s", z
);
1969 utf8_printf(p
->out
, "%s", p
->colSeparator
);
1971 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
1977 if( p
->cnt
++==0 && p
->showHeader
){
1978 raw_printf(p
->out
,"<TR>");
1979 for(i
=0; i
<nArg
; i
++){
1980 raw_printf(p
->out
,"<TH>");
1981 output_html_string(p
->out
, azCol
[i
]);
1982 raw_printf(p
->out
,"</TH>\n");
1984 raw_printf(p
->out
,"</TR>\n");
1986 if( azArg
==0 ) break;
1987 raw_printf(p
->out
,"<TR>");
1988 for(i
=0; i
<nArg
; i
++){
1989 raw_printf(p
->out
,"<TD>");
1990 output_html_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
1991 raw_printf(p
->out
,"</TD>\n");
1993 raw_printf(p
->out
,"</TR>\n");
1997 if( p
->cnt
++==0 && p
->showHeader
){
1998 for(i
=0; i
<nArg
; i
++){
1999 output_c_string(p
->out
,azCol
[i
] ? azCol
[i
] : "");
2000 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2002 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2004 if( azArg
==0 ) break;
2005 for(i
=0; i
<nArg
; i
++){
2006 output_c_string(p
->out
, azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2007 if(i
<nArg
-1) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2009 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2013 setBinaryMode(p
->out
, 1);
2014 if( p
->cnt
++==0 && p
->showHeader
){
2015 for(i
=0; i
<nArg
; i
++){
2016 output_csv(p
, azCol
[i
] ? azCol
[i
] : "", i
<nArg
-1);
2018 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2021 for(i
=0; i
<nArg
; i
++){
2022 output_csv(p
, azArg
[i
], i
<nArg
-1);
2024 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2026 setTextMode(p
->out
, 1);
2030 if( azArg
==0 ) break;
2031 utf8_printf(p
->out
,"INSERT INTO %s",p
->zDestTable
);
2032 if( p
->showHeader
){
2033 raw_printf(p
->out
,"(");
2034 for(i
=0; i
<nArg
; i
++){
2035 if( i
>0 ) raw_printf(p
->out
, ",");
2036 if( quoteChar(azCol
[i
]) ){
2037 char *z
= sqlite3_mprintf("\"%w\"", azCol
[i
]);
2038 utf8_printf(p
->out
, "%s", z
);
2041 raw_printf(p
->out
, "%s", azCol
[i
]);
2044 raw_printf(p
->out
,")");
2047 for(i
=0; i
<nArg
; i
++){
2048 raw_printf(p
->out
, i
>0 ? "," : " VALUES(");
2049 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2050 utf8_printf(p
->out
,"NULL");
2051 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2052 if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2053 output_quoted_string(p
->out
, azArg
[i
]);
2055 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2057 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2058 utf8_printf(p
->out
,"%s", azArg
[i
]);
2059 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2061 double r
= sqlite3_column_double(p
->pStmt
, i
);
2063 memcpy(&ur
,&r
,sizeof(r
));
2064 if( ur
==0x7ff0000000000000LL
){
2065 raw_printf(p
->out
, "1e999");
2066 }else if( ur
==0xfff0000000000000LL
){
2067 raw_printf(p
->out
, "-1e999");
2069 sqlite3_snprintf(50,z
,"%!.20g", r
);
2070 raw_printf(p
->out
, "%s", z
);
2072 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2073 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2074 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2075 output_hex_blob(p
->out
, pBlob
, nBlob
);
2076 }else if( isNumber(azArg
[i
], 0) ){
2077 utf8_printf(p
->out
,"%s", azArg
[i
]);
2078 }else if( ShellHasFlag(p
, SHFLG_Newlines
) ){
2079 output_quoted_string(p
->out
, azArg
[i
]);
2081 output_quoted_escaped_string(p
->out
, azArg
[i
]);
2084 raw_printf(p
->out
,");\n");
2088 if( azArg
==0 ) break;
2089 if( p
->cnt
==0 && p
->showHeader
){
2090 for(i
=0; i
<nArg
; i
++){
2091 if( i
>0 ) raw_printf(p
->out
, ",");
2092 output_quoted_string(p
->out
, azCol
[i
]);
2094 raw_printf(p
->out
,"\n");
2097 for(i
=0; i
<nArg
; i
++){
2098 if( i
>0 ) raw_printf(p
->out
, ",");
2099 if( (azArg
[i
]==0) || (aiType
&& aiType
[i
]==SQLITE_NULL
) ){
2100 utf8_printf(p
->out
,"NULL");
2101 }else if( aiType
&& aiType
[i
]==SQLITE_TEXT
){
2102 output_quoted_string(p
->out
, azArg
[i
]);
2103 }else if( aiType
&& aiType
[i
]==SQLITE_INTEGER
){
2104 utf8_printf(p
->out
,"%s", azArg
[i
]);
2105 }else if( aiType
&& aiType
[i
]==SQLITE_FLOAT
){
2107 double r
= sqlite3_column_double(p
->pStmt
, i
);
2108 sqlite3_snprintf(50,z
,"%!.20g", r
);
2109 raw_printf(p
->out
, "%s", z
);
2110 }else if( aiType
&& aiType
[i
]==SQLITE_BLOB
&& p
->pStmt
){
2111 const void *pBlob
= sqlite3_column_blob(p
->pStmt
, i
);
2112 int nBlob
= sqlite3_column_bytes(p
->pStmt
, i
);
2113 output_hex_blob(p
->out
, pBlob
, nBlob
);
2114 }else if( isNumber(azArg
[i
], 0) ){
2115 utf8_printf(p
->out
,"%s", azArg
[i
]);
2117 output_quoted_string(p
->out
, azArg
[i
]);
2120 raw_printf(p
->out
,"\n");
2124 if( p
->cnt
++==0 && p
->showHeader
){
2125 for(i
=0; i
<nArg
; i
++){
2126 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2127 utf8_printf(p
->out
,"%s",azCol
[i
] ? azCol
[i
] : "");
2129 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2131 if( azArg
==0 ) break;
2132 for(i
=0; i
<nArg
; i
++){
2133 if( i
>0 ) utf8_printf(p
->out
, "%s", p
->colSeparator
);
2134 utf8_printf(p
->out
,"%s",azArg
[i
] ? azArg
[i
] : p
->nullValue
);
2136 utf8_printf(p
->out
, "%s", p
->rowSeparator
);
2140 eqp_append(p
, atoi(azArg
[0]), atoi(azArg
[1]), azArg
[3]);
2148 ** This is the callback routine that the SQLite library
2149 ** invokes for each row of a query result.
2151 static int callback(void *pArg
, int nArg
, char **azArg
, char **azCol
){
2152 /* since we don't have type info, call the shell_callback with a NULL value */
2153 return shell_callback(pArg
, nArg
, azArg
, azCol
, NULL
);
2157 ** This is the callback routine from sqlite3_exec() that appends all
2158 ** output onto the end of a ShellText object.
2160 static int captureOutputCallback(void *pArg
, int nArg
, char **azArg
, char **az
){
2161 ShellText
*p
= (ShellText
*)pArg
;
2163 UNUSED_PARAMETER(az
);
2164 if( azArg
==0 ) return 0;
2165 if( p
->n
) appendText(p
, "|", 0);
2166 for(i
=0; i
<nArg
; i
++){
2167 if( i
) appendText(p
, ",", 0);
2168 if( azArg
[i
] ) appendText(p
, azArg
[i
], 0);
2174 ** Generate an appropriate SELFTEST table in the main database.
2176 static void createSelftestTable(ShellState
*p
){
2179 "SAVEPOINT selftest_init;\n"
2180 "CREATE TABLE IF NOT EXISTS selftest(\n"
2181 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2182 " op TEXT,\n" /* Operator: memo run */
2183 " cmd TEXT,\n" /* Command text */
2184 " ans TEXT\n" /* Desired answer */
2186 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2187 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2188 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2189 " 'memo','Tests generated by --init');\n"
2190 "INSERT INTO [_shell$self]\n"
2192 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2193 "FROM sqlite_master ORDER BY 2'',224))',\n"
2194 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2195 "FROM sqlite_master ORDER BY 2',224));\n"
2196 "INSERT INTO [_shell$self]\n"
2198 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2199 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2200 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2202 " SELECT name FROM sqlite_master\n"
2203 " WHERE type='table'\n"
2204 " AND name<>'selftest'\n"
2205 " AND coalesce(rootpage,0)>0\n"
2208 "INSERT INTO [_shell$self]\n"
2209 " VALUES('run','PRAGMA integrity_check','ok');\n"
2210 "INSERT INTO selftest(tno,op,cmd,ans)"
2211 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2212 "DROP TABLE [_shell$self];"
2215 utf8_printf(stderr
, "SELFTEST initialization failure: %s\n", zErrMsg
);
2216 sqlite3_free(zErrMsg
);
2218 sqlite3_exec(p
->db
, "RELEASE selftest_init",0,0,0);
2223 ** Set the destination table field of the ShellState structure to
2224 ** the name of the table given. Escape any quote characters in the
2227 static void set_table_name(ShellState
*p
, const char *zName
){
2232 if( p
->zDestTable
){
2233 free(p
->zDestTable
);
2236 if( zName
==0 ) return;
2237 cQuote
= quoteChar(zName
);
2238 n
= strlen30(zName
);
2239 if( cQuote
) n
+= n
+2;
2240 z
= p
->zDestTable
= malloc( n
+1 );
2241 if( z
==0 ) shell_out_of_memory();
2243 if( cQuote
) z
[n
++] = cQuote
;
2244 for(i
=0; zName
[i
]; i
++){
2246 if( zName
[i
]==cQuote
) z
[n
++] = cQuote
;
2248 if( cQuote
) z
[n
++] = cQuote
;
2254 ** Execute a query statement that will generate SQL output. Print
2255 ** the result columns, comma-separated, on a line and then add a
2256 ** semicolon terminator to the end of that line.
2258 ** If the number of columns is 1 and that column contains text "--"
2259 ** then write the semicolon on a separate line. That way, if a
2260 ** "--" comment occurs at the end of the statement, the comment
2261 ** won't consume the semicolon terminator.
2263 static int run_table_dump_query(
2264 ShellState
*p
, /* Query context */
2265 const char *zSelect
, /* SELECT statement to extract content */
2266 const char *zFirstRow
/* Print before first row, if not NULL */
2268 sqlite3_stmt
*pSelect
;
2273 rc
= sqlite3_prepare_v2(p
->db
, zSelect
, -1, &pSelect
, 0);
2274 if( rc
!=SQLITE_OK
|| !pSelect
){
2275 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2276 sqlite3_errmsg(p
->db
));
2277 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2280 rc
= sqlite3_step(pSelect
);
2281 nResult
= sqlite3_column_count(pSelect
);
2282 while( rc
==SQLITE_ROW
){
2284 utf8_printf(p
->out
, "%s", zFirstRow
);
2287 z
= (const char*)sqlite3_column_text(pSelect
, 0);
2288 utf8_printf(p
->out
, "%s", z
);
2289 for(i
=1; i
<nResult
; i
++){
2290 utf8_printf(p
->out
, ",%s", sqlite3_column_text(pSelect
, i
));
2293 while( z
[0] && (z
[0]!='-' || z
[1]!='-') ) z
++;
2295 raw_printf(p
->out
, "\n;\n");
2297 raw_printf(p
->out
, ";\n");
2299 rc
= sqlite3_step(pSelect
);
2301 rc
= sqlite3_finalize(pSelect
);
2302 if( rc
!=SQLITE_OK
){
2303 utf8_printf(p
->out
, "/**** ERROR: (%d) %s *****/\n", rc
,
2304 sqlite3_errmsg(p
->db
));
2305 if( (rc
&0xff)!=SQLITE_CORRUPT
) p
->nErr
++;
2311 ** Allocate space and save off current error string.
2313 static char *save_err_msg(
2314 sqlite3
*db
/* Database to query */
2316 int nErrMsg
= 1+strlen30(sqlite3_errmsg(db
));
2317 char *zErrMsg
= sqlite3_malloc64(nErrMsg
);
2319 memcpy(zErrMsg
, sqlite3_errmsg(db
), nErrMsg
);
2326 ** Attempt to display I/O stats on Linux using /proc/PID/io
2328 static void displayLinuxIoStats(FILE *out
){
2331 sqlite3_snprintf(sizeof(z
), z
, "/proc/%d/io", getpid());
2332 in
= fopen(z
, "rb");
2334 while( fgets(z
, sizeof(z
), in
)!=0 ){
2335 static const struct {
2336 const char *zPattern
;
2339 { "rchar: ", "Bytes received by read():" },
2340 { "wchar: ", "Bytes sent to write():" },
2341 { "syscr: ", "Read() system calls:" },
2342 { "syscw: ", "Write() system calls:" },
2343 { "read_bytes: ", "Bytes read from storage:" },
2344 { "write_bytes: ", "Bytes written to storage:" },
2345 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
2348 for(i
=0; i
<ArraySize(aTrans
); i
++){
2349 int n
= strlen30(aTrans
[i
].zPattern
);
2350 if( strncmp(aTrans
[i
].zPattern
, z
, n
)==0 ){
2351 utf8_printf(out
, "%-36s %s", aTrans
[i
].zDesc
, &z
[n
]);
2361 ** Display a single line of status using 64-bit values.
2363 static void displayStatLine(
2364 ShellState
*p
, /* The shell context */
2365 char *zLabel
, /* Label for this one line */
2366 char *zFormat
, /* Format for the result */
2367 int iStatusCtrl
, /* Which status to display */
2368 int bReset
/* True to reset the stats */
2370 sqlite3_int64 iCur
= -1;
2371 sqlite3_int64 iHiwtr
= -1;
2374 sqlite3_status64(iStatusCtrl
, &iCur
, &iHiwtr
, bReset
);
2375 for(i
=0, nPercent
=0; zFormat
[i
]; i
++){
2376 if( zFormat
[i
]=='%' ) nPercent
++;
2379 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iCur
, iHiwtr
);
2381 sqlite3_snprintf(sizeof(zLine
), zLine
, zFormat
, iHiwtr
);
2383 raw_printf(p
->out
, "%-36s %s\n", zLabel
, zLine
);
2387 ** Display memory stats.
2389 static int display_stats(
2390 sqlite3
*db
, /* Database to query */
2391 ShellState
*pArg
, /* Pointer to ShellState */
2392 int bReset
/* True to reset the stats */
2397 if( pArg
==0 || pArg
->out
==0 ) return 0;
2400 if( pArg
->pStmt
&& (pArg
->statsOn
& 2) ){
2402 sqlite3_stmt
*pStmt
= pArg
->pStmt
;
2404 nCol
= sqlite3_column_count(pStmt
);
2405 raw_printf(out
, "%-36s %d\n", "Number of output columns:", nCol
);
2406 for(i
=0; i
<nCol
; i
++){
2407 sqlite3_snprintf(sizeof(z
),z
,"Column %d %nname:", i
, &x
);
2408 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_name(pStmt
,i
));
2409 #ifndef SQLITE_OMIT_DECLTYPE
2410 sqlite3_snprintf(30, z
+x
, "declared type:");
2411 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_decltype(pStmt
, i
));
2413 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2414 sqlite3_snprintf(30, z
+x
, "database name:");
2415 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_database_name(pStmt
,i
));
2416 sqlite3_snprintf(30, z
+x
, "table name:");
2417 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_table_name(pStmt
,i
));
2418 sqlite3_snprintf(30, z
+x
, "origin name:");
2419 utf8_printf(out
, "%-36s %s\n", z
, sqlite3_column_origin_name(pStmt
,i
));
2424 displayStatLine(pArg
, "Memory Used:",
2425 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED
, bReset
);
2426 displayStatLine(pArg
, "Number of Outstanding Allocations:",
2427 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT
, bReset
);
2428 if( pArg
->shellFlgs
& SHFLG_Pagecache
){
2429 displayStatLine(pArg
, "Number of Pcache Pages Used:",
2430 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED
, bReset
);
2432 displayStatLine(pArg
, "Number of Pcache Overflow Bytes:",
2433 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW
, bReset
);
2434 displayStatLine(pArg
, "Largest Allocation:",
2435 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE
, bReset
);
2436 displayStatLine(pArg
, "Largest Pcache Allocation:",
2437 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE
, bReset
);
2438 #ifdef YYTRACKMAXSTACKDEPTH
2439 displayStatLine(pArg
, "Deepest Parser Stack:",
2440 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK
, bReset
);
2444 if( pArg
->shellFlgs
& SHFLG_Lookaside
){
2446 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_USED
,
2447 &iCur
, &iHiwtr
, bReset
);
2448 raw_printf(pArg
->out
,
2449 "Lookaside Slots Used: %d (max %d)\n",
2451 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_HIT
,
2452 &iCur
, &iHiwtr
, bReset
);
2453 raw_printf(pArg
->out
, "Successful lookaside attempts: %d\n",
2455 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
,
2456 &iCur
, &iHiwtr
, bReset
);
2457 raw_printf(pArg
->out
, "Lookaside failures due to size: %d\n",
2459 sqlite3_db_status(db
, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
,
2460 &iCur
, &iHiwtr
, bReset
);
2461 raw_printf(pArg
->out
, "Lookaside failures due to OOM: %d\n",
2465 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_USED
, &iCur
, &iHiwtr
, bReset
);
2466 raw_printf(pArg
->out
, "Pager Heap Usage: %d bytes\n",
2469 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_HIT
, &iCur
, &iHiwtr
, 1);
2470 raw_printf(pArg
->out
, "Page cache hits: %d\n", iCur
);
2472 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_MISS
, &iCur
, &iHiwtr
, 1);
2473 raw_printf(pArg
->out
, "Page cache misses: %d\n", iCur
);
2475 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_WRITE
, &iCur
, &iHiwtr
, 1);
2476 raw_printf(pArg
->out
, "Page cache writes: %d\n", iCur
);
2478 sqlite3_db_status(db
, SQLITE_DBSTATUS_CACHE_SPILL
, &iCur
, &iHiwtr
, 1);
2479 raw_printf(pArg
->out
, "Page cache spills: %d\n", iCur
);
2481 sqlite3_db_status(db
, SQLITE_DBSTATUS_SCHEMA_USED
, &iCur
, &iHiwtr
, bReset
);
2482 raw_printf(pArg
->out
, "Schema Heap Usage: %d bytes\n",
2485 sqlite3_db_status(db
, SQLITE_DBSTATUS_STMT_USED
, &iCur
, &iHiwtr
, bReset
);
2486 raw_printf(pArg
->out
, "Statement Heap/Lookaside Usage: %d bytes\n",
2491 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_FULLSCAN_STEP
,
2493 raw_printf(pArg
->out
, "Fullscan Steps: %d\n", iCur
);
2494 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_SORT
, bReset
);
2495 raw_printf(pArg
->out
, "Sort Operations: %d\n", iCur
);
2496 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_AUTOINDEX
,bReset
);
2497 raw_printf(pArg
->out
, "Autoindex Inserts: %d\n", iCur
);
2498 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_VM_STEP
, bReset
);
2499 raw_printf(pArg
->out
, "Virtual Machine Steps: %d\n", iCur
);
2500 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_REPREPARE
, bReset
);
2501 raw_printf(pArg
->out
, "Reprepare operations: %d\n", iCur
);
2502 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_RUN
, bReset
);
2503 raw_printf(pArg
->out
, "Number of times run: %d\n", iCur
);
2504 iCur
= sqlite3_stmt_status(pArg
->pStmt
, SQLITE_STMTSTATUS_MEMUSED
, bReset
);
2505 raw_printf(pArg
->out
, "Memory used by prepared stmt: %d\n", iCur
);
2509 displayLinuxIoStats(pArg
->out
);
2512 /* Do not remove this machine readable comment: extra-stats-output-here */
2518 ** Display scan stats.
2520 static void display_scanstats(
2521 sqlite3
*db
, /* Database to query */
2522 ShellState
*pArg
/* Pointer to ShellState */
2524 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2525 UNUSED_PARAMETER(db
);
2526 UNUSED_PARAMETER(pArg
);
2529 raw_printf(pArg
->out
, "-------- scanstats --------\n");
2531 for(k
=0; k
<=mx
; k
++){
2532 double rEstLoop
= 1.0;
2534 sqlite3_stmt
*p
= pArg
->pStmt
;
2535 sqlite3_int64 nLoop
, nVisit
;
2538 const char *zExplain
;
2539 if( sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NLOOP
, (void*)&nLoop
) ){
2542 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_SELECTID
, (void*)&iSid
);
2543 if( iSid
>mx
) mx
= iSid
;
2544 if( iSid
!=k
) continue;
2546 rEstLoop
= (double)nLoop
;
2547 if( k
>0 ) raw_printf(pArg
->out
, "-------- subquery %d -------\n", k
);
2550 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_NVISIT
, (void*)&nVisit
);
2551 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EST
, (void*)&rEst
);
2552 sqlite3_stmt_scanstatus(p
, i
, SQLITE_SCANSTAT_EXPLAIN
, (void*)&zExplain
);
2553 utf8_printf(pArg
->out
, "Loop %2d: %s\n", n
, zExplain
);
2555 raw_printf(pArg
->out
,
2556 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
2557 nLoop
, nVisit
, (sqlite3_int64
)(rEstLoop
+0.5), rEst
2561 raw_printf(pArg
->out
, "---------------------------\n");
2566 ** Parameter azArray points to a zero-terminated array of strings. zStr
2567 ** points to a single nul-terminated string. Return non-zero if zStr
2568 ** is equal, according to strcmp(), to any of the strings in the array.
2569 ** Otherwise, return zero.
2571 static int str_in_array(const char *zStr
, const char **azArray
){
2573 for(i
=0; azArray
[i
]; i
++){
2574 if( 0==strcmp(zStr
, azArray
[i
]) ) return 1;
2580 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2581 ** and populate the ShellState.aiIndent[] array with the number of
2582 ** spaces each opcode should be indented before it is output.
2584 ** The indenting rules are:
2586 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2587 ** all opcodes that occur between the p2 jump destination and the opcode
2588 ** itself by 2 spaces.
2590 ** * For each "Goto", if the jump destination is earlier in the program
2591 ** and ends on one of:
2592 ** Yield SeekGt SeekLt RowSetRead Rewind
2593 ** or if the P1 parameter is one instead of zero,
2594 ** then indent all opcodes between the earlier instruction
2595 ** and "Goto" by 2 spaces.
2597 static void explain_data_prepare(ShellState
*p
, sqlite3_stmt
*pSql
){
2598 const char *zSql
; /* The text of the SQL statement */
2599 const char *z
; /* Used to check if this is an EXPLAIN */
2600 int *abYield
= 0; /* True if op is an OP_Yield */
2601 int nAlloc
= 0; /* Allocated size of p->aiIndent[], abYield */
2602 int iOp
; /* Index of operation in p->aiIndent[] */
2604 const char *azNext
[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
2605 const char *azYield
[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2607 const char *azGoto
[] = { "Goto", 0 };
2609 /* Try to figure out if this is really an EXPLAIN statement. If this
2610 ** cannot be verified, return early. */
2611 if( sqlite3_column_count(pSql
)!=8 ){
2615 zSql
= sqlite3_sql(pSql
);
2616 if( zSql
==0 ) return;
2617 for(z
=zSql
; *z
==' ' || *z
=='\t' || *z
=='\n' || *z
=='\f' || *z
=='\r'; z
++);
2618 if( sqlite3_strnicmp(z
, "explain", 7) ){
2623 for(iOp
=0; SQLITE_ROW
==sqlite3_step(pSql
); iOp
++){
2625 int iAddr
= sqlite3_column_int(pSql
, 0);
2626 const char *zOp
= (const char*)sqlite3_column_text(pSql
, 1);
2628 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2629 ** p2 is an instruction address, set variable p2op to the index of that
2630 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2631 ** the current instruction is part of a sub-program generated by an
2632 ** SQL trigger or foreign key. */
2633 int p2
= sqlite3_column_int(pSql
, 3);
2634 int p2op
= (p2
+ (iOp
-iAddr
));
2636 /* Grow the p->aiIndent array as required */
2639 /* Do further verfication that this is explain output. Abort if
2641 static const char *explainCols
[] = {
2642 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2644 for(jj
=0; jj
<ArraySize(explainCols
); jj
++){
2645 if( strcmp(sqlite3_column_name(pSql
,jj
),explainCols
[jj
])!=0 ){
2647 sqlite3_reset(pSql
);
2653 p
->aiIndent
= (int*)sqlite3_realloc64(p
->aiIndent
, nAlloc
*sizeof(int));
2654 if( p
->aiIndent
==0 ) shell_out_of_memory();
2655 abYield
= (int*)sqlite3_realloc64(abYield
, nAlloc
*sizeof(int));
2656 if( abYield
==0 ) shell_out_of_memory();
2658 abYield
[iOp
] = str_in_array(zOp
, azYield
);
2659 p
->aiIndent
[iOp
] = 0;
2662 if( str_in_array(zOp
, azNext
) ){
2663 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2665 if( str_in_array(zOp
, azGoto
) && p2op
<p
->nIndent
2666 && (abYield
[p2op
] || sqlite3_column_int(pSql
, 2))
2668 for(i
=p2op
; i
<iOp
; i
++) p
->aiIndent
[i
] += 2;
2673 sqlite3_free(abYield
);
2674 sqlite3_reset(pSql
);
2678 ** Free the array allocated by explain_data_prepare().
2680 static void explain_data_delete(ShellState
*p
){
2681 sqlite3_free(p
->aiIndent
);
2688 ** Disable and restore .wheretrace and .selecttrace settings.
2690 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2691 extern int sqlite3SelectTrace
;
2692 static int savedSelectTrace
;
2694 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2695 extern int sqlite3WhereTrace
;
2696 static int savedWhereTrace
;
2698 static void disable_debug_trace_modes(void){
2699 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2700 savedSelectTrace
= sqlite3SelectTrace
;
2701 sqlite3SelectTrace
= 0;
2703 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2704 savedWhereTrace
= sqlite3WhereTrace
;
2705 sqlite3WhereTrace
= 0;
2708 static void restore_debug_trace_modes(void){
2709 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2710 sqlite3SelectTrace
= savedSelectTrace
;
2712 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2713 sqlite3WhereTrace
= savedWhereTrace
;
2718 ** Run a prepared statement
2720 static void exec_prepared_stmt(
2721 ShellState
*pArg
, /* Pointer to ShellState */
2722 sqlite3_stmt
*pStmt
/* Statment to run */
2726 /* perform the first step. this will tell us if we
2727 ** have a result set or not and how wide it is.
2729 rc
= sqlite3_step(pStmt
);
2730 /* if we have a result set... */
2731 if( SQLITE_ROW
== rc
){
2732 /* allocate space for col name ptr, value ptr, and type */
2733 int nCol
= sqlite3_column_count(pStmt
);
2734 void *pData
= sqlite3_malloc64(3*nCol
*sizeof(const char*) + 1);
2738 char **azCols
= (char **)pData
; /* Names of result columns */
2739 char **azVals
= &azCols
[nCol
]; /* Results */
2740 int *aiTypes
= (int *)&azVals
[nCol
]; /* Result types */
2742 assert(sizeof(int) <= sizeof(char *));
2743 /* save off ptrs to column names */
2744 for(i
=0; i
<nCol
; i
++){
2745 azCols
[i
] = (char *)sqlite3_column_name(pStmt
, i
);
2748 /* extract the data and data types */
2749 for(i
=0; i
<nCol
; i
++){
2750 aiTypes
[i
] = x
= sqlite3_column_type(pStmt
, i
);
2751 if( x
==SQLITE_BLOB
&& pArg
&& pArg
->cMode
==MODE_Insert
){
2754 azVals
[i
] = (char*)sqlite3_column_text(pStmt
, i
);
2756 if( !azVals
[i
] && (aiTypes
[i
]!=SQLITE_NULL
) ){
2758 break; /* from for */
2762 /* if data and types extracted successfully... */
2763 if( SQLITE_ROW
== rc
){
2764 /* call the supplied callback with the result row data */
2765 if( shell_callback(pArg
, nCol
, azVals
, azCols
, aiTypes
) ){
2768 rc
= sqlite3_step(pStmt
);
2771 } while( SQLITE_ROW
== rc
);
2772 sqlite3_free(pData
);
2777 #ifndef SQLITE_OMIT_VIRTUALTABLE
2779 ** This function is called to process SQL if the previous shell command
2780 ** was ".expert". It passes the SQL in the second argument directly to
2781 ** the sqlite3expert object.
2783 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2784 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2785 ** an English language error message. It is the responsibility of the
2786 ** caller to eventually free this buffer using sqlite3_free().
2788 static int expertHandleSQL(
2793 assert( pState
->expert
.pExpert
);
2794 assert( pzErr
==0 || *pzErr
==0 );
2795 return sqlite3_expert_sql(pState
->expert
.pExpert
, zSql
, pzErr
);
2799 ** This function is called either to silently clean up the object
2800 ** created by the ".expert" command (if bCancel==1), or to generate a
2801 ** report from it and then clean it up (if bCancel==0).
2803 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
2804 ** code. In this case, (*pzErr) may be set to point to a buffer containing
2805 ** an English language error message. It is the responsibility of the
2806 ** caller to eventually free this buffer using sqlite3_free().
2808 static int expertFinish(
2814 sqlite3expert
*p
= pState
->expert
.pExpert
;
2816 assert( bCancel
|| pzErr
==0 || *pzErr
==0 );
2818 FILE *out
= pState
->out
;
2819 int bVerbose
= pState
->expert
.bVerbose
;
2821 rc
= sqlite3_expert_analyze(p
, pzErr
);
2822 if( rc
==SQLITE_OK
){
2823 int nQuery
= sqlite3_expert_count(p
);
2827 const char *zCand
= sqlite3_expert_report(p
,0,EXPERT_REPORT_CANDIDATES
);
2828 raw_printf(out
, "-- Candidates -----------------------------\n");
2829 raw_printf(out
, "%s\n", zCand
);
2831 for(i
=0; i
<nQuery
; i
++){
2832 const char *zSql
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_SQL
);
2833 const char *zIdx
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_INDEXES
);
2834 const char *zEQP
= sqlite3_expert_report(p
, i
, EXPERT_REPORT_PLAN
);
2835 if( zIdx
==0 ) zIdx
= "(no new indexes)\n";
2837 raw_printf(out
, "-- Query %d --------------------------------\n",i
+1);
2838 raw_printf(out
, "%s\n\n", zSql
);
2840 raw_printf(out
, "%s\n", zIdx
);
2841 raw_printf(out
, "%s\n", zEQP
);
2845 sqlite3_expert_destroy(p
);
2846 pState
->expert
.pExpert
= 0;
2851 ** Implementation of ".expert" dot command.
2853 static int expertDotCommand(
2854 ShellState
*pState
, /* Current shell tool state */
2855 char **azArg
, /* Array of arguments passed to dot command */
2856 int nArg
/* Number of entries in azArg[] */
2863 assert( pState
->expert
.pExpert
==0 );
2864 memset(&pState
->expert
, 0, sizeof(ExpertInfo
));
2866 for(i
=1; rc
==SQLITE_OK
&& i
<nArg
; i
++){
2869 if( z
[0]=='-' && z
[1]=='-' ) z
++;
2871 if( n
>=2 && 0==strncmp(z
, "-verbose", n
) ){
2872 pState
->expert
.bVerbose
= 1;
2874 else if( n
>=2 && 0==strncmp(z
, "-sample", n
) ){
2876 raw_printf(stderr
, "option requires an argument: %s\n", z
);
2879 iSample
= (int)integerValue(azArg
[++i
]);
2880 if( iSample
<0 || iSample
>100 ){
2881 raw_printf(stderr
, "value out of range: %s\n", azArg
[i
]);
2887 raw_printf(stderr
, "unknown option: %s\n", z
);
2892 if( rc
==SQLITE_OK
){
2893 pState
->expert
.pExpert
= sqlite3_expert_new(pState
->db
, &zErr
);
2894 if( pState
->expert
.pExpert
==0 ){
2895 raw_printf(stderr
, "sqlite3_expert_new: %s\n", zErr
);
2898 sqlite3_expert_config(
2899 pState
->expert
.pExpert
, EXPERT_CONFIG_SAMPLE
, iSample
2906 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2909 ** Execute a statement or set of statements. Print
2910 ** any result rows/columns depending on the current mode
2911 ** set via the supplied callback.
2913 ** This is very similar to SQLite's built-in sqlite3_exec()
2914 ** function except it takes a slightly different callback
2915 ** and callback data argument.
2917 static int shell_exec(
2918 ShellState
*pArg
, /* Pointer to ShellState */
2919 const char *zSql
, /* SQL to be evaluated */
2920 char **pzErrMsg
/* Error msg written here */
2922 sqlite3_stmt
*pStmt
= NULL
; /* Statement to execute. */
2923 int rc
= SQLITE_OK
; /* Return Code */
2925 const char *zLeftover
; /* Tail of unprocessed SQL */
2926 sqlite3
*db
= pArg
->db
;
2932 #ifndef SQLITE_OMIT_VIRTUALTABLE
2933 if( pArg
->expert
.pExpert
){
2934 rc
= expertHandleSQL(pArg
, zSql
, pzErrMsg
);
2935 return expertFinish(pArg
, (rc
!=SQLITE_OK
), pzErrMsg
);
2939 while( zSql
[0] && (SQLITE_OK
== rc
) ){
2940 static const char *zStmtSql
;
2941 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, &zLeftover
);
2942 if( SQLITE_OK
!= rc
){
2944 *pzErrMsg
= save_err_msg(db
);
2948 /* this happens for a comment or white-space */
2950 while( IsSpace(zSql
[0]) ) zSql
++;
2953 zStmtSql
= sqlite3_sql(pStmt
);
2954 if( zStmtSql
==0 ) zStmtSql
= "";
2955 while( IsSpace(zStmtSql
[0]) ) zStmtSql
++;
2957 /* save off the prepared statment handle and reset row count */
2959 pArg
->pStmt
= pStmt
;
2963 /* echo the sql statement if echo on */
2964 if( pArg
&& ShellHasFlag(pArg
, SHFLG_Echo
) ){
2965 utf8_printf(pArg
->out
, "%s\n", zStmtSql
? zStmtSql
: zSql
);
2968 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
2969 if( pArg
&& pArg
->autoEQP
&& sqlite3_strlike("EXPLAIN%",zStmtSql
,0)!=0 ){
2970 sqlite3_stmt
*pExplain
;
2973 disable_debug_trace_modes();
2974 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, -1, &triggerEQP
);
2975 if( pArg
->autoEQP
>=AUTOEQP_trigger
){
2976 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 1, 0);
2978 zEQP
= sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql
);
2979 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2980 if( rc
==SQLITE_OK
){
2981 while( sqlite3_step(pExplain
)==SQLITE_ROW
){
2982 const char *zEQPLine
= (const char*)sqlite3_column_text(pExplain
,3);
2983 int iEqpId
= sqlite3_column_int(pExplain
, 0);
2984 int iParentId
= sqlite3_column_int(pExplain
, 1);
2985 if( zEQPLine
[0]=='-' ) eqp_render(pArg
);
2986 eqp_append(pArg
, iEqpId
, iParentId
, zEQPLine
);
2990 sqlite3_finalize(pExplain
);
2992 if( pArg
->autoEQP
>=AUTOEQP_full
){
2993 /* Also do an EXPLAIN for ".eqp full" mode */
2994 zEQP
= sqlite3_mprintf("EXPLAIN %s", zStmtSql
);
2995 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
2996 if( rc
==SQLITE_OK
){
2997 pArg
->cMode
= MODE_Explain
;
2998 explain_data_prepare(pArg
, pExplain
);
2999 exec_prepared_stmt(pArg
, pExplain
);
3000 explain_data_delete(pArg
);
3002 sqlite3_finalize(pExplain
);
3005 if( pArg
->autoEQP
>=AUTOEQP_trigger
&& triggerEQP
==0 ){
3006 sqlite3_db_config(db
, SQLITE_DBCONFIG_TRIGGER_EQP
, 0, 0);
3007 /* Reprepare pStmt before reactiving trace modes */
3008 sqlite3_finalize(pStmt
);
3009 sqlite3_prepare_v2(db
, zSql
, -1, &pStmt
, 0);
3010 if( pArg
) pArg
->pStmt
= pStmt
;
3012 restore_debug_trace_modes();
3016 pArg
->cMode
= pArg
->mode
;
3017 if( pArg
->autoExplain
){
3018 if( sqlite3_column_count(pStmt
)==8
3019 && sqlite3_strlike("EXPLAIN%", zStmtSql
,0)==0
3021 pArg
->cMode
= MODE_Explain
;
3023 if( sqlite3_column_count(pStmt
)==4
3024 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql
,0)==0 ){
3025 pArg
->cMode
= MODE_EQP
;
3029 /* If the shell is currently in ".explain" mode, gather the extra
3030 ** data required to add indents to the output.*/
3031 if( pArg
->cMode
==MODE_Explain
){
3032 explain_data_prepare(pArg
, pStmt
);
3036 exec_prepared_stmt(pArg
, pStmt
);
3037 explain_data_delete(pArg
);
3040 /* print usage stats if stats on */
3041 if( pArg
&& pArg
->statsOn
){
3042 display_stats(db
, pArg
, 0);
3045 /* print loop-counters if required */
3046 if( pArg
&& pArg
->scanstatsOn
){
3047 display_scanstats(db
, pArg
);
3050 /* Finalize the statement just executed. If this fails, save a
3051 ** copy of the error message. Otherwise, set zSql to point to the
3052 ** next statement to execute. */
3053 rc2
= sqlite3_finalize(pStmt
);
3054 if( rc
!=SQLITE_NOMEM
) rc
= rc2
;
3055 if( rc
==SQLITE_OK
){
3057 while( IsSpace(zSql
[0]) ) zSql
++;
3058 }else if( pzErrMsg
){
3059 *pzErrMsg
= save_err_msg(db
);
3062 /* clear saved stmt handle */
3073 ** Release memory previously allocated by tableColumnList().
3075 static void freeColumnList(char **azCol
){
3077 for(i
=1; azCol
[i
]; i
++){
3078 sqlite3_free(azCol
[i
]);
3080 /* azCol[0] is a static string */
3081 sqlite3_free(azCol
);
3085 ** Return a list of pointers to strings which are the names of all
3086 ** columns in table zTab. The memory to hold the names is dynamically
3087 ** allocated and must be released by the caller using a subsequent call
3088 ** to freeColumnList().
3090 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3091 ** value that needs to be preserved, then azCol[0] is filled in with the
3092 ** name of the rowid column.
3094 ** The first regular column in the table is azCol[1]. The list is terminated
3095 ** by an entry with azCol[i]==0.
3097 static char **tableColumnList(ShellState
*p
, const char *zTab
){
3099 sqlite3_stmt
*pStmt
;
3103 int nPK
= 0; /* Number of PRIMARY KEY columns seen */
3104 int isIPK
= 0; /* True if one PRIMARY KEY column of type INTEGER */
3105 int preserveRowid
= ShellHasFlag(p
, SHFLG_PreserveRowid
);
3108 zSql
= sqlite3_mprintf("PRAGMA table_info=%Q", zTab
);
3109 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3112 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3113 if( nCol
>=nAlloc
-2 ){
3114 nAlloc
= nAlloc
*2 + nCol
+ 10;
3115 azCol
= sqlite3_realloc(azCol
, nAlloc
*sizeof(azCol
[0]));
3116 if( azCol
==0 ) shell_out_of_memory();
3118 azCol
[++nCol
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 1));
3119 if( sqlite3_column_int(pStmt
, 5) ){
3122 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt
,2),
3131 sqlite3_finalize(pStmt
);
3132 if( azCol
==0 ) return 0;
3136 /* The decision of whether or not a rowid really needs to be preserved
3137 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3138 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3139 ** rowids on tables where the rowid is inaccessible because there are other
3140 ** columns in the table named "rowid", "_rowid_", and "oid".
3142 if( preserveRowid
&& isIPK
){
3143 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3144 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3145 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3146 ** ROWID aliases. To distinguish these cases, check to see if
3147 ** there is a "pk" entry in "PRAGMA index_list". There will be
3148 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3150 zSql
= sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3151 " WHERE origin='pk'", zTab
);
3152 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
3155 freeColumnList(azCol
);
3158 rc
= sqlite3_step(pStmt
);
3159 sqlite3_finalize(pStmt
);
3160 preserveRowid
= rc
==SQLITE_ROW
;
3162 if( preserveRowid
){
3163 /* Only preserve the rowid if we can find a name to use for the
3165 static char *azRowid
[] = { "rowid", "_rowid_", "oid" };
3168 for(i
=1; i
<=nCol
; i
++){
3169 if( sqlite3_stricmp(azRowid
[j
],azCol
[i
])==0 ) break;
3172 /* At this point, we know that azRowid[j] is not the name of any
3173 ** ordinary column in the table. Verify that azRowid[j] is a valid
3174 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3175 ** tables will fail this last check */
3176 rc
= sqlite3_table_column_metadata(p
->db
,0,zTab
,azRowid
[j
],0,0,0,0,0);
3177 if( rc
==SQLITE_OK
) azCol
[0] = azRowid
[j
];
3186 ** Toggle the reverse_unordered_selects setting.
3188 static void toggleSelectOrder(sqlite3
*db
){
3189 sqlite3_stmt
*pStmt
= 0;
3192 sqlite3_prepare_v2(db
, "PRAGMA reverse_unordered_selects", -1, &pStmt
, 0);
3193 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3194 iSetting
= sqlite3_column_int(pStmt
, 0);
3196 sqlite3_finalize(pStmt
);
3197 sqlite3_snprintf(sizeof(zStmt
), zStmt
,
3198 "PRAGMA reverse_unordered_selects(%d)", !iSetting
);
3199 sqlite3_exec(db
, zStmt
, 0, 0, 0);
3203 ** This is a different callback routine used for dumping the database.
3204 ** Each row received by this callback consists of a table name,
3205 ** the table type ("index" or "table") and SQL to create the table.
3206 ** This routine should print text sufficient to recreate the table.
3208 static int dump_callback(void *pArg
, int nArg
, char **azArg
, char **azNotUsed
){
3213 ShellState
*p
= (ShellState
*)pArg
;
3215 UNUSED_PARAMETER(azNotUsed
);
3216 if( nArg
!=3 || azArg
==0 ) return 0;
3221 if( strcmp(zTable
, "sqlite_sequence")==0 ){
3222 raw_printf(p
->out
, "DELETE FROM sqlite_sequence;\n");
3223 }else if( sqlite3_strglob("sqlite_stat?", zTable
)==0 ){
3224 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
3225 }else if( strncmp(zTable
, "sqlite_", 7)==0 ){
3227 }else if( strncmp(zSql
, "CREATE VIRTUAL TABLE", 20)==0 ){
3229 if( !p
->writableSchema
){
3230 raw_printf(p
->out
, "PRAGMA writable_schema=ON;\n");
3231 p
->writableSchema
= 1;
3233 zIns
= sqlite3_mprintf(
3234 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3235 "VALUES('table','%q','%q',0,'%q');",
3236 zTable
, zTable
, zSql
);
3237 utf8_printf(p
->out
, "%s\n", zIns
);
3241 printSchemaLine(p
->out
, zSql
, ";\n");
3244 if( strcmp(zType
, "table")==0 ){
3249 char *savedDestTable
;
3252 azCol
= tableColumnList(p
, zTable
);
3258 /* Always quote the table name, even if it appears to be pure ascii,
3259 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
3261 appendText(&sTable
, zTable
, quoteChar(zTable
));
3262 /* If preserving the rowid, add a column list after the table name.
3263 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3264 ** instead of the usual "INSERT INTO tab VALUES(...)".
3267 appendText(&sTable
, "(", 0);
3268 appendText(&sTable
, azCol
[0], 0);
3269 for(i
=1; azCol
[i
]; i
++){
3270 appendText(&sTable
, ",", 0);
3271 appendText(&sTable
, azCol
[i
], quoteChar(azCol
[i
]));
3273 appendText(&sTable
, ")", 0);
3276 /* Build an appropriate SELECT statement */
3278 appendText(&sSelect
, "SELECT ", 0);
3280 appendText(&sSelect
, azCol
[0], 0);
3281 appendText(&sSelect
, ",", 0);
3283 for(i
=1; azCol
[i
]; i
++){
3284 appendText(&sSelect
, azCol
[i
], quoteChar(azCol
[i
]));
3286 appendText(&sSelect
, ",", 0);
3289 freeColumnList(azCol
);
3290 appendText(&sSelect
, " FROM ", 0);
3291 appendText(&sSelect
, zTable
, quoteChar(zTable
));
3293 savedDestTable
= p
->zDestTable
;
3294 savedMode
= p
->mode
;
3295 p
->zDestTable
= sTable
.z
;
3296 p
->mode
= p
->cMode
= MODE_Insert
;
3297 rc
= shell_exec(p
, sSelect
.z
, 0);
3298 if( (rc
&0xff)==SQLITE_CORRUPT
){
3299 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3300 toggleSelectOrder(p
->db
);
3301 shell_exec(p
, sSelect
.z
, 0);
3302 toggleSelectOrder(p
->db
);
3304 p
->zDestTable
= savedDestTable
;
3305 p
->mode
= savedMode
;
3314 ** Run zQuery. Use dump_callback() as the callback routine so that
3315 ** the contents of the query are output as SQL statements.
3317 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
3318 ** "ORDER BY rowid DESC" to the end.
3320 static int run_schema_dump_query(
3326 rc
= sqlite3_exec(p
->db
, zQuery
, dump_callback
, p
, &zErr
);
3327 if( rc
==SQLITE_CORRUPT
){
3329 int len
= strlen30(zQuery
);
3330 raw_printf(p
->out
, "/****** CORRUPTION ERROR *******/\n");
3332 utf8_printf(p
->out
, "/****** %s ******/\n", zErr
);
3336 zQ2
= malloc( len
+100 );
3337 if( zQ2
==0 ) return rc
;
3338 sqlite3_snprintf(len
+100, zQ2
, "%s ORDER BY rowid DESC", zQuery
);
3339 rc
= sqlite3_exec(p
->db
, zQ2
, dump_callback
, p
, &zErr
);
3341 utf8_printf(p
->out
, "/****** ERROR: %s ******/\n", zErr
);
3343 rc
= SQLITE_CORRUPT
;
3352 ** Text of help messages.
3354 ** The help text for each individual command begins with a line that starts
3355 ** with ".". Subsequent lines are supplimental information.
3357 ** There must be two or more spaces between the end of the command and the
3358 ** start of the description of what that command does.
3360 static const char *(azHelp
[]) = {
3361 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
3362 ".archive ... Manage SQL archives",
3363 " Each command must have exactly one of the following options:",
3364 " -c, --create Create a new archive",
3365 " -u, --update Update or add files to an existing archive",
3366 " -t, --list List contents of archive",
3367 " -x, --extract Extract files from archive",
3368 " Optional arguments:",
3369 " -v, --verbose Print each filename as it is processed",
3370 " -f FILE, --file FILE Operate on archive FILE (default is current db)",
3371 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS",
3372 " -C DIR, --directory DIR Change to directory DIR to read/extract files",
3373 " -n, --dryrun Show the SQL that would have occurred",
3375 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar",
3376 " .ar -tf archive.sar # List members of archive.sar",
3377 " .ar -xvf archive.sar # Verbosely extract files from archive.sar",
3379 " http://sqlite.org/cli.html#sqlar_archive_support",
3381 #ifndef SQLITE_OMIT_AUTHORIZATION
3382 ".auth ON|OFF Show authorizer callbacks",
3384 ".backup ?DB? FILE Backup DB (default \"main\") to FILE",
3385 " --append Use the appendvfs",
3386 ".bail on|off Stop after hitting an error. Default OFF",
3387 ".binary on|off Turn binary output on or off. Default OFF",
3388 ".cd DIRECTORY Change the working directory to DIRECTORY",
3389 ".changes on|off Show number of rows changed by SQL",
3390 ".check GLOB Fail if output since .testcase does not match",
3391 ".clone NEWDB Clone data into NEWDB from the existing database",
3392 ".databases List names and files of attached databases",
3393 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options",
3394 ".dbinfo ?DB? Show status information about the database",
3395 ".dump ?TABLE? ... Render all database content as SQL",
3397 " --preserve-rowids Include ROWID values in the output",
3398 " --newlines Allow unescaped newline characters in output",
3399 " TABLE is LIKE pattern for the tables to dump",
3400 ".echo on|off Turn command echo on or off",
3401 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN",
3402 ".excel Display the output of next command in a spreadsheet",
3403 ".exit ?CODE? Exit this program with return-code CODE",
3404 ".expert EXPERIMENTAL. Suggest indexes for specified queries",
3405 /* Because explain mode comes on automatically now, the ".explain" mode
3406 ** is removed from the help screen. It is still supported for legacy, however */
3407 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic",*/
3408 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables",
3409 ".headers on|off Turn display of headers on or off",
3410 ".help ?-all? ?PATTERN? Show help text for PATTERN",
3411 ".import FILE TABLE Import data from FILE into TABLE",
3412 #ifndef SQLITE_OMIT_TEST_CONTROL
3413 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX",
3415 ".indexes ?TABLE? Show names of indexes",
3416 " If TABLE is specified, only show indexes for",
3417 " tables matching TABLE using the LIKE operator.",
3418 #ifdef SQLITE_ENABLE_IOTRACE
3419 ".iotrace FILE Enable I/O diagnostic logging to FILE",
3421 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT",
3422 ".lint OPTIONS Report potential schema issues.",
3424 " fkey-indexes Find missing foreign key indexes",
3425 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3426 ".load FILE ?ENTRY? Load an extension library",
3428 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout",
3429 ".mode MODE ?TABLE? Set output mode",
3431 " ascii Columns/rows delimited by 0x1F and 0x1E",
3432 " csv Comma-separated values",
3433 " column Left-aligned columns. (See .width)",
3434 " html HTML <table> code",
3435 " insert SQL insert statements for TABLE",
3436 " line One value per line",
3437 " list Values delimited by \"|\"",
3438 " quote Escape answers as for SQL",
3439 " tabs Tab-separated values",
3440 " tcl TCL list elements",
3441 ".nullvalue STRING Use STRING in place of NULL values",
3442 ".once (-e|-x|FILE) Output for the next SQL command only to FILE",
3443 " If FILE begins with '|' then open as a pipe",
3445 " -e Invoke system text editor",
3446 " -x Open in a spreadsheet",
3447 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE",
3449 " --append Use appendvfs to append database to the end of FILE",
3450 #ifdef SQLITE_ENABLE_DESERIALIZE
3451 " --deserialize Load into memory useing sqlite3_deserialize()",
3453 " --new Initialize FILE to an empty database",
3454 " --readonly Open FILE readonly",
3455 " --zip FILE is a ZIP archive",
3456 ".output ?FILE? Send output to FILE or stdout if FILE is omitted",
3457 " If FILE begins with '|' then open it as a pipe.",
3458 ".print STRING... Print literal STRING",
3459 ".prompt MAIN CONTINUE Replace the standard prompts",
3460 ".quit Exit this program",
3461 ".read FILE Read input from FILE",
3462 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE",
3463 ".save FILE Write in-memory database into FILE",
3464 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off",
3465 ".schema ?PATTERN? Show the CREATE statements matching PATTERN",
3467 " --indent Try to pretty-print the schema",
3468 ".selftest ?OPTIONS? Run tests defined in the SELFTEST table",
3470 " --init Create a new SELFTEST table",
3471 " -v Verbose output",
3472 ".separator COL ?ROW? Change the column and row separators",
3473 #if defined(SQLITE_ENABLE_SESSION)
3474 ".session ?NAME? CMD ... Create or control sessions",
3476 " attach TABLE Attach TABLE",
3477 " changeset FILE Write a changeset into FILE",
3478 " close Close one session",
3479 " enable ?BOOLEAN? Set or query the enable bit",
3480 " filter GLOB... Reject tables matching GLOBs",
3481 " indirect ?BOOLEAN? Mark or query the indirect status",
3482 " isempty Query whether the session is empty",
3483 " list List currently open session names",
3484 " open DB NAME Open a new session on DB",
3485 " patchset FILE Write a patchset into FILE",
3486 " If ?NAME? is omitted, the first defined session is used.",
3488 ".sha3sum ... Compute a SHA3 hash of database content",
3490 " --schema Also hash the sqlite_master table",
3491 " --sha3-224 Use the sha3-224 algorithm",
3492 " --sha3-256 Use the sha3-256 algorithm. This is the default.",
3493 " --sha3-384 Use the sha3-384 algorithm",
3494 " --sha3-512 Use the sha3-512 algorithm",
3495 " Any other argument is a LIKE pattern for tables to hash",
3496 #ifndef SQLITE_NOHAVE_SYSTEM
3497 ".shell CMD ARGS... Run CMD ARGS... in a system shell",
3499 ".show Show the current values for various settings",
3500 ".stats ?on|off? Show stats or turn stats on or off",
3501 #ifndef SQLITE_NOHAVE_SYSTEM
3502 ".system CMD ARGS... Run CMD ARGS... in a system shell",
3504 ".tables ?TABLE? List names of tables matching LIKE pattern TABLE",
3505 ".testcase NAME Begin redirecting output to 'testcase-out.txt'",
3506 ".timeout MS Try opening locked tables for MS milliseconds",
3507 ".timer on|off Turn SQL timer on or off",
3508 ".trace FILE|off Output each SQL statement as it is run",
3509 ".vfsinfo ?AUX? Information about the top-level VFS",
3510 ".vfslist List all available VFSes",
3511 ".vfsname ?AUX? Print the name of the VFS stack",
3512 ".width NUM1 NUM2 ... Set column widths for \"column\" mode",
3513 " Negative values right-justify",
3517 ** Output help text.
3519 ** zPattern describes the set of commands for which help text is provided.
3520 ** If zPattern is NULL, then show all commands, but only give a one-line
3521 ** description of each.
3523 ** Return the number of matches.
3525 static int showHelp(FILE *out
, const char *zPattern
){
3532 || strcmp(zPattern
,"-a")==0
3533 || strcmp(zPattern
,"-all")==0
3535 /* Show all commands, but only one line per command */
3536 if( zPattern
==0 ) zPattern
= "";
3537 for(i
=0; i
<ArraySize(azHelp
); i
++){
3538 if( azHelp
[i
][0]=='.' || zPattern
[0] ){
3539 utf8_printf(out
, "%s\n", azHelp
[i
]);
3544 /* Look for commands that for which zPattern is an exact prefix */
3545 zPat
= sqlite3_mprintf(".%s*", zPattern
);
3546 for(i
=0; i
<ArraySize(azHelp
); i
++){
3547 if( sqlite3_strglob(zPat
, azHelp
[i
])==0 ){
3548 utf8_printf(out
, "%s\n", azHelp
[i
]);
3556 /* when zPattern is a prefix of exactly one command, then include the
3557 ** details of that command, which should begin at offset j */
3558 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
][0]!='.' ){
3559 utf8_printf(out
, "%s\n", azHelp
[j
]);
3565 /* Look for commands that contain zPattern anywhere. Show the complete
3566 ** text of all commands that match. */
3567 zPat
= sqlite3_mprintf("%%%s%%", zPattern
);
3568 for(i
=0; i
<ArraySize(azHelp
); i
++){
3569 if( azHelp
[i
][0]=='.' ) j
= i
;
3570 if( sqlite3_strlike(zPat
, azHelp
[i
], 0)==0 ){
3571 utf8_printf(out
, "%s\n", azHelp
[j
]);
3572 while( j
<ArraySize(azHelp
)-1 && azHelp
[j
+1][0]!='.' ){
3574 utf8_printf(out
, "%s\n", azHelp
[j
]);
3585 /* Forward reference */
3586 static int process_input(ShellState
*p
, FILE *in
);
3589 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
3590 ** and return a pointer to the buffer. The caller is responsible for freeing
3593 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3596 ** For convenience, a nul-terminator byte is always appended to the data read
3597 ** from the file before the buffer is returned. This byte is not included in
3598 ** the final value of (*pnByte), if applicable.
3600 ** NULL is returned if any error is encountered. The final value of *pnByte
3601 ** is undefined in this case.
3603 static char *readFile(const char *zName
, int *pnByte
){
3604 FILE *in
= fopen(zName
, "rb");
3608 if( in
==0 ) return 0;
3609 fseek(in
, 0, SEEK_END
);
3612 pBuf
= sqlite3_malloc64( nIn
+1 );
3613 if( pBuf
==0 ){ fclose(in
); return 0; }
3614 nRead
= fread(pBuf
, nIn
, 1, in
);
3621 if( pnByte
) *pnByte
= nIn
;
3625 #if defined(SQLITE_ENABLE_SESSION)
3627 ** Close a single OpenSession object and release all of its associated
3630 static void session_close(OpenSession
*pSession
){
3632 sqlite3session_delete(pSession
->p
);
3633 sqlite3_free(pSession
->zName
);
3634 for(i
=0; i
<pSession
->nFilter
; i
++){
3635 sqlite3_free(pSession
->azFilter
[i
]);
3637 sqlite3_free(pSession
->azFilter
);
3638 memset(pSession
, 0, sizeof(OpenSession
));
3643 ** Close all OpenSession objects and release all associated resources.
3645 #if defined(SQLITE_ENABLE_SESSION)
3646 static void session_close_all(ShellState
*p
){
3648 for(i
=0; i
<p
->nSession
; i
++){
3649 session_close(&p
->aSession
[i
]);
3654 # define session_close_all(X)
3658 ** Implementation of the xFilter function for an open session. Omit
3659 ** any tables named by ".session filter" but let all other table through.
3661 #if defined(SQLITE_ENABLE_SESSION)
3662 static int session_filter(void *pCtx
, const char *zTab
){
3663 OpenSession
*pSession
= (OpenSession
*)pCtx
;
3665 for(i
=0; i
<pSession
->nFilter
; i
++){
3666 if( sqlite3_strglob(pSession
->azFilter
[i
], zTab
)==0 ) return 0;
3673 ** Try to deduce the type of file for zName based on its content. Return
3674 ** one of the SHELL_OPEN_* constants.
3676 ** If the file does not exist or is empty but its name looks like a ZIP
3677 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
3678 ** Otherwise, assume an ordinary database regardless of the filename if
3679 ** the type cannot be determined from content.
3681 int deduceDatabaseType(const char *zName
, int dfltZip
){
3682 FILE *f
= fopen(zName
, "rb");
3684 int rc
= SHELL_OPEN_UNSPEC
;
3687 if( dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
3688 return SHELL_OPEN_ZIPFILE
;
3690 return SHELL_OPEN_NORMAL
;
3693 n
= fread(zBuf
, 16, 1, f
);
3694 if( n
==1 && memcmp(zBuf
, "SQLite format 3", 16)==0 ){
3696 return SHELL_OPEN_NORMAL
;
3698 fseek(f
, -25, SEEK_END
);
3699 n
= fread(zBuf
, 25, 1, f
);
3700 if( n
==1 && memcmp(zBuf
, "Start-Of-SQLite3-", 17)==0 ){
3701 rc
= SHELL_OPEN_APPENDVFS
;
3703 fseek(f
, -22, SEEK_END
);
3704 n
= fread(zBuf
, 22, 1, f
);
3705 if( n
==1 && zBuf
[0]==0x50 && zBuf
[1]==0x4b && zBuf
[2]==0x05
3707 rc
= SHELL_OPEN_ZIPFILE
;
3708 }else if( n
==0 && dfltZip
&& sqlite3_strlike("%.zip",zName
,0)==0 ){
3709 rc
= SHELL_OPEN_ZIPFILE
;
3716 /* Flags for open_db().
3718 ** The default behavior of open_db() is to exit(1) if the database fails to
3719 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
3720 ** but still returns without calling exit.
3722 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
3723 ** ZIP archive if the file does not exist or is empty and its name matches
3724 ** the *.zip pattern.
3726 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
3727 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
3730 ** Make sure the database is open. If it is not, then open it. If
3731 ** the database fails to open, print an error message and exit.
3733 static void open_db(ShellState
*p
, int openFlags
){
3735 if( p
->openMode
==SHELL_OPEN_UNSPEC
){
3736 if( p
->zDbFilename
==0 || p
->zDbFilename
[0]==0 ){
3737 p
->openMode
= SHELL_OPEN_NORMAL
;
3739 p
->openMode
= (u8
)deduceDatabaseType(p
->zDbFilename
,
3740 (openFlags
& OPEN_DB_ZIPFILE
)!=0);
3743 switch( p
->openMode
){
3744 case SHELL_OPEN_APPENDVFS
: {
3745 sqlite3_open_v2(p
->zDbFilename
, &p
->db
,
3746 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, "apndvfs");
3749 case SHELL_OPEN_DESERIALIZE
: {
3750 sqlite3_open(0, &p
->db
);
3753 case SHELL_OPEN_ZIPFILE
: {
3754 sqlite3_open(":memory:", &p
->db
);
3757 case SHELL_OPEN_READONLY
: {
3758 sqlite3_open_v2(p
->zDbFilename
, &p
->db
, SQLITE_OPEN_READONLY
, 0);
3761 case SHELL_OPEN_UNSPEC
:
3762 case SHELL_OPEN_NORMAL
: {
3763 sqlite3_open(p
->zDbFilename
, &p
->db
);
3768 if( p
->db
==0 || SQLITE_OK
!=sqlite3_errcode(p
->db
) ){
3769 utf8_printf(stderr
,"Error: unable to open database \"%s\": %s\n",
3770 p
->zDbFilename
, sqlite3_errmsg(p
->db
));
3771 if( openFlags
& OPEN_DB_KEEPALIVE
) return;
3774 #ifndef SQLITE_OMIT_LOAD_EXTENSION
3775 sqlite3_enable_load_extension(p
->db
, 1);
3777 sqlite3_fileio_init(p
->db
, 0, 0);
3778 sqlite3_shathree_init(p
->db
, 0, 0);
3779 sqlite3_completion_init(p
->db
, 0, 0);
3780 #ifdef SQLITE_HAVE_ZLIB
3781 sqlite3_zipfile_init(p
->db
, 0, 0);
3782 sqlite3_sqlar_init(p
->db
, 0, 0);
3784 sqlite3_create_function(p
->db
, "shell_add_schema", 3, SQLITE_UTF8
, 0,
3785 shellAddSchemaName
, 0, 0);
3786 sqlite3_create_function(p
->db
, "shell_module_schema", 1, SQLITE_UTF8
, 0,
3787 shellModuleSchema
, 0, 0);
3788 sqlite3_create_function(p
->db
, "shell_putsnl", 1, SQLITE_UTF8
, p
,
3789 shellPutsFunc
, 0, 0);
3790 #ifndef SQLITE_NOHAVE_SYSTEM
3791 sqlite3_create_function(p
->db
, "edit", 1, SQLITE_UTF8
, 0,
3793 sqlite3_create_function(p
->db
, "edit", 2, SQLITE_UTF8
, 0,
3796 if( p
->openMode
==SHELL_OPEN_ZIPFILE
){
3797 char *zSql
= sqlite3_mprintf(
3798 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p
->zDbFilename
);
3799 sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
3802 #ifdef SQLITE_ENABLE_DESERIALIZE
3803 else if( p
->openMode
==SHELL_OPEN_DESERIALIZE
){
3805 unsigned char *aData
= (unsigned char*)readFile(p
->zDbFilename
, &nData
);
3806 int rc
= sqlite3_deserialize(p
->db
, "main", aData
, nData
, nData
,
3807 SQLITE_DESERIALIZE_RESIZEABLE
|
3808 SQLITE_DESERIALIZE_FREEONCLOSE
);
3810 utf8_printf(stderr
, "Error: sqlite3_deserialize() returns %d\n", rc
);
3818 ** Attempt to close the databaes connection. Report errors.
3820 void close_db(sqlite3
*db
){
3821 int rc
= sqlite3_close(db
);
3823 utf8_printf(stderr
, "Error: sqlite3_close() returns %d: %s\n",
3824 rc
, sqlite3_errmsg(db
));
3828 #if HAVE_READLINE || HAVE_EDITLINE
3830 ** Readline completion callbacks
3832 static char *readline_completion_generator(const char *text
, int state
){
3833 static sqlite3_stmt
*pStmt
= 0;
3837 sqlite3_finalize(pStmt
);
3838 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3839 " FROM completion(%Q) ORDER BY 1", text
);
3840 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3843 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
3844 zRet
= strdup((const char*)sqlite3_column_text(pStmt
, 0));
3846 sqlite3_finalize(pStmt
);
3852 static char **readline_completion(const char *zText
, int iStart
, int iEnd
){
3853 rl_attempted_completion_over
= 1;
3854 return rl_completion_matches(zText
, readline_completion_generator
);
3857 #elif HAVE_LINENOISE
3859 ** Linenoise completion callback
3861 static void linenoise_completion(const char *zLine
, linenoiseCompletions
*lc
){
3862 int nLine
= strlen30(zLine
);
3864 sqlite3_stmt
*pStmt
= 0;
3868 if( nLine
>sizeof(zBuf
)-30 ) return;
3869 if( zLine
[0]=='.' || zLine
[0]=='#') return;
3870 for(i
=nLine
-1; i
>=0 && (isalnum(zLine
[i
]) || zLine
[i
]=='_'); i
--){}
3871 if( i
==nLine
-1 ) return;
3873 memcpy(zBuf
, zLine
, iStart
);
3874 zSql
= sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
3875 " FROM completion(%Q,%Q) ORDER BY 1",
3876 &zLine
[iStart
], zLine
);
3877 sqlite3_prepare_v2(globalDb
, zSql
, -1, &pStmt
, 0);
3879 sqlite3_exec(globalDb
, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
3880 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
3881 const char *zCompletion
= (const char*)sqlite3_column_text(pStmt
, 0);
3882 int nCompletion
= sqlite3_column_bytes(pStmt
, 0);
3883 if( iStart
+nCompletion
< sizeof(zBuf
)-1 ){
3884 memcpy(zBuf
+iStart
, zCompletion
, nCompletion
+1);
3885 linenoiseAddCompletion(lc
, zBuf
);
3888 sqlite3_finalize(pStmt
);
3893 ** Do C-language style dequoting.
3899 ** \v -> vertical tab
3901 ** \r -> carriage return
3906 ** \NNN -> ascii character NNN in octal
3908 static void resolve_backslashes(char *z
){
3911 while( *z
&& *z
!='\\' ) z
++;
3912 for(i
=j
=0; (c
= z
[i
])!=0; i
++, j
++){
3913 if( c
=='\\' && z
[i
+1]!=0 ){
3931 }else if( c
=='\'' ){
3933 }else if( c
=='\\' ){
3935 }else if( c
>='0' && c
<='7' ){
3937 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3939 c
= (c
<<3) + z
[i
] - '0';
3940 if( z
[i
+1]>='0' && z
[i
+1]<='7' ){
3942 c
= (c
<<3) + z
[i
] - '0';
3953 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3954 ** for TRUE and FALSE. Return the integer value if appropriate.
3956 static int booleanValue(const char *zArg
){
3958 if( zArg
[0]=='0' && zArg
[1]=='x' ){
3959 for(i
=2; hexDigitValue(zArg
[i
])>=0; i
++){}
3961 for(i
=0; zArg
[i
]>='0' && zArg
[i
]<='9'; i
++){}
3963 if( i
>0 && zArg
[i
]==0 ) return (int)(integerValue(zArg
) & 0xffffffff);
3964 if( sqlite3_stricmp(zArg
, "on")==0 || sqlite3_stricmp(zArg
,"yes")==0 ){
3967 if( sqlite3_stricmp(zArg
, "off")==0 || sqlite3_stricmp(zArg
,"no")==0 ){
3970 utf8_printf(stderr
, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
3976 ** Set or clear a shell flag according to a boolean value.
3978 static void setOrClearFlag(ShellState
*p
, unsigned mFlag
, const char *zArg
){
3979 if( booleanValue(zArg
) ){
3980 ShellSetFlag(p
, mFlag
);
3982 ShellClearFlag(p
, mFlag
);
3987 ** Close an output file, assuming it is not stderr or stdout
3989 static void output_file_close(FILE *f
){
3990 if( f
&& f
!=stdout
&& f
!=stderr
) fclose(f
);
3994 ** Try to open an output file. The names "stdout" and "stderr" are
3995 ** recognized and do the right thing. NULL is returned if the output
3996 ** filename is "off".
3998 static FILE *output_file_open(const char *zFile
, int bTextMode
){
4000 if( strcmp(zFile
,"stdout")==0 ){
4002 }else if( strcmp(zFile
, "stderr")==0 ){
4004 }else if( strcmp(zFile
, "off")==0 ){
4007 f
= fopen(zFile
, bTextMode
? "w" : "wb");
4009 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
4015 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
4017 ** A routine for handling output from sqlite3_trace().
4019 static int sql_trace_callback(
4025 FILE *f
= (FILE*)pArg
;
4026 UNUSED_PARAMETER(mType
);
4027 UNUSED_PARAMETER(pP
);
4029 const char *z
= (const char*)pX
;
4030 int i
= strlen30(z
);
4031 while( i
>0 && z
[i
-1]==';' ){ i
--; }
4032 utf8_printf(f
, "%.*s;\n", i
, z
);
4039 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
4040 ** a useful spot to set a debugger breakpoint.
4042 static void test_breakpoint(void){
4043 static int nCall
= 0;
4048 ** An object used to read a CSV and other files for import.
4050 typedef struct ImportCtx ImportCtx
;
4052 const char *zFile
; /* Name of the input file */
4053 FILE *in
; /* Read the CSV text from this input stream */
4054 char *z
; /* Accumulated text for a field */
4055 int n
; /* Number of bytes in z */
4056 int nAlloc
; /* Space allocated for z[] */
4057 int nLine
; /* Current line number */
4058 int bNotFirst
; /* True if one or more bytes already read */
4059 int cTerm
; /* Character that terminated the most recent field */
4060 int cColSep
; /* The column separator character. (Usually ",") */
4061 int cRowSep
; /* The row separator character. (Usually "\n") */
4064 /* Append a single byte to z[] */
4065 static void import_append_char(ImportCtx
*p
, int c
){
4066 if( p
->n
+1>=p
->nAlloc
){
4067 p
->nAlloc
+= p
->nAlloc
+ 100;
4068 p
->z
= sqlite3_realloc64(p
->z
, p
->nAlloc
);
4069 if( p
->z
==0 ) shell_out_of_memory();
4071 p
->z
[p
->n
++] = (char)c
;
4074 /* Read a single field of CSV text. Compatible with rfc4180 and extended
4075 ** with the option of having a separator other than ",".
4077 ** + Input comes from p->in.
4078 ** + Store results in p->z of length p->n. Space to hold p->z comes
4079 ** from sqlite3_malloc64().
4080 ** + Use p->cSep as the column separator. The default is ",".
4081 ** + Use p->rSep as the row separator. The default is "\n".
4082 ** + Keep track of the line number in p->nLine.
4083 ** + Store the character that terminates the field in p->cTerm. Store
4084 ** EOF on end-of-file.
4085 ** + Report syntax errors on stderr
4087 static char *SQLITE_CDECL
csv_read_one_field(ImportCtx
*p
){
4089 int cSep
= p
->cColSep
;
4090 int rSep
= p
->cRowSep
;
4093 if( c
==EOF
|| seenInterrupt
){
4099 int startLine
= p
->nLine
;
4104 if( c
==rSep
) p
->nLine
++;
4111 if( (c
==cSep
&& pc
==cQuote
)
4112 || (c
==rSep
&& pc
==cQuote
)
4113 || (c
==rSep
&& pc
=='\r' && ppc
==cQuote
)
4114 || (c
==EOF
&& pc
==cQuote
)
4116 do{ p
->n
--; }while( p
->z
[p
->n
]!=cQuote
);
4120 if( pc
==cQuote
&& c
!='\r' ){
4121 utf8_printf(stderr
, "%s:%d: unescaped %c character\n",
4122 p
->zFile
, p
->nLine
, cQuote
);
4125 utf8_printf(stderr
, "%s:%d: unterminated %c-quoted field\n",
4126 p
->zFile
, startLine
, cQuote
);
4130 import_append_char(p
, c
);
4135 /* If this is the first field being parsed and it begins with the
4136 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4137 if( (c
&0xff)==0xef && p
->bNotFirst
==0 ){
4138 import_append_char(p
, c
);
4140 if( (c
&0xff)==0xbb ){
4141 import_append_char(p
, c
);
4143 if( (c
&0xff)==0xbf ){
4146 return csv_read_one_field(p
);
4150 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
4151 import_append_char(p
, c
);
4156 if( p
->n
>0 && p
->z
[p
->n
-1]=='\r' ) p
->n
--;
4160 if( p
->z
) p
->z
[p
->n
] = 0;
4165 /* Read a single field of ASCII delimited text.
4167 ** + Input comes from p->in.
4168 ** + Store results in p->z of length p->n. Space to hold p->z comes
4169 ** from sqlite3_malloc64().
4170 ** + Use p->cSep as the column separator. The default is "\x1F".
4171 ** + Use p->rSep as the row separator. The default is "\x1E".
4172 ** + Keep track of the row number in p->nLine.
4173 ** + Store the character that terminates the field in p->cTerm. Store
4174 ** EOF on end-of-file.
4175 ** + Report syntax errors on stderr
4177 static char *SQLITE_CDECL
ascii_read_one_field(ImportCtx
*p
){
4179 int cSep
= p
->cColSep
;
4180 int rSep
= p
->cRowSep
;
4183 if( c
==EOF
|| seenInterrupt
){
4187 while( c
!=EOF
&& c
!=cSep
&& c
!=rSep
){
4188 import_append_char(p
, c
);
4195 if( p
->z
) p
->z
[p
->n
] = 0;
4200 ** Try to transfer data for table zTable. If an error is seen while
4201 ** moving forward, try to go backwards. The backwards movement won't
4202 ** work for WITHOUT ROWID tables.
4204 static void tryToCloneData(
4209 sqlite3_stmt
*pQuery
= 0;
4210 sqlite3_stmt
*pInsert
= 0;
4215 int nTable
= strlen30(zTable
);
4218 const int spinRate
= 10000;
4220 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\"", zTable
);
4221 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4223 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
4224 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4228 n
= sqlite3_column_count(pQuery
);
4229 zInsert
= sqlite3_malloc64(200 + nTable
+ n
*3);
4230 if( zInsert
==0 ) shell_out_of_memory();
4231 sqlite3_snprintf(200+nTable
,zInsert
,
4232 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable
);
4233 i
= strlen30(zInsert
);
4235 memcpy(zInsert
+i
, ",?", 2);
4238 memcpy(zInsert
+i
, ");", 3);
4239 rc
= sqlite3_prepare_v2(newDb
, zInsert
, -1, &pInsert
, 0);
4241 utf8_printf(stderr
, "Error %d: %s on [%s]\n",
4242 sqlite3_extended_errcode(newDb
), sqlite3_errmsg(newDb
),
4247 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4249 switch( sqlite3_column_type(pQuery
, i
) ){
4251 sqlite3_bind_null(pInsert
, i
+1);
4254 case SQLITE_INTEGER
: {
4255 sqlite3_bind_int64(pInsert
, i
+1, sqlite3_column_int64(pQuery
,i
));
4258 case SQLITE_FLOAT
: {
4259 sqlite3_bind_double(pInsert
, i
+1, sqlite3_column_double(pQuery
,i
));
4263 sqlite3_bind_text(pInsert
, i
+1,
4264 (const char*)sqlite3_column_text(pQuery
,i
),
4269 sqlite3_bind_blob(pInsert
, i
+1, sqlite3_column_blob(pQuery
,i
),
4270 sqlite3_column_bytes(pQuery
,i
),
4276 rc
= sqlite3_step(pInsert
);
4277 if( rc
!=SQLITE_OK
&& rc
!=SQLITE_ROW
&& rc
!=SQLITE_DONE
){
4278 utf8_printf(stderr
, "Error %d: %s\n", sqlite3_extended_errcode(newDb
),
4279 sqlite3_errmsg(newDb
));
4281 sqlite3_reset(pInsert
);
4283 if( (cnt
%spinRate
)==0 ){
4284 printf("%c\b", "|/-\\"[(cnt
/spinRate
)%4]);
4288 if( rc
==SQLITE_DONE
) break;
4289 sqlite3_finalize(pQuery
);
4290 sqlite3_free(zQuery
);
4291 zQuery
= sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4293 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4295 utf8_printf(stderr
, "Warning: cannot step \"%s\" backwards", zTable
);
4298 } /* End for(k=0...) */
4301 sqlite3_finalize(pQuery
);
4302 sqlite3_finalize(pInsert
);
4303 sqlite3_free(zQuery
);
4304 sqlite3_free(zInsert
);
4309 ** Try to transfer all rows of the schema that match zWhere. For
4310 ** each row, invoke xForEach() on the object defined by that row.
4311 ** If an error is encountered while moving forward through the
4312 ** sqlite_master table, try again moving backwards.
4314 static void tryToCloneSchema(
4318 void (*xForEach
)(ShellState
*,sqlite3
*,const char*)
4320 sqlite3_stmt
*pQuery
= 0;
4323 const unsigned char *zName
;
4324 const unsigned char *zSql
;
4327 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4328 " WHERE %s", zWhere
);
4329 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4331 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4332 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4334 goto end_schema_xfer
;
4336 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4337 zName
= sqlite3_column_text(pQuery
, 0);
4338 zSql
= sqlite3_column_text(pQuery
, 1);
4339 printf("%s... ", zName
); fflush(stdout
);
4340 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4342 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4343 sqlite3_free(zErrMsg
);
4347 xForEach(p
, newDb
, (const char*)zName
);
4351 if( rc
!=SQLITE_DONE
){
4352 sqlite3_finalize(pQuery
);
4353 sqlite3_free(zQuery
);
4354 zQuery
= sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4355 " WHERE %s ORDER BY rowid DESC", zWhere
);
4356 rc
= sqlite3_prepare_v2(p
->db
, zQuery
, -1, &pQuery
, 0);
4358 utf8_printf(stderr
, "Error: (%d) %s on [%s]\n",
4359 sqlite3_extended_errcode(p
->db
), sqlite3_errmsg(p
->db
),
4361 goto end_schema_xfer
;
4363 while( (rc
= sqlite3_step(pQuery
))==SQLITE_ROW
){
4364 zName
= sqlite3_column_text(pQuery
, 0);
4365 zSql
= sqlite3_column_text(pQuery
, 1);
4366 printf("%s... ", zName
); fflush(stdout
);
4367 sqlite3_exec(newDb
, (const char*)zSql
, 0, 0, &zErrMsg
);
4369 utf8_printf(stderr
, "Error: %s\nSQL: [%s]\n", zErrMsg
, zSql
);
4370 sqlite3_free(zErrMsg
);
4374 xForEach(p
, newDb
, (const char*)zName
);
4380 sqlite3_finalize(pQuery
);
4381 sqlite3_free(zQuery
);
4385 ** Open a new database file named "zNewDb". Try to recover as much information
4386 ** as possible out of the main database (which might be corrupt) and write it
4389 static void tryToClone(ShellState
*p
, const char *zNewDb
){
4392 if( access(zNewDb
,0)==0 ){
4393 utf8_printf(stderr
, "File \"%s\" already exists.\n", zNewDb
);
4396 rc
= sqlite3_open(zNewDb
, &newDb
);
4398 utf8_printf(stderr
, "Cannot create output database: %s\n",
4399 sqlite3_errmsg(newDb
));
4401 sqlite3_exec(p
->db
, "PRAGMA writable_schema=ON;", 0, 0, 0);
4402 sqlite3_exec(newDb
, "BEGIN EXCLUSIVE;", 0, 0, 0);
4403 tryToCloneSchema(p
, newDb
, "type='table'", tryToCloneData
);
4404 tryToCloneSchema(p
, newDb
, "type!='table'", 0);
4405 sqlite3_exec(newDb
, "COMMIT;", 0, 0, 0);
4406 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4412 ** Change the output file back to stdout.
4414 ** If the p->doXdgOpen flag is set, that means the output was being
4415 ** redirected to a temporary file named by p->zTempFile. In that case,
4416 ** launch start/open/xdg-open on that temporary file.
4418 static void output_reset(ShellState
*p
){
4419 if( p
->outfile
[0]=='|' ){
4420 #ifndef SQLITE_OMIT_POPEN
4424 output_file_close(p
->out
);
4425 #ifndef SQLITE_NOHAVE_SYSTEM
4427 const char *zXdgOpenCmd
=
4430 #elif defined(__APPLE__)
4436 zCmd
= sqlite3_mprintf("%s %s", zXdgOpenCmd
, p
->zTempFile
);
4438 utf8_printf(stderr
, "Failed: [%s]\n", zCmd
);
4444 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
4451 ** Run an SQL command and return the single integer result.
4453 static int db_int(ShellState
*p
, const char *zSql
){
4454 sqlite3_stmt
*pStmt
;
4456 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
4457 if( pStmt
&& sqlite3_step(pStmt
)==SQLITE_ROW
){
4458 res
= sqlite3_column_int(pStmt
,0);
4460 sqlite3_finalize(pStmt
);
4465 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
4467 static unsigned int get2byteInt(unsigned char *a
){
4468 return (a
[0]<<8) + a
[1];
4470 static unsigned int get4byteInt(unsigned char *a
){
4471 return (a
[0]<<24) + (a
[1]<<16) + (a
[2]<<8) + a
[3];
4475 ** Implementation of the ".info" command.
4477 ** Return 1 on error, 2 to exit, and 0 otherwise.
4479 static int shell_dbinfo_command(ShellState
*p
, int nArg
, char **azArg
){
4480 static const struct { const char *zName
; int ofst
; } aField
[] = {
4481 { "file change counter:", 24 },
4482 { "database page count:", 28 },
4483 { "freelist page count:", 36 },
4484 { "schema cookie:", 40 },
4485 { "schema format:", 44 },
4486 { "default cache size:", 48 },
4487 { "autovacuum top root:", 52 },
4488 { "incremental vacuum:", 64 },
4489 { "text encoding:", 56 },
4490 { "user version:", 60 },
4491 { "application id:", 68 },
4492 { "software version:", 96 },
4494 static const struct { const char *zName
; const char *zSql
; } aQuery
[] = {
4495 { "number of tables:",
4496 "SELECT count(*) FROM %s WHERE type='table'" },
4497 { "number of indexes:",
4498 "SELECT count(*) FROM %s WHERE type='index'" },
4499 { "number of triggers:",
4500 "SELECT count(*) FROM %s WHERE type='trigger'" },
4501 { "number of views:",
4502 "SELECT count(*) FROM %s WHERE type='view'" },
4504 "SELECT total(length(sql)) FROM %s" },
4507 unsigned iDataVersion
;
4509 char *zDb
= nArg
>=2 ? azArg
[1] : "main";
4510 sqlite3_stmt
*pStmt
= 0;
4511 unsigned char aHdr
[100];
4513 if( p
->db
==0 ) return 1;
4514 sqlite3_prepare_v2(p
->db
,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4516 sqlite3_bind_text(pStmt
, 1, zDb
, -1, SQLITE_STATIC
);
4517 if( sqlite3_step(pStmt
)==SQLITE_ROW
4518 && sqlite3_column_bytes(pStmt
,0)>100
4520 memcpy(aHdr
, sqlite3_column_blob(pStmt
,0), 100);
4521 sqlite3_finalize(pStmt
);
4523 raw_printf(stderr
, "unable to read database header\n");
4524 sqlite3_finalize(pStmt
);
4527 i
= get2byteInt(aHdr
+16);
4528 if( i
==1 ) i
= 65536;
4529 utf8_printf(p
->out
, "%-20s %d\n", "database page size:", i
);
4530 utf8_printf(p
->out
, "%-20s %d\n", "write format:", aHdr
[18]);
4531 utf8_printf(p
->out
, "%-20s %d\n", "read format:", aHdr
[19]);
4532 utf8_printf(p
->out
, "%-20s %d\n", "reserved bytes:", aHdr
[20]);
4533 for(i
=0; i
<ArraySize(aField
); i
++){
4534 int ofst
= aField
[i
].ofst
;
4535 unsigned int val
= get4byteInt(aHdr
+ ofst
);
4536 utf8_printf(p
->out
, "%-20s %u", aField
[i
].zName
, val
);
4539 if( val
==1 ) raw_printf(p
->out
, " (utf8)");
4540 if( val
==2 ) raw_printf(p
->out
, " (utf16le)");
4541 if( val
==3 ) raw_printf(p
->out
, " (utf16be)");
4544 raw_printf(p
->out
, "\n");
4547 zSchemaTab
= sqlite3_mprintf("main.sqlite_master");
4548 }else if( strcmp(zDb
,"temp")==0 ){
4549 zSchemaTab
= sqlite3_mprintf("%s", "sqlite_temp_master");
4551 zSchemaTab
= sqlite3_mprintf("\"%w\".sqlite_master", zDb
);
4553 for(i
=0; i
<ArraySize(aQuery
); i
++){
4554 char *zSql
= sqlite3_mprintf(aQuery
[i
].zSql
, zSchemaTab
);
4555 int val
= db_int(p
, zSql
);
4557 utf8_printf(p
->out
, "%-20s %d\n", aQuery
[i
].zName
, val
);
4559 sqlite3_free(zSchemaTab
);
4560 sqlite3_file_control(p
->db
, zDb
, SQLITE_FCNTL_DATA_VERSION
, &iDataVersion
);
4561 utf8_printf(p
->out
, "%-20s %u\n", "data version", iDataVersion
);
4566 ** Print the current sqlite3_errmsg() value to stderr and return 1.
4568 static int shellDatabaseError(sqlite3
*db
){
4569 const char *zErr
= sqlite3_errmsg(db
);
4570 utf8_printf(stderr
, "Error: %s\n", zErr
);
4575 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4576 ** if they match and FALSE (0) if they do not match.
4580 ** '*' Matches any sequence of zero or more characters.
4582 ** '?' Matches exactly one character.
4584 ** [...] Matches one character from the enclosed list of
4587 ** [^...] Matches one character not in the enclosed list.
4589 ** '#' Matches any sequence of one or more digits with an
4590 ** optional + or - sign in front
4592 ** ' ' Any span of whitespace matches any other span of
4595 ** Extra whitespace at the end of z[] is ignored.
4597 static int testcase_glob(const char *zGlob
, const char *z
){
4602 while( (c
= (*(zGlob
++)))!=0 ){
4604 if( !IsSpace(*z
) ) return 0;
4605 while( IsSpace(*zGlob
) ) zGlob
++;
4606 while( IsSpace(*z
) ) z
++;
4608 while( (c
=(*(zGlob
++))) == '*' || c
=='?' ){
4609 if( c
=='?' && (*(z
++))==0 ) return 0;
4614 while( *z
&& testcase_glob(zGlob
-1,z
)==0 ){
4619 while( (c2
= (*(z
++)))!=0 ){
4622 if( c2
==0 ) return 0;
4624 if( testcase_glob(zGlob
,z
) ) return 1;
4628 if( (*(z
++))==0 ) return 0;
4634 if( c
==0 ) return 0;
4641 if( c
==']' ) seen
= 1;
4644 while( c2
&& c2
!=']' ){
4645 if( c2
=='-' && zGlob
[0]!=']' && zGlob
[0]!=0 && prior_c
>0 ){
4647 if( c
>=prior_c
&& c
<=c2
) seen
= 1;
4657 if( c2
==0 || (seen
^ invert
)==0 ) return 0;
4659 if( (z
[0]=='-' || z
[0]=='+') && IsDigit(z
[1]) ) z
++;
4660 if( !IsDigit(z
[0]) ) return 0;
4662 while( IsDigit(z
[0]) ){ z
++; }
4664 if( c
!=(*(z
++)) ) return 0;
4667 while( IsSpace(*z
) ){ z
++; }
4673 ** Compare the string as a command-line option with either one or two
4674 ** initial "-" characters.
4676 static int optionMatch(const char *zStr
, const char *zOpt
){
4677 if( zStr
[0]!='-' ) return 0;
4679 if( zStr
[0]=='-' ) zStr
++;
4680 return strcmp(zStr
, zOpt
)==0;
4686 int shellDeleteFile(const char *zFilename
){
4689 wchar_t *z
= sqlite3_win32_utf8_to_unicode(zFilename
);
4693 rc
= unlink(zFilename
);
4699 ** Try to delete the temporary file (if there is one) and free the
4700 ** memory used to hold the name of the temp file.
4702 static void clearTempFile(ShellState
*p
){
4703 if( p
->zTempFile
==0 ) return;
4704 if( p
->doXdgOpen
) return;
4705 if( shellDeleteFile(p
->zTempFile
) ) return;
4706 sqlite3_free(p
->zTempFile
);
4711 ** Create a new temp file name with the given suffix.
4713 static void newTempFile(ShellState
*p
, const char *zSuffix
){
4715 sqlite3_free(p
->zTempFile
);
4718 sqlite3_file_control(p
->db
, 0, SQLITE_FCNTL_TEMPFILENAME
, &p
->zTempFile
);
4720 if( p
->zTempFile
==0 ){
4722 sqlite3_randomness(sizeof(r
), &r
);
4723 p
->zTempFile
= sqlite3_mprintf("temp%llx.%s", r
, zSuffix
);
4725 p
->zTempFile
= sqlite3_mprintf("%z.%s", p
->zTempFile
, zSuffix
);
4727 if( p
->zTempFile
==0 ){
4728 raw_printf(stderr
, "out of memory\n");
4735 ** The implementation of SQL scalar function fkey_collate_clause(), used
4736 ** by the ".lint fkey-indexes" command. This scalar function is always
4737 ** called with four arguments - the parent table name, the parent column name,
4738 ** the child table name and the child column name.
4740 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4742 ** If either of the named tables or columns do not exist, this function
4743 ** returns an empty string. An empty string is also returned if both tables
4744 ** and columns exist but have the same default collation sequence. Or,
4745 ** if both exist but the default collation sequences are different, this
4746 ** function returns the string " COLLATE <parent-collation>", where
4747 ** <parent-collation> is the default collation sequence of the parent column.
4749 static void shellFkeyCollateClause(
4750 sqlite3_context
*pCtx
,
4752 sqlite3_value
**apVal
4754 sqlite3
*db
= sqlite3_context_db_handle(pCtx
);
4755 const char *zParent
;
4756 const char *zParentCol
;
4757 const char *zParentSeq
;
4759 const char *zChildCol
;
4760 const char *zChildSeq
= 0; /* Initialize to avoid false-positive warning */
4764 zParent
= (const char*)sqlite3_value_text(apVal
[0]);
4765 zParentCol
= (const char*)sqlite3_value_text(apVal
[1]);
4766 zChild
= (const char*)sqlite3_value_text(apVal
[2]);
4767 zChildCol
= (const char*)sqlite3_value_text(apVal
[3]);
4769 sqlite3_result_text(pCtx
, "", -1, SQLITE_STATIC
);
4770 rc
= sqlite3_table_column_metadata(
4771 db
, "main", zParent
, zParentCol
, 0, &zParentSeq
, 0, 0, 0
4773 if( rc
==SQLITE_OK
){
4774 rc
= sqlite3_table_column_metadata(
4775 db
, "main", zChild
, zChildCol
, 0, &zChildSeq
, 0, 0, 0
4779 if( rc
==SQLITE_OK
&& sqlite3_stricmp(zParentSeq
, zChildSeq
) ){
4780 char *z
= sqlite3_mprintf(" COLLATE %s", zParentSeq
);
4781 sqlite3_result_text(pCtx
, z
, -1, SQLITE_TRANSIENT
);
4788 ** The implementation of dot-command ".lint fkey-indexes".
4790 static int lintFkeyIndexes(
4791 ShellState
*pState
, /* Current shell tool state */
4792 char **azArg
, /* Array of arguments passed to dot command */
4793 int nArg
/* Number of entries in azArg[] */
4795 sqlite3
*db
= pState
->db
; /* Database handle to query "main" db of */
4796 FILE *out
= pState
->out
; /* Stream to write non-error output to */
4797 int bVerbose
= 0; /* If -verbose is present */
4798 int bGroupByParent
= 0; /* If -groupbyparent is present */
4799 int i
; /* To iterate through azArg[] */
4800 const char *zIndent
= ""; /* How much to indent CREATE INDEX by */
4801 int rc
; /* Return code */
4802 sqlite3_stmt
*pSql
= 0; /* Compiled version of SQL statement below */
4805 ** This SELECT statement returns one row for each foreign key constraint
4806 ** in the schema of the main database. The column values are:
4808 ** 0. The text of an SQL statement similar to:
4810 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
4812 ** This SELECT is similar to the one that the foreign keys implementation
4813 ** needs to run internally on child tables. If there is an index that can
4814 ** be used to optimize this query, then it can also be used by the FK
4815 ** implementation to optimize DELETE or UPDATE statements on the parent
4818 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4819 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4820 ** contains an index that can be used to optimize the query.
4822 ** 2. Human readable text that describes the child table and columns. e.g.
4824 ** "child_table(child_key1, child_key2)"
4826 ** 3. Human readable text that describes the parent table and columns. e.g.
4828 ** "parent_table(parent_key1, parent_key2)"
4830 ** 4. A full CREATE INDEX statement for an index that could be used to
4831 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4833 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4835 ** 5. The name of the parent table.
4837 ** These six values are used by the C logic below to generate the report.
4841 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
4842 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4843 " || fkey_collate_clause("
4844 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
4846 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
4847 " || group_concat('*=?', ' AND ') || ')'"
4849 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
4851 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
4853 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4854 " || ' ON ' || quote(s.name) || '('"
4855 " || group_concat(quote(f.[from]) ||"
4856 " fkey_collate_clause("
4857 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
4861 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4862 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
4863 "GROUP BY s.name, f.id "
4864 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
4866 const char *zGlobIPK
= "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
4868 for(i
=2; i
<nArg
; i
++){
4869 int n
= strlen30(azArg
[i
]);
4870 if( n
>1 && sqlite3_strnicmp("-verbose", azArg
[i
], n
)==0 ){
4873 else if( n
>1 && sqlite3_strnicmp("-groupbyparent", azArg
[i
], n
)==0 ){
4878 raw_printf(stderr
, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4881 return SQLITE_ERROR
;
4885 /* Register the fkey_collate_clause() SQL function */
4886 rc
= sqlite3_create_function(db
, "fkey_collate_clause", 4, SQLITE_UTF8
,
4887 0, shellFkeyCollateClause
, 0, 0
4891 if( rc
==SQLITE_OK
){
4892 rc
= sqlite3_prepare_v2(db
, zSql
, -1, &pSql
, 0);
4894 if( rc
==SQLITE_OK
){
4895 sqlite3_bind_int(pSql
, 1, bGroupByParent
);
4898 if( rc
==SQLITE_OK
){
4901 while( SQLITE_ROW
==sqlite3_step(pSql
) ){
4903 sqlite3_stmt
*pExplain
= 0;
4904 const char *zEQP
= (const char*)sqlite3_column_text(pSql
, 0);
4905 const char *zGlob
= (const char*)sqlite3_column_text(pSql
, 1);
4906 const char *zFrom
= (const char*)sqlite3_column_text(pSql
, 2);
4907 const char *zTarget
= (const char*)sqlite3_column_text(pSql
, 3);
4908 const char *zCI
= (const char*)sqlite3_column_text(pSql
, 4);
4909 const char *zParent
= (const char*)sqlite3_column_text(pSql
, 5);
4911 rc
= sqlite3_prepare_v2(db
, zEQP
, -1, &pExplain
, 0);
4912 if( rc
!=SQLITE_OK
) break;
4913 if( SQLITE_ROW
==sqlite3_step(pExplain
) ){
4914 const char *zPlan
= (const char*)sqlite3_column_text(pExplain
, 3);
4916 0==sqlite3_strglob(zGlob
, zPlan
)
4917 || 0==sqlite3_strglob(zGlobIPK
, zPlan
)
4920 rc
= sqlite3_finalize(pExplain
);
4921 if( rc
!=SQLITE_OK
) break;
4924 raw_printf(stderr
, "Error: internal error");
4928 && (bVerbose
|| res
==0)
4929 && (zPrev
==0 || sqlite3_stricmp(zParent
, zPrev
))
4931 raw_printf(out
, "-- Parent table %s\n", zParent
);
4932 sqlite3_free(zPrev
);
4933 zPrev
= sqlite3_mprintf("%s", zParent
);
4937 raw_printf(out
, "%s%s --> %s\n", zIndent
, zCI
, zTarget
);
4938 }else if( bVerbose
){
4939 raw_printf(out
, "%s/* no extra indexes required for %s -> %s */\n",
4940 zIndent
, zFrom
, zTarget
4945 sqlite3_free(zPrev
);
4947 if( rc
!=SQLITE_OK
){
4948 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4951 rc2
= sqlite3_finalize(pSql
);
4952 if( rc
==SQLITE_OK
&& rc2
!=SQLITE_OK
){
4954 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4957 raw_printf(stderr
, "%s\n", sqlite3_errmsg(db
));
4964 ** Implementation of ".lint" dot command.
4966 static int lintDotCommand(
4967 ShellState
*pState
, /* Current shell tool state */
4968 char **azArg
, /* Array of arguments passed to dot command */
4969 int nArg
/* Number of entries in azArg[] */
4972 n
= (nArg
>=2 ? strlen30(azArg
[1]) : 0);
4973 if( n
<1 || sqlite3_strnicmp(azArg
[1], "fkey-indexes", n
) ) goto usage
;
4974 return lintFkeyIndexes(pState
, azArg
, nArg
);
4977 raw_printf(stderr
, "Usage %s sub-command ?switches...?\n", azArg
[0]);
4978 raw_printf(stderr
, "Where sub-commands are:\n");
4979 raw_printf(stderr
, " fkey-indexes\n");
4980 return SQLITE_ERROR
;
4983 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
4984 /*********************************************************************************
4985 ** The ".archive" or ".ar" command.
4987 static void shellPrepare(
4991 sqlite3_stmt
**ppStmt
4994 if( *pRc
==SQLITE_OK
){
4995 int rc
= sqlite3_prepare_v2(db
, zSql
, -1, ppStmt
, 0);
4996 if( rc
!=SQLITE_OK
){
4997 raw_printf(stderr
, "sql error: %s (%d)\n",
4998 sqlite3_errmsg(db
), sqlite3_errcode(db
)
5005 static void shellPreparePrintf(
5008 sqlite3_stmt
**ppStmt
,
5013 if( *pRc
==SQLITE_OK
){
5017 z
= sqlite3_vmprintf(zFmt
, ap
);
5020 *pRc
= SQLITE_NOMEM
;
5022 shellPrepare(db
, pRc
, z
, ppStmt
);
5028 static void shellFinalize(
5033 sqlite3
*db
= sqlite3_db_handle(pStmt
);
5034 int rc
= sqlite3_finalize(pStmt
);
5035 if( *pRc
==SQLITE_OK
){
5036 if( rc
!=SQLITE_OK
){
5037 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
5044 static void shellReset(
5048 int rc
= sqlite3_reset(pStmt
);
5049 if( *pRc
==SQLITE_OK
){
5050 if( rc
!=SQLITE_OK
){
5051 sqlite3
*db
= sqlite3_db_handle(pStmt
);
5052 raw_printf(stderr
, "SQL error: %s\n", sqlite3_errmsg(db
));
5058 ** Structure representing a single ".ar" command.
5060 typedef struct ArCommand ArCommand
;
5062 u8 eCmd
; /* An AR_CMD_* value */
5063 u8 bVerbose
; /* True if --verbose */
5064 u8 bZip
; /* True if the archive is a ZIP */
5065 u8 bDryRun
; /* True if --dry-run */
5066 u8 bAppend
; /* True if --append */
5067 u8 fromCmdLine
; /* Run from -A instead of .archive */
5068 int nArg
; /* Number of command arguments */
5069 char *zSrcTable
; /* "sqlar", "zipfile($file)" or "zip" */
5070 const char *zFile
; /* --file argument, or NULL */
5071 const char *zDir
; /* --directory argument, or NULL */
5072 char **azArg
; /* Array of command arguments */
5073 ShellState
*p
; /* Shell state */
5074 sqlite3
*db
; /* Database containing the archive */
5078 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
5080 static int arUsage(FILE *f
){
5081 showHelp(f
,"archive");
5082 return SQLITE_ERROR
;
5086 ** Print an error message for the .ar command to stderr and return
5089 static int arErrorMsg(ArCommand
*pAr
, const char *zFmt
, ...){
5093 z
= sqlite3_vmprintf(zFmt
, ap
);
5095 utf8_printf(stderr
, "Error: %s\n", z
);
5096 if( pAr
->fromCmdLine
){
5097 utf8_printf(stderr
, "Use \"-A\" for more help\n");
5099 utf8_printf(stderr
, "Use \".archive --help\" for more help\n");
5102 return SQLITE_ERROR
;
5106 ** Values for ArCommand.eCmd.
5108 #define AR_CMD_CREATE 1
5109 #define AR_CMD_EXTRACT 2
5110 #define AR_CMD_LIST 3
5111 #define AR_CMD_UPDATE 4
5112 #define AR_CMD_HELP 5
5115 ** Other (non-command) switches.
5117 #define AR_SWITCH_VERBOSE 6
5118 #define AR_SWITCH_FILE 7
5119 #define AR_SWITCH_DIRECTORY 8
5120 #define AR_SWITCH_APPEND 9
5121 #define AR_SWITCH_DRYRUN 10
5123 static int arProcessSwitch(ArCommand
*pAr
, int eSwitch
, const char *zArg
){
5126 case AR_CMD_EXTRACT
:
5131 return arErrorMsg(pAr
, "multiple command options");
5133 pAr
->eCmd
= eSwitch
;
5136 case AR_SWITCH_DRYRUN
:
5139 case AR_SWITCH_VERBOSE
:
5142 case AR_SWITCH_APPEND
:
5144 /* Fall thru into --file */
5145 case AR_SWITCH_FILE
:
5148 case AR_SWITCH_DIRECTORY
:
5157 ** Parse the command line for an ".ar" command. The results are written into
5158 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
5159 ** successfully, otherwise an error message is written to stderr and
5160 ** SQLITE_ERROR returned.
5162 static int arParseCommand(
5163 char **azArg
, /* Array of arguments passed to dot command */
5164 int nArg
, /* Number of entries in azArg[] */
5165 ArCommand
*pAr
/* Populate this object */
5173 { "create", 'c', AR_CMD_CREATE
, 0 },
5174 { "extract", 'x', AR_CMD_EXTRACT
, 0 },
5175 { "list", 't', AR_CMD_LIST
, 0 },
5176 { "update", 'u', AR_CMD_UPDATE
, 0 },
5177 { "help", 'h', AR_CMD_HELP
, 0 },
5178 { "verbose", 'v', AR_SWITCH_VERBOSE
, 0 },
5179 { "file", 'f', AR_SWITCH_FILE
, 1 },
5180 { "append", 'a', AR_SWITCH_APPEND
, 1 },
5181 { "directory", 'C', AR_SWITCH_DIRECTORY
, 1 },
5182 { "dryrun", 'n', AR_SWITCH_DRYRUN
, 0 },
5184 int nSwitch
= sizeof(aSwitch
) / sizeof(struct ArSwitch
);
5185 struct ArSwitch
*pEnd
= &aSwitch
[nSwitch
];
5188 utf8_printf(stderr
, "Wrong number of arguments. Usage:\n");
5189 return arUsage(stderr
);
5193 /* Traditional style [tar] invocation */
5196 for(i
=0; z
[i
]; i
++){
5197 const char *zArg
= 0;
5198 struct ArSwitch
*pOpt
;
5199 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5200 if( z
[i
]==pOpt
->cShort
) break;
5203 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
5207 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
5209 zArg
= azArg
[iArg
++];
5211 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5213 pAr
->nArg
= nArg
-iArg
;
5215 pAr
->azArg
= &azArg
[iArg
];
5218 /* Non-traditional invocation */
5220 for(iArg
=1; iArg
<nArg
; iArg
++){
5224 /* All remaining command line words are command arguments. */
5225 pAr
->azArg
= &azArg
[iArg
];
5226 pAr
->nArg
= nArg
-iArg
;
5233 /* One or more short options */
5235 const char *zArg
= 0;
5236 struct ArSwitch
*pOpt
;
5237 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5238 if( z
[i
]==pOpt
->cShort
) break;
5241 return arErrorMsg(pAr
, "unrecognized option: %c", z
[i
]);
5248 if( iArg
>=(nArg
-1) ){
5249 return arErrorMsg(pAr
, "option requires an argument: %c",z
[i
]);
5251 zArg
= azArg
[++iArg
];
5254 if( arProcessSwitch(pAr
, pOpt
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5256 }else if( z
[2]=='\0' ){
5257 /* A -- option, indicating that all remaining command line words
5258 ** are command arguments. */
5259 pAr
->azArg
= &azArg
[iArg
+1];
5260 pAr
->nArg
= nArg
-iArg
-1;
5264 const char *zArg
= 0; /* Argument for option, if any */
5265 struct ArSwitch
*pMatch
= 0; /* Matching option */
5266 struct ArSwitch
*pOpt
; /* Iterator */
5267 for(pOpt
=&aSwitch
[0]; pOpt
<pEnd
; pOpt
++){
5268 const char *zLong
= pOpt
->zLong
;
5269 if( (n
-2)<=strlen30(zLong
) && 0==memcmp(&z
[2], zLong
, n
-2) ){
5271 return arErrorMsg(pAr
, "ambiguous option: %s",z
);
5279 return arErrorMsg(pAr
, "unrecognized option: %s", z
);
5282 if( iArg
>=(nArg
-1) ){
5283 return arErrorMsg(pAr
, "option requires an argument: %s", z
);
5285 zArg
= azArg
[++iArg
];
5287 if( arProcessSwitch(pAr
, pMatch
->eSwitch
, zArg
) ) return SQLITE_ERROR
;
5297 ** This function assumes that all arguments within the ArCommand.azArg[]
5298 ** array refer to archive members, as for the --extract or --list commands.
5299 ** It checks that each of them are present. If any specified file is not
5300 ** present in the archive, an error is printed to stderr and an error
5301 ** code returned. Otherwise, if all specified arguments are present in
5302 ** the archive, SQLITE_OK is returned.
5304 ** This function strips any trailing '/' characters from each argument.
5305 ** This is consistent with the way the [tar] command seems to work on
5308 static int arCheckEntries(ArCommand
*pAr
){
5312 sqlite3_stmt
*pTest
= 0;
5314 shellPreparePrintf(pAr
->db
, &rc
, &pTest
,
5315 "SELECT name FROM %s WHERE name=$name",
5318 j
= sqlite3_bind_parameter_index(pTest
, "$name");
5319 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5320 char *z
= pAr
->azArg
[i
];
5321 int n
= strlen30(z
);
5323 while( n
>0 && z
[n
-1]=='/' ) n
--;
5325 sqlite3_bind_text(pTest
, j
, z
, -1, SQLITE_STATIC
);
5326 if( SQLITE_ROW
==sqlite3_step(pTest
) ){
5329 shellReset(&rc
, pTest
);
5330 if( rc
==SQLITE_OK
&& bOk
==0 ){
5331 utf8_printf(stderr
, "not found in archive: %s\n", z
);
5335 shellFinalize(&rc
, pTest
);
5341 ** Format a WHERE clause that can be used against the "sqlar" table to
5342 ** identify all archive members that match the command arguments held
5343 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
5344 ** The caller is responsible for eventually calling sqlite3_free() on
5345 ** any non-NULL (*pzWhere) value.
5347 static void arWhereClause(
5350 char **pzWhere
/* OUT: New WHERE clause */
5353 if( *pRc
==SQLITE_OK
){
5355 zWhere
= sqlite3_mprintf("1");
5358 const char *zSep
= "";
5359 for(i
=0; i
<pAr
->nArg
; i
++){
5360 const char *z
= pAr
->azArg
[i
];
5361 zWhere
= sqlite3_mprintf(
5362 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
5363 zWhere
, zSep
, z
, strlen30(z
)+1, z
5366 *pRc
= SQLITE_NOMEM
;
5377 ** Implementation of .ar "lisT" command.
5379 static int arListCommand(ArCommand
*pAr
){
5380 const char *zSql
= "SELECT %s FROM %s WHERE %s";
5381 const char *azCols
[] = {
5383 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
5387 sqlite3_stmt
*pSql
= 0;
5390 rc
= arCheckEntries(pAr
);
5391 arWhereClause(&rc
, pAr
, &zWhere
);
5393 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql
, azCols
[pAr
->bVerbose
],
5394 pAr
->zSrcTable
, zWhere
);
5396 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5398 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5399 if( pAr
->bVerbose
){
5400 utf8_printf(pAr
->p
->out
, "%s % 10d %s %s\n",
5401 sqlite3_column_text(pSql
, 0),
5402 sqlite3_column_int(pSql
, 1),
5403 sqlite3_column_text(pSql
, 2),
5404 sqlite3_column_text(pSql
, 3)
5407 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5411 shellFinalize(&rc
, pSql
);
5412 sqlite3_free(zWhere
);
5418 ** Implementation of .ar "eXtract" command.
5420 static int arExtractCommand(ArCommand
*pAr
){
5424 " writefile(($dir || name), %s, mode, mtime) "
5425 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
5426 " AND name NOT GLOB '*..[/\\]*'";
5428 const char *azExtraArg
[] = {
5429 "sqlar_uncompress(data, sz)",
5433 sqlite3_stmt
*pSql
= 0;
5439 /* If arguments are specified, check that they actually exist within
5440 ** the archive before proceeding. And formulate a WHERE clause to
5442 rc
= arCheckEntries(pAr
);
5443 arWhereClause(&rc
, pAr
, &zWhere
);
5445 if( rc
==SQLITE_OK
){
5447 zDir
= sqlite3_mprintf("%s/", pAr
->zDir
);
5449 zDir
= sqlite3_mprintf("");
5451 if( zDir
==0 ) rc
= SQLITE_NOMEM
;
5454 shellPreparePrintf(pAr
->db
, &rc
, &pSql
, zSql1
,
5455 azExtraArg
[pAr
->bZip
], pAr
->zSrcTable
, zWhere
5458 if( rc
==SQLITE_OK
){
5459 j
= sqlite3_bind_parameter_index(pSql
, "$dir");
5460 sqlite3_bind_text(pSql
, j
, zDir
, -1, SQLITE_STATIC
);
5462 /* Run the SELECT statement twice. The first time, writefile() is called
5463 ** for all archive members that should be extracted. The second time,
5464 ** only for the directories. This is because the timestamps for
5465 ** extracted directories must be reset after they are populated (as
5466 ** populating them changes the timestamp). */
5468 j
= sqlite3_bind_parameter_index(pSql
, "$dirOnly");
5469 sqlite3_bind_int(pSql
, j
, i
);
5471 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_sql(pSql
));
5473 while( rc
==SQLITE_OK
&& SQLITE_ROW
==sqlite3_step(pSql
) ){
5474 if( i
==0 && pAr
->bVerbose
){
5475 utf8_printf(pAr
->p
->out
, "%s\n", sqlite3_column_text(pSql
, 0));
5479 shellReset(&rc
, pSql
);
5481 shellFinalize(&rc
, pSql
);
5485 sqlite3_free(zWhere
);
5490 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
5492 static int arExecSql(ArCommand
*pAr
, const char *zSql
){
5495 utf8_printf(pAr
->p
->out
, "%s\n", zSql
);
5499 rc
= sqlite3_exec(pAr
->db
, zSql
, 0, 0, &zErr
);
5501 utf8_printf(stdout
, "ERROR: %s\n", zErr
);
5510 ** Implementation of .ar "create" and "update" commands.
5512 ** Create the "sqlar" table in the database if it does not already exist.
5513 ** Then add each file in the azFile[] array to the archive. Directories
5514 ** are added recursively. If argument bVerbose is non-zero, a message is
5515 ** printed on stdout for each file archived.
5517 ** The create command is the same as update, except that it drops
5518 ** any existing "sqlar" table before beginning.
5520 static int arCreateOrUpdateCommand(
5521 ArCommand
*pAr
, /* Command arguments and options */
5522 int bUpdate
/* true for a --create. false for --update */
5524 const char *zCreate
=
5525 "CREATE TABLE IF NOT EXISTS sqlar(\n"
5526 " name TEXT PRIMARY KEY, -- name of the file\n"
5527 " mode INT, -- access permissions\n"
5528 " mtime INT, -- last modification time\n"
5529 " sz INT, -- original file size\n"
5530 " data BLOB -- compressed content\n"
5532 const char *zDrop
= "DROP TABLE IF EXISTS sqlar";
5533 const char *zInsertFmt
[2] = {
5534 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
5539 " CASE substr(lsmode(mode),1,1)\n"
5540 " WHEN '-' THEN length(data)\n"
5541 " WHEN 'd' THEN 0\n"
5543 " sqlar_compress(data)\n"
5544 " FROM fsdir(%Q,%Q)\n"
5545 " WHERE lsmode(mode) NOT LIKE '?%%';",
5546 "REPLACE INTO %s(name,mode,mtime,data)\n"
5552 " FROM fsdir(%Q,%Q)\n"
5553 " WHERE lsmode(mode) NOT LIKE '?%%';"
5555 int i
; /* For iterating through azFile[] */
5556 int rc
; /* Return code */
5557 const char *zTab
= 0; /* SQL table into which to insert */
5561 arExecSql(pAr
, "PRAGMA page_size=512");
5562 rc
= arExecSql(pAr
, "SAVEPOINT ar;");
5563 if( rc
!=SQLITE_OK
) return rc
;
5566 /* Initialize the zipfile virtual table, if necessary */
5569 sqlite3_randomness(sizeof(r
),&r
);
5570 sqlite3_snprintf(sizeof(zTemp
),zTemp
,"zip%016llx",r
);
5572 zSql
= sqlite3_mprintf(
5573 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
5576 rc
= arExecSql(pAr
, zSql
);
5582 /* Initialize the table for an SQLAR */
5585 rc
= arExecSql(pAr
, zDrop
);
5586 if( rc
!=SQLITE_OK
) goto end_ar_transaction
;
5588 rc
= arExecSql(pAr
, zCreate
);
5590 for(i
=0; i
<pAr
->nArg
&& rc
==SQLITE_OK
; i
++){
5591 char *zSql2
= sqlite3_mprintf(zInsertFmt
[pAr
->bZip
], zTab
,
5592 pAr
->bVerbose
? "shell_putsnl(name)" : "name",
5593 pAr
->azArg
[i
], pAr
->zDir
);
5594 rc
= arExecSql(pAr
, zSql2
);
5595 sqlite3_free(zSql2
);
5598 if( rc
!=SQLITE_OK
){
5599 arExecSql(pAr
, "ROLLBACK TO ar; RELEASE ar;");
5601 rc
= arExecSql(pAr
, "RELEASE ar;");
5602 if( pAr
->bZip
&& pAr
->zFile
){
5603 zSql
= sqlite3_mprintf("DROP TABLE %s", zTemp
);
5604 arExecSql(pAr
, zSql
);
5612 ** Implementation of ".ar" dot command.
5614 static int arDotCommand(
5615 ShellState
*pState
, /* Current shell tool state */
5616 int fromCmdLine
, /* True if -A command-line option, not .ar cmd */
5617 char **azArg
, /* Array of arguments passed to dot command */
5618 int nArg
/* Number of entries in azArg[] */
5622 memset(&cmd
, 0, sizeof(cmd
));
5623 cmd
.fromCmdLine
= fromCmdLine
;
5624 rc
= arParseCommand(azArg
, nArg
, &cmd
);
5625 if( rc
==SQLITE_OK
){
5626 int eDbType
= SHELL_OPEN_UNSPEC
;
5628 cmd
.db
= pState
->db
;
5630 eDbType
= deduceDatabaseType(cmd
.zFile
, 1);
5632 eDbType
= pState
->openMode
;
5634 if( eDbType
==SHELL_OPEN_ZIPFILE
){
5635 if( cmd
.eCmd
==AR_CMD_EXTRACT
|| cmd
.eCmd
==AR_CMD_LIST
){
5637 cmd
.zSrcTable
= sqlite3_mprintf("zip");
5639 cmd
.zSrcTable
= sqlite3_mprintf("zipfile(%Q)", cmd
.zFile
);
5643 }else if( cmd
.zFile
){
5645 if( cmd
.bAppend
) eDbType
= SHELL_OPEN_APPENDVFS
;
5646 if( cmd
.eCmd
==AR_CMD_CREATE
|| cmd
.eCmd
==AR_CMD_UPDATE
){
5647 flags
= SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
;
5649 flags
= SQLITE_OPEN_READONLY
;
5653 utf8_printf(pState
->out
, "-- open database '%s'%s\n", cmd
.zFile
,
5654 eDbType
==SHELL_OPEN_APPENDVFS
? " using 'apndvfs'" : "");
5656 rc
= sqlite3_open_v2(cmd
.zFile
, &cmd
.db
, flags
,
5657 eDbType
==SHELL_OPEN_APPENDVFS
? "apndvfs" : 0);
5658 if( rc
!=SQLITE_OK
){
5659 utf8_printf(stderr
, "cannot open file: %s (%s)\n",
5660 cmd
.zFile
, sqlite3_errmsg(cmd
.db
)
5662 goto end_ar_command
;
5664 sqlite3_fileio_init(cmd
.db
, 0, 0);
5665 sqlite3_sqlar_init(cmd
.db
, 0, 0);
5666 sqlite3_create_function(cmd
.db
, "shell_putsnl", 1, SQLITE_UTF8
, cmd
.p
,
5667 shellPutsFunc
, 0, 0);
5670 if( cmd
.zSrcTable
==0 && cmd
.bZip
==0 && cmd
.eCmd
!=AR_CMD_HELP
){
5671 if( cmd
.eCmd
!=AR_CMD_CREATE
5672 && sqlite3_table_column_metadata(cmd
.db
,0,"sqlar","name",0,0,0,0,0)
5674 utf8_printf(stderr
, "database does not contain an 'sqlar' table\n");
5676 goto end_ar_command
;
5678 cmd
.zSrcTable
= sqlite3_mprintf("sqlar");
5683 rc
= arCreateOrUpdateCommand(&cmd
, 0);
5686 case AR_CMD_EXTRACT
:
5687 rc
= arExtractCommand(&cmd
);
5691 rc
= arListCommand(&cmd
);
5695 arUsage(pState
->out
);
5699 assert( cmd
.eCmd
==AR_CMD_UPDATE
);
5700 rc
= arCreateOrUpdateCommand(&cmd
, 1);
5705 if( cmd
.db
!=pState
->db
){
5708 sqlite3_free(cmd
.zSrcTable
);
5712 /* End of the ".archive" or ".ar" command logic
5713 **********************************************************************************/
5714 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
5718 ** If an input line begins with "." then invoke this routine to
5719 ** process that line.
5721 ** Return 1 on error, 2 to exit, and 0 otherwise.
5723 static int do_meta_command(char *zLine
, ShellState
*p
){
5730 #ifndef SQLITE_OMIT_VIRTUALTABLE
5731 if( p
->expert
.pExpert
){
5732 expertFinish(p
, 1, 0);
5736 /* Parse the input line into tokens.
5738 while( zLine
[h
] && nArg
<ArraySize(azArg
) ){
5739 while( IsSpace(zLine
[h
]) ){ h
++; }
5740 if( zLine
[h
]==0 ) break;
5741 if( zLine
[h
]=='\'' || zLine
[h
]=='"' ){
5742 int delim
= zLine
[h
++];
5743 azArg
[nArg
++] = &zLine
[h
];
5744 while( zLine
[h
] && zLine
[h
]!=delim
){
5745 if( zLine
[h
]=='\\' && delim
=='"' && zLine
[h
+1]!=0 ) h
++;
5748 if( zLine
[h
]==delim
){
5751 if( delim
=='"' ) resolve_backslashes(azArg
[nArg
-1]);
5753 azArg
[nArg
++] = &zLine
[h
];
5754 while( zLine
[h
] && !IsSpace(zLine
[h
]) ){ h
++; }
5755 if( zLine
[h
] ) zLine
[h
++] = 0;
5756 resolve_backslashes(azArg
[nArg
-1]);
5760 /* Process the input line.
5762 if( nArg
==0 ) return 0; /* no tokens, no error */
5763 n
= strlen30(azArg
[0]);
5767 #ifndef SQLITE_OMIT_AUTHORIZATION
5768 if( c
=='a' && strncmp(azArg
[0], "auth", n
)==0 ){
5770 raw_printf(stderr
, "Usage: .auth ON|OFF\n");
5772 goto meta_command_exit
;
5775 if( booleanValue(azArg
[1]) ){
5776 sqlite3_set_authorizer(p
->db
, shellAuth
, p
);
5778 sqlite3_set_authorizer(p
->db
, 0, 0);
5783 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
5784 if( c
=='a' && strncmp(azArg
[0], "archive", n
)==0 ){
5786 rc
= arDotCommand(p
, 0, azArg
, nArg
);
5790 if( (c
=='b' && n
>=3 && strncmp(azArg
[0], "backup", n
)==0)
5791 || (c
=='s' && n
>=3 && strncmp(azArg
[0], "save", n
)==0)
5793 const char *zDestFile
= 0;
5794 const char *zDb
= 0;
5796 sqlite3_backup
*pBackup
;
5798 const char *zVfs
= 0;
5799 for(j
=1; j
<nArg
; j
++){
5800 const char *z
= azArg
[j
];
5802 if( z
[1]=='-' ) z
++;
5803 if( strcmp(z
, "-append")==0 ){
5807 utf8_printf(stderr
, "unknown option: %s\n", azArg
[j
]);
5810 }else if( zDestFile
==0 ){
5811 zDestFile
= azArg
[j
];
5814 zDestFile
= azArg
[j
];
5816 raw_printf(stderr
, "Usage: .backup ?DB? ?--append? FILENAME\n");
5821 raw_printf(stderr
, "missing FILENAME argument on .backup\n");
5824 if( zDb
==0 ) zDb
= "main";
5825 rc
= sqlite3_open_v2(zDestFile
, &pDest
,
5826 SQLITE_OPEN_READWRITE
|SQLITE_OPEN_CREATE
, zVfs
);
5827 if( rc
!=SQLITE_OK
){
5828 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zDestFile
);
5833 pBackup
= sqlite3_backup_init(pDest
, "main", p
->db
, zDb
);
5835 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5839 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
){}
5840 sqlite3_backup_finish(pBackup
);
5841 if( rc
==SQLITE_DONE
){
5844 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(pDest
));
5850 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "bail", n
)==0 ){
5852 bail_on_error
= booleanValue(azArg
[1]);
5854 raw_printf(stderr
, "Usage: .bail on|off\n");
5859 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "binary", n
)==0 ){
5861 if( booleanValue(azArg
[1]) ){
5862 setBinaryMode(p
->out
, 1);
5864 setTextMode(p
->out
, 1);
5867 raw_printf(stderr
, "Usage: .binary on|off\n");
5872 if( c
=='c' && strcmp(azArg
[0],"cd")==0 ){
5874 #if defined(_WIN32) || defined(WIN32)
5875 wchar_t *z
= sqlite3_win32_utf8_to_unicode(azArg
[1]);
5876 rc
= !SetCurrentDirectoryW(z
);
5879 rc
= chdir(azArg
[1]);
5882 utf8_printf(stderr
, "Cannot change to directory \"%s\"\n", azArg
[1]);
5886 raw_printf(stderr
, "Usage: .cd DIRECTORY\n");
5891 /* The undocumented ".breakpoint" command causes a call to the no-op
5892 ** routine named test_breakpoint().
5894 if( c
=='b' && n
>=3 && strncmp(azArg
[0], "breakpoint", n
)==0 ){
5898 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "changes", n
)==0 ){
5900 setOrClearFlag(p
, SHFLG_CountChanges
, azArg
[1]);
5902 raw_printf(stderr
, "Usage: .changes on|off\n");
5907 /* Cancel output redirection, if it is currently set (by .testcase)
5908 ** Then read the content of the testcase-out.txt file and compare against
5909 ** azArg[1]. If there are differences, report an error and exit.
5911 if( c
=='c' && n
>=3 && strncmp(azArg
[0], "check", n
)==0 ){
5915 raw_printf(stderr
, "Usage: .check GLOB-PATTERN\n");
5917 }else if( (zRes
= readFile("testcase-out.txt", 0))==0 ){
5918 raw_printf(stderr
, "Error: cannot read 'testcase-out.txt'\n");
5920 }else if( testcase_glob(azArg
[1],zRes
)==0 ){
5922 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5923 p
->zTestcase
, azArg
[1], zRes
);
5926 utf8_printf(stdout
, "testcase-%s ok\n", p
->zTestcase
);
5932 if( c
=='c' && strncmp(azArg
[0], "clone", n
)==0 ){
5934 tryToClone(p
, azArg
[1]);
5936 raw_printf(stderr
, "Usage: .clone FILENAME\n");
5941 if( c
=='d' && n
>1 && strncmp(azArg
[0], "databases", n
)==0 ){
5945 memcpy(&data
, p
, sizeof(data
));
5946 data
.showHeader
= 0;
5947 data
.cMode
= data
.mode
= MODE_List
;
5948 sqlite3_snprintf(sizeof(data
.colSeparator
),data
.colSeparator
,": ");
5950 sqlite3_exec(p
->db
, "SELECT name, file FROM pragma_database_list",
5951 callback
, &data
, &zErrMsg
);
5953 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
5954 sqlite3_free(zErrMsg
);
5959 if( c
=='d' && n
>=3 && strncmp(azArg
[0], "dbconfig", n
)==0 ){
5960 static const struct DbConfigChoices
{
5964 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY
},
5965 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER
},
5966 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
},
5967 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
},
5968 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE
},
5969 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG
},
5970 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP
},
5971 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE
},
5972 { "defensive", SQLITE_DBCONFIG_DEFENSIVE
},
5976 for(ii
=0; ii
<ArraySize(aDbConfig
); ii
++){
5977 if( nArg
>1 && strcmp(azArg
[1], aDbConfig
[ii
].zName
)!=0 ) continue;
5979 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, booleanValue(azArg
[2]), 0);
5981 sqlite3_db_config(p
->db
, aDbConfig
[ii
].op
, -1, &v
);
5982 utf8_printf(p
->out
, "%18s %s\n", aDbConfig
[ii
].zName
, v
? "on" : "off");
5985 if( nArg
>1 && ii
==ArraySize(aDbConfig
) ){
5986 utf8_printf(stderr
, "Error: unknown dbconfig \"%s\"\n", azArg
[1]);
5987 utf8_printf(stderr
, "Enter \".dbconfig\" with no arguments for a list\n");
5991 if( c
=='d' && n
>=3 && strncmp(azArg
[0], "dbinfo", n
)==0 ){
5992 rc
= shell_dbinfo_command(p
, nArg
, azArg
);
5995 if( c
=='d' && strncmp(azArg
[0], "dump", n
)==0 ){
5996 const char *zLike
= 0;
5998 int savedShowHeader
= p
->showHeader
;
5999 int savedShellFlags
= p
->shellFlgs
;
6000 ShellClearFlag(p
, SHFLG_PreserveRowid
|SHFLG_Newlines
|SHFLG_Echo
);
6001 for(i
=1; i
<nArg
; i
++){
6002 if( azArg
[i
][0]=='-' ){
6003 const char *z
= azArg
[i
]+1;
6004 if( z
[0]=='-' ) z
++;
6005 if( strcmp(z
,"preserve-rowids")==0 ){
6006 #ifdef SQLITE_OMIT_VIRTUALTABLE
6007 raw_printf(stderr
, "The --preserve-rowids option is not compatible"
6008 " with SQLITE_OMIT_VIRTUALTABLE\n");
6010 goto meta_command_exit
;
6012 ShellSetFlag(p
, SHFLG_PreserveRowid
);
6015 if( strcmp(z
,"newlines")==0 ){
6016 ShellSetFlag(p
, SHFLG_Newlines
);
6019 raw_printf(stderr
, "Unknown option \"%s\" on \".dump\"\n", azArg
[i
]);
6021 goto meta_command_exit
;
6024 raw_printf(stderr
, "Usage: .dump ?--preserve-rowids? "
6025 "?--newlines? ?LIKE-PATTERN?\n");
6027 goto meta_command_exit
;
6033 /* When playing back a "dump", the content might appear in an order
6034 ** which causes immediate foreign key constraints to be violated.
6035 ** So disable foreign-key constraint enforcement to prevent problems. */
6036 raw_printf(p
->out
, "PRAGMA foreign_keys=OFF;\n");
6037 raw_printf(p
->out
, "BEGIN TRANSACTION;\n");
6038 p
->writableSchema
= 0;
6040 /* Set writable_schema=ON since doing so forces SQLite to initialize
6041 ** as much of the schema as it can even if the sqlite_master table is
6043 sqlite3_exec(p
->db
, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
6046 run_schema_dump_query(p
,
6047 "SELECT name, type, sql FROM sqlite_master "
6048 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
6050 run_schema_dump_query(p
,
6051 "SELECT name, type, sql FROM sqlite_master "
6052 "WHERE name=='sqlite_sequence'"
6054 run_table_dump_query(p
,
6055 "SELECT sql FROM sqlite_master "
6056 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
6060 zSql
= sqlite3_mprintf(
6061 "SELECT name, type, sql FROM sqlite_master "
6062 "WHERE tbl_name LIKE %Q AND type=='table'"
6063 " AND sql NOT NULL", zLike
);
6064 run_schema_dump_query(p
,zSql
);
6066 zSql
= sqlite3_mprintf(
6067 "SELECT sql FROM sqlite_master "
6068 "WHERE sql NOT NULL"
6069 " AND type IN ('index','trigger','view')"
6070 " AND tbl_name LIKE %Q", zLike
);
6071 run_table_dump_query(p
, zSql
, 0);
6074 if( p
->writableSchema
){
6075 raw_printf(p
->out
, "PRAGMA writable_schema=OFF;\n");
6076 p
->writableSchema
= 0;
6078 sqlite3_exec(p
->db
, "PRAGMA writable_schema=OFF;", 0, 0, 0);
6079 sqlite3_exec(p
->db
, "RELEASE dump;", 0, 0, 0);
6080 raw_printf(p
->out
, p
->nErr
? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
6081 p
->showHeader
= savedShowHeader
;
6082 p
->shellFlgs
= savedShellFlags
;
6085 if( c
=='e' && strncmp(azArg
[0], "echo", n
)==0 ){
6087 setOrClearFlag(p
, SHFLG_Echo
, azArg
[1]);
6089 raw_printf(stderr
, "Usage: .echo on|off\n");
6094 if( c
=='e' && strncmp(azArg
[0], "eqp", n
)==0 ){
6097 if( strcmp(azArg
[1],"full")==0 ){
6098 p
->autoEQP
= AUTOEQP_full
;
6099 }else if( strcmp(azArg
[1],"trigger")==0 ){
6100 p
->autoEQP
= AUTOEQP_trigger
;
6101 }else if( strcmp(azArg
[1],"test")==0 ){
6102 p
->autoEQP
= AUTOEQP_on
;
6105 p
->autoEQP
= (u8
)booleanValue(azArg
[1]);
6108 raw_printf(stderr
, "Usage: .eqp off|on|trigger|full\n");
6113 if( c
=='e' && strncmp(azArg
[0], "exit", n
)==0 ){
6114 if( nArg
>1 && (rc
= (int)integerValue(azArg
[1]))!=0 ) exit(rc
);
6118 /* The ".explain" command is automatic now. It is largely pointless. It
6119 ** retained purely for backwards compatibility */
6120 if( c
=='e' && strncmp(azArg
[0], "explain", n
)==0 ){
6123 if( strcmp(azArg
[1],"auto")==0 ){
6126 val
= booleanValue(azArg
[1]);
6129 if( val
==1 && p
->mode
!=MODE_Explain
){
6130 p
->normalMode
= p
->mode
;
6131 p
->mode
= MODE_Explain
;
6134 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
6136 }else if( val
==99 ){
6137 if( p
->mode
==MODE_Explain
) p
->mode
= p
->normalMode
;
6142 #ifndef SQLITE_OMIT_VIRTUALTABLE
6143 if( c
=='e' && strncmp(azArg
[0], "expert", n
)==0 ){
6145 expertDotCommand(p
, azArg
, nArg
);
6149 if( c
=='f' && strncmp(azArg
[0], "fullschema", n
)==0 ){
6153 memcpy(&data
, p
, sizeof(data
));
6154 data
.showHeader
= 0;
6155 data
.cMode
= data
.mode
= MODE_Semi
;
6156 if( nArg
==2 && optionMatch(azArg
[1], "indent") ){
6157 data
.cMode
= data
.mode
= MODE_Pretty
;
6161 raw_printf(stderr
, "Usage: .fullschema ?--indent?\n");
6163 goto meta_command_exit
;
6166 rc
= sqlite3_exec(p
->db
,
6168 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
6169 " FROM sqlite_master UNION ALL"
6170 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
6171 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
6173 callback
, &data
, &zErrMsg
6175 if( rc
==SQLITE_OK
){
6176 sqlite3_stmt
*pStmt
;
6177 rc
= sqlite3_prepare_v2(p
->db
,
6178 "SELECT rowid FROM sqlite_master"
6179 " WHERE name GLOB 'sqlite_stat[134]'",
6181 doStats
= sqlite3_step(pStmt
)==SQLITE_ROW
;
6182 sqlite3_finalize(pStmt
);
6185 raw_printf(p
->out
, "/* No STAT tables available */\n");
6187 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
6188 sqlite3_exec(p
->db
, "SELECT 'ANALYZE sqlite_master'",
6189 callback
, &data
, &zErrMsg
);
6190 data
.cMode
= data
.mode
= MODE_Insert
;
6191 data
.zDestTable
= "sqlite_stat1";
6192 shell_exec(&data
, "SELECT * FROM sqlite_stat1", &zErrMsg
);
6193 data
.zDestTable
= "sqlite_stat3";
6194 shell_exec(&data
, "SELECT * FROM sqlite_stat3", &zErrMsg
);
6195 data
.zDestTable
= "sqlite_stat4";
6196 shell_exec(&data
, "SELECT * FROM sqlite_stat4", &zErrMsg
);
6197 raw_printf(p
->out
, "ANALYZE sqlite_master;\n");
6201 if( c
=='h' && strncmp(azArg
[0], "headers", n
)==0 ){
6203 p
->showHeader
= booleanValue(azArg
[1]);
6205 raw_printf(stderr
, "Usage: .headers on|off\n");
6210 if( c
=='h' && strncmp(azArg
[0], "help", n
)==0 ){
6212 n
= showHelp(p
->out
, azArg
[1]);
6214 utf8_printf(p
->out
, "Nothing matches '%s'\n", azArg
[1]);
6217 showHelp(p
->out
, 0);
6221 if( c
=='i' && strncmp(azArg
[0], "import", n
)==0 ){
6222 char *zTable
; /* Insert data into this table */
6223 char *zFile
; /* Name of file to extra content from */
6224 sqlite3_stmt
*pStmt
= NULL
; /* A statement */
6225 int nCol
; /* Number of columns in the table */
6226 int nByte
; /* Number of bytes in an SQL string */
6227 int i
, j
; /* Loop counters */
6228 int needCommit
; /* True to COMMIT or ROLLBACK at end */
6229 int nSep
; /* Number of bytes in p->colSeparator[] */
6230 char *zSql
; /* An SQL statement */
6231 ImportCtx sCtx
; /* Reader context */
6232 char *(SQLITE_CDECL
*xRead
)(ImportCtx
*); /* Func to read one value */
6233 int (SQLITE_CDECL
*xCloser
)(FILE*); /* Func to close file */
6236 raw_printf(stderr
, "Usage: .import FILE TABLE\n");
6237 goto meta_command_exit
;
6242 memset(&sCtx
, 0, sizeof(sCtx
));
6244 nSep
= strlen30(p
->colSeparator
);
6247 "Error: non-null column separator required for import\n");
6251 raw_printf(stderr
, "Error: multi-character column separators not allowed"
6255 nSep
= strlen30(p
->rowSeparator
);
6257 raw_printf(stderr
, "Error: non-null row separator required for import\n");
6260 if( nSep
==2 && p
->mode
==MODE_Csv
&& strcmp(p
->rowSeparator
, SEP_CrLf
)==0 ){
6261 /* When importing CSV (only), if the row separator is set to the
6262 ** default output row separator, change it to the default input
6263 ** row separator. This avoids having to maintain different input
6264 ** and output row separators. */
6265 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6266 nSep
= strlen30(p
->rowSeparator
);
6269 raw_printf(stderr
, "Error: multi-character row separators not allowed"
6275 if( sCtx
.zFile
[0]=='|' ){
6276 #ifdef SQLITE_OMIT_POPEN
6277 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6280 sCtx
.in
= popen(sCtx
.zFile
+1, "r");
6281 sCtx
.zFile
= "<pipe>";
6285 sCtx
.in
= fopen(sCtx
.zFile
, "rb");
6288 if( p
->mode
==MODE_Ascii
){
6289 xRead
= ascii_read_one_field
;
6291 xRead
= csv_read_one_field
;
6294 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zFile
);
6297 sCtx
.cColSep
= p
->colSeparator
[0];
6298 sCtx
.cRowSep
= p
->rowSeparator
[0];
6299 zSql
= sqlite3_mprintf("SELECT * FROM %s", zTable
);
6302 shell_out_of_memory();
6304 nByte
= strlen30(zSql
);
6305 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6306 import_append_char(&sCtx
, 0); /* To ensure sCtx.z is allocated */
6307 if( rc
&& sqlite3_strglob("no such table: *", sqlite3_errmsg(p
->db
))==0 ){
6308 char *zCreate
= sqlite3_mprintf("CREATE TABLE %s", zTable
);
6310 while( xRead(&sCtx
) ){
6311 zCreate
= sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate
, cSep
, sCtx
.z
);
6313 if( sCtx
.cTerm
!=sCtx
.cColSep
) break;
6316 sqlite3_free(zCreate
);
6317 sqlite3_free(sCtx
.z
);
6319 utf8_printf(stderr
,"%s: empty file\n", sCtx
.zFile
);
6322 zCreate
= sqlite3_mprintf("%z\n)", zCreate
);
6323 rc
= sqlite3_exec(p
->db
, zCreate
, 0, 0, 0);
6324 sqlite3_free(zCreate
);
6326 utf8_printf(stderr
, "CREATE TABLE %s(...) failed: %s\n", zTable
,
6327 sqlite3_errmsg(p
->db
));
6328 sqlite3_free(sCtx
.z
);
6332 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6336 if (pStmt
) sqlite3_finalize(pStmt
);
6337 utf8_printf(stderr
,"Error: %s\n", sqlite3_errmsg(p
->db
));
6341 nCol
= sqlite3_column_count(pStmt
);
6342 sqlite3_finalize(pStmt
);
6344 if( nCol
==0 ) return 0; /* no columns, no error */
6345 zSql
= sqlite3_malloc64( nByte
*2 + 20 + nCol
*2 );
6348 shell_out_of_memory();
6350 sqlite3_snprintf(nByte
+20, zSql
, "INSERT INTO \"%w\" VALUES(?", zTable
);
6352 for(i
=1; i
<nCol
; i
++){
6358 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6361 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6362 if (pStmt
) sqlite3_finalize(pStmt
);
6366 needCommit
= sqlite3_get_autocommit(p
->db
);
6367 if( needCommit
) sqlite3_exec(p
->db
, "BEGIN", 0, 0, 0);
6369 int startLine
= sCtx
.nLine
;
6370 for(i
=0; i
<nCol
; i
++){
6371 char *z
= xRead(&sCtx
);
6373 ** Did we reach end-of-file before finding any columns?
6374 ** If so, stop instead of NULL filling the remaining columns.
6376 if( z
==0 && i
==0 ) break;
6378 ** Did we reach end-of-file OR end-of-line before finding any
6379 ** columns in ASCII mode? If so, stop instead of NULL filling
6380 ** the remaining columns.
6382 if( p
->mode
==MODE_Ascii
&& (z
==0 || z
[0]==0) && i
==0 ) break;
6383 sqlite3_bind_text(pStmt
, i
+1, z
, -1, SQLITE_TRANSIENT
);
6384 if( i
<nCol
-1 && sCtx
.cTerm
!=sCtx
.cColSep
){
6385 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6386 "filling the rest with NULL\n",
6387 sCtx
.zFile
, startLine
, nCol
, i
+1);
6389 while( i
<=nCol
){ sqlite3_bind_null(pStmt
, i
); i
++; }
6392 if( sCtx
.cTerm
==sCtx
.cColSep
){
6396 }while( sCtx
.cTerm
==sCtx
.cColSep
);
6397 utf8_printf(stderr
, "%s:%d: expected %d columns but found %d - "
6399 sCtx
.zFile
, startLine
, nCol
, i
);
6402 sqlite3_step(pStmt
);
6403 rc
= sqlite3_reset(pStmt
);
6404 if( rc
!=SQLITE_OK
){
6405 utf8_printf(stderr
, "%s:%d: INSERT failed: %s\n", sCtx
.zFile
,
6406 startLine
, sqlite3_errmsg(p
->db
));
6409 }while( sCtx
.cTerm
!=EOF
);
6412 sqlite3_free(sCtx
.z
);
6413 sqlite3_finalize(pStmt
);
6414 if( needCommit
) sqlite3_exec(p
->db
, "COMMIT", 0, 0, 0);
6417 #ifndef SQLITE_UNTESTABLE
6418 if( c
=='i' && strncmp(azArg
[0], "imposter", n
)==0 ){
6421 sqlite3_stmt
*pStmt
;
6424 if( !(nArg
==3 || (nArg
==2 && sqlite3_stricmp(azArg
[1],"off")==0)) ){
6425 utf8_printf(stderr
, "Usage: .imposter INDEX IMPOSTER\n"
6426 " .imposter off\n");
6428 goto meta_command_exit
;
6432 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 1);
6433 goto meta_command_exit
;
6435 zSql
= sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6436 " WHERE name='%q' AND type='index'", azArg
[1]);
6437 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6439 if( sqlite3_step(pStmt
)==SQLITE_ROW
){
6440 tnum
= sqlite3_column_int(pStmt
, 0);
6442 sqlite3_finalize(pStmt
);
6444 utf8_printf(stderr
, "no such index: \"%s\"\n", azArg
[1]);
6446 goto meta_command_exit
;
6448 zSql
= sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg
[1]);
6449 rc
= sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
6452 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6454 const char *zCol
= (const char*)sqlite3_column_text(pStmt
,2);
6457 if( sqlite3_column_int(pStmt
,1)==-1 ){
6460 sqlite3_snprintf(sizeof(zLabel
),zLabel
,"expr%d",i
);
6465 zCollist
= sqlite3_mprintf("\"%w\"", zCol
);
6467 zCollist
= sqlite3_mprintf("%z,\"%w\"", zCollist
, zCol
);
6470 sqlite3_finalize(pStmt
);
6471 zSql
= sqlite3_mprintf(
6472 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6473 azArg
[2], zCollist
, zCollist
);
6474 sqlite3_free(zCollist
);
6475 rc
= sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 1, tnum
);
6476 if( rc
==SQLITE_OK
){
6477 rc
= sqlite3_exec(p
->db
, zSql
, 0, 0, 0);
6478 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER
, p
->db
, "main", 0, 0);
6480 utf8_printf(stderr
, "Error in [%s]: %s\n", zSql
, sqlite3_errmsg(p
->db
));
6482 utf8_printf(stdout
, "%s;\n", zSql
);
6484 "WARNING: writing to an imposter table will corrupt the index!\n"
6488 raw_printf(stderr
, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc
);
6493 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6495 #ifdef SQLITE_ENABLE_IOTRACE
6496 if( c
=='i' && strncmp(azArg
[0], "iotrace", n
)==0 ){
6497 SQLITE_API
extern void (SQLITE_CDECL
*sqlite3IoTrace
)(const char*, ...);
6498 if( iotrace
&& iotrace
!=stdout
) fclose(iotrace
);
6502 }else if( strcmp(azArg
[1], "-")==0 ){
6503 sqlite3IoTrace
= iotracePrintf
;
6506 iotrace
= fopen(azArg
[1], "w");
6508 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", azArg
[1]);
6512 sqlite3IoTrace
= iotracePrintf
;
6518 if( c
=='l' && n
>=5 && strncmp(azArg
[0], "limits", n
)==0 ){
6519 static const struct {
6520 const char *zLimitName
; /* Name of a limit */
6521 int limitCode
; /* Integer code for that limit */
6523 { "length", SQLITE_LIMIT_LENGTH
},
6524 { "sql_length", SQLITE_LIMIT_SQL_LENGTH
},
6525 { "column", SQLITE_LIMIT_COLUMN
},
6526 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH
},
6527 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT
},
6528 { "vdbe_op", SQLITE_LIMIT_VDBE_OP
},
6529 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG
},
6530 { "attached", SQLITE_LIMIT_ATTACHED
},
6531 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH
},
6532 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER
},
6533 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH
},
6534 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS
},
6539 for(i
=0; i
<ArraySize(aLimit
); i
++){
6540 printf("%20s %d\n", aLimit
[i
].zLimitName
,
6541 sqlite3_limit(p
->db
, aLimit
[i
].limitCode
, -1));
6544 raw_printf(stderr
, "Usage: .limit NAME ?NEW-VALUE?\n");
6546 goto meta_command_exit
;
6549 n2
= strlen30(azArg
[1]);
6550 for(i
=0; i
<ArraySize(aLimit
); i
++){
6551 if( sqlite3_strnicmp(aLimit
[i
].zLimitName
, azArg
[1], n2
)==0 ){
6555 utf8_printf(stderr
, "ambiguous limit: \"%s\"\n", azArg
[1]);
6557 goto meta_command_exit
;
6562 utf8_printf(stderr
, "unknown limit: \"%s\"\n"
6563 "enter \".limits\" with no arguments for a list.\n",
6566 goto meta_command_exit
;
6569 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
,
6570 (int)integerValue(azArg
[2]));
6572 printf("%20s %d\n", aLimit
[iLimit
].zLimitName
,
6573 sqlite3_limit(p
->db
, aLimit
[iLimit
].limitCode
, -1));
6577 if( c
=='l' && n
>2 && strncmp(azArg
[0], "lint", n
)==0 ){
6579 lintDotCommand(p
, azArg
, nArg
);
6582 #ifndef SQLITE_OMIT_LOAD_EXTENSION
6583 if( c
=='l' && strncmp(azArg
[0], "load", n
)==0 ){
6584 const char *zFile
, *zProc
;
6587 raw_printf(stderr
, "Usage: .load FILE ?ENTRYPOINT?\n");
6589 goto meta_command_exit
;
6592 zProc
= nArg
>=3 ? azArg
[2] : 0;
6594 rc
= sqlite3_load_extension(p
->db
, zFile
, zProc
, &zErrMsg
);
6595 if( rc
!=SQLITE_OK
){
6596 utf8_printf(stderr
, "Error: %s\n", zErrMsg
);
6597 sqlite3_free(zErrMsg
);
6603 if( c
=='l' && strncmp(azArg
[0], "log", n
)==0 ){
6605 raw_printf(stderr
, "Usage: .log FILENAME\n");
6608 const char *zFile
= azArg
[1];
6609 output_file_close(p
->pLog
);
6610 p
->pLog
= output_file_open(zFile
, 0);
6614 if( c
=='m' && strncmp(azArg
[0], "mode", n
)==0 ){
6615 const char *zMode
= nArg
>=2 ? azArg
[1] : "";
6616 int n2
= strlen30(zMode
);
6618 if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"lines",n2
)==0 ){
6619 p
->mode
= MODE_Line
;
6620 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6621 }else if( c2
=='c' && strncmp(azArg
[1],"columns",n2
)==0 ){
6622 p
->mode
= MODE_Column
;
6623 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6624 }else if( c2
=='l' && n2
>2 && strncmp(azArg
[1],"list",n2
)==0 ){
6625 p
->mode
= MODE_List
;
6626 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Column
);
6627 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6628 }else if( c2
=='h' && strncmp(azArg
[1],"html",n2
)==0 ){
6629 p
->mode
= MODE_Html
;
6630 }else if( c2
=='t' && strncmp(azArg
[1],"tcl",n2
)==0 ){
6632 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Space
);
6633 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Row
);
6634 }else if( c2
=='c' && strncmp(azArg
[1],"csv",n2
)==0 ){
6636 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6637 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6638 }else if( c2
=='t' && strncmp(azArg
[1],"tabs",n2
)==0 ){
6639 p
->mode
= MODE_List
;
6640 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Tab
);
6641 }else if( c2
=='i' && strncmp(azArg
[1],"insert",n2
)==0 ){
6642 p
->mode
= MODE_Insert
;
6643 set_table_name(p
, nArg
>=3 ? azArg
[2] : "table");
6644 }else if( c2
=='q' && strncmp(azArg
[1],"quote",n2
)==0 ){
6645 p
->mode
= MODE_Quote
;
6646 }else if( c2
=='a' && strncmp(azArg
[1],"ascii",n2
)==0 ){
6647 p
->mode
= MODE_Ascii
;
6648 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Unit
);
6649 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_Record
);
6650 }else if( nArg
==1 ){
6651 raw_printf(p
->out
, "current output mode: %s\n", modeDescr
[p
->mode
]);
6653 raw_printf(stderr
, "Error: mode should be one of: "
6654 "ascii column csv html insert line list quote tabs tcl\n");
6660 if( c
=='n' && strncmp(azArg
[0], "nullvalue", n
)==0 ){
6662 sqlite3_snprintf(sizeof(p
->nullValue
), p
->nullValue
,
6663 "%.*s", (int)ArraySize(p
->nullValue
)-1, azArg
[1]);
6665 raw_printf(stderr
, "Usage: .nullvalue STRING\n");
6670 if( c
=='o' && strncmp(azArg
[0], "open", n
)==0 && n
>=2 ){
6671 char *zNewFilename
; /* Name of the database file to open */
6672 int iName
= 1; /* Index in azArg[] of the filename */
6673 int newFlag
= 0; /* True to delete file before opening */
6674 /* Close the existing database */
6675 session_close_all(p
);
6679 sqlite3_free(p
->zFreeOnClose
);
6680 p
->zFreeOnClose
= 0;
6681 p
->openMode
= SHELL_OPEN_UNSPEC
;
6682 /* Check for command-line arguments */
6683 for(iName
=1; iName
<nArg
&& azArg
[iName
][0]=='-'; iName
++){
6684 const char *z
= azArg
[iName
];
6685 if( optionMatch(z
,"new") ){
6687 #ifdef SQLITE_HAVE_ZLIB
6688 }else if( optionMatch(z
, "zip") ){
6689 p
->openMode
= SHELL_OPEN_ZIPFILE
;
6691 }else if( optionMatch(z
, "append") ){
6692 p
->openMode
= SHELL_OPEN_APPENDVFS
;
6693 }else if( optionMatch(z
, "readonly") ){
6694 p
->openMode
= SHELL_OPEN_READONLY
;
6695 #ifdef SQLITE_ENABLE_DESERIALIZE
6696 }else if( optionMatch(z
, "deserialize") ){
6697 p
->openMode
= SHELL_OPEN_DESERIALIZE
;
6699 }else if( z
[0]=='-' ){
6700 utf8_printf(stderr
, "unknown option: %s\n", z
);
6702 goto meta_command_exit
;
6705 /* If a filename is specified, try to open it first */
6706 zNewFilename
= nArg
>iName
? sqlite3_mprintf("%s", azArg
[iName
]) : 0;
6708 if( newFlag
) shellDeleteFile(zNewFilename
);
6709 p
->zDbFilename
= zNewFilename
;
6710 open_db(p
, OPEN_DB_KEEPALIVE
);
6712 utf8_printf(stderr
, "Error: cannot open '%s'\n", zNewFilename
);
6713 sqlite3_free(zNewFilename
);
6715 p
->zFreeOnClose
= zNewFilename
;
6719 /* As a fall-back open a TEMP database */
6726 && (strncmp(azArg
[0], "output", n
)==0||strncmp(azArg
[0], "once", n
)==0))
6727 || (c
=='e' && n
==5 && strcmp(azArg
[0],"excel")==0)
6729 const char *zFile
= nArg
>=2 ? azArg
[1] : "stdout";
6731 if( azArg
[0][0]=='e' ){
6732 /* Transform the ".excel" command into ".once -x" */
6735 zFile
= azArg
[1] = "-x";
6739 utf8_printf(stderr
, "Usage: .%s [-e|-x|FILE]\n", azArg
[0]);
6741 goto meta_command_exit
;
6743 if( n
>1 && strncmp(azArg
[0], "once", n
)==0 ){
6745 raw_printf(stderr
, "Usage: .once (-e|-x|FILE)\n");
6747 goto meta_command_exit
;
6754 if( zFile
[0]=='-' && zFile
[1]=='-' ) zFile
++;
6755 #ifndef SQLITE_NOHAVE_SYSTEM
6756 if( strcmp(zFile
, "-e")==0 || strcmp(zFile
, "-x")==0 ){
6759 if( zFile
[1]=='x' ){
6760 newTempFile(p
, "csv");
6762 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
, SEP_Comma
);
6763 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
, SEP_CrLf
);
6765 newTempFile(p
, "txt");
6768 zFile
= p
->zTempFile
;
6770 #endif /* SQLITE_NOHAVE_SYSTEM */
6771 if( zFile
[0]=='|' ){
6772 #ifdef SQLITE_OMIT_POPEN
6773 raw_printf(stderr
, "Error: pipes are not supported in this OS\n");
6777 p
->out
= popen(zFile
+ 1, "w");
6779 utf8_printf(stderr
,"Error: cannot open pipe \"%s\"\n", zFile
+ 1);
6783 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6787 p
->out
= output_file_open(zFile
, bTxtMode
);
6789 if( strcmp(zFile
,"off")!=0 ){
6790 utf8_printf(stderr
,"Error: cannot write to \"%s\"\n", zFile
);
6795 sqlite3_snprintf(sizeof(p
->outfile
), p
->outfile
, "%s", zFile
);
6800 if( c
=='p' && n
>=3 && strncmp(azArg
[0], "print", n
)==0 ){
6802 for(i
=1; i
<nArg
; i
++){
6803 if( i
>1 ) raw_printf(p
->out
, " ");
6804 utf8_printf(p
->out
, "%s", azArg
[i
]);
6806 raw_printf(p
->out
, "\n");
6809 if( c
=='p' && strncmp(azArg
[0], "prompt", n
)==0 ){
6811 strncpy(mainPrompt
,azArg
[1],(int)ArraySize(mainPrompt
)-1);
6814 strncpy(continuePrompt
,azArg
[2],(int)ArraySize(continuePrompt
)-1);
6818 if( c
=='q' && strncmp(azArg
[0], "quit", n
)==0 ){
6822 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "read", n
)==0 ){
6825 raw_printf(stderr
, "Usage: .read FILE\n");
6827 goto meta_command_exit
;
6829 alt
= fopen(azArg
[1], "rb");
6831 utf8_printf(stderr
,"Error: cannot open \"%s\"\n", azArg
[1]);
6834 rc
= process_input(p
, alt
);
6839 if( c
=='r' && n
>=3 && strncmp(azArg
[0], "restore", n
)==0 ){
6840 const char *zSrcFile
;
6843 sqlite3_backup
*pBackup
;
6847 zSrcFile
= azArg
[1];
6849 }else if( nArg
==3 ){
6850 zSrcFile
= azArg
[2];
6853 raw_printf(stderr
, "Usage: .restore ?DB? FILE\n");
6855 goto meta_command_exit
;
6857 rc
= sqlite3_open(zSrcFile
, &pSrc
);
6858 if( rc
!=SQLITE_OK
){
6859 utf8_printf(stderr
, "Error: cannot open \"%s\"\n", zSrcFile
);
6864 pBackup
= sqlite3_backup_init(p
->db
, zDb
, pSrc
, "main");
6866 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6870 while( (rc
= sqlite3_backup_step(pBackup
,100))==SQLITE_OK
6871 || rc
==SQLITE_BUSY
){
6872 if( rc
==SQLITE_BUSY
){
6873 if( nTimeout
++ >= 3 ) break;
6877 sqlite3_backup_finish(pBackup
);
6878 if( rc
==SQLITE_DONE
){
6880 }else if( rc
==SQLITE_BUSY
|| rc
==SQLITE_LOCKED
){
6881 raw_printf(stderr
, "Error: source database is busy\n");
6884 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6890 if( c
=='s' && strncmp(azArg
[0], "scanstats", n
)==0 ){
6892 p
->scanstatsOn
= (u8
)booleanValue(azArg
[1]);
6893 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
6894 raw_printf(stderr
, "Warning: .scanstats not available in this build.\n");
6897 raw_printf(stderr
, "Usage: .scanstats on|off\n");
6902 if( c
=='s' && strncmp(azArg
[0], "schema", n
)==0 ){
6906 const char *zDiv
= "(";
6907 const char *zName
= 0;
6913 memcpy(&data
, p
, sizeof(data
));
6914 data
.showHeader
= 0;
6915 data
.cMode
= data
.mode
= MODE_Semi
;
6917 for(ii
=1; ii
<nArg
; ii
++){
6918 if( optionMatch(azArg
[ii
],"indent") ){
6919 data
.cMode
= data
.mode
= MODE_Pretty
;
6920 }else if( optionMatch(azArg
[ii
],"debug") ){
6922 }else if( zName
==0 ){
6925 raw_printf(stderr
, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
6927 goto meta_command_exit
;
6931 int isMaster
= sqlite3_strlike(zName
, "sqlite_master", '\\')==0;
6932 if( isMaster
|| sqlite3_strlike(zName
,"sqlite_temp_master", '\\')==0 ){
6933 char *new_argv
[2], *new_colv
[2];
6934 new_argv
[0] = sqlite3_mprintf(
6935 "CREATE TABLE %s (\n"
6939 " rootpage integer,\n"
6941 ")", isMaster
? "sqlite_master" : "sqlite_temp_master");
6943 new_colv
[0] = "sql";
6945 callback(&data
, 1, new_argv
, new_colv
);
6946 sqlite3_free(new_argv
[0]);
6950 sqlite3_stmt
*pStmt
= 0;
6951 rc
= sqlite3_prepare_v2(p
->db
, "SELECT name FROM pragma_database_list",
6954 utf8_printf(stderr
, "Error: %s\n", sqlite3_errmsg(p
->db
));
6955 sqlite3_finalize(pStmt
);
6957 goto meta_command_exit
;
6959 appendText(&sSelect
, "SELECT sql FROM", 0);
6961 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
6962 const char *zDb
= (const char*)sqlite3_column_text(pStmt
, 0);
6964 sqlite3_snprintf(sizeof(zScNum
), zScNum
, "%d", ++iSchema
);
6965 appendText(&sSelect
, zDiv
, 0);
6966 zDiv
= " UNION ALL ";
6967 appendText(&sSelect
, "SELECT shell_add_schema(sql,", 0);
6968 if( sqlite3_stricmp(zDb
, "main")!=0 ){
6969 appendText(&sSelect
, zDb
, '"');
6971 appendText(&sSelect
, "NULL", 0);
6973 appendText(&sSelect
, ",name) AS sql, type, tbl_name, name, rowid,", 0);
6974 appendText(&sSelect
, zScNum
, 0);
6975 appendText(&sSelect
, " AS snum, ", 0);
6976 appendText(&sSelect
, zDb
, '\'');
6977 appendText(&sSelect
, " AS sname FROM ", 0);
6978 appendText(&sSelect
, zDb
, '"');
6979 appendText(&sSelect
, ".sqlite_master", 0);
6981 sqlite3_finalize(pStmt
);
6982 #ifdef SQLITE_INTROSPECTION_PRAGMAS
6984 appendText(&sSelect
,
6985 " UNION ALL SELECT shell_module_schema(name),"
6986 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
6989 appendText(&sSelect
, ") WHERE ", 0);
6991 char *zQarg
= sqlite3_mprintf("%Q", zName
);
6992 int bGlob
= strchr(zName
, '*') != 0 || strchr(zName
, '?') != 0 ||
6993 strchr(zName
, '[') != 0;
6994 if( strchr(zName
, '.') ){
6995 appendText(&sSelect
, "lower(printf('%s.%s',sname,tbl_name))", 0);
6997 appendText(&sSelect
, "lower(tbl_name)", 0);
6999 appendText(&sSelect
, bGlob
? " GLOB " : " LIKE ", 0);
7000 appendText(&sSelect
, zQarg
, 0);
7002 appendText(&sSelect
, " ESCAPE '\\' ", 0);
7004 appendText(&sSelect
, " AND ", 0);
7005 sqlite3_free(zQarg
);
7007 appendText(&sSelect
, "type!='meta' AND sql IS NOT NULL"
7008 " ORDER BY snum, rowid", 0);
7010 utf8_printf(p
->out
, "SQL: %s;\n", sSelect
.z
);
7012 rc
= sqlite3_exec(p
->db
, sSelect
.z
, callback
, &data
, &zErrMsg
);
7017 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
7018 sqlite3_free(zErrMsg
);
7020 }else if( rc
!= SQLITE_OK
){
7021 raw_printf(stderr
,"Error: querying schema information\n");
7028 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
7029 if( c
=='s' && n
==11 && strncmp(azArg
[0], "selecttrace", n
)==0 ){
7030 sqlite3SelectTrace
= (int)integerValue(azArg
[1]);
7034 #if defined(SQLITE_ENABLE_SESSION)
7035 if( c
=='s' && strncmp(azArg
[0],"session",n
)==0 && n
>=3 ){
7036 OpenSession
*pSession
= &p
->aSession
[0];
7037 char **azCmd
= &azArg
[1];
7039 int nCmd
= nArg
- 1;
7041 if( nArg
<=1 ) goto session_syntax_error
;
7044 for(iSes
=0; iSes
<p
->nSession
; iSes
++){
7045 if( strcmp(p
->aSession
[iSes
].zName
, azArg
[1])==0 ) break;
7047 if( iSes
<p
->nSession
){
7048 pSession
= &p
->aSession
[iSes
];
7052 pSession
= &p
->aSession
[0];
7057 /* .session attach TABLE
7058 ** Invoke the sqlite3session_attach() interface to attach a particular
7059 ** table so that it is never filtered.
7061 if( strcmp(azCmd
[0],"attach")==0 ){
7062 if( nCmd
!=2 ) goto session_syntax_error
;
7063 if( pSession
->p
==0 ){
7065 raw_printf(stderr
, "ERROR: No sessions are open\n");
7067 rc
= sqlite3session_attach(pSession
->p
, azCmd
[1]);
7069 raw_printf(stderr
, "ERROR: sqlite3session_attach() returns %d\n", rc
);
7075 /* .session changeset FILE
7076 ** .session patchset FILE
7077 ** Write a changeset or patchset into a file. The file is overwritten.
7079 if( strcmp(azCmd
[0],"changeset")==0 || strcmp(azCmd
[0],"patchset")==0 ){
7081 if( nCmd
!=2 ) goto session_syntax_error
;
7082 if( pSession
->p
==0 ) goto session_not_open
;
7083 out
= fopen(azCmd
[1], "wb");
7085 utf8_printf(stderr
, "ERROR: cannot open \"%s\" for writing\n", azCmd
[1]);
7089 if( azCmd
[0][0]=='c' ){
7090 rc
= sqlite3session_changeset(pSession
->p
, &szChng
, &pChng
);
7092 rc
= sqlite3session_patchset(pSession
->p
, &szChng
, &pChng
);
7095 printf("Error: error code %d\n", rc
);
7099 && fwrite(pChng
, szChng
, 1, out
)!=1 ){
7100 raw_printf(stderr
, "ERROR: Failed to write entire %d-byte output\n",
7103 sqlite3_free(pChng
);
7109 ** Close the identified session
7111 if( strcmp(azCmd
[0], "close")==0 ){
7112 if( nCmd
!=1 ) goto session_syntax_error
;
7114 session_close(pSession
);
7115 p
->aSession
[iSes
] = p
->aSession
[--p
->nSession
];
7119 /* .session enable ?BOOLEAN?
7120 ** Query or set the enable flag
7122 if( strcmp(azCmd
[0], "enable")==0 ){
7124 if( nCmd
>2 ) goto session_syntax_error
;
7125 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
7127 ii
= sqlite3session_enable(pSession
->p
, ii
);
7128 utf8_printf(p
->out
, "session %s enable flag = %d\n",
7129 pSession
->zName
, ii
);
7133 /* .session filter GLOB ....
7134 ** Set a list of GLOB patterns of table names to be excluded.
7136 if( strcmp(azCmd
[0], "filter")==0 ){
7138 if( nCmd
<2 ) goto session_syntax_error
;
7140 for(ii
=0; ii
<pSession
->nFilter
; ii
++){
7141 sqlite3_free(pSession
->azFilter
[ii
]);
7143 sqlite3_free(pSession
->azFilter
);
7144 nByte
= sizeof(pSession
->azFilter
[0])*(nCmd
-1);
7145 pSession
->azFilter
= sqlite3_malloc( nByte
);
7146 if( pSession
->azFilter
==0 ){
7147 raw_printf(stderr
, "Error: out or memory\n");
7150 for(ii
=1; ii
<nCmd
; ii
++){
7151 pSession
->azFilter
[ii
-1] = sqlite3_mprintf("%s", azCmd
[ii
]);
7153 pSession
->nFilter
= ii
-1;
7157 /* .session indirect ?BOOLEAN?
7158 ** Query or set the indirect flag
7160 if( strcmp(azCmd
[0], "indirect")==0 ){
7162 if( nCmd
>2 ) goto session_syntax_error
;
7163 ii
= nCmd
==1 ? -1 : booleanValue(azCmd
[1]);
7165 ii
= sqlite3session_indirect(pSession
->p
, ii
);
7166 utf8_printf(p
->out
, "session %s indirect flag = %d\n",
7167 pSession
->zName
, ii
);
7172 ** Determine if the session is empty
7174 if( strcmp(azCmd
[0], "isempty")==0 ){
7176 if( nCmd
!=1 ) goto session_syntax_error
;
7178 ii
= sqlite3session_isempty(pSession
->p
);
7179 utf8_printf(p
->out
, "session %s isempty flag = %d\n",
7180 pSession
->zName
, ii
);
7185 ** List all currently open sessions
7187 if( strcmp(azCmd
[0],"list")==0 ){
7188 for(i
=0; i
<p
->nSession
; i
++){
7189 utf8_printf(p
->out
, "%d %s\n", i
, p
->aSession
[i
].zName
);
7193 /* .session open DB NAME
7194 ** Open a new session called NAME on the attached database DB.
7195 ** DB is normally "main".
7197 if( strcmp(azCmd
[0],"open")==0 ){
7199 if( nCmd
!=3 ) goto session_syntax_error
;
7201 if( zName
[0]==0 ) goto session_syntax_error
;
7202 for(i
=0; i
<p
->nSession
; i
++){
7203 if( strcmp(p
->aSession
[i
].zName
,zName
)==0 ){
7204 utf8_printf(stderr
, "Session \"%s\" already exists\n", zName
);
7205 goto meta_command_exit
;
7208 if( p
->nSession
>=ArraySize(p
->aSession
) ){
7209 raw_printf(stderr
, "Maximum of %d sessions\n", ArraySize(p
->aSession
));
7210 goto meta_command_exit
;
7212 pSession
= &p
->aSession
[p
->nSession
];
7213 rc
= sqlite3session_create(p
->db
, azCmd
[1], &pSession
->p
);
7215 raw_printf(stderr
, "Cannot open session: error code=%d\n", rc
);
7217 goto meta_command_exit
;
7219 pSession
->nFilter
= 0;
7220 sqlite3session_table_filter(pSession
->p
, session_filter
, pSession
);
7222 pSession
->zName
= sqlite3_mprintf("%s", zName
);
7224 /* If no command name matches, show a syntax error */
7225 session_syntax_error
:
7226 showHelp(p
->out
, "session");
7231 /* Undocumented commands for internal testing. Subject to change
7232 ** without notice. */
7233 if( c
=='s' && n
>=10 && strncmp(azArg
[0], "selftest-", 9)==0 ){
7234 if( strncmp(azArg
[0]+9, "boolean", n
-9)==0 ){
7236 for(i
=1; i
<nArg
; i
++){
7237 v
= booleanValue(azArg
[i
]);
7238 utf8_printf(p
->out
, "%s: %d 0x%x\n", azArg
[i
], v
, v
);
7241 if( strncmp(azArg
[0]+9, "integer", n
-9)==0 ){
7242 int i
; sqlite3_int64 v
;
7243 for(i
=1; i
<nArg
; i
++){
7245 v
= integerValue(azArg
[i
]);
7246 sqlite3_snprintf(sizeof(zBuf
),zBuf
,"%s: %lld 0x%llx\n", azArg
[i
],v
,v
);
7247 utf8_printf(p
->out
, "%s", zBuf
);
7253 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"selftest",n
)==0 ){
7254 int bIsInit
= 0; /* True to initialize the SELFTEST table */
7255 int bVerbose
= 0; /* Verbose output */
7256 int bSelftestExists
; /* True if SELFTEST already exists */
7257 int i
, k
; /* Loop counters */
7258 int nTest
= 0; /* Number of tests runs */
7259 int nErr
= 0; /* Number of errors seen */
7260 ShellText str
; /* Answer for a query */
7261 sqlite3_stmt
*pStmt
= 0; /* Query against the SELFTEST table */
7264 for(i
=1; i
<nArg
; i
++){
7265 const char *z
= azArg
[i
];
7266 if( z
[0]=='-' && z
[1]=='-' ) z
++;
7267 if( strcmp(z
,"-init")==0 ){
7270 if( strcmp(z
,"-v")==0 ){
7274 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7275 azArg
[i
], azArg
[0]);
7276 raw_printf(stderr
, "Should be one of: --init -v\n");
7278 goto meta_command_exit
;
7281 if( sqlite3_table_column_metadata(p
->db
,"main","selftest",0,0,0,0,0,0)
7283 bSelftestExists
= 0;
7285 bSelftestExists
= 1;
7288 createSelftestTable(p
);
7289 bSelftestExists
= 1;
7292 appendText(&str
, "x", 0);
7293 for(k
=bSelftestExists
; k
>=0; k
--){
7295 rc
= sqlite3_prepare_v2(p
->db
,
7296 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
7299 rc
= sqlite3_prepare_v2(p
->db
,
7300 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
7301 " (1,'run','PRAGMA integrity_check','ok')",
7305 raw_printf(stderr
, "Error querying the selftest table\n");
7307 sqlite3_finalize(pStmt
);
7308 goto meta_command_exit
;
7310 for(i
=1; sqlite3_step(pStmt
)==SQLITE_ROW
; i
++){
7311 int tno
= sqlite3_column_int(pStmt
, 0);
7312 const char *zOp
= (const char*)sqlite3_column_text(pStmt
, 1);
7313 const char *zSql
= (const char*)sqlite3_column_text(pStmt
, 2);
7314 const char *zAns
= (const char*)sqlite3_column_text(pStmt
, 3);
7318 char *zQuote
= sqlite3_mprintf("%q", zSql
);
7319 printf("%d: %s %s\n", tno
, zOp
, zSql
);
7320 sqlite3_free(zQuote
);
7322 if( strcmp(zOp
,"memo")==0 ){
7323 utf8_printf(p
->out
, "%s\n", zSql
);
7325 if( strcmp(zOp
,"run")==0 ){
7329 rc
= sqlite3_exec(p
->db
, zSql
, captureOutputCallback
, &str
, &zErrMsg
);
7332 utf8_printf(p
->out
, "Result: %s\n", str
.z
);
7334 if( rc
|| zErrMsg
){
7337 utf8_printf(p
->out
, "%d: error-code-%d: %s\n", tno
, rc
, zErrMsg
);
7338 sqlite3_free(zErrMsg
);
7339 }else if( strcmp(zAns
,str
.z
)!=0 ){
7342 utf8_printf(p
->out
, "%d: Expected: [%s]\n", tno
, zAns
);
7343 utf8_printf(p
->out
, "%d: Got: [%s]\n", tno
, str
.z
);
7348 "Unknown operation \"%s\" on selftest line %d\n", zOp
, tno
);
7352 } /* End loop over rows of content from SELFTEST */
7353 sqlite3_finalize(pStmt
);
7354 } /* End loop over k */
7356 utf8_printf(p
->out
, "%d errors out of %d tests\n", nErr
, nTest
);
7359 if( c
=='s' && strncmp(azArg
[0], "separator", n
)==0 ){
7360 if( nArg
<2 || nArg
>3 ){
7361 raw_printf(stderr
, "Usage: .separator COL ?ROW?\n");
7365 sqlite3_snprintf(sizeof(p
->colSeparator
), p
->colSeparator
,
7366 "%.*s", (int)ArraySize(p
->colSeparator
)-1, azArg
[1]);
7369 sqlite3_snprintf(sizeof(p
->rowSeparator
), p
->rowSeparator
,
7370 "%.*s", (int)ArraySize(p
->rowSeparator
)-1, azArg
[2]);
7374 if( c
=='s' && n
>=4 && strncmp(azArg
[0],"sha3sum",n
)==0 ){
7375 const char *zLike
= 0; /* Which table to checksum. 0 means everything */
7376 int i
; /* Loop counter */
7377 int bSchema
= 0; /* Also hash the schema */
7378 int bSeparate
= 0; /* Hash each table separately */
7379 int iSize
= 224; /* Hash algorithm to use */
7380 int bDebug
= 0; /* Only show the query that would have run */
7381 sqlite3_stmt
*pStmt
; /* For querying tables names */
7382 char *zSql
; /* SQL to be run */
7383 char *zSep
; /* Separator */
7384 ShellText sSql
; /* Complete SQL for the query to run the hash */
7385 ShellText sQuery
; /* Set of queries used to read all content */
7387 for(i
=1; i
<nArg
; i
++){
7388 const char *z
= azArg
[i
];
7391 if( z
[0]=='-' ) z
++;
7392 if( strcmp(z
,"schema")==0 ){
7395 if( strcmp(z
,"sha3-224")==0 || strcmp(z
,"sha3-256")==0
7396 || strcmp(z
,"sha3-384")==0 || strcmp(z
,"sha3-512")==0
7398 iSize
= atoi(&z
[5]);
7400 if( strcmp(z
,"debug")==0 ){
7404 utf8_printf(stderr
, "Unknown option \"%s\" on \"%s\"\n",
7405 azArg
[i
], azArg
[0]);
7406 raw_printf(stderr
, "Should be one of: --schema"
7407 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
7409 goto meta_command_exit
;
7412 raw_printf(stderr
, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7414 goto meta_command_exit
;
7418 if( sqlite3_strlike("sqlite\\_%", zLike
, '\\')==0 ) bSchema
= 1;
7422 zSql
= "SELECT lower(name) FROM sqlite_master"
7423 " WHERE type='table' AND coalesce(rootpage,0)>1"
7424 " UNION ALL SELECT 'sqlite_master'"
7425 " ORDER BY 1 collate nocase";
7427 zSql
= "SELECT lower(name) FROM sqlite_master"
7428 " WHERE type='table' AND coalesce(rootpage,0)>1"
7429 " AND name NOT LIKE 'sqlite_%'"
7430 " ORDER BY 1 collate nocase";
7432 sqlite3_prepare_v2(p
->db
, zSql
, -1, &pStmt
, 0);
7435 appendText(&sSql
, "WITH [sha3sum$query](a,b) AS(",0);
7437 while( SQLITE_ROW
==sqlite3_step(pStmt
) ){
7438 const char *zTab
= (const char*)sqlite3_column_text(pStmt
,0);
7439 if( zLike
&& sqlite3_strlike(zLike
, zTab
, 0)!=0 ) continue;
7440 if( strncmp(zTab
, "sqlite_",7)!=0 ){
7441 appendText(&sQuery
,"SELECT * FROM ", 0);
7442 appendText(&sQuery
,zTab
,'"');
7443 appendText(&sQuery
," NOT INDEXED;", 0);
7444 }else if( strcmp(zTab
, "sqlite_master")==0 ){
7445 appendText(&sQuery
,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7446 " ORDER BY name;", 0);
7447 }else if( strcmp(zTab
, "sqlite_sequence")==0 ){
7448 appendText(&sQuery
,"SELECT name,seq FROM sqlite_sequence"
7449 " ORDER BY name;", 0);
7450 }else if( strcmp(zTab
, "sqlite_stat1")==0 ){
7451 appendText(&sQuery
,"SELECT tbl,idx,stat FROM sqlite_stat1"
7452 " ORDER BY tbl,idx;", 0);
7453 }else if( strcmp(zTab
, "sqlite_stat3")==0
7454 || strcmp(zTab
, "sqlite_stat4")==0 ){
7455 appendText(&sQuery
, "SELECT * FROM ", 0);
7456 appendText(&sQuery
, zTab
, 0);
7457 appendText(&sQuery
, " ORDER BY tbl, idx, rowid;\n", 0);
7459 appendText(&sSql
, zSep
, 0);
7460 appendText(&sSql
, sQuery
.z
, '\'');
7462 appendText(&sSql
, ",", 0);
7463 appendText(&sSql
, zTab
, '\'');
7466 sqlite3_finalize(pStmt
);
7468 zSql
= sqlite3_mprintf(
7470 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7471 " FROM [sha3sum$query]",
7474 zSql
= sqlite3_mprintf(
7476 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7477 " FROM [sha3sum$query]",
7483 utf8_printf(p
->out
, "%s\n", zSql
);
7485 shell_exec(p
, zSql
, 0);
7490 #ifndef SQLITE_NOHAVE_SYSTEM
7492 && (strncmp(azArg
[0], "shell", n
)==0 || strncmp(azArg
[0],"system",n
)==0)
7497 raw_printf(stderr
, "Usage: .system COMMAND\n");
7499 goto meta_command_exit
;
7501 zCmd
= sqlite3_mprintf(strchr(azArg
[1],' ')==0?"%s":"\"%s\"", azArg
[1]);
7502 for(i
=2; i
<nArg
; i
++){
7503 zCmd
= sqlite3_mprintf(strchr(azArg
[i
],' ')==0?"%z %s":"%z \"%s\"",
7508 if( x
) raw_printf(stderr
, "System command returns %d\n", x
);
7510 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
7512 if( c
=='s' && strncmp(azArg
[0], "show", n
)==0 ){
7513 static const char *azBool
[] = { "off", "on", "trigger", "full"};
7516 raw_printf(stderr
, "Usage: .show\n");
7518 goto meta_command_exit
;
7520 utf8_printf(p
->out
, "%12.12s: %s\n","echo",
7521 azBool
[ShellHasFlag(p
, SHFLG_Echo
)]);
7522 utf8_printf(p
->out
, "%12.12s: %s\n","eqp", azBool
[p
->autoEQP
&3]);
7523 utf8_printf(p
->out
, "%12.12s: %s\n","explain",
7524 p
->mode
==MODE_Explain
? "on" : p
->autoExplain
? "auto" : "off");
7525 utf8_printf(p
->out
,"%12.12s: %s\n","headers", azBool
[p
->showHeader
!=0]);
7526 utf8_printf(p
->out
, "%12.12s: %s\n","mode", modeDescr
[p
->mode
]);
7527 utf8_printf(p
->out
, "%12.12s: ", "nullvalue");
7528 output_c_string(p
->out
, p
->nullValue
);
7529 raw_printf(p
->out
, "\n");
7530 utf8_printf(p
->out
,"%12.12s: %s\n","output",
7531 strlen30(p
->outfile
) ? p
->outfile
: "stdout");
7532 utf8_printf(p
->out
,"%12.12s: ", "colseparator");
7533 output_c_string(p
->out
, p
->colSeparator
);
7534 raw_printf(p
->out
, "\n");
7535 utf8_printf(p
->out
,"%12.12s: ", "rowseparator");
7536 output_c_string(p
->out
, p
->rowSeparator
);
7537 raw_printf(p
->out
, "\n");
7538 utf8_printf(p
->out
, "%12.12s: %s\n","stats", azBool
[p
->statsOn
!=0]);
7539 utf8_printf(p
->out
, "%12.12s: ", "width");
7540 for (i
=0;i
<(int)ArraySize(p
->colWidth
) && p
->colWidth
[i
] != 0;i
++) {
7541 raw_printf(p
->out
, "%d ", p
->colWidth
[i
]);
7543 raw_printf(p
->out
, "\n");
7544 utf8_printf(p
->out
, "%12.12s: %s\n", "filename",
7545 p
->zDbFilename
? p
->zDbFilename
: "");
7548 if( c
=='s' && strncmp(azArg
[0], "stats", n
)==0 ){
7550 p
->statsOn
= (u8
)booleanValue(azArg
[1]);
7551 }else if( nArg
==1 ){
7552 display_stats(p
->db
, p
, 0);
7554 raw_printf(stderr
, "Usage: .stats ?on|off?\n");
7559 if( (c
=='t' && n
>1 && strncmp(azArg
[0], "tables", n
)==0)
7560 || (c
=='i' && (strncmp(azArg
[0], "indices", n
)==0
7561 || strncmp(azArg
[0], "indexes", n
)==0) )
7563 sqlite3_stmt
*pStmt
;
7570 rc
= sqlite3_prepare_v2(p
->db
, "PRAGMA database_list", -1, &pStmt
, 0);
7572 sqlite3_finalize(pStmt
);
7573 return shellDatabaseError(p
->db
);
7576 if( nArg
>2 && c
=='i' ){
7577 /* It is an historical accident that the .indexes command shows an error
7578 ** when called with the wrong number of arguments whereas the .tables
7579 ** command does not. */
7580 raw_printf(stderr
, "Usage: .indexes ?LIKE-PATTERN?\n");
7582 sqlite3_finalize(pStmt
);
7583 goto meta_command_exit
;
7585 for(ii
=0; sqlite3_step(pStmt
)==SQLITE_ROW
; ii
++){
7586 const char *zDbName
= (const char*)sqlite3_column_text(pStmt
, 1);
7587 if( zDbName
==0 ) continue;
7588 if( s
.z
&& s
.z
[0] ) appendText(&s
, " UNION ALL ", 0);
7589 if( sqlite3_stricmp(zDbName
, "main")==0 ){
7590 appendText(&s
, "SELECT name FROM ", 0);
7592 appendText(&s
, "SELECT ", 0);
7593 appendText(&s
, zDbName
, '\'');
7594 appendText(&s
, "||'.'||name FROM ", 0);
7596 appendText(&s
, zDbName
, '"');
7597 appendText(&s
, ".sqlite_master ", 0);
7599 appendText(&s
," WHERE type IN ('table','view')"
7600 " AND name NOT LIKE 'sqlite_%'"
7601 " AND name LIKE ?1", 0);
7603 appendText(&s
," WHERE type='index'"
7604 " AND tbl_name LIKE ?1", 0);
7607 rc
= sqlite3_finalize(pStmt
);
7608 appendText(&s
, " ORDER BY 1", 0);
7609 rc
= sqlite3_prepare_v2(p
->db
, s
.z
, -1, &pStmt
, 0);
7611 if( rc
) return shellDatabaseError(p
->db
);
7613 /* Run the SQL statement prepared by the above block. Store the results
7614 ** as an array of nul-terminated strings in azResult[]. */
7618 sqlite3_bind_text(pStmt
, 1, azArg
[1], -1, SQLITE_TRANSIENT
);
7620 sqlite3_bind_text(pStmt
, 1, "%", -1, SQLITE_STATIC
);
7622 while( sqlite3_step(pStmt
)==SQLITE_ROW
){
7625 int n2
= nAlloc
*2 + 10;
7626 azNew
= sqlite3_realloc64(azResult
, sizeof(azResult
[0])*n2
);
7627 if( azNew
==0 ) shell_out_of_memory();
7631 azResult
[nRow
] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt
, 0));
7632 if( 0==azResult
[nRow
] ) shell_out_of_memory();
7635 if( sqlite3_finalize(pStmt
)!=SQLITE_OK
){
7636 rc
= shellDatabaseError(p
->db
);
7639 /* Pretty-print the contents of array azResult[] to the output */
7640 if( rc
==0 && nRow
>0 ){
7641 int len
, maxlen
= 0;
7643 int nPrintCol
, nPrintRow
;
7644 for(i
=0; i
<nRow
; i
++){
7645 len
= strlen30(azResult
[i
]);
7646 if( len
>maxlen
) maxlen
= len
;
7648 nPrintCol
= 80/(maxlen
+2);
7649 if( nPrintCol
<1 ) nPrintCol
= 1;
7650 nPrintRow
= (nRow
+ nPrintCol
- 1)/nPrintCol
;
7651 for(i
=0; i
<nPrintRow
; i
++){
7652 for(j
=i
; j
<nRow
; j
+=nPrintRow
){
7653 char *zSp
= j
<nPrintRow
? "" : " ";
7654 utf8_printf(p
->out
, "%s%-*s", zSp
, maxlen
,
7655 azResult
[j
] ? azResult
[j
]:"");
7657 raw_printf(p
->out
, "\n");
7661 for(ii
=0; ii
<nRow
; ii
++) sqlite3_free(azResult
[ii
]);
7662 sqlite3_free(azResult
);
7665 /* Begin redirecting output to the file "testcase-out.txt" */
7666 if( c
=='t' && strcmp(azArg
[0],"testcase")==0 ){
7668 p
->out
= output_file_open("testcase-out.txt", 0);
7670 raw_printf(stderr
, "Error: cannot open 'testcase-out.txt'\n");
7673 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "%s", azArg
[1]);
7675 sqlite3_snprintf(sizeof(p
->zTestcase
), p
->zTestcase
, "?");
7679 #ifndef SQLITE_UNTESTABLE
7680 if( c
=='t' && n
>=8 && strncmp(azArg
[0], "testctrl", n
)==0 ){
7681 static const struct {
7682 const char *zCtrlName
; /* Name of a test-control option */
7683 int ctrlCode
; /* Integer code for that option */
7684 const char *zUsage
; /* Usage notes */
7686 { "always", SQLITE_TESTCTRL_ALWAYS
, "BOOLEAN" },
7687 { "assert", SQLITE_TESTCTRL_ASSERT
, "BOOLEAN" },
7688 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
7689 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
7690 { "byteorder", SQLITE_TESTCTRL_BYTEORDER
, "" },
7691 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
7692 { "imposter", SQLITE_TESTCTRL_IMPOSTER
, "SCHEMA ON/OFF ROOTPAGE"},
7693 { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
, "BOOLEAN" },
7694 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT
,"BOOLEAN" },
7695 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT
, "BOOLEAN" },
7696 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS
, "DISABLE-MASK" },
7698 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE
, "" },
7700 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE
, "OFFSET " },
7701 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET
, "" },
7702 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE
, "" },
7703 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE
, "" },
7704 { "reserve", SQLITE_TESTCTRL_RESERVE
, "BYTES-OF-RESERVE" },
7708 int rc2
= 0; /* 0: usage. 1: %d 2: %x 3: no-output */
7711 const char *zCmd
= 0;
7714 zCmd
= nArg
>=2 ? azArg
[1] : "help";
7716 /* The argument can optionally begin with "-" or "--" */
7717 if( zCmd
[0]=='-' && zCmd
[1] ){
7719 if( zCmd
[0]=='-' && zCmd
[1] ) zCmd
++;
7722 /* --help lists all test-controls */
7723 if( strcmp(zCmd
,"help")==0 ){
7724 utf8_printf(p
->out
, "Available test-controls:\n");
7725 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7726 utf8_printf(p
->out
, " .testctrl %s %s\n",
7727 aCtrl
[i
].zCtrlName
, aCtrl
[i
].zUsage
);
7730 goto meta_command_exit
;
7733 /* convert testctrl text option to value. allow any unique prefix
7734 ** of the option name, or a numerical value. */
7735 n2
= strlen30(zCmd
);
7736 for(i
=0; i
<ArraySize(aCtrl
); i
++){
7737 if( strncmp(zCmd
, aCtrl
[i
].zCtrlName
, n2
)==0 ){
7739 testctrl
= aCtrl
[i
].ctrlCode
;
7742 utf8_printf(stderr
, "Error: ambiguous test-control: \"%s\"\n"
7743 "Use \".testctrl --help\" for help\n", zCmd
);
7745 goto meta_command_exit
;
7750 utf8_printf(stderr
,"Error: unknown test-control: %s\n"
7751 "Use \".testctrl --help\" for help\n", zCmd
);
7755 /* sqlite3_test_control(int, db, int) */
7756 case SQLITE_TESTCTRL_OPTIMIZATIONS
:
7757 case SQLITE_TESTCTRL_RESERVE
:
7759 int opt
= (int)strtol(azArg
[2], 0, 0);
7760 rc2
= sqlite3_test_control(testctrl
, p
->db
, opt
);
7765 /* sqlite3_test_control(int) */
7766 case SQLITE_TESTCTRL_PRNG_SAVE
:
7767 case SQLITE_TESTCTRL_PRNG_RESTORE
:
7768 case SQLITE_TESTCTRL_PRNG_RESET
:
7769 case SQLITE_TESTCTRL_BYTEORDER
:
7771 rc2
= sqlite3_test_control(testctrl
);
7772 isOk
= testctrl
==SQLITE_TESTCTRL_BYTEORDER
? 1 : 3;
7776 /* sqlite3_test_control(int, uint) */
7777 case SQLITE_TESTCTRL_PENDING_BYTE
:
7779 unsigned int opt
= (unsigned int)integerValue(azArg
[2]);
7780 rc2
= sqlite3_test_control(testctrl
, opt
);
7785 /* sqlite3_test_control(int, int) */
7786 case SQLITE_TESTCTRL_ASSERT
:
7787 case SQLITE_TESTCTRL_ALWAYS
:
7788 case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
:
7790 int opt
= booleanValue(azArg
[2]);
7791 rc2
= sqlite3_test_control(testctrl
, opt
);
7796 /* sqlite3_test_control(int, int) */
7797 case SQLITE_TESTCTRL_LOCALTIME_FAULT
:
7798 case SQLITE_TESTCTRL_NEVER_CORRUPT
:
7800 int opt
= booleanValue(azArg
[2]);
7801 rc2
= sqlite3_test_control(testctrl
, opt
);
7806 case SQLITE_TESTCTRL_IMPOSTER
:
7808 rc2
= sqlite3_test_control(testctrl
, p
->db
,
7810 integerValue(azArg
[3]),
7811 integerValue(azArg
[4]));
7817 case SQLITE_TESTCTRL_PARSER_COVERAGE
:
7819 sqlite3_test_control(testctrl
, p
->out
);
7825 if( isOk
==0 && iCtrl
>=0 ){
7826 utf8_printf(p
->out
, "Usage: .testctrl %s %s\n", zCmd
, aCtrl
[iCtrl
].zUsage
);
7828 }else if( isOk
==1 ){
7829 raw_printf(p
->out
, "%d\n", rc2
);
7830 }else if( isOk
==2 ){
7831 raw_printf(p
->out
, "0x%08x\n", rc2
);
7834 #endif /* !defined(SQLITE_UNTESTABLE) */
7836 if( c
=='t' && n
>4 && strncmp(azArg
[0], "timeout", n
)==0 ){
7838 sqlite3_busy_timeout(p
->db
, nArg
>=2 ? (int)integerValue(azArg
[1]) : 0);
7841 if( c
=='t' && n
>=5 && strncmp(azArg
[0], "timer", n
)==0 ){
7843 enableTimer
= booleanValue(azArg
[1]);
7844 if( enableTimer
&& !HAS_TIMER
){
7845 raw_printf(stderr
, "Error: timer not available on this system.\n");
7849 raw_printf(stderr
, "Usage: .timer on|off\n");
7854 if( c
=='t' && strncmp(azArg
[0], "trace", n
)==0 ){
7857 raw_printf(stderr
, "Usage: .trace FILE|off\n");
7859 goto meta_command_exit
;
7861 output_file_close(p
->traceOut
);
7862 p
->traceOut
= output_file_open(azArg
[1], 0);
7863 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
7864 if( p
->traceOut
==0 ){
7865 sqlite3_trace_v2(p
->db
, 0, 0, 0);
7867 sqlite3_trace_v2(p
->db
, SQLITE_TRACE_STMT
, sql_trace_callback
,p
->traceOut
);
7872 #if SQLITE_USER_AUTHENTICATION
7873 if( c
=='u' && strncmp(azArg
[0], "user", n
)==0 ){
7875 raw_printf(stderr
, "Usage: .user SUBCOMMAND ...\n");
7877 goto meta_command_exit
;
7880 if( strcmp(azArg
[1],"login")==0 ){
7882 raw_printf(stderr
, "Usage: .user login USER PASSWORD\n");
7884 goto meta_command_exit
;
7886 rc
= sqlite3_user_authenticate(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]));
7888 utf8_printf(stderr
, "Authentication failed for user %s\n", azArg
[2]);
7891 }else if( strcmp(azArg
[1],"add")==0 ){
7893 raw_printf(stderr
, "Usage: .user add USER PASSWORD ISADMIN\n");
7895 goto meta_command_exit
;
7897 rc
= sqlite3_user_add(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7898 booleanValue(azArg
[4]));
7900 raw_printf(stderr
, "User-Add failed: %d\n", rc
);
7903 }else if( strcmp(azArg
[1],"edit")==0 ){
7905 raw_printf(stderr
, "Usage: .user edit USER PASSWORD ISADMIN\n");
7907 goto meta_command_exit
;
7909 rc
= sqlite3_user_change(p
->db
, azArg
[2], azArg
[3], strlen30(azArg
[3]),
7910 booleanValue(azArg
[4]));
7912 raw_printf(stderr
, "User-Edit failed: %d\n", rc
);
7915 }else if( strcmp(azArg
[1],"delete")==0 ){
7917 raw_printf(stderr
, "Usage: .user delete USER\n");
7919 goto meta_command_exit
;
7921 rc
= sqlite3_user_delete(p
->db
, azArg
[2]);
7923 raw_printf(stderr
, "User-Delete failed: %d\n", rc
);
7927 raw_printf(stderr
, "Usage: .user login|add|edit|delete ...\n");
7929 goto meta_command_exit
;
7932 #endif /* SQLITE_USER_AUTHENTICATION */
7934 if( c
=='v' && strncmp(azArg
[0], "version", n
)==0 ){
7935 utf8_printf(p
->out
, "SQLite %s %s\n" /*extra-version-info*/,
7936 sqlite3_libversion(), sqlite3_sourceid());
7937 #if SQLITE_HAVE_ZLIB
7938 utf8_printf(p
->out
, "zlib version %s\n", zlibVersion());
7940 #define CTIMEOPT_VAL_(opt) #opt
7941 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
7942 #if defined(__clang__) && defined(__clang_major__)
7943 utf8_printf(p
->out
, "clang-" CTIMEOPT_VAL(__clang_major__
) "."
7944 CTIMEOPT_VAL(__clang_minor__
) "."
7945 CTIMEOPT_VAL(__clang_patchlevel__
) "\n");
7946 #elif defined(_MSC_VER)
7947 utf8_printf(p
->out
, "msvc-" CTIMEOPT_VAL(_MSC_VER
) "\n");
7948 #elif defined(__GNUC__) && defined(__VERSION__)
7949 utf8_printf(p
->out
, "gcc-" __VERSION__
"\n");
7953 if( c
=='v' && strncmp(azArg
[0], "vfsinfo", n
)==0 ){
7954 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7955 sqlite3_vfs
*pVfs
= 0;
7957 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFS_POINTER
, &pVfs
);
7959 utf8_printf(p
->out
, "vfs.zName = \"%s\"\n", pVfs
->zName
);
7960 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7961 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7962 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7967 if( c
=='v' && strncmp(azArg
[0], "vfslist", n
)==0 ){
7969 sqlite3_vfs
*pCurrent
= 0;
7971 sqlite3_file_control(p
->db
, "main", SQLITE_FCNTL_VFS_POINTER
, &pCurrent
);
7973 for(pVfs
=sqlite3_vfs_find(0); pVfs
; pVfs
=pVfs
->pNext
){
7974 utf8_printf(p
->out
, "vfs.zName = \"%s\"%s\n", pVfs
->zName
,
7975 pVfs
==pCurrent
? " <--- CURRENT" : "");
7976 raw_printf(p
->out
, "vfs.iVersion = %d\n", pVfs
->iVersion
);
7977 raw_printf(p
->out
, "vfs.szOsFile = %d\n", pVfs
->szOsFile
);
7978 raw_printf(p
->out
, "vfs.mxPathname = %d\n", pVfs
->mxPathname
);
7980 raw_printf(p
->out
, "-----------------------------------\n");
7985 if( c
=='v' && strncmp(azArg
[0], "vfsname", n
)==0 ){
7986 const char *zDbName
= nArg
==2 ? azArg
[1] : "main";
7989 sqlite3_file_control(p
->db
, zDbName
, SQLITE_FCNTL_VFSNAME
, &zVfsName
);
7991 utf8_printf(p
->out
, "%s\n", zVfsName
);
7992 sqlite3_free(zVfsName
);
7997 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7998 if( c
=='w' && strncmp(azArg
[0], "wheretrace", n
)==0 ){
7999 sqlite3WhereTrace
= nArg
>=2 ? booleanValue(azArg
[1]) : 0xff;
8003 if( c
=='w' && strncmp(azArg
[0], "width", n
)==0 ){
8005 assert( nArg
<=ArraySize(azArg
) );
8006 for(j
=1; j
<nArg
&& j
<ArraySize(p
->colWidth
); j
++){
8007 p
->colWidth
[j
-1] = (int)integerValue(azArg
[j
]);
8012 utf8_printf(stderr
, "Error: unknown command or invalid arguments: "
8013 " \"%s\". Enter \".help\" for help\n", azArg
[0]);
8020 if( p
->outCount
==0 ) output_reset(p
);
8026 ** Return TRUE if a semicolon occurs anywhere in the first N characters
8029 static int line_contains_semicolon(const char *z
, int N
){
8031 for(i
=0; i
<N
; i
++){ if( z
[i
]==';' ) return 1; }
8036 ** Test to see if a line consists entirely of whitespace.
8038 static int _all_whitespace(const char *z
){
8040 if( IsSpace(z
[0]) ) continue;
8041 if( *z
=='/' && z
[1]=='*' ){
8043 while( *z
&& (*z
!='*' || z
[1]!='/') ){ z
++; }
8044 if( *z
==0 ) return 0;
8048 if( *z
=='-' && z
[1]=='-' ){
8050 while( *z
&& *z
!='\n' ){ z
++; }
8051 if( *z
==0 ) return 1;
8060 ** Return TRUE if the line typed in is an SQL command terminator other
8061 ** than a semi-colon. The SQL Server style "go" command is understood
8062 ** as is the Oracle "/".
8064 static int line_is_command_terminator(const char *zLine
){
8065 while( IsSpace(zLine
[0]) ){ zLine
++; };
8066 if( zLine
[0]=='/' && _all_whitespace(&zLine
[1]) ){
8067 return 1; /* Oracle */
8069 if( ToLower(zLine
[0])=='g' && ToLower(zLine
[1])=='o'
8070 && _all_whitespace(&zLine
[2]) ){
8071 return 1; /* SQL Server */
8077 ** We need a default sqlite3_complete() implementation to use in case
8078 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
8079 ** any arbitrary text is a complete SQL statement. This is not very
8080 ** user-friendly, but it does seem to work.
8082 #ifdef SQLITE_OMIT_COMPLETE
8083 #define sqlite3_complete(x) 1
8087 ** Return true if zSql is a complete SQL statement. Return false if it
8088 ** ends in the middle of a string literal or C-style comment.
8090 static int line_is_complete(char *zSql
, int nSql
){
8092 if( zSql
==0 ) return 1;
8095 rc
= sqlite3_complete(zSql
);
8101 ** Run a single line of SQL. Return the number of errors.
8103 static int runOneSqlLine(ShellState
*p
, char *zSql
, FILE *in
, int startline
){
8108 if( ShellHasFlag(p
,SHFLG_Backslash
) ) resolve_backslashes(zSql
);
8110 rc
= shell_exec(p
, zSql
, &zErrMsg
);
8112 if( rc
|| zErrMsg
){
8114 if( in
!=0 || !stdin_is_interactive
){
8115 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
,
8116 "Error: near line %d:", startline
);
8118 sqlite3_snprintf(sizeof(zPrefix
), zPrefix
, "Error:");
8121 utf8_printf(stderr
, "%s %s\n", zPrefix
, zErrMsg
);
8122 sqlite3_free(zErrMsg
);
8125 utf8_printf(stderr
, "%s %s\n", zPrefix
, sqlite3_errmsg(p
->db
));
8128 }else if( ShellHasFlag(p
, SHFLG_CountChanges
) ){
8129 raw_printf(p
->out
, "changes: %3d total_changes: %d\n",
8130 sqlite3_changes(p
->db
), sqlite3_total_changes(p
->db
));
8137 ** Read input from *in and process it. If *in==0 then input
8138 ** is interactive - the user is typing it it. Otherwise, input
8139 ** is coming from a file or device. A prompt is issued and history
8140 ** is saved only if input is interactive. An interrupt signal will
8141 ** cause this routine to exit immediately, unless input is interactive.
8143 ** Return the number of errors.
8145 static int process_input(ShellState
*p
, FILE *in
){
8146 char *zLine
= 0; /* A single input line */
8147 char *zSql
= 0; /* Accumulated SQL text */
8148 int nLine
; /* Length of current line */
8149 int nSql
= 0; /* Bytes of zSql[] used */
8150 int nAlloc
= 0; /* Allocated zSql[] space */
8151 int nSqlPrior
= 0; /* Bytes of zSql[] used by prior line */
8152 int rc
; /* Error code */
8153 int errCnt
= 0; /* Number of errors seen */
8154 int lineno
= 0; /* Current line number */
8155 int startline
= 0; /* Line number for start of current input */
8157 while( errCnt
==0 || !bail_on_error
|| (in
==0 && stdin_is_interactive
) ){
8159 zLine
= one_input_line(in
, zLine
, nSql
>0);
8162 if( in
==0 && stdin_is_interactive
) printf("\n");
8165 if( seenInterrupt
){
8170 if( nSql
==0 && _all_whitespace(zLine
) ){
8171 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
8174 if( zLine
&& (zLine
[0]=='.' || zLine
[0]=='#') && nSql
==0 ){
8175 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zLine
);
8176 if( zLine
[0]=='.' ){
8177 rc
= do_meta_command(zLine
, p
);
8178 if( rc
==2 ){ /* exit requested */
8186 if( line_is_command_terminator(zLine
) && line_is_complete(zSql
, nSql
) ){
8187 memcpy(zLine
,";",2);
8189 nLine
= strlen30(zLine
);
8190 if( nSql
+nLine
+2>=nAlloc
){
8191 nAlloc
= nSql
+nLine
+100;
8192 zSql
= realloc(zSql
, nAlloc
);
8193 if( zSql
==0 ) shell_out_of_memory();
8198 for(i
=0; zLine
[i
] && IsSpace(zLine
[i
]); i
++){}
8199 assert( nAlloc
>0 && zSql
!=0 );
8200 memcpy(zSql
, zLine
+i
, nLine
+1-i
);
8204 zSql
[nSql
++] = '\n';
8205 memcpy(zSql
+nSql
, zLine
, nLine
+1);
8208 if( nSql
&& line_contains_semicolon(&zSql
[nSqlPrior
], nSql
-nSqlPrior
)
8209 && sqlite3_complete(zSql
) ){
8210 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
8218 }else if( nSql
&& _all_whitespace(zSql
) ){
8219 if( ShellHasFlag(p
, SHFLG_Echo
) ) printf("%s\n", zSql
);
8223 if( nSql
&& !_all_whitespace(zSql
) ){
8224 errCnt
+= runOneSqlLine(p
, zSql
, in
, startline
);
8232 ** Return a pathname which is the user's home directory. A
8233 ** 0 return indicates an error of some kind.
8235 static char *find_home_dir(int clearFlag
){
8236 static char *home_dir
= NULL
;
8242 if( home_dir
) return home_dir
;
8244 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
8245 && !defined(__RTP__) && !defined(_WRS_KERNEL)
8247 struct passwd
*pwent
;
8248 uid_t uid
= getuid();
8249 if( (pwent
=getpwuid(uid
)) != NULL
) {
8250 home_dir
= pwent
->pw_dir
;
8255 #if defined(_WIN32_WCE)
8256 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
8261 #if defined(_WIN32) || defined(WIN32)
8263 home_dir
= getenv("USERPROFILE");
8268 home_dir
= getenv("HOME");
8271 #if defined(_WIN32) || defined(WIN32)
8273 char *zDrive
, *zPath
;
8275 zDrive
= getenv("HOMEDRIVE");
8276 zPath
= getenv("HOMEPATH");
8277 if( zDrive
&& zPath
){
8278 n
= strlen30(zDrive
) + strlen30(zPath
) + 1;
8279 home_dir
= malloc( n
);
8280 if( home_dir
==0 ) return 0;
8281 sqlite3_snprintf(n
, home_dir
, "%s%s", zDrive
, zPath
);
8288 #endif /* !_WIN32_WCE */
8291 int n
= strlen30(home_dir
) + 1;
8292 char *z
= malloc( n
);
8293 if( z
) memcpy(z
, home_dir
, n
);
8301 ** Read input from the file given by sqliterc_override. Or if that
8302 ** parameter is NULL, take input from ~/.sqliterc
8304 ** Returns the number of errors.
8306 static void process_sqliterc(
8307 ShellState
*p
, /* Configuration data */
8308 const char *sqliterc_override
/* Name of config file. NULL to use default */
8310 char *home_dir
= NULL
;
8311 const char *sqliterc
= sqliterc_override
;
8315 if (sqliterc
== NULL
) {
8316 home_dir
= find_home_dir(0);
8318 raw_printf(stderr
, "-- warning: cannot find home directory;"
8319 " cannot read ~/.sqliterc\n");
8322 zBuf
= sqlite3_mprintf("%s/.sqliterc",home_dir
);
8325 in
= fopen(sqliterc
,"rb");
8327 if( stdin_is_interactive
){
8328 utf8_printf(stderr
,"-- Loading resources from %s\n",sqliterc
);
8330 process_input(p
,in
);
8337 ** Show available command line options
8339 static const char zOptions
[] =
8340 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
8341 " -A ARGS... run \".archive ARGS\" and exit\n"
8343 " -append append the database to the end of the file\n"
8344 " -ascii set output mode to 'ascii'\n"
8345 " -bail stop after hitting an error\n"
8346 " -batch force batch I/O\n"
8347 " -column set output mode to 'column'\n"
8348 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
8349 " -csv set output mode to 'csv'\n"
8350 " -echo print commands before execution\n"
8351 " -init FILENAME read/process named file\n"
8352 " -[no]header turn headers on or off\n"
8353 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8354 " -heap SIZE Size of heap for memsys3 or memsys5\n"
8356 " -help show this message\n"
8357 " -html set output mode to HTML\n"
8358 " -interactive force interactive I/O\n"
8359 " -line set output mode to 'line'\n"
8360 " -list set output mode to 'list'\n"
8361 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
8362 " -mmap N default mmap size set to N\n"
8363 #ifdef SQLITE_ENABLE_MULTIPLEX
8364 " -multiplex enable the multiplexor VFS\n"
8366 " -newline SEP set output row separator. Default: '\\n'\n"
8367 " -nullvalue TEXT set text string for NULL values. Default ''\n"
8368 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
8369 " -quote set output mode to 'quote'\n"
8370 " -readonly open the database read-only\n"
8371 " -separator SEP set output column separator. Default: '|'\n"
8372 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8373 " -sorterref SIZE sorter references threshold size\n"
8375 " -stats print memory stats before each finalize\n"
8376 " -version show SQLite version\n"
8377 " -vfs NAME use NAME as the default VFS\n"
8378 #ifdef SQLITE_ENABLE_VFSTRACE
8379 " -vfstrace enable tracing of all VFS calls\n"
8381 #ifdef SQLITE_HAVE_ZLIB
8382 " -zip open the file as a ZIP Archive\n"
8385 static void usage(int showDetail
){
8387 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
8388 "FILENAME is the name of an SQLite database. A new database is created\n"
8389 "if the file does not previously exist.\n", Argv0
);
8391 utf8_printf(stderr
, "OPTIONS include:\n%s", zOptions
);
8393 raw_printf(stderr
, "Use the -help option for additional information\n");
8399 ** Internal check: Verify that the SQLite is uninitialized. Print a
8400 ** error message if it is initialized.
8402 static void verify_uninitialized(void){
8403 if( sqlite3_config(-1)==SQLITE_MISUSE
){
8404 utf8_printf(stdout
, "WARNING: attempt to configure SQLite after"
8405 " initialization.\n");
8410 ** Initialize the state information in data
8412 static void main_init(ShellState
*data
) {
8413 memset(data
, 0, sizeof(*data
));
8414 data
->normalMode
= data
->cMode
= data
->mode
= MODE_List
;
8415 data
->autoExplain
= 1;
8416 memcpy(data
->colSeparator
,SEP_Column
, 2);
8417 memcpy(data
->rowSeparator
,SEP_Row
, 2);
8418 data
->showHeader
= 0;
8419 data
->shellFlgs
= SHFLG_Lookaside
;
8420 verify_uninitialized();
8421 sqlite3_config(SQLITE_CONFIG_URI
, 1);
8422 sqlite3_config(SQLITE_CONFIG_LOG
, shellLog
, data
);
8423 sqlite3_config(SQLITE_CONFIG_MULTITHREAD
);
8424 sqlite3_snprintf(sizeof(mainPrompt
), mainPrompt
,"sqlite> ");
8425 sqlite3_snprintf(sizeof(continuePrompt
), continuePrompt
," ...> ");
8429 ** Output text to the console in a font that attracts extra attention.
8432 static void printBold(const char *zText
){
8433 HANDLE out
= GetStdHandle(STD_OUTPUT_HANDLE
);
8434 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo
;
8435 GetConsoleScreenBufferInfo(out
, &defaultScreenInfo
);
8436 SetConsoleTextAttribute(out
,
8437 FOREGROUND_RED
|FOREGROUND_INTENSITY
8439 printf("%s", zText
);
8440 SetConsoleTextAttribute(out
, defaultScreenInfo
.wAttributes
);
8443 static void printBold(const char *zText
){
8444 printf("\033[1m%s\033[0m", zText
);
8449 ** Get the argument to an --option. Throw an error and die if no argument
8452 static char *cmdline_option_value(int argc
, char **argv
, int i
){
8454 utf8_printf(stderr
, "%s: Error: missing argument to %s\n",
8455 argv
[0], argv
[argc
-1]);
8461 #ifndef SQLITE_SHELL_IS_UTF8
8462 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
8463 # define SQLITE_SHELL_IS_UTF8 (0)
8465 # define SQLITE_SHELL_IS_UTF8 (1)
8469 #if SQLITE_SHELL_IS_UTF8
8470 int SQLITE_CDECL
main(int argc
, char **argv
){
8472 int SQLITE_CDECL
wmain(int argc
, wchar_t **wargv
){
8477 const char *zInitFile
= 0;
8480 int warnInmemoryDb
= 0;
8484 const char *zVfs
= 0; /* Value of -vfs command-line option */
8485 #if !SQLITE_SHELL_IS_UTF8
8486 char **argvToFree
= 0;
8490 setBinaryMode(stdin
, 0);
8491 setvbuf(stderr
, 0, _IONBF
, 0); /* Make sure stderr is unbuffered */
8492 stdin_is_interactive
= isatty(0);
8493 stdout_is_console
= isatty(1);
8495 #if !defined(_WIN32_WCE)
8496 if( getenv("SQLITE_DEBUG_BREAK") ){
8497 if( isatty(0) && isatty(2) ){
8499 "attach debugger to process %d and press any key to continue.\n",
8503 #if defined(_WIN32) || defined(WIN32)
8505 #elif defined(SIGTRAP)
8512 #if USE_SYSTEM_SQLITE+0!=1
8513 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID
,60)!=0 ){
8514 utf8_printf(stderr
, "SQLite header and source version mismatch\n%s\n%s\n",
8515 sqlite3_sourceid(), SQLITE_SOURCE_ID
);
8521 /* On Windows, we must translate command-line arguments into UTF-8.
8522 ** The SQLite memory allocator subsystem has to be enabled in order to
8523 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
8524 ** subsequent sqlite3_config() calls will work. So copy all results into
8525 ** memory that does not come from the SQLite memory allocator.
8527 #if !SQLITE_SHELL_IS_UTF8
8528 sqlite3_initialize();
8529 argvToFree
= malloc(sizeof(argv
[0])*argc
*2);
8531 argv
= argvToFree
+ argc
;
8532 if( argv
==0 ) shell_out_of_memory();
8533 for(i
=0; i
<argc
; i
++){
8534 char *z
= sqlite3_win32_unicode_to_utf8(wargv
[i
]);
8536 if( z
==0 ) shell_out_of_memory();
8538 argv
[i
] = malloc( n
+1 );
8539 if( argv
[i
]==0 ) shell_out_of_memory();
8540 memcpy(argv
[i
], z
, n
+1);
8541 argvToFree
[i
] = argv
[i
];
8547 assert( argc
>=1 && argv
&& argv
[0] );
8550 /* Make sure we have a valid signal handler early, before anything
8554 signal(SIGINT
, interrupt_handler
);
8555 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
8556 SetConsoleCtrlHandler(ConsoleCtrlHandler
, TRUE
);
8559 #ifdef SQLITE_SHELL_DBNAME_PROC
8561 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8562 ** of a C-function that will provide the name of the database file. Use
8563 ** this compile-time option to embed this shell program in larger
8565 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8566 SQLITE_SHELL_DBNAME_PROC(&data
.zDbFilename
);
8571 /* Do an initial pass through the command-line argument to locate
8572 ** the name of the database file, the name of the initialization file,
8573 ** the size of the alternative malloc heap,
8574 ** and the first command to execute.
8576 verify_uninitialized();
8577 for(i
=1; i
<argc
; i
++){
8581 if( data
.zDbFilename
==0 ){
8582 data
.zDbFilename
= z
;
8584 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8585 ** mean that nothing is read from stdin */
8588 azCmd
= realloc(azCmd
, sizeof(azCmd
[0])*nCmd
);
8589 if( azCmd
==0 ) shell_out_of_memory();
8593 if( z
[1]=='-' ) z
++;
8594 if( strcmp(z
,"-separator")==0
8595 || strcmp(z
,"-nullvalue")==0
8596 || strcmp(z
,"-newline")==0
8597 || strcmp(z
,"-cmd")==0
8599 (void)cmdline_option_value(argc
, argv
, ++i
);
8600 }else if( strcmp(z
,"-init")==0 ){
8601 zInitFile
= cmdline_option_value(argc
, argv
, ++i
);
8602 }else if( strcmp(z
,"-batch")==0 ){
8603 /* Need to check for batch mode here to so we can avoid printing
8604 ** informational messages (like from process_sqliterc) before
8605 ** we do the actual processing of arguments later in a second pass.
8607 stdin_is_interactive
= 0;
8608 }else if( strcmp(z
,"-heap")==0 ){
8609 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
8611 sqlite3_int64 szHeap
;
8613 zSize
= cmdline_option_value(argc
, argv
, ++i
);
8614 szHeap
= integerValue(zSize
);
8615 if( szHeap
>0x7fff0000 ) szHeap
= 0x7fff0000;
8616 sqlite3_config(SQLITE_CONFIG_HEAP
, malloc((int)szHeap
), (int)szHeap
, 64);
8618 (void)cmdline_option_value(argc
, argv
, ++i
);
8620 }else if( strcmp(z
,"-pagecache")==0 ){
8622 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8623 if( sz
>70000 ) sz
= 70000;
8625 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8626 sqlite3_config(SQLITE_CONFIG_PAGECACHE
,
8627 (n
>0 && sz
>0) ? malloc(n
*sz
) : 0, sz
, n
);
8628 data
.shellFlgs
|= SHFLG_Pagecache
;
8629 }else if( strcmp(z
,"-lookaside")==0 ){
8631 sz
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8633 n
= (int)integerValue(cmdline_option_value(argc
,argv
,++i
));
8635 sqlite3_config(SQLITE_CONFIG_LOOKASIDE
, sz
, n
);
8636 if( sz
*n
==0 ) data
.shellFlgs
&= ~SHFLG_Lookaside
;
8637 #ifdef SQLITE_ENABLE_VFSTRACE
8638 }else if( strcmp(z
,"-vfstrace")==0 ){
8639 extern int vfstrace_register(
8640 const char *zTraceName
,
8641 const char *zOldVfsName
,
8642 int (*xOut
)(const char*,void*),
8646 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs
,stderr
,1);
8648 #ifdef SQLITE_ENABLE_MULTIPLEX
8649 }else if( strcmp(z
,"-multiplex")==0 ){
8650 extern int sqlite3_multiple_initialize(const char*,int);
8651 sqlite3_multiplex_initialize(0, 1);
8653 }else if( strcmp(z
,"-mmap")==0 ){
8654 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8655 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE
, sz
, sz
);
8656 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8657 }else if( strcmp(z
,"-sorterref")==0 ){
8658 sqlite3_int64 sz
= integerValue(cmdline_option_value(argc
,argv
,++i
));
8659 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE
, (int)sz
);
8661 }else if( strcmp(z
,"-vfs")==0 ){
8662 zVfs
= cmdline_option_value(argc
, argv
, ++i
);
8663 #ifdef SQLITE_HAVE_ZLIB
8664 }else if( strcmp(z
,"-zip")==0 ){
8665 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8667 }else if( strcmp(z
,"-append")==0 ){
8668 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8669 #ifdef SQLITE_ENABLE_DESERIALIZE
8670 }else if( strcmp(z
,"-deserialize")==0 ){
8671 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
8673 }else if( strcmp(z
,"-readonly")==0 ){
8674 data
.openMode
= SHELL_OPEN_READONLY
;
8675 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8676 }else if( strncmp(z
, "-A",2)==0 ){
8677 /* All remaining command-line arguments are passed to the ".archive"
8678 ** command, so ignore them */
8683 verify_uninitialized();
8686 #ifdef SQLITE_SHELL_INIT_PROC
8688 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
8689 ** of a C-function that will perform initialization actions on SQLite that
8690 ** occur just before or after sqlite3_initialize(). Use this compile-time
8691 ** option to embed this shell program in larger applications. */
8692 extern void SQLITE_SHELL_INIT_PROC(void);
8693 SQLITE_SHELL_INIT_PROC();
8696 /* All the sqlite3_config() calls have now been made. So it is safe
8697 ** to call sqlite3_initialize() and process any command line -vfs option. */
8698 sqlite3_initialize();
8702 sqlite3_vfs
*pVfs
= sqlite3_vfs_find(zVfs
);
8704 sqlite3_vfs_register(pVfs
, 1);
8706 utf8_printf(stderr
, "no such VFS: \"%s\"\n", argv
[i
]);
8711 if( data
.zDbFilename
==0 ){
8712 #ifndef SQLITE_OMIT_MEMORYDB
8713 data
.zDbFilename
= ":memory:";
8714 warnInmemoryDb
= argc
==1;
8716 utf8_printf(stderr
,"%s: Error: no database filename specified\n", Argv0
);
8721 sqlite3_appendvfs_init(0,0,0);
8723 /* Go ahead and open the database file if it already exists. If the
8724 ** file does not exist, delay opening it. This prevents empty database
8725 ** files from being created if a user mistypes the database name argument
8726 ** to the sqlite command-line tool.
8728 if( access(data
.zDbFilename
, 0)==0 ){
8732 /* Process the initialization file if there is one. If no -init option
8733 ** is given on the command line, look for a file named ~/.sqliterc and
8734 ** try to process it.
8736 process_sqliterc(&data
,zInitFile
);
8738 /* Make a second pass through the command-line argument and set
8739 ** options. This second pass is delayed until after the initialization
8740 ** file is processed so that the command-line arguments will override
8741 ** settings in the initialization file.
8743 for(i
=1; i
<argc
; i
++){
8745 if( z
[0]!='-' ) continue;
8746 if( z
[1]=='-' ){ z
++; }
8747 if( strcmp(z
,"-init")==0 ){
8749 }else if( strcmp(z
,"-html")==0 ){
8750 data
.mode
= MODE_Html
;
8751 }else if( strcmp(z
,"-list")==0 ){
8752 data
.mode
= MODE_List
;
8753 }else if( strcmp(z
,"-quote")==0 ){
8754 data
.mode
= MODE_Quote
;
8755 }else if( strcmp(z
,"-line")==0 ){
8756 data
.mode
= MODE_Line
;
8757 }else if( strcmp(z
,"-column")==0 ){
8758 data
.mode
= MODE_Column
;
8759 }else if( strcmp(z
,"-csv")==0 ){
8760 data
.mode
= MODE_Csv
;
8761 memcpy(data
.colSeparator
,",",2);
8762 #ifdef SQLITE_HAVE_ZLIB
8763 }else if( strcmp(z
,"-zip")==0 ){
8764 data
.openMode
= SHELL_OPEN_ZIPFILE
;
8766 }else if( strcmp(z
,"-append")==0 ){
8767 data
.openMode
= SHELL_OPEN_APPENDVFS
;
8768 #ifdef SQLITE_ENABLE_DESERIALIZE
8769 }else if( strcmp(z
,"-deserialize")==0 ){
8770 data
.openMode
= SHELL_OPEN_DESERIALIZE
;
8772 }else if( strcmp(z
,"-readonly")==0 ){
8773 data
.openMode
= SHELL_OPEN_READONLY
;
8774 }else if( strcmp(z
,"-ascii")==0 ){
8775 data
.mode
= MODE_Ascii
;
8776 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8778 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8780 }else if( strcmp(z
,"-separator")==0 ){
8781 sqlite3_snprintf(sizeof(data
.colSeparator
), data
.colSeparator
,
8782 "%s",cmdline_option_value(argc
,argv
,++i
));
8783 }else if( strcmp(z
,"-newline")==0 ){
8784 sqlite3_snprintf(sizeof(data
.rowSeparator
), data
.rowSeparator
,
8785 "%s",cmdline_option_value(argc
,argv
,++i
));
8786 }else if( strcmp(z
,"-nullvalue")==0 ){
8787 sqlite3_snprintf(sizeof(data
.nullValue
), data
.nullValue
,
8788 "%s",cmdline_option_value(argc
,argv
,++i
));
8789 }else if( strcmp(z
,"-header")==0 ){
8790 data
.showHeader
= 1;
8791 }else if( strcmp(z
,"-noheader")==0 ){
8792 data
.showHeader
= 0;
8793 }else if( strcmp(z
,"-echo")==0 ){
8794 ShellSetFlag(&data
, SHFLG_Echo
);
8795 }else if( strcmp(z
,"-eqp")==0 ){
8796 data
.autoEQP
= AUTOEQP_on
;
8797 }else if( strcmp(z
,"-eqpfull")==0 ){
8798 data
.autoEQP
= AUTOEQP_full
;
8799 }else if( strcmp(z
,"-stats")==0 ){
8801 }else if( strcmp(z
,"-scanstats")==0 ){
8802 data
.scanstatsOn
= 1;
8803 }else if( strcmp(z
,"-backslash")==0 ){
8804 /* Undocumented command-line option: -backslash
8805 ** Causes C-style backslash escapes to be evaluated in SQL statements
8806 ** prior to sending the SQL into SQLite. Useful for injecting
8807 ** crazy bytes in the middle of SQL statements for testing and debugging.
8809 ShellSetFlag(&data
, SHFLG_Backslash
);
8810 }else if( strcmp(z
,"-bail")==0 ){
8812 }else if( strcmp(z
,"-version")==0 ){
8813 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
8815 }else if( strcmp(z
,"-interactive")==0 ){
8816 stdin_is_interactive
= 1;
8817 }else if( strcmp(z
,"-batch")==0 ){
8818 stdin_is_interactive
= 0;
8819 }else if( strcmp(z
,"-heap")==0 ){
8821 }else if( strcmp(z
,"-pagecache")==0 ){
8823 }else if( strcmp(z
,"-lookaside")==0 ){
8825 }else if( strcmp(z
,"-mmap")==0 ){
8827 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
8828 }else if( strcmp(z
,"-sorterref")==0 ){
8831 }else if( strcmp(z
,"-vfs")==0 ){
8833 #ifdef SQLITE_ENABLE_VFSTRACE
8834 }else if( strcmp(z
,"-vfstrace")==0 ){
8837 #ifdef SQLITE_ENABLE_MULTIPLEX
8838 }else if( strcmp(z
,"-multiplex")==0 ){
8841 }else if( strcmp(z
,"-help")==0 ){
8843 }else if( strcmp(z
,"-cmd")==0 ){
8844 /* Run commands that follow -cmd first and separately from commands
8845 ** that simply appear on the command-line. This seems goofy. It would
8846 ** be better if all commands ran in the order that they appear. But
8847 ** we retain the goofy behavior for historical compatibility. */
8848 if( i
==argc
-1 ) break;
8849 z
= cmdline_option_value(argc
,argv
,++i
);
8851 rc
= do_meta_command(z
, &data
);
8852 if( rc
&& bail_on_error
) return rc
==2 ? 0 : rc
;
8855 rc
= shell_exec(&data
, z
, &zErrMsg
);
8857 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8858 if( bail_on_error
) return rc
!=0 ? rc
: 1;
8860 utf8_printf(stderr
,"Error: unable to process SQL \"%s\"\n", z
);
8861 if( bail_on_error
) return rc
;
8864 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
8865 }else if( strncmp(z
, "-A", 2)==0 ){
8867 utf8_printf(stderr
, "Error: cannot mix regular SQL or dot-commands"
8868 " with \"%s\"\n", z
);
8871 open_db(&data
, OPEN_DB_ZIPFILE
);
8874 arDotCommand(&data
, 1, argv
+(i
-1), argc
-(i
-1));
8876 arDotCommand(&data
, 1, argv
+i
, argc
-i
);
8882 utf8_printf(stderr
,"%s: Error: unknown option: %s\n", Argv0
, z
);
8883 raw_printf(stderr
,"Use -help for a list of options.\n");
8886 data
.cMode
= data
.mode
;
8890 /* Run all arguments that do not begin with '-' as if they were separate
8891 ** command-line inputs, except for the argToSkip argument which contains
8892 ** the database filename.
8894 for(i
=0; i
<nCmd
; i
++){
8895 if( azCmd
[i
][0]=='.' ){
8896 rc
= do_meta_command(azCmd
[i
], &data
);
8897 if( rc
) return rc
==2 ? 0 : rc
;
8900 rc
= shell_exec(&data
, azCmd
[i
], &zErrMsg
);
8902 utf8_printf(stderr
,"Error: %s\n", zErrMsg
);
8903 return rc
!=0 ? rc
: 1;
8905 utf8_printf(stderr
,"Error: unable to process SQL: %s\n", azCmd
[i
]);
8912 /* Run commands received from standard input
8914 if( stdin_is_interactive
){
8919 /* BEGIN SQLCIPHER */
8920 #ifdef SQLITE_HAS_CODEC
8921 "SQLCipher version %s %.19s\n" /*extra-version-info*/
8923 "SQLite version %s %.19s\n" /*extra-version-info*/
8926 "Enter \".help\" for usage hints.\n",
8927 sqlite3_libversion(), sqlite3_sourceid()
8929 if( warnInmemoryDb
){
8930 printf("Connected to a ");
8931 printBold("transient in-memory database");
8932 printf(".\nUse \".open FILENAME\" to reopen on a "
8933 "persistent database.\n");
8935 zHistory
= getenv("SQLITE_HISTORY");
8937 zHistory
= strdup(zHistory
);
8938 }else if( (zHome
= find_home_dir(0))!=0 ){
8939 nHistory
= strlen30(zHome
) + 20;
8940 if( (zHistory
= malloc(nHistory
))!=0 ){
8941 sqlite3_snprintf(nHistory
, zHistory
,"%s/.sqlite_history", zHome
);
8944 if( zHistory
){ shell_read_history(zHistory
); }
8945 #if HAVE_READLINE || HAVE_EDITLINE
8946 rl_attempted_completion_function
= readline_completion
;
8947 #elif HAVE_LINENOISE
8948 linenoiseSetCompletionCallback(linenoise_completion
);
8950 rc
= process_input(&data
, 0);
8952 shell_stifle_history(2000);
8953 shell_write_history(zHistory
);
8957 rc
= process_input(&data
, stdin
);
8960 set_table_name(&data
, 0);
8962 session_close_all(&data
);
8965 sqlite3_free(data
.zFreeOnClose
);
8967 output_reset(&data
);
8969 clearTempFile(&data
);
8970 #if !SQLITE_SHELL_IS_UTF8
8971 for(i
=0; i
<argcToFree
; i
++) free(argvToFree
[i
]);
8974 /* Clear the global data structure so that valgrind will detect memory
8976 memset(&data
, 0, sizeof(data
));