2 ** This file is automatically generated by the script in the canonical
3 ** SQLite source tree at tool/mkshellc.tcl. That script combines source
4 ** code from various constituent source files of SQLite into this single
5 ** "shell.c" file used to implement the SQLite command-line shell.
7 ** Most of the code found below comes from the "src/shell.c.in" file in
8 ** the canonical SQLite source tree. That main file contains "INCLUDE"
9 ** lines that specify other files in the canonical source tree that are
10 ** inserted to getnerate this complete program source file.
12 ** The code from multiple files is combined into this single "shell.c"
13 ** source file to help make the command-line program easier to compile.
15 ** To modify this program, get a copy of the canonical SQLite source tree,
16 ** edit the src/shell.c.in" and/or some of the other files that are included
17 ** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
22 ** The author disclaims copyright to this source code. In place of
23 ** a legal notice, here is a blessing:
25 ** May you do good and not evil.
26 ** May you find forgiveness for yourself and forgive others.
27 ** May you share freely, never taking more than you give.
29 *************************************************************************
30 ** This file contains code to implement the "sqlite" command line
31 ** utility for accessing SQLite databases.
33 #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
34 /* This needs to come before any includes for MSVC compiler */
35 #define _CRT_SECURE_NO_WARNINGS
39 ** Warning pragmas copied from msvc.h in the core.
42 #pragma warning(disable : 4054)
43 #pragma warning(disable : 4055)
44 #pragma warning(disable : 4100)
45 #pragma warning(disable : 4127)
46 #pragma warning(disable : 4130)
47 #pragma warning(disable : 4152)
48 #pragma warning(disable : 4189)
49 #pragma warning(disable : 4206)
50 #pragma warning(disable : 4210)
51 #pragma warning(disable : 4232)
52 #pragma warning(disable : 4244)
53 #pragma warning(disable : 4305)
54 #pragma warning(disable : 4306)
55 #pragma warning(disable : 4702)
56 #pragma warning(disable : 4706)
57 #endif /* defined(_MSC_VER) */
60 ** No support for loadable extensions in VxWorks.
62 #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
63 # define SQLITE_OMIT_LOAD_EXTENSION 1
67 ** Enable large-file support for fopen() and friends on unix.
69 #ifndef SQLITE_DISABLE_LFS
70 # define _LARGE_FILE 1
71 # ifndef _FILE_OFFSET_BITS
72 # define _FILE_OFFSET_BITS 64
74 # define _LARGEFILE_SOURCE 1
82 typedef sqlite3_int64 i64;
83 typedef sqlite3_uint64 u64;
84 typedef unsigned char u8;
85 #if SQLITE_USER_AUTHENTICATION
86 # include "sqlite3userauth.h"
91 #if !defined(_WIN32) && !defined(WIN32)
93 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
97 #if (!defined(_WIN32) && !defined(WIN32)) || defined(__MINGW32__)
100 # define GETPID getpid
101 # if defined(__MINGW32__)
102 # define DIRENT dirent
104 # define S_ISLNK(mode) (0)
108 # define GETPID (int)GetCurrentProcessId
110 #include <sys/types.h>
111 #include <sys/stat.h>
114 # include <readline/readline.h>
115 # include <readline/history.h>
119 # include <editline/readline.h>
122 #if HAVE_EDITLINE || HAVE_READLINE
124 # define shell_add_history(X) add_history(X)
125 # define shell_read_history(X) read_history(X)
126 # define shell_write_history(X) write_history(X)
127 # define shell_stifle_history(X) stifle_history(X)
128 # define shell_readline(X) readline(X)
132 # include "linenoise.h"
133 # define shell_add_history(X) linenoiseHistoryAdd(X)
134 # define shell_read_history(X) linenoiseHistoryLoad(X)
135 # define shell_write_history(X) linenoiseHistorySave(X)
136 # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
137 # define shell_readline(X) linenoise(X)
141 # define shell_read_history(X)
142 # define shell_write_history(X)
143 # define shell_stifle_history(X)
145 # define SHELL_USE_LOCAL_GETLINE 1
149 #if defined(_WIN32) || defined(WIN32)
152 # define isatty(h) _isatty(h)
154 # define access(f,m) _access((f),(m))
157 # define unlink _unlink
160 # define popen _popen
162 # define pclose _pclose
164 /* Make sure isatty() has a prototype. */
165 extern int isatty(int);
167 # if !defined(__RTP__) && !defined(_WRS_KERNEL)
168 /* popen and pclose are not C89 functions and so are
169 ** sometimes omitted from the <stdio.h> header */
170 extern FILE *popen(const char*,const char*);
171 extern int pclose(FILE*);
173 # define SQLITE_OMIT_POPEN 1
177 #if defined(_WIN32_WCE)
178 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
179 * thus we always assume that we have a console. That can be
180 * overridden with the -batch command line option.
185 /* ctype macros that work with signed characters */
186 #define IsSpace(X) isspace((unsigned char)X)
187 #define IsDigit(X) isdigit((unsigned char)X)
188 #define ToLower(X) (char)tolower((unsigned char)X)
190 #if defined(_WIN32) || defined(WIN32)
193 /* string conversion routines only needed on Win32 */
194 extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
195 extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
196 extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
197 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
200 /* On Windows, we normally run with output mode of TEXT so that \n characters
201 ** are automatically translated into \r\n. However, this behavior needs
202 ** to be disabled in some cases (ex: when generating CSV output and when
203 ** rendering quoted strings that contain \n characters). The following
204 ** routines take care of that.
206 #if defined(_WIN32) || defined(WIN32)
207 static void setBinaryMode(FILE *file, int isOutput){
208 if( isOutput ) fflush(file);
209 _setmode(_fileno(file), _O_BINARY);
211 static void setTextMode(FILE *file, int isOutput){
212 if( isOutput ) fflush(file);
213 _setmode(_fileno(file), _O_TEXT);
216 # define setBinaryMode(X,Y)
217 # define setTextMode(X,Y)
221 /* True if the timer is enabled */
222 static int enableTimer = 0;
224 /* Return the current wall-clock time */
225 static sqlite3_int64 timeOfDay(void){
226 static sqlite3_vfs *clockVfs = 0;
228 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
229 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
230 clockVfs->xCurrentTimeInt64(clockVfs, &t);
233 clockVfs->xCurrentTime(clockVfs, &r);
234 t = (sqlite3_int64)(r*86400000.0);
239 #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
240 #include <sys/time.h>
241 #include <sys/resource.h>
243 /* VxWorks does not support getrusage() as far as we can determine */
244 #if defined(_WRS_KERNEL) || defined(__RTP__)
246 struct timeval ru_utime; /* user CPU time used */
247 struct timeval ru_stime; /* system CPU time used */
249 #define getrusage(A,B) memset(B,0,sizeof(*B))
252 /* Saved resource information for the beginning of an operation */
253 static struct rusage sBegin; /* CPU time at start */
254 static sqlite3_int64 iBegin; /* Wall-clock time at start */
257 ** Begin timing an operation
259 static void beginTimer(void){
261 getrusage(RUSAGE_SELF, &sBegin);
262 iBegin = timeOfDay();
266 /* Return the difference of two time_structs in seconds */
267 static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
268 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
269 (double)(pEnd->tv_sec - pStart->tv_sec);
273 ** Print the timing results.
275 static void endTimer(void){
277 sqlite3_int64 iEnd = timeOfDay();
279 getrusage(RUSAGE_SELF, &sEnd);
280 printf("Run Time: real %.3f user %f sys %f\n",
281 (iEnd - iBegin)*0.001,
282 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
283 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
287 #define BEGIN_TIMER beginTimer()
288 #define END_TIMER endTimer()
291 #elif (defined(_WIN32) || defined(WIN32))
293 /* Saved resource information for the beginning of an operation */
294 static HANDLE hProcess;
295 static FILETIME ftKernelBegin;
296 static FILETIME ftUserBegin;
297 static sqlite3_int64 ftWallBegin;
298 typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
299 LPFILETIME, LPFILETIME);
300 static GETPROCTIMES getProcessTimesAddr = NULL;
303 ** Check to see if we have timer support. Return 1 if necessary
304 ** support found (or found previously).
306 static int hasTimer(void){
307 if( getProcessTimesAddr ){
310 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
311 ** versions. See if the version we are running on has it, and if it
312 ** does, save off a pointer to it and the current process handle.
314 hProcess = GetCurrentProcess();
316 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
317 if( NULL != hinstLib ){
318 getProcessTimesAddr =
319 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
320 if( NULL != getProcessTimesAddr ){
323 FreeLibrary(hinstLib);
331 ** Begin timing an operation
333 static void beginTimer(void){
334 if( enableTimer && getProcessTimesAddr ){
335 FILETIME ftCreation, ftExit;
336 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
337 &ftKernelBegin,&ftUserBegin);
338 ftWallBegin = timeOfDay();
342 /* Return the difference of two FILETIME structs in seconds */
343 static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
344 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
345 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
346 return (double) ((i64End - i64Start) / 10000000.0);
350 ** Print the timing results.
352 static void endTimer(void){
353 if( enableTimer && getProcessTimesAddr){
354 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
355 sqlite3_int64 ftWallEnd = timeOfDay();
356 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
357 printf("Run Time: real %.3f user %f sys %f\n",
358 (ftWallEnd - ftWallBegin)*0.001,
359 timeDiff(&ftUserBegin, &ftUserEnd),
360 timeDiff(&ftKernelBegin, &ftKernelEnd));
364 #define BEGIN_TIMER beginTimer()
365 #define END_TIMER endTimer()
366 #define HAS_TIMER hasTimer()
375 ** Used to prevent warnings about unused parameters
377 #define UNUSED_PARAMETER(x) (void)(x)
380 ** Number of elements in an array
382 #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
385 ** If the following flag is set, then command execution stops
386 ** at an error if we are not interactive.
388 static int bail_on_error = 0;
391 ** Threat stdin as an interactive input if the following variable
392 ** is true. Otherwise, assume stdin is connected to a file or pipe.
394 static int stdin_is_interactive = 1;
397 ** On Windows systems we have to know if standard output is a console
398 ** in order to translate UTF-8 into MBCS. The following variable is
399 ** true if translation is required.
401 static int stdout_is_console = 1;
404 ** The following is the open SQLite database. We make a pointer
405 ** to this database a static variable so that it can be accessed
406 ** by the SIGINT handler to interrupt database processing.
408 static sqlite3 *globalDb = 0;
411 ** True if an interrupt (Control-C) has been received.
413 static volatile int seenInterrupt = 0;
416 ** This is the name of our program. It is set in main(), used
417 ** in a number of other places, mostly for error messages.
422 ** Prompt strings. Initialized in main. Settable with
423 ** .prompt main continue
425 static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
426 static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
429 ** Render output like fprintf(). Except, if the output is going to the
430 ** console and if this is running on a Windows machine, translate the
431 ** output from UTF-8 into MBCS.
433 #if defined(_WIN32) || defined(WIN32)
434 void utf8_printf(FILE *out, const char *zFormat, ...){
436 va_start(ap, zFormat);
437 if( stdout_is_console && (out==stdout || out==stderr) ){
438 char *z1 = sqlite3_vmprintf(zFormat, ap);
439 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
444 vfprintf(out, zFormat, ap);
448 #elif !defined(utf8_printf)
449 # define utf8_printf fprintf
453 ** Render output like fprintf(). This should not be used on anything that
454 ** includes string formatting (e.g. "%s").
456 #if !defined(raw_printf)
457 # define raw_printf fprintf
460 /* Indicate out-of-memory and exit. */
461 static void shell_out_of_memory(void){
462 raw_printf(stderr,"Error: out of memory\n");
467 ** Write I/O traces to the following stream.
469 #ifdef SQLITE_ENABLE_IOTRACE
470 static FILE *iotrace = 0;
474 ** This routine works like printf in that its first argument is a
475 ** format string and subsequent arguments are values to be substituted
476 ** in place of % fields. The result of formatting this string
477 ** is written to iotrace.
479 #ifdef SQLITE_ENABLE_IOTRACE
480 static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
483 if( iotrace==0 ) return;
484 va_start(ap, zFormat);
485 z = sqlite3_vmprintf(zFormat, ap);
487 utf8_printf(iotrace, "%s", z);
493 ** Output string zUtf to stream pOut as w characters. If w is negative,
494 ** then right-justify the text. W is the width in UTF-8 characters, not
495 ** in bytes. This is different from the %*.*s specification in printf
496 ** since with %*.*s the width is measured in bytes, not characters.
498 static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
501 int aw = w<0 ? -w : w;
503 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
504 for(i=n=0; zUtf[i]; i++){
505 if( (zUtf[i]&0xc0)!=0x80 ){
508 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
514 utf8_printf(pOut, "%.*s", i, zUtf);
516 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
518 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
524 ** Determines if a string is a number of not.
526 static int isNumber(const char *z, int *realnum){
527 if( *z=='-' || *z=='+' ) z++;
532 if( realnum ) *realnum = 0;
533 while( IsDigit(*z) ){ z++; }
536 if( !IsDigit(*z) ) return 0;
537 while( IsDigit(*z) ){ z++; }
538 if( realnum ) *realnum = 1;
540 if( *z=='e' || *z=='E' ){
542 if( *z=='+' || *z=='-' ) z++;
543 if( !IsDigit(*z) ) return 0;
544 while( IsDigit(*z) ){ z++; }
545 if( realnum ) *realnum = 1;
551 ** Compute a string length that is limited to what can be stored in
552 ** lower 30 bits of a 32-bit signed integer.
554 static int strlen30(const char *z){
556 while( *z2 ){ z2++; }
557 return 0x3fffffff & (int)(z2 - z);
561 ** Return the length of a string in characters. Multibyte UTF8 characters
562 ** count as a single character.
564 static int strlenChar(const char *z){
567 if( (0xc0&*(z++))!=0x80 ) n++;
573 ** This routine reads a line of text from FILE in, stores
574 ** the text in memory obtained from malloc() and returns a pointer
575 ** to the text. NULL is returned at end of file, or if malloc()
578 ** If zLine is not NULL then it is a malloced buffer returned from
579 ** a previous call to this routine that may be reused.
581 static char *local_getline(char *zLine, FILE *in){
582 int nLine = zLine==0 ? 0 : 100;
587 nLine = nLine*2 + 100;
588 zLine = realloc(zLine, nLine);
589 if( zLine==0 ) shell_out_of_memory();
591 if( fgets(&zLine[n], nLine - n, in)==0 ){
599 while( zLine[n] ) n++;
600 if( n>0 && zLine[n-1]=='\n' ){
602 if( n>0 && zLine[n-1]=='\r' ) n--;
607 #if defined(_WIN32) || defined(WIN32)
608 /* For interactive input on Windows systems, translate the
609 ** multi-byte characterset characters into UTF-8. */
610 if( stdin_is_interactive && in==stdin ){
611 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
613 int nTrans = strlen30(zTrans)+1;
615 zLine = realloc(zLine, nTrans);
616 if( zLine==0 ) shell_out_of_memory();
618 memcpy(zLine, zTrans, nTrans);
619 sqlite3_free(zTrans);
622 #endif /* defined(_WIN32) || defined(WIN32) */
627 ** Retrieve a single line of input text.
629 ** If in==0 then read from standard input and prompt before each line.
630 ** If isContinuation is true, then a continuation prompt is appropriate.
631 ** If isContinuation is zero, then the main prompt should be used.
633 ** If zPrior is not NULL then it is a buffer from a prior call to this
634 ** routine that can be reused.
636 ** The result is stored in space obtained from malloc() and must either
637 ** be freed by the caller or else passed back into this routine via the
638 ** zPrior argument for reuse.
640 static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
644 zResult = local_getline(zPrior, in);
646 zPrompt = isContinuation ? continuePrompt : mainPrompt;
647 #if SHELL_USE_LOCAL_GETLINE
648 printf("%s", zPrompt);
650 zResult = local_getline(zPrior, stdin);
653 zResult = shell_readline(zPrompt);
654 if( zResult && *zResult ) shell_add_history(zResult);
662 ** Return the value of a hexadecimal digit. Return -1 if the input
663 ** is not a hex digit.
665 static int hexDigitValue(char c){
666 if( c>='0' && c<='9' ) return c - '0';
667 if( c>='a' && c<='f' ) return c - 'a' + 10;
668 if( c>='A' && c<='F' ) return c - 'A' + 10;
673 ** Interpret zArg as an integer value, possibly with suffixes.
675 static sqlite3_int64 integerValue(const char *zArg){
677 static const struct { char *zSuffix; int iMult; } aMult[] = {
679 { "MiB", 1024*1024 },
680 { "GiB", 1024*1024*1024 },
683 { "GB", 1000000000 },
693 }else if( zArg[0]=='+' ){
696 if( zArg[0]=='0' && zArg[1]=='x' ){
699 while( (x = hexDigitValue(zArg[0]))>=0 ){
704 while( IsDigit(zArg[0]) ){
705 v = v*10 + zArg[0] - '0';
709 for(i=0; i<ArraySize(aMult); i++){
710 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
715 return isNeg? -v : v;
719 ** A variable length string to which one can append text.
721 typedef struct ShellText ShellText;
729 ** Initialize and destroy a ShellText object
731 static void initText(ShellText *p){
732 memset(p, 0, sizeof(*p));
734 static void freeText(ShellText *p){
739 /* zIn is either a pointer to a NULL-terminated string in memory obtained
740 ** from malloc(), or a NULL pointer. The string pointed to by zAppend is
741 ** added to zIn, and the result returned in memory obtained from malloc().
742 ** zIn, if it was not NULL, is freed.
744 ** If the third argument, quote, is not '\0', then it is used as a
745 ** quote character for zAppend.
747 static void appendText(ShellText *p, char const *zAppend, char quote){
750 int nAppend = strlen30(zAppend);
752 len = nAppend+p->n+1;
755 for(i=0; i<nAppend; i++){
756 if( zAppend[i]==quote ) len++;
760 if( p->n+len>=p->nAlloc ){
761 p->nAlloc = p->nAlloc*2 + len + 20;
762 p->z = realloc(p->z, p->nAlloc);
763 if( p->z==0 ) shell_out_of_memory();
767 char *zCsr = p->z+p->n;
769 for(i=0; i<nAppend; i++){
770 *zCsr++ = zAppend[i];
771 if( zAppend[i]==quote ) *zCsr++ = quote;
774 p->n = (int)(zCsr - p->z);
777 memcpy(p->z+p->n, zAppend, nAppend);
784 ** Attempt to determine if identifier zName needs to be quoted, either
785 ** because it contains non-alphanumeric characters, or because it is an
786 ** SQLite keyword. Be conservative in this estimate: When in doubt assume
787 ** that quoting is required.
789 ** Return '"' if quoting is required. Return 0 if no quoting is required.
791 static char quoteChar(const char *zName){
793 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
794 for(i=0; zName[i]; i++){
795 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
797 return sqlite3_keyword_check(zName, i) ? '"' : 0;
801 ** Construct a fake object name and column list to describe the structure
802 ** of the view, virtual table, or table valued function zSchema.zName.
804 static char *shellFakeSchema(
805 sqlite3 *db, /* The database connection containing the vtab */
806 const char *zSchema, /* Schema of the database holding the vtab */
807 const char *zName /* The name of the virtual table */
809 sqlite3_stmt *pStmt = 0;
816 zSql = sqlite3_mprintf("PRAGMA \"%w\".table_info=%Q;",
817 zSchema ? zSchema : "main", zName);
818 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
822 cQuote = quoteChar(zSchema);
823 if( cQuote && sqlite3_stricmp(zSchema,"temp")==0 ) cQuote = 0;
824 appendText(&s, zSchema, cQuote);
825 appendText(&s, ".", 0);
827 cQuote = quoteChar(zName);
828 appendText(&s, zName, cQuote);
829 while( sqlite3_step(pStmt)==SQLITE_ROW ){
830 const char *zCol = (const char*)sqlite3_column_text(pStmt, 1);
832 appendText(&s, zDiv, 0);
834 cQuote = quoteChar(zCol);
835 appendText(&s, zCol, cQuote);
837 appendText(&s, ")", 0);
838 sqlite3_finalize(pStmt);
847 ** SQL function: shell_module_schema(X)
849 ** Return a fake schema for the table-valued function or eponymous virtual
852 static void shellModuleSchema(
853 sqlite3_context *pCtx,
855 sqlite3_value **apVal
857 const char *zName = (const char*)sqlite3_value_text(apVal[0]);
858 char *zFake = shellFakeSchema(sqlite3_context_db_handle(pCtx), 0, zName);
859 UNUSED_PARAMETER(nVal);
861 sqlite3_result_text(pCtx, sqlite3_mprintf("/* %s */", zFake),
868 ** SQL function: shell_add_schema(S,X)
870 ** Add the schema name X to the CREATE statement in S and return the result.
873 ** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
878 ** CREATE UNIQUE INDEX
881 ** CREATE VIRTUAL TABLE
883 ** This UDF is used by the .schema command to insert the schema name of
884 ** attached databases into the middle of the sqlite_master.sql field.
886 static void shellAddSchemaName(
887 sqlite3_context *pCtx,
889 sqlite3_value **apVal
891 static const char *aPrefix[] = {
900 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
901 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
902 const char *zName = (const char*)sqlite3_value_text(apVal[2]);
903 sqlite3 *db = sqlite3_context_db_handle(pCtx);
904 UNUSED_PARAMETER(nVal);
905 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
906 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
907 int n = strlen30(aPrefix[i]);
908 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
912 char cQuote = quoteChar(zSchema);
913 if( cQuote && sqlite3_stricmp(zSchema,"temp")!=0 ){
914 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
916 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
920 && aPrefix[i][0]=='V'
921 && (zFake = shellFakeSchema(db, zSchema, zName))!=0
924 z = sqlite3_mprintf("%s\n/* %s */", zIn, zFake);
926 z = sqlite3_mprintf("%z\n/* %s */", z, zFake);
931 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
937 sqlite3_result_value(pCtx, apVal[0]);
941 ** The source code for several run-time loadable extensions is inserted
942 ** below by the ../tool/mkshellc.tcl script. Before processing that included
943 ** code, we need to override some macros to make the included program code
944 ** work here in the middle of this regular program.
946 #define SQLITE_EXTENSION_INIT1
947 #define SQLITE_EXTENSION_INIT2(X) (void)(X)
949 #if defined(_WIN32) && defined(_MSC_VER)
950 /************************* Begin test_windirent.h ******************/
954 ** The author disclaims copyright to this source code. In place of
955 ** a legal notice, here is a blessing:
957 ** May you do good and not evil.
958 ** May you find forgiveness for yourself and forgive others.
959 ** May you share freely, never taking more than you give.
961 *************************************************************************
962 ** This file contains declarations for most of the opendir() family of
963 ** POSIX functions on Win32 using the MSVCRT.
966 #if defined(_WIN32) && defined(_MSC_VER) && !defined(SQLITE_WINDIRENT_H)
967 #define SQLITE_WINDIRENT_H
970 ** We need several data types from the Windows SDK header.
973 #ifndef WIN32_LEAN_AND_MEAN
974 #define WIN32_LEAN_AND_MEAN
980 ** We need several support functions from the SQLite core.
985 ** We need several things from the ANSI and MSVCRT headers.
993 #include <sys/types.h>
994 #include <sys/stat.h>
997 ** We may need several defines that should have been in "sys/stat.h".
1001 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
1005 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
1009 #define S_ISLNK(mode) (0)
1013 ** We may need to provide the "mode_t" type.
1016 #ifndef MODE_T_DEFINED
1017 #define MODE_T_DEFINED
1018 typedef unsigned short mode_t;
1022 ** We may need to provide the "ino_t" type.
1025 #ifndef INO_T_DEFINED
1026 #define INO_T_DEFINED
1027 typedef unsigned short ino_t;
1031 ** We need to define "NAME_MAX" if it was not present in "limits.h".
1035 # ifdef FILENAME_MAX
1036 # define NAME_MAX (FILENAME_MAX)
1038 # define NAME_MAX (260)
1043 ** We need to define "NULL_INTPTR_T" and "BAD_INTPTR_T".
1046 #ifndef NULL_INTPTR_T
1047 # define NULL_INTPTR_T ((intptr_t)(0))
1050 #ifndef BAD_INTPTR_T
1051 # define BAD_INTPTR_T ((intptr_t)(-1))
1055 ** We need to provide the necessary structures and related types.
1058 #ifndef DIRENT_DEFINED
1059 #define DIRENT_DEFINED
1060 typedef struct DIRENT DIRENT;
1061 typedef DIRENT *LPDIRENT;
1063 ino_t d_ino; /* Sequence number, do not use. */
1064 unsigned d_attributes; /* Win32 file attributes. */
1065 char d_name[NAME_MAX + 1]; /* Name within the directory. */
1071 typedef struct DIR DIR;
1074 intptr_t d_handle; /* Value returned by "_findfirst". */
1075 DIRENT d_first; /* DIRENT constructed based on "_findfirst". */
1076 DIRENT d_next; /* DIRENT constructed based on "_findnext". */
1081 ** Provide a macro, for use by the implementation, to determine if a
1082 ** particular directory entry should be skipped over when searching for
1083 ** the next directory entry that should be returned by the readdir() or
1084 ** readdir_r() functions.
1088 # define is_filtered(a) ((((a).attrib)&_A_HIDDEN) || (((a).attrib)&_A_SYSTEM))
1092 ** Provide the function prototype for the POSIX compatiable getenv()
1093 ** function. This function is not thread-safe.
1096 extern const char *windirent_getenv(const char *name);
1099 ** Finally, we can provide the function prototypes for the opendir(),
1100 ** readdir(), readdir_r(), and closedir() POSIX functions.
1103 extern LPDIR opendir(const char *dirname);
1104 extern LPDIRENT readdir(LPDIR dirp);
1105 extern INT readdir_r(LPDIR dirp, LPDIRENT entry, LPDIRENT *result);
1106 extern INT closedir(LPDIR dirp);
1108 #endif /* defined(WIN32) && defined(_MSC_VER) */
1110 /************************* End test_windirent.h ********************/
1111 /************************* Begin test_windirent.c ******************/
1115 ** The author disclaims copyright to this source code. In place of
1116 ** a legal notice, here is a blessing:
1118 ** May you do good and not evil.
1119 ** May you find forgiveness for yourself and forgive others.
1120 ** May you share freely, never taking more than you give.
1122 *************************************************************************
1123 ** This file contains code to implement most of the opendir() family of
1124 ** POSIX functions on Win32 using the MSVCRT.
1127 #if defined(_WIN32) && defined(_MSC_VER)
1128 /* #include "test_windirent.h" */
1131 ** Implementation of the POSIX getenv() function using the Win32 API.
1132 ** This function is not thread-safe.
1134 const char *windirent_getenv(
1137 static char value[32768]; /* Maximum length, per MSDN */
1138 DWORD dwSize = sizeof(value) / sizeof(char); /* Size in chars */
1139 DWORD dwRet; /* Value returned by GetEnvironmentVariableA() */
1141 memset(value, 0, sizeof(value));
1142 dwRet = GetEnvironmentVariableA(name, value, dwSize);
1143 if( dwRet==0 || dwRet>dwSize ){
1145 ** The function call to GetEnvironmentVariableA() failed -OR-
1146 ** the buffer is not large enough. Either way, return NULL.
1151 ** The function call to GetEnvironmentVariableA() succeeded
1152 ** -AND- the buffer contains the entire value.
1159 ** Implementation of the POSIX opendir() function using the MSVCRT.
1164 struct _finddata_t data;
1165 LPDIR dirp = (LPDIR)sqlite3_malloc(sizeof(DIR));
1166 SIZE_T namesize = sizeof(data.name) / sizeof(data.name[0]);
1168 if( dirp==NULL ) return NULL;
1169 memset(dirp, 0, sizeof(DIR));
1171 /* TODO: Remove this if Unix-style root paths are not used. */
1172 if( sqlite3_stricmp(dirname, "/")==0 ){
1173 dirname = windirent_getenv("SystemDrive");
1176 memset(&data, 0, sizeof(struct _finddata_t));
1177 _snprintf(data.name, namesize, "%s\\*", dirname);
1178 dirp->d_handle = _findfirst(data.name, &data);
1180 if( dirp->d_handle==BAD_INTPTR_T ){
1185 /* TODO: Remove this block to allow hidden and/or system files. */
1186 if( is_filtered(data) ){
1189 memset(&data, 0, sizeof(struct _finddata_t));
1190 if( _findnext(dirp->d_handle, &data)==-1 ){
1195 /* TODO: Remove this block to allow hidden and/or system files. */
1196 if( is_filtered(data) ) goto next;
1199 dirp->d_first.d_attributes = data.attrib;
1200 strncpy(dirp->d_first.d_name, data.name, NAME_MAX);
1201 dirp->d_first.d_name[NAME_MAX] = '\0';
1207 ** Implementation of the POSIX readdir() function using the MSVCRT.
1212 struct _finddata_t data;
1214 if( dirp==NULL ) return NULL;
1216 if( dirp->d_first.d_ino==0 ){
1217 dirp->d_first.d_ino++;
1218 dirp->d_next.d_ino++;
1220 return &dirp->d_first;
1225 memset(&data, 0, sizeof(struct _finddata_t));
1226 if( _findnext(dirp->d_handle, &data)==-1 ) return NULL;
1228 /* TODO: Remove this block to allow hidden and/or system files. */
1229 if( is_filtered(data) ) goto next;
1231 dirp->d_next.d_ino++;
1232 dirp->d_next.d_attributes = data.attrib;
1233 strncpy(dirp->d_next.d_name, data.name, NAME_MAX);
1234 dirp->d_next.d_name[NAME_MAX] = '\0';
1236 return &dirp->d_next;
1240 ** Implementation of the POSIX readdir_r() function using the MSVCRT.
1247 struct _finddata_t data;
1249 if( dirp==NULL ) return EBADF;
1251 if( dirp->d_first.d_ino==0 ){
1252 dirp->d_first.d_ino++;
1253 dirp->d_next.d_ino++;
1255 entry->d_ino = dirp->d_first.d_ino;
1256 entry->d_attributes = dirp->d_first.d_attributes;
1257 strncpy(entry->d_name, dirp->d_first.d_name, NAME_MAX);
1258 entry->d_name[NAME_MAX] = '\0';
1266 memset(&data, 0, sizeof(struct _finddata_t));
1267 if( _findnext(dirp->d_handle, &data)==-1 ){
1272 /* TODO: Remove this block to allow hidden and/or system files. */
1273 if( is_filtered(data) ) goto next;
1275 entry->d_ino = (ino_t)-1; /* not available */
1276 entry->d_attributes = data.attrib;
1277 strncpy(entry->d_name, data.name, NAME_MAX);
1278 entry->d_name[NAME_MAX] = '\0';
1285 ** Implementation of the POSIX closedir() function using the MSVCRT.
1292 if( dirp==NULL ) return EINVAL;
1294 if( dirp->d_handle!=NULL_INTPTR_T && dirp->d_handle!=BAD_INTPTR_T ){
1295 result = _findclose(dirp->d_handle);
1302 #endif /* defined(WIN32) && defined(_MSC_VER) */
1304 /************************* End test_windirent.c ********************/
1305 #define dirent DIRENT
1307 /************************* Begin ../ext/misc/shathree.c ******************/
1311 ** The author disclaims copyright to this source code. In place of
1312 ** a legal notice, here is a blessing:
1314 ** May you do good and not evil.
1315 ** May you find forgiveness for yourself and forgive others.
1316 ** May you share freely, never taking more than you give.
1318 ******************************************************************************
1320 ** This SQLite extension implements a functions that compute SHA1 hashes.
1321 ** Two SQL functions are implemented:
1324 ** sha3_query(Y,SIZE)
1326 ** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
1329 ** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
1330 ** and returns a hash of their results.
1332 ** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
1333 ** is used. If SIZE is included it must be one of the integers 224, 256,
1334 ** 384, or 512, to determine SHA3 hash variant that is computed.
1336 SQLITE_EXTENSION_INIT1
1340 /* typedef sqlite3_uint64 u64; */
1342 /******************************************************************************
1346 ** Macros to determine whether the machine is big or little endian,
1347 ** and whether or not that determination is run-time or compile-time.
1349 ** For best performance, an attempt is made to guess at the byte-order
1350 ** using C-preprocessor macros. If that is unsuccessful, or if
1351 ** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
1354 #ifndef SHA3_BYTEORDER
1355 # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
1356 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
1357 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
1359 # define SHA3_BYTEORDER 1234
1360 # elif defined(sparc) || defined(__ppc__)
1361 # define SHA3_BYTEORDER 4321
1363 # define SHA3_BYTEORDER 0
1369 ** State structure for a SHA3 hash in progress
1371 typedef struct SHA3Context SHA3Context;
1372 struct SHA3Context {
1374 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
1375 unsigned char x[1600]; /* ... or 1600 bytes */
1377 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
1378 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
1379 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
1383 ** A single step of the Keccak mixing function for a 1600-bit state
1385 static void KeccakF1600Step(SHA3Context *p){
1387 u64 b0, b1, b2, b3, b4;
1388 u64 c0, c1, c2, c3, c4;
1389 u64 d0, d1, d2, d3, d4;
1390 static const u64 RC[] = {
1391 0x0000000000000001ULL, 0x0000000000008082ULL,
1392 0x800000000000808aULL, 0x8000000080008000ULL,
1393 0x000000000000808bULL, 0x0000000080000001ULL,
1394 0x8000000080008081ULL, 0x8000000000008009ULL,
1395 0x000000000000008aULL, 0x0000000000000088ULL,
1396 0x0000000080008009ULL, 0x000000008000000aULL,
1397 0x000000008000808bULL, 0x800000000000008bULL,
1398 0x8000000000008089ULL, 0x8000000000008003ULL,
1399 0x8000000000008002ULL, 0x8000000000000080ULL,
1400 0x000000000000800aULL, 0x800000008000000aULL,
1401 0x8000000080008081ULL, 0x8000000000008080ULL,
1402 0x0000000080000001ULL, 0x8000000080008008ULL
1404 # define a00 (p->u.s[0])
1405 # define a01 (p->u.s[1])
1406 # define a02 (p->u.s[2])
1407 # define a03 (p->u.s[3])
1408 # define a04 (p->u.s[4])
1409 # define a10 (p->u.s[5])
1410 # define a11 (p->u.s[6])
1411 # define a12 (p->u.s[7])
1412 # define a13 (p->u.s[8])
1413 # define a14 (p->u.s[9])
1414 # define a20 (p->u.s[10])
1415 # define a21 (p->u.s[11])
1416 # define a22 (p->u.s[12])
1417 # define a23 (p->u.s[13])
1418 # define a24 (p->u.s[14])
1419 # define a30 (p->u.s[15])
1420 # define a31 (p->u.s[16])
1421 # define a32 (p->u.s[17])
1422 # define a33 (p->u.s[18])
1423 # define a34 (p->u.s[19])
1424 # define a40 (p->u.s[20])
1425 # define a41 (p->u.s[21])
1426 # define a42 (p->u.s[22])
1427 # define a43 (p->u.s[23])
1428 # define a44 (p->u.s[24])
1429 # define ROL64(a,x) ((a<<x)|(a>>(64-x)))
1431 for(i=0; i<24; i+=4){
1432 c0 = a00^a10^a20^a30^a40;
1433 c1 = a01^a11^a21^a31^a41;
1434 c2 = a02^a12^a22^a32^a42;
1435 c3 = a03^a13^a23^a33^a43;
1436 c4 = a04^a14^a24^a34^a44;
1437 d0 = c4^ROL64(c1, 1);
1438 d1 = c0^ROL64(c2, 1);
1439 d2 = c1^ROL64(c3, 1);
1440 d3 = c2^ROL64(c4, 1);
1441 d4 = c3^ROL64(c0, 1);
1444 b1 = ROL64((a11^d1), 44);
1445 b2 = ROL64((a22^d2), 43);
1446 b3 = ROL64((a33^d3), 21);
1447 b4 = ROL64((a44^d4), 14);
1448 a00 = b0 ^((~b1)& b2 );
1450 a11 = b1 ^((~b2)& b3 );
1451 a22 = b2 ^((~b3)& b4 );
1452 a33 = b3 ^((~b4)& b0 );
1453 a44 = b4 ^((~b0)& b1 );
1455 b2 = ROL64((a20^d0), 3);
1456 b3 = ROL64((a31^d1), 45);
1457 b4 = ROL64((a42^d2), 61);
1458 b0 = ROL64((a03^d3), 28);
1459 b1 = ROL64((a14^d4), 20);
1460 a20 = b0 ^((~b1)& b2 );
1461 a31 = b1 ^((~b2)& b3 );
1462 a42 = b2 ^((~b3)& b4 );
1463 a03 = b3 ^((~b4)& b0 );
1464 a14 = b4 ^((~b0)& b1 );
1466 b4 = ROL64((a40^d0), 18);
1467 b0 = ROL64((a01^d1), 1);
1468 b1 = ROL64((a12^d2), 6);
1469 b2 = ROL64((a23^d3), 25);
1470 b3 = ROL64((a34^d4), 8);
1471 a40 = b0 ^((~b1)& b2 );
1472 a01 = b1 ^((~b2)& b3 );
1473 a12 = b2 ^((~b3)& b4 );
1474 a23 = b3 ^((~b4)& b0 );
1475 a34 = b4 ^((~b0)& b1 );
1477 b1 = ROL64((a10^d0), 36);
1478 b2 = ROL64((a21^d1), 10);
1479 b3 = ROL64((a32^d2), 15);
1480 b4 = ROL64((a43^d3), 56);
1481 b0 = ROL64((a04^d4), 27);
1482 a10 = b0 ^((~b1)& b2 );
1483 a21 = b1 ^((~b2)& b3 );
1484 a32 = b2 ^((~b3)& b4 );
1485 a43 = b3 ^((~b4)& b0 );
1486 a04 = b4 ^((~b0)& b1 );
1488 b3 = ROL64((a30^d0), 41);
1489 b4 = ROL64((a41^d1), 2);
1490 b0 = ROL64((a02^d2), 62);
1491 b1 = ROL64((a13^d3), 55);
1492 b2 = ROL64((a24^d4), 39);
1493 a30 = b0 ^((~b1)& b2 );
1494 a41 = b1 ^((~b2)& b3 );
1495 a02 = b2 ^((~b3)& b4 );
1496 a13 = b3 ^((~b4)& b0 );
1497 a24 = b4 ^((~b0)& b1 );
1499 c0 = a00^a20^a40^a10^a30;
1500 c1 = a11^a31^a01^a21^a41;
1501 c2 = a22^a42^a12^a32^a02;
1502 c3 = a33^a03^a23^a43^a13;
1503 c4 = a44^a14^a34^a04^a24;
1504 d0 = c4^ROL64(c1, 1);
1505 d1 = c0^ROL64(c2, 1);
1506 d2 = c1^ROL64(c3, 1);
1507 d3 = c2^ROL64(c4, 1);
1508 d4 = c3^ROL64(c0, 1);
1511 b1 = ROL64((a31^d1), 44);
1512 b2 = ROL64((a12^d2), 43);
1513 b3 = ROL64((a43^d3), 21);
1514 b4 = ROL64((a24^d4), 14);
1515 a00 = b0 ^((~b1)& b2 );
1517 a31 = b1 ^((~b2)& b3 );
1518 a12 = b2 ^((~b3)& b4 );
1519 a43 = b3 ^((~b4)& b0 );
1520 a24 = b4 ^((~b0)& b1 );
1522 b2 = ROL64((a40^d0), 3);
1523 b3 = ROL64((a21^d1), 45);
1524 b4 = ROL64((a02^d2), 61);
1525 b0 = ROL64((a33^d3), 28);
1526 b1 = ROL64((a14^d4), 20);
1527 a40 = b0 ^((~b1)& b2 );
1528 a21 = b1 ^((~b2)& b3 );
1529 a02 = b2 ^((~b3)& b4 );
1530 a33 = b3 ^((~b4)& b0 );
1531 a14 = b4 ^((~b0)& b1 );
1533 b4 = ROL64((a30^d0), 18);
1534 b0 = ROL64((a11^d1), 1);
1535 b1 = ROL64((a42^d2), 6);
1536 b2 = ROL64((a23^d3), 25);
1537 b3 = ROL64((a04^d4), 8);
1538 a30 = b0 ^((~b1)& b2 );
1539 a11 = b1 ^((~b2)& b3 );
1540 a42 = b2 ^((~b3)& b4 );
1541 a23 = b3 ^((~b4)& b0 );
1542 a04 = b4 ^((~b0)& b1 );
1544 b1 = ROL64((a20^d0), 36);
1545 b2 = ROL64((a01^d1), 10);
1546 b3 = ROL64((a32^d2), 15);
1547 b4 = ROL64((a13^d3), 56);
1548 b0 = ROL64((a44^d4), 27);
1549 a20 = b0 ^((~b1)& b2 );
1550 a01 = b1 ^((~b2)& b3 );
1551 a32 = b2 ^((~b3)& b4 );
1552 a13 = b3 ^((~b4)& b0 );
1553 a44 = b4 ^((~b0)& b1 );
1555 b3 = ROL64((a10^d0), 41);
1556 b4 = ROL64((a41^d1), 2);
1557 b0 = ROL64((a22^d2), 62);
1558 b1 = ROL64((a03^d3), 55);
1559 b2 = ROL64((a34^d4), 39);
1560 a10 = b0 ^((~b1)& b2 );
1561 a41 = b1 ^((~b2)& b3 );
1562 a22 = b2 ^((~b3)& b4 );
1563 a03 = b3 ^((~b4)& b0 );
1564 a34 = b4 ^((~b0)& b1 );
1566 c0 = a00^a40^a30^a20^a10;
1567 c1 = a31^a21^a11^a01^a41;
1568 c2 = a12^a02^a42^a32^a22;
1569 c3 = a43^a33^a23^a13^a03;
1570 c4 = a24^a14^a04^a44^a34;
1571 d0 = c4^ROL64(c1, 1);
1572 d1 = c0^ROL64(c2, 1);
1573 d2 = c1^ROL64(c3, 1);
1574 d3 = c2^ROL64(c4, 1);
1575 d4 = c3^ROL64(c0, 1);
1578 b1 = ROL64((a21^d1), 44);
1579 b2 = ROL64((a42^d2), 43);
1580 b3 = ROL64((a13^d3), 21);
1581 b4 = ROL64((a34^d4), 14);
1582 a00 = b0 ^((~b1)& b2 );
1584 a21 = b1 ^((~b2)& b3 );
1585 a42 = b2 ^((~b3)& b4 );
1586 a13 = b3 ^((~b4)& b0 );
1587 a34 = b4 ^((~b0)& b1 );
1589 b2 = ROL64((a30^d0), 3);
1590 b3 = ROL64((a01^d1), 45);
1591 b4 = ROL64((a22^d2), 61);
1592 b0 = ROL64((a43^d3), 28);
1593 b1 = ROL64((a14^d4), 20);
1594 a30 = b0 ^((~b1)& b2 );
1595 a01 = b1 ^((~b2)& b3 );
1596 a22 = b2 ^((~b3)& b4 );
1597 a43 = b3 ^((~b4)& b0 );
1598 a14 = b4 ^((~b0)& b1 );
1600 b4 = ROL64((a10^d0), 18);
1601 b0 = ROL64((a31^d1), 1);
1602 b1 = ROL64((a02^d2), 6);
1603 b2 = ROL64((a23^d3), 25);
1604 b3 = ROL64((a44^d4), 8);
1605 a10 = b0 ^((~b1)& b2 );
1606 a31 = b1 ^((~b2)& b3 );
1607 a02 = b2 ^((~b3)& b4 );
1608 a23 = b3 ^((~b4)& b0 );
1609 a44 = b4 ^((~b0)& b1 );
1611 b1 = ROL64((a40^d0), 36);
1612 b2 = ROL64((a11^d1), 10);
1613 b3 = ROL64((a32^d2), 15);
1614 b4 = ROL64((a03^d3), 56);
1615 b0 = ROL64((a24^d4), 27);
1616 a40 = b0 ^((~b1)& b2 );
1617 a11 = b1 ^((~b2)& b3 );
1618 a32 = b2 ^((~b3)& b4 );
1619 a03 = b3 ^((~b4)& b0 );
1620 a24 = b4 ^((~b0)& b1 );
1622 b3 = ROL64((a20^d0), 41);
1623 b4 = ROL64((a41^d1), 2);
1624 b0 = ROL64((a12^d2), 62);
1625 b1 = ROL64((a33^d3), 55);
1626 b2 = ROL64((a04^d4), 39);
1627 a20 = b0 ^((~b1)& b2 );
1628 a41 = b1 ^((~b2)& b3 );
1629 a12 = b2 ^((~b3)& b4 );
1630 a33 = b3 ^((~b4)& b0 );
1631 a04 = b4 ^((~b0)& b1 );
1633 c0 = a00^a30^a10^a40^a20;
1634 c1 = a21^a01^a31^a11^a41;
1635 c2 = a42^a22^a02^a32^a12;
1636 c3 = a13^a43^a23^a03^a33;
1637 c4 = a34^a14^a44^a24^a04;
1638 d0 = c4^ROL64(c1, 1);
1639 d1 = c0^ROL64(c2, 1);
1640 d2 = c1^ROL64(c3, 1);
1641 d3 = c2^ROL64(c4, 1);
1642 d4 = c3^ROL64(c0, 1);
1645 b1 = ROL64((a01^d1), 44);
1646 b2 = ROL64((a02^d2), 43);
1647 b3 = ROL64((a03^d3), 21);
1648 b4 = ROL64((a04^d4), 14);
1649 a00 = b0 ^((~b1)& b2 );
1651 a01 = b1 ^((~b2)& b3 );
1652 a02 = b2 ^((~b3)& b4 );
1653 a03 = b3 ^((~b4)& b0 );
1654 a04 = b4 ^((~b0)& b1 );
1656 b2 = ROL64((a10^d0), 3);
1657 b3 = ROL64((a11^d1), 45);
1658 b4 = ROL64((a12^d2), 61);
1659 b0 = ROL64((a13^d3), 28);
1660 b1 = ROL64((a14^d4), 20);
1661 a10 = b0 ^((~b1)& b2 );
1662 a11 = b1 ^((~b2)& b3 );
1663 a12 = b2 ^((~b3)& b4 );
1664 a13 = b3 ^((~b4)& b0 );
1665 a14 = b4 ^((~b0)& b1 );
1667 b4 = ROL64((a20^d0), 18);
1668 b0 = ROL64((a21^d1), 1);
1669 b1 = ROL64((a22^d2), 6);
1670 b2 = ROL64((a23^d3), 25);
1671 b3 = ROL64((a24^d4), 8);
1672 a20 = b0 ^((~b1)& b2 );
1673 a21 = b1 ^((~b2)& b3 );
1674 a22 = b2 ^((~b3)& b4 );
1675 a23 = b3 ^((~b4)& b0 );
1676 a24 = b4 ^((~b0)& b1 );
1678 b1 = ROL64((a30^d0), 36);
1679 b2 = ROL64((a31^d1), 10);
1680 b3 = ROL64((a32^d2), 15);
1681 b4 = ROL64((a33^d3), 56);
1682 b0 = ROL64((a34^d4), 27);
1683 a30 = b0 ^((~b1)& b2 );
1684 a31 = b1 ^((~b2)& b3 );
1685 a32 = b2 ^((~b3)& b4 );
1686 a33 = b3 ^((~b4)& b0 );
1687 a34 = b4 ^((~b0)& b1 );
1689 b3 = ROL64((a40^d0), 41);
1690 b4 = ROL64((a41^d1), 2);
1691 b0 = ROL64((a42^d2), 62);
1692 b1 = ROL64((a43^d3), 55);
1693 b2 = ROL64((a44^d4), 39);
1694 a40 = b0 ^((~b1)& b2 );
1695 a41 = b1 ^((~b2)& b3 );
1696 a42 = b2 ^((~b3)& b4 );
1697 a43 = b3 ^((~b4)& b0 );
1698 a44 = b4 ^((~b0)& b1 );
1703 ** Initialize a new hash. iSize determines the size of the hash
1704 ** in bits and should be one of 224, 256, 384, or 512. Or iSize
1705 ** can be zero to use the default hash size of 256 bits.
1707 static void SHA3Init(SHA3Context *p, int iSize){
1708 memset(p, 0, sizeof(*p));
1709 if( iSize>=128 && iSize<=512 ){
1710 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1712 p->nRate = (1600 - 2*256)/8;
1714 #if SHA3_BYTEORDER==1234
1715 /* Known to be little-endian at compile-time. No-op */
1716 #elif SHA3_BYTEORDER==4321
1717 p->ixMask = 7; /* Big-endian */
1720 static unsigned int one = 1;
1721 if( 1==*(unsigned char*)&one ){
1722 /* Little endian. No byte swapping. */
1725 /* Big endian. Byte swap. */
1733 ** Make consecutive calls to the SHA3Update function to add new content
1736 static void SHA3Update(
1738 const unsigned char *aData,
1742 #if SHA3_BYTEORDER==1234
1743 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1744 for(; i+7<nData; i+=8){
1745 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1747 if( p->nLoaded>=p->nRate ){
1754 for(; i<nData; i++){
1755 #if SHA3_BYTEORDER==1234
1756 p->u.x[p->nLoaded] ^= aData[i];
1757 #elif SHA3_BYTEORDER==4321
1758 p->u.x[p->nLoaded^0x07] ^= aData[i];
1760 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1763 if( p->nLoaded==p->nRate ){
1771 ** After all content has been added, invoke SHA3Final() to compute
1772 ** the final hash. The function returns a pointer to the binary
1775 static unsigned char *SHA3Final(SHA3Context *p){
1777 if( p->nLoaded==p->nRate-1 ){
1778 const unsigned char c1 = 0x86;
1779 SHA3Update(p, &c1, 1);
1781 const unsigned char c2 = 0x06;
1782 const unsigned char c3 = 0x80;
1783 SHA3Update(p, &c2, 1);
1784 p->nLoaded = p->nRate - 1;
1785 SHA3Update(p, &c3, 1);
1787 for(i=0; i<p->nRate; i++){
1788 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1790 return &p->u.x[p->nRate];
1792 /* End of the hashing logic
1793 *****************************************************************************/
1796 ** Implementation of the sha3(X,SIZE) function.
1798 ** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
1799 ** size is 256. If X is a BLOB, it is hashed as is.
1800 ** For all other non-NULL types of input, X is converted into a UTF-8 string
1801 ** and the string is hashed without the trailing 0x00 terminator. The hash
1802 ** of a NULL value is NULL.
1804 static void sha3Func(
1805 sqlite3_context *context,
1807 sqlite3_value **argv
1810 int eType = sqlite3_value_type(argv[0]);
1811 int nByte = sqlite3_value_bytes(argv[0]);
1816 iSize = sqlite3_value_int(argv[1]);
1817 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1818 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1823 if( eType==SQLITE_NULL ) return;
1824 SHA3Init(&cx, iSize);
1825 if( eType==SQLITE_BLOB ){
1826 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1828 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1830 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1833 /* Compute a string using sqlite3_vsnprintf() with a maximum length
1834 ** of 50 bytes and add it to the hash.
1836 static void hash_step_vformat(
1837 SHA3Context *p, /* Add content to this context */
1838 const char *zFormat,
1844 va_start(ap, zFormat);
1845 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1847 n = (int)strlen(zBuf);
1848 SHA3Update(p, (unsigned char*)zBuf, n);
1852 ** Implementation of the sha3_query(SQL,SIZE) function.
1854 ** This function compiles and runs the SQL statement(s) given in the
1855 ** argument. The results are hashed using a SIZE-bit SHA3. The default
1858 ** The format of the byte stream that is hashed is summarized as follows:
1868 ** <sql> is the original SQL text for each statement run and <n> is
1869 ** the size of that text. The SQL text is UTF-8. A single R character
1870 ** occurs before the start of each row. N means a NULL value.
1871 ** I mean an 8-byte little-endian integer <int>. F is a floating point
1872 ** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1873 ** B means blobs of <size> bytes. T means text rendered as <size>
1874 ** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1877 ** For each SQL statement in the X input, there is one S segment. Each
1878 ** S segment is followed by zero or more R segments, one for each row in the
1879 ** result set. After each R, there are one or more N, I, F, B, or T segments,
1880 ** one for each column in the result set. Segments are concatentated directly
1881 ** with no delimiters of any kind.
1883 static void sha3QueryFunc(
1884 sqlite3_context *context,
1886 sqlite3_value **argv
1888 sqlite3 *db = sqlite3_context_db_handle(context);
1889 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1890 sqlite3_stmt *pStmt = 0;
1891 int nCol; /* Number of columns in the result set */
1892 int i; /* Loop counter */
1902 iSize = sqlite3_value_int(argv[1]);
1903 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1904 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1909 if( zSql==0 ) return;
1910 SHA3Init(&cx, iSize);
1912 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1914 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1915 zSql, sqlite3_errmsg(db));
1916 sqlite3_finalize(pStmt);
1917 sqlite3_result_error(context, zMsg, -1);
1921 if( !sqlite3_stmt_readonly(pStmt) ){
1922 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1923 sqlite3_finalize(pStmt);
1924 sqlite3_result_error(context, zMsg, -1);
1928 nCol = sqlite3_column_count(pStmt);
1929 z = sqlite3_sql(pStmt);
1931 hash_step_vformat(&cx,"S%d:",n);
1932 SHA3Update(&cx,(unsigned char*)z,n);
1934 /* Compute a hash over the result of the query */
1935 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1936 SHA3Update(&cx,(const unsigned char*)"R",1);
1937 for(i=0; i<nCol; i++){
1938 switch( sqlite3_column_type(pStmt,i) ){
1940 SHA3Update(&cx, (const unsigned char*)"N",1);
1943 case SQLITE_INTEGER: {
1947 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1949 for(j=8; j>=1; j--){
1954 SHA3Update(&cx, x, 9);
1957 case SQLITE_FLOAT: {
1961 double r = sqlite3_column_double(pStmt,i);
1963 for(j=8; j>=1; j--){
1968 SHA3Update(&cx,x,9);
1972 int n2 = sqlite3_column_bytes(pStmt, i);
1973 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1974 hash_step_vformat(&cx,"T%d:",n2);
1975 SHA3Update(&cx, z2, n2);
1979 int n2 = sqlite3_column_bytes(pStmt, i);
1980 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1981 hash_step_vformat(&cx,"B%d:",n2);
1982 SHA3Update(&cx, z2, n2);
1988 sqlite3_finalize(pStmt);
1990 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1997 int sqlite3_shathree_init(
2000 const sqlite3_api_routines *pApi
2003 SQLITE_EXTENSION_INIT2(pApi);
2004 (void)pzErrMsg; /* Unused parameter */
2005 rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
2007 if( rc==SQLITE_OK ){
2008 rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
2011 if( rc==SQLITE_OK ){
2012 rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
2013 sha3QueryFunc, 0, 0);
2015 if( rc==SQLITE_OK ){
2016 rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
2017 sha3QueryFunc, 0, 0);
2022 /************************* End ../ext/misc/shathree.c ********************/
2023 /************************* Begin ../ext/misc/fileio.c ******************/
2027 ** The author disclaims copyright to this source code. In place of
2028 ** a legal notice, here is a blessing:
2030 ** May you do good and not evil.
2031 ** May you find forgiveness for yourself and forgive others.
2032 ** May you share freely, never taking more than you give.
2034 ******************************************************************************
2036 ** This SQLite extension implements SQL functions readfile() and
2037 ** writefile(), and eponymous virtual type "fsdir".
2039 ** WRITEFILE(FILE, DATA [, MODE [, MTIME]]):
2041 ** If neither of the optional arguments is present, then this UDF
2042 ** function writes blob DATA to file FILE. If successful, the number
2043 ** of bytes written is returned. If an error occurs, NULL is returned.
2045 ** If the first option argument - MODE - is present, then it must
2046 ** be passed an integer value that corresponds to a POSIX mode
2047 ** value (file type + permissions, as returned in the stat.st_mode
2048 ** field by the stat() system call). Three types of files may
2049 ** be written/created:
2051 ** regular files: (mode & 0170000)==0100000
2052 ** symbolic links: (mode & 0170000)==0120000
2053 ** directories: (mode & 0170000)==0040000
2055 ** For a directory, the DATA is ignored. For a symbolic link, it is
2056 ** interpreted as text and used as the target of the link. For a
2057 ** regular file, it is interpreted as a blob and written into the
2058 ** named file. Regardless of the type of file, its permissions are
2059 ** set to (mode & 0777) before returning.
2061 ** If the optional MTIME argument is present, then it is interpreted
2062 ** as an integer - the number of seconds since the unix epoch. The
2063 ** modification-time of the target file is set to this value before
2066 ** If three or more arguments are passed to this function and an
2067 ** error is encountered, an exception is raised.
2071 ** Read and return the contents of file FILE (type blob) from disk.
2077 ** SELECT * FROM fsdir($path [, $dir]);
2079 ** Parameter $path is an absolute or relative pathname. If the file that it
2080 ** refers to does not exist, it is an error. If the path refers to a regular
2081 ** file or symbolic link, it returns a single row. Or, if the path refers
2082 ** to a directory, it returns one row for the directory, and one row for each
2083 ** file within the hierarchy rooted at $path.
2085 ** Each row has the following columns:
2087 ** name: Path to file or directory (text value).
2088 ** mode: Value of stat.st_mode for directory entry (an integer).
2089 ** mtime: Value of stat.st_mtime for directory entry (an integer).
2090 ** data: For a regular file, a blob containing the file data. For a
2091 ** symlink, a text value containing the text of the link. For a
2094 ** If a non-NULL value is specified for the optional $dir parameter and
2095 ** $path is a relative path, then $path is interpreted relative to $dir.
2096 ** And the paths returned in the "name" column of the table are also
2097 ** relative to directory $dir.
2099 SQLITE_EXTENSION_INIT1
2104 #include <sys/types.h>
2105 #include <sys/stat.h>
2107 #if !defined(_WIN32) && !defined(WIN32)
2108 # include <unistd.h>
2109 # include <dirent.h>
2111 # include <sys/time.h>
2113 # include "windows.h"
2115 # include <direct.h>
2116 /* # include "test_windirent.h" */
2117 # define dirent DIRENT
2119 # define chmod _chmod
2124 # define mkdir(path,mode) _mkdir(path)
2125 # define lstat(path,buf) stat(path,buf)
2131 #define FSDIR_SCHEMA "(name,mode,mtime,data,path HIDDEN,dir HIDDEN)"
2134 ** Set the result stored by context ctx to a blob containing the
2135 ** contents of file zName.
2137 static void readFileContents(sqlite3_context *ctx, const char *zName){
2142 in = fopen(zName, "rb");
2144 fseek(in, 0, SEEK_END);
2147 pBuf = sqlite3_malloc( nIn );
2148 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
2149 sqlite3_result_blob(ctx, pBuf, nIn, sqlite3_free);
2157 ** Implementation of the "readfile(X)" SQL function. The entire content
2158 ** of the file named X is read and returned as a BLOB. NULL is returned
2159 ** if the file does not exist or is unreadable.
2161 static void readfileFunc(
2162 sqlite3_context *context,
2164 sqlite3_value **argv
2167 (void)(argc); /* Unused parameter */
2168 zName = (const char*)sqlite3_value_text(argv[0]);
2169 if( zName==0 ) return;
2170 readFileContents(context, zName);
2174 ** Set the error message contained in context ctx to the results of
2175 ** vprintf(zFmt, ...).
2177 static void ctxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
2181 zMsg = sqlite3_vmprintf(zFmt, ap);
2182 sqlite3_result_error(ctx, zMsg, -1);
2189 ** This function is designed to convert a Win32 FILETIME structure into the
2190 ** number of seconds since the Unix Epoch (1970-01-01 00:00:00 UTC).
2192 static sqlite3_uint64 fileTimeToUnixTime(
2193 LPFILETIME pFileTime
2195 SYSTEMTIME epochSystemTime;
2196 ULARGE_INTEGER epochIntervals;
2197 FILETIME epochFileTime;
2198 ULARGE_INTEGER fileIntervals;
2200 memset(&epochSystemTime, 0, sizeof(SYSTEMTIME));
2201 epochSystemTime.wYear = 1970;
2202 epochSystemTime.wMonth = 1;
2203 epochSystemTime.wDay = 1;
2204 SystemTimeToFileTime(&epochSystemTime, &epochFileTime);
2205 epochIntervals.LowPart = epochFileTime.dwLowDateTime;
2206 epochIntervals.HighPart = epochFileTime.dwHighDateTime;
2208 fileIntervals.LowPart = pFileTime->dwLowDateTime;
2209 fileIntervals.HighPart = pFileTime->dwHighDateTime;
2211 return (fileIntervals.QuadPart - epochIntervals.QuadPart) / 10000000;
2215 ** This function attempts to normalize the time values found in the stat()
2216 ** buffer to UTC. This is necessary on Win32, where the runtime library
2217 ** appears to return these values as local times.
2219 static void statTimesToUtc(
2221 struct stat *pStatBuf
2224 WIN32_FIND_DATAW fd;
2225 LPWSTR zUnicodeName;
2226 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2227 zUnicodeName = sqlite3_win32_utf8_to_unicode(zPath);
2229 memset(&fd, 0, sizeof(WIN32_FIND_DATAW));
2230 hFindFile = FindFirstFileW(zUnicodeName, &fd);
2231 if( hFindFile!=NULL ){
2232 pStatBuf->st_ctime = (time_t)fileTimeToUnixTime(&fd.ftCreationTime);
2233 pStatBuf->st_atime = (time_t)fileTimeToUnixTime(&fd.ftLastAccessTime);
2234 pStatBuf->st_mtime = (time_t)fileTimeToUnixTime(&fd.ftLastWriteTime);
2235 FindClose(hFindFile);
2237 sqlite3_free(zUnicodeName);
2243 ** This function is used in place of stat(). On Windows, special handling
2244 ** is required in order for the included time to be returned as UTC. On all
2245 ** other systems, this function simply calls stat().
2247 static int fileStat(
2249 struct stat *pStatBuf
2252 int rc = stat(zPath, pStatBuf);
2253 if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2256 return stat(zPath, pStatBuf);
2261 ** This function is used in place of lstat(). On Windows, special handling
2262 ** is required in order for the included time to be returned as UTC. On all
2263 ** other systems, this function simply calls lstat().
2265 static int fileLinkStat(
2267 struct stat *pStatBuf
2270 int rc = lstat(zPath, pStatBuf);
2271 if( rc==0 ) statTimesToUtc(zPath, pStatBuf);
2274 return lstat(zPath, pStatBuf);
2279 ** Argument zFile is the name of a file that will be created and/or written
2280 ** by SQL function writefile(). This function ensures that the directory
2281 ** zFile will be written to exists, creating it if required. The permissions
2282 ** for any path components created by this function are set to (mode&0777).
2284 ** If an OOM condition is encountered, SQLITE_NOMEM is returned. Otherwise,
2285 ** SQLITE_OK is returned if the directory is successfully created, or
2286 ** SQLITE_ERROR otherwise.
2288 static int makeDirectory(
2292 char *zCopy = sqlite3_mprintf("%s", zFile);
2298 int nCopy = (int)strlen(zCopy);
2301 while( rc==SQLITE_OK ){
2305 for(; zCopy[i]!='/' && i<nCopy; i++);
2306 if( i==nCopy ) break;
2309 rc2 = fileStat(zCopy, &sStat);
2311 if( mkdir(zCopy, mode & 0777) ) rc = SQLITE_ERROR;
2313 if( !S_ISDIR(sStat.st_mode) ) rc = SQLITE_ERROR;
2319 sqlite3_free(zCopy);
2326 ** This function does the work for the writefile() UDF. Refer to
2327 ** header comments at the top of this file for details.
2329 static int writeFile(
2330 sqlite3_context *pCtx, /* Context to return bytes written in */
2331 const char *zFile, /* File to write */
2332 sqlite3_value *pData, /* Data to write */
2333 mode_t mode, /* MODE parameter passed to writefile() */
2334 sqlite3_int64 mtime /* MTIME parameter (or -1 to not set time) */
2336 #if !defined(_WIN32) && !defined(WIN32)
2337 if( S_ISLNK(mode) ){
2338 const char *zTo = (const char*)sqlite3_value_text(pData);
2339 if( symlink(zTo, zFile)<0 ) return 1;
2343 if( S_ISDIR(mode) ){
2344 if( mkdir(zFile, mode) ){
2345 /* The mkdir() call to create the directory failed. This might not
2346 ** be an error though - if there is already a directory at the same
2347 ** path and either the permissions already match or can be changed
2348 ** to do so using chmod(), it is not an error. */
2351 || 0!=fileStat(zFile, &sStat)
2352 || !S_ISDIR(sStat.st_mode)
2353 || ((sStat.st_mode&0777)!=(mode&0777) && 0!=chmod(zFile, mode&0777))
2359 sqlite3_int64 nWrite = 0;
2362 FILE *out = fopen(zFile, "wb");
2363 if( out==0 ) return 1;
2364 z = (const char*)sqlite3_value_blob(pData);
2366 sqlite3_int64 n = fwrite(z, 1, sqlite3_value_bytes(pData), out);
2367 nWrite = sqlite3_value_bytes(pData);
2373 if( rc==0 && mode && chmod(zFile, mode & 0777) ){
2377 sqlite3_result_int64(pCtx, nWrite);
2384 FILETIME lastAccess;
2386 SYSTEMTIME currentTime;
2389 LPWSTR zUnicodeName;
2390 extern LPWSTR sqlite3_win32_utf8_to_unicode(const char*);
2392 GetSystemTime(¤tTime);
2393 SystemTimeToFileTime(¤tTime, &lastAccess);
2394 intervals = Int32x32To64(mtime, 10000000) + 116444736000000000;
2395 lastWrite.dwLowDateTime = (DWORD)intervals;
2396 lastWrite.dwHighDateTime = intervals >> 32;
2397 zUnicodeName = sqlite3_win32_utf8_to_unicode(zFile);
2398 if( zUnicodeName==0 ){
2401 hFile = CreateFileW(
2402 zUnicodeName, FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
2403 FILE_FLAG_BACKUP_SEMANTICS, NULL
2405 sqlite3_free(zUnicodeName);
2406 if( hFile!=INVALID_HANDLE_VALUE ){
2407 BOOL bResult = SetFileTime(hFile, NULL, &lastAccess, &lastWrite);
2413 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
2415 struct timespec times[2];
2416 times[0].tv_nsec = times[1].tv_nsec = 0;
2417 times[0].tv_sec = time(0);
2418 times[1].tv_sec = mtime;
2419 if( utimensat(AT_FDCWD, zFile, times, AT_SYMLINK_NOFOLLOW) ){
2424 struct timeval times[2];
2425 times[0].tv_usec = times[1].tv_usec = 0;
2426 times[0].tv_sec = time(0);
2427 times[1].tv_sec = mtime;
2428 if( utimes(zFile, times) ){
2438 ** Implementation of the "writefile(W,X[,Y[,Z]]])" SQL function.
2439 ** Refer to header comments at the top of this file for details.
2441 static void writefileFunc(
2442 sqlite3_context *context,
2444 sqlite3_value **argv
2449 sqlite3_int64 mtime = -1;
2451 if( argc<2 || argc>4 ){
2452 sqlite3_result_error(context,
2453 "wrong number of arguments to function writefile()", -1
2458 zFile = (const char*)sqlite3_value_text(argv[0]);
2459 if( zFile==0 ) return;
2461 mode = (mode_t)sqlite3_value_int(argv[2]);
2464 mtime = sqlite3_value_int64(argv[3]);
2467 res = writeFile(context, zFile, argv[1], mode, mtime);
2468 if( res==1 && errno==ENOENT ){
2469 if( makeDirectory(zFile, mode)==SQLITE_OK ){
2470 res = writeFile(context, zFile, argv[1], mode, mtime);
2474 if( argc>2 && res!=0 ){
2475 if( S_ISLNK(mode) ){
2476 ctxErrorMsg(context, "failed to create symlink: %s", zFile);
2477 }else if( S_ISDIR(mode) ){
2478 ctxErrorMsg(context, "failed to create directory: %s", zFile);
2480 ctxErrorMsg(context, "failed to write file: %s", zFile);
2486 ** SQL function: lsmode(MODE)
2488 ** Given a numberic st_mode from stat(), convert it into a human-readable
2489 ** text string in the style of "ls -l".
2491 static void lsModeFunc(
2492 sqlite3_context *context,
2494 sqlite3_value **argv
2497 int iMode = sqlite3_value_int(argv[0]);
2500 if( S_ISLNK(iMode) ){
2502 }else if( S_ISREG(iMode) ){
2504 }else if( S_ISDIR(iMode) ){
2510 int m = (iMode >> ((2-i)*3));
2511 char *a = &z[1 + i*3];
2512 a[0] = (m & 0x4) ? 'r' : '-';
2513 a[1] = (m & 0x2) ? 'w' : '-';
2514 a[2] = (m & 0x1) ? 'x' : '-';
2517 sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT);
2520 #ifndef SQLITE_OMIT_VIRTUALTABLE
2523 ** Cursor type for recursively iterating through a directory structure.
2525 typedef struct fsdir_cursor fsdir_cursor;
2526 typedef struct FsdirLevel FsdirLevel;
2529 DIR *pDir; /* From opendir() */
2530 char *zDir; /* Name of directory (nul-terminated) */
2533 struct fsdir_cursor {
2534 sqlite3_vtab_cursor base; /* Base class - must be first */
2536 int nLvl; /* Number of entries in aLvl[] array */
2537 int iLvl; /* Index of current entry */
2538 FsdirLevel *aLvl; /* Hierarchy of directories being traversed */
2543 struct stat sStat; /* Current lstat() results */
2544 char *zPath; /* Path to current entry */
2545 sqlite3_int64 iRowid; /* Current rowid */
2548 typedef struct fsdir_tab fsdir_tab;
2550 sqlite3_vtab base; /* Base class - must be first */
2554 ** Construct a new fsdir virtual table object.
2556 static int fsdirConnect(
2559 int argc, const char *const*argv,
2560 sqlite3_vtab **ppVtab,
2563 fsdir_tab *pNew = 0;
2569 rc = sqlite3_declare_vtab(db, "CREATE TABLE x" FSDIR_SCHEMA);
2570 if( rc==SQLITE_OK ){
2571 pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
2572 if( pNew==0 ) return SQLITE_NOMEM;
2573 memset(pNew, 0, sizeof(*pNew));
2575 *ppVtab = (sqlite3_vtab*)pNew;
2580 ** This method is the destructor for fsdir vtab objects.
2582 static int fsdirDisconnect(sqlite3_vtab *pVtab){
2583 sqlite3_free(pVtab);
2588 ** Constructor for a new fsdir_cursor object.
2590 static int fsdirOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
2593 pCur = sqlite3_malloc( sizeof(*pCur) );
2594 if( pCur==0 ) return SQLITE_NOMEM;
2595 memset(pCur, 0, sizeof(*pCur));
2597 *ppCursor = &pCur->base;
2602 ** Reset a cursor back to the state it was in when first returned
2605 static void fsdirResetCursor(fsdir_cursor *pCur){
2607 for(i=0; i<=pCur->iLvl; i++){
2608 FsdirLevel *pLvl = &pCur->aLvl[i];
2609 if( pLvl->pDir ) closedir(pLvl->pDir);
2610 sqlite3_free(pLvl->zDir);
2612 sqlite3_free(pCur->zPath);
2613 sqlite3_free(pCur->aLvl);
2624 ** Destructor for an fsdir_cursor.
2626 static int fsdirClose(sqlite3_vtab_cursor *cur){
2627 fsdir_cursor *pCur = (fsdir_cursor*)cur;
2629 fsdirResetCursor(pCur);
2635 ** Set the error message for the virtual table associated with cursor
2636 ** pCur to the results of vprintf(zFmt, ...).
2638 static void fsdirSetErrmsg(fsdir_cursor *pCur, const char *zFmt, ...){
2641 pCur->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
2647 ** Advance an fsdir_cursor to its next row of output.
2649 static int fsdirNext(sqlite3_vtab_cursor *cur){
2650 fsdir_cursor *pCur = (fsdir_cursor*)cur;
2651 mode_t m = pCur->sStat.st_mode;
2655 /* Descend into this directory */
2656 int iNew = pCur->iLvl + 1;
2658 if( iNew>=pCur->nLvl ){
2660 int nByte = nNew*sizeof(FsdirLevel);
2661 FsdirLevel *aNew = (FsdirLevel*)sqlite3_realloc(pCur->aLvl, nByte);
2662 if( aNew==0 ) return SQLITE_NOMEM;
2663 memset(&aNew[pCur->nLvl], 0, sizeof(FsdirLevel)*(nNew-pCur->nLvl));
2668 pLvl = &pCur->aLvl[iNew];
2670 pLvl->zDir = pCur->zPath;
2672 pLvl->pDir = opendir(pLvl->zDir);
2673 if( pLvl->pDir==0 ){
2674 fsdirSetErrmsg(pCur, "cannot read directory: %s", pCur->zPath);
2675 return SQLITE_ERROR;
2679 while( pCur->iLvl>=0 ){
2680 FsdirLevel *pLvl = &pCur->aLvl[pCur->iLvl];
2681 struct dirent *pEntry = readdir(pLvl->pDir);
2683 if( pEntry->d_name[0]=='.' ){
2684 if( pEntry->d_name[1]=='.' && pEntry->d_name[2]=='\0' ) continue;
2685 if( pEntry->d_name[1]=='\0' ) continue;
2687 sqlite3_free(pCur->zPath);
2688 pCur->zPath = sqlite3_mprintf("%s/%s", pLvl->zDir, pEntry->d_name);
2689 if( pCur->zPath==0 ) return SQLITE_NOMEM;
2690 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2691 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2692 return SQLITE_ERROR;
2696 closedir(pLvl->pDir);
2697 sqlite3_free(pLvl->zDir);
2704 sqlite3_free(pCur->zPath);
2710 ** Return values of columns for the row at which the series_cursor
2711 ** is currently pointing.
2713 static int fsdirColumn(
2714 sqlite3_vtab_cursor *cur, /* The cursor */
2715 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
2716 int i /* Which column to return */
2718 fsdir_cursor *pCur = (fsdir_cursor*)cur;
2720 case 0: { /* name */
2721 sqlite3_result_text(ctx, &pCur->zPath[pCur->nBase], -1, SQLITE_TRANSIENT);
2726 sqlite3_result_int64(ctx, pCur->sStat.st_mode);
2730 sqlite3_result_int64(ctx, pCur->sStat.st_mtime);
2733 case 3: { /* data */
2734 mode_t m = pCur->sStat.st_mode;
2736 sqlite3_result_null(ctx);
2737 #if !defined(_WIN32) && !defined(WIN32)
2738 }else if( S_ISLNK(m) ){
2740 char *aBuf = aStatic;
2745 n = readlink(pCur->zPath, aBuf, nBuf);
2747 if( aBuf!=aStatic ) sqlite3_free(aBuf);
2749 aBuf = sqlite3_malloc(nBuf);
2751 sqlite3_result_error_nomem(ctx);
2752 return SQLITE_NOMEM;
2756 sqlite3_result_text(ctx, aBuf, n, SQLITE_TRANSIENT);
2757 if( aBuf!=aStatic ) sqlite3_free(aBuf);
2760 readFileContents(ctx, pCur->zPath);
2768 ** Return the rowid for the current row. In this implementation, the
2769 ** first row returned is assigned rowid value 1, and each subsequent
2770 ** row a value 1 more than that of the previous.
2772 static int fsdirRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
2773 fsdir_cursor *pCur = (fsdir_cursor*)cur;
2774 *pRowid = pCur->iRowid;
2779 ** Return TRUE if the cursor has been moved off of the last
2782 static int fsdirEof(sqlite3_vtab_cursor *cur){
2783 fsdir_cursor *pCur = (fsdir_cursor*)cur;
2784 return (pCur->zPath==0);
2788 ** xFilter callback.
2790 static int fsdirFilter(
2791 sqlite3_vtab_cursor *cur,
2792 int idxNum, const char *idxStr,
2793 int argc, sqlite3_value **argv
2795 const char *zDir = 0;
2796 fsdir_cursor *pCur = (fsdir_cursor*)cur;
2798 fsdirResetCursor(pCur);
2801 fsdirSetErrmsg(pCur, "table function fsdir requires an argument");
2802 return SQLITE_ERROR;
2805 assert( argc==idxNum && (argc==1 || argc==2) );
2806 zDir = (const char*)sqlite3_value_text(argv[0]);
2808 fsdirSetErrmsg(pCur, "table function fsdir requires a non-NULL argument");
2809 return SQLITE_ERROR;
2812 pCur->zBase = (const char*)sqlite3_value_text(argv[1]);
2815 pCur->nBase = (int)strlen(pCur->zBase)+1;
2816 pCur->zPath = sqlite3_mprintf("%s/%s", pCur->zBase, zDir);
2818 pCur->zPath = sqlite3_mprintf("%s", zDir);
2821 if( pCur->zPath==0 ){
2822 return SQLITE_NOMEM;
2824 if( fileLinkStat(pCur->zPath, &pCur->sStat) ){
2825 fsdirSetErrmsg(pCur, "cannot stat file: %s", pCur->zPath);
2826 return SQLITE_ERROR;
2833 ** SQLite will invoke this method one or more times while planning a query
2834 ** that uses the generate_series virtual table. This routine needs to create
2835 ** a query plan for each invocation and compute an estimated cost for that
2838 ** In this implementation idxNum is used to represent the
2839 ** query plan. idxStr is unused.
2841 ** The query plan is represented by bits in idxNum:
2843 ** (1) start = $value -- constraint exists
2844 ** (2) stop = $value -- constraint exists
2845 ** (4) step = $value -- constraint exists
2846 ** (8) output in descending order
2848 static int fsdirBestIndex(
2850 sqlite3_index_info *pIdxInfo
2852 int i; /* Loop over constraints */
2855 const struct sqlite3_index_constraint *pConstraint;
2858 pConstraint = pIdxInfo->aConstraint;
2859 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2860 if( pConstraint->usable==0 ) continue;
2861 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2862 if( pConstraint->iColumn==4 ) idx4 = i;
2863 if( pConstraint->iColumn==5 ) idx5 = i;
2867 pIdxInfo->idxNum = 0;
2868 pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
2870 pIdxInfo->aConstraintUsage[idx4].omit = 1;
2871 pIdxInfo->aConstraintUsage[idx4].argvIndex = 1;
2873 pIdxInfo->aConstraintUsage[idx5].omit = 1;
2874 pIdxInfo->aConstraintUsage[idx5].argvIndex = 2;
2875 pIdxInfo->idxNum = 2;
2876 pIdxInfo->estimatedCost = 10.0;
2878 pIdxInfo->idxNum = 1;
2879 pIdxInfo->estimatedCost = 100.0;
2887 ** Register the "fsdir" virtual table.
2889 static int fsdirRegister(sqlite3 *db){
2890 static sqlite3_module fsdirModule = {
2893 fsdirConnect, /* xConnect */
2894 fsdirBestIndex, /* xBestIndex */
2895 fsdirDisconnect, /* xDisconnect */
2897 fsdirOpen, /* xOpen - open a cursor */
2898 fsdirClose, /* xClose - close a cursor */
2899 fsdirFilter, /* xFilter - configure scan constraints */
2900 fsdirNext, /* xNext - advance a cursor */
2901 fsdirEof, /* xEof - check for end of scan */
2902 fsdirColumn, /* xColumn - read data */
2903 fsdirRowid, /* xRowid - read data */
2909 0, /* xFindMethod */
2916 int rc = sqlite3_create_module(db, "fsdir", &fsdirModule, 0);
2919 #else /* SQLITE_OMIT_VIRTUALTABLE */
2920 # define fsdirRegister(x) SQLITE_OK
2926 int sqlite3_fileio_init(
2929 const sqlite3_api_routines *pApi
2932 SQLITE_EXTENSION_INIT2(pApi);
2933 (void)pzErrMsg; /* Unused parameter */
2934 rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
2935 readfileFunc, 0, 0);
2936 if( rc==SQLITE_OK ){
2937 rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
2938 writefileFunc, 0, 0);
2940 if( rc==SQLITE_OK ){
2941 rc = sqlite3_create_function(db, "lsmode", 1, SQLITE_UTF8, 0,
2944 if( rc==SQLITE_OK ){
2945 rc = fsdirRegister(db);
2950 /************************* End ../ext/misc/fileio.c ********************/
2951 /************************* Begin ../ext/misc/completion.c ******************/
2955 ** The author disclaims copyright to this source code. In place of
2956 ** a legal notice, here is a blessing:
2958 ** May you do good and not evil.
2959 ** May you find forgiveness for yourself and forgive others.
2960 ** May you share freely, never taking more than you give.
2962 *************************************************************************
2964 ** This file implements an eponymous virtual table that returns suggested
2965 ** completions for a partial SQL input.
2969 ** SELECT DISTINCT candidate COLLATE nocase
2970 ** FROM completion($prefix,$wholeline)
2973 ** The two query parameters are optional. $prefix is the text of the
2974 ** current word being typed and that is to be completed. $wholeline is
2975 ** the complete input line, used for context.
2977 ** The raw completion() table might return the same candidate multiple
2978 ** times, for example if the same column name is used to two or more
2979 ** tables. And the candidates are returned in an arbitrary order. Hence,
2980 ** the DISTINCT and ORDER BY are recommended.
2982 ** This virtual table operates at the speed of human typing, and so there
2983 ** is no attempt to make it fast. Even a slow implementation will be much
2984 ** faster than any human can type.
2987 SQLITE_EXTENSION_INIT1
2992 #ifndef SQLITE_OMIT_VIRTUALTABLE
2994 /* completion_vtab is a subclass of sqlite3_vtab which will
2995 ** serve as the underlying representation of a completion virtual table
2997 typedef struct completion_vtab completion_vtab;
2998 struct completion_vtab {
2999 sqlite3_vtab base; /* Base class - must be first */
3000 sqlite3 *db; /* Database connection for this completion vtab */
3003 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
3004 ** serve as the underlying representation of a cursor that scans
3005 ** over rows of the result
3007 typedef struct completion_cursor completion_cursor;
3008 struct completion_cursor {
3009 sqlite3_vtab_cursor base; /* Base class - must be first */
3010 sqlite3 *db; /* Database connection for this cursor */
3011 int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
3012 char *zPrefix; /* The prefix for the word we want to complete */
3013 char *zLine; /* The whole that we want to complete */
3014 const char *zCurrentRow; /* Current output row */
3015 int szRow; /* Length of the zCurrentRow string */
3016 sqlite3_stmt *pStmt; /* Current statement */
3017 sqlite3_int64 iRowid; /* The rowid */
3018 int ePhase; /* Current phase */
3019 int j; /* inter-phase counter */
3022 /* Values for ePhase:
3024 #define COMPLETION_FIRST_PHASE 1
3025 #define COMPLETION_KEYWORDS 1
3026 #define COMPLETION_PRAGMAS 2
3027 #define COMPLETION_FUNCTIONS 3
3028 #define COMPLETION_COLLATIONS 4
3029 #define COMPLETION_INDEXES 5
3030 #define COMPLETION_TRIGGERS 6
3031 #define COMPLETION_DATABASES 7
3032 #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
3033 #define COMPLETION_COLUMNS 9
3034 #define COMPLETION_MODULES 10
3035 #define COMPLETION_EOF 11
3038 ** The completionConnect() method is invoked to create a new
3039 ** completion_vtab that describes the completion virtual table.
3041 ** Think of this routine as the constructor for completion_vtab objects.
3043 ** All this routine needs to do is:
3045 ** (1) Allocate the completion_vtab object and initialize all fields.
3047 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
3048 ** result set of queries against completion will look like.
3050 static int completionConnect(
3053 int argc, const char *const*argv,
3054 sqlite3_vtab **ppVtab,
3057 completion_vtab *pNew;
3060 (void)(pAux); /* Unused parameter */
3061 (void)(argc); /* Unused parameter */
3062 (void)(argv); /* Unused parameter */
3063 (void)(pzErr); /* Unused parameter */
3065 /* Column numbers */
3066 #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
3067 #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
3068 #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
3069 #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
3071 rc = sqlite3_declare_vtab(db,
3074 " prefix TEXT HIDDEN,"
3075 " wholeline TEXT HIDDEN,"
3076 " phase INT HIDDEN" /* Used for debugging only */
3078 if( rc==SQLITE_OK ){
3079 pNew = sqlite3_malloc( sizeof(*pNew) );
3080 *ppVtab = (sqlite3_vtab*)pNew;
3081 if( pNew==0 ) return SQLITE_NOMEM;
3082 memset(pNew, 0, sizeof(*pNew));
3089 ** This method is the destructor for completion_cursor objects.
3091 static int completionDisconnect(sqlite3_vtab *pVtab){
3092 sqlite3_free(pVtab);
3097 ** Constructor for a new completion_cursor object.
3099 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
3100 completion_cursor *pCur;
3101 pCur = sqlite3_malloc( sizeof(*pCur) );
3102 if( pCur==0 ) return SQLITE_NOMEM;
3103 memset(pCur, 0, sizeof(*pCur));
3104 pCur->db = ((completion_vtab*)p)->db;
3105 *ppCursor = &pCur->base;
3110 ** Reset the completion_cursor.
3112 static void completionCursorReset(completion_cursor *pCur){
3113 sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
3114 sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
3115 sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
3120 ** Destructor for a completion_cursor.
3122 static int completionClose(sqlite3_vtab_cursor *cur){
3123 completionCursorReset((completion_cursor*)cur);
3129 ** Advance a completion_cursor to its next row of output.
3131 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
3132 ** record the current state of the scan. This routine sets ->zCurrentRow
3133 ** to the current row of output and then returns. If no more rows remain,
3134 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
3135 ** table that has reached the end of its scan.
3137 ** The current implementation just lists potential identifiers and
3138 ** keywords and filters them by zPrefix. Future enhancements should
3139 ** take zLine into account to try to restrict the set of identifiers and
3140 ** keywords based on what would be legal at the current point of input.
3142 static int completionNext(sqlite3_vtab_cursor *cur){
3143 completion_cursor *pCur = (completion_cursor*)cur;
3144 int eNextPhase = 0; /* Next phase to try if current phase reaches end */
3145 int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
3147 while( pCur->ePhase!=COMPLETION_EOF ){
3148 switch( pCur->ePhase ){
3149 case COMPLETION_KEYWORDS: {
3150 if( pCur->j >= sqlite3_keyword_count() ){
3151 pCur->zCurrentRow = 0;
3152 pCur->ePhase = COMPLETION_DATABASES;
3154 sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
3159 case COMPLETION_DATABASES: {
3160 if( pCur->pStmt==0 ){
3161 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
3165 eNextPhase = COMPLETION_TABLES;
3168 case COMPLETION_TABLES: {
3169 if( pCur->pStmt==0 ){
3172 const char *zSep = "";
3173 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3174 while( sqlite3_step(pS2)==SQLITE_ROW ){
3175 const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3176 zSql = sqlite3_mprintf(
3178 "SELECT name FROM \"%w\".sqlite_master",
3181 if( zSql==0 ) return SQLITE_NOMEM;
3184 sqlite3_finalize(pS2);
3185 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3189 eNextPhase = COMPLETION_COLUMNS;
3192 case COMPLETION_COLUMNS: {
3193 if( pCur->pStmt==0 ){
3196 const char *zSep = "";
3197 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
3198 while( sqlite3_step(pS2)==SQLITE_ROW ){
3199 const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
3200 zSql = sqlite3_mprintf(
3202 "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
3203 " JOIN pragma_table_info(sm.name,%Q) AS pti"
3204 " WHERE sm.type='table'",
3205 zSql, zSep, zDb, zDb
3207 if( zSql==0 ) return SQLITE_NOMEM;
3210 sqlite3_finalize(pS2);
3211 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
3215 eNextPhase = COMPLETION_EOF;
3220 /* This case is when the phase presets zCurrentRow */
3221 if( pCur->zCurrentRow==0 ) continue;
3223 if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
3224 /* Extract the next row of content */
3225 pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
3226 pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
3228 /* When all rows are finished, advance to the next phase */
3229 sqlite3_finalize(pCur->pStmt);
3231 pCur->ePhase = eNextPhase;
3235 if( pCur->nPrefix==0 ) break;
3236 if( pCur->nPrefix<=pCur->szRow
3237 && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
3247 ** Return values of columns for the row at which the completion_cursor
3248 ** is currently pointing.
3250 static int completionColumn(
3251 sqlite3_vtab_cursor *cur, /* The cursor */
3252 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
3253 int i /* Which column to return */
3255 completion_cursor *pCur = (completion_cursor*)cur;
3257 case COMPLETION_COLUMN_CANDIDATE: {
3258 sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
3261 case COMPLETION_COLUMN_PREFIX: {
3262 sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
3265 case COMPLETION_COLUMN_WHOLELINE: {
3266 sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
3269 case COMPLETION_COLUMN_PHASE: {
3270 sqlite3_result_int(ctx, pCur->ePhase);
3278 ** Return the rowid for the current row. In this implementation, the
3279 ** rowid is the same as the output value.
3281 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
3282 completion_cursor *pCur = (completion_cursor*)cur;
3283 *pRowid = pCur->iRowid;
3288 ** Return TRUE if the cursor has been moved off of the last
3291 static int completionEof(sqlite3_vtab_cursor *cur){
3292 completion_cursor *pCur = (completion_cursor*)cur;
3293 return pCur->ePhase >= COMPLETION_EOF;
3297 ** This method is called to "rewind" the completion_cursor object back
3298 ** to the first row of output. This method is always called at least
3299 ** once prior to any call to completionColumn() or completionRowid() or
3302 static int completionFilter(
3303 sqlite3_vtab_cursor *pVtabCursor,
3304 int idxNum, const char *idxStr,
3305 int argc, sqlite3_value **argv
3307 completion_cursor *pCur = (completion_cursor *)pVtabCursor;
3309 (void)(idxStr); /* Unused parameter */
3310 (void)(argc); /* Unused parameter */
3311 completionCursorReset(pCur);
3313 pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
3314 if( pCur->nPrefix>0 ){
3315 pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3316 if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3321 pCur->nLine = sqlite3_value_bytes(argv[iArg]);
3322 if( pCur->nLine>0 ){
3323 pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
3324 if( pCur->zLine==0 ) return SQLITE_NOMEM;
3327 if( pCur->zLine!=0 && pCur->zPrefix==0 ){
3328 int i = pCur->nLine;
3329 while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
3332 pCur->nPrefix = pCur->nLine - i;
3333 if( pCur->nPrefix>0 ){
3334 pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
3335 if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
3339 pCur->ePhase = COMPLETION_FIRST_PHASE;
3340 return completionNext(pVtabCursor);
3344 ** SQLite will invoke this method one or more times while planning a query
3345 ** that uses the completion virtual table. This routine needs to create
3346 ** a query plan for each invocation and compute an estimated cost for that
3349 ** There are two hidden parameters that act as arguments to the table-valued
3350 ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
3351 ** is available and bit 1 is set if "wholeline" is available.
3353 static int completionBestIndex(
3355 sqlite3_index_info *pIdxInfo
3357 int i; /* Loop over constraints */
3358 int idxNum = 0; /* The query plan bitmask */
3359 int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
3360 int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
3361 int nArg = 0; /* Number of arguments that completeFilter() expects */
3362 const struct sqlite3_index_constraint *pConstraint;
3364 (void)(tab); /* Unused parameter */
3365 pConstraint = pIdxInfo->aConstraint;
3366 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
3367 if( pConstraint->usable==0 ) continue;
3368 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
3369 switch( pConstraint->iColumn ){
3370 case COMPLETION_COLUMN_PREFIX:
3374 case COMPLETION_COLUMN_WHOLELINE:
3381 pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
3382 pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
3384 if( wholelineIdx>=0 ){
3385 pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
3386 pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
3388 pIdxInfo->idxNum = idxNum;
3389 pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
3390 pIdxInfo->estimatedRows = 500 - 100*nArg;
3395 ** This following structure defines all the methods for the
3396 ** completion virtual table.
3398 static sqlite3_module completionModule = {
3401 completionConnect, /* xConnect */
3402 completionBestIndex, /* xBestIndex */
3403 completionDisconnect, /* xDisconnect */
3405 completionOpen, /* xOpen - open a cursor */
3406 completionClose, /* xClose - close a cursor */
3407 completionFilter, /* xFilter - configure scan constraints */
3408 completionNext, /* xNext - advance a cursor */
3409 completionEof, /* xEof - check for end of scan */
3410 completionColumn, /* xColumn - read data */
3411 completionRowid, /* xRowid - read data */
3417 0, /* xFindMethod */
3424 #endif /* SQLITE_OMIT_VIRTUALTABLE */
3426 int sqlite3CompletionVtabInit(sqlite3 *db){
3428 #ifndef SQLITE_OMIT_VIRTUALTABLE
3429 rc = sqlite3_create_module(db, "completion", &completionModule, 0);
3437 int sqlite3_completion_init(
3440 const sqlite3_api_routines *pApi
3443 SQLITE_EXTENSION_INIT2(pApi);
3444 (void)(pzErrMsg); /* Unused parameter */
3445 #ifndef SQLITE_OMIT_VIRTUALTABLE
3446 rc = sqlite3CompletionVtabInit(db);
3451 /************************* End ../ext/misc/completion.c ********************/
3452 /************************* Begin ../ext/misc/appendvfs.c ******************/
3456 ** The author disclaims copyright to this source code. In place of
3457 ** a legal notice, here is a blessing:
3459 ** May you do good and not evil.
3460 ** May you find forgiveness for yourself and forgive others.
3461 ** May you share freely, never taking more than you give.
3463 ******************************************************************************
3465 ** This file implements a VFS shim that allows an SQLite database to be
3466 ** appended onto the end of some other file, such as an executable.
3468 ** A special record must appear at the end of the file that identifies the
3469 ** file as an appended database and provides an offset to page 1. For
3470 ** best performance page 1 should be located at a disk page boundary, though
3471 ** that is not required.
3473 ** When opening a database using this VFS, the connection might treat
3474 ** the file as an ordinary SQLite database, or it might treat is as a
3475 ** database appended onto some other file. Here are the rules:
3477 ** (1) When opening a new empty file, that file is treated as an ordinary
3480 ** (2) When opening a file that begins with the standard SQLite prefix
3481 ** string "SQLite format 3", that file is treated as an ordinary
3484 ** (3) When opening a file that ends with the appendvfs trailer string
3485 ** "Start-Of-SQLite3-NNNNNNNN" that file is treated as an appended
3488 ** (4) If none of the above apply and the SQLITE_OPEN_CREATE flag is
3489 ** set, then a new database is appended to the already existing file.
3491 ** (5) Otherwise, SQLITE_CANTOPEN is returned.
3493 ** To avoid unnecessary complications with the PENDING_BYTE, the size of
3494 ** the file containing the database is limited to 1GB. This VFS will refuse
3495 ** to read or write past the 1GB mark. This restriction might be lifted in
3496 ** future versions. For now, if you need a large database, then keep the
3497 ** database in a separate file.
3499 ** If the file being opened is not an appended database, then this shim is
3500 ** a pass-through into the default underlying VFS.
3502 SQLITE_EXTENSION_INIT1
3506 /* The append mark at the end of the database is:
3508 ** Start-Of-SQLite3-NNNNNNNN
3509 ** 123456789 123456789 12345
3511 ** The NNNNNNNN represents a 64-bit big-endian unsigned integer which is
3512 ** the offset to page 1.
3514 #define APND_MARK_PREFIX "Start-Of-SQLite3-"
3515 #define APND_MARK_PREFIX_SZ 17
3516 #define APND_MARK_SIZE 25
3519 ** Maximum size of the combined prefix + database + append-mark. This
3520 ** must be less than 0x40000000 to avoid locking issues on Windows.
3522 #define APND_MAX_SIZE (65536*15259)
3525 ** Forward declaration of objects used by this utility
3527 typedef struct sqlite3_vfs ApndVfs;
3528 typedef struct ApndFile ApndFile;
3530 /* Access to a lower-level VFS that (might) implement dynamic loading,
3531 ** access to randomness, etc.
3533 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
3534 #define ORIGFILE(p) ((sqlite3_file*)(((ApndFile*)(p))+1))
3538 sqlite3_file base; /* IO methods */
3539 sqlite3_int64 iPgOne; /* File offset to page 1 */
3540 sqlite3_int64 iMark; /* Start of the append-mark */
3544 ** Methods for ApndFile
3546 static int apndClose(sqlite3_file*);
3547 static int apndRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
3548 static int apndWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
3549 static int apndTruncate(sqlite3_file*, sqlite3_int64 size);
3550 static int apndSync(sqlite3_file*, int flags);
3551 static int apndFileSize(sqlite3_file*, sqlite3_int64 *pSize);
3552 static int apndLock(sqlite3_file*, int);
3553 static int apndUnlock(sqlite3_file*, int);
3554 static int apndCheckReservedLock(sqlite3_file*, int *pResOut);
3555 static int apndFileControl(sqlite3_file*, int op, void *pArg);
3556 static int apndSectorSize(sqlite3_file*);
3557 static int apndDeviceCharacteristics(sqlite3_file*);
3558 static int apndShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
3559 static int apndShmLock(sqlite3_file*, int offset, int n, int flags);
3560 static void apndShmBarrier(sqlite3_file*);
3561 static int apndShmUnmap(sqlite3_file*, int deleteFlag);
3562 static int apndFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
3563 static int apndUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
3566 ** Methods for ApndVfs
3568 static int apndOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
3569 static int apndDelete(sqlite3_vfs*, const char *zName, int syncDir);
3570 static int apndAccess(sqlite3_vfs*, const char *zName, int flags, int *);
3571 static int apndFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
3572 static void *apndDlOpen(sqlite3_vfs*, const char *zFilename);
3573 static void apndDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
3574 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
3575 static void apndDlClose(sqlite3_vfs*, void*);
3576 static int apndRandomness(sqlite3_vfs*, int nByte, char *zOut);
3577 static int apndSleep(sqlite3_vfs*, int microseconds);
3578 static int apndCurrentTime(sqlite3_vfs*, double*);
3579 static int apndGetLastError(sqlite3_vfs*, int, char *);
3580 static int apndCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
3581 static int apndSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
3582 static sqlite3_syscall_ptr apndGetSystemCall(sqlite3_vfs*, const char *z);
3583 static const char *apndNextSystemCall(sqlite3_vfs*, const char *zName);
3585 static sqlite3_vfs apnd_vfs = {
3586 3, /* iVersion (set when registered) */
3587 0, /* szOsFile (set when registered) */
3588 1024, /* mxPathname */
3590 "apndvfs", /* zName */
3591 0, /* pAppData (set when registered) */
3592 apndOpen, /* xOpen */
3593 apndDelete, /* xDelete */
3594 apndAccess, /* xAccess */
3595 apndFullPathname, /* xFullPathname */
3596 apndDlOpen, /* xDlOpen */
3597 apndDlError, /* xDlError */
3598 apndDlSym, /* xDlSym */
3599 apndDlClose, /* xDlClose */
3600 apndRandomness, /* xRandomness */
3601 apndSleep, /* xSleep */
3602 apndCurrentTime, /* xCurrentTime */
3603 apndGetLastError, /* xGetLastError */
3604 apndCurrentTimeInt64, /* xCurrentTimeInt64 */
3605 apndSetSystemCall, /* xSetSystemCall */
3606 apndGetSystemCall, /* xGetSystemCall */
3607 apndNextSystemCall /* xNextSystemCall */
3610 static const sqlite3_io_methods apnd_io_methods = {
3612 apndClose, /* xClose */
3613 apndRead, /* xRead */
3614 apndWrite, /* xWrite */
3615 apndTruncate, /* xTruncate */
3616 apndSync, /* xSync */
3617 apndFileSize, /* xFileSize */
3618 apndLock, /* xLock */
3619 apndUnlock, /* xUnlock */
3620 apndCheckReservedLock, /* xCheckReservedLock */
3621 apndFileControl, /* xFileControl */
3622 apndSectorSize, /* xSectorSize */
3623 apndDeviceCharacteristics, /* xDeviceCharacteristics */
3624 apndShmMap, /* xShmMap */
3625 apndShmLock, /* xShmLock */
3626 apndShmBarrier, /* xShmBarrier */
3627 apndShmUnmap, /* xShmUnmap */
3628 apndFetch, /* xFetch */
3629 apndUnfetch /* xUnfetch */
3635 ** Close an apnd-file.
3637 static int apndClose(sqlite3_file *pFile){
3638 pFile = ORIGFILE(pFile);
3639 return pFile->pMethods->xClose(pFile);
3643 ** Read data from an apnd-file.
3645 static int apndRead(
3646 sqlite3_file *pFile,
3651 ApndFile *p = (ApndFile *)pFile;
3652 pFile = ORIGFILE(pFile);
3653 return pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3657 ** Add the append-mark onto the end of the file.
3659 static int apndWriteMark(ApndFile *p, sqlite3_file *pFile){
3661 unsigned char a[APND_MARK_SIZE];
3662 memcpy(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ);
3664 a[APND_MARK_PREFIX_SZ+i] = (p->iPgOne >> (56 - i*8)) & 0xff;
3666 return pFile->pMethods->xWrite(pFile, a, APND_MARK_SIZE, p->iMark);
3670 ** Write data to an apnd-file.
3672 static int apndWrite(
3673 sqlite3_file *pFile,
3679 ApndFile *p = (ApndFile *)pFile;
3680 pFile = ORIGFILE(pFile);
3681 if( iOfst+iAmt>=APND_MAX_SIZE ) return SQLITE_FULL;
3682 rc = pFile->pMethods->xWrite(pFile, zBuf, iAmt, iOfst+p->iPgOne);
3683 if( rc==SQLITE_OK && iOfst + iAmt + p->iPgOne > p->iMark ){
3684 sqlite3_int64 sz = 0;
3685 rc = pFile->pMethods->xFileSize(pFile, &sz);
3686 if( rc==SQLITE_OK ){
3687 p->iMark = sz - APND_MARK_SIZE;
3688 if( iOfst + iAmt + p->iPgOne > p->iMark ){
3689 p->iMark = p->iPgOne + iOfst + iAmt;
3690 rc = apndWriteMark(p, pFile);
3698 ** Truncate an apnd-file.
3700 static int apndTruncate(sqlite3_file *pFile, sqlite_int64 size){
3702 ApndFile *p = (ApndFile *)pFile;
3703 pFile = ORIGFILE(pFile);
3704 rc = pFile->pMethods->xTruncate(pFile, size+p->iPgOne+APND_MARK_SIZE);
3705 if( rc==SQLITE_OK ){
3706 p->iMark = p->iPgOne+size;
3707 rc = apndWriteMark(p, pFile);
3713 ** Sync an apnd-file.
3715 static int apndSync(sqlite3_file *pFile, int flags){
3716 pFile = ORIGFILE(pFile);
3717 return pFile->pMethods->xSync(pFile, flags);
3721 ** Return the current file-size of an apnd-file.
3723 static int apndFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
3724 ApndFile *p = (ApndFile *)pFile;
3726 pFile = ORIGFILE(p);
3727 rc = pFile->pMethods->xFileSize(pFile, pSize);
3728 if( rc==SQLITE_OK && p->iPgOne ){
3729 *pSize -= p->iPgOne + APND_MARK_SIZE;
3735 ** Lock an apnd-file.
3737 static int apndLock(sqlite3_file *pFile, int eLock){
3738 pFile = ORIGFILE(pFile);
3739 return pFile->pMethods->xLock(pFile, eLock);
3743 ** Unlock an apnd-file.
3745 static int apndUnlock(sqlite3_file *pFile, int eLock){
3746 pFile = ORIGFILE(pFile);
3747 return pFile->pMethods->xUnlock(pFile, eLock);
3751 ** Check if another file-handle holds a RESERVED lock on an apnd-file.
3753 static int apndCheckReservedLock(sqlite3_file *pFile, int *pResOut){
3754 pFile = ORIGFILE(pFile);
3755 return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
3759 ** File control method. For custom operations on an apnd-file.
3761 static int apndFileControl(sqlite3_file *pFile, int op, void *pArg){
3762 ApndFile *p = (ApndFile *)pFile;
3764 pFile = ORIGFILE(pFile);
3765 rc = pFile->pMethods->xFileControl(pFile, op, pArg);
3766 if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
3767 *(char**)pArg = sqlite3_mprintf("apnd(%lld)/%z", p->iPgOne, *(char**)pArg);
3773 ** Return the sector-size in bytes for an apnd-file.
3775 static int apndSectorSize(sqlite3_file *pFile){
3776 pFile = ORIGFILE(pFile);
3777 return pFile->pMethods->xSectorSize(pFile);
3781 ** Return the device characteristic flags supported by an apnd-file.
3783 static int apndDeviceCharacteristics(sqlite3_file *pFile){
3784 pFile = ORIGFILE(pFile);
3785 return pFile->pMethods->xDeviceCharacteristics(pFile);
3788 /* Create a shared memory file mapping */
3789 static int apndShmMap(
3790 sqlite3_file *pFile,
3796 pFile = ORIGFILE(pFile);
3797 return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
3800 /* Perform locking on a shared-memory segment */
3801 static int apndShmLock(sqlite3_file *pFile, int offset, int n, int flags){
3802 pFile = ORIGFILE(pFile);
3803 return pFile->pMethods->xShmLock(pFile,offset,n,flags);
3806 /* Memory barrier operation on shared memory */
3807 static void apndShmBarrier(sqlite3_file *pFile){
3808 pFile = ORIGFILE(pFile);
3809 pFile->pMethods->xShmBarrier(pFile);
3812 /* Unmap a shared memory segment */
3813 static int apndShmUnmap(sqlite3_file *pFile, int deleteFlag){
3814 pFile = ORIGFILE(pFile);
3815 return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
3818 /* Fetch a page of a memory-mapped file */
3819 static int apndFetch(
3820 sqlite3_file *pFile,
3821 sqlite3_int64 iOfst,
3825 ApndFile *p = (ApndFile *)pFile;
3826 pFile = ORIGFILE(pFile);
3827 return pFile->pMethods->xFetch(pFile, iOfst+p->iPgOne, iAmt, pp);
3830 /* Release a memory-mapped page */
3831 static int apndUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
3832 ApndFile *p = (ApndFile *)pFile;
3833 pFile = ORIGFILE(pFile);
3834 return pFile->pMethods->xUnfetch(pFile, iOfst+p->iPgOne, pPage);
3838 ** Check to see if the file is an ordinary SQLite database file.
3840 static int apndIsOrdinaryDatabaseFile(sqlite3_int64 sz, sqlite3_file *pFile){
3843 static const char aSqliteHdr[] = "SQLite format 3";
3844 if( sz<512 ) return 0;
3845 rc = pFile->pMethods->xRead(pFile, zHdr, sizeof(zHdr), 0);
3847 return memcmp(zHdr, aSqliteHdr, sizeof(zHdr))==0;
3851 ** Try to read the append-mark off the end of a file. Return the
3852 ** start of the appended database if the append-mark is present. If
3853 ** there is no append-mark, return -1;
3855 static sqlite3_int64 apndReadMark(sqlite3_int64 sz, sqlite3_file *pFile){
3857 sqlite3_int64 iMark;
3858 unsigned char a[APND_MARK_SIZE];
3860 if( sz<=APND_MARK_SIZE ) return -1;
3861 rc = pFile->pMethods->xRead(pFile, a, APND_MARK_SIZE, sz-APND_MARK_SIZE);
3863 if( memcmp(a, APND_MARK_PREFIX, APND_MARK_PREFIX_SZ)!=0 ) return -1;
3864 iMark = ((sqlite3_int64)(a[APND_MARK_PREFIX_SZ]&0x7f))<<56;
3866 iMark += (sqlite3_int64)a[APND_MARK_PREFIX_SZ+i]<<(56-8*i);
3872 ** Open an apnd file handle.
3874 static int apndOpen(
3877 sqlite3_file *pFile,
3882 sqlite3_file *pSubFile;
3883 sqlite3_vfs *pSubVfs;
3886 pSubVfs = ORIGVFS(pVfs);
3887 if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
3888 return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
3890 p = (ApndFile*)pFile;
3891 memset(p, 0, sizeof(*p));
3892 pSubFile = ORIGFILE(pFile);
3893 p->base.pMethods = &apnd_io_methods;
3894 rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
3895 if( rc ) goto apnd_open_done;
3896 rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
3898 pSubFile->pMethods->xClose(pSubFile);
3899 goto apnd_open_done;
3901 if( apndIsOrdinaryDatabaseFile(sz, pSubFile) ){
3902 memmove(pFile, pSubFile, pSubVfs->szOsFile);
3906 p->iPgOne = apndReadMark(sz, pFile);
3910 if( (flags & SQLITE_OPEN_CREATE)==0 ){
3911 pSubFile->pMethods->xClose(pSubFile);
3912 rc = SQLITE_CANTOPEN;
3914 p->iPgOne = (sz+0xfff) & ~(sqlite3_int64)0xfff;
3916 if( rc ) pFile->pMethods = 0;
3921 ** All other VFS methods are pass-thrus.
3923 static int apndDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
3924 return ORIGVFS(pVfs)->xDelete(ORIGVFS(pVfs), zPath, dirSync);
3926 static int apndAccess(
3932 return ORIGVFS(pVfs)->xAccess(ORIGVFS(pVfs), zPath, flags, pResOut);
3934 static int apndFullPathname(
3940 return ORIGVFS(pVfs)->xFullPathname(ORIGVFS(pVfs),zPath,nOut,zOut);
3942 static void *apndDlOpen(sqlite3_vfs *pVfs, const char *zPath){
3943 return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
3945 static void apndDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
3946 ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
3948 static void (*apndDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
3949 return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
3951 static void apndDlClose(sqlite3_vfs *pVfs, void *pHandle){
3952 ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
3954 static int apndRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
3955 return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
3957 static int apndSleep(sqlite3_vfs *pVfs, int nMicro){
3958 return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
3960 static int apndCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
3961 return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
3963 static int apndGetLastError(sqlite3_vfs *pVfs, int a, char *b){
3964 return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
3966 static int apndCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
3967 return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
3969 static int apndSetSystemCall(
3972 sqlite3_syscall_ptr pCall
3974 return ORIGVFS(pVfs)->xSetSystemCall(ORIGVFS(pVfs),zName,pCall);
3976 static sqlite3_syscall_ptr apndGetSystemCall(
3980 return ORIGVFS(pVfs)->xGetSystemCall(ORIGVFS(pVfs),zName);
3982 static const char *apndNextSystemCall(sqlite3_vfs *pVfs, const char *zName){
3983 return ORIGVFS(pVfs)->xNextSystemCall(ORIGVFS(pVfs), zName);
3991 ** This routine is called when the extension is loaded.
3992 ** Register the new VFS.
3994 int sqlite3_appendvfs_init(
3997 const sqlite3_api_routines *pApi
4001 SQLITE_EXTENSION_INIT2(pApi);
4004 pOrig = sqlite3_vfs_find(0);
4005 apnd_vfs.iVersion = pOrig->iVersion;
4006 apnd_vfs.pAppData = pOrig;
4007 apnd_vfs.szOsFile = pOrig->szOsFile + sizeof(ApndFile);
4008 rc = sqlite3_vfs_register(&apnd_vfs, 0);
4009 #ifdef APPENDVFS_TEST
4010 if( rc==SQLITE_OK ){
4011 rc = sqlite3_auto_extension((void(*)(void))apndvfsRegister);
4014 if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
4018 /************************* End ../ext/misc/appendvfs.c ********************/
4019 #ifdef SQLITE_HAVE_ZLIB
4020 /************************* Begin ../ext/misc/zipfile.c ******************/
4024 ** The author disclaims copyright to this source code. In place of
4025 ** a legal notice, here is a blessing:
4027 ** May you do good and not evil.
4028 ** May you find forgiveness for yourself and forgive others.
4029 ** May you share freely, never taking more than you give.
4031 ******************************************************************************
4033 ** This file implements a virtual table for reading and writing ZIP archive
4038 ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename);
4040 ** Current limitations:
4042 ** * No support for encryption
4043 ** * No support for ZIP archives spanning multiple files
4044 ** * No support for zip64 extensions
4045 ** * Only the "inflate/deflate" (zlib) compression method is supported
4047 SQLITE_EXTENSION_INIT1
4054 #ifndef SQLITE_OMIT_VIRTUALTABLE
4056 #ifndef SQLITE_AMALGAMATION
4058 /* typedef sqlite3_int64 i64; */
4059 /* typedef unsigned char u8; */
4060 typedef unsigned short u16;
4061 typedef unsigned long u32;
4062 #define MIN(a,b) ((a)<(b) ? (a) : (b))
4064 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
4065 # define ALWAYS(X) (1)
4066 # define NEVER(X) (0)
4067 #elif !defined(NDEBUG)
4068 # define ALWAYS(X) ((X)?1:(assert(0),0))
4069 # define NEVER(X) ((X)?(assert(0),1):0)
4071 # define ALWAYS(X) (X)
4072 # define NEVER(X) (X)
4075 #endif /* SQLITE_AMALGAMATION */
4078 ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK.
4080 ** In some ways it would be better to obtain these values from system
4081 ** header files. But, the dependency is undesirable and (a) these
4082 ** have been stable for decades, (b) the values are part of POSIX and
4083 ** are also made explicit in [man stat], and (c) are part of the
4084 ** file format for zip archives.
4087 # define S_IFDIR 0040000
4090 # define S_IFREG 0100000
4093 # define S_IFLNK 0120000
4096 static const char ZIPFILE_SCHEMA[] =
4098 "name PRIMARY KEY," /* 0: Name of file in zip archive */
4099 "mode," /* 1: POSIX mode for file */
4100 "mtime," /* 2: Last modification time (secs since 1970)*/
4101 "sz," /* 3: Size of object */
4102 "rawdata," /* 4: Raw data */
4103 "data," /* 5: Uncompressed data */
4104 "method," /* 6: Compression method (integer) */
4105 "z HIDDEN" /* 7: Name of zip file */
4108 #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */
4109 #define ZIPFILE_BUFFER_SIZE (64*1024)
4113 ** Magic numbers used to read and write zip files.
4115 ** ZIPFILE_NEWENTRY_MADEBY:
4116 ** Use this value for the "version-made-by" field in new zip file
4117 ** entries. The upper byte indicates "unix", and the lower byte
4118 ** indicates that the zip file matches pkzip specification 3.0.
4119 ** This is what info-zip seems to do.
4121 ** ZIPFILE_NEWENTRY_REQUIRED:
4122 ** Value for "version-required-to-extract" field of new entries.
4123 ** Version 2.0 is required to support folders and deflate compression.
4125 ** ZIPFILE_NEWENTRY_FLAGS:
4126 ** Value for "general-purpose-bit-flags" field of new entries. Bit
4127 ** 11 means "utf-8 filename and comment".
4129 ** ZIPFILE_SIGNATURE_CDS:
4130 ** First 4 bytes of a valid CDS record.
4132 ** ZIPFILE_SIGNATURE_LFH:
4133 ** First 4 bytes of a valid LFH record.
4135 ** ZIPFILE_SIGNATURE_EOCD
4136 ** First 4 bytes of a valid EOCD record.
4138 #define ZIPFILE_EXTRA_TIMESTAMP 0x5455
4139 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30)
4140 #define ZIPFILE_NEWENTRY_REQUIRED 20
4141 #define ZIPFILE_NEWENTRY_FLAGS 0x800
4142 #define ZIPFILE_SIGNATURE_CDS 0x02014b50
4143 #define ZIPFILE_SIGNATURE_LFH 0x04034b50
4144 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50
4147 ** The sizes of the fixed-size part of each of the three main data
4148 ** structures in a zip archive.
4150 #define ZIPFILE_LFH_FIXED_SZ 30
4151 #define ZIPFILE_EOCD_FIXED_SZ 22
4152 #define ZIPFILE_CDS_FIXED_SZ 46
4155 *** 4.3.16 End of central directory record:
4157 *** end of central dir signature 4 bytes (0x06054b50)
4158 *** number of this disk 2 bytes
4159 *** number of the disk with the
4160 *** start of the central directory 2 bytes
4161 *** total number of entries in the
4162 *** central directory on this disk 2 bytes
4163 *** total number of entries in
4164 *** the central directory 2 bytes
4165 *** size of the central directory 4 bytes
4166 *** offset of start of central
4167 *** directory with respect to
4168 *** the starting disk number 4 bytes
4169 *** .ZIP file comment length 2 bytes
4170 *** .ZIP file comment (variable size)
4172 typedef struct ZipfileEOCD ZipfileEOCD;
4173 struct ZipfileEOCD {
4183 *** 4.3.12 Central directory structure:
4187 *** central file header signature 4 bytes (0x02014b50)
4188 *** version made by 2 bytes
4189 *** version needed to extract 2 bytes
4190 *** general purpose bit flag 2 bytes
4191 *** compression method 2 bytes
4192 *** last mod file time 2 bytes
4193 *** last mod file date 2 bytes
4195 *** compressed size 4 bytes
4196 *** uncompressed size 4 bytes
4197 *** file name length 2 bytes
4198 *** extra field length 2 bytes
4199 *** file comment length 2 bytes
4200 *** disk number start 2 bytes
4201 *** internal file attributes 2 bytes
4202 *** external file attributes 4 bytes
4203 *** relative offset of local header 4 bytes
4205 typedef struct ZipfileCDS ZipfileCDS;
4208 u16 iVersionExtract;
4223 char *zFile; /* Filename (sqlite3_malloc()) */
4227 *** 4.3.7 Local file header:
4229 *** local file header signature 4 bytes (0x04034b50)
4230 *** version needed to extract 2 bytes
4231 *** general purpose bit flag 2 bytes
4232 *** compression method 2 bytes
4233 *** last mod file time 2 bytes
4234 *** last mod file date 2 bytes
4236 *** compressed size 4 bytes
4237 *** uncompressed size 4 bytes
4238 *** file name length 2 bytes
4239 *** extra field length 2 bytes
4242 typedef struct ZipfileLFH ZipfileLFH;
4244 u16 iVersionExtract;
4256 typedef struct ZipfileEntry ZipfileEntry;
4257 struct ZipfileEntry {
4258 ZipfileCDS cds; /* Parsed CDS record */
4259 u32 mUnixTime; /* Modification time, in UNIX format */
4260 u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */
4261 i64 iDataOff; /* Offset to data in file (if aData==0) */
4262 u8 *aData; /* cds.szCompressed bytes of compressed data */
4263 ZipfileEntry *pNext; /* Next element in in-memory CDS */
4267 ** Cursor type for zipfile tables.
4269 typedef struct ZipfileCsr ZipfileCsr;
4271 sqlite3_vtab_cursor base; /* Base class - must be first */
4272 i64 iId; /* Cursor ID */
4273 u8 bEof; /* True when at EOF */
4274 u8 bNoop; /* If next xNext() call is no-op */
4276 /* Used outside of write transactions */
4277 FILE *pFile; /* Zip file */
4278 i64 iNextOff; /* Offset of next record in central directory */
4279 ZipfileEOCD eocd; /* Parse of central directory record */
4281 ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */
4282 ZipfileEntry *pCurrent; /* Current entry */
4283 ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */
4286 typedef struct ZipfileTab ZipfileTab;
4288 sqlite3_vtab base; /* Base class - must be first */
4289 char *zFile; /* Zip file this table accesses (may be NULL) */
4290 sqlite3 *db; /* Host database connection */
4291 u8 *aBuffer; /* Temporary buffer used for various tasks */
4293 ZipfileCsr *pCsrList; /* List of cursors */
4296 /* The following are used by write transactions only */
4297 ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */
4298 ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */
4299 FILE *pWriteFd; /* File handle open on zip archive */
4300 i64 szCurrent; /* Current size of zip archive */
4301 i64 szOrig; /* Size of archive at start of transaction */
4305 ** Set the error message contained in context ctx to the results of
4306 ** vprintf(zFmt, ...).
4308 static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){
4312 zMsg = sqlite3_vmprintf(zFmt, ap);
4313 sqlite3_result_error(ctx, zMsg, -1);
4319 ** If string zIn is quoted, dequote it in place. Otherwise, if the string
4320 ** is not quoted, do nothing.
4322 static void zipfileDequote(char *zIn){
4324 if( q=='"' || q=='\'' || q=='`' || q=='[' ){
4327 if( q=='[' ) q = ']';
4328 while( ALWAYS(zIn[iIn]) ){
4329 char c = zIn[iIn++];
4330 if( c==q && zIn[iIn++]!=q ) break;
4338 ** Construct a new ZipfileTab virtual table object.
4340 ** argv[0] -> module name ("zipfile")
4341 ** argv[1] -> database name
4342 ** argv[2] -> table name
4343 ** argv[...] -> "column name" and other module argument fields.
4345 static int zipfileConnect(
4348 int argc, const char *const*argv,
4349 sqlite3_vtab **ppVtab,
4352 int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE;
4354 const char *zFile = 0;
4355 ZipfileTab *pNew = 0;
4358 /* If the table name is not "zipfile", require that the argument be
4359 ** specified. This stops zipfile tables from being created as:
4361 ** CREATE VIRTUAL TABLE zzz USING zipfile();
4363 ** It does not prevent:
4365 ** CREATE VIRTUAL TABLE zipfile USING zipfile();
4367 assert( 0==sqlite3_stricmp(argv[0], "zipfile") );
4368 if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){
4369 *pzErr = sqlite3_mprintf("zipfile constructor requires one argument");
4370 return SQLITE_ERROR;
4375 nFile = (int)strlen(zFile)+1;
4378 rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA);
4379 if( rc==SQLITE_OK ){
4380 pNew = (ZipfileTab*)sqlite3_malloc(nByte+nFile);
4381 if( pNew==0 ) return SQLITE_NOMEM;
4382 memset(pNew, 0, nByte+nFile);
4384 pNew->aBuffer = (u8*)&pNew[1];
4386 pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE];
4387 memcpy(pNew->zFile, zFile, nFile);
4388 zipfileDequote(pNew->zFile);
4391 *ppVtab = (sqlite3_vtab*)pNew;
4396 ** Free the ZipfileEntry structure indicated by the only argument.
4398 static void zipfileEntryFree(ZipfileEntry *p){
4400 sqlite3_free(p->cds.zFile);
4406 ** Release resources that should be freed at the end of a write
4409 static void zipfileCleanupTransaction(ZipfileTab *pTab){
4410 ZipfileEntry *pEntry;
4411 ZipfileEntry *pNext;
4413 if( pTab->pWriteFd ){
4414 fclose(pTab->pWriteFd);
4417 for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){
4418 pNext = pEntry->pNext;
4419 zipfileEntryFree(pEntry);
4421 pTab->pFirstEntry = 0;
4422 pTab->pLastEntry = 0;
4423 pTab->szCurrent = 0;
4428 ** This method is the destructor for zipfile vtab objects.
4430 static int zipfileDisconnect(sqlite3_vtab *pVtab){
4431 zipfileCleanupTransaction((ZipfileTab*)pVtab);
4432 sqlite3_free(pVtab);
4437 ** Constructor for a new ZipfileCsr object.
4439 static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){
4440 ZipfileTab *pTab = (ZipfileTab*)p;
4442 pCsr = sqlite3_malloc(sizeof(*pCsr));
4443 *ppCsr = (sqlite3_vtab_cursor*)pCsr;
4445 return SQLITE_NOMEM;
4447 memset(pCsr, 0, sizeof(*pCsr));
4448 pCsr->iId = ++pTab->iNextCsrid;
4449 pCsr->pCsrNext = pTab->pCsrList;
4450 pTab->pCsrList = pCsr;
4455 ** Reset a cursor back to the state it was in when first returned
4456 ** by zipfileOpen().
4458 static void zipfileResetCursor(ZipfileCsr *pCsr){
4460 ZipfileEntry *pNext;
4464 fclose(pCsr->pFile);
4466 zipfileEntryFree(pCsr->pCurrent);
4470 for(p=pCsr->pFreeEntry; p; p=pNext){
4472 zipfileEntryFree(p);
4477 ** Destructor for an ZipfileCsr.
4479 static int zipfileClose(sqlite3_vtab_cursor *cur){
4480 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4481 ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab);
4483 zipfileResetCursor(pCsr);
4485 /* Remove this cursor from the ZipfileTab.pCsrList list. */
4486 for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext));
4487 *pp = pCsr->pCsrNext;
4494 ** Set the error message for the virtual table associated with cursor
4495 ** pCsr to the results of vprintf(zFmt, ...).
4497 static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){
4500 sqlite3_free(pTab->base.zErrMsg);
4501 pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap);
4504 static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){
4507 sqlite3_free(pCsr->base.pVtab->zErrMsg);
4508 pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap);
4513 ** Read nRead bytes of data from offset iOff of file pFile into buffer
4514 ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code
4517 ** If an error does occur, output variable (*pzErrmsg) may be set to point
4518 ** to an English language error message. It is the responsibility of the
4519 ** caller to eventually free this buffer using
4522 static int zipfileReadData(
4523 FILE *pFile, /* Read from this file */
4524 u8 *aRead, /* Read into this buffer */
4525 int nRead, /* Number of bytes to read */
4526 i64 iOff, /* Offset to read from */
4527 char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */
4530 fseek(pFile, (long)iOff, SEEK_SET);
4531 n = fread(aRead, 1, nRead, pFile);
4532 if( (int)n!=nRead ){
4533 *pzErrmsg = sqlite3_mprintf("error in fread()");
4534 return SQLITE_ERROR;
4539 static int zipfileAppendData(
4545 fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
4546 n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
4547 if( (int)n!=nWrite ){
4548 pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
4549 return SQLITE_ERROR;
4551 pTab->szCurrent += nWrite;
4556 ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf.
4558 static u16 zipfileGetU16(const u8 *aBuf){
4559 return (aBuf[1] << 8) + aBuf[0];
4563 ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf.
4565 static u32 zipfileGetU32(const u8 *aBuf){
4566 return ((u32)(aBuf[3]) << 24)
4567 + ((u32)(aBuf[2]) << 16)
4568 + ((u32)(aBuf[1]) << 8)
4569 + ((u32)(aBuf[0]) << 0);
4573 ** Write a 16-bit little endiate integer into buffer aBuf.
4575 static void zipfilePutU16(u8 *aBuf, u16 val){
4576 aBuf[0] = val & 0xFF;
4577 aBuf[1] = (val>>8) & 0xFF;
4581 ** Write a 32-bit little endiate integer into buffer aBuf.
4583 static void zipfilePutU32(u8 *aBuf, u32 val){
4584 aBuf[0] = val & 0xFF;
4585 aBuf[1] = (val>>8) & 0xFF;
4586 aBuf[2] = (val>>16) & 0xFF;
4587 aBuf[3] = (val>>24) & 0xFF;
4590 #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) )
4591 #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) )
4593 #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; }
4594 #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; }
4597 ** Magic numbers used to read CDS records.
4599 #define ZIPFILE_CDS_NFILE_OFF 28
4600 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20
4603 ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR
4604 ** if the record is not well-formed, or SQLITE_OK otherwise.
4606 static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){
4608 u32 sig = zipfileRead32(aRead);
4610 if( sig!=ZIPFILE_SIGNATURE_CDS ){
4613 pCDS->iVersionMadeBy = zipfileRead16(aRead);
4614 pCDS->iVersionExtract = zipfileRead16(aRead);
4615 pCDS->flags = zipfileRead16(aRead);
4616 pCDS->iCompression = zipfileRead16(aRead);
4617 pCDS->mTime = zipfileRead16(aRead);
4618 pCDS->mDate = zipfileRead16(aRead);
4619 pCDS->crc32 = zipfileRead32(aRead);
4620 pCDS->szCompressed = zipfileRead32(aRead);
4621 pCDS->szUncompressed = zipfileRead32(aRead);
4622 assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
4623 pCDS->nFile = zipfileRead16(aRead);
4624 pCDS->nExtra = zipfileRead16(aRead);
4625 pCDS->nComment = zipfileRead16(aRead);
4626 pCDS->iDiskStart = zipfileRead16(aRead);
4627 pCDS->iInternalAttr = zipfileRead16(aRead);
4628 pCDS->iExternalAttr = zipfileRead32(aRead);
4629 pCDS->iOffset = zipfileRead32(aRead);
4630 assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] );
4637 ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR
4638 ** if the record is not well-formed, or SQLITE_OK otherwise.
4640 static int zipfileReadLFH(
4644 u8 *aRead = aBuffer;
4647 u32 sig = zipfileRead32(aRead);
4648 if( sig!=ZIPFILE_SIGNATURE_LFH ){
4651 pLFH->iVersionExtract = zipfileRead16(aRead);
4652 pLFH->flags = zipfileRead16(aRead);
4653 pLFH->iCompression = zipfileRead16(aRead);
4654 pLFH->mTime = zipfileRead16(aRead);
4655 pLFH->mDate = zipfileRead16(aRead);
4656 pLFH->crc32 = zipfileRead32(aRead);
4657 pLFH->szCompressed = zipfileRead32(aRead);
4658 pLFH->szUncompressed = zipfileRead32(aRead);
4659 pLFH->nFile = zipfileRead16(aRead);
4660 pLFH->nExtra = zipfileRead16(aRead);
4667 ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields.
4668 ** Scan through this buffer to find an "extra-timestamp" field. If one
4669 ** exists, extract the 32-bit modification-timestamp from it and store
4670 ** the value in output parameter *pmTime.
4672 ** Zero is returned if no extra-timestamp record could be found (and so
4673 ** *pmTime is left unchanged), or non-zero otherwise.
4675 ** The general format of an extra field is:
4677 ** Header ID 2 bytes
4678 ** Data Size 2 bytes
4681 static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){
4684 u8 *pEnd = &aExtra[nExtra];
4687 u16 id = zipfileRead16(p);
4688 u16 nByte = zipfileRead16(p);
4691 case ZIPFILE_EXTRA_TIMESTAMP: {
4693 if( b & 0x01 ){ /* 0x01 -> modtime is present */
4694 *pmTime = zipfileGetU32(&p[1]);
4707 ** Convert the standard MS-DOS timestamp stored in the mTime and mDate
4708 ** fields of the CDS structure passed as the only argument to a 32-bit
4709 ** UNIX seconds-since-the-epoch timestamp. Return the result.
4711 ** "Standard" MS-DOS time format:
4713 ** File modification time:
4714 ** Bits 00-04: seconds divided by 2
4715 ** Bits 05-10: minute
4717 ** File modification date:
4719 ** Bits 05-08: month (1-12)
4720 ** Bits 09-15: years from 1980
4722 ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx
4724 static u32 zipfileMtime(ZipfileCDS *pCDS){
4725 int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F));
4726 int M = ((pCDS->mDate >> 5) & 0x0F);
4727 int D = (pCDS->mDate & 0x1F);
4730 int sec = (pCDS->mTime & 0x1F)*2;
4731 int min = (pCDS->mTime >> 5) & 0x3F;
4732 int hr = (pCDS->mTime >> 11) & 0x1F;
4735 /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */
4737 /* Calculate the JD in seconds for noon on the day in question */
4742 JD = (i64)(24*60*60) * (
4743 (int)(365.25 * (Y + 4716))
4744 + (int)(30.6001 * (M + 1))
4748 /* Correct the JD for the time within the day */
4749 JD += (hr-12) * 3600 + min * 60 + sec;
4751 /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */
4752 return (u32)(JD - (i64)(24405875) * 24*60*6);
4756 ** The opposite of zipfileMtime(). This function populates the mTime and
4757 ** mDate fields of the CDS structure passed as the first argument according
4758 ** to the UNIX timestamp value passed as the second.
4760 static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){
4761 /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */
4762 i64 JD = (i64)2440588 + mUnixTime / (24*60*60);
4768 A = (int)((JD - 1867216.25)/36524.25);
4769 A = (int)(JD + 1 + A - (A/4));
4771 C = (int)((B - 122.1)/365.25);
4772 D = (36525*(C&32767))/100;
4773 E = (int)((B-D)/30.6001);
4775 day = B - D - (int)(30.6001*E);
4776 mon = (E<14 ? E-1 : E-13);
4777 yr = mon>2 ? C-4716 : C-4715;
4779 hr = (mUnixTime % (24*60*60)) / (60*60);
4780 min = (mUnixTime % (60*60)) / 60;
4781 sec = (mUnixTime % 60);
4784 pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9));
4785 pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11));
4787 pCds->mDate = pCds->mTime = 0;
4790 assert( mUnixTime<315507600
4791 || mUnixTime==zipfileMtime(pCds)
4792 || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds))
4793 /* || (mUnixTime % 2) */
4798 ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in
4799 ** size) containing an entire zip archive image. Or, if aBlob is NULL,
4800 ** then pFile is a file-handle open on a zip file. In either case, this
4801 ** function creates a ZipfileEntry object based on the zip archive entry
4802 ** for which the CDS record is at offset iOff.
4804 ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to
4805 ** the new object. Otherwise, an SQLite error code is returned and the
4806 ** final value of (*ppEntry) undefined.
4808 static int zipfileGetEntry(
4809 ZipfileTab *pTab, /* Store any error message here */
4810 const u8 *aBlob, /* Pointer to in-memory file image */
4811 int nBlob, /* Size of aBlob[] in bytes */
4812 FILE *pFile, /* If aBlob==0, read from this file */
4813 i64 iOff, /* Offset of CDS record */
4814 ZipfileEntry **ppEntry /* OUT: Pointer to new object */
4817 char **pzErr = &pTab->base.zErrMsg;
4821 aRead = pTab->aBuffer;
4822 rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr);
4824 aRead = (u8*)&aBlob[iOff];
4827 if( rc==SQLITE_OK ){
4831 int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]);
4832 int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]);
4833 nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]);
4835 nAlloc = sizeof(ZipfileEntry) + nExtra;
4837 nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]);
4840 pNew = (ZipfileEntry*)sqlite3_malloc(nAlloc);
4844 memset(pNew, 0, sizeof(ZipfileEntry));
4845 rc = zipfileReadCDS(aRead, &pNew->cds);
4846 if( rc!=SQLITE_OK ){
4847 *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff);
4848 }else if( aBlob==0 ){
4849 rc = zipfileReadData(
4850 pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr
4853 aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ];
4857 if( rc==SQLITE_OK ){
4858 u32 *pt = &pNew->mUnixTime;
4859 pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead);
4860 pNew->aExtra = (u8*)&pNew[1];
4861 memcpy(pNew->aExtra, &aRead[nFile], nExtra);
4862 if( pNew->cds.zFile==0 ){
4864 }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){
4865 pNew->mUnixTime = zipfileMtime(&pNew->cds);
4869 if( rc==SQLITE_OK ){
4870 static const int szFix = ZIPFILE_LFH_FIXED_SZ;
4873 rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr);
4875 aRead = (u8*)&aBlob[pNew->cds.iOffset];
4878 rc = zipfileReadLFH(aRead, &lfh);
4879 if( rc==SQLITE_OK ){
4880 pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ;
4881 pNew->iDataOff += lfh.nFile + lfh.nExtra;
4882 if( aBlob && pNew->cds.szCompressed ){
4883 pNew->aData = &pNew->aExtra[nExtra];
4884 memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed);
4887 *pzErr = sqlite3_mprintf("failed to read LFH at offset %d",
4888 (int)pNew->cds.iOffset
4893 if( rc!=SQLITE_OK ){
4894 zipfileEntryFree(pNew);
4904 ** Advance an ZipfileCsr to its next row of output.
4906 static int zipfileNext(sqlite3_vtab_cursor *cur){
4907 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
4911 i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize;
4912 zipfileEntryFree(pCsr->pCurrent);
4914 if( pCsr->iNextOff>=iEof ){
4917 ZipfileEntry *p = 0;
4918 ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab);
4919 rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p);
4920 if( rc==SQLITE_OK ){
4921 pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ;
4922 pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment;
4928 pCsr->pCurrent = pCsr->pCurrent->pNext;
4930 if( pCsr->pCurrent==0 ){
4939 static void zipfileFree(void *p) {
4944 ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the
4945 ** size is nOut bytes. This function uncompresses the data and sets the
4946 ** return value in context pCtx to the result (a blob).
4948 ** If an error occurs, an error code is left in pCtx instead.
4950 static void zipfileInflate(
4951 sqlite3_context *pCtx, /* Store result here */
4952 const u8 *aIn, /* Compressed data */
4953 int nIn, /* Size of buffer aIn[] in bytes */
4954 int nOut /* Expected output size */
4956 u8 *aRes = sqlite3_malloc(nOut);
4958 sqlite3_result_error_nomem(pCtx);
4962 memset(&str, 0, sizeof(str));
4964 str.next_in = (Byte*)aIn;
4966 str.next_out = (Byte*)aRes;
4967 str.avail_out = nOut;
4969 err = inflateInit2(&str, -15);
4971 zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err);
4973 err = inflate(&str, Z_NO_FLUSH);
4974 if( err!=Z_STREAM_END ){
4975 zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err);
4977 sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree);
4987 ** Buffer aIn (size nIn bytes) contains uncompressed data. This function
4988 ** compresses it and sets (*ppOut) to point to a buffer containing the
4989 ** compressed data. The caller is responsible for eventually calling
4990 ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut)
4991 ** is set to the size of buffer (*ppOut) in bytes.
4993 ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error
4994 ** code is returned and an error message left in virtual-table handle
4995 ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this
4998 static int zipfileDeflate(
4999 const u8 *aIn, int nIn, /* Input */
5000 u8 **ppOut, int *pnOut, /* Output */
5001 char **pzErr /* OUT: Error message */
5003 int nAlloc = (int)compressBound(nIn);
5007 aOut = (u8*)sqlite3_malloc(nAlloc);
5013 memset(&str, 0, sizeof(str));
5014 str.next_in = (Bytef*)aIn;
5016 str.next_out = aOut;
5017 str.avail_out = nAlloc;
5019 deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
5020 res = deflate(&str, Z_FINISH);
5022 if( res==Z_STREAM_END ){
5024 *pnOut = (int)str.total_out;
5027 *pzErr = sqlite3_mprintf("zipfile: deflate() error");
5038 ** Return values of columns for the row at which the series_cursor
5039 ** is currently pointing.
5041 static int zipfileColumn(
5042 sqlite3_vtab_cursor *cur, /* The cursor */
5043 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
5044 int i /* Which column to return */
5046 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5047 ZipfileCDS *pCDS = &pCsr->pCurrent->cds;
5051 sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT);
5054 /* TODO: Whether or not the following is correct surely depends on
5055 ** the platform on which the archive was created. */
5056 sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16);
5058 case 2: { /* mtime */
5059 sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime);
5063 if( sqlite3_vtab_nochange(ctx)==0 ){
5064 sqlite3_result_int64(ctx, pCDS->szUncompressed);
5068 case 4: /* rawdata */
5069 if( sqlite3_vtab_nochange(ctx) ) break;
5070 case 5: { /* data */
5071 if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){
5072 int sz = pCDS->szCompressed;
5073 int szFinal = pCDS->szUncompressed;
5077 if( pCsr->pCurrent->aData ){
5078 aBuf = pCsr->pCurrent->aData;
5080 aBuf = aFree = sqlite3_malloc(sz);
5084 FILE *pFile = pCsr->pFile;
5086 pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd;
5088 rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff,
5089 &pCsr->base.pVtab->zErrMsg
5093 if( rc==SQLITE_OK ){
5094 if( i==5 && pCDS->iCompression ){
5095 zipfileInflate(ctx, aBuf, sz, szFinal);
5097 sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT);
5100 sqlite3_free(aFree);
5102 /* Figure out if this is a directory or a zero-sized file. Consider
5103 ** it to be a directory either if the mode suggests so, or if
5104 ** the final character in the name is '/'. */
5105 u32 mode = pCDS->iExternalAttr >> 16;
5106 if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){
5107 sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC);
5113 case 6: /* method */
5114 sqlite3_result_int(ctx, pCDS->iCompression);
5118 sqlite3_result_int64(ctx, pCsr->iId);
5126 ** Return TRUE if the cursor is at EOF.
5128 static int zipfileEof(sqlite3_vtab_cursor *cur){
5129 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5134 ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size
5135 ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile
5136 ** is guaranteed to be a file-handle open on a zip file.
5138 ** This function attempts to locate the EOCD record within the zip archive
5139 ** and populate *pEOCD with the results of decoding it. SQLITE_OK is
5140 ** returned if successful. Otherwise, an SQLite error code is returned and
5141 ** an English language error message may be left in virtual-table pTab.
5143 static int zipfileReadEOCD(
5144 ZipfileTab *pTab, /* Return errors here */
5145 const u8 *aBlob, /* Pointer to in-memory file image */
5146 int nBlob, /* Size of aBlob[] in bytes */
5147 FILE *pFile, /* Read from this file if aBlob==0 */
5148 ZipfileEOCD *pEOCD /* Object to populate */
5150 u8 *aRead = pTab->aBuffer; /* Temporary buffer */
5151 int nRead; /* Bytes to read from file */
5155 i64 iOff; /* Offset to read from */
5156 i64 szFile; /* Total size of file in bytes */
5157 fseek(pFile, 0, SEEK_END);
5158 szFile = (i64)ftell(pFile);
5160 memset(pEOCD, 0, sizeof(ZipfileEOCD));
5163 nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE));
5164 iOff = szFile - nRead;
5165 rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg);
5167 nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE));
5168 aRead = (u8*)&aBlob[nBlob-nRead];
5171 if( rc==SQLITE_OK ){
5174 /* Scan backwards looking for the signature bytes */
5175 for(i=nRead-20; i>=0; i--){
5176 if( aRead[i]==0x50 && aRead[i+1]==0x4b
5177 && aRead[i+2]==0x05 && aRead[i+3]==0x06
5183 pTab->base.zErrMsg = sqlite3_mprintf(
5184 "cannot find end of central directory record"
5186 return SQLITE_ERROR;
5190 pEOCD->iDisk = zipfileRead16(aRead);
5191 pEOCD->iFirstDisk = zipfileRead16(aRead);
5192 pEOCD->nEntry = zipfileRead16(aRead);
5193 pEOCD->nEntryTotal = zipfileRead16(aRead);
5194 pEOCD->nSize = zipfileRead32(aRead);
5195 pEOCD->iOffset = zipfileRead32(aRead);
5202 ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry
5203 ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added
5204 ** to the end of the list. Otherwise, it is added to the list immediately
5205 ** before pBefore (which is guaranteed to be a part of said list).
5207 static void zipfileAddEntry(
5209 ZipfileEntry *pBefore,
5212 assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) );
5213 assert( pNew->pNext==0 );
5215 if( pTab->pFirstEntry==0 ){
5216 pTab->pFirstEntry = pTab->pLastEntry = pNew;
5218 assert( pTab->pLastEntry->pNext==0 );
5219 pTab->pLastEntry->pNext = pNew;
5220 pTab->pLastEntry = pNew;
5224 for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext));
5225 pNew->pNext = pBefore;
5230 static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){
5236 rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd);
5237 iOff = eocd.iOffset;
5238 for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){
5239 ZipfileEntry *pNew = 0;
5240 rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew);
5242 if( rc==SQLITE_OK ){
5243 zipfileAddEntry(pTab, 0, pNew);
5244 iOff += ZIPFILE_CDS_FIXED_SZ;
5245 iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment;
5252 ** xFilter callback.
5254 static int zipfileFilter(
5255 sqlite3_vtab_cursor *cur,
5256 int idxNum, const char *idxStr,
5257 int argc, sqlite3_value **argv
5259 ZipfileTab *pTab = (ZipfileTab*)cur->pVtab;
5260 ZipfileCsr *pCsr = (ZipfileCsr*)cur;
5261 const char *zFile = 0; /* Zip file to scan */
5262 int rc = SQLITE_OK; /* Return Code */
5263 int bInMemory = 0; /* True for an in-memory zipfile */
5265 zipfileResetCursor(pCsr);
5268 zFile = pTab->zFile;
5269 }else if( idxNum==0 ){
5270 zipfileCursorErr(pCsr, "zipfile() function requires an argument");
5271 return SQLITE_ERROR;
5272 }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
5273 const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]);
5274 int nBlob = sqlite3_value_bytes(argv[0]);
5275 assert( pTab->pFirstEntry==0 );
5276 rc = zipfileLoadDirectory(pTab, aBlob, nBlob);
5277 pCsr->pFreeEntry = pTab->pFirstEntry;
5278 pTab->pFirstEntry = pTab->pLastEntry = 0;
5279 if( rc!=SQLITE_OK ) return rc;
5282 zFile = (const char*)sqlite3_value_text(argv[0]);
5285 if( 0==pTab->pWriteFd && 0==bInMemory ){
5286 pCsr->pFile = fopen(zFile, "rb");
5287 if( pCsr->pFile==0 ){
5288 zipfileCursorErr(pCsr, "cannot open file: %s", zFile);
5291 rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd);
5292 if( rc==SQLITE_OK ){
5293 if( pCsr->eocd.nEntry==0 ){
5296 pCsr->iNextOff = pCsr->eocd.iOffset;
5297 rc = zipfileNext(cur);
5303 pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry;
5304 rc = zipfileNext(cur);
5311 ** xBestIndex callback.
5313 static int zipfileBestIndex(
5315 sqlite3_index_info *pIdxInfo
5319 for(i=0; i<pIdxInfo->nConstraint; i++){
5320 const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
5321 if( pCons->usable==0 ) continue;
5322 if( pCons->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
5323 if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue;
5327 if( i<pIdxInfo->nConstraint ){
5328 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
5329 pIdxInfo->aConstraintUsage[i].omit = 1;
5330 pIdxInfo->estimatedCost = 1000.0;
5331 pIdxInfo->idxNum = 1;
5333 pIdxInfo->estimatedCost = (double)(((sqlite3_int64)1) << 50);
5334 pIdxInfo->idxNum = 0;
5340 static ZipfileEntry *zipfileNewEntry(const char *zPath){
5342 pNew = sqlite3_malloc(sizeof(ZipfileEntry));
5344 memset(pNew, 0, sizeof(ZipfileEntry));
5345 pNew->cds.zFile = sqlite3_mprintf("%s", zPath);
5346 if( pNew->cds.zFile==0 ){
5354 static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){
5355 ZipfileCDS *pCds = &pEntry->cds;
5360 /* Write the LFH itself */
5361 zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH);
5362 zipfileWrite16(a, pCds->iVersionExtract);
5363 zipfileWrite16(a, pCds->flags);
5364 zipfileWrite16(a, pCds->iCompression);
5365 zipfileWrite16(a, pCds->mTime);
5366 zipfileWrite16(a, pCds->mDate);
5367 zipfileWrite32(a, pCds->crc32);
5368 zipfileWrite32(a, pCds->szCompressed);
5369 zipfileWrite32(a, pCds->szUncompressed);
5370 zipfileWrite16(a, (u16)pCds->nFile);
5371 zipfileWrite16(a, pCds->nExtra);
5372 assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] );
5374 /* Add the file name */
5375 memcpy(a, pCds->zFile, (int)pCds->nFile);
5376 a += (int)pCds->nFile;
5378 /* The "extra" data */
5379 zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5380 zipfileWrite16(a, 5);
5382 zipfileWrite32(a, pEntry->mUnixTime);
5387 static int zipfileAppendEntry(
5389 ZipfileEntry *pEntry,
5393 u8 *aBuf = pTab->aBuffer;
5397 nBuf = zipfileSerializeLFH(pEntry, aBuf);
5398 rc = zipfileAppendData(pTab, aBuf, nBuf);
5399 if( rc==SQLITE_OK ){
5400 pEntry->iDataOff = pTab->szCurrent;
5401 rc = zipfileAppendData(pTab, pData, nData);
5407 static int zipfileGetMode(
5408 sqlite3_value *pVal,
5409 int bIsDir, /* If true, default to directory */
5410 u32 *pMode, /* OUT: Mode value */
5411 char **pzErr /* OUT: Error message */
5413 const char *z = (const char*)sqlite3_value_text(pVal);
5416 mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644));
5417 }else if( z[0]>='0' && z[0]<='9' ){
5418 mode = (unsigned int)sqlite3_value_int(pVal);
5420 const char zTemplate[11] = "-rwxrwxrwx";
5422 if( strlen(z)!=10 ) goto parse_error;
5424 case '-': mode |= S_IFREG; break;
5425 case 'd': mode |= S_IFDIR; break;
5426 case 'l': mode |= S_IFLNK; break;
5427 default: goto parse_error;
5429 for(i=1; i<10; i++){
5430 if( z[i]==zTemplate[i] ) mode |= 1 << (9-i);
5431 else if( z[i]!='-' ) goto parse_error;
5434 if( ((mode & S_IFDIR)==0)==bIsDir ){
5435 /* The "mode" attribute is a directory, but data has been specified.
5436 ** Or vice-versa - no data but "mode" is a file or symlink. */
5437 *pzErr = sqlite3_mprintf("zipfile: mode does not match data");
5438 return SQLITE_CONSTRAINT;
5444 *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z);
5445 return SQLITE_ERROR;
5449 ** Both (const char*) arguments point to nul-terminated strings. Argument
5450 ** nB is the value of strlen(zB). This function returns 0 if the strings are
5451 ** identical, ignoring any trailing '/' character in either path. */
5452 static int zipfileComparePath(const char *zA, const char *zB, int nB){
5453 int nA = (int)strlen(zA);
5454 if( zA[nA-1]=='/' ) nA--;
5455 if( zB[nB-1]=='/' ) nB--;
5456 if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
5460 static int zipfileBegin(sqlite3_vtab *pVtab){
5461 ZipfileTab *pTab = (ZipfileTab*)pVtab;
5464 assert( pTab->pWriteFd==0 );
5466 /* Open a write fd on the file. Also load the entire central directory
5467 ** structure into memory. During the transaction any new file data is
5468 ** appended to the archive file, but the central directory is accumulated
5469 ** in main-memory until the transaction is committed. */
5470 pTab->pWriteFd = fopen(pTab->zFile, "ab+");
5471 if( pTab->pWriteFd==0 ){
5472 pTab->base.zErrMsg = sqlite3_mprintf(
5473 "zipfile: failed to open file %s for writing", pTab->zFile
5477 fseek(pTab->pWriteFd, 0, SEEK_END);
5478 pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd);
5479 rc = zipfileLoadDirectory(pTab, 0, 0);
5482 if( rc!=SQLITE_OK ){
5483 zipfileCleanupTransaction(pTab);
5490 ** Return the current time as a 32-bit timestamp in UNIX epoch format (like
5493 static u32 zipfileTime(void){
5494 sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
5496 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
5498 pVfs->xCurrentTimeInt64(pVfs, &ms);
5499 ret = (u32)((ms/1000) - ((i64)24405875 * 8640));
5502 pVfs->xCurrentTime(pVfs, &day);
5503 ret = (u32)((day - 2440587.5) * 86400);
5509 ** Return a 32-bit timestamp in UNIX epoch format.
5511 ** If the value passed as the only argument is either NULL or an SQL NULL,
5512 ** return the current time. Otherwise, return the value stored in (*pVal)
5513 ** cast to a 32-bit unsigned integer.
5515 static u32 zipfileGetTime(sqlite3_value *pVal){
5516 if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
5517 return zipfileTime();
5519 return (u32)sqlite3_value_int64(pVal);
5523 ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry
5524 ** linked list. Remove it from the list and free the object.
5526 static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){
5529 for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext));
5531 zipfileEntryFree(pOld);
5538 static int zipfileUpdate(
5539 sqlite3_vtab *pVtab,
5541 sqlite3_value **apVal,
5542 sqlite_int64 *pRowid
5544 ZipfileTab *pTab = (ZipfileTab*)pVtab;
5545 int rc = SQLITE_OK; /* Return Code */
5546 ZipfileEntry *pNew = 0; /* New in-memory CDS entry */
5548 u32 mode = 0; /* Mode for new entry */
5549 u32 mTime = 0; /* Modification time for new entry */
5550 i64 sz = 0; /* Uncompressed size */
5551 const char *zPath = 0; /* Path for new entry */
5552 int nPath = 0; /* strlen(zPath) */
5553 const u8 *pData = 0; /* Pointer to buffer containing content */
5554 int nData = 0; /* Size of pData buffer in bytes */
5555 int iMethod = 0; /* Compression method for new entry */
5556 u8 *pFree = 0; /* Free this */
5557 char *zFree = 0; /* Also free this */
5558 ZipfileEntry *pOld = 0;
5559 ZipfileEntry *pOld2 = 0;
5560 int bUpdate = 0; /* True for an update that modifies "name" */
5564 if( pTab->pWriteFd==0 ){
5565 rc = zipfileBegin(pVtab);
5566 if( rc!=SQLITE_OK ) return rc;
5569 /* If this is a DELETE or UPDATE, find the archive entry to delete. */
5570 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
5571 const char *zDelete = (const char*)sqlite3_value_text(apVal[0]);
5572 int nDelete = (int)strlen(zDelete);
5574 const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]);
5575 if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){
5579 for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){
5580 if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){
5583 assert( pOld->pNext );
5588 /* Check that "sz" and "rawdata" are both NULL: */
5589 if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){
5590 zipfileTableErr(pTab, "sz must be NULL");
5591 rc = SQLITE_CONSTRAINT;
5593 if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){
5594 zipfileTableErr(pTab, "rawdata must be NULL");
5595 rc = SQLITE_CONSTRAINT;
5598 if( rc==SQLITE_OK ){
5599 if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){
5600 /* data=NULL. A directory */
5603 /* Value specified for "data", and possibly "method". This must be
5604 ** a regular file or a symlink. */
5605 const u8 *aIn = sqlite3_value_blob(apVal[7]);
5606 int nIn = sqlite3_value_bytes(apVal[7]);
5607 int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL;
5609 iMethod = sqlite3_value_int(apVal[8]);
5613 if( iMethod!=0 && iMethod!=8 ){
5614 zipfileTableErr(pTab, "unknown compression method: %d", iMethod);
5615 rc = SQLITE_CONSTRAINT;
5617 if( bAuto || iMethod ){
5619 rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg);
5620 if( rc==SQLITE_OK ){
5621 if( iMethod || nCmp<nIn ){
5628 iCrc32 = crc32(0, aIn, nIn);
5633 if( rc==SQLITE_OK ){
5634 rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg);
5637 if( rc==SQLITE_OK ){
5638 zPath = (const char*)sqlite3_value_text(apVal[2]);
5639 nPath = (int)strlen(zPath);
5640 mTime = zipfileGetTime(apVal[4]);
5643 if( rc==SQLITE_OK && bIsDir ){
5644 /* For a directory, check that the last character in the path is a
5645 ** '/'. This appears to be required for compatibility with info-zip
5646 ** (the unzip command on unix). It does not create directories
5648 if( zPath[nPath-1]!='/' ){
5649 zFree = sqlite3_mprintf("%s/", zPath);
5650 if( zFree==0 ){ rc = SQLITE_NOMEM; }
5651 zPath = (const char*)zFree;
5656 /* Check that we're not inserting a duplicate entry -OR- updating an
5657 ** entry with a path, thereby making it into a duplicate. */
5658 if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){
5660 for(p=pTab->pFirstEntry; p; p=p->pNext){
5661 if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){
5662 switch( sqlite3_vtab_on_conflict(pTab->db) ){
5663 case SQLITE_IGNORE: {
5664 goto zipfile_update_done;
5666 case SQLITE_REPLACE: {
5671 zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath);
5672 rc = SQLITE_CONSTRAINT;
5681 if( rc==SQLITE_OK ){
5682 /* Create the new CDS record. */
5683 pNew = zipfileNewEntry(zPath);
5687 pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
5688 pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
5689 pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS;
5690 pNew->cds.iCompression = (u16)iMethod;
5691 zipfileMtimeToDos(&pNew->cds, mTime);
5692 pNew->cds.crc32 = iCrc32;
5693 pNew->cds.szCompressed = nData;
5694 pNew->cds.szUncompressed = (u32)sz;
5695 pNew->cds.iExternalAttr = (mode<<16);
5696 pNew->cds.iOffset = (u32)pTab->szCurrent;
5697 pNew->cds.nFile = (u16)nPath;
5698 pNew->mUnixTime = (u32)mTime;
5699 rc = zipfileAppendEntry(pTab, pNew, pData, nData);
5700 zipfileAddEntry(pTab, pOld, pNew);
5705 if( rc==SQLITE_OK && (pOld || pOld2) ){
5707 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
5708 if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){
5709 pCsr->pCurrent = pCsr->pCurrent->pNext;
5714 zipfileRemoveEntryFromList(pTab, pOld);
5715 zipfileRemoveEntryFromList(pTab, pOld2);
5718 zipfile_update_done:
5719 sqlite3_free(pFree);
5720 sqlite3_free(zFree);
5724 static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){
5726 zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD);
5727 zipfileWrite16(a, p->iDisk);
5728 zipfileWrite16(a, p->iFirstDisk);
5729 zipfileWrite16(a, p->nEntry);
5730 zipfileWrite16(a, p->nEntryTotal);
5731 zipfileWrite32(a, p->nSize);
5732 zipfileWrite32(a, p->iOffset);
5733 zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/
5738 static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){
5739 int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer);
5740 assert( nBuf==ZIPFILE_EOCD_FIXED_SZ );
5741 return zipfileAppendData(pTab, pTab->aBuffer, nBuf);
5745 ** Serialize the CDS structure into buffer aBuf[]. Return the number
5746 ** of bytes written.
5748 static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){
5750 ZipfileCDS *pCDS = &pEntry->cds;
5752 if( pEntry->aExtra==0 ){
5756 zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS);
5757 zipfileWrite16(a, pCDS->iVersionMadeBy);
5758 zipfileWrite16(a, pCDS->iVersionExtract);
5759 zipfileWrite16(a, pCDS->flags);
5760 zipfileWrite16(a, pCDS->iCompression);
5761 zipfileWrite16(a, pCDS->mTime);
5762 zipfileWrite16(a, pCDS->mDate);
5763 zipfileWrite32(a, pCDS->crc32);
5764 zipfileWrite32(a, pCDS->szCompressed);
5765 zipfileWrite32(a, pCDS->szUncompressed);
5766 assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] );
5767 zipfileWrite16(a, pCDS->nFile);
5768 zipfileWrite16(a, pCDS->nExtra);
5769 zipfileWrite16(a, pCDS->nComment);
5770 zipfileWrite16(a, pCDS->iDiskStart);
5771 zipfileWrite16(a, pCDS->iInternalAttr);
5772 zipfileWrite32(a, pCDS->iExternalAttr);
5773 zipfileWrite32(a, pCDS->iOffset);
5775 memcpy(a, pCDS->zFile, pCDS->nFile);
5778 if( pEntry->aExtra ){
5779 int n = (int)pCDS->nExtra + (int)pCDS->nComment;
5780 memcpy(a, pEntry->aExtra, n);
5783 assert( pCDS->nExtra==9 );
5784 zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP);
5785 zipfileWrite16(a, 5);
5787 zipfileWrite32(a, pEntry->mUnixTime);
5793 static int zipfileCommit(sqlite3_vtab *pVtab){
5794 ZipfileTab *pTab = (ZipfileTab*)pVtab;
5796 if( pTab->pWriteFd ){
5797 i64 iOffset = pTab->szCurrent;
5802 /* Write out all entries */
5803 for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){
5804 int n = zipfileSerializeCDS(p, pTab->aBuffer);
5805 rc = zipfileAppendData(pTab, pTab->aBuffer, n);
5809 /* Write out the EOCD record */
5811 eocd.iFirstDisk = 0;
5812 eocd.nEntry = (u16)nEntry;
5813 eocd.nEntryTotal = (u16)nEntry;
5814 eocd.nSize = (u32)(pTab->szCurrent - iOffset);
5815 eocd.iOffset = (u32)iOffset;
5816 rc = zipfileAppendEOCD(pTab, &eocd);
5818 zipfileCleanupTransaction(pTab);
5823 static int zipfileRollback(sqlite3_vtab *pVtab){
5824 return zipfileCommit(pVtab);
5827 static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){
5829 for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){
5830 if( iId==pCsr->iId ) break;
5835 static void zipfileFunctionCds(
5836 sqlite3_context *context,
5838 sqlite3_value **argv
5841 ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context);
5844 pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0]));
5846 ZipfileCDS *p = &pCsr->pCurrent->cds;
5847 char *zRes = sqlite3_mprintf("{"
5848 "\"version-made-by\" : %u, "
5849 "\"version-to-extract\" : %u, "
5851 "\"compression\" : %u, "
5855 "\"compressed-size\" : %u, "
5856 "\"uncompressed-size\" : %u, "
5857 "\"file-name-length\" : %u, "
5858 "\"extra-field-length\" : %u, "
5859 "\"file-comment-length\" : %u, "
5860 "\"disk-number-start\" : %u, "
5861 "\"internal-attr\" : %u, "
5862 "\"external-attr\" : %u, "
5863 "\"offset\" : %u }",
5864 (u32)p->iVersionMadeBy, (u32)p->iVersionExtract,
5865 (u32)p->flags, (u32)p->iCompression,
5866 (u32)p->mTime, (u32)p->mDate,
5867 (u32)p->crc32, (u32)p->szCompressed,
5868 (u32)p->szUncompressed, (u32)p->nFile,
5869 (u32)p->nExtra, (u32)p->nComment,
5870 (u32)p->iDiskStart, (u32)p->iInternalAttr,
5871 (u32)p->iExternalAttr, (u32)p->iOffset
5875 sqlite3_result_error_nomem(context);
5877 sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT);
5884 ** xFindFunction method.
5886 static int zipfileFindFunction(
5887 sqlite3_vtab *pVtab, /* Virtual table handle */
5888 int nArg, /* Number of SQL function arguments */
5889 const char *zName, /* Name of SQL function */
5890 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
5891 void **ppArg /* OUT: User data for *pxFunc */
5893 if( sqlite3_stricmp("zipfile_cds", zName)==0 ){
5894 *pxFunc = zipfileFunctionCds;
5895 *ppArg = (void*)pVtab;
5901 typedef struct ZipfileBuffer ZipfileBuffer;
5902 struct ZipfileBuffer {
5903 u8 *a; /* Pointer to buffer */
5904 int n; /* Size of buffer in bytes */
5905 int nAlloc; /* Byte allocated at a[] */
5908 typedef struct ZipfileCtx ZipfileCtx;
5915 static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){
5916 if( pBuf->n+nByte>pBuf->nAlloc ){
5918 int nNew = pBuf->n ? pBuf->n*2 : 512;
5919 int nReq = pBuf->n + nByte;
5921 while( nNew<nReq ) nNew = nNew*2;
5922 aNew = sqlite3_realloc(pBuf->a, nNew);
5923 if( aNew==0 ) return SQLITE_NOMEM;
5925 pBuf->nAlloc = nNew;
5931 ** xStep() callback for the zipfile() aggregate. This can be called in
5932 ** any of the following ways:
5934 ** SELECT zipfile(name,data) ...
5935 ** SELECT zipfile(name,mode,mtime,data) ...
5936 ** SELECT zipfile(name,mode,mtime,data,method) ...
5938 void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
5939 ZipfileCtx *p; /* Aggregate function context */
5940 ZipfileEntry e; /* New entry to add to zip archive */
5942 sqlite3_value *pName = 0;
5943 sqlite3_value *pMode = 0;
5944 sqlite3_value *pMtime = 0;
5945 sqlite3_value *pData = 0;
5946 sqlite3_value *pMethod = 0;
5953 int iMethod = -1; /* Compression method to use (0 or 8) */
5955 const u8 *aData = 0; /* Possibly compressed data for new entry */
5956 int nData = 0; /* Size of aData[] in bytes */
5957 int szUncompressed = 0; /* Size of data before compression */
5958 u8 *aFree = 0; /* Free this before returning */
5959 u32 iCrc32 = 0; /* crc32 of uncompressed data */
5961 char *zName = 0; /* Path (name) of new entry */
5962 int nName = 0; /* Size of zName in bytes */
5963 char *zFree = 0; /* Free this before returning */
5966 memset(&e, 0, sizeof(e));
5967 p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
5970 /* Martial the arguments into stack variables */
5971 if( nVal!=2 && nVal!=4 && nVal!=5 ){
5972 zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()");
5974 goto zipfile_step_out;
5988 /* Check that the 'name' parameter looks ok. */
5989 zName = (char*)sqlite3_value_text(pName);
5990 nName = sqlite3_value_bytes(pName);
5992 zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL");
5994 goto zipfile_step_out;
5997 /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use
5998 ** deflate compression) or NULL (choose automatically). */
5999 if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){
6000 iMethod = (int)sqlite3_value_int64(pMethod);
6001 if( iMethod!=0 && iMethod!=8 ){
6002 zErr = sqlite3_mprintf("illegal method value: %d", iMethod);
6004 goto zipfile_step_out;
6008 /* Now inspect the data. If this is NULL, then the new entry must be a
6009 ** directory. Otherwise, figure out whether or not the data should
6010 ** be deflated or simply stored in the zip archive. */
6011 if( sqlite3_value_type(pData)==SQLITE_NULL ){
6015 aData = sqlite3_value_blob(pData);
6016 szUncompressed = nData = sqlite3_value_bytes(pData);
6017 iCrc32 = crc32(0, aData, nData);
6018 if( iMethod<0 || iMethod==8 ){
6020 rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr);
6021 if( rc!=SQLITE_OK ){
6022 goto zipfile_step_out;
6024 if( iMethod==8 || nOut<nData ){
6034 /* Decode the "mode" argument. */
6035 rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr);
6036 if( rc ) goto zipfile_step_out;
6038 /* Decode the "mtime" argument. */
6039 e.mUnixTime = zipfileGetTime(pMtime);
6041 /* If this is a directory entry, ensure that there is exactly one '/'
6042 ** at the end of the path. Or, if this is not a directory and the path
6043 ** ends in '/' it is an error. */
6045 if( zName[nName-1]=='/' ){
6046 zErr = sqlite3_mprintf("non-directory name must not end with /");
6048 goto zipfile_step_out;
6051 if( zName[nName-1]!='/' ){
6052 zName = zFree = sqlite3_mprintf("%s/", zName);
6056 goto zipfile_step_out;
6059 while( nName>1 && zName[nName-2]=='/' ) nName--;
6063 /* Assemble the ZipfileEntry object for the new zip archive entry */
6064 e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY;
6065 e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED;
6066 e.cds.flags = ZIPFILE_NEWENTRY_FLAGS;
6067 e.cds.iCompression = (u16)iMethod;
6068 zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime);
6069 e.cds.crc32 = iCrc32;
6070 e.cds.szCompressed = nData;
6071 e.cds.szUncompressed = szUncompressed;
6072 e.cds.iExternalAttr = (mode<<16);
6073 e.cds.iOffset = p->body.n;
6074 e.cds.nFile = (u16)nName;
6075 e.cds.zFile = zName;
6077 /* Append the LFH to the body of the new archive */
6078 nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9;
6079 if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out;
6080 p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]);
6082 /* Append the data to the body of the new archive */
6084 if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out;
6085 memcpy(&p->body.a[p->body.n], aData, nData);
6089 /* Append the CDS record to the directory of the new archive */
6090 nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9;
6091 if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out;
6092 p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]);
6094 /* Increment the count of entries in the archive */
6098 sqlite3_free(aFree);
6099 sqlite3_free(zFree);
6102 sqlite3_result_error(pCtx, zErr, -1);
6104 sqlite3_result_error_code(pCtx, rc);
6111 ** xFinalize() callback for zipfile aggregate function.
6113 void zipfileFinal(sqlite3_context *pCtx){
6119 p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx));
6122 memset(&eocd, 0, sizeof(eocd));
6123 eocd.nEntry = (u16)p->nEntry;
6124 eocd.nEntryTotal = (u16)p->nEntry;
6125 eocd.nSize = p->cds.n;
6126 eocd.iOffset = p->body.n;
6128 nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ;
6129 aZip = (u8*)sqlite3_malloc(nZip);
6131 sqlite3_result_error_nomem(pCtx);
6133 memcpy(aZip, p->body.a, p->body.n);
6134 memcpy(&aZip[p->body.n], p->cds.a, p->cds.n);
6135 zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]);
6136 sqlite3_result_blob(pCtx, aZip, nZip, zipfileFree);
6140 sqlite3_free(p->body.a);
6141 sqlite3_free(p->cds.a);
6146 ** Register the "zipfile" virtual table.
6148 static int zipfileRegister(sqlite3 *db){
6149 static sqlite3_module zipfileModule = {
6151 zipfileConnect, /* xCreate */
6152 zipfileConnect, /* xConnect */
6153 zipfileBestIndex, /* xBestIndex */
6154 zipfileDisconnect, /* xDisconnect */
6155 zipfileDisconnect, /* xDestroy */
6156 zipfileOpen, /* xOpen - open a cursor */
6157 zipfileClose, /* xClose - close a cursor */
6158 zipfileFilter, /* xFilter - configure scan constraints */
6159 zipfileNext, /* xNext - advance a cursor */
6160 zipfileEof, /* xEof - check for end of scan */
6161 zipfileColumn, /* xColumn - read data */
6162 0, /* xRowid - read data */
6163 zipfileUpdate, /* xUpdate */
6164 zipfileBegin, /* xBegin */
6166 zipfileCommit, /* xCommit */
6167 zipfileRollback, /* xRollback */
6168 zipfileFindFunction, /* xFindMethod */
6172 int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0);
6173 if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1);
6174 if( rc==SQLITE_OK ){
6175 rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0,
6176 zipfileStep, zipfileFinal
6181 #else /* SQLITE_OMIT_VIRTUALTABLE */
6182 # define zipfileRegister(x) SQLITE_OK
6188 int sqlite3_zipfile_init(
6191 const sqlite3_api_routines *pApi
6193 SQLITE_EXTENSION_INIT2(pApi);
6194 (void)pzErrMsg; /* Unused parameter */
6195 return zipfileRegister(db);
6198 /************************* End ../ext/misc/zipfile.c ********************/
6199 /************************* Begin ../ext/misc/sqlar.c ******************/
6203 ** The author disclaims copyright to this source code. In place of
6204 ** a legal notice, here is a blessing:
6206 ** May you do good and not evil.
6207 ** May you find forgiveness for yourself and forgive others.
6208 ** May you share freely, never taking more than you give.
6210 ******************************************************************************
6212 ** Utility functions sqlar_compress() and sqlar_uncompress(). Useful
6213 ** for working with sqlar archives and used by the shell tool's built-in
6216 SQLITE_EXTENSION_INIT1
6220 ** Implementation of the "sqlar_compress(X)" SQL function.
6222 ** If the type of X is SQLITE_BLOB, and compressing that blob using
6223 ** zlib utility function compress() yields a smaller blob, return the
6224 ** compressed blob. Otherwise, return a copy of X.
6226 ** SQLar uses the "zlib format" for compressed content. The zlib format
6227 ** contains a two-byte identification header and a four-byte checksum at
6228 ** the end. This is different from ZIP which uses the raw deflate format.
6230 ** Future enhancements to SQLar might add support for new compression formats.
6231 ** If so, those new formats will be identified by alternative headers in the
6234 static void sqlarCompressFunc(
6235 sqlite3_context *context,
6237 sqlite3_value **argv
6240 if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){
6241 const Bytef *pData = sqlite3_value_blob(argv[0]);
6242 uLong nData = sqlite3_value_bytes(argv[0]);
6243 uLongf nOut = compressBound(nData);
6246 pOut = (Bytef*)sqlite3_malloc(nOut);
6248 sqlite3_result_error_nomem(context);
6251 if( Z_OK!=compress(pOut, &nOut, pData, nData) ){
6252 sqlite3_result_error(context, "error in compress()", -1);
6253 }else if( nOut<nData ){
6254 sqlite3_result_blob(context, pOut, nOut, SQLITE_TRANSIENT);
6256 sqlite3_result_value(context, argv[0]);
6261 sqlite3_result_value(context, argv[0]);
6266 ** Implementation of the "sqlar_uncompress(X,SZ)" SQL function
6268 ** Parameter SZ is interpreted as an integer. If it is less than or
6269 ** equal to zero, then this function returns a copy of X. Or, if
6270 ** SZ is equal to the size of X when interpreted as a blob, also
6271 ** return a copy of X. Otherwise, decompress blob X using zlib
6272 ** utility function uncompress() and return the results (another
6275 static void sqlarUncompressFunc(
6276 sqlite3_context *context,
6278 sqlite3_value **argv
6284 sz = sqlite3_value_int(argv[1]);
6286 if( sz<=0 || sz==(nData = sqlite3_value_bytes(argv[0])) ){
6287 sqlite3_result_value(context, argv[0]);
6289 const Bytef *pData= sqlite3_value_blob(argv[0]);
6290 Bytef *pOut = sqlite3_malloc(sz);
6291 if( Z_OK!=uncompress(pOut, &sz, pData, nData) ){
6292 sqlite3_result_error(context, "error in uncompress()", -1);
6294 sqlite3_result_blob(context, pOut, sz, SQLITE_TRANSIENT);
6304 int sqlite3_sqlar_init(
6307 const sqlite3_api_routines *pApi
6310 SQLITE_EXTENSION_INIT2(pApi);
6311 (void)pzErrMsg; /* Unused parameter */
6312 rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
6313 sqlarCompressFunc, 0, 0);
6314 if( rc==SQLITE_OK ){
6315 rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
6316 sqlarUncompressFunc, 0, 0);
6321 /************************* End ../ext/misc/sqlar.c ********************/
6323 /************************* Begin ../ext/expert/sqlite3expert.h ******************/
6327 ** The author disclaims copyright to this source code. In place of
6328 ** a legal notice, here is a blessing:
6330 ** May you do good and not evil.
6331 ** May you find forgiveness for yourself and forgive others.
6332 ** May you share freely, never taking more than you give.
6334 *************************************************************************
6339 typedef struct sqlite3expert sqlite3expert;
6342 ** Create a new sqlite3expert object.
6344 ** If successful, a pointer to the new object is returned and (*pzErr) set
6345 ** to NULL. Or, if an error occurs, NULL is returned and (*pzErr) set to
6346 ** an English-language error message. In this case it is the responsibility
6347 ** of the caller to eventually free the error message buffer using
6350 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErr);
6353 ** Configure an sqlite3expert object.
6355 ** EXPERT_CONFIG_SAMPLE:
6356 ** By default, sqlite3_expert_analyze() generates sqlite_stat1 data for
6357 ** each candidate index. This involves scanning and sorting the entire
6358 ** contents of each user database table once for each candidate index
6359 ** associated with the table. For large databases, this can be
6360 ** prohibitively slow. This option allows the sqlite3expert object to
6361 ** be configured so that sqlite_stat1 data is instead generated based on a
6362 ** subset of each table, or so that no sqlite_stat1 data is used at all.
6364 ** A single integer argument is passed to this option. If the value is less
6365 ** than or equal to zero, then no sqlite_stat1 data is generated or used by
6366 ** the analysis - indexes are recommended based on the database schema only.
6367 ** Or, if the value is 100 or greater, complete sqlite_stat1 data is
6368 ** generated for each candidate index (this is the default). Finally, if the
6369 ** value falls between 0 and 100, then it represents the percentage of user
6370 ** table rows that should be considered when generating sqlite_stat1 data.
6374 ** // Do not generate any sqlite_stat1 data
6375 ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 0);
6377 ** // Generate sqlite_stat1 data based on 10% of the rows in each table.
6378 ** sqlite3_expert_config(pExpert, EXPERT_CONFIG_SAMPLE, 10);
6380 int sqlite3_expert_config(sqlite3expert *p, int op, ...);
6382 #define EXPERT_CONFIG_SAMPLE 1 /* int */
6385 ** Specify zero or more SQL statements to be included in the analysis.
6387 ** Buffer zSql must contain zero or more complete SQL statements. This
6388 ** function parses all statements contained in the buffer and adds them
6389 ** to the internal list of statements to analyze. If successful, SQLITE_OK
6390 ** is returned and (*pzErr) set to NULL. Or, if an error occurs - for example
6391 ** due to a error in the SQL - an SQLite error code is returned and (*pzErr)
6392 ** may be set to point to an English language error message. In this case
6393 ** the caller is responsible for eventually freeing the error message buffer
6394 ** using sqlite3_free().
6396 ** If an error does occur while processing one of the statements in the
6397 ** buffer passed as the second argument, none of the statements in the
6398 ** buffer are added to the analysis.
6400 ** This function must be called before sqlite3_expert_analyze(). If a call
6401 ** to this function is made on an sqlite3expert object that has already
6402 ** been passed to sqlite3_expert_analyze() SQLITE_MISUSE is returned
6403 ** immediately and no statements are added to the analysis.
6405 int sqlite3_expert_sql(
6406 sqlite3expert *p, /* From a successful sqlite3_expert_new() */
6407 const char *zSql, /* SQL statement(s) to add */
6408 char **pzErr /* OUT: Error message (if any) */
6413 ** This function is called after the sqlite3expert object has been configured
6414 ** with all SQL statements using sqlite3_expert_sql() to actually perform
6415 ** the analysis. Once this function has been called, it is not possible to
6416 ** add further SQL statements to the analysis.
6418 ** If successful, SQLITE_OK is returned and (*pzErr) is set to NULL. Or, if
6419 ** an error occurs, an SQLite error code is returned and (*pzErr) set to
6420 ** point to a buffer containing an English language error message. In this
6421 ** case it is the responsibility of the caller to eventually free the buffer
6422 ** using sqlite3_free().
6424 ** If an error does occur within this function, the sqlite3expert object
6425 ** is no longer useful for any purpose. At that point it is no longer
6426 ** possible to add further SQL statements to the object or to re-attempt
6427 ** the analysis. The sqlite3expert object must still be freed using a call
6428 ** sqlite3_expert_destroy().
6430 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr);
6433 ** Return the total number of statements loaded using sqlite3_expert_sql().
6434 ** The total number of SQL statements may be different from the total number
6435 ** to calls to sqlite3_expert_sql().
6437 int sqlite3_expert_count(sqlite3expert*);
6440 ** Return a component of the report.
6442 ** This function is called after sqlite3_expert_analyze() to extract the
6443 ** results of the analysis. Each call to this function returns either a
6444 ** NULL pointer or a pointer to a buffer containing a nul-terminated string.
6445 ** The value passed as the third argument must be one of the EXPERT_REPORT_*
6446 ** #define constants defined below.
6448 ** For some EXPERT_REPORT_* parameters, the buffer returned contains
6449 ** information relating to a specific SQL statement. In these cases that
6450 ** SQL statement is identified by the value passed as the second argument.
6451 ** SQL statements are numbered from 0 in the order in which they are parsed.
6452 ** If an out-of-range value (less than zero or equal to or greater than the
6453 ** value returned by sqlite3_expert_count()) is passed as the second argument
6454 ** along with such an EXPERT_REPORT_* parameter, NULL is always returned.
6456 ** EXPERT_REPORT_SQL:
6457 ** Return the text of SQL statement iStmt.
6459 ** EXPERT_REPORT_INDEXES:
6460 ** Return a buffer containing the CREATE INDEX statements for all recommended
6461 ** indexes for statement iStmt. If there are no new recommeded indexes, NULL
6464 ** EXPERT_REPORT_PLAN:
6465 ** Return a buffer containing the EXPLAIN QUERY PLAN output for SQL query
6466 ** iStmt after the proposed indexes have been added to the database schema.
6468 ** EXPERT_REPORT_CANDIDATES:
6469 ** Return a pointer to a buffer containing the CREATE INDEX statements
6470 ** for all indexes that were tested (for all SQL statements). The iStmt
6471 ** parameter is ignored for EXPERT_REPORT_CANDIDATES calls.
6473 const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
6476 ** Values for the third argument passed to sqlite3_expert_report().
6478 #define EXPERT_REPORT_SQL 1
6479 #define EXPERT_REPORT_INDEXES 2
6480 #define EXPERT_REPORT_PLAN 3
6481 #define EXPERT_REPORT_CANDIDATES 4
6484 ** Free an (sqlite3expert*) handle and all associated resources. There
6485 ** should be one call to this function for each successful call to
6486 ** sqlite3-expert_new().
6488 void sqlite3_expert_destroy(sqlite3expert*);
6492 /************************* End ../ext/expert/sqlite3expert.h ********************/
6493 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
6497 ** The author disclaims copyright to this source code. In place of
6498 ** a legal notice, here is a blessing:
6500 ** May you do good and not evil.
6501 ** May you find forgiveness for yourself and forgive others.
6502 ** May you share freely, never taking more than you give.
6504 *************************************************************************
6510 #ifndef SQLITE_OMIT_VIRTUALTABLE
6512 /* typedef sqlite3_int64 i64; */
6513 /* typedef sqlite3_uint64 u64; */
6515 typedef struct IdxColumn IdxColumn;
6516 typedef struct IdxConstraint IdxConstraint;
6517 typedef struct IdxScan IdxScan;
6518 typedef struct IdxStatement IdxStatement;
6519 typedef struct IdxTable IdxTable;
6520 typedef struct IdxWrite IdxWrite;
6522 #define STRLEN (int)strlen
6525 ** A temp table name that we assume no user database will actually use.
6526 ** If this assumption proves incorrect triggers on the table with the
6527 ** conflicting name will be ignored.
6529 #define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
6532 ** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
6533 ** any other type of single-ended range constraint on a column).
6536 ** Used to temporarily link IdxConstraint objects into lists while
6537 ** creating candidate indexes.
6539 struct IdxConstraint {
6540 char *zColl; /* Collation sequence */
6541 int bRange; /* True for range, false for eq */
6542 int iCol; /* Constrained table column */
6543 int bFlag; /* Used by idxFindCompatible() */
6544 int bDesc; /* True if ORDER BY <expr> DESC */
6545 IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
6546 IdxConstraint *pLink; /* See above */
6550 ** A single scan of a single table.
6553 IdxTable *pTab; /* Associated table object */
6554 int iDb; /* Database containing table zTable */
6555 i64 covering; /* Mask of columns required for cov. index */
6556 IdxConstraint *pOrder; /* ORDER BY columns */
6557 IdxConstraint *pEq; /* List of == constraints */
6558 IdxConstraint *pRange; /* List of < constraints */
6559 IdxScan *pNextScan; /* Next IdxScan object for same analysis */
6563 ** Information regarding a single database table. Extracted from
6564 ** "PRAGMA table_info" by function idxGetTableInfo().
6573 char *zName; /* Table name */
6575 IdxTable *pNext; /* Next table in linked list of all tables */
6579 ** An object of the following type is created for each unique table/write-op
6580 ** seen. The objects are stored in a singly-linked list beginning at
6581 ** sqlite3expert.pWrite.
6585 int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
6590 ** Each statement being analyzed is represented by an instance of this
6593 struct IdxStatement {
6594 int iId; /* Statement number */
6595 char *zSql; /* SQL statement */
6596 char *zIdx; /* Indexes */
6597 char *zEQP; /* Plan */
6598 IdxStatement *pNext;
6603 ** A hash table for storing strings. With space for a payload string
6604 ** with each entry. Methods are:
6611 #define IDX_HASH_SIZE 1023
6612 typedef struct IdxHashEntry IdxHashEntry;
6613 typedef struct IdxHash IdxHash;
6614 struct IdxHashEntry {
6615 char *zKey; /* nul-terminated key */
6616 char *zVal; /* nul-terminated value string */
6617 char *zVal2; /* nul-terminated value string 2 */
6618 IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
6619 IdxHashEntry *pNext; /* Next entry in hash */
6622 IdxHashEntry *pFirst;
6623 IdxHashEntry *aHash[IDX_HASH_SIZE];
6627 ** sqlite3expert object.
6629 struct sqlite3expert {
6630 int iSample; /* Percentage of tables to sample for stat1 */
6631 sqlite3 *db; /* User database */
6632 sqlite3 *dbm; /* In-memory db for this analysis */
6633 sqlite3 *dbv; /* Vtab schema for this analysis */
6634 IdxTable *pTable; /* List of all IdxTable objects */
6635 IdxScan *pScan; /* List of scan objects */
6636 IdxWrite *pWrite; /* List of write objects */
6637 IdxStatement *pStatement; /* List of IdxStatement objects */
6638 int bRun; /* True once analysis has run */
6640 int rc; /* Error code from whereinfo hook */
6641 IdxHash hIdx; /* Hash containing all candidate indexes */
6642 char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
6647 ** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
6648 ** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
6650 static void *idxMalloc(int *pRc, int nByte){
6652 assert( *pRc==SQLITE_OK );
6654 pRet = sqlite3_malloc(nByte);
6656 memset(pRet, 0, nByte);
6658 *pRc = SQLITE_NOMEM;
6664 ** Initialize an IdxHash hash table.
6666 static void idxHashInit(IdxHash *pHash){
6667 memset(pHash, 0, sizeof(IdxHash));
6671 ** Reset an IdxHash hash table.
6673 static void idxHashClear(IdxHash *pHash){
6675 for(i=0; i<IDX_HASH_SIZE; i++){
6676 IdxHashEntry *pEntry;
6677 IdxHashEntry *pNext;
6678 for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
6679 pNext = pEntry->pHashNext;
6680 sqlite3_free(pEntry->zVal2);
6681 sqlite3_free(pEntry);
6684 memset(pHash, 0, sizeof(IdxHash));
6688 ** Return the index of the hash bucket that the string specified by the
6689 ** arguments to this function belongs.
6691 static int idxHashString(const char *z, int n){
6692 unsigned int ret = 0;
6695 ret += (ret<<3) + (unsigned char)(z[i]);
6697 return (int)(ret % IDX_HASH_SIZE);
6701 ** If zKey is already present in the hash table, return non-zero and do
6702 ** nothing. Otherwise, add an entry with key zKey and payload string zVal to
6703 ** the hash table passed as the second argument.
6705 static int idxHashAdd(
6711 int nKey = STRLEN(zKey);
6712 int iHash = idxHashString(zKey, nKey);
6713 int nVal = (zVal ? STRLEN(zVal) : 0);
6714 IdxHashEntry *pEntry;
6716 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
6717 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
6721 pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + nKey+1 + nVal+1);
6723 pEntry->zKey = (char*)&pEntry[1];
6724 memcpy(pEntry->zKey, zKey, nKey);
6726 pEntry->zVal = &pEntry->zKey[nKey+1];
6727 memcpy(pEntry->zVal, zVal, nVal);
6729 pEntry->pHashNext = pHash->aHash[iHash];
6730 pHash->aHash[iHash] = pEntry;
6732 pEntry->pNext = pHash->pFirst;
6733 pHash->pFirst = pEntry;
6739 ** If zKey/nKey is present in the hash table, return a pointer to the
6740 ** hash-entry object.
6742 static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
6744 IdxHashEntry *pEntry;
6745 if( nKey<0 ) nKey = STRLEN(zKey);
6746 iHash = idxHashString(zKey, nKey);
6748 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
6749 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
6757 ** If the hash table contains an entry with a key equal to the string
6758 ** passed as the final two arguments to this function, return a pointer
6759 ** to the payload string. Otherwise, if zKey/nKey is not present in the
6760 ** hash table, return NULL.
6762 static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
6763 IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
6764 if( pEntry ) return pEntry->zVal;
6769 ** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
6770 ** variable to point to a copy of nul-terminated string zColl.
6772 static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
6773 IdxConstraint *pNew;
6774 int nColl = STRLEN(zColl);
6776 assert( *pRc==SQLITE_OK );
6777 pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) * nColl + 1);
6779 pNew->zColl = (char*)&pNew[1];
6780 memcpy(pNew->zColl, zColl, nColl+1);
6786 ** An error associated with database handle db has just occurred. Pass
6787 ** the error message to callback function xOut.
6789 static void idxDatabaseError(
6790 sqlite3 *db, /* Database handle */
6791 char **pzErrmsg /* Write error here */
6793 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
6797 ** Prepare an SQL statement.
6799 static int idxPrepareStmt(
6800 sqlite3 *db, /* Database handle to compile against */
6801 sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
6802 char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
6803 const char *zSql /* SQL statement to compile */
6805 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
6806 if( rc!=SQLITE_OK ){
6808 idxDatabaseError(db, pzErrmsg);
6814 ** Prepare an SQL statement using the results of a printf() formatting.
6816 static int idxPrintfPrepareStmt(
6817 sqlite3 *db, /* Database handle to compile against */
6818 sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
6819 char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
6820 const char *zFmt, /* printf() format of SQL statement */
6821 ... /* Trailing printf() arguments */
6827 zSql = sqlite3_vmprintf(zFmt, ap);
6831 rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
6839 /*************************************************************************
6840 ** Beginning of virtual table implementation.
6842 typedef struct ExpertVtab ExpertVtab;
6846 sqlite3expert *pExpert;
6849 typedef struct ExpertCsr ExpertCsr;
6851 sqlite3_vtab_cursor base;
6852 sqlite3_stmt *pData;
6855 static char *expertDequote(const char *zIn){
6856 int n = STRLEN(zIn);
6857 char *zRet = sqlite3_malloc(n);
6859 assert( zIn[0]=='\'' );
6860 assert( zIn[n-1]=='\'' );
6865 for(iIn=1; iIn<(n-1); iIn++){
6866 if( zIn[iIn]=='\'' ){
6867 assert( zIn[iIn+1]=='\'' );
6870 zRet[iOut++] = zIn[iIn];
6879 ** This function is the implementation of both the xConnect and xCreate
6880 ** methods of the r-tree virtual table.
6882 ** argv[0] -> module name
6883 ** argv[1] -> database name
6884 ** argv[2] -> table name
6885 ** argv[...] -> column names...
6887 static int expertConnect(
6890 int argc, const char *const*argv,
6891 sqlite3_vtab **ppVtab,
6894 sqlite3expert *pExpert = (sqlite3expert*)pAux;
6899 *pzErr = sqlite3_mprintf("internal error!");
6902 char *zCreateTable = expertDequote(argv[3]);
6904 rc = sqlite3_declare_vtab(db, zCreateTable);
6905 if( rc==SQLITE_OK ){
6906 p = idxMalloc(&rc, sizeof(ExpertVtab));
6908 if( rc==SQLITE_OK ){
6909 p->pExpert = pExpert;
6910 p->pTab = pExpert->pTable;
6911 assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
6913 sqlite3_free(zCreateTable);
6919 *ppVtab = (sqlite3_vtab*)p;
6923 static int expertDisconnect(sqlite3_vtab *pVtab){
6924 ExpertVtab *p = (ExpertVtab*)pVtab;
6929 static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
6930 ExpertVtab *p = (ExpertVtab*)pVtab;
6935 SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
6936 SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
6937 SQLITE_INDEX_CONSTRAINT_LE;
6939 pScan = idxMalloc(&rc, sizeof(IdxScan));
6943 /* Link the new scan object into the list */
6944 pScan->pTab = p->pTab;
6945 pScan->pNextScan = p->pExpert->pScan;
6946 p->pExpert->pScan = pScan;
6948 /* Add the constraints to the IdxScan object */
6949 for(i=0; i<pIdxInfo->nConstraint; i++){
6950 struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
6952 && pCons->iColumn>=0
6953 && p->pTab->aCol[pCons->iColumn].iPk==0
6954 && (pCons->op & opmask)
6956 IdxConstraint *pNew;
6957 const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
6958 pNew = idxNewConstraint(&rc, zColl);
6960 pNew->iCol = pCons->iColumn;
6961 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
6962 pNew->pNext = pScan->pEq;
6966 pNew->pNext = pScan->pRange;
6967 pScan->pRange = pNew;
6971 pIdxInfo->aConstraintUsage[i].argvIndex = n;
6975 /* Add the ORDER BY to the IdxScan object */
6976 for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
6977 int iCol = pIdxInfo->aOrderBy[i].iColumn;
6979 IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
6982 pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
6983 pNew->pNext = pScan->pOrder;
6984 pNew->pLink = pScan->pOrder;
6985 pScan->pOrder = pNew;
6992 pIdxInfo->estimatedCost = 1000000.0 / (n+1);
6996 static int expertUpdate(
6997 sqlite3_vtab *pVtab,
6999 sqlite3_value **azData,
7000 sqlite_int64 *pRowid
7010 ** Virtual table module xOpen method.
7012 static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
7016 pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
7017 *ppCursor = (sqlite3_vtab_cursor*)pCsr;
7022 ** Virtual table module xClose method.
7024 static int expertClose(sqlite3_vtab_cursor *cur){
7025 ExpertCsr *pCsr = (ExpertCsr*)cur;
7026 sqlite3_finalize(pCsr->pData);
7032 ** Virtual table module xEof method.
7034 ** Return non-zero if the cursor does not currently point to a valid
7035 ** record (i.e if the scan has finished), or zero otherwise.
7037 static int expertEof(sqlite3_vtab_cursor *cur){
7038 ExpertCsr *pCsr = (ExpertCsr*)cur;
7039 return pCsr->pData==0;
7043 ** Virtual table module xNext method.
7045 static int expertNext(sqlite3_vtab_cursor *cur){
7046 ExpertCsr *pCsr = (ExpertCsr*)cur;
7049 assert( pCsr->pData );
7050 rc = sqlite3_step(pCsr->pData);
7051 if( rc!=SQLITE_ROW ){
7052 rc = sqlite3_finalize(pCsr->pData);
7062 ** Virtual table module xRowid method.
7064 static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
7071 ** Virtual table module xColumn method.
7073 static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
7074 ExpertCsr *pCsr = (ExpertCsr*)cur;
7075 sqlite3_value *pVal;
7076 pVal = sqlite3_column_value(pCsr->pData, i);
7078 sqlite3_result_value(ctx, pVal);
7084 ** Virtual table module xFilter method.
7086 static int expertFilter(
7087 sqlite3_vtab_cursor *cur,
7088 int idxNum, const char *idxStr,
7089 int argc, sqlite3_value **argv
7091 ExpertCsr *pCsr = (ExpertCsr*)cur;
7092 ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
7093 sqlite3expert *pExpert = pVtab->pExpert;
7100 rc = sqlite3_finalize(pCsr->pData);
7102 if( rc==SQLITE_OK ){
7103 rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
7104 "SELECT * FROM main.%Q WHERE sample()", pVtab->pTab->zName
7108 if( rc==SQLITE_OK ){
7109 rc = expertNext(cur);
7114 static int idxRegisterVtab(sqlite3expert *p){
7115 static sqlite3_module expertModule = {
7117 expertConnect, /* xCreate - create a table */
7118 expertConnect, /* xConnect - connect to an existing table */
7119 expertBestIndex, /* xBestIndex - Determine search strategy */
7120 expertDisconnect, /* xDisconnect - Disconnect from a table */
7121 expertDisconnect, /* xDestroy - Drop a table */
7122 expertOpen, /* xOpen - open a cursor */
7123 expertClose, /* xClose - close a cursor */
7124 expertFilter, /* xFilter - configure scan constraints */
7125 expertNext, /* xNext - advance a cursor */
7126 expertEof, /* xEof */
7127 expertColumn, /* xColumn - read data */
7128 expertRowid, /* xRowid - read data */
7129 expertUpdate, /* xUpdate - write data */
7130 0, /* xBegin - begin transaction */
7131 0, /* xSync - sync transaction */
7132 0, /* xCommit - commit transaction */
7133 0, /* xRollback - rollback transaction */
7134 0, /* xFindFunction - function overloading */
7135 0, /* xRename - rename the table */
7138 0, /* xRollbackTo */
7141 return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
7144 ** End of virtual table implementation.
7145 *************************************************************************/
7147 ** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
7148 ** is called, set it to the return value of sqlite3_finalize() before
7149 ** returning. Otherwise, discard the sqlite3_finalize() return value.
7151 static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
7152 int rc = sqlite3_finalize(pStmt);
7153 if( *pRc==SQLITE_OK ) *pRc = rc;
7157 ** Attempt to allocate an IdxTable structure corresponding to table zTab
7158 ** in the main database of connection db. If successful, set (*ppOut) to
7159 ** point to the new object and return SQLITE_OK. Otherwise, return an
7160 ** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
7161 ** set to point to an error string.
7163 ** It is the responsibility of the caller to eventually free either the
7164 ** IdxTable object or error message using sqlite3_free().
7166 static int idxGetTableInfo(
7167 sqlite3 *db, /* Database connection to read details from */
7168 const char *zTab, /* Table name */
7169 IdxTable **ppOut, /* OUT: New object (if successful) */
7170 char **pzErrmsg /* OUT: Error message (if not) */
7172 sqlite3_stmt *p1 = 0;
7174 int nTab = STRLEN(zTab);
7175 int nByte = sizeof(IdxTable) + nTab + 1;
7180 rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
7181 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7182 const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7183 nByte += 1 + STRLEN(zCol);
7184 rc = sqlite3_table_column_metadata(
7185 db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7187 nByte += 1 + STRLEN(zCol);
7190 rc2 = sqlite3_reset(p1);
7191 if( rc==SQLITE_OK ) rc = rc2;
7193 nByte += sizeof(IdxColumn) * nCol;
7194 if( rc==SQLITE_OK ){
7195 pNew = idxMalloc(&rc, nByte);
7197 if( rc==SQLITE_OK ){
7198 pNew->aCol = (IdxColumn*)&pNew[1];
7200 pCsr = (char*)&pNew->aCol[nCol];
7204 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
7205 const char *zCol = (const char*)sqlite3_column_text(p1, 1);
7206 int nCopy = STRLEN(zCol) + 1;
7207 pNew->aCol[nCol].zName = pCsr;
7208 pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
7209 memcpy(pCsr, zCol, nCopy);
7212 rc = sqlite3_table_column_metadata(
7213 db, "main", zTab, zCol, 0, &zCol, 0, 0, 0
7215 if( rc==SQLITE_OK ){
7216 nCopy = STRLEN(zCol) + 1;
7217 pNew->aCol[nCol].zColl = pCsr;
7218 memcpy(pCsr, zCol, nCopy);
7224 idxFinalize(&rc, p1);
7226 if( rc!=SQLITE_OK ){
7231 memcpy(pNew->zName, zTab, nTab+1);
7239 ** This function is a no-op if *pRc is set to anything other than
7240 ** SQLITE_OK when it is called.
7242 ** If *pRc is initially set to SQLITE_OK, then the text specified by
7243 ** the printf() style arguments is appended to zIn and the result returned
7244 ** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
7245 ** zIn before returning.
7247 static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
7251 int nIn = zIn ? STRLEN(zIn) : 0;
7254 if( *pRc==SQLITE_OK ){
7255 zAppend = sqlite3_vmprintf(zFmt, ap);
7257 nAppend = STRLEN(zAppend);
7258 zRet = (char*)sqlite3_malloc(nIn + nAppend + 1);
7260 if( zAppend && zRet ){
7261 if( nIn ) memcpy(zRet, zIn, nIn);
7262 memcpy(&zRet[nIn], zAppend, nAppend+1);
7266 *pRc = SQLITE_NOMEM;
7268 sqlite3_free(zAppend);
7276 ** Return true if zId must be quoted in order to use it as an SQL
7277 ** identifier, or false otherwise.
7279 static int idxIdentifierRequiresQuotes(const char *zId){
7281 for(i=0; zId[i]; i++){
7283 && !(zId[i]>='0' && zId[i]<='9')
7284 && !(zId[i]>='a' && zId[i]<='z')
7285 && !(zId[i]>='A' && zId[i]<='Z')
7294 ** This function appends an index column definition suitable for constraint
7295 ** pCons to the string passed as zIn and returns the result.
7297 static char *idxAppendColDefn(
7298 int *pRc, /* IN/OUT: Error code */
7299 char *zIn, /* Column defn accumulated so far */
7300 IdxTable *pTab, /* Table index will be created on */
7301 IdxConstraint *pCons
7304 IdxColumn *p = &pTab->aCol[pCons->iCol];
7305 if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
7307 if( idxIdentifierRequiresQuotes(p->zName) ){
7308 zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
7310 zRet = idxAppendText(pRc, zRet, "%s", p->zName);
7313 if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
7314 if( idxIdentifierRequiresQuotes(pCons->zColl) ){
7315 zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
7317 zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
7322 zRet = idxAppendText(pRc, zRet, " DESC");
7328 ** Search database dbm for an index compatible with the one idxCreateFromCons()
7329 ** would create from arguments pScan, pEq and pTail. If no error occurs and
7330 ** such an index is found, return non-zero. Or, if no such index is found,
7333 ** If an error occurs, set *pRc to an SQLite error code and return zero.
7335 static int idxFindCompatible(
7336 int *pRc, /* OUT: Error code */
7337 sqlite3* dbm, /* Database to search */
7338 IdxScan *pScan, /* Scan for table to search for index on */
7339 IdxConstraint *pEq, /* List of == constraints */
7340 IdxConstraint *pTail /* List of range constraints */
7342 const char *zTbl = pScan->pTab->zName;
7343 sqlite3_stmt *pIdxList = 0;
7344 IdxConstraint *pIter;
7345 int nEq = 0; /* Number of elements in pEq */
7348 /* Count the elements in list pEq */
7349 for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
7351 rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
7352 while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
7354 IdxConstraint *pT = pTail;
7355 sqlite3_stmt *pInfo = 0;
7356 const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
7358 /* Zero the IdxConstraint.bFlag values in the pEq list */
7359 for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
7361 rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
7362 while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
7363 int iIdx = sqlite3_column_int(pInfo, 0);
7364 int iCol = sqlite3_column_int(pInfo, 1);
7365 const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
7368 for(pIter=pEq; pIter; pIter=pIter->pLink){
7369 if( pIter->bFlag ) continue;
7370 if( pIter->iCol!=iCol ) continue;
7371 if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
7381 if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
7389 idxFinalize(&rc, pInfo);
7391 if( rc==SQLITE_OK && bMatch ){
7392 sqlite3_finalize(pIdxList);
7396 idxFinalize(&rc, pIdxList);
7402 static int idxCreateFromCons(
7406 IdxConstraint *pTail
7408 sqlite3 *dbm = p->dbm;
7410 if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
7411 IdxTable *pTab = pScan->pTab;
7414 IdxConstraint *pCons;
7418 for(pCons=pEq; pCons; pCons=pCons->pLink){
7419 zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7421 for(pCons=pTail; pCons; pCons=pCons->pLink){
7422 zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
7425 if( rc==SQLITE_OK ){
7426 /* Hash the list of columns to come up with a name for the index */
7427 const char *zTable = pScan->pTab->zName;
7428 char *zName; /* Index name */
7430 for(i=0; zCols[i]; i++){
7431 h += ((h<<3) + zCols[i]);
7433 zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
7437 if( idxIdentifierRequiresQuotes(zTable) ){
7438 zFmt = "CREATE INDEX '%q' ON %Q(%s)";
7440 zFmt = "CREATE INDEX %s ON %s(%s)";
7442 zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
7446 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
7447 idxHashAdd(&rc, &p->hIdx, zName, zIdx);
7449 sqlite3_free(zName);
7454 sqlite3_free(zCols);
7460 ** Return true if list pList (linked by IdxConstraint.pLink) contains
7461 ** a constraint compatible with *p. Otherwise return false.
7463 static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
7464 IdxConstraint *pCmp;
7465 for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
7466 if( p->iCol==pCmp->iCol ) return 1;
7471 static int idxCreateFromWhere(
7473 IdxScan *pScan, /* Create indexes for this scan */
7474 IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
7476 IdxConstraint *p1 = 0;
7477 IdxConstraint *pCon;
7480 /* Gather up all the == constraints. */
7481 for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
7482 if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7488 /* Create an index using the == constraints collected above. And the
7489 ** range constraint/ORDER BY terms passed in by the caller, if any. */
7490 rc = idxCreateFromCons(p, pScan, p1, pTail);
7492 /* If no range/ORDER BY passed by the caller, create a version of the
7493 ** index for each range constraint. */
7495 for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
7496 assert( pCon->pLink==0 );
7497 if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
7498 rc = idxCreateFromCons(p, pScan, p1, pCon);
7507 ** Create candidate indexes in database [dbm] based on the data in
7508 ** linked-list pScan.
7510 static int idxCreateCandidates(sqlite3expert *p){
7514 for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
7515 rc = idxCreateFromWhere(p, pIter, 0);
7516 if( rc==SQLITE_OK && pIter->pOrder ){
7517 rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
7525 ** Free all elements of the linked list starting at pConstraint.
7527 static void idxConstraintFree(IdxConstraint *pConstraint){
7528 IdxConstraint *pNext;
7531 for(p=pConstraint; p; p=pNext){
7538 ** Free all elements of the linked list starting from pScan up until pLast
7539 ** (pLast is not freed).
7541 static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
7544 for(p=pScan; p!=pLast; p=pNext){
7545 pNext = p->pNextScan;
7546 idxConstraintFree(p->pOrder);
7547 idxConstraintFree(p->pEq);
7548 idxConstraintFree(p->pRange);
7554 ** Free all elements of the linked list starting from pStatement up
7555 ** until pLast (pLast is not freed).
7557 static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
7559 IdxStatement *pNext;
7560 for(p=pStatement; p!=pLast; p=pNext){
7562 sqlite3_free(p->zEQP);
7563 sqlite3_free(p->zIdx);
7569 ** Free the linked list of IdxTable objects starting at pTab.
7571 static void idxTableFree(IdxTable *pTab){
7574 for(pIter=pTab; pIter; pIter=pNext){
7575 pNext = pIter->pNext;
7576 sqlite3_free(pIter);
7581 ** Free the linked list of IdxWrite objects starting at pTab.
7583 static void idxWriteFree(IdxWrite *pTab){
7586 for(pIter=pTab; pIter; pIter=pNext){
7587 pNext = pIter->pNext;
7588 sqlite3_free(pIter);
7595 ** This function is called after candidate indexes have been created. It
7596 ** runs all the queries to see which indexes they prefer, and populates
7597 ** IdxStatement.zIdx and IdxStatement.zEQP with the results.
7601 char **pzErr /* OUT: Error message (sqlite3_malloc) */
7603 IdxStatement *pStmt;
7604 sqlite3 *dbm = p->dbm;
7610 for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
7611 IdxHashEntry *pEntry;
7612 sqlite3_stmt *pExplain = 0;
7613 idxHashClear(&hIdx);
7614 rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
7615 "EXPLAIN QUERY PLAN %s", pStmt->zSql
7617 while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
7618 /* int iId = sqlite3_column_int(pExplain, 0); */
7619 /* int iParent = sqlite3_column_int(pExplain, 1); */
7620 /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
7621 const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
7622 int nDetail = STRLEN(zDetail);
7625 for(i=0; i<nDetail; i++){
7626 const char *zIdx = 0;
7627 if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
7628 zIdx = &zDetail[i+13];
7629 }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
7630 zIdx = &zDetail[i+22];
7635 while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
7638 zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
7640 idxHashAdd(&rc, &hIdx, zSql, 0);
7641 if( rc ) goto find_indexes_out;
7647 if( zDetail[0]!='-' ){
7648 pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
7652 for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
7653 pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
7656 idxFinalize(&rc, pExplain);
7660 idxHashClear(&hIdx);
7664 static int idxAuthCallback(
7670 const char *zTrigger
7675 if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
7676 if( sqlite3_stricmp(zDb, "main")==0 ){
7677 sqlite3expert *p = (sqlite3expert*)pCtx;
7679 for(pTab=p->pTable; pTab; pTab=pTab->pNext){
7680 if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
7684 for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
7685 if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
7688 pWrite = idxMalloc(&rc, sizeof(IdxWrite));
7689 if( rc==SQLITE_OK ){
7690 pWrite->pTab = pTab;
7692 pWrite->pNext = p->pWrite;
7702 static int idxProcessOneTrigger(
7707 static const char *zInt = UNIQUE_TABLE_NAME;
7708 static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
7709 IdxTable *pTab = pWrite->pTab;
7710 const char *zTab = pTab->zName;
7712 "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
7713 "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
7715 sqlite3_stmt *pSelect = 0;
7719 /* Create the table and its triggers in the temp schema */
7720 rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
7721 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
7722 const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
7723 rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
7725 idxFinalize(&rc, pSelect);
7727 /* Rename the table in the temp schema to zInt */
7728 if( rc==SQLITE_OK ){
7729 char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
7733 rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
7738 switch( pWrite->eOp ){
7739 case SQLITE_INSERT: {
7741 zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
7742 for(i=0; i<pTab->nCol; i++){
7743 zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
7745 zWrite = idxAppendText(&rc, zWrite, ")");
7748 case SQLITE_UPDATE: {
7750 zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
7751 for(i=0; i<pTab->nCol; i++){
7752 zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
7759 assert( pWrite->eOp==SQLITE_DELETE );
7760 if( rc==SQLITE_OK ){
7761 zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
7762 if( zWrite==0 ) rc = SQLITE_NOMEM;
7767 if( rc==SQLITE_OK ){
7768 sqlite3_stmt *pX = 0;
7769 rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
7770 idxFinalize(&rc, pX);
7771 if( rc!=SQLITE_OK ){
7772 idxDatabaseError(p->dbv, pzErr);
7775 sqlite3_free(zWrite);
7777 if( rc==SQLITE_OK ){
7778 rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
7784 static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
7787 IdxWrite *pFirst = p->pWrite;
7789 while( rc==SQLITE_OK && pFirst!=pEnd ){
7791 for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
7792 rc = idxProcessOneTrigger(p, pIter, pzErr);
7802 static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
7803 int rc = idxRegisterVtab(p);
7804 sqlite3_stmt *pSchema = 0;
7806 /* For each table in the main db schema:
7808 ** 1) Add an entry to the p->pTable list, and
7809 ** 2) Create the equivalent virtual table in dbv.
7811 rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
7812 "SELECT type, name, sql, 1 FROM sqlite_master "
7813 "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
7815 "SELECT type, name, sql, 2 FROM sqlite_master "
7816 "WHERE type = 'trigger'"
7817 " AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
7820 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
7821 const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
7822 const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
7823 const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
7825 if( zType[0]=='v' || zType[1]=='r' ){
7826 rc = sqlite3_exec(p->dbv, zSql, 0, 0, pzErrmsg);
7829 rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
7830 if( rc==SQLITE_OK ){
7834 pTab->pNext = p->pTable;
7837 /* The statement the vtab will pass to sqlite3_declare_vtab() */
7838 zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
7839 for(i=0; i<pTab->nCol; i++){
7840 zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %s",
7841 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
7844 zInner = idxAppendText(&rc, zInner, ")");
7846 /* The CVT statement to create the vtab */
7847 zOuter = idxAppendText(&rc, 0,
7848 "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
7850 if( rc==SQLITE_OK ){
7851 rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
7853 sqlite3_free(zInner);
7854 sqlite3_free(zOuter);
7858 idxFinalize(&rc, pSchema);
7862 struct IdxSampleCtx {
7864 double target; /* Target nRet/nRow value */
7865 double nRow; /* Number of rows seen */
7866 double nRet; /* Number of rows returned */
7869 static void idxSampleFunc(
7870 sqlite3_context *pCtx,
7872 sqlite3_value **argv
7874 struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
7882 bRet = (p->nRet / p->nRow) <= p->target;
7885 sqlite3_randomness(2, (void*)&rnd);
7886 bRet = ((int)rnd % 100) <= p->iTarget;
7890 sqlite3_result_int(pCtx, bRet);
7892 p->nRet += (double)bRet;
7898 int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
7899 i64 iVal; /* SQLITE_INTEGER value */
7900 double rVal; /* SQLITE_FLOAT value */
7901 int nByte; /* Bytes of space allocated at z */
7902 int n; /* Size of buffer z */
7903 char *z; /* SQLITE_TEXT/BLOB value */
7908 ** Implementation of scalar function rem().
7910 static void idxRemFunc(
7911 sqlite3_context *pCtx,
7913 sqlite3_value **argv
7915 struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
7916 struct IdxRemSlot *pSlot;
7920 iSlot = sqlite3_value_int(argv[0]);
7921 assert( iSlot<=p->nSlot );
7922 pSlot = &p->aSlot[iSlot];
7924 switch( pSlot->eType ){
7929 case SQLITE_INTEGER:
7930 sqlite3_result_int64(pCtx, pSlot->iVal);
7934 sqlite3_result_double(pCtx, pSlot->rVal);
7938 sqlite3_result_blob(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
7942 sqlite3_result_text(pCtx, pSlot->z, pSlot->n, SQLITE_TRANSIENT);
7946 pSlot->eType = sqlite3_value_type(argv[1]);
7947 switch( pSlot->eType ){
7952 case SQLITE_INTEGER:
7953 pSlot->iVal = sqlite3_value_int64(argv[1]);
7957 pSlot->rVal = sqlite3_value_double(argv[1]);
7962 int nByte = sqlite3_value_bytes(argv[1]);
7963 if( nByte>pSlot->nByte ){
7964 char *zNew = (char*)sqlite3_realloc(pSlot->z, nByte*2);
7966 sqlite3_result_error_nomem(pCtx);
7969 pSlot->nByte = nByte*2;
7973 if( pSlot->eType==SQLITE_BLOB ){
7974 memcpy(pSlot->z, sqlite3_value_blob(argv[1]), nByte);
7976 memcpy(pSlot->z, sqlite3_value_text(argv[1]), nByte);
7983 static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
7986 "SELECT max(i.seqno) FROM "
7987 " sqlite_master AS s, "
7988 " pragma_index_list(s.name) AS l, "
7989 " pragma_index_info(l.name) AS i "
7990 "WHERE s.type = 'table'";
7991 sqlite3_stmt *pMax = 0;
7994 rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
7995 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
7996 *pnMax = sqlite3_column_int(pMax, 0) + 1;
7998 idxFinalize(&rc, pMax);
8003 static int idxPopulateOneStat1(
8005 sqlite3_stmt *pIndexXInfo,
8006 sqlite3_stmt *pWriteStat,
8016 sqlite3_stmt *pQuery = 0;
8020 assert( p->iSample>0 );
8022 /* Formulate the query text */
8023 sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
8024 while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
8025 const char *zComma = zCols==0 ? "" : ", ";
8026 const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
8027 const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
8028 zCols = idxAppendText(&rc, zCols,
8029 "%sx.%Q IS rem(%d, x.%Q) COLLATE %s", zComma, zName, nCol, zName, zColl
8031 zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
8033 sqlite3_reset(pIndexXInfo);
8034 if( rc==SQLITE_OK ){
8035 if( p->iSample==100 ){
8036 zQuery = sqlite3_mprintf(
8037 "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
8040 zQuery = sqlite3_mprintf(
8041 "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
8045 sqlite3_free(zCols);
8046 sqlite3_free(zOrder);
8048 /* Formulate the query text */
8049 if( rc==SQLITE_OK ){
8050 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8051 rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
8053 sqlite3_free(zQuery);
8055 if( rc==SQLITE_OK ){
8056 aStat = (int*)idxMalloc(&rc, sizeof(int)*(nCol+1));
8058 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8059 IdxHashEntry *pEntry;
8061 for(i=0; i<=nCol; i++) aStat[i] = 1;
8062 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
8064 for(i=0; i<nCol; i++){
8065 if( sqlite3_column_int(pQuery, i)==0 ) break;
8067 for(/*no-op*/; i<nCol; i++){
8072 if( rc==SQLITE_OK ){
8074 zStat = sqlite3_mprintf("%d", s0);
8075 if( zStat==0 ) rc = SQLITE_NOMEM;
8076 for(i=1; rc==SQLITE_OK && i<=nCol; i++){
8077 zStat = idxAppendText(&rc, zStat, " %d", (s0+aStat[i]/2) / aStat[i]);
8081 if( rc==SQLITE_OK ){
8082 sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
8083 sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
8084 sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
8085 sqlite3_step(pWriteStat);
8086 rc = sqlite3_reset(pWriteStat);
8089 pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
8091 assert( pEntry->zVal2==0 );
8092 pEntry->zVal2 = zStat;
8094 sqlite3_free(zStat);
8097 sqlite3_free(aStat);
8098 idxFinalize(&rc, pQuery);
8103 static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
8107 rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8108 if( rc!=SQLITE_OK ) return rc;
8110 zSql = sqlite3_mprintf(
8111 "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
8113 if( zSql==0 ) return SQLITE_NOMEM;
8114 rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
8121 ** This function is called as part of sqlite3_expert_analyze(). Candidate
8122 ** indexes have already been created in database sqlite3expert.dbm, this
8123 ** function populates sqlite_stat1 table in the same database.
8125 ** The stat1 data is generated by querying the
8127 static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
8130 struct IdxRemCtx *pCtx = 0;
8131 struct IdxSampleCtx samplectx;
8133 i64 iPrev = -100000;
8134 sqlite3_stmt *pAllIndex = 0;
8135 sqlite3_stmt *pIndexXInfo = 0;
8136 sqlite3_stmt *pWrite = 0;
8138 const char *zAllIndex =
8139 "SELECT s.rowid, s.name, l.name FROM "
8140 " sqlite_master AS s, "
8141 " pragma_index_list(s.name) AS l "
8142 "WHERE s.type = 'table'";
8143 const char *zIndexXInfo =
8144 "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
8145 const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
8147 /* If iSample==0, no sqlite_stat1 data is required. */
8148 if( p->iSample==0 ) return SQLITE_OK;
8150 rc = idxLargestIndex(p->dbm, &nMax, pzErr);
8151 if( nMax<=0 || rc!=SQLITE_OK ) return rc;
8153 rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
8155 if( rc==SQLITE_OK ){
8156 int nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
8157 pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
8160 if( rc==SQLITE_OK ){
8161 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
8162 rc = sqlite3_create_function(
8163 dbrem, "rem", 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
8166 if( rc==SQLITE_OK ){
8167 rc = sqlite3_create_function(
8168 p->db, "sample", 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
8172 if( rc==SQLITE_OK ){
8173 pCtx->nSlot = nMax+1;
8174 rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
8176 if( rc==SQLITE_OK ){
8177 rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
8179 if( rc==SQLITE_OK ){
8180 rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
8183 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
8184 i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
8185 const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
8186 const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
8187 if( p->iSample<100 && iPrev!=iRowid ){
8188 samplectx.target = (double)p->iSample / 100.0;
8189 samplectx.iTarget = p->iSample;
8190 samplectx.nRow = 0.0;
8191 samplectx.nRet = 0.0;
8192 rc = idxBuildSampleTable(p, zTab);
8193 if( rc!=SQLITE_OK ) break;
8195 rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
8198 if( rc==SQLITE_OK && p->iSample<100 ){
8199 rc = sqlite3_exec(p->dbv,
8200 "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
8204 idxFinalize(&rc, pAllIndex);
8205 idxFinalize(&rc, pIndexXInfo);
8206 idxFinalize(&rc, pWrite);
8208 for(i=0; i<pCtx->nSlot; i++){
8209 sqlite3_free(pCtx->aSlot[i].z);
8213 if( rc==SQLITE_OK ){
8214 rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
8217 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
8222 ** Allocate a new sqlite3expert object.
8224 sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
8226 sqlite3expert *pNew;
8228 pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
8230 /* Open two in-memory databases to work with. The "vtab database" (dbv)
8231 ** will contain a virtual table corresponding to each real table in
8232 ** the user database schema, and a copy of each view. It is used to
8233 ** collect information regarding the WHERE, ORDER BY and other clauses
8234 ** of the user's query.
8236 if( rc==SQLITE_OK ){
8238 pNew->iSample = 100;
8239 rc = sqlite3_open(":memory:", &pNew->dbv);
8241 if( rc==SQLITE_OK ){
8242 rc = sqlite3_open(":memory:", &pNew->dbm);
8243 if( rc==SQLITE_OK ){
8244 sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
8249 /* Copy the entire schema of database [db] into [dbm]. */
8250 if( rc==SQLITE_OK ){
8252 rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
8253 "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
8254 " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
8256 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
8257 const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
8258 rc = sqlite3_exec(pNew->dbm, zSql, 0, 0, pzErrmsg);
8260 idxFinalize(&rc, pSql);
8263 /* Create the vtab schema */
8264 if( rc==SQLITE_OK ){
8265 rc = idxCreateVtabSchema(pNew, pzErrmsg);
8268 /* Register the auth callback with dbv */
8269 if( rc==SQLITE_OK ){
8270 sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
8273 /* If an error has occurred, free the new object and reutrn NULL. Otherwise,
8274 ** return the new sqlite3expert handle. */
8275 if( rc!=SQLITE_OK ){
8276 sqlite3_expert_destroy(pNew);
8283 ** Configure an sqlite3expert object.
8285 int sqlite3_expert_config(sqlite3expert *p, int op, ...){
8290 case EXPERT_CONFIG_SAMPLE: {
8291 int iVal = va_arg(ap, int);
8292 if( iVal<0 ) iVal = 0;
8293 if( iVal>100 ) iVal = 100;
8298 rc = SQLITE_NOTFOUND;
8307 ** Add an SQL statement to the analysis.
8309 int sqlite3_expert_sql(
8310 sqlite3expert *p, /* From sqlite3_expert_new() */
8311 const char *zSql, /* SQL statement to add */
8312 char **pzErr /* OUT: Error message (if any) */
8314 IdxScan *pScanOrig = p->pScan;
8315 IdxStatement *pStmtOrig = p->pStatement;
8317 const char *zStmt = zSql;
8319 if( p->bRun ) return SQLITE_MISUSE;
8321 while( rc==SQLITE_OK && zStmt && zStmt[0] ){
8322 sqlite3_stmt *pStmt = 0;
8323 rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
8324 if( rc==SQLITE_OK ){
8327 const char *z = sqlite3_sql(pStmt);
8329 pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
8330 if( rc==SQLITE_OK ){
8331 pNew->zSql = (char*)&pNew[1];
8332 memcpy(pNew->zSql, z, n+1);
8333 pNew->pNext = p->pStatement;
8334 if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
8335 p->pStatement = pNew;
8337 sqlite3_finalize(pStmt);
8340 idxDatabaseError(p->dbv, pzErr);
8344 if( rc!=SQLITE_OK ){
8345 idxScanFree(p->pScan, pScanOrig);
8346 idxStatementFree(p->pStatement, pStmtOrig);
8347 p->pScan = pScanOrig;
8348 p->pStatement = pStmtOrig;
8354 int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
8356 IdxHashEntry *pEntry;
8358 /* Do trigger processing to collect any extra IdxScan structures */
8359 rc = idxProcessTriggers(p, pzErr);
8361 /* Create candidate indexes within the in-memory database file */
8362 if( rc==SQLITE_OK ){
8363 rc = idxCreateCandidates(p);
8366 /* Generate the stat1 data */
8367 if( rc==SQLITE_OK ){
8368 rc = idxPopulateStat1(p, pzErr);
8371 /* Formulate the EXPERT_REPORT_CANDIDATES text */
8372 for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
8373 p->zCandidates = idxAppendText(&rc, p->zCandidates,
8374 "%s;%s%s\n", pEntry->zVal,
8375 pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
8379 /* Figure out which of the candidate indexes are preferred by the query
8380 ** planner and report the results to the user. */
8381 if( rc==SQLITE_OK ){
8382 rc = idxFindIndexes(p, pzErr);
8385 if( rc==SQLITE_OK ){
8392 ** Return the total number of statements that have been added to this
8393 ** sqlite3expert using sqlite3_expert_sql().
8395 int sqlite3_expert_count(sqlite3expert *p){
8397 if( p->pStatement ) nRet = p->pStatement->iId+1;
8402 ** Return a component of the report.
8404 const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
8405 const char *zRet = 0;
8406 IdxStatement *pStmt;
8408 if( p->bRun==0 ) return 0;
8409 for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
8411 case EXPERT_REPORT_SQL:
8412 if( pStmt ) zRet = pStmt->zSql;
8414 case EXPERT_REPORT_INDEXES:
8415 if( pStmt ) zRet = pStmt->zIdx;
8417 case EXPERT_REPORT_PLAN:
8418 if( pStmt ) zRet = pStmt->zEQP;
8420 case EXPERT_REPORT_CANDIDATES:
8421 zRet = p->zCandidates;
8428 ** Free an sqlite3expert object.
8430 void sqlite3_expert_destroy(sqlite3expert *p){
8432 sqlite3_close(p->dbm);
8433 sqlite3_close(p->dbv);
8434 idxScanFree(p->pScan, 0);
8435 idxStatementFree(p->pStatement, 0);
8436 idxTableFree(p->pTable);
8437 idxWriteFree(p->pWrite);
8438 idxHashClear(&p->hIdx);
8439 sqlite3_free(p->zCandidates);
8444 #endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
8446 /************************* End ../ext/expert/sqlite3expert.c ********************/
8448 #if defined(SQLITE_ENABLE_SESSION)
8450 ** State information for a single open session
8452 typedef struct OpenSession OpenSession;
8453 struct OpenSession {
8454 char *zName; /* Symbolic name for this session */
8455 int nFilter; /* Number of xFilter rejection GLOB patterns */
8456 char **azFilter; /* Array of xFilter rejection GLOB patterns */
8457 sqlite3_session *p; /* The open session */
8462 ** Shell output mode information from before ".explain on",
8463 ** saved so that it can be restored by ".explain off"
8465 typedef struct SavedModeInfo SavedModeInfo;
8466 struct SavedModeInfo {
8467 int valid; /* Is there legit data in here? */
8468 int mode; /* Mode prior to ".explain on" */
8469 int showHeader; /* The ".header" setting prior to ".explain on" */
8470 int colWidth[100]; /* Column widths prior to ".explain on" */
8473 typedef struct ExpertInfo ExpertInfo;
8475 sqlite3expert *pExpert;
8479 /* A single line in the EQP output */
8480 typedef struct EQPGraphRow EQPGraphRow;
8481 struct EQPGraphRow {
8482 int iEqpId; /* ID for this row */
8483 int iParentId; /* ID of the parent row */
8484 EQPGraphRow *pNext; /* Next row in sequence */
8485 char zText[1]; /* Text to display for this row */
8488 /* All EQP output is collected into an instance of the following */
8489 typedef struct EQPGraph EQPGraph;
8491 EQPGraphRow *pRow; /* Linked list of all rows of the EQP output */
8492 EQPGraphRow *pLast; /* Last element of the pRow list */
8493 char zPrefix[100]; /* Graph prefix */
8497 ** State information about the database connection is contained in an
8498 ** instance of the following structure.
8500 typedef struct ShellState ShellState;
8502 sqlite3 *db; /* The database */
8503 u8 autoExplain; /* Automatically turn on .explain mode */
8504 u8 autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
8505 u8 autoEQPtest; /* autoEQP is in test mode */
8506 u8 statsOn; /* True to display memory stats before each finalize */
8507 u8 scanstatsOn; /* True to display scan stats before each finalize */
8508 u8 openMode; /* SHELL_OPEN_NORMAL, _APPENDVFS, or _ZIPFILE */
8509 u8 doXdgOpen; /* Invoke start/open/xdg-open in output_reset() */
8510 u8 nEqpLevel; /* Depth of the EQP output graph */
8511 unsigned mEqpLines; /* Mask of veritical lines in the EQP output graph */
8512 int outCount; /* Revert to stdout when reaching zero */
8513 int cnt; /* Number of records displayed so far */
8514 FILE *out; /* Write results here */
8515 FILE *traceOut; /* Output for sqlite3_trace() */
8516 int nErr; /* Number of errors seen */
8517 int mode; /* An output mode setting */
8518 int modePrior; /* Saved mode */
8519 int cMode; /* temporary output mode for the current query */
8520 int normalMode; /* Output mode before ".explain on" */
8521 int writableSchema; /* True if PRAGMA writable_schema=ON */
8522 int showHeader; /* True to show column names in List or Column mode */
8523 int nCheck; /* Number of ".check" commands run */
8524 unsigned shellFlgs; /* Various flags */
8525 char *zDestTable; /* Name of destination table when MODE_Insert */
8526 char *zTempFile; /* Temporary file that might need deleting */
8527 char zTestcase[30]; /* Name of current test case */
8528 char colSeparator[20]; /* Column separator character for several modes */
8529 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
8530 char colSepPrior[20]; /* Saved column separator */
8531 char rowSepPrior[20]; /* Saved row separator */
8532 int colWidth[100]; /* Requested width of each column when in column mode*/
8533 int actualWidth[100]; /* Actual width of each column */
8534 char nullValue[20]; /* The text to print when a NULL comes back from
8536 char outfile[FILENAME_MAX]; /* Filename for *out */
8537 const char *zDbFilename; /* name of the database file */
8538 char *zFreeOnClose; /* Filename to free when closing */
8539 const char *zVfs; /* Name of VFS to use */
8540 sqlite3_stmt *pStmt; /* Current statement if any. */
8541 FILE *pLog; /* Write log output here */
8542 int *aiIndent; /* Array of indents used in MODE_Explain */
8543 int nIndent; /* Size of array aiIndent[] */
8544 int iIndent; /* Index of current op in aiIndent[] */
8545 EQPGraph sGraph; /* Information for the graphical EXPLAIN QUERY PLAN */
8546 #if defined(SQLITE_ENABLE_SESSION)
8547 int nSession; /* Number of active sessions */
8548 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
8550 ExpertInfo expert; /* Valid if previous command was ".expert OPT..." */
8554 /* Allowed values for ShellState.autoEQP
8556 #define AUTOEQP_off 0 /* Automatic EXPLAIN QUERY PLAN is off */
8557 #define AUTOEQP_on 1 /* Automatic EQP is on */
8558 #define AUTOEQP_trigger 2 /* On and also show plans for triggers */
8559 #define AUTOEQP_full 3 /* Show full EXPLAIN */
8561 /* Allowed values for ShellState.openMode
8563 #define SHELL_OPEN_UNSPEC 0 /* No open-mode specified */
8564 #define SHELL_OPEN_NORMAL 1 /* Normal database file */
8565 #define SHELL_OPEN_APPENDVFS 2 /* Use appendvfs */
8566 #define SHELL_OPEN_ZIPFILE 3 /* Use the zipfile virtual table */
8567 #define SHELL_OPEN_READONLY 4 /* Open a normal database read-only */
8570 ** These are the allowed shellFlgs values
8572 #define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
8573 #define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
8574 #define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
8575 #define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
8576 #define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
8577 #define SHFLG_CountChanges 0x00000020 /* .changes setting */
8578 #define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
8581 ** Macros for testing and setting shellFlgs
8583 #define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
8584 #define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
8585 #define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
8588 ** These are the allowed modes.
8590 #define MODE_Line 0 /* One column per line. Blank line between records */
8591 #define MODE_Column 1 /* One record per line in neat columns */
8592 #define MODE_List 2 /* One record per line with a separator */
8593 #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
8594 #define MODE_Html 4 /* Generate an XHTML table */
8595 #define MODE_Insert 5 /* Generate SQL "insert" statements */
8596 #define MODE_Quote 6 /* Quote values as for SQL */
8597 #define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
8598 #define MODE_Csv 8 /* Quote strings, numbers are plain */
8599 #define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
8600 #define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
8601 #define MODE_Pretty 11 /* Pretty-print schemas */
8602 #define MODE_EQP 12 /* Converts EXPLAIN QUERY PLAN output into a graph */
8604 static const char *modeDescr[] = {
8621 ** These are the column/row/line separators used by the various
8622 ** import/export modes.
8624 #define SEP_Column "|"
8625 #define SEP_Row "\n"
8626 #define SEP_Tab "\t"
8627 #define SEP_Space " "
8628 #define SEP_Comma ","
8629 #define SEP_CrLf "\r\n"
8630 #define SEP_Unit "\x1F"
8631 #define SEP_Record "\x1E"
8634 ** A callback for the sqlite3_log() interface.
8636 static void shellLog(void *pArg, int iErrCode, const char *zMsg){
8637 ShellState *p = (ShellState*)pArg;
8638 if( p->pLog==0 ) return;
8639 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
8644 ** SQL function: shell_putsnl(X)
8646 ** Write the text X to the screen (or whatever output is being directed)
8647 ** adding a newline at the end, and then return X.
8649 static void shellPutsFunc(
8650 sqlite3_context *pCtx,
8652 sqlite3_value **apVal
8654 ShellState *p = (ShellState*)sqlite3_user_data(pCtx);
8656 utf8_printf(p->out, "%s\n", sqlite3_value_text(apVal[0]));
8657 sqlite3_result_value(pCtx, apVal[0]);
8661 ** SQL function: edit(VALUE)
8662 ** edit(VALUE,EDITOR)
8666 ** (1) Write VALUE into a temporary file.
8667 ** (2) Run program EDITOR on that temporary file.
8668 ** (3) Read the temporary file back and return its content as the result.
8669 ** (4) Delete the temporary file
8671 ** If the EDITOR argument is omitted, use the value in the VISUAL
8672 ** environment variable. If still there is no EDITOR, through an error.
8674 ** Also throw an error if the EDITOR program returns a non-zero exit code.
8676 #ifndef SQLITE_NOHAVE_SYSTEM
8677 static void editFunc(
8678 sqlite3_context *context,
8680 sqlite3_value **argv
8682 const char *zEditor;
8683 char *zTempFile = 0;
8692 unsigned char *p = 0;
8695 zEditor = (const char*)sqlite3_value_text(argv[1]);
8697 zEditor = getenv("VISUAL");
8700 sqlite3_result_error(context, "no editor for edit()", -1);
8703 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
8704 sqlite3_result_error(context, "NULL input to edit()", -1);
8707 db = sqlite3_context_db_handle(context);
8709 sqlite3_file_control(db, 0, SQLITE_FCNTL_TEMPFILENAME, &zTempFile);
8711 sqlite3_uint64 r = 0;
8712 sqlite3_randomness(sizeof(r), &r);
8713 zTempFile = sqlite3_mprintf("temp%llx", r);
8715 sqlite3_result_error_nomem(context);
8719 bBin = sqlite3_value_type(argv[0])==SQLITE_BLOB;
8720 /* When writing the file to be edited, do \n to \r\n conversions on systems
8721 ** that want \r\n line endings */
8722 f = fopen(zTempFile, bBin ? "wb" : "w");
8724 sqlite3_result_error(context, "edit() cannot open temp file", -1);
8727 sz = sqlite3_value_bytes(argv[0]);
8729 x = fwrite(sqlite3_value_blob(argv[0]), 1, sz, f);
8731 const char *z = (const char*)sqlite3_value_text(argv[0]);
8732 /* Remember whether or not the value originally contained \r\n */
8733 if( z && strstr(z,"\r\n")!=0 ) hasCRNL = 1;
8734 x = fwrite(sqlite3_value_text(argv[0]), 1, sz, f);
8739 sqlite3_result_error(context, "edit() could not write the whole file", -1);
8742 zCmd = sqlite3_mprintf("%s \"%s\"", zEditor, zTempFile);
8744 sqlite3_result_error_nomem(context);
8750 sqlite3_result_error(context, "EDITOR returned non-zero", -1);
8753 f = fopen(zTempFile, "rb");
8755 sqlite3_result_error(context,
8756 "edit() cannot reopen temp file after edit", -1);
8759 fseek(f, 0, SEEK_END);
8762 p = sqlite3_malloc64( sz+(bBin==0) );
8764 sqlite3_result_error_nomem(context);
8767 x = fread(p, 1, sz, f);
8771 sqlite3_result_error(context, "could not read back the whole file", -1);
8775 sqlite3_result_blob64(context, p, sz, sqlite3_free);
8779 /* If the original contains \r\n then do no conversions back to \n */
8782 /* If the file did not originally contain \r\n then convert any new
8783 ** \r\n back into \n */
8784 for(i=j=0; i<sz; i++){
8785 if( p[i]=='\r' && p[i+1]=='\n' ) i++;
8791 sqlite3_result_text64(context, (const char*)p, sz,
8792 sqlite3_free, SQLITE_UTF8);
8799 sqlite3_free(zTempFile);
8802 #endif /* SQLITE_NOHAVE_SYSTEM */
8805 ** Save or restore the current output mode
8807 static void outputModePush(ShellState *p){
8808 p->modePrior = p->mode;
8809 memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
8810 memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
8812 static void outputModePop(ShellState *p){
8813 p->mode = p->modePrior;
8814 memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
8815 memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
8819 ** Output the given string as a hex-encoded blob (eg. X'1234' )
8821 static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
8823 char *zBlob = (char *)pBlob;
8824 raw_printf(out,"X'");
8825 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
8826 raw_printf(out,"'");
8830 ** Find a string that is not found anywhere in z[]. Return a pointer
8833 ** Try to use zA and zB first. If both of those are already found in z[]
8834 ** then make up some string and store it in the buffer zBuf.
8836 static const char *unused_string(
8837 const char *z, /* Result must not appear anywhere in z */
8838 const char *zA, const char *zB, /* Try these first */
8839 char *zBuf /* Space to store a generated string */
8842 if( strstr(z, zA)==0 ) return zA;
8843 if( strstr(z, zB)==0 ) return zB;
8845 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
8846 }while( strstr(z,zBuf)!=0 );
8851 ** Output the given string as a quoted string using SQL quoting conventions.
8853 ** See also: output_quoted_escaped_string()
8855 static void output_quoted_string(FILE *out, const char *z){
8858 setBinaryMode(out, 1);
8859 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
8861 utf8_printf(out,"'%s'",z);
8863 raw_printf(out, "'");
8865 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
8868 utf8_printf(out, "%.*s", i, z);
8872 raw_printf(out, "'");
8880 raw_printf(out, "'");
8882 setTextMode(out, 1);
8886 ** Output the given string as a quoted string using SQL quoting conventions.
8887 ** Additionallly , escape the "\n" and "\r" characters so that they do not
8888 ** get corrupted by end-of-line translation facilities in some operating
8891 ** This is like output_quoted_string() but with the addition of the \r\n
8892 ** escape mechanism.
8894 static void output_quoted_escaped_string(FILE *out, const char *z){
8897 setBinaryMode(out, 1);
8898 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
8900 utf8_printf(out,"'%s'",z);
8902 const char *zNL = 0;
8903 const char *zCR = 0;
8906 char zBuf1[20], zBuf2[20];
8907 for(i=0; z[i]; i++){
8908 if( z[i]=='\n' ) nNL++;
8909 if( z[i]=='\r' ) nCR++;
8912 raw_printf(out, "replace(");
8913 zNL = unused_string(z, "\\n", "\\012", zBuf1);
8916 raw_printf(out, "replace(");
8917 zCR = unused_string(z, "\\r", "\\015", zBuf2);
8919 raw_printf(out, "'");
8921 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
8924 utf8_printf(out, "%.*s", i, z);
8928 raw_printf(out, "'");
8936 raw_printf(out, "%s", zNL);
8939 raw_printf(out, "%s", zCR);
8941 raw_printf(out, "'");
8943 raw_printf(out, ",'%s',char(13))", zCR);
8946 raw_printf(out, ",'%s',char(10))", zNL);
8949 setTextMode(out, 1);
8953 ** Output the given string as a quoted according to C or TCL quoting rules.
8955 static void output_c_string(FILE *out, const char *z){
8958 while( (c = *(z++))!=0 ){
8965 }else if( c=='\t' ){
8968 }else if( c=='\n' ){
8971 }else if( c=='\r' ){
8974 }else if( !isprint(c&0xff) ){
8975 raw_printf(out, "\\%03o", c&0xff);
8984 ** Output the given string with characters that are special to
8987 static void output_html_string(FILE *out, const char *z){
8999 utf8_printf(out,"%.*s",i,z);
9002 raw_printf(out,"<");
9003 }else if( z[i]=='&' ){
9004 raw_printf(out,"&");
9005 }else if( z[i]=='>' ){
9006 raw_printf(out,">");
9007 }else if( z[i]=='\"' ){
9008 raw_printf(out,""");
9009 }else if( z[i]=='\'' ){
9010 raw_printf(out,"'");
9019 ** If a field contains any character identified by a 1 in the following
9020 ** array, then the string must be quoted for CSV.
9022 static const char needCsvQuote[] = {
9023 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9024 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9025 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
9026 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9027 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9028 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9029 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
9030 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
9031 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9032 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9033 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9034 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9035 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9036 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9037 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9038 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9042 ** Output a single term of CSV. Actually, p->colSeparator is used for
9043 ** the separator, which may or may not be a comma. p->nullValue is
9044 ** the null value. Strings are quoted if necessary. The separator
9045 ** is only issued if bSep is true.
9047 static void output_csv(ShellState *p, const char *z, int bSep){
9050 utf8_printf(out,"%s",p->nullValue);
9053 int nSep = strlen30(p->colSeparator);
9054 for(i=0; z[i]; i++){
9055 if( needCsvQuote[((unsigned char*)z)[i]]
9056 || (z[i]==p->colSeparator[0] &&
9057 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
9063 char *zQuoted = sqlite3_mprintf("\"%w\"", z);
9064 utf8_printf(out, "%s", zQuoted);
9065 sqlite3_free(zQuoted);
9067 utf8_printf(out, "%s", z);
9071 utf8_printf(p->out, "%s", p->colSeparator);
9076 ** This routine runs when the user presses Ctrl-C
9078 static void interrupt_handler(int NotUsed){
9079 UNUSED_PARAMETER(NotUsed);
9081 if( seenInterrupt>2 ) exit(1);
9082 if( globalDb ) sqlite3_interrupt(globalDb);
9085 #if (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
9087 ** This routine runs for console events (e.g. Ctrl-C) on Win32
9089 static BOOL WINAPI ConsoleCtrlHandler(
9090 DWORD dwCtrlType /* One of the CTRL_*_EVENT constants */
9092 if( dwCtrlType==CTRL_C_EVENT ){
9093 interrupt_handler(0);
9100 #ifndef SQLITE_OMIT_AUTHORIZATION
9102 ** When the ".auth ON" is set, the following authorizer callback is
9103 ** invoked. It always returns SQLITE_OK.
9105 static int shellAuth(
9113 ShellState *p = (ShellState*)pClientData;
9114 static const char *azAction[] = { 0,
9115 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
9116 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
9117 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
9118 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
9119 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
9120 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
9121 "PRAGMA", "READ", "SELECT",
9122 "TRANSACTION", "UPDATE", "ATTACH",
9123 "DETACH", "ALTER_TABLE", "REINDEX",
9124 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
9125 "FUNCTION", "SAVEPOINT", "RECURSIVE"
9133 utf8_printf(p->out, "authorizer: %s", azAction[op]);
9135 raw_printf(p->out, " ");
9137 output_c_string(p->out, az[i]);
9139 raw_printf(p->out, "NULL");
9142 raw_printf(p->out, "\n");
9148 ** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
9150 ** This routine converts some CREATE TABLE statements for shadow tables
9151 ** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
9153 static void printSchemaLine(FILE *out, const char *z, const char *zTail){
9154 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
9155 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
9157 utf8_printf(out, "%s%s", z, zTail);
9160 static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
9163 printSchemaLine(out, z, zTail);
9168 ** Return true if string z[] has nothing but whitespace and comments to the
9169 ** end of the first line.
9171 static int wsToEol(const char *z){
9173 for(i=0; z[i]; i++){
9174 if( z[i]=='\n' ) return 1;
9175 if( IsSpace(z[i]) ) continue;
9176 if( z[i]=='-' && z[i+1]=='-' ) return 1;
9183 ** Add a new entry to the EXPLAIN QUERY PLAN data
9185 static void eqp_append(ShellState *p, int iEqpId, int p2, const char *zText){
9187 int nText = strlen30(zText);
9188 if( p->autoEQPtest ){
9189 utf8_printf(p->out, "%d,%d,%s\n", iEqpId, p2, zText);
9191 pNew = sqlite3_malloc64( sizeof(*pNew) + nText );
9192 if( pNew==0 ) shell_out_of_memory();
9193 pNew->iEqpId = iEqpId;
9194 pNew->iParentId = p2;
9195 memcpy(pNew->zText, zText, nText+1);
9197 if( p->sGraph.pLast ){
9198 p->sGraph.pLast->pNext = pNew;
9200 p->sGraph.pRow = pNew;
9202 p->sGraph.pLast = pNew;
9206 ** Free and reset the EXPLAIN QUERY PLAN data that has been collected
9209 static void eqp_reset(ShellState *p){
9210 EQPGraphRow *pRow, *pNext;
9211 for(pRow = p->sGraph.pRow; pRow; pRow = pNext){
9212 pNext = pRow->pNext;
9215 memset(&p->sGraph, 0, sizeof(p->sGraph));
9218 /* Return the next EXPLAIN QUERY PLAN line with iEqpId that occurs after
9219 ** pOld, or return the first such line if pOld is NULL
9221 static EQPGraphRow *eqp_next_row(ShellState *p, int iEqpId, EQPGraphRow *pOld){
9222 EQPGraphRow *pRow = pOld ? pOld->pNext : p->sGraph.pRow;
9223 while( pRow && pRow->iParentId!=iEqpId ) pRow = pRow->pNext;
9227 /* Render a single level of the graph that has iEqpId as its parent. Called
9228 ** recursively to render sublevels.
9230 static void eqp_render_level(ShellState *p, int iEqpId){
9231 EQPGraphRow *pRow, *pNext;
9232 int n = strlen30(p->sGraph.zPrefix);
9234 for(pRow = eqp_next_row(p, iEqpId, 0); pRow; pRow = pNext){
9235 pNext = eqp_next_row(p, iEqpId, pRow);
9237 utf8_printf(p->out, "%s%s%s\n", p->sGraph.zPrefix, pNext ? "|--" : "`--", z);
9238 if( n<(int)sizeof(p->sGraph.zPrefix)-7 ){
9239 memcpy(&p->sGraph.zPrefix[n], pNext ? "| " : " ", 4);
9240 eqp_render_level(p, pRow->iEqpId);
9241 p->sGraph.zPrefix[n] = 0;
9247 ** Display and reset the EXPLAIN QUERY PLAN data
9249 static void eqp_render(ShellState *p){
9250 EQPGraphRow *pRow = p->sGraph.pRow;
9252 if( pRow->zText[0]=='-' ){
9253 if( pRow->pNext==0 ){
9257 utf8_printf(p->out, "%s\n", pRow->zText+3);
9258 p->sGraph.pRow = pRow->pNext;
9261 utf8_printf(p->out, "QUERY PLAN\n");
9263 p->sGraph.zPrefix[0] = 0;
9264 eqp_render_level(p, 0);
9270 ** This is the callback routine that the shell
9271 ** invokes for each row of a query result.
9273 static int shell_callback(
9275 int nArg, /* Number of result columns */
9276 char **azArg, /* Text of each result column */
9277 char **azCol, /* Column names */
9278 int *aiType /* Column types */
9281 ShellState *p = (ShellState*)pArg;
9283 if( azArg==0 ) return 0;
9287 if( azArg==0 ) break;
9288 for(i=0; i<nArg; i++){
9289 int len = strlen30(azCol[i] ? azCol[i] : "");
9290 if( len>w ) w = len;
9292 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
9293 for(i=0; i<nArg; i++){
9294 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
9295 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
9301 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
9302 const int *colWidth;
9305 if( p->cMode==MODE_Column ){
9306 colWidth = p->colWidth;
9307 showHdr = p->showHeader;
9308 rowSep = p->rowSeparator;
9310 colWidth = aExplainWidths;
9315 for(i=0; i<nArg; i++){
9317 if( i<ArraySize(p->colWidth) ){
9323 w = strlenChar(azCol[i] ? azCol[i] : "");
9325 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
9328 if( i<ArraySize(p->actualWidth) ){
9329 p->actualWidth[i] = w;
9332 utf8_width_print(p->out, w, azCol[i]);
9333 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
9337 for(i=0; i<nArg; i++){
9339 if( i<ArraySize(p->actualWidth) ){
9340 w = p->actualWidth[i];
9345 utf8_printf(p->out,"%-*.*s%s",w,w,
9346 "----------------------------------------------------------"
9347 "----------------------------------------------------------",
9348 i==nArg-1 ? rowSep : " ");
9352 if( azArg==0 ) break;
9353 for(i=0; i<nArg; i++){
9355 if( i<ArraySize(p->actualWidth) ){
9356 w = p->actualWidth[i];
9360 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
9361 w = strlenChar(azArg[i]);
9363 if( i==1 && p->aiIndent && p->pStmt ){
9364 if( p->iIndent<p->nIndent ){
9365 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
9369 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
9370 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
9374 case MODE_Semi: { /* .schema and .fullschema output */
9375 printSchemaLine(p->out, azArg[0], ";\n");
9378 case MODE_Pretty: { /* .schema and .fullschema with --indent */
9386 if( azArg[0]==0 ) break;
9387 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
9388 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
9390 utf8_printf(p->out, "%s;\n", azArg[0]);
9393 z = sqlite3_mprintf("%s", azArg[0]);
9395 for(i=0; IsSpace(z[i]); i++){}
9396 for(; (c = z[i])!=0; i++){
9398 if( z[j-1]=='\r' ) z[j-1] = '\n';
9399 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
9400 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
9405 while( j>0 && IsSpace(z[j-1]) ){ j--; }
9407 if( strlen30(z)>=79 ){
9408 for(i=j=0; (c = z[i])!=0; i++){ /* Copy changes from z[i] back to z[j] */
9411 }else if( c=='"' || c=='\'' || c=='`' ){
9415 }else if( c=='-' && z[i+1]=='-' ){
9421 if( nLine>0 && nParen==0 && j>0 ){
9422 printSchemaLineN(p->out, z, j, "\n");
9427 if( nParen==1 && cEnd==0
9428 && (c=='(' || c=='\n' || (c==',' && !wsToEol(z+i+1)))
9431 printSchemaLineN(p->out, z, j, "\n ");
9434 while( IsSpace(z[i+1]) ){ i++; }
9439 printSchemaLine(p->out, z, ";\n");
9444 if( p->cnt++==0 && p->showHeader ){
9445 for(i=0; i<nArg; i++){
9446 utf8_printf(p->out,"%s%s",azCol[i],
9447 i==nArg-1 ? p->rowSeparator : p->colSeparator);
9450 if( azArg==0 ) break;
9451 for(i=0; i<nArg; i++){
9453 if( z==0 ) z = p->nullValue;
9454 utf8_printf(p->out, "%s", z);
9456 utf8_printf(p->out, "%s", p->colSeparator);
9458 utf8_printf(p->out, "%s", p->rowSeparator);
9464 if( p->cnt++==0 && p->showHeader ){
9465 raw_printf(p->out,"<TR>");
9466 for(i=0; i<nArg; i++){
9467 raw_printf(p->out,"<TH>");
9468 output_html_string(p->out, azCol[i]);
9469 raw_printf(p->out,"</TH>\n");
9471 raw_printf(p->out,"</TR>\n");
9473 if( azArg==0 ) break;
9474 raw_printf(p->out,"<TR>");
9475 for(i=0; i<nArg; i++){
9476 raw_printf(p->out,"<TD>");
9477 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
9478 raw_printf(p->out,"</TD>\n");
9480 raw_printf(p->out,"</TR>\n");
9484 if( p->cnt++==0 && p->showHeader ){
9485 for(i=0; i<nArg; i++){
9486 output_c_string(p->out,azCol[i] ? azCol[i] : "");
9487 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
9489 utf8_printf(p->out, "%s", p->rowSeparator);
9491 if( azArg==0 ) break;
9492 for(i=0; i<nArg; i++){
9493 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
9494 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
9496 utf8_printf(p->out, "%s", p->rowSeparator);
9500 setBinaryMode(p->out, 1);
9501 if( p->cnt++==0 && p->showHeader ){
9502 for(i=0; i<nArg; i++){
9503 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
9505 utf8_printf(p->out, "%s", p->rowSeparator);
9508 for(i=0; i<nArg; i++){
9509 output_csv(p, azArg[i], i<nArg-1);
9511 utf8_printf(p->out, "%s", p->rowSeparator);
9513 setTextMode(p->out, 1);
9517 if( azArg==0 ) break;
9518 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
9519 if( p->showHeader ){
9520 raw_printf(p->out,"(");
9521 for(i=0; i<nArg; i++){
9522 if( i>0 ) raw_printf(p->out, ",");
9523 if( quoteChar(azCol[i]) ){
9524 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
9525 utf8_printf(p->out, "%s", z);
9528 raw_printf(p->out, "%s", azCol[i]);
9531 raw_printf(p->out,")");
9534 for(i=0; i<nArg; i++){
9535 raw_printf(p->out, i>0 ? "," : " VALUES(");
9536 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
9537 utf8_printf(p->out,"NULL");
9538 }else if( aiType && aiType[i]==SQLITE_TEXT ){
9539 if( ShellHasFlag(p, SHFLG_Newlines) ){
9540 output_quoted_string(p->out, azArg[i]);
9542 output_quoted_escaped_string(p->out, azArg[i]);
9544 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
9545 utf8_printf(p->out,"%s", azArg[i]);
9546 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
9548 double r = sqlite3_column_double(p->pStmt, i);
9550 memcpy(&ur,&r,sizeof(r));
9551 if( ur==0x7ff0000000000000LL ){
9552 raw_printf(p->out, "1e999");
9553 }else if( ur==0xfff0000000000000LL ){
9554 raw_printf(p->out, "-1e999");
9556 sqlite3_snprintf(50,z,"%!.20g", r);
9557 raw_printf(p->out, "%s", z);
9559 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
9560 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
9561 int nBlob = sqlite3_column_bytes(p->pStmt, i);
9562 output_hex_blob(p->out, pBlob, nBlob);
9563 }else if( isNumber(azArg[i], 0) ){
9564 utf8_printf(p->out,"%s", azArg[i]);
9565 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
9566 output_quoted_string(p->out, azArg[i]);
9568 output_quoted_escaped_string(p->out, azArg[i]);
9571 raw_printf(p->out,");\n");
9575 if( azArg==0 ) break;
9576 if( p->cnt==0 && p->showHeader ){
9577 for(i=0; i<nArg; i++){
9578 if( i>0 ) raw_printf(p->out, ",");
9579 output_quoted_string(p->out, azCol[i]);
9581 raw_printf(p->out,"\n");
9584 for(i=0; i<nArg; i++){
9585 if( i>0 ) raw_printf(p->out, ",");
9586 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
9587 utf8_printf(p->out,"NULL");
9588 }else if( aiType && aiType[i]==SQLITE_TEXT ){
9589 output_quoted_string(p->out, azArg[i]);
9590 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
9591 utf8_printf(p->out,"%s", azArg[i]);
9592 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
9594 double r = sqlite3_column_double(p->pStmt, i);
9595 sqlite3_snprintf(50,z,"%!.20g", r);
9596 raw_printf(p->out, "%s", z);
9597 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
9598 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
9599 int nBlob = sqlite3_column_bytes(p->pStmt, i);
9600 output_hex_blob(p->out, pBlob, nBlob);
9601 }else if( isNumber(azArg[i], 0) ){
9602 utf8_printf(p->out,"%s", azArg[i]);
9604 output_quoted_string(p->out, azArg[i]);
9607 raw_printf(p->out,"\n");
9611 if( p->cnt++==0 && p->showHeader ){
9612 for(i=0; i<nArg; i++){
9613 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
9614 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
9616 utf8_printf(p->out, "%s", p->rowSeparator);
9618 if( azArg==0 ) break;
9619 for(i=0; i<nArg; i++){
9620 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
9621 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
9623 utf8_printf(p->out, "%s", p->rowSeparator);
9627 eqp_append(p, atoi(azArg[0]), atoi(azArg[1]), azArg[3]);
9635 ** This is the callback routine that the SQLite library
9636 ** invokes for each row of a query result.
9638 static int callback(void *pArg, int nArg, char **azArg, char **azCol){
9639 /* since we don't have type info, call the shell_callback with a NULL value */
9640 return shell_callback(pArg, nArg, azArg, azCol, NULL);
9644 ** This is the callback routine from sqlite3_exec() that appends all
9645 ** output onto the end of a ShellText object.
9647 static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
9648 ShellText *p = (ShellText*)pArg;
9650 UNUSED_PARAMETER(az);
9651 if( azArg==0 ) return 0;
9652 if( p->n ) appendText(p, "|", 0);
9653 for(i=0; i<nArg; i++){
9654 if( i ) appendText(p, ",", 0);
9655 if( azArg[i] ) appendText(p, azArg[i], 0);
9661 ** Generate an appropriate SELFTEST table in the main database.
9663 static void createSelftestTable(ShellState *p){
9666 "SAVEPOINT selftest_init;\n"
9667 "CREATE TABLE IF NOT EXISTS selftest(\n"
9668 " tno INTEGER PRIMARY KEY,\n" /* Test number */
9669 " op TEXT,\n" /* Operator: memo run */
9670 " cmd TEXT,\n" /* Command text */
9671 " ans TEXT\n" /* Desired answer */
9673 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
9674 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
9675 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
9676 " 'memo','Tests generated by --init');\n"
9677 "INSERT INTO [_shell$self]\n"
9679 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
9680 "FROM sqlite_master ORDER BY 2'',224))',\n"
9681 " hex(sha3_query('SELECT type,name,tbl_name,sql "
9682 "FROM sqlite_master ORDER BY 2',224));\n"
9683 "INSERT INTO [_shell$self]\n"
9685 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
9686 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
9687 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
9689 " SELECT name FROM sqlite_master\n"
9690 " WHERE type='table'\n"
9691 " AND name<>'selftest'\n"
9692 " AND coalesce(rootpage,0)>0\n"
9695 "INSERT INTO [_shell$self]\n"
9696 " VALUES('run','PRAGMA integrity_check','ok');\n"
9697 "INSERT INTO selftest(tno,op,cmd,ans)"
9698 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
9699 "DROP TABLE [_shell$self];"
9702 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
9703 sqlite3_free(zErrMsg);
9705 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
9710 ** Set the destination table field of the ShellState structure to
9711 ** the name of the table given. Escape any quote characters in the
9714 static void set_table_name(ShellState *p, const char *zName){
9719 if( p->zDestTable ){
9720 free(p->zDestTable);
9723 if( zName==0 ) return;
9724 cQuote = quoteChar(zName);
9725 n = strlen30(zName);
9726 if( cQuote ) n += n+2;
9727 z = p->zDestTable = malloc( n+1 );
9728 if( z==0 ) shell_out_of_memory();
9730 if( cQuote ) z[n++] = cQuote;
9731 for(i=0; zName[i]; i++){
9733 if( zName[i]==cQuote ) z[n++] = cQuote;
9735 if( cQuote ) z[n++] = cQuote;
9741 ** Execute a query statement that will generate SQL output. Print
9742 ** the result columns, comma-separated, on a line and then add a
9743 ** semicolon terminator to the end of that line.
9745 ** If the number of columns is 1 and that column contains text "--"
9746 ** then write the semicolon on a separate line. That way, if a
9747 ** "--" comment occurs at the end of the statement, the comment
9748 ** won't consume the semicolon terminator.
9750 static int run_table_dump_query(
9751 ShellState *p, /* Query context */
9752 const char *zSelect, /* SELECT statement to extract content */
9753 const char *zFirstRow /* Print before first row, if not NULL */
9755 sqlite3_stmt *pSelect;
9760 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
9761 if( rc!=SQLITE_OK || !pSelect ){
9762 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
9763 sqlite3_errmsg(p->db));
9764 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
9767 rc = sqlite3_step(pSelect);
9768 nResult = sqlite3_column_count(pSelect);
9769 while( rc==SQLITE_ROW ){
9771 utf8_printf(p->out, "%s", zFirstRow);
9774 z = (const char*)sqlite3_column_text(pSelect, 0);
9775 utf8_printf(p->out, "%s", z);
9776 for(i=1; i<nResult; i++){
9777 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
9780 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
9782 raw_printf(p->out, "\n;\n");
9784 raw_printf(p->out, ";\n");
9786 rc = sqlite3_step(pSelect);
9788 rc = sqlite3_finalize(pSelect);
9789 if( rc!=SQLITE_OK ){
9790 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
9791 sqlite3_errmsg(p->db));
9792 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
9798 ** Allocate space and save off current error string.
9800 static char *save_err_msg(
9801 sqlite3 *db /* Database to query */
9803 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
9804 char *zErrMsg = sqlite3_malloc64(nErrMsg);
9806 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
9813 ** Attempt to display I/O stats on Linux using /proc/PID/io
9815 static void displayLinuxIoStats(FILE *out){
9818 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
9819 in = fopen(z, "rb");
9821 while( fgets(z, sizeof(z), in)!=0 ){
9822 static const struct {
9823 const char *zPattern;
9826 { "rchar: ", "Bytes received by read():" },
9827 { "wchar: ", "Bytes sent to write():" },
9828 { "syscr: ", "Read() system calls:" },
9829 { "syscw: ", "Write() system calls:" },
9830 { "read_bytes: ", "Bytes read from storage:" },
9831 { "write_bytes: ", "Bytes written to storage:" },
9832 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
9835 for(i=0; i<ArraySize(aTrans); i++){
9836 int n = strlen30(aTrans[i].zPattern);
9837 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
9838 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
9848 ** Display a single line of status using 64-bit values.
9850 static void displayStatLine(
9851 ShellState *p, /* The shell context */
9852 char *zLabel, /* Label for this one line */
9853 char *zFormat, /* Format for the result */
9854 int iStatusCtrl, /* Which status to display */
9855 int bReset /* True to reset the stats */
9857 sqlite3_int64 iCur = -1;
9858 sqlite3_int64 iHiwtr = -1;
9861 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
9862 for(i=0, nPercent=0; zFormat[i]; i++){
9863 if( zFormat[i]=='%' ) nPercent++;
9866 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
9868 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
9870 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
9874 ** Display memory stats.
9876 static int display_stats(
9877 sqlite3 *db, /* Database to query */
9878 ShellState *pArg, /* Pointer to ShellState */
9879 int bReset /* True to reset the stats */
9884 if( pArg==0 || pArg->out==0 ) return 0;
9887 if( pArg->pStmt && (pArg->statsOn & 2) ){
9889 sqlite3_stmt *pStmt = pArg->pStmt;
9891 nCol = sqlite3_column_count(pStmt);
9892 raw_printf(out, "%-36s %d\n", "Number of output columns:", nCol);
9893 for(i=0; i<nCol; i++){
9894 sqlite3_snprintf(sizeof(z),z,"Column %d %nname:", i, &x);
9895 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_name(pStmt,i));
9896 #ifndef SQLITE_OMIT_DECLTYPE
9897 sqlite3_snprintf(30, z+x, "declared type:");
9898 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_decltype(pStmt, i));
9900 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9901 sqlite3_snprintf(30, z+x, "database name:");
9902 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_database_name(pStmt,i));
9903 sqlite3_snprintf(30, z+x, "table name:");
9904 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_table_name(pStmt,i));
9905 sqlite3_snprintf(30, z+x, "origin name:");
9906 utf8_printf(out, "%-36s %s\n", z, sqlite3_column_origin_name(pStmt,i));
9911 displayStatLine(pArg, "Memory Used:",
9912 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
9913 displayStatLine(pArg, "Number of Outstanding Allocations:",
9914 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
9915 if( pArg->shellFlgs & SHFLG_Pagecache ){
9916 displayStatLine(pArg, "Number of Pcache Pages Used:",
9917 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
9919 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
9920 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
9921 displayStatLine(pArg, "Largest Allocation:",
9922 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
9923 displayStatLine(pArg, "Largest Pcache Allocation:",
9924 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
9925 #ifdef YYTRACKMAXSTACKDEPTH
9926 displayStatLine(pArg, "Deepest Parser Stack:",
9927 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
9931 if( pArg->shellFlgs & SHFLG_Lookaside ){
9933 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
9934 &iCur, &iHiwtr, bReset);
9935 raw_printf(pArg->out,
9936 "Lookaside Slots Used: %d (max %d)\n",
9938 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
9939 &iCur, &iHiwtr, bReset);
9940 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
9942 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
9943 &iCur, &iHiwtr, bReset);
9944 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
9946 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
9947 &iCur, &iHiwtr, bReset);
9948 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
9952 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
9953 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
9956 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
9957 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
9959 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
9960 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
9962 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
9963 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
9965 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_SPILL, &iCur, &iHiwtr, 1);
9966 raw_printf(pArg->out, "Page cache spills: %d\n", iCur);
9968 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
9969 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
9972 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
9973 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
9978 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
9980 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
9981 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
9982 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
9983 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
9984 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
9985 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
9986 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
9987 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_REPREPARE, bReset);
9988 raw_printf(pArg->out, "Reprepare operations: %d\n", iCur);
9989 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_RUN, bReset);
9990 raw_printf(pArg->out, "Number of times run: %d\n", iCur);
9991 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_MEMUSED, bReset);
9992 raw_printf(pArg->out, "Memory used by prepared stmt: %d\n", iCur);
9996 displayLinuxIoStats(pArg->out);
9999 /* Do not remove this machine readable comment: extra-stats-output-here */
10005 ** Display scan stats.
10007 static void display_scanstats(
10008 sqlite3 *db, /* Database to query */
10009 ShellState *pArg /* Pointer to ShellState */
10011 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
10012 UNUSED_PARAMETER(db);
10013 UNUSED_PARAMETER(pArg);
10016 raw_printf(pArg->out, "-------- scanstats --------\n");
10018 for(k=0; k<=mx; k++){
10019 double rEstLoop = 1.0;
10020 for(i=n=0; 1; i++){
10021 sqlite3_stmt *p = pArg->pStmt;
10022 sqlite3_int64 nLoop, nVisit;
10025 const char *zExplain;
10026 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
10029 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
10030 if( iSid>mx ) mx = iSid;
10031 if( iSid!=k ) continue;
10033 rEstLoop = (double)nLoop;
10034 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
10037 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
10038 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
10039 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
10040 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
10042 raw_printf(pArg->out,
10043 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
10044 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
10048 raw_printf(pArg->out, "---------------------------\n");
10053 ** Parameter azArray points to a zero-terminated array of strings. zStr
10054 ** points to a single nul-terminated string. Return non-zero if zStr
10055 ** is equal, according to strcmp(), to any of the strings in the array.
10056 ** Otherwise, return zero.
10058 static int str_in_array(const char *zStr, const char **azArray){
10060 for(i=0; azArray[i]; i++){
10061 if( 0==strcmp(zStr, azArray[i]) ) return 1;
10067 ** If compiled statement pSql appears to be an EXPLAIN statement, allocate
10068 ** and populate the ShellState.aiIndent[] array with the number of
10069 ** spaces each opcode should be indented before it is output.
10071 ** The indenting rules are:
10073 ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
10074 ** all opcodes that occur between the p2 jump destination and the opcode
10075 ** itself by 2 spaces.
10077 ** * For each "Goto", if the jump destination is earlier in the program
10078 ** and ends on one of:
10079 ** Yield SeekGt SeekLt RowSetRead Rewind
10080 ** or if the P1 parameter is one instead of zero,
10081 ** then indent all opcodes between the earlier instruction
10082 ** and "Goto" by 2 spaces.
10084 static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
10085 const char *zSql; /* The text of the SQL statement */
10086 const char *z; /* Used to check if this is an EXPLAIN */
10087 int *abYield = 0; /* True if op is an OP_Yield */
10088 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
10089 int iOp; /* Index of operation in p->aiIndent[] */
10091 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", 0 };
10092 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
10094 const char *azGoto[] = { "Goto", 0 };
10096 /* Try to figure out if this is really an EXPLAIN statement. If this
10097 ** cannot be verified, return early. */
10098 if( sqlite3_column_count(pSql)!=8 ){
10099 p->cMode = p->mode;
10102 zSql = sqlite3_sql(pSql);
10103 if( zSql==0 ) return;
10104 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
10105 if( sqlite3_strnicmp(z, "explain", 7) ){
10106 p->cMode = p->mode;
10110 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
10112 int iAddr = sqlite3_column_int(pSql, 0);
10113 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
10115 /* Set p2 to the P2 field of the current opcode. Then, assuming that
10116 ** p2 is an instruction address, set variable p2op to the index of that
10117 ** instruction in the aiIndent[] array. p2 and p2op may be different if
10118 ** the current instruction is part of a sub-program generated by an
10119 ** SQL trigger or foreign key. */
10120 int p2 = sqlite3_column_int(pSql, 3);
10121 int p2op = (p2 + (iOp-iAddr));
10123 /* Grow the p->aiIndent array as required */
10126 /* Do further verfication that this is explain output. Abort if
10128 static const char *explainCols[] = {
10129 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
10131 for(jj=0; jj<ArraySize(explainCols); jj++){
10132 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
10133 p->cMode = p->mode;
10134 sqlite3_reset(pSql);
10140 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
10141 if( p->aiIndent==0 ) shell_out_of_memory();
10142 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
10143 if( abYield==0 ) shell_out_of_memory();
10145 abYield[iOp] = str_in_array(zOp, azYield);
10146 p->aiIndent[iOp] = 0;
10147 p->nIndent = iOp+1;
10149 if( str_in_array(zOp, azNext) ){
10150 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
10152 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
10153 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
10155 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
10160 sqlite3_free(abYield);
10161 sqlite3_reset(pSql);
10165 ** Free the array allocated by explain_data_prepare().
10167 static void explain_data_delete(ShellState *p){
10168 sqlite3_free(p->aiIndent);
10175 ** Disable and restore .wheretrace and .selecttrace settings.
10177 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10178 extern int sqlite3SelectTrace;
10179 static int savedSelectTrace;
10181 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10182 extern int sqlite3WhereTrace;
10183 static int savedWhereTrace;
10185 static void disable_debug_trace_modes(void){
10186 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10187 savedSelectTrace = sqlite3SelectTrace;
10188 sqlite3SelectTrace = 0;
10190 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10191 savedWhereTrace = sqlite3WhereTrace;
10192 sqlite3WhereTrace = 0;
10195 static void restore_debug_trace_modes(void){
10196 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
10197 sqlite3SelectTrace = savedSelectTrace;
10199 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
10200 sqlite3WhereTrace = savedWhereTrace;
10205 ** Run a prepared statement
10207 static void exec_prepared_stmt(
10208 ShellState *pArg, /* Pointer to ShellState */
10209 sqlite3_stmt *pStmt /* Statment to run */
10213 /* perform the first step. this will tell us if we
10214 ** have a result set or not and how wide it is.
10216 rc = sqlite3_step(pStmt);
10217 /* if we have a result set... */
10218 if( SQLITE_ROW == rc ){
10219 /* allocate space for col name ptr, value ptr, and type */
10220 int nCol = sqlite3_column_count(pStmt);
10221 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
10225 char **azCols = (char **)pData; /* Names of result columns */
10226 char **azVals = &azCols[nCol]; /* Results */
10227 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
10229 assert(sizeof(int) <= sizeof(char *));
10230 /* save off ptrs to column names */
10231 for(i=0; i<nCol; i++){
10232 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
10235 /* extract the data and data types */
10236 for(i=0; i<nCol; i++){
10237 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
10238 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
10241 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
10243 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
10245 break; /* from for */
10249 /* if data and types extracted successfully... */
10250 if( SQLITE_ROW == rc ){
10251 /* call the supplied callback with the result row data */
10252 if( shell_callback(pArg, nCol, azVals, azCols, aiTypes) ){
10255 rc = sqlite3_step(pStmt);
10258 } while( SQLITE_ROW == rc );
10259 sqlite3_free(pData);
10264 #ifndef SQLITE_OMIT_VIRTUALTABLE
10266 ** This function is called to process SQL if the previous shell command
10267 ** was ".expert". It passes the SQL in the second argument directly to
10268 ** the sqlite3expert object.
10270 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
10271 ** code. In this case, (*pzErr) may be set to point to a buffer containing
10272 ** an English language error message. It is the responsibility of the
10273 ** caller to eventually free this buffer using sqlite3_free().
10275 static int expertHandleSQL(
10276 ShellState *pState,
10280 assert( pState->expert.pExpert );
10281 assert( pzErr==0 || *pzErr==0 );
10282 return sqlite3_expert_sql(pState->expert.pExpert, zSql, pzErr);
10286 ** This function is called either to silently clean up the object
10287 ** created by the ".expert" command (if bCancel==1), or to generate a
10288 ** report from it and then clean it up (if bCancel==0).
10290 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error
10291 ** code. In this case, (*pzErr) may be set to point to a buffer containing
10292 ** an English language error message. It is the responsibility of the
10293 ** caller to eventually free this buffer using sqlite3_free().
10295 static int expertFinish(
10296 ShellState *pState,
10300 int rc = SQLITE_OK;
10301 sqlite3expert *p = pState->expert.pExpert;
10303 assert( bCancel || pzErr==0 || *pzErr==0 );
10305 FILE *out = pState->out;
10306 int bVerbose = pState->expert.bVerbose;
10308 rc = sqlite3_expert_analyze(p, pzErr);
10309 if( rc==SQLITE_OK ){
10310 int nQuery = sqlite3_expert_count(p);
10314 const char *zCand = sqlite3_expert_report(p,0,EXPERT_REPORT_CANDIDATES);
10315 raw_printf(out, "-- Candidates -----------------------------\n");
10316 raw_printf(out, "%s\n", zCand);
10318 for(i=0; i<nQuery; i++){
10319 const char *zSql = sqlite3_expert_report(p, i, EXPERT_REPORT_SQL);
10320 const char *zIdx = sqlite3_expert_report(p, i, EXPERT_REPORT_INDEXES);
10321 const char *zEQP = sqlite3_expert_report(p, i, EXPERT_REPORT_PLAN);
10322 if( zIdx==0 ) zIdx = "(no new indexes)\n";
10324 raw_printf(out, "-- Query %d --------------------------------\n",i+1);
10325 raw_printf(out, "%s\n\n", zSql);
10327 raw_printf(out, "%s\n", zIdx);
10328 raw_printf(out, "%s\n", zEQP);
10332 sqlite3_expert_destroy(p);
10333 pState->expert.pExpert = 0;
10338 ** Implementation of ".expert" dot command.
10340 static int expertDotCommand(
10341 ShellState *pState, /* Current shell tool state */
10342 char **azArg, /* Array of arguments passed to dot command */
10343 int nArg /* Number of entries in azArg[] */
10345 int rc = SQLITE_OK;
10350 assert( pState->expert.pExpert==0 );
10351 memset(&pState->expert, 0, sizeof(ExpertInfo));
10353 for(i=1; rc==SQLITE_OK && i<nArg; i++){
10354 char *z = azArg[i];
10356 if( z[0]=='-' && z[1]=='-' ) z++;
10358 if( n>=2 && 0==strncmp(z, "-verbose", n) ){
10359 pState->expert.bVerbose = 1;
10361 else if( n>=2 && 0==strncmp(z, "-sample", n) ){
10363 raw_printf(stderr, "option requires an argument: %s\n", z);
10366 iSample = (int)integerValue(azArg[++i]);
10367 if( iSample<0 || iSample>100 ){
10368 raw_printf(stderr, "value out of range: %s\n", azArg[i]);
10374 raw_printf(stderr, "unknown option: %s\n", z);
10379 if( rc==SQLITE_OK ){
10380 pState->expert.pExpert = sqlite3_expert_new(pState->db, &zErr);
10381 if( pState->expert.pExpert==0 ){
10382 raw_printf(stderr, "sqlite3_expert_new: %s\n", zErr);
10385 sqlite3_expert_config(
10386 pState->expert.pExpert, EXPERT_CONFIG_SAMPLE, iSample
10393 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
10396 ** Execute a statement or set of statements. Print
10397 ** any result rows/columns depending on the current mode
10398 ** set via the supplied callback.
10400 ** This is very similar to SQLite's built-in sqlite3_exec()
10401 ** function except it takes a slightly different callback
10402 ** and callback data argument.
10404 static int shell_exec(
10405 ShellState *pArg, /* Pointer to ShellState */
10406 const char *zSql, /* SQL to be evaluated */
10407 char **pzErrMsg /* Error msg written here */
10409 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
10410 int rc = SQLITE_OK; /* Return Code */
10412 const char *zLeftover; /* Tail of unprocessed SQL */
10413 sqlite3 *db = pArg->db;
10419 #ifndef SQLITE_OMIT_VIRTUALTABLE
10420 if( pArg->expert.pExpert ){
10421 rc = expertHandleSQL(pArg, zSql, pzErrMsg);
10422 return expertFinish(pArg, (rc!=SQLITE_OK), pzErrMsg);
10426 while( zSql[0] && (SQLITE_OK == rc) ){
10427 static const char *zStmtSql;
10428 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
10429 if( SQLITE_OK != rc ){
10431 *pzErrMsg = save_err_msg(db);
10435 /* this happens for a comment or white-space */
10437 while( IsSpace(zSql[0]) ) zSql++;
10440 zStmtSql = sqlite3_sql(pStmt);
10441 if( zStmtSql==0 ) zStmtSql = "";
10442 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
10444 /* save off the prepared statment handle and reset row count */
10446 pArg->pStmt = pStmt;
10450 /* echo the sql statement if echo on */
10451 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
10452 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
10455 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
10456 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
10457 sqlite3_stmt *pExplain;
10459 int triggerEQP = 0;
10460 disable_debug_trace_modes();
10461 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, -1, &triggerEQP);
10462 if( pArg->autoEQP>=AUTOEQP_trigger ){
10463 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 1, 0);
10465 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
10466 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
10467 if( rc==SQLITE_OK ){
10468 while( sqlite3_step(pExplain)==SQLITE_ROW ){
10469 const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
10470 int iEqpId = sqlite3_column_int(pExplain, 0);
10471 int iParentId = sqlite3_column_int(pExplain, 1);
10472 if( zEQPLine[0]=='-' ) eqp_render(pArg);
10473 eqp_append(pArg, iEqpId, iParentId, zEQPLine);
10477 sqlite3_finalize(pExplain);
10478 sqlite3_free(zEQP);
10479 if( pArg->autoEQP>=AUTOEQP_full ){
10480 /* Also do an EXPLAIN for ".eqp full" mode */
10481 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
10482 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
10483 if( rc==SQLITE_OK ){
10484 pArg->cMode = MODE_Explain;
10485 explain_data_prepare(pArg, pExplain);
10486 exec_prepared_stmt(pArg, pExplain);
10487 explain_data_delete(pArg);
10489 sqlite3_finalize(pExplain);
10490 sqlite3_free(zEQP);
10492 if( pArg->autoEQP>=AUTOEQP_trigger && triggerEQP==0 ){
10493 sqlite3_db_config(db, SQLITE_DBCONFIG_TRIGGER_EQP, 0, 0);
10494 /* Reprepare pStmt before reactiving trace modes */
10495 sqlite3_finalize(pStmt);
10496 sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
10497 if( pArg ) pArg->pStmt = pStmt;
10499 restore_debug_trace_modes();
10503 pArg->cMode = pArg->mode;
10504 if( pArg->autoExplain ){
10505 if( sqlite3_column_count(pStmt)==8
10506 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
10508 pArg->cMode = MODE_Explain;
10510 if( sqlite3_column_count(pStmt)==4
10511 && sqlite3_strlike("EXPLAIN QUERY PLAN%", zStmtSql,0)==0 ){
10512 pArg->cMode = MODE_EQP;
10516 /* If the shell is currently in ".explain" mode, gather the extra
10517 ** data required to add indents to the output.*/
10518 if( pArg->cMode==MODE_Explain ){
10519 explain_data_prepare(pArg, pStmt);
10523 exec_prepared_stmt(pArg, pStmt);
10524 explain_data_delete(pArg);
10527 /* print usage stats if stats on */
10528 if( pArg && pArg->statsOn ){
10529 display_stats(db, pArg, 0);
10532 /* print loop-counters if required */
10533 if( pArg && pArg->scanstatsOn ){
10534 display_scanstats(db, pArg);
10537 /* Finalize the statement just executed. If this fails, save a
10538 ** copy of the error message. Otherwise, set zSql to point to the
10539 ** next statement to execute. */
10540 rc2 = sqlite3_finalize(pStmt);
10541 if( rc!=SQLITE_NOMEM ) rc = rc2;
10542 if( rc==SQLITE_OK ){
10544 while( IsSpace(zSql[0]) ) zSql++;
10545 }else if( pzErrMsg ){
10546 *pzErrMsg = save_err_msg(db);
10549 /* clear saved stmt handle */
10551 pArg->pStmt = NULL;
10560 ** Release memory previously allocated by tableColumnList().
10562 static void freeColumnList(char **azCol){
10564 for(i=1; azCol[i]; i++){
10565 sqlite3_free(azCol[i]);
10567 /* azCol[0] is a static string */
10568 sqlite3_free(azCol);
10572 ** Return a list of pointers to strings which are the names of all
10573 ** columns in table zTab. The memory to hold the names is dynamically
10574 ** allocated and must be released by the caller using a subsequent call
10575 ** to freeColumnList().
10577 ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
10578 ** value that needs to be preserved, then azCol[0] is filled in with the
10579 ** name of the rowid column.
10581 ** The first regular column in the table is azCol[1]. The list is terminated
10582 ** by an entry with azCol[i]==0.
10584 static char **tableColumnList(ShellState *p, const char *zTab){
10586 sqlite3_stmt *pStmt;
10590 int nPK = 0; /* Number of PRIMARY KEY columns seen */
10591 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
10592 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
10595 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
10596 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10597 sqlite3_free(zSql);
10599 while( sqlite3_step(pStmt)==SQLITE_ROW ){
10600 if( nCol>=nAlloc-2 ){
10601 nAlloc = nAlloc*2 + nCol + 10;
10602 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
10603 if( azCol==0 ) shell_out_of_memory();
10605 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
10606 if( sqlite3_column_int(pStmt, 5) ){
10609 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
10618 sqlite3_finalize(pStmt);
10619 if( azCol==0 ) return 0;
10623 /* The decision of whether or not a rowid really needs to be preserved
10624 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
10625 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
10626 ** rowids on tables where the rowid is inaccessible because there are other
10627 ** columns in the table named "rowid", "_rowid_", and "oid".
10629 if( preserveRowid && isIPK ){
10630 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
10631 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
10632 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
10633 ** ROWID aliases. To distinguish these cases, check to see if
10634 ** there is a "pk" entry in "PRAGMA index_list". There will be
10635 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
10637 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
10638 " WHERE origin='pk'", zTab);
10639 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
10640 sqlite3_free(zSql);
10642 freeColumnList(azCol);
10645 rc = sqlite3_step(pStmt);
10646 sqlite3_finalize(pStmt);
10647 preserveRowid = rc==SQLITE_ROW;
10649 if( preserveRowid ){
10650 /* Only preserve the rowid if we can find a name to use for the
10652 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
10654 for(j=0; j<3; j++){
10655 for(i=1; i<=nCol; i++){
10656 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
10659 /* At this point, we know that azRowid[j] is not the name of any
10660 ** ordinary column in the table. Verify that azRowid[j] is a valid
10661 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
10662 ** tables will fail this last check */
10663 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
10664 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
10673 ** Toggle the reverse_unordered_selects setting.
10675 static void toggleSelectOrder(sqlite3 *db){
10676 sqlite3_stmt *pStmt = 0;
10679 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
10680 if( sqlite3_step(pStmt)==SQLITE_ROW ){
10681 iSetting = sqlite3_column_int(pStmt, 0);
10683 sqlite3_finalize(pStmt);
10684 sqlite3_snprintf(sizeof(zStmt), zStmt,
10685 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
10686 sqlite3_exec(db, zStmt, 0, 0, 0);
10690 ** This is a different callback routine used for dumping the database.
10691 ** Each row received by this callback consists of a table name,
10692 ** the table type ("index" or "table") and SQL to create the table.
10693 ** This routine should print text sufficient to recreate the table.
10695 static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
10697 const char *zTable;
10700 ShellState *p = (ShellState *)pArg;
10702 UNUSED_PARAMETER(azNotUsed);
10703 if( nArg!=3 || azArg==0 ) return 0;
10708 if( strcmp(zTable, "sqlite_sequence")==0 ){
10709 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
10710 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
10711 raw_printf(p->out, "ANALYZE sqlite_master;\n");
10712 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
10714 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
10716 if( !p->writableSchema ){
10717 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
10718 p->writableSchema = 1;
10720 zIns = sqlite3_mprintf(
10721 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
10722 "VALUES('table','%q','%q',0,'%q');",
10723 zTable, zTable, zSql);
10724 utf8_printf(p->out, "%s\n", zIns);
10725 sqlite3_free(zIns);
10728 printSchemaLine(p->out, zSql, ";\n");
10731 if( strcmp(zType, "table")==0 ){
10736 char *savedDestTable;
10739 azCol = tableColumnList(p, zTable);
10745 /* Always quote the table name, even if it appears to be pure ascii,
10746 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
10748 appendText(&sTable, zTable, quoteChar(zTable));
10749 /* If preserving the rowid, add a column list after the table name.
10750 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
10751 ** instead of the usual "INSERT INTO tab VALUES(...)".
10754 appendText(&sTable, "(", 0);
10755 appendText(&sTable, azCol[0], 0);
10756 for(i=1; azCol[i]; i++){
10757 appendText(&sTable, ",", 0);
10758 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
10760 appendText(&sTable, ")", 0);
10763 /* Build an appropriate SELECT statement */
10764 initText(&sSelect);
10765 appendText(&sSelect, "SELECT ", 0);
10767 appendText(&sSelect, azCol[0], 0);
10768 appendText(&sSelect, ",", 0);
10770 for(i=1; azCol[i]; i++){
10771 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
10773 appendText(&sSelect, ",", 0);
10776 freeColumnList(azCol);
10777 appendText(&sSelect, " FROM ", 0);
10778 appendText(&sSelect, zTable, quoteChar(zTable));
10780 savedDestTable = p->zDestTable;
10781 savedMode = p->mode;
10782 p->zDestTable = sTable.z;
10783 p->mode = p->cMode = MODE_Insert;
10784 rc = shell_exec(p, sSelect.z, 0);
10785 if( (rc&0xff)==SQLITE_CORRUPT ){
10786 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
10787 toggleSelectOrder(p->db);
10788 shell_exec(p, sSelect.z, 0);
10789 toggleSelectOrder(p->db);
10791 p->zDestTable = savedDestTable;
10792 p->mode = savedMode;
10794 freeText(&sSelect);
10795 if( rc ) p->nErr++;
10801 ** Run zQuery. Use dump_callback() as the callback routine so that
10802 ** the contents of the query are output as SQL statements.
10804 ** If we get a SQLITE_CORRUPT error, rerun the query after appending
10805 ** "ORDER BY rowid DESC" to the end.
10807 static int run_schema_dump_query(
10813 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
10814 if( rc==SQLITE_CORRUPT ){
10816 int len = strlen30(zQuery);
10817 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
10819 utf8_printf(p->out, "/****** %s ******/\n", zErr);
10820 sqlite3_free(zErr);
10823 zQ2 = malloc( len+100 );
10824 if( zQ2==0 ) return rc;
10825 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
10826 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
10828 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
10830 rc = SQLITE_CORRUPT;
10832 sqlite3_free(zErr);
10839 ** Text of a help message
10841 static char zHelp[] =
10842 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
10843 ".archive ... Manage SQL archives: \".archive --help\" for details\n"
10845 #ifndef SQLITE_OMIT_AUTHORIZATION
10846 ".auth ON|OFF Show authorizer callbacks\n"
10848 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
10849 " Add \"--append\" to open using appendvfs.\n"
10850 ".bail on|off Stop after hitting an error. Default OFF\n"
10851 ".binary on|off Turn binary output on or off. Default OFF\n"
10852 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
10853 ".changes on|off Show number of rows changed by SQL\n"
10854 ".check GLOB Fail if output since .testcase does not match\n"
10855 ".clone NEWDB Clone data into NEWDB from the existing database\n"
10856 ".databases List names and files of attached databases\n"
10857 ".dbconfig ?op? ?val? List or change sqlite3_db_config() options\n"
10858 ".dbinfo ?DB? Show status information about the database\n"
10859 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
10860 " If TABLE specified, only dump tables matching\n"
10861 " LIKE pattern TABLE.\n"
10862 ".echo on|off Turn command echo on or off\n"
10863 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
10864 ".excel Display the output of next command in a spreadsheet\n"
10865 ".exit Exit this program\n"
10866 ".expert EXPERIMENTAL. Suggest indexes for specified queries\n"
10867 /* Because explain mode comes on automatically now, the ".explain" mode
10868 ** is removed from the help screen. It is still supported for legacy, however */
10869 /*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
10870 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
10871 ".headers on|off Turn display of headers on or off\n"
10872 ".help Show this message\n"
10873 ".import FILE TABLE Import data from FILE into TABLE\n"
10874 #ifndef SQLITE_OMIT_TEST_CONTROL
10875 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
10877 ".indexes ?TABLE? Show names of all indexes\n"
10878 " If TABLE specified, only show indexes for tables\n"
10879 " matching LIKE pattern TABLE.\n"
10880 #ifdef SQLITE_ENABLE_IOTRACE
10881 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
10883 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
10884 ".lint OPTIONS Report potential schema issues. Options:\n"
10885 " fkey-indexes Find missing foreign key indexes\n"
10886 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10887 ".load FILE ?ENTRY? Load an extension library\n"
10889 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
10890 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
10891 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
10892 " csv Comma-separated values\n"
10893 " column Left-aligned columns. (See .width)\n"
10894 " html HTML <table> code\n"
10895 " insert SQL insert statements for TABLE\n"
10896 " line One value per line\n"
10897 " list Values delimited by \"|\"\n"
10898 " quote Escape answers as for SQL\n"
10899 " tabs Tab-separated values\n"
10900 " tcl TCL list elements\n"
10901 ".nullvalue STRING Use STRING in place of NULL values\n"
10902 ".once (-e|-x|FILE) Output for the next SQL command only to FILE\n"
10903 " or invoke system text editor (-e) or spreadsheet (-x)\n"
10904 " on the output.\n"
10905 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
10906 " The --new option starts with an empty file\n"
10907 " Other options: --readonly --append --zip\n"
10908 ".output ?FILE? Send output to FILE or stdout\n"
10909 ".print STRING... Print literal STRING\n"
10910 ".prompt MAIN CONTINUE Replace the standard prompts\n"
10911 ".quit Exit this program\n"
10912 ".read FILENAME Execute SQL in FILENAME\n"
10913 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
10914 ".save FILE Write in-memory database into FILE\n"
10915 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
10916 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
10917 " Add --indent for pretty-printing\n"
10918 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
10919 ".separator COL ?ROW? Change the column separator and optionally the row\n"
10920 " separator for both the output mode and .import\n"
10921 #if defined(SQLITE_ENABLE_SESSION)
10922 ".session CMD ... Create or control sessions\n"
10924 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
10925 #ifndef SQLITE_NOHAVE_SYSTEM
10926 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
10928 ".show Show the current values for various settings\n"
10929 ".stats ?on|off? Show stats or turn stats on or off\n"
10930 #ifndef SQLITE_NOHAVE_SYSTEM
10931 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
10933 ".tables ?TABLE? List names of tables\n"
10934 " If TABLE specified, only list tables matching\n"
10935 " LIKE pattern TABLE.\n"
10936 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
10937 ".timeout MS Try opening locked tables for MS milliseconds\n"
10938 ".timer on|off Turn SQL timer on or off\n"
10939 ".trace FILE|off Output each SQL statement as it is run\n"
10940 ".vfsinfo ?AUX? Information about the top-level VFS\n"
10941 ".vfslist List all available VFSes\n"
10942 ".vfsname ?AUX? Print the name of the VFS stack\n"
10943 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
10944 " Negative values right-justify\n"
10947 #if defined(SQLITE_ENABLE_SESSION)
10949 ** Print help information for the ".sessions" command
10951 void session_help(ShellState *p){
10953 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
10954 "If ?NAME? is omitted, the first defined session is used.\n"
10956 " attach TABLE Attach TABLE\n"
10957 " changeset FILE Write a changeset into FILE\n"
10958 " close Close one session\n"
10959 " enable ?BOOLEAN? Set or query the enable bit\n"
10960 " filter GLOB... Reject tables matching GLOBs\n"
10961 " indirect ?BOOLEAN? Mark or query the indirect status\n"
10962 " isempty Query whether the session is empty\n"
10963 " list List currently open session names\n"
10964 " open DB NAME Open a new session on DB\n"
10965 " patchset FILE Write a patchset into FILE\n"
10971 /* Forward reference */
10972 static int process_input(ShellState *p, FILE *in);
10975 ** Read the content of file zName into memory obtained from sqlite3_malloc64()
10976 ** and return a pointer to the buffer. The caller is responsible for freeing
10979 ** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
10982 ** For convenience, a nul-terminator byte is always appended to the data read
10983 ** from the file before the buffer is returned. This byte is not included in
10984 ** the final value of (*pnByte), if applicable.
10986 ** NULL is returned if any error is encountered. The final value of *pnByte
10987 ** is undefined in this case.
10989 static char *readFile(const char *zName, int *pnByte){
10990 FILE *in = fopen(zName, "rb");
10994 if( in==0 ) return 0;
10995 fseek(in, 0, SEEK_END);
10998 pBuf = sqlite3_malloc64( nIn+1 );
10999 if( pBuf==0 ) return 0;
11000 nRead = fread(pBuf, nIn, 1, in);
11003 sqlite3_free(pBuf);
11007 if( pnByte ) *pnByte = nIn;
11011 #if defined(SQLITE_ENABLE_SESSION)
11013 ** Close a single OpenSession object and release all of its associated
11016 static void session_close(OpenSession *pSession){
11018 sqlite3session_delete(pSession->p);
11019 sqlite3_free(pSession->zName);
11020 for(i=0; i<pSession->nFilter; i++){
11021 sqlite3_free(pSession->azFilter[i]);
11023 sqlite3_free(pSession->azFilter);
11024 memset(pSession, 0, sizeof(OpenSession));
11029 ** Close all OpenSession objects and release all associated resources.
11031 #if defined(SQLITE_ENABLE_SESSION)
11032 static void session_close_all(ShellState *p){
11034 for(i=0; i<p->nSession; i++){
11035 session_close(&p->aSession[i]);
11040 # define session_close_all(X)
11044 ** Implementation of the xFilter function for an open session. Omit
11045 ** any tables named by ".session filter" but let all other table through.
11047 #if defined(SQLITE_ENABLE_SESSION)
11048 static int session_filter(void *pCtx, const char *zTab){
11049 OpenSession *pSession = (OpenSession*)pCtx;
11051 for(i=0; i<pSession->nFilter; i++){
11052 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
11059 ** Try to deduce the type of file for zName based on its content. Return
11060 ** one of the SHELL_OPEN_* constants.
11062 ** If the file does not exist or is empty but its name looks like a ZIP
11063 ** archive and the dfltZip flag is true, then assume it is a ZIP archive.
11064 ** Otherwise, assume an ordinary database regardless of the filename if
11065 ** the type cannot be determined from content.
11067 int deduceDatabaseType(const char *zName, int dfltZip){
11068 FILE *f = fopen(zName, "rb");
11070 int rc = SHELL_OPEN_UNSPEC;
11073 if( dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
11074 return SHELL_OPEN_ZIPFILE;
11076 return SHELL_OPEN_NORMAL;
11079 fseek(f, -25, SEEK_END);
11080 n = fread(zBuf, 25, 1, f);
11081 if( n==1 && memcmp(zBuf, "Start-Of-SQLite3-", 17)==0 ){
11082 rc = SHELL_OPEN_APPENDVFS;
11084 fseek(f, -22, SEEK_END);
11085 n = fread(zBuf, 22, 1, f);
11086 if( n==1 && zBuf[0]==0x50 && zBuf[1]==0x4b && zBuf[2]==0x05
11087 && zBuf[3]==0x06 ){
11088 rc = SHELL_OPEN_ZIPFILE;
11089 }else if( n==0 && dfltZip && sqlite3_strlike("%.zip",zName,0)==0 ){
11090 rc = SHELL_OPEN_ZIPFILE;
11097 /* Flags for open_db().
11099 ** The default behavior of open_db() is to exit(1) if the database fails to
11100 ** open. The OPEN_DB_KEEPALIVE flag changes that so that it prints an error
11101 ** but still returns without calling exit.
11103 ** The OPEN_DB_ZIPFILE flag causes open_db() to prefer to open files as a
11104 ** ZIP archive if the file does not exist or is empty and its name matches
11105 ** the *.zip pattern.
11107 #define OPEN_DB_KEEPALIVE 0x001 /* Return after error if true */
11108 #define OPEN_DB_ZIPFILE 0x002 /* Open as ZIP if name matches *.zip */
11111 ** Make sure the database is open. If it is not, then open it. If
11112 ** the database fails to open, print an error message and exit.
11114 static void open_db(ShellState *p, int openFlags){
11116 if( p->openMode==SHELL_OPEN_UNSPEC ){
11117 if( p->zDbFilename==0 || p->zDbFilename[0]==0 ){
11118 p->openMode = SHELL_OPEN_NORMAL;
11120 p->openMode = (u8)deduceDatabaseType(p->zDbFilename,
11121 (openFlags & OPEN_DB_ZIPFILE)!=0);
11124 switch( p->openMode ){
11125 case SHELL_OPEN_APPENDVFS: {
11126 sqlite3_open_v2(p->zDbFilename, &p->db,
11127 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
11130 case SHELL_OPEN_ZIPFILE: {
11131 sqlite3_open(":memory:", &p->db);
11134 case SHELL_OPEN_READONLY: {
11135 sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
11138 case SHELL_OPEN_UNSPEC:
11139 case SHELL_OPEN_NORMAL: {
11140 sqlite3_open(p->zDbFilename, &p->db);
11145 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
11146 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
11147 p->zDbFilename, sqlite3_errmsg(p->db));
11148 if( openFlags & OPEN_DB_KEEPALIVE ) return;
11151 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11152 sqlite3_enable_load_extension(p->db, 1);
11154 sqlite3_fileio_init(p->db, 0, 0);
11155 sqlite3_shathree_init(p->db, 0, 0);
11156 sqlite3_completion_init(p->db, 0, 0);
11157 #ifdef SQLITE_HAVE_ZLIB
11158 sqlite3_zipfile_init(p->db, 0, 0);
11159 sqlite3_sqlar_init(p->db, 0, 0);
11161 sqlite3_create_function(p->db, "shell_add_schema", 3, SQLITE_UTF8, 0,
11162 shellAddSchemaName, 0, 0);
11163 sqlite3_create_function(p->db, "shell_module_schema", 1, SQLITE_UTF8, 0,
11164 shellModuleSchema, 0, 0);
11165 sqlite3_create_function(p->db, "shell_putsnl", 1, SQLITE_UTF8, p,
11166 shellPutsFunc, 0, 0);
11167 #ifndef SQLITE_NOHAVE_SYSTEM
11168 sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
11170 sqlite3_create_function(p->db, "edit", 2, SQLITE_UTF8, 0,
11173 if( p->openMode==SHELL_OPEN_ZIPFILE ){
11174 char *zSql = sqlite3_mprintf(
11175 "CREATE VIRTUAL TABLE zip USING zipfile(%Q);", p->zDbFilename);
11176 sqlite3_exec(p->db, zSql, 0, 0, 0);
11177 sqlite3_free(zSql);
11183 ** Attempt to close the databaes connection. Report errors.
11185 void close_db(sqlite3 *db){
11186 int rc = sqlite3_close(db);
11188 utf8_printf(stderr, "Error: sqlite3_close() returns %d: %s\n",
11189 rc, sqlite3_errmsg(db));
11193 #if HAVE_READLINE || HAVE_EDITLINE
11195 ** Readline completion callbacks
11197 static char *readline_completion_generator(const char *text, int state){
11198 static sqlite3_stmt *pStmt = 0;
11202 sqlite3_finalize(pStmt);
11203 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
11204 " FROM completion(%Q) ORDER BY 1", text);
11205 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
11206 sqlite3_free(zSql);
11208 if( sqlite3_step(pStmt)==SQLITE_ROW ){
11209 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
11211 sqlite3_finalize(pStmt);
11217 static char **readline_completion(const char *zText, int iStart, int iEnd){
11218 rl_attempted_completion_over = 1;
11219 return rl_completion_matches(zText, readline_completion_generator);
11222 #elif HAVE_LINENOISE
11224 ** Linenoise completion callback
11226 static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
11227 int nLine = strlen30(zLine);
11229 sqlite3_stmt *pStmt = 0;
11233 if( nLine>sizeof(zBuf)-30 ) return;
11234 if( zLine[0]=='.' || zLine[0]=='#') return;
11235 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
11236 if( i==nLine-1 ) return;
11238 memcpy(zBuf, zLine, iStart);
11239 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
11240 " FROM completion(%Q,%Q) ORDER BY 1",
11241 &zLine[iStart], zLine);
11242 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
11243 sqlite3_free(zSql);
11244 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
11245 while( sqlite3_step(pStmt)==SQLITE_ROW ){
11246 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
11247 int nCompletion = sqlite3_column_bytes(pStmt, 0);
11248 if( iStart+nCompletion < sizeof(zBuf)-1 ){
11249 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
11250 linenoiseAddCompletion(lc, zBuf);
11253 sqlite3_finalize(pStmt);
11258 ** Do C-language style dequoting.
11264 ** \v -> vertical tab
11266 ** \r -> carriage return
11271 ** \NNN -> ascii character NNN in octal
11273 static void resolve_backslashes(char *z){
11276 while( *z && *z!='\\' ) z++;
11277 for(i=j=0; (c = z[i])!=0; i++, j++){
11278 if( c=='\\' && z[i+1]!=0 ){
11282 }else if( c=='b' ){
11284 }else if( c=='t' ){
11286 }else if( c=='n' ){
11288 }else if( c=='v' ){
11290 }else if( c=='f' ){
11292 }else if( c=='r' ){
11294 }else if( c=='"' ){
11296 }else if( c=='\'' ){
11298 }else if( c=='\\' ){
11300 }else if( c>='0' && c<='7' ){
11302 if( z[i+1]>='0' && z[i+1]<='7' ){
11304 c = (c<<3) + z[i] - '0';
11305 if( z[i+1]>='0' && z[i+1]<='7' ){
11307 c = (c<<3) + z[i] - '0';
11314 if( j<i ) z[j] = 0;
11318 ** Interpret zArg as either an integer or a boolean value. Return 1 or 0
11319 ** for TRUE and FALSE. Return the integer value if appropriate.
11321 static int booleanValue(const char *zArg){
11323 if( zArg[0]=='0' && zArg[1]=='x' ){
11324 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
11326 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
11328 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
11329 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
11332 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
11335 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
11341 ** Set or clear a shell flag according to a boolean value.
11343 static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
11344 if( booleanValue(zArg) ){
11345 ShellSetFlag(p, mFlag);
11347 ShellClearFlag(p, mFlag);
11352 ** Close an output file, assuming it is not stderr or stdout
11354 static void output_file_close(FILE *f){
11355 if( f && f!=stdout && f!=stderr ) fclose(f);
11359 ** Try to open an output file. The names "stdout" and "stderr" are
11360 ** recognized and do the right thing. NULL is returned if the output
11361 ** filename is "off".
11363 static FILE *output_file_open(const char *zFile, int bTextMode){
11365 if( strcmp(zFile,"stdout")==0 ){
11367 }else if( strcmp(zFile, "stderr")==0 ){
11369 }else if( strcmp(zFile, "off")==0 ){
11372 f = fopen(zFile, bTextMode ? "w" : "wb");
11374 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
11380 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
11382 ** A routine for handling output from sqlite3_trace().
11384 static int sql_trace_callback(
11390 FILE *f = (FILE*)pArg;
11391 UNUSED_PARAMETER(mType);
11392 UNUSED_PARAMETER(pP);
11394 const char *z = (const char*)pX;
11395 int i = strlen30(z);
11396 while( i>0 && z[i-1]==';' ){ i--; }
11397 utf8_printf(f, "%.*s;\n", i, z);
11404 ** A no-op routine that runs with the ".breakpoint" doc-command. This is
11405 ** a useful spot to set a debugger breakpoint.
11407 static void test_breakpoint(void){
11408 static int nCall = 0;
11413 ** An object used to read a CSV and other files for import.
11415 typedef struct ImportCtx ImportCtx;
11417 const char *zFile; /* Name of the input file */
11418 FILE *in; /* Read the CSV text from this input stream */
11419 char *z; /* Accumulated text for a field */
11420 int n; /* Number of bytes in z */
11421 int nAlloc; /* Space allocated for z[] */
11422 int nLine; /* Current line number */
11423 int bNotFirst; /* True if one or more bytes already read */
11424 int cTerm; /* Character that terminated the most recent field */
11425 int cColSep; /* The column separator character. (Usually ",") */
11426 int cRowSep; /* The row separator character. (Usually "\n") */
11429 /* Append a single byte to z[] */
11430 static void import_append_char(ImportCtx *p, int c){
11431 if( p->n+1>=p->nAlloc ){
11432 p->nAlloc += p->nAlloc + 100;
11433 p->z = sqlite3_realloc64(p->z, p->nAlloc);
11434 if( p->z==0 ) shell_out_of_memory();
11436 p->z[p->n++] = (char)c;
11439 /* Read a single field of CSV text. Compatible with rfc4180 and extended
11440 ** with the option of having a separator other than ",".
11442 ** + Input comes from p->in.
11443 ** + Store results in p->z of length p->n. Space to hold p->z comes
11444 ** from sqlite3_malloc64().
11445 ** + Use p->cSep as the column separator. The default is ",".
11446 ** + Use p->rSep as the row separator. The default is "\n".
11447 ** + Keep track of the line number in p->nLine.
11448 ** + Store the character that terminates the field in p->cTerm. Store
11449 ** EOF on end-of-file.
11450 ** + Report syntax errors on stderr
11452 static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
11454 int cSep = p->cColSep;
11455 int rSep = p->cRowSep;
11458 if( c==EOF || seenInterrupt ){
11464 int startLine = p->nLine;
11469 if( c==rSep ) p->nLine++;
11476 if( (c==cSep && pc==cQuote)
11477 || (c==rSep && pc==cQuote)
11478 || (c==rSep && pc=='\r' && ppc==cQuote)
11479 || (c==EOF && pc==cQuote)
11481 do{ p->n--; }while( p->z[p->n]!=cQuote );
11485 if( pc==cQuote && c!='\r' ){
11486 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
11487 p->zFile, p->nLine, cQuote);
11490 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
11491 p->zFile, startLine, cQuote);
11495 import_append_char(p, c);
11500 /* If this is the first field being parsed and it begins with the
11501 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
11502 if( (c&0xff)==0xef && p->bNotFirst==0 ){
11503 import_append_char(p, c);
11505 if( (c&0xff)==0xbb ){
11506 import_append_char(p, c);
11508 if( (c&0xff)==0xbf ){
11511 return csv_read_one_field(p);
11515 while( c!=EOF && c!=cSep && c!=rSep ){
11516 import_append_char(p, c);
11521 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
11525 if( p->z ) p->z[p->n] = 0;
11530 /* Read a single field of ASCII delimited text.
11532 ** + Input comes from p->in.
11533 ** + Store results in p->z of length p->n. Space to hold p->z comes
11534 ** from sqlite3_malloc64().
11535 ** + Use p->cSep as the column separator. The default is "\x1F".
11536 ** + Use p->rSep as the row separator. The default is "\x1E".
11537 ** + Keep track of the row number in p->nLine.
11538 ** + Store the character that terminates the field in p->cTerm. Store
11539 ** EOF on end-of-file.
11540 ** + Report syntax errors on stderr
11542 static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
11544 int cSep = p->cColSep;
11545 int rSep = p->cRowSep;
11548 if( c==EOF || seenInterrupt ){
11552 while( c!=EOF && c!=cSep && c!=rSep ){
11553 import_append_char(p, c);
11560 if( p->z ) p->z[p->n] = 0;
11565 ** Try to transfer data for table zTable. If an error is seen while
11566 ** moving forward, try to go backwards. The backwards movement won't
11567 ** work for WITHOUT ROWID tables.
11569 static void tryToCloneData(
11574 sqlite3_stmt *pQuery = 0;
11575 sqlite3_stmt *pInsert = 0;
11580 int nTable = strlen30(zTable);
11583 const int spinRate = 10000;
11585 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
11586 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11588 utf8_printf(stderr, "Error %d: %s on [%s]\n",
11589 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11591 goto end_data_xfer;
11593 n = sqlite3_column_count(pQuery);
11594 zInsert = sqlite3_malloc64(200 + nTable + n*3);
11595 if( zInsert==0 ) shell_out_of_memory();
11596 sqlite3_snprintf(200+nTable,zInsert,
11597 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
11598 i = strlen30(zInsert);
11599 for(j=1; j<n; j++){
11600 memcpy(zInsert+i, ",?", 2);
11603 memcpy(zInsert+i, ");", 3);
11604 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
11606 utf8_printf(stderr, "Error %d: %s on [%s]\n",
11607 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
11609 goto end_data_xfer;
11611 for(k=0; k<2; k++){
11612 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11613 for(i=0; i<n; i++){
11614 switch( sqlite3_column_type(pQuery, i) ){
11615 case SQLITE_NULL: {
11616 sqlite3_bind_null(pInsert, i+1);
11619 case SQLITE_INTEGER: {
11620 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
11623 case SQLITE_FLOAT: {
11624 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
11627 case SQLITE_TEXT: {
11628 sqlite3_bind_text(pInsert, i+1,
11629 (const char*)sqlite3_column_text(pQuery,i),
11630 -1, SQLITE_STATIC);
11633 case SQLITE_BLOB: {
11634 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
11635 sqlite3_column_bytes(pQuery,i),
11641 rc = sqlite3_step(pInsert);
11642 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
11643 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
11644 sqlite3_errmsg(newDb));
11646 sqlite3_reset(pInsert);
11648 if( (cnt%spinRate)==0 ){
11649 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
11653 if( rc==SQLITE_DONE ) break;
11654 sqlite3_finalize(pQuery);
11655 sqlite3_free(zQuery);
11656 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
11658 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11660 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
11663 } /* End for(k=0...) */
11666 sqlite3_finalize(pQuery);
11667 sqlite3_finalize(pInsert);
11668 sqlite3_free(zQuery);
11669 sqlite3_free(zInsert);
11674 ** Try to transfer all rows of the schema that match zWhere. For
11675 ** each row, invoke xForEach() on the object defined by that row.
11676 ** If an error is encountered while moving forward through the
11677 ** sqlite_master table, try again moving backwards.
11679 static void tryToCloneSchema(
11682 const char *zWhere,
11683 void (*xForEach)(ShellState*,sqlite3*,const char*)
11685 sqlite3_stmt *pQuery = 0;
11688 const unsigned char *zName;
11689 const unsigned char *zSql;
11692 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
11693 " WHERE %s", zWhere);
11694 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11696 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
11697 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11699 goto end_schema_xfer;
11701 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11702 zName = sqlite3_column_text(pQuery, 0);
11703 zSql = sqlite3_column_text(pQuery, 1);
11704 printf("%s... ", zName); fflush(stdout);
11705 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
11707 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
11708 sqlite3_free(zErrMsg);
11712 xForEach(p, newDb, (const char*)zName);
11716 if( rc!=SQLITE_DONE ){
11717 sqlite3_finalize(pQuery);
11718 sqlite3_free(zQuery);
11719 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
11720 " WHERE %s ORDER BY rowid DESC", zWhere);
11721 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
11723 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
11724 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
11726 goto end_schema_xfer;
11728 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
11729 zName = sqlite3_column_text(pQuery, 0);
11730 zSql = sqlite3_column_text(pQuery, 1);
11731 printf("%s... ", zName); fflush(stdout);
11732 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
11734 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
11735 sqlite3_free(zErrMsg);
11739 xForEach(p, newDb, (const char*)zName);
11745 sqlite3_finalize(pQuery);
11746 sqlite3_free(zQuery);
11750 ** Open a new database file named "zNewDb". Try to recover as much information
11751 ** as possible out of the main database (which might be corrupt) and write it
11754 static void tryToClone(ShellState *p, const char *zNewDb){
11756 sqlite3 *newDb = 0;
11757 if( access(zNewDb,0)==0 ){
11758 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
11761 rc = sqlite3_open(zNewDb, &newDb);
11763 utf8_printf(stderr, "Cannot create output database: %s\n",
11764 sqlite3_errmsg(newDb));
11766 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
11767 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
11768 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
11769 tryToCloneSchema(p, newDb, "type!='table'", 0);
11770 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
11771 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
11777 ** Change the output file back to stdout.
11779 ** If the p->doXdgOpen flag is set, that means the output was being
11780 ** redirected to a temporary file named by p->zTempFile. In that case,
11781 ** launch start/open/xdg-open on that temporary file.
11783 static void output_reset(ShellState *p){
11784 if( p->outfile[0]=='|' ){
11785 #ifndef SQLITE_OMIT_POPEN
11789 output_file_close(p->out);
11790 #ifndef SQLITE_NOHAVE_SYSTEM
11791 if( p->doXdgOpen ){
11792 const char *zXdgOpenCmd =
11793 #if defined(_WIN32)
11795 #elif defined(__APPLE__)
11801 zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
11802 if( system(zCmd) ){
11803 utf8_printf(stderr, "Failed: [%s]\n", zCmd);
11805 sqlite3_free(zCmd);
11809 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
11816 ** Run an SQL command and return the single integer result.
11818 static int db_int(ShellState *p, const char *zSql){
11819 sqlite3_stmt *pStmt;
11821 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
11822 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
11823 res = sqlite3_column_int(pStmt,0);
11825 sqlite3_finalize(pStmt);
11830 ** Convert a 2-byte or 4-byte big-endian integer into a native integer
11832 static unsigned int get2byteInt(unsigned char *a){
11833 return (a[0]<<8) + a[1];
11835 static unsigned int get4byteInt(unsigned char *a){
11836 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
11840 ** Implementation of the ".info" command.
11842 ** Return 1 on error, 2 to exit, and 0 otherwise.
11844 static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
11845 static const struct { const char *zName; int ofst; } aField[] = {
11846 { "file change counter:", 24 },
11847 { "database page count:", 28 },
11848 { "freelist page count:", 36 },
11849 { "schema cookie:", 40 },
11850 { "schema format:", 44 },
11851 { "default cache size:", 48 },
11852 { "autovacuum top root:", 52 },
11853 { "incremental vacuum:", 64 },
11854 { "text encoding:", 56 },
11855 { "user version:", 60 },
11856 { "application id:", 68 },
11857 { "software version:", 96 },
11859 static const struct { const char *zName; const char *zSql; } aQuery[] = {
11860 { "number of tables:",
11861 "SELECT count(*) FROM %s WHERE type='table'" },
11862 { "number of indexes:",
11863 "SELECT count(*) FROM %s WHERE type='index'" },
11864 { "number of triggers:",
11865 "SELECT count(*) FROM %s WHERE type='trigger'" },
11866 { "number of views:",
11867 "SELECT count(*) FROM %s WHERE type='view'" },
11869 "SELECT total(length(sql)) FROM %s" },
11872 unsigned iDataVersion;
11874 char *zDb = nArg>=2 ? azArg[1] : "main";
11875 sqlite3_stmt *pStmt = 0;
11876 unsigned char aHdr[100];
11878 if( p->db==0 ) return 1;
11879 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
11881 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
11882 if( sqlite3_step(pStmt)==SQLITE_ROW
11883 && sqlite3_column_bytes(pStmt,0)>100
11885 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
11886 sqlite3_finalize(pStmt);
11888 raw_printf(stderr, "unable to read database header\n");
11889 sqlite3_finalize(pStmt);
11892 i = get2byteInt(aHdr+16);
11893 if( i==1 ) i = 65536;
11894 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
11895 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
11896 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
11897 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
11898 for(i=0; i<ArraySize(aField); i++){
11899 int ofst = aField[i].ofst;
11900 unsigned int val = get4byteInt(aHdr + ofst);
11901 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
11904 if( val==1 ) raw_printf(p->out, " (utf8)");
11905 if( val==2 ) raw_printf(p->out, " (utf16le)");
11906 if( val==3 ) raw_printf(p->out, " (utf16be)");
11909 raw_printf(p->out, "\n");
11912 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
11913 }else if( strcmp(zDb,"temp")==0 ){
11914 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
11916 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
11918 for(i=0; i<ArraySize(aQuery); i++){
11919 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
11920 int val = db_int(p, zSql);
11921 sqlite3_free(zSql);
11922 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
11924 sqlite3_free(zSchemaTab);
11925 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_DATA_VERSION, &iDataVersion);
11926 utf8_printf(p->out, "%-20s %u\n", "data version", iDataVersion);
11931 ** Print the current sqlite3_errmsg() value to stderr and return 1.
11933 static int shellDatabaseError(sqlite3 *db){
11934 const char *zErr = sqlite3_errmsg(db);
11935 utf8_printf(stderr, "Error: %s\n", zErr);
11940 ** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
11941 ** if they match and FALSE (0) if they do not match.
11945 ** '*' Matches any sequence of zero or more characters.
11947 ** '?' Matches exactly one character.
11949 ** [...] Matches one character from the enclosed list of
11952 ** [^...] Matches one character not in the enclosed list.
11954 ** '#' Matches any sequence of one or more digits with an
11955 ** optional + or - sign in front
11957 ** ' ' Any span of whitespace matches any other span of
11960 ** Extra whitespace at the end of z[] is ignored.
11962 static int testcase_glob(const char *zGlob, const char *z){
11967 while( (c = (*(zGlob++)))!=0 ){
11969 if( !IsSpace(*z) ) return 0;
11970 while( IsSpace(*zGlob) ) zGlob++;
11971 while( IsSpace(*z) ) z++;
11972 }else if( c=='*' ){
11973 while( (c=(*(zGlob++))) == '*' || c=='?' ){
11974 if( c=='?' && (*(z++))==0 ) return 0;
11978 }else if( c=='[' ){
11979 while( *z && testcase_glob(zGlob-1,z)==0 ){
11984 while( (c2 = (*(z++)))!=0 ){
11987 if( c2==0 ) return 0;
11989 if( testcase_glob(zGlob,z) ) return 1;
11992 }else if( c=='?' ){
11993 if( (*(z++))==0 ) return 0;
11994 }else if( c=='[' ){
11999 if( c==0 ) return 0;
12006 if( c==']' ) seen = 1;
12009 while( c2 && c2!=']' ){
12010 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
12012 if( c>=prior_c && c<=c2 ) seen = 1;
12022 if( c2==0 || (seen ^ invert)==0 ) return 0;
12023 }else if( c=='#' ){
12024 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
12025 if( !IsDigit(z[0]) ) return 0;
12027 while( IsDigit(z[0]) ){ z++; }
12029 if( c!=(*(z++)) ) return 0;
12032 while( IsSpace(*z) ){ z++; }
12038 ** Compare the string as a command-line option with either one or two
12039 ** initial "-" characters.
12041 static int optionMatch(const char *zStr, const char *zOpt){
12042 if( zStr[0]!='-' ) return 0;
12044 if( zStr[0]=='-' ) zStr++;
12045 return strcmp(zStr, zOpt)==0;
12051 int shellDeleteFile(const char *zFilename){
12054 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
12058 rc = unlink(zFilename);
12064 ** Try to delete the temporary file (if there is one) and free the
12065 ** memory used to hold the name of the temp file.
12067 static void clearTempFile(ShellState *p){
12068 if( p->zTempFile==0 ) return;
12069 if( p->doXdgOpen ) return;
12070 if( shellDeleteFile(p->zTempFile) ) return;
12071 sqlite3_free(p->zTempFile);
12076 ** Create a new temp file name with the given suffix.
12078 static void newTempFile(ShellState *p, const char *zSuffix){
12080 sqlite3_free(p->zTempFile);
12083 sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
12085 if( p->zTempFile==0 ){
12087 sqlite3_randomness(sizeof(r), &r);
12088 p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
12090 p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
12092 if( p->zTempFile==0 ){
12093 raw_printf(stderr, "out of memory\n");
12100 ** The implementation of SQL scalar function fkey_collate_clause(), used
12101 ** by the ".lint fkey-indexes" command. This scalar function is always
12102 ** called with four arguments - the parent table name, the parent column name,
12103 ** the child table name and the child column name.
12105 ** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
12107 ** If either of the named tables or columns do not exist, this function
12108 ** returns an empty string. An empty string is also returned if both tables
12109 ** and columns exist but have the same default collation sequence. Or,
12110 ** if both exist but the default collation sequences are different, this
12111 ** function returns the string " COLLATE <parent-collation>", where
12112 ** <parent-collation> is the default collation sequence of the parent column.
12114 static void shellFkeyCollateClause(
12115 sqlite3_context *pCtx,
12117 sqlite3_value **apVal
12119 sqlite3 *db = sqlite3_context_db_handle(pCtx);
12120 const char *zParent;
12121 const char *zParentCol;
12122 const char *zParentSeq;
12123 const char *zChild;
12124 const char *zChildCol;
12125 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
12129 zParent = (const char*)sqlite3_value_text(apVal[0]);
12130 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
12131 zChild = (const char*)sqlite3_value_text(apVal[2]);
12132 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
12134 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
12135 rc = sqlite3_table_column_metadata(
12136 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
12138 if( rc==SQLITE_OK ){
12139 rc = sqlite3_table_column_metadata(
12140 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
12144 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
12145 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
12146 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
12153 ** The implementation of dot-command ".lint fkey-indexes".
12155 static int lintFkeyIndexes(
12156 ShellState *pState, /* Current shell tool state */
12157 char **azArg, /* Array of arguments passed to dot command */
12158 int nArg /* Number of entries in azArg[] */
12160 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
12161 FILE *out = pState->out; /* Stream to write non-error output to */
12162 int bVerbose = 0; /* If -verbose is present */
12163 int bGroupByParent = 0; /* If -groupbyparent is present */
12164 int i; /* To iterate through azArg[] */
12165 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
12166 int rc; /* Return code */
12167 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
12170 ** This SELECT statement returns one row for each foreign key constraint
12171 ** in the schema of the main database. The column values are:
12173 ** 0. The text of an SQL statement similar to:
12175 ** "EXPLAIN QUERY PLAN SELECT 1 FROM child_table WHERE child_key=?"
12177 ** This SELECT is similar to the one that the foreign keys implementation
12178 ** needs to run internally on child tables. If there is an index that can
12179 ** be used to optimize this query, then it can also be used by the FK
12180 ** implementation to optimize DELETE or UPDATE statements on the parent
12183 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
12184 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
12185 ** contains an index that can be used to optimize the query.
12187 ** 2. Human readable text that describes the child table and columns. e.g.
12189 ** "child_table(child_key1, child_key2)"
12191 ** 3. Human readable text that describes the parent table and columns. e.g.
12193 ** "parent_table(parent_key1, parent_key2)"
12195 ** 4. A full CREATE INDEX statement for an index that could be used to
12196 ** optimize DELETE or UPDATE statements on the parent table. e.g.
12198 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
12200 ** 5. The name of the parent table.
12202 ** These six values are used by the C logic below to generate the report.
12206 " 'EXPLAIN QUERY PLAN SELECT 1 FROM ' || quote(s.name) || ' WHERE '"
12207 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
12208 " || fkey_collate_clause("
12209 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
12211 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
12212 " || group_concat('*=?', ' AND ') || ')'"
12214 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
12216 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
12218 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
12219 " || ' ON ' || quote(s.name) || '('"
12220 " || group_concat(quote(f.[from]) ||"
12221 " fkey_collate_clause("
12222 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
12226 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
12227 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
12228 "GROUP BY s.name, f.id "
12229 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
12231 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
12233 for(i=2; i<nArg; i++){
12234 int n = strlen30(azArg[i]);
12235 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
12238 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
12239 bGroupByParent = 1;
12243 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
12246 return SQLITE_ERROR;
12250 /* Register the fkey_collate_clause() SQL function */
12251 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
12252 0, shellFkeyCollateClause, 0, 0
12256 if( rc==SQLITE_OK ){
12257 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
12259 if( rc==SQLITE_OK ){
12260 sqlite3_bind_int(pSql, 1, bGroupByParent);
12263 if( rc==SQLITE_OK ){
12266 while( SQLITE_ROW==sqlite3_step(pSql) ){
12268 sqlite3_stmt *pExplain = 0;
12269 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
12270 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
12271 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
12272 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
12273 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
12274 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
12276 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
12277 if( rc!=SQLITE_OK ) break;
12278 if( SQLITE_ROW==sqlite3_step(pExplain) ){
12279 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
12281 0==sqlite3_strglob(zGlob, zPlan)
12282 || 0==sqlite3_strglob(zGlobIPK, zPlan)
12285 rc = sqlite3_finalize(pExplain);
12286 if( rc!=SQLITE_OK ) break;
12289 raw_printf(stderr, "Error: internal error");
12293 && (bVerbose || res==0)
12294 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
12296 raw_printf(out, "-- Parent table %s\n", zParent);
12297 sqlite3_free(zPrev);
12298 zPrev = sqlite3_mprintf("%s", zParent);
12302 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
12303 }else if( bVerbose ){
12304 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
12305 zIndent, zFrom, zTarget
12310 sqlite3_free(zPrev);
12312 if( rc!=SQLITE_OK ){
12313 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12316 rc2 = sqlite3_finalize(pSql);
12317 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
12319 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12322 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
12329 ** Implementation of ".lint" dot command.
12331 static int lintDotCommand(
12332 ShellState *pState, /* Current shell tool state */
12333 char **azArg, /* Array of arguments passed to dot command */
12334 int nArg /* Number of entries in azArg[] */
12337 n = (nArg>=2 ? strlen30(azArg[1]) : 0);
12338 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
12339 return lintFkeyIndexes(pState, azArg, nArg);
12342 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
12343 raw_printf(stderr, "Where sub-commands are:\n");
12344 raw_printf(stderr, " fkey-indexes\n");
12345 return SQLITE_ERROR;
12348 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
12349 /*********************************************************************************
12350 ** The ".archive" or ".ar" command.
12352 static void shellPrepare(
12356 sqlite3_stmt **ppStmt
12359 if( *pRc==SQLITE_OK ){
12360 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
12361 if( rc!=SQLITE_OK ){
12362 raw_printf(stderr, "sql error: %s (%d)\n",
12363 sqlite3_errmsg(db), sqlite3_errcode(db)
12370 static void shellPreparePrintf(
12373 sqlite3_stmt **ppStmt,
12378 if( *pRc==SQLITE_OK ){
12381 va_start(ap, zFmt);
12382 z = sqlite3_vmprintf(zFmt, ap);
12384 *pRc = SQLITE_NOMEM;
12386 shellPrepare(db, pRc, z, ppStmt);
12392 static void shellFinalize(
12394 sqlite3_stmt *pStmt
12397 sqlite3 *db = sqlite3_db_handle(pStmt);
12398 int rc = sqlite3_finalize(pStmt);
12399 if( *pRc==SQLITE_OK ){
12400 if( rc!=SQLITE_OK ){
12401 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
12408 static void shellReset(
12410 sqlite3_stmt *pStmt
12412 int rc = sqlite3_reset(pStmt);
12413 if( *pRc==SQLITE_OK ){
12414 if( rc!=SQLITE_OK ){
12415 sqlite3 *db = sqlite3_db_handle(pStmt);
12416 raw_printf(stderr, "SQL error: %s\n", sqlite3_errmsg(db));
12422 ** Structure representing a single ".ar" command.
12424 typedef struct ArCommand ArCommand;
12426 u8 eCmd; /* An AR_CMD_* value */
12427 u8 bVerbose; /* True if --verbose */
12428 u8 bZip; /* True if the archive is a ZIP */
12429 u8 bDryRun; /* True if --dry-run */
12430 u8 bAppend; /* True if --append */
12431 u8 fromCmdLine; /* Run from -A instead of .archive */
12432 int nArg; /* Number of command arguments */
12433 char *zSrcTable; /* "sqlar", "zipfile($file)" or "zip" */
12434 const char *zFile; /* --file argument, or NULL */
12435 const char *zDir; /* --directory argument, or NULL */
12436 char **azArg; /* Array of command arguments */
12437 ShellState *p; /* Shell state */
12438 sqlite3 *db; /* Database containing the archive */
12442 ** Print a usage message for the .ar command to stderr and return SQLITE_ERROR.
12444 static int arUsage(FILE *f){
12447 "Usage: .ar [OPTION...] [FILE...]\n"
12448 "The .ar command manages sqlar archives.\n"
12451 " .ar -cf archive.sar foo bar # Create archive.sar from files foo and bar\n"
12452 " .ar -tf archive.sar # List members of archive.sar\n"
12453 " .ar -xvf archive.sar # Verbosely extract files from archive.sar\n"
12455 "Each command line must feature exactly one command option:\n"
12456 " -c, --create Create a new archive\n"
12457 " -u, --update Update or add files to an existing archive\n"
12458 " -t, --list List contents of archive\n"
12459 " -x, --extract Extract files from archive\n"
12461 "And zero or more optional options:\n"
12462 " -v, --verbose Print each filename as it is processed\n"
12463 " -f FILE, --file FILE Operate on archive FILE (default is current db)\n"
12464 " -a FILE, --append FILE Operate on FILE opened using the apndvfs VFS\n"
12465 " -C DIR, --directory DIR Change to directory DIR to read/extract files\n"
12466 " -n, --dryrun Show the SQL that would have occurred\n"
12468 "See also: http://sqlite.org/cli.html#sqlar_archive_support\n"
12471 return SQLITE_ERROR;
12475 ** Print an error message for the .ar command to stderr and return
12478 static int arErrorMsg(ArCommand *pAr, const char *zFmt, ...){
12481 va_start(ap, zFmt);
12482 z = sqlite3_vmprintf(zFmt, ap);
12484 utf8_printf(stderr, "Error: %s\n", z);
12485 if( pAr->fromCmdLine ){
12486 utf8_printf(stderr, "Use \"-A\" for more help\n");
12488 utf8_printf(stderr, "Use \".archive --help\" for more help\n");
12491 return SQLITE_ERROR;
12495 ** Values for ArCommand.eCmd.
12497 #define AR_CMD_CREATE 1
12498 #define AR_CMD_EXTRACT 2
12499 #define AR_CMD_LIST 3
12500 #define AR_CMD_UPDATE 4
12501 #define AR_CMD_HELP 5
12504 ** Other (non-command) switches.
12506 #define AR_SWITCH_VERBOSE 6
12507 #define AR_SWITCH_FILE 7
12508 #define AR_SWITCH_DIRECTORY 8
12509 #define AR_SWITCH_APPEND 9
12510 #define AR_SWITCH_DRYRUN 10
12512 static int arProcessSwitch(ArCommand *pAr, int eSwitch, const char *zArg){
12514 case AR_CMD_CREATE:
12515 case AR_CMD_EXTRACT:
12517 case AR_CMD_UPDATE:
12520 return arErrorMsg(pAr, "multiple command options");
12522 pAr->eCmd = eSwitch;
12525 case AR_SWITCH_DRYRUN:
12528 case AR_SWITCH_VERBOSE:
12531 case AR_SWITCH_APPEND:
12533 /* Fall thru into --file */
12534 case AR_SWITCH_FILE:
12537 case AR_SWITCH_DIRECTORY:
12546 ** Parse the command line for an ".ar" command. The results are written into
12547 ** structure (*pAr). SQLITE_OK is returned if the command line is parsed
12548 ** successfully, otherwise an error message is written to stderr and
12549 ** SQLITE_ERROR returned.
12551 static int arParseCommand(
12552 char **azArg, /* Array of arguments passed to dot command */
12553 int nArg, /* Number of entries in azArg[] */
12554 ArCommand *pAr /* Populate this object */
12562 { "create", 'c', AR_CMD_CREATE, 0 },
12563 { "extract", 'x', AR_CMD_EXTRACT, 0 },
12564 { "list", 't', AR_CMD_LIST, 0 },
12565 { "update", 'u', AR_CMD_UPDATE, 0 },
12566 { "help", 'h', AR_CMD_HELP, 0 },
12567 { "verbose", 'v', AR_SWITCH_VERBOSE, 0 },
12568 { "file", 'f', AR_SWITCH_FILE, 1 },
12569 { "append", 'a', AR_SWITCH_APPEND, 1 },
12570 { "directory", 'C', AR_SWITCH_DIRECTORY, 1 },
12571 { "dryrun", 'n', AR_SWITCH_DRYRUN, 0 },
12573 int nSwitch = sizeof(aSwitch) / sizeof(struct ArSwitch);
12574 struct ArSwitch *pEnd = &aSwitch[nSwitch];
12577 return arUsage(stderr);
12579 char *z = azArg[1];
12581 /* Traditional style [tar] invocation */
12584 for(i=0; z[i]; i++){
12585 const char *zArg = 0;
12586 struct ArSwitch *pOpt;
12587 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12588 if( z[i]==pOpt->cShort ) break;
12591 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
12595 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
12597 zArg = azArg[iArg++];
12599 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
12601 pAr->nArg = nArg-iArg;
12603 pAr->azArg = &azArg[iArg];
12606 /* Non-traditional invocation */
12608 for(iArg=1; iArg<nArg; iArg++){
12612 /* All remaining command line words are command arguments. */
12613 pAr->azArg = &azArg[iArg];
12614 pAr->nArg = nArg-iArg;
12621 /* One or more short options */
12622 for(i=1; i<n; i++){
12623 const char *zArg = 0;
12624 struct ArSwitch *pOpt;
12625 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12626 if( z[i]==pOpt->cShort ) break;
12629 return arErrorMsg(pAr, "unrecognized option: %c", z[i]);
12636 if( iArg>=(nArg-1) ){
12637 return arErrorMsg(pAr, "option requires an argument: %c",z[i]);
12639 zArg = azArg[++iArg];
12642 if( arProcessSwitch(pAr, pOpt->eSwitch, zArg) ) return SQLITE_ERROR;
12644 }else if( z[2]=='\0' ){
12645 /* A -- option, indicating that all remaining command line words
12646 ** are command arguments. */
12647 pAr->azArg = &azArg[iArg+1];
12648 pAr->nArg = nArg-iArg-1;
12651 /* A long option */
12652 const char *zArg = 0; /* Argument for option, if any */
12653 struct ArSwitch *pMatch = 0; /* Matching option */
12654 struct ArSwitch *pOpt; /* Iterator */
12655 for(pOpt=&aSwitch[0]; pOpt<pEnd; pOpt++){
12656 const char *zLong = pOpt->zLong;
12657 if( (n-2)<=strlen30(zLong) && 0==memcmp(&z[2], zLong, n-2) ){
12659 return arErrorMsg(pAr, "ambiguous option: %s",z);
12667 return arErrorMsg(pAr, "unrecognized option: %s", z);
12669 if( pMatch->bArg ){
12670 if( iArg>=(nArg-1) ){
12671 return arErrorMsg(pAr, "option requires an argument: %s", z);
12673 zArg = azArg[++iArg];
12675 if( arProcessSwitch(pAr, pMatch->eSwitch, zArg) ) return SQLITE_ERROR;
12685 ** This function assumes that all arguments within the ArCommand.azArg[]
12686 ** array refer to archive members, as for the --extract or --list commands.
12687 ** It checks that each of them are present. If any specified file is not
12688 ** present in the archive, an error is printed to stderr and an error
12689 ** code returned. Otherwise, if all specified arguments are present in
12690 ** the archive, SQLITE_OK is returned.
12692 ** This function strips any trailing '/' characters from each argument.
12693 ** This is consistent with the way the [tar] command seems to work on
12696 static int arCheckEntries(ArCommand *pAr){
12697 int rc = SQLITE_OK;
12700 sqlite3_stmt *pTest = 0;
12702 shellPreparePrintf(pAr->db, &rc, &pTest,
12703 "SELECT name FROM %s WHERE name=$name",
12706 j = sqlite3_bind_parameter_index(pTest, "$name");
12707 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
12708 char *z = pAr->azArg[i];
12709 int n = strlen30(z);
12711 while( n>0 && z[n-1]=='/' ) n--;
12713 sqlite3_bind_text(pTest, j, z, -1, SQLITE_STATIC);
12714 if( SQLITE_ROW==sqlite3_step(pTest) ){
12717 shellReset(&rc, pTest);
12718 if( rc==SQLITE_OK && bOk==0 ){
12719 utf8_printf(stderr, "not found in archive: %s\n", z);
12723 shellFinalize(&rc, pTest);
12729 ** Format a WHERE clause that can be used against the "sqlar" table to
12730 ** identify all archive members that match the command arguments held
12731 ** in (*pAr). Leave this WHERE clause in (*pzWhere) before returning.
12732 ** The caller is responsible for eventually calling sqlite3_free() on
12733 ** any non-NULL (*pzWhere) value.
12735 static void arWhereClause(
12738 char **pzWhere /* OUT: New WHERE clause */
12741 if( *pRc==SQLITE_OK ){
12742 if( pAr->nArg==0 ){
12743 zWhere = sqlite3_mprintf("1");
12746 const char *zSep = "";
12747 for(i=0; i<pAr->nArg; i++){
12748 const char *z = pAr->azArg[i];
12749 zWhere = sqlite3_mprintf(
12750 "%z%s name = '%q' OR substr(name,1,%d) = '%q/'",
12751 zWhere, zSep, z, strlen30(z)+1, z
12754 *pRc = SQLITE_NOMEM;
12765 ** Implementation of .ar "lisT" command.
12767 static int arListCommand(ArCommand *pAr){
12768 const char *zSql = "SELECT %s FROM %s WHERE %s";
12769 const char *azCols[] = {
12771 "lsmode(mode), sz, datetime(mtime, 'unixepoch'), name"
12775 sqlite3_stmt *pSql = 0;
12778 rc = arCheckEntries(pAr);
12779 arWhereClause(&rc, pAr, &zWhere);
12781 shellPreparePrintf(pAr->db, &rc, &pSql, zSql, azCols[pAr->bVerbose],
12782 pAr->zSrcTable, zWhere);
12783 if( pAr->bDryRun ){
12784 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
12786 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12787 if( pAr->bVerbose ){
12788 utf8_printf(pAr->p->out, "%s % 10d %s %s\n",
12789 sqlite3_column_text(pSql, 0),
12790 sqlite3_column_int(pSql, 1),
12791 sqlite3_column_text(pSql, 2),
12792 sqlite3_column_text(pSql, 3)
12795 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
12799 shellFinalize(&rc, pSql);
12800 sqlite3_free(zWhere);
12806 ** Implementation of .ar "eXtract" command.
12808 static int arExtractCommand(ArCommand *pAr){
12809 const char *zSql1 =
12812 " writefile(($dir || name), %s, mode, mtime) "
12813 "FROM %s WHERE (%s) AND (data IS NULL OR $dirOnly = 0)"
12814 " AND name NOT GLOB '*..[/\\]*'";
12816 const char *azExtraArg[] = {
12817 "sqlar_uncompress(data, sz)",
12821 sqlite3_stmt *pSql = 0;
12822 int rc = SQLITE_OK;
12827 /* If arguments are specified, check that they actually exist within
12828 ** the archive before proceeding. And formulate a WHERE clause to
12830 rc = arCheckEntries(pAr);
12831 arWhereClause(&rc, pAr, &zWhere);
12833 if( rc==SQLITE_OK ){
12835 zDir = sqlite3_mprintf("%s/", pAr->zDir);
12837 zDir = sqlite3_mprintf("");
12839 if( zDir==0 ) rc = SQLITE_NOMEM;
12842 shellPreparePrintf(pAr->db, &rc, &pSql, zSql1,
12843 azExtraArg[pAr->bZip], pAr->zSrcTable, zWhere
12846 if( rc==SQLITE_OK ){
12847 j = sqlite3_bind_parameter_index(pSql, "$dir");
12848 sqlite3_bind_text(pSql, j, zDir, -1, SQLITE_STATIC);
12850 /* Run the SELECT statement twice. The first time, writefile() is called
12851 ** for all archive members that should be extracted. The second time,
12852 ** only for the directories. This is because the timestamps for
12853 ** extracted directories must be reset after they are populated (as
12854 ** populating them changes the timestamp). */
12855 for(i=0; i<2; i++){
12856 j = sqlite3_bind_parameter_index(pSql, "$dirOnly");
12857 sqlite3_bind_int(pSql, j, i);
12858 if( pAr->bDryRun ){
12859 utf8_printf(pAr->p->out, "%s\n", sqlite3_sql(pSql));
12861 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
12862 if( i==0 && pAr->bVerbose ){
12863 utf8_printf(pAr->p->out, "%s\n", sqlite3_column_text(pSql, 0));
12867 shellReset(&rc, pSql);
12869 shellFinalize(&rc, pSql);
12872 sqlite3_free(zDir);
12873 sqlite3_free(zWhere);
12878 ** Run the SQL statement in zSql. Or if doing a --dryrun, merely print it out.
12880 static int arExecSql(ArCommand *pAr, const char *zSql){
12882 if( pAr->bDryRun ){
12883 utf8_printf(pAr->p->out, "%s\n", zSql);
12887 rc = sqlite3_exec(pAr->db, zSql, 0, 0, &zErr);
12889 utf8_printf(stdout, "ERROR: %s\n", zErr);
12890 sqlite3_free(zErr);
12898 ** Implementation of .ar "create" and "update" commands.
12900 ** Create the "sqlar" table in the database if it does not already exist.
12901 ** Then add each file in the azFile[] array to the archive. Directories
12902 ** are added recursively. If argument bVerbose is non-zero, a message is
12903 ** printed on stdout for each file archived.
12905 ** The create command is the same as update, except that it drops
12906 ** any existing "sqlar" table before beginning.
12908 static int arCreateOrUpdateCommand(
12909 ArCommand *pAr, /* Command arguments and options */
12910 int bUpdate /* true for a --create. false for --update */
12912 const char *zCreate =
12913 "CREATE TABLE IF NOT EXISTS sqlar(\n"
12914 " name TEXT PRIMARY KEY, -- name of the file\n"
12915 " mode INT, -- access permissions\n"
12916 " mtime INT, -- last modification time\n"
12917 " sz INT, -- original file size\n"
12918 " data BLOB -- compressed content\n"
12920 const char *zDrop = "DROP TABLE IF EXISTS sqlar";
12921 const char *zInsertFmt[2] = {
12922 "REPLACE INTO %s(name,mode,mtime,sz,data)\n"
12927 " CASE substr(lsmode(mode),1,1)\n"
12928 " WHEN '-' THEN length(data)\n"
12929 " WHEN 'd' THEN 0\n"
12931 " sqlar_compress(data)\n"
12932 " FROM fsdir(%Q,%Q)\n"
12933 " WHERE lsmode(mode) NOT LIKE '?%%';",
12934 "REPLACE INTO %s(name,mode,mtime,data)\n"
12940 " FROM fsdir(%Q,%Q)\n"
12941 " WHERE lsmode(mode) NOT LIKE '?%%';"
12943 int i; /* For iterating through azFile[] */
12944 int rc; /* Return code */
12945 const char *zTab = 0; /* SQL table into which to insert */
12949 arExecSql(pAr, "PRAGMA page_size=512");
12950 rc = arExecSql(pAr, "SAVEPOINT ar;");
12951 if( rc!=SQLITE_OK ) return rc;
12954 /* Initialize the zipfile virtual table, if necessary */
12957 sqlite3_randomness(sizeof(r),&r);
12958 sqlite3_snprintf(sizeof(zTemp),zTemp,"zip%016llx",r);
12960 zSql = sqlite3_mprintf(
12961 "CREATE VIRTUAL TABLE temp.%s USING zipfile(%Q)",
12964 rc = arExecSql(pAr, zSql);
12965 sqlite3_free(zSql);
12970 /* Initialize the table for an SQLAR */
12973 rc = arExecSql(pAr, zDrop);
12974 if( rc!=SQLITE_OK ) goto end_ar_transaction;
12976 rc = arExecSql(pAr, zCreate);
12978 for(i=0; i<pAr->nArg && rc==SQLITE_OK; i++){
12979 char *zSql2 = sqlite3_mprintf(zInsertFmt[pAr->bZip], zTab,
12980 pAr->bVerbose ? "shell_putsnl(name)" : "name",
12981 pAr->azArg[i], pAr->zDir);
12982 rc = arExecSql(pAr, zSql2);
12983 sqlite3_free(zSql2);
12985 end_ar_transaction:
12986 if( rc!=SQLITE_OK ){
12987 arExecSql(pAr, "ROLLBACK TO ar; RELEASE ar;");
12989 rc = arExecSql(pAr, "RELEASE ar;");
12990 if( pAr->bZip && pAr->zFile ){
12991 zSql = sqlite3_mprintf("DROP TABLE %s", zTemp);
12992 arExecSql(pAr, zSql);
12993 sqlite3_free(zSql);
13000 ** Implementation of ".ar" dot command.
13002 static int arDotCommand(
13003 ShellState *pState, /* Current shell tool state */
13004 int fromCmdLine, /* True if -A command-line option, not .ar cmd */
13005 char **azArg, /* Array of arguments passed to dot command */
13006 int nArg /* Number of entries in azArg[] */
13010 memset(&cmd, 0, sizeof(cmd));
13011 cmd.fromCmdLine = fromCmdLine;
13012 rc = arParseCommand(azArg, nArg, &cmd);
13013 if( rc==SQLITE_OK ){
13014 int eDbType = SHELL_OPEN_UNSPEC;
13016 cmd.db = pState->db;
13018 eDbType = deduceDatabaseType(cmd.zFile, 1);
13020 eDbType = pState->openMode;
13022 if( eDbType==SHELL_OPEN_ZIPFILE ){
13023 if( cmd.eCmd==AR_CMD_EXTRACT || cmd.eCmd==AR_CMD_LIST ){
13024 if( cmd.zFile==0 ){
13025 cmd.zSrcTable = sqlite3_mprintf("zip");
13027 cmd.zSrcTable = sqlite3_mprintf("zipfile(%Q)", cmd.zFile);
13031 }else if( cmd.zFile ){
13033 if( cmd.bAppend ) eDbType = SHELL_OPEN_APPENDVFS;
13034 if( cmd.eCmd==AR_CMD_CREATE || cmd.eCmd==AR_CMD_UPDATE ){
13035 flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
13037 flags = SQLITE_OPEN_READONLY;
13041 utf8_printf(pState->out, "-- open database '%s'%s\n", cmd.zFile,
13042 eDbType==SHELL_OPEN_APPENDVFS ? " using 'apndvfs'" : "");
13044 rc = sqlite3_open_v2(cmd.zFile, &cmd.db, flags,
13045 eDbType==SHELL_OPEN_APPENDVFS ? "apndvfs" : 0);
13046 if( rc!=SQLITE_OK ){
13047 utf8_printf(stderr, "cannot open file: %s (%s)\n",
13048 cmd.zFile, sqlite3_errmsg(cmd.db)
13050 goto end_ar_command;
13052 sqlite3_fileio_init(cmd.db, 0, 0);
13053 sqlite3_sqlar_init(cmd.db, 0, 0);
13054 sqlite3_create_function(cmd.db, "shell_putsnl", 1, SQLITE_UTF8, cmd.p,
13055 shellPutsFunc, 0, 0);
13058 if( cmd.zSrcTable==0 && cmd.bZip==0 && cmd.eCmd!=AR_CMD_HELP ){
13059 if( cmd.eCmd!=AR_CMD_CREATE
13060 && sqlite3_table_column_metadata(cmd.db,0,"sqlar","name",0,0,0,0,0)
13062 utf8_printf(stderr, "database does not contain an 'sqlar' table\n");
13064 goto end_ar_command;
13066 cmd.zSrcTable = sqlite3_mprintf("sqlar");
13069 switch( cmd.eCmd ){
13070 case AR_CMD_CREATE:
13071 rc = arCreateOrUpdateCommand(&cmd, 0);
13074 case AR_CMD_EXTRACT:
13075 rc = arExtractCommand(&cmd);
13079 rc = arListCommand(&cmd);
13083 arUsage(pState->out);
13087 assert( cmd.eCmd==AR_CMD_UPDATE );
13088 rc = arCreateOrUpdateCommand(&cmd, 1);
13093 if( cmd.db!=pState->db ){
13096 sqlite3_free(cmd.zSrcTable);
13100 /* End of the ".archive" or ".ar" command logic
13101 **********************************************************************************/
13102 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB) */
13106 ** If an input line begins with "." then invoke this routine to
13107 ** process that line.
13109 ** Return 1 on error, 2 to exit, and 0 otherwise.
13111 static int do_meta_command(char *zLine, ShellState *p){
13118 #ifndef SQLITE_OMIT_VIRTUALTABLE
13119 if( p->expert.pExpert ){
13120 expertFinish(p, 1, 0);
13124 /* Parse the input line into tokens.
13126 while( zLine[h] && nArg<ArraySize(azArg) ){
13127 while( IsSpace(zLine[h]) ){ h++; }
13128 if( zLine[h]==0 ) break;
13129 if( zLine[h]=='\'' || zLine[h]=='"' ){
13130 int delim = zLine[h++];
13131 azArg[nArg++] = &zLine[h];
13132 while( zLine[h] && zLine[h]!=delim ){
13133 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
13136 if( zLine[h]==delim ){
13139 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
13141 azArg[nArg++] = &zLine[h];
13142 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
13143 if( zLine[h] ) zLine[h++] = 0;
13144 resolve_backslashes(azArg[nArg-1]);
13148 /* Process the input line.
13150 if( nArg==0 ) return 0; /* no tokens, no error */
13151 n = strlen30(azArg[0]);
13155 #ifndef SQLITE_OMIT_AUTHORIZATION
13156 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
13158 raw_printf(stderr, "Usage: .auth ON|OFF\n");
13160 goto meta_command_exit;
13163 if( booleanValue(azArg[1]) ){
13164 sqlite3_set_authorizer(p->db, shellAuth, p);
13166 sqlite3_set_authorizer(p->db, 0, 0);
13171 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
13172 if( c=='a' && strncmp(azArg[0], "archive", n)==0 ){
13174 rc = arDotCommand(p, 0, azArg, nArg);
13178 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
13179 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
13181 const char *zDestFile = 0;
13182 const char *zDb = 0;
13184 sqlite3_backup *pBackup;
13186 const char *zVfs = 0;
13187 for(j=1; j<nArg; j++){
13188 const char *z = azArg[j];
13190 if( z[1]=='-' ) z++;
13191 if( strcmp(z, "-append")==0 ){
13195 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
13198 }else if( zDestFile==0 ){
13199 zDestFile = azArg[j];
13200 }else if( zDb==0 ){
13202 zDestFile = azArg[j];
13204 raw_printf(stderr, "Usage: .backup ?DB? ?--append? FILENAME\n");
13208 if( zDestFile==0 ){
13209 raw_printf(stderr, "missing FILENAME argument on .backup\n");
13212 if( zDb==0 ) zDb = "main";
13213 rc = sqlite3_open_v2(zDestFile, &pDest,
13214 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, zVfs);
13215 if( rc!=SQLITE_OK ){
13216 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
13221 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
13223 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
13227 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
13228 sqlite3_backup_finish(pBackup);
13229 if( rc==SQLITE_DONE ){
13232 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
13238 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
13240 bail_on_error = booleanValue(azArg[1]);
13242 raw_printf(stderr, "Usage: .bail on|off\n");
13247 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
13249 if( booleanValue(azArg[1]) ){
13250 setBinaryMode(p->out, 1);
13252 setTextMode(p->out, 1);
13255 raw_printf(stderr, "Usage: .binary on|off\n");
13260 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
13262 #if defined(_WIN32) || defined(WIN32)
13263 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
13264 rc = !SetCurrentDirectoryW(z);
13267 rc = chdir(azArg[1]);
13270 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
13274 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
13279 /* The undocumented ".breakpoint" command causes a call to the no-op
13280 ** routine named test_breakpoint().
13282 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
13286 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
13288 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
13290 raw_printf(stderr, "Usage: .changes on|off\n");
13295 /* Cancel output redirection, if it is currently set (by .testcase)
13296 ** Then read the content of the testcase-out.txt file and compare against
13297 ** azArg[1]. If there are differences, report an error and exit.
13299 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
13303 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
13305 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
13306 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
13308 }else if( testcase_glob(azArg[1],zRes)==0 ){
13309 utf8_printf(stderr,
13310 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
13311 p->zTestcase, azArg[1], zRes);
13314 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
13317 sqlite3_free(zRes);
13320 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
13322 tryToClone(p, azArg[1]);
13324 raw_printf(stderr, "Usage: .clone FILENAME\n");
13329 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
13333 memcpy(&data, p, sizeof(data));
13334 data.showHeader = 0;
13335 data.cMode = data.mode = MODE_List;
13336 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
13338 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
13339 callback, &data, &zErrMsg);
13341 utf8_printf(stderr,"Error: %s\n", zErrMsg);
13342 sqlite3_free(zErrMsg);
13347 if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
13348 static const struct DbConfigChoices {const char *zName; int op;} aDbConfig[] = {
13349 { "enable_fkey", SQLITE_DBCONFIG_ENABLE_FKEY },
13350 { "enable_trigger", SQLITE_DBCONFIG_ENABLE_TRIGGER },
13351 { "fts3_tokenizer", SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
13352 { "load_extension", SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
13353 { "no_ckpt_on_close", SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE },
13354 { "enable_qpsg", SQLITE_DBCONFIG_ENABLE_QPSG },
13355 { "trigger_eqp", SQLITE_DBCONFIG_TRIGGER_EQP },
13356 { "reset_database", SQLITE_DBCONFIG_RESET_DATABASE },
13360 for(ii=0; ii<ArraySize(aDbConfig); ii++){
13361 if( nArg>1 && strcmp(azArg[1], aDbConfig[ii].zName)!=0 ) continue;
13363 sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
13365 sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
13366 utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
13367 if( nArg>1 ) break;
13369 if( nArg>1 && ii==ArraySize(aDbConfig) ){
13370 utf8_printf(stderr, "Error: unknown dbconfig \"%s\"\n", azArg[1]);
13371 utf8_printf(stderr, "Enter \".dbconfig\" with no arguments for a list\n");
13375 if( c=='d' && n>=3 && strncmp(azArg[0], "dbinfo", n)==0 ){
13376 rc = shell_dbinfo_command(p, nArg, azArg);
13379 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
13380 const char *zLike = 0;
13382 int savedShowHeader = p->showHeader;
13383 int savedShellFlags = p->shellFlgs;
13384 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
13385 for(i=1; i<nArg; i++){
13386 if( azArg[i][0]=='-' ){
13387 const char *z = azArg[i]+1;
13388 if( z[0]=='-' ) z++;
13389 if( strcmp(z,"preserve-rowids")==0 ){
13390 #ifdef SQLITE_OMIT_VIRTUALTABLE
13391 raw_printf(stderr, "The --preserve-rowids option is not compatible"
13392 " with SQLITE_OMIT_VIRTUALTABLE\n");
13394 goto meta_command_exit;
13396 ShellSetFlag(p, SHFLG_PreserveRowid);
13399 if( strcmp(z,"newlines")==0 ){
13400 ShellSetFlag(p, SHFLG_Newlines);
13403 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
13405 goto meta_command_exit;
13408 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
13409 "?--newlines? ?LIKE-PATTERN?\n");
13411 goto meta_command_exit;
13417 /* When playing back a "dump", the content might appear in an order
13418 ** which causes immediate foreign key constraints to be violated.
13419 ** So disable foreign-key constraint enforcement to prevent problems. */
13420 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
13421 raw_printf(p->out, "BEGIN TRANSACTION;\n");
13422 p->writableSchema = 0;
13424 /* Set writable_schema=ON since doing so forces SQLite to initialize
13425 ** as much of the schema as it can even if the sqlite_master table is
13427 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
13430 run_schema_dump_query(p,
13431 "SELECT name, type, sql FROM sqlite_master "
13432 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
13434 run_schema_dump_query(p,
13435 "SELECT name, type, sql FROM sqlite_master "
13436 "WHERE name=='sqlite_sequence'"
13438 run_table_dump_query(p,
13439 "SELECT sql FROM sqlite_master "
13440 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
13444 zSql = sqlite3_mprintf(
13445 "SELECT name, type, sql FROM sqlite_master "
13446 "WHERE tbl_name LIKE %Q AND type=='table'"
13447 " AND sql NOT NULL", zLike);
13448 run_schema_dump_query(p,zSql);
13449 sqlite3_free(zSql);
13450 zSql = sqlite3_mprintf(
13451 "SELECT sql FROM sqlite_master "
13452 "WHERE sql NOT NULL"
13453 " AND type IN ('index','trigger','view')"
13454 " AND tbl_name LIKE %Q", zLike);
13455 run_table_dump_query(p, zSql, 0);
13456 sqlite3_free(zSql);
13458 if( p->writableSchema ){
13459 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
13460 p->writableSchema = 0;
13462 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
13463 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
13464 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
13465 p->showHeader = savedShowHeader;
13466 p->shellFlgs = savedShellFlags;
13469 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
13471 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
13473 raw_printf(stderr, "Usage: .echo on|off\n");
13478 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
13480 p->autoEQPtest = 0;
13481 if( strcmp(azArg[1],"full")==0 ){
13482 p->autoEQP = AUTOEQP_full;
13483 }else if( strcmp(azArg[1],"trigger")==0 ){
13484 p->autoEQP = AUTOEQP_trigger;
13485 }else if( strcmp(azArg[1],"test")==0 ){
13486 p->autoEQP = AUTOEQP_on;
13487 p->autoEQPtest = 1;
13489 p->autoEQP = (u8)booleanValue(azArg[1]);
13492 raw_printf(stderr, "Usage: .eqp off|on|trigger|full\n");
13497 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
13498 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
13502 /* The ".explain" command is automatic now. It is largely pointless. It
13503 ** retained purely for backwards compatibility */
13504 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
13507 if( strcmp(azArg[1],"auto")==0 ){
13510 val = booleanValue(azArg[1]);
13513 if( val==1 && p->mode!=MODE_Explain ){
13514 p->normalMode = p->mode;
13515 p->mode = MODE_Explain;
13516 p->autoExplain = 0;
13517 }else if( val==0 ){
13518 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
13519 p->autoExplain = 0;
13520 }else if( val==99 ){
13521 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
13522 p->autoExplain = 1;
13526 #ifndef SQLITE_OMIT_VIRTUALTABLE
13527 if( c=='e' && strncmp(azArg[0], "expert", n)==0 ){
13529 expertDotCommand(p, azArg, nArg);
13533 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
13537 memcpy(&data, p, sizeof(data));
13538 data.showHeader = 0;
13539 data.cMode = data.mode = MODE_Semi;
13540 if( nArg==2 && optionMatch(azArg[1], "indent") ){
13541 data.cMode = data.mode = MODE_Pretty;
13545 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
13547 goto meta_command_exit;
13550 rc = sqlite3_exec(p->db,
13552 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
13553 " FROM sqlite_master UNION ALL"
13554 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
13555 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
13557 callback, &data, &zErrMsg
13559 if( rc==SQLITE_OK ){
13560 sqlite3_stmt *pStmt;
13561 rc = sqlite3_prepare_v2(p->db,
13562 "SELECT rowid FROM sqlite_master"
13563 " WHERE name GLOB 'sqlite_stat[134]'",
13565 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
13566 sqlite3_finalize(pStmt);
13569 raw_printf(p->out, "/* No STAT tables available */\n");
13571 raw_printf(p->out, "ANALYZE sqlite_master;\n");
13572 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
13573 callback, &data, &zErrMsg);
13574 data.cMode = data.mode = MODE_Insert;
13575 data.zDestTable = "sqlite_stat1";
13576 shell_exec(&data, "SELECT * FROM sqlite_stat1", &zErrMsg);
13577 data.zDestTable = "sqlite_stat3";
13578 shell_exec(&data, "SELECT * FROM sqlite_stat3", &zErrMsg);
13579 data.zDestTable = "sqlite_stat4";
13580 shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
13581 raw_printf(p->out, "ANALYZE sqlite_master;\n");
13585 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
13587 p->showHeader = booleanValue(azArg[1]);
13589 raw_printf(stderr, "Usage: .headers on|off\n");
13594 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
13595 utf8_printf(p->out, "%s", zHelp);
13598 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
13599 char *zTable; /* Insert data into this table */
13600 char *zFile; /* Name of file to extra content from */
13601 sqlite3_stmt *pStmt = NULL; /* A statement */
13602 int nCol; /* Number of columns in the table */
13603 int nByte; /* Number of bytes in an SQL string */
13604 int i, j; /* Loop counters */
13605 int needCommit; /* True to COMMIT or ROLLBACK at end */
13606 int nSep; /* Number of bytes in p->colSeparator[] */
13607 char *zSql; /* An SQL statement */
13608 ImportCtx sCtx; /* Reader context */
13609 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
13610 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
13613 raw_printf(stderr, "Usage: .import FILE TABLE\n");
13614 goto meta_command_exit;
13619 memset(&sCtx, 0, sizeof(sCtx));
13621 nSep = strlen30(p->colSeparator);
13624 "Error: non-null column separator required for import\n");
13628 raw_printf(stderr, "Error: multi-character column separators not allowed"
13632 nSep = strlen30(p->rowSeparator);
13634 raw_printf(stderr, "Error: non-null row separator required for import\n");
13637 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
13638 /* When importing CSV (only), if the row separator is set to the
13639 ** default output row separator, change it to the default input
13640 ** row separator. This avoids having to maintain different input
13641 ** and output row separators. */
13642 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13643 nSep = strlen30(p->rowSeparator);
13646 raw_printf(stderr, "Error: multi-character row separators not allowed"
13650 sCtx.zFile = zFile;
13652 if( sCtx.zFile[0]=='|' ){
13653 #ifdef SQLITE_OMIT_POPEN
13654 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
13657 sCtx.in = popen(sCtx.zFile+1, "r");
13658 sCtx.zFile = "<pipe>";
13662 sCtx.in = fopen(sCtx.zFile, "rb");
13665 if( p->mode==MODE_Ascii ){
13666 xRead = ascii_read_one_field;
13668 xRead = csv_read_one_field;
13671 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
13674 sCtx.cColSep = p->colSeparator[0];
13675 sCtx.cRowSep = p->rowSeparator[0];
13676 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
13679 shell_out_of_memory();
13681 nByte = strlen30(zSql);
13682 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13683 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
13684 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
13685 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
13687 while( xRead(&sCtx) ){
13688 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
13690 if( sCtx.cTerm!=sCtx.cColSep ) break;
13693 sqlite3_free(zCreate);
13694 sqlite3_free(sCtx.z);
13696 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
13699 zCreate = sqlite3_mprintf("%z\n)", zCreate);
13700 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
13701 sqlite3_free(zCreate);
13703 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
13704 sqlite3_errmsg(p->db));
13705 sqlite3_free(sCtx.z);
13709 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13711 sqlite3_free(zSql);
13713 if (pStmt) sqlite3_finalize(pStmt);
13714 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
13718 nCol = sqlite3_column_count(pStmt);
13719 sqlite3_finalize(pStmt);
13721 if( nCol==0 ) return 0; /* no columns, no error */
13722 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
13725 shell_out_of_memory();
13727 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
13728 j = strlen30(zSql);
13729 for(i=1; i<nCol; i++){
13735 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13736 sqlite3_free(zSql);
13738 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
13739 if (pStmt) sqlite3_finalize(pStmt);
13743 needCommit = sqlite3_get_autocommit(p->db);
13744 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
13746 int startLine = sCtx.nLine;
13747 for(i=0; i<nCol; i++){
13748 char *z = xRead(&sCtx);
13750 ** Did we reach end-of-file before finding any columns?
13751 ** If so, stop instead of NULL filling the remaining columns.
13753 if( z==0 && i==0 ) break;
13755 ** Did we reach end-of-file OR end-of-line before finding any
13756 ** columns in ASCII mode? If so, stop instead of NULL filling
13757 ** the remaining columns.
13759 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
13760 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
13761 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
13762 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
13763 "filling the rest with NULL\n",
13764 sCtx.zFile, startLine, nCol, i+1);
13766 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
13769 if( sCtx.cTerm==sCtx.cColSep ){
13773 }while( sCtx.cTerm==sCtx.cColSep );
13774 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
13775 "extras ignored\n",
13776 sCtx.zFile, startLine, nCol, i);
13779 sqlite3_step(pStmt);
13780 rc = sqlite3_reset(pStmt);
13781 if( rc!=SQLITE_OK ){
13782 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
13783 startLine, sqlite3_errmsg(p->db));
13786 }while( sCtx.cTerm!=EOF );
13789 sqlite3_free(sCtx.z);
13790 sqlite3_finalize(pStmt);
13791 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
13794 #ifndef SQLITE_UNTESTABLE
13795 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
13797 char *zCollist = 0;
13798 sqlite3_stmt *pStmt;
13801 if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
13802 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
13803 " .imposter off\n");
13805 goto meta_command_exit;
13809 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
13810 goto meta_command_exit;
13812 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
13813 " WHERE name='%q' AND type='index'", azArg[1]);
13814 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13815 sqlite3_free(zSql);
13816 if( sqlite3_step(pStmt)==SQLITE_ROW ){
13817 tnum = sqlite3_column_int(pStmt, 0);
13819 sqlite3_finalize(pStmt);
13821 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
13823 goto meta_command_exit;
13825 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
13826 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
13827 sqlite3_free(zSql);
13829 while( sqlite3_step(pStmt)==SQLITE_ROW ){
13831 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
13834 if( sqlite3_column_int(pStmt,1)==-1 ){
13837 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
13842 zCollist = sqlite3_mprintf("\"%w\"", zCol);
13844 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
13847 sqlite3_finalize(pStmt);
13848 zSql = sqlite3_mprintf(
13849 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
13850 azArg[2], zCollist, zCollist);
13851 sqlite3_free(zCollist);
13852 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
13853 if( rc==SQLITE_OK ){
13854 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
13855 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
13857 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
13859 utf8_printf(stdout, "%s;\n", zSql);
13861 "WARNING: writing to an imposter table will corrupt the index!\n"
13865 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
13868 sqlite3_free(zSql);
13870 #endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
13872 #ifdef SQLITE_ENABLE_IOTRACE
13873 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
13874 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
13875 if( iotrace && iotrace!=stdout ) fclose(iotrace);
13878 sqlite3IoTrace = 0;
13879 }else if( strcmp(azArg[1], "-")==0 ){
13880 sqlite3IoTrace = iotracePrintf;
13883 iotrace = fopen(azArg[1], "w");
13885 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
13886 sqlite3IoTrace = 0;
13889 sqlite3IoTrace = iotracePrintf;
13895 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
13896 static const struct {
13897 const char *zLimitName; /* Name of a limit */
13898 int limitCode; /* Integer code for that limit */
13900 { "length", SQLITE_LIMIT_LENGTH },
13901 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
13902 { "column", SQLITE_LIMIT_COLUMN },
13903 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
13904 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
13905 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
13906 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
13907 { "attached", SQLITE_LIMIT_ATTACHED },
13908 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
13909 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
13910 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
13911 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
13916 for(i=0; i<ArraySize(aLimit); i++){
13917 printf("%20s %d\n", aLimit[i].zLimitName,
13918 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
13920 }else if( nArg>3 ){
13921 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
13923 goto meta_command_exit;
13926 n2 = strlen30(azArg[1]);
13927 for(i=0; i<ArraySize(aLimit); i++){
13928 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
13932 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
13934 goto meta_command_exit;
13939 utf8_printf(stderr, "unknown limit: \"%s\"\n"
13940 "enter \".limits\" with no arguments for a list.\n",
13943 goto meta_command_exit;
13946 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
13947 (int)integerValue(azArg[2]));
13949 printf("%20s %d\n", aLimit[iLimit].zLimitName,
13950 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
13954 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
13956 lintDotCommand(p, azArg, nArg);
13959 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13960 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
13961 const char *zFile, *zProc;
13964 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
13966 goto meta_command_exit;
13969 zProc = nArg>=3 ? azArg[2] : 0;
13971 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
13972 if( rc!=SQLITE_OK ){
13973 utf8_printf(stderr, "Error: %s\n", zErrMsg);
13974 sqlite3_free(zErrMsg);
13980 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
13982 raw_printf(stderr, "Usage: .log FILENAME\n");
13985 const char *zFile = azArg[1];
13986 output_file_close(p->pLog);
13987 p->pLog = output_file_open(zFile, 0);
13991 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
13992 const char *zMode = nArg>=2 ? azArg[1] : "";
13993 int n2 = strlen30(zMode);
13995 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
13996 p->mode = MODE_Line;
13997 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
13998 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
13999 p->mode = MODE_Column;
14000 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
14001 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
14002 p->mode = MODE_List;
14003 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
14004 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
14005 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
14006 p->mode = MODE_Html;
14007 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
14008 p->mode = MODE_Tcl;
14009 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
14010 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
14011 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
14012 p->mode = MODE_Csv;
14013 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
14014 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
14015 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
14016 p->mode = MODE_List;
14017 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
14018 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
14019 p->mode = MODE_Insert;
14020 set_table_name(p, nArg>=3 ? azArg[2] : "table");
14021 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
14022 p->mode = MODE_Quote;
14023 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
14024 p->mode = MODE_Ascii;
14025 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
14026 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
14027 }else if( nArg==1 ){
14028 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
14030 raw_printf(stderr, "Error: mode should be one of: "
14031 "ascii column csv html insert line list quote tabs tcl\n");
14034 p->cMode = p->mode;
14037 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
14039 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
14040 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
14042 raw_printf(stderr, "Usage: .nullvalue STRING\n");
14047 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
14048 char *zNewFilename; /* Name of the database file to open */
14049 int iName = 1; /* Index in azArg[] of the filename */
14050 int newFlag = 0; /* True to delete file before opening */
14051 /* Close the existing database */
14052 session_close_all(p);
14055 p->zDbFilename = 0;
14056 sqlite3_free(p->zFreeOnClose);
14057 p->zFreeOnClose = 0;
14058 p->openMode = SHELL_OPEN_UNSPEC;
14059 /* Check for command-line arguments */
14060 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
14061 const char *z = azArg[iName];
14062 if( optionMatch(z,"new") ){
14064 #ifdef SQLITE_HAVE_ZLIB
14065 }else if( optionMatch(z, "zip") ){
14066 p->openMode = SHELL_OPEN_ZIPFILE;
14068 }else if( optionMatch(z, "append") ){
14069 p->openMode = SHELL_OPEN_APPENDVFS;
14070 }else if( optionMatch(z, "readonly") ){
14071 p->openMode = SHELL_OPEN_READONLY;
14072 }else if( z[0]=='-' ){
14073 utf8_printf(stderr, "unknown option: %s\n", z);
14075 goto meta_command_exit;
14078 /* If a filename is specified, try to open it first */
14079 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
14080 if( zNewFilename ){
14081 if( newFlag ) shellDeleteFile(zNewFilename);
14082 p->zDbFilename = zNewFilename;
14083 open_db(p, OPEN_DB_KEEPALIVE);
14085 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
14086 sqlite3_free(zNewFilename);
14088 p->zFreeOnClose = zNewFilename;
14092 /* As a fall-back open a TEMP database */
14093 p->zDbFilename = 0;
14099 && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
14100 || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
14102 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
14104 if( azArg[0][0]=='e' ){
14105 /* Transform the ".excel" command into ".once -x" */
14108 zFile = azArg[1] = "-x";
14112 utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
14114 goto meta_command_exit;
14116 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
14118 raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
14120 goto meta_command_exit;
14127 if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
14128 #ifndef SQLITE_NOHAVE_SYSTEM
14129 if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
14132 if( zFile[1]=='x' ){
14133 newTempFile(p, "csv");
14134 p->mode = MODE_Csv;
14135 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
14136 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
14138 newTempFile(p, "txt");
14141 zFile = p->zTempFile;
14143 #endif /* SQLITE_NOHAVE_SYSTEM */
14144 if( zFile[0]=='|' ){
14145 #ifdef SQLITE_OMIT_POPEN
14146 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
14150 p->out = popen(zFile + 1, "w");
14152 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
14156 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
14160 p->out = output_file_open(zFile, bTxtMode);
14162 if( strcmp(zFile,"off")!=0 ){
14163 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
14168 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
14173 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
14175 for(i=1; i<nArg; i++){
14176 if( i>1 ) raw_printf(p->out, " ");
14177 utf8_printf(p->out, "%s", azArg[i]);
14179 raw_printf(p->out, "\n");
14182 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
14184 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
14187 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
14191 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
14195 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
14198 raw_printf(stderr, "Usage: .read FILE\n");
14200 goto meta_command_exit;
14202 alt = fopen(azArg[1], "rb");
14204 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
14207 rc = process_input(p, alt);
14212 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
14213 const char *zSrcFile;
14216 sqlite3_backup *pBackup;
14220 zSrcFile = azArg[1];
14222 }else if( nArg==3 ){
14223 zSrcFile = azArg[2];
14226 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
14228 goto meta_command_exit;
14230 rc = sqlite3_open(zSrcFile, &pSrc);
14231 if( rc!=SQLITE_OK ){
14232 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
14237 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
14239 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14243 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
14244 || rc==SQLITE_BUSY ){
14245 if( rc==SQLITE_BUSY ){
14246 if( nTimeout++ >= 3 ) break;
14247 sqlite3_sleep(100);
14250 sqlite3_backup_finish(pBackup);
14251 if( rc==SQLITE_DONE ){
14253 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
14254 raw_printf(stderr, "Error: source database is busy\n");
14257 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14263 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
14265 p->scanstatsOn = (u8)booleanValue(azArg[1]);
14266 #ifndef SQLITE_ENABLE_STMT_SCANSTATUS
14267 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
14270 raw_printf(stderr, "Usage: .scanstats on|off\n");
14275 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
14279 const char *zDiv = "(";
14280 const char *zName = 0;
14286 memcpy(&data, p, sizeof(data));
14287 data.showHeader = 0;
14288 data.cMode = data.mode = MODE_Semi;
14289 initText(&sSelect);
14290 for(ii=1; ii<nArg; ii++){
14291 if( optionMatch(azArg[ii],"indent") ){
14292 data.cMode = data.mode = MODE_Pretty;
14293 }else if( optionMatch(azArg[ii],"debug") ){
14295 }else if( zName==0 ){
14298 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
14300 goto meta_command_exit;
14304 int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
14305 if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
14306 char *new_argv[2], *new_colv[2];
14307 new_argv[0] = sqlite3_mprintf(
14308 "CREATE TABLE %s (\n"
14311 " tbl_name text,\n"
14312 " rootpage integer,\n"
14314 ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
14316 new_colv[0] = "sql";
14318 callback(&data, 1, new_argv, new_colv);
14319 sqlite3_free(new_argv[0]);
14323 sqlite3_stmt *pStmt = 0;
14324 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
14327 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
14328 sqlite3_finalize(pStmt);
14330 goto meta_command_exit;
14332 appendText(&sSelect, "SELECT sql FROM", 0);
14334 while( sqlite3_step(pStmt)==SQLITE_ROW ){
14335 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
14337 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
14338 appendText(&sSelect, zDiv, 0);
14339 zDiv = " UNION ALL ";
14340 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
14341 if( sqlite3_stricmp(zDb, "main")!=0 ){
14342 appendText(&sSelect, zDb, '"');
14344 appendText(&sSelect, "NULL", 0);
14346 appendText(&sSelect, ",name) AS sql, type, tbl_name, name, rowid,", 0);
14347 appendText(&sSelect, zScNum, 0);
14348 appendText(&sSelect, " AS snum, ", 0);
14349 appendText(&sSelect, zDb, '\'');
14350 appendText(&sSelect, " AS sname FROM ", 0);
14351 appendText(&sSelect, zDb, '"');
14352 appendText(&sSelect, ".sqlite_master", 0);
14354 sqlite3_finalize(pStmt);
14355 #ifdef SQLITE_INTROSPECTION_PRAGMAS
14357 appendText(&sSelect,
14358 " UNION ALL SELECT shell_module_schema(name),"
14359 " 'table', name, name, name, 9e+99, 'main' FROM pragma_module_list", 0);
14362 appendText(&sSelect, ") WHERE ", 0);
14364 char *zQarg = sqlite3_mprintf("%Q", zName);
14365 int bGlob = strchr(zName, '*') != 0 || strchr(zName, '?') != 0 ||
14366 strchr(zName, '[') != 0;
14367 if( strchr(zName, '.') ){
14368 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
14370 appendText(&sSelect, "lower(tbl_name)", 0);
14372 appendText(&sSelect, bGlob ? " GLOB " : " LIKE ", 0);
14373 appendText(&sSelect, zQarg, 0);
14375 appendText(&sSelect, " ESCAPE '\\' ", 0);
14377 appendText(&sSelect, " AND ", 0);
14378 sqlite3_free(zQarg);
14380 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
14381 " ORDER BY snum, rowid", 0);
14383 utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
14385 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
14387 freeText(&sSelect);
14390 utf8_printf(stderr,"Error: %s\n", zErrMsg);
14391 sqlite3_free(zErrMsg);
14393 }else if( rc != SQLITE_OK ){
14394 raw_printf(stderr,"Error: querying schema information\n");
14401 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
14402 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
14403 sqlite3SelectTrace = (int)integerValue(azArg[1]);
14407 #if defined(SQLITE_ENABLE_SESSION)
14408 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
14409 OpenSession *pSession = &p->aSession[0];
14410 char **azCmd = &azArg[1];
14412 int nCmd = nArg - 1;
14414 if( nArg<=1 ) goto session_syntax_error;
14417 for(iSes=0; iSes<p->nSession; iSes++){
14418 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
14420 if( iSes<p->nSession ){
14421 pSession = &p->aSession[iSes];
14425 pSession = &p->aSession[0];
14430 /* .session attach TABLE
14431 ** Invoke the sqlite3session_attach() interface to attach a particular
14432 ** table so that it is never filtered.
14434 if( strcmp(azCmd[0],"attach")==0 ){
14435 if( nCmd!=2 ) goto session_syntax_error;
14436 if( pSession->p==0 ){
14438 raw_printf(stderr, "ERROR: No sessions are open\n");
14440 rc = sqlite3session_attach(pSession->p, azCmd[1]);
14442 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
14448 /* .session changeset FILE
14449 ** .session patchset FILE
14450 ** Write a changeset or patchset into a file. The file is overwritten.
14452 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
14454 if( nCmd!=2 ) goto session_syntax_error;
14455 if( pSession->p==0 ) goto session_not_open;
14456 out = fopen(azCmd[1], "wb");
14458 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
14462 if( azCmd[0][0]=='c' ){
14463 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
14465 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
14468 printf("Error: error code %d\n", rc);
14472 && fwrite(pChng, szChng, 1, out)!=1 ){
14473 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
14476 sqlite3_free(pChng);
14482 ** Close the identified session
14484 if( strcmp(azCmd[0], "close")==0 ){
14485 if( nCmd!=1 ) goto session_syntax_error;
14487 session_close(pSession);
14488 p->aSession[iSes] = p->aSession[--p->nSession];
14492 /* .session enable ?BOOLEAN?
14493 ** Query or set the enable flag
14495 if( strcmp(azCmd[0], "enable")==0 ){
14497 if( nCmd>2 ) goto session_syntax_error;
14498 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
14500 ii = sqlite3session_enable(pSession->p, ii);
14501 utf8_printf(p->out, "session %s enable flag = %d\n",
14502 pSession->zName, ii);
14506 /* .session filter GLOB ....
14507 ** Set a list of GLOB patterns of table names to be excluded.
14509 if( strcmp(azCmd[0], "filter")==0 ){
14511 if( nCmd<2 ) goto session_syntax_error;
14513 for(ii=0; ii<pSession->nFilter; ii++){
14514 sqlite3_free(pSession->azFilter[ii]);
14516 sqlite3_free(pSession->azFilter);
14517 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
14518 pSession->azFilter = sqlite3_malloc( nByte );
14519 if( pSession->azFilter==0 ){
14520 raw_printf(stderr, "Error: out or memory\n");
14523 for(ii=1; ii<nCmd; ii++){
14524 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
14526 pSession->nFilter = ii-1;
14530 /* .session indirect ?BOOLEAN?
14531 ** Query or set the indirect flag
14533 if( strcmp(azCmd[0], "indirect")==0 ){
14535 if( nCmd>2 ) goto session_syntax_error;
14536 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
14538 ii = sqlite3session_indirect(pSession->p, ii);
14539 utf8_printf(p->out, "session %s indirect flag = %d\n",
14540 pSession->zName, ii);
14544 /* .session isempty
14545 ** Determine if the session is empty
14547 if( strcmp(azCmd[0], "isempty")==0 ){
14549 if( nCmd!=1 ) goto session_syntax_error;
14551 ii = sqlite3session_isempty(pSession->p);
14552 utf8_printf(p->out, "session %s isempty flag = %d\n",
14553 pSession->zName, ii);
14558 ** List all currently open sessions
14560 if( strcmp(azCmd[0],"list")==0 ){
14561 for(i=0; i<p->nSession; i++){
14562 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
14566 /* .session open DB NAME
14567 ** Open a new session called NAME on the attached database DB.
14568 ** DB is normally "main".
14570 if( strcmp(azCmd[0],"open")==0 ){
14572 if( nCmd!=3 ) goto session_syntax_error;
14574 if( zName[0]==0 ) goto session_syntax_error;
14575 for(i=0; i<p->nSession; i++){
14576 if( strcmp(p->aSession[i].zName,zName)==0 ){
14577 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
14578 goto meta_command_exit;
14581 if( p->nSession>=ArraySize(p->aSession) ){
14582 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
14583 goto meta_command_exit;
14585 pSession = &p->aSession[p->nSession];
14586 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
14588 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
14590 goto meta_command_exit;
14592 pSession->nFilter = 0;
14593 sqlite3session_table_filter(pSession->p, session_filter, pSession);
14595 pSession->zName = sqlite3_mprintf("%s", zName);
14597 /* If no command name matches, show a syntax error */
14598 session_syntax_error:
14603 #ifdef SQLITE_DEBUG
14604 /* Undocumented commands for internal testing. Subject to change
14605 ** without notice. */
14606 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
14607 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
14609 for(i=1; i<nArg; i++){
14610 v = booleanValue(azArg[i]);
14611 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
14614 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
14615 int i; sqlite3_int64 v;
14616 for(i=1; i<nArg; i++){
14618 v = integerValue(azArg[i]);
14619 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
14620 utf8_printf(p->out, "%s", zBuf);
14626 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
14627 int bIsInit = 0; /* True to initialize the SELFTEST table */
14628 int bVerbose = 0; /* Verbose output */
14629 int bSelftestExists; /* True if SELFTEST already exists */
14630 int i, k; /* Loop counters */
14631 int nTest = 0; /* Number of tests runs */
14632 int nErr = 0; /* Number of errors seen */
14633 ShellText str; /* Answer for a query */
14634 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
14637 for(i=1; i<nArg; i++){
14638 const char *z = azArg[i];
14639 if( z[0]=='-' && z[1]=='-' ) z++;
14640 if( strcmp(z,"-init")==0 ){
14643 if( strcmp(z,"-v")==0 ){
14647 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
14648 azArg[i], azArg[0]);
14649 raw_printf(stderr, "Should be one of: --init -v\n");
14651 goto meta_command_exit;
14654 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
14656 bSelftestExists = 0;
14658 bSelftestExists = 1;
14661 createSelftestTable(p);
14662 bSelftestExists = 1;
14665 appendText(&str, "x", 0);
14666 for(k=bSelftestExists; k>=0; k--){
14668 rc = sqlite3_prepare_v2(p->db,
14669 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
14672 rc = sqlite3_prepare_v2(p->db,
14673 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
14674 " (1,'run','PRAGMA integrity_check','ok')",
14678 raw_printf(stderr, "Error querying the selftest table\n");
14680 sqlite3_finalize(pStmt);
14681 goto meta_command_exit;
14683 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
14684 int tno = sqlite3_column_int(pStmt, 0);
14685 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
14686 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
14687 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
14691 char *zQuote = sqlite3_mprintf("%q", zSql);
14692 printf("%d: %s %s\n", tno, zOp, zSql);
14693 sqlite3_free(zQuote);
14695 if( strcmp(zOp,"memo")==0 ){
14696 utf8_printf(p->out, "%s\n", zSql);
14698 if( strcmp(zOp,"run")==0 ){
14702 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
14705 utf8_printf(p->out, "Result: %s\n", str.z);
14707 if( rc || zErrMsg ){
14710 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
14711 sqlite3_free(zErrMsg);
14712 }else if( strcmp(zAns,str.z)!=0 ){
14715 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
14716 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
14720 utf8_printf(stderr,
14721 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
14725 } /* End loop over rows of content from SELFTEST */
14726 sqlite3_finalize(pStmt);
14727 } /* End loop over k */
14729 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
14732 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
14733 if( nArg<2 || nArg>3 ){
14734 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
14738 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
14739 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
14742 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
14743 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
14747 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
14748 const char *zLike = 0; /* Which table to checksum. 0 means everything */
14749 int i; /* Loop counter */
14750 int bSchema = 0; /* Also hash the schema */
14751 int bSeparate = 0; /* Hash each table separately */
14752 int iSize = 224; /* Hash algorithm to use */
14753 int bDebug = 0; /* Only show the query that would have run */
14754 sqlite3_stmt *pStmt; /* For querying tables names */
14755 char *zSql; /* SQL to be run */
14756 char *zSep; /* Separator */
14757 ShellText sSql; /* Complete SQL for the query to run the hash */
14758 ShellText sQuery; /* Set of queries used to read all content */
14760 for(i=1; i<nArg; i++){
14761 const char *z = azArg[i];
14764 if( z[0]=='-' ) z++;
14765 if( strcmp(z,"schema")==0 ){
14768 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
14769 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
14771 iSize = atoi(&z[5]);
14773 if( strcmp(z,"debug")==0 ){
14777 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
14778 azArg[i], azArg[0]);
14779 raw_printf(stderr, "Should be one of: --schema"
14780 " --sha3-224 --sha3-256 --sha3-384 --sha3-512\n");
14782 goto meta_command_exit;
14785 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
14787 goto meta_command_exit;
14791 if( sqlite3_strlike("sqlite\\_%", zLike, '\\')==0 ) bSchema = 1;
14795 zSql = "SELECT lower(name) FROM sqlite_master"
14796 " WHERE type='table' AND coalesce(rootpage,0)>1"
14797 " UNION ALL SELECT 'sqlite_master'"
14798 " ORDER BY 1 collate nocase";
14800 zSql = "SELECT lower(name) FROM sqlite_master"
14801 " WHERE type='table' AND coalesce(rootpage,0)>1"
14802 " AND name NOT LIKE 'sqlite_%'"
14803 " ORDER BY 1 collate nocase";
14805 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
14808 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
14810 while( SQLITE_ROW==sqlite3_step(pStmt) ){
14811 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
14812 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
14813 if( strncmp(zTab, "sqlite_",7)!=0 ){
14814 appendText(&sQuery,"SELECT * FROM ", 0);
14815 appendText(&sQuery,zTab,'"');
14816 appendText(&sQuery," NOT INDEXED;", 0);
14817 }else if( strcmp(zTab, "sqlite_master")==0 ){
14818 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
14819 " ORDER BY name;", 0);
14820 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
14821 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
14822 " ORDER BY name;", 0);
14823 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
14824 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
14825 " ORDER BY tbl,idx;", 0);
14826 }else if( strcmp(zTab, "sqlite_stat3")==0
14827 || strcmp(zTab, "sqlite_stat4")==0 ){
14828 appendText(&sQuery, "SELECT * FROM ", 0);
14829 appendText(&sQuery, zTab, 0);
14830 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
14832 appendText(&sSql, zSep, 0);
14833 appendText(&sSql, sQuery.z, '\'');
14835 appendText(&sSql, ",", 0);
14836 appendText(&sSql, zTab, '\'');
14839 sqlite3_finalize(pStmt);
14841 zSql = sqlite3_mprintf(
14843 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
14844 " FROM [sha3sum$query]",
14847 zSql = sqlite3_mprintf(
14849 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
14850 " FROM [sha3sum$query]",
14856 utf8_printf(p->out, "%s\n", zSql);
14858 shell_exec(p, zSql, 0);
14860 sqlite3_free(zSql);
14863 #ifndef SQLITE_NOHAVE_SYSTEM
14865 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
14870 raw_printf(stderr, "Usage: .system COMMAND\n");
14872 goto meta_command_exit;
14874 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
14875 for(i=2; i<nArg; i++){
14876 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
14880 sqlite3_free(zCmd);
14881 if( x ) raw_printf(stderr, "System command returns %d\n", x);
14883 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
14885 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
14886 static const char *azBool[] = { "off", "on", "trigger", "full"};
14889 raw_printf(stderr, "Usage: .show\n");
14891 goto meta_command_exit;
14893 utf8_printf(p->out, "%12.12s: %s\n","echo",
14894 azBool[ShellHasFlag(p, SHFLG_Echo)]);
14895 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
14896 utf8_printf(p->out, "%12.12s: %s\n","explain",
14897 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
14898 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
14899 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
14900 utf8_printf(p->out, "%12.12s: ", "nullvalue");
14901 output_c_string(p->out, p->nullValue);
14902 raw_printf(p->out, "\n");
14903 utf8_printf(p->out,"%12.12s: %s\n","output",
14904 strlen30(p->outfile) ? p->outfile : "stdout");
14905 utf8_printf(p->out,"%12.12s: ", "colseparator");
14906 output_c_string(p->out, p->colSeparator);
14907 raw_printf(p->out, "\n");
14908 utf8_printf(p->out,"%12.12s: ", "rowseparator");
14909 output_c_string(p->out, p->rowSeparator);
14910 raw_printf(p->out, "\n");
14911 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
14912 utf8_printf(p->out, "%12.12s: ", "width");
14913 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
14914 raw_printf(p->out, "%d ", p->colWidth[i]);
14916 raw_printf(p->out, "\n");
14917 utf8_printf(p->out, "%12.12s: %s\n", "filename",
14918 p->zDbFilename ? p->zDbFilename : "");
14921 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
14923 p->statsOn = (u8)booleanValue(azArg[1]);
14924 }else if( nArg==1 ){
14925 display_stats(p->db, p, 0);
14927 raw_printf(stderr, "Usage: .stats ?on|off?\n");
14932 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
14933 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
14934 || strncmp(azArg[0], "indexes", n)==0) )
14936 sqlite3_stmt *pStmt;
14943 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
14945 sqlite3_finalize(pStmt);
14946 return shellDatabaseError(p->db);
14949 if( nArg>2 && c=='i' ){
14950 /* It is an historical accident that the .indexes command shows an error
14951 ** when called with the wrong number of arguments whereas the .tables
14952 ** command does not. */
14953 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
14955 sqlite3_finalize(pStmt);
14956 goto meta_command_exit;
14958 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
14959 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
14960 if( zDbName==0 ) continue;
14961 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
14962 if( sqlite3_stricmp(zDbName, "main")==0 ){
14963 appendText(&s, "SELECT name FROM ", 0);
14965 appendText(&s, "SELECT ", 0);
14966 appendText(&s, zDbName, '\'');
14967 appendText(&s, "||'.'||name FROM ", 0);
14969 appendText(&s, zDbName, '"');
14970 appendText(&s, ".sqlite_master ", 0);
14972 appendText(&s," WHERE type IN ('table','view')"
14973 " AND name NOT LIKE 'sqlite_%'"
14974 " AND name LIKE ?1", 0);
14976 appendText(&s," WHERE type='index'"
14977 " AND tbl_name LIKE ?1", 0);
14980 rc = sqlite3_finalize(pStmt);
14981 appendText(&s, " ORDER BY 1", 0);
14982 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
14984 if( rc ) return shellDatabaseError(p->db);
14986 /* Run the SQL statement prepared by the above block. Store the results
14987 ** as an array of nul-terminated strings in azResult[]. */
14991 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
14993 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
14995 while( sqlite3_step(pStmt)==SQLITE_ROW ){
14996 if( nRow>=nAlloc ){
14998 int n2 = nAlloc*2 + 10;
14999 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
15000 if( azNew==0 ) shell_out_of_memory();
15004 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
15005 if( 0==azResult[nRow] ) shell_out_of_memory();
15008 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
15009 rc = shellDatabaseError(p->db);
15012 /* Pretty-print the contents of array azResult[] to the output */
15013 if( rc==0 && nRow>0 ){
15014 int len, maxlen = 0;
15016 int nPrintCol, nPrintRow;
15017 for(i=0; i<nRow; i++){
15018 len = strlen30(azResult[i]);
15019 if( len>maxlen ) maxlen = len;
15021 nPrintCol = 80/(maxlen+2);
15022 if( nPrintCol<1 ) nPrintCol = 1;
15023 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
15024 for(i=0; i<nPrintRow; i++){
15025 for(j=i; j<nRow; j+=nPrintRow){
15026 char *zSp = j<nPrintRow ? "" : " ";
15027 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
15028 azResult[j] ? azResult[j]:"");
15030 raw_printf(p->out, "\n");
15034 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
15035 sqlite3_free(azResult);
15038 /* Begin redirecting output to the file "testcase-out.txt" */
15039 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
15041 p->out = output_file_open("testcase-out.txt", 0);
15043 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
15046 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
15048 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
15052 #ifndef SQLITE_UNTESTABLE
15053 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 ){
15054 static const struct {
15055 const char *zCtrlName; /* Name of a test-control option */
15056 int ctrlCode; /* Integer code for that option */
15057 const char *zUsage; /* Usage notes */
15059 { "always", SQLITE_TESTCTRL_ALWAYS, "BOOLEAN" },
15060 { "assert", SQLITE_TESTCTRL_ASSERT, "BOOLEAN" },
15061 /*{ "benign_malloc_hooks",SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, "" },*/
15062 /*{ "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST, "" },*/
15063 { "byteorder", SQLITE_TESTCTRL_BYTEORDER, "" },
15064 /*{ "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL, "" }, */
15065 { "imposter", SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
15066 { "localtime_fault", SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN" },
15067 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN" },
15068 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK" },
15070 { "parser_coverage", SQLITE_TESTCTRL_PARSER_COVERAGE, "" },
15072 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE, "OFFSET " },
15073 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET, "" },
15074 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE, "" },
15075 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE, "" },
15076 { "reserve", SQLITE_TESTCTRL_RESERVE, "BYTES-OF-RESERVE" },
15080 int rc2 = 0; /* 0: usage. 1: %d 2: %x 3: no-output */
15083 const char *zCmd = 0;
15086 zCmd = nArg>=2 ? azArg[1] : "help";
15088 /* The argument can optionally begin with "-" or "--" */
15089 if( zCmd[0]=='-' && zCmd[1] ){
15091 if( zCmd[0]=='-' && zCmd[1] ) zCmd++;
15094 /* --help lists all test-controls */
15095 if( strcmp(zCmd,"help")==0 ){
15096 utf8_printf(p->out, "Available test-controls:\n");
15097 for(i=0; i<ArraySize(aCtrl); i++){
15098 utf8_printf(p->out, " .testctrl %s %s\n",
15099 aCtrl[i].zCtrlName, aCtrl[i].zUsage);
15102 goto meta_command_exit;
15105 /* convert testctrl text option to value. allow any unique prefix
15106 ** of the option name, or a numerical value. */
15107 n2 = strlen30(zCmd);
15108 for(i=0; i<ArraySize(aCtrl); i++){
15109 if( strncmp(zCmd, aCtrl[i].zCtrlName, n2)==0 ){
15111 testctrl = aCtrl[i].ctrlCode;
15114 utf8_printf(stderr, "Error: ambiguous test-control: \"%s\"\n"
15115 "Use \".testctrl --help\" for help\n", zCmd);
15117 goto meta_command_exit;
15122 utf8_printf(stderr,"Error: unknown test-control: %s\n"
15123 "Use \".testctrl --help\" for help\n", zCmd);
15127 /* sqlite3_test_control(int, db, int) */
15128 case SQLITE_TESTCTRL_OPTIMIZATIONS:
15129 case SQLITE_TESTCTRL_RESERVE:
15131 int opt = (int)strtol(azArg[2], 0, 0);
15132 rc2 = sqlite3_test_control(testctrl, p->db, opt);
15137 /* sqlite3_test_control(int) */
15138 case SQLITE_TESTCTRL_PRNG_SAVE:
15139 case SQLITE_TESTCTRL_PRNG_RESTORE:
15140 case SQLITE_TESTCTRL_PRNG_RESET:
15141 case SQLITE_TESTCTRL_BYTEORDER:
15143 rc2 = sqlite3_test_control(testctrl);
15144 isOk = testctrl==SQLITE_TESTCTRL_BYTEORDER ? 1 : 3;
15148 /* sqlite3_test_control(int, uint) */
15149 case SQLITE_TESTCTRL_PENDING_BYTE:
15151 unsigned int opt = (unsigned int)integerValue(azArg[2]);
15152 rc2 = sqlite3_test_control(testctrl, opt);
15157 /* sqlite3_test_control(int, int) */
15158 case SQLITE_TESTCTRL_ASSERT:
15159 case SQLITE_TESTCTRL_ALWAYS:
15161 int opt = booleanValue(azArg[2]);
15162 rc2 = sqlite3_test_control(testctrl, opt);
15167 /* sqlite3_test_control(int, int) */
15168 case SQLITE_TESTCTRL_LOCALTIME_FAULT:
15169 case SQLITE_TESTCTRL_NEVER_CORRUPT:
15171 int opt = booleanValue(azArg[2]);
15172 rc2 = sqlite3_test_control(testctrl, opt);
15177 case SQLITE_TESTCTRL_IMPOSTER:
15179 rc2 = sqlite3_test_control(testctrl, p->db,
15181 integerValue(azArg[3]),
15182 integerValue(azArg[4]));
15188 case SQLITE_TESTCTRL_PARSER_COVERAGE:
15190 sqlite3_test_control(testctrl, p->out);
15196 if( isOk==0 && iCtrl>=0 ){
15197 utf8_printf(p->out, "Usage: .testctrl %s %s\n", zCmd, aCtrl[iCtrl].zUsage);
15199 }else if( isOk==1 ){
15200 raw_printf(p->out, "%d\n", rc2);
15201 }else if( isOk==2 ){
15202 raw_printf(p->out, "0x%08x\n", rc2);
15205 #endif /* !defined(SQLITE_UNTESTABLE) */
15207 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
15209 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
15212 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
15214 enableTimer = booleanValue(azArg[1]);
15215 if( enableTimer && !HAS_TIMER ){
15216 raw_printf(stderr, "Error: timer not available on this system.\n");
15220 raw_printf(stderr, "Usage: .timer on|off\n");
15225 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
15228 raw_printf(stderr, "Usage: .trace FILE|off\n");
15230 goto meta_command_exit;
15232 output_file_close(p->traceOut);
15233 p->traceOut = output_file_open(azArg[1], 0);
15234 #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
15235 if( p->traceOut==0 ){
15236 sqlite3_trace_v2(p->db, 0, 0, 0);
15238 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
15243 #if SQLITE_USER_AUTHENTICATION
15244 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
15246 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
15248 goto meta_command_exit;
15251 if( strcmp(azArg[1],"login")==0 ){
15253 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
15255 goto meta_command_exit;
15257 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], strlen30(azArg[3]));
15259 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
15262 }else if( strcmp(azArg[1],"add")==0 ){
15264 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
15266 goto meta_command_exit;
15268 rc = sqlite3_user_add(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
15269 booleanValue(azArg[4]));
15271 raw_printf(stderr, "User-Add failed: %d\n", rc);
15274 }else if( strcmp(azArg[1],"edit")==0 ){
15276 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
15278 goto meta_command_exit;
15280 rc = sqlite3_user_change(p->db, azArg[2], azArg[3], strlen30(azArg[3]),
15281 booleanValue(azArg[4]));
15283 raw_printf(stderr, "User-Edit failed: %d\n", rc);
15286 }else if( strcmp(azArg[1],"delete")==0 ){
15288 raw_printf(stderr, "Usage: .user delete USER\n");
15290 goto meta_command_exit;
15292 rc = sqlite3_user_delete(p->db, azArg[2]);
15294 raw_printf(stderr, "User-Delete failed: %d\n", rc);
15298 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
15300 goto meta_command_exit;
15303 #endif /* SQLITE_USER_AUTHENTICATION */
15305 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
15306 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
15307 sqlite3_libversion(), sqlite3_sourceid());
15308 #if SQLITE_HAVE_ZLIB
15309 utf8_printf(p->out, "zlib version %s\n", zlibVersion());
15311 #define CTIMEOPT_VAL_(opt) #opt
15312 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
15313 #if defined(__clang__) && defined(__clang_major__)
15314 utf8_printf(p->out, "clang-" CTIMEOPT_VAL(__clang_major__) "."
15315 CTIMEOPT_VAL(__clang_minor__) "."
15316 CTIMEOPT_VAL(__clang_patchlevel__) "\n");
15317 #elif defined(_MSC_VER)
15318 utf8_printf(p->out, "msvc-" CTIMEOPT_VAL(_MSC_VER) "\n");
15319 #elif defined(__GNUC__) && defined(__VERSION__)
15320 utf8_printf(p->out, "gcc-" __VERSION__ "\n");
15324 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
15325 const char *zDbName = nArg==2 ? azArg[1] : "main";
15326 sqlite3_vfs *pVfs = 0;
15328 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
15330 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
15331 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
15332 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
15333 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
15338 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
15340 sqlite3_vfs *pCurrent = 0;
15342 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
15344 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
15345 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
15346 pVfs==pCurrent ? " <--- CURRENT" : "");
15347 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
15348 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
15349 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
15351 raw_printf(p->out, "-----------------------------------\n");
15356 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
15357 const char *zDbName = nArg==2 ? azArg[1] : "main";
15358 char *zVfsName = 0;
15360 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
15362 utf8_printf(p->out, "%s\n", zVfsName);
15363 sqlite3_free(zVfsName);
15368 #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
15369 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
15370 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
15374 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
15376 assert( nArg<=ArraySize(azArg) );
15377 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
15378 p->colWidth[j-1] = (int)integerValue(azArg[j]);
15383 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
15384 " \"%s\". Enter \".help\" for help\n", azArg[0]);
15391 if( p->outCount==0 ) output_reset(p);
15397 ** Return TRUE if a semicolon occurs anywhere in the first N characters
15400 static int line_contains_semicolon(const char *z, int N){
15402 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
15407 ** Test to see if a line consists entirely of whitespace.
15409 static int _all_whitespace(const char *z){
15411 if( IsSpace(z[0]) ) continue;
15412 if( *z=='/' && z[1]=='*' ){
15414 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
15415 if( *z==0 ) return 0;
15419 if( *z=='-' && z[1]=='-' ){
15421 while( *z && *z!='\n' ){ z++; }
15422 if( *z==0 ) return 1;
15431 ** Return TRUE if the line typed in is an SQL command terminator other
15432 ** than a semi-colon. The SQL Server style "go" command is understood
15433 ** as is the Oracle "/".
15435 static int line_is_command_terminator(const char *zLine){
15436 while( IsSpace(zLine[0]) ){ zLine++; };
15437 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
15438 return 1; /* Oracle */
15440 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
15441 && _all_whitespace(&zLine[2]) ){
15442 return 1; /* SQL Server */
15448 ** We need a default sqlite3_complete() implementation to use in case
15449 ** the shell is compiled with SQLITE_OMIT_COMPLETE. The default assumes
15450 ** any arbitrary text is a complete SQL statement. This is not very
15451 ** user-friendly, but it does seem to work.
15453 #ifdef SQLITE_OMIT_COMPLETE
15454 int sqlite3_complete(const char *zSql){ return 1; }
15458 ** Return true if zSql is a complete SQL statement. Return false if it
15459 ** ends in the middle of a string literal or C-style comment.
15461 static int line_is_complete(char *zSql, int nSql){
15463 if( zSql==0 ) return 1;
15466 rc = sqlite3_complete(zSql);
15472 ** Run a single line of SQL. Return the number of errors.
15474 static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
15479 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
15481 rc = shell_exec(p, zSql, &zErrMsg);
15483 if( rc || zErrMsg ){
15485 if( in!=0 || !stdin_is_interactive ){
15486 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
15487 "Error: near line %d:", startline);
15489 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
15492 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
15493 sqlite3_free(zErrMsg);
15496 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
15499 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
15500 raw_printf(p->out, "changes: %3d total_changes: %d\n",
15501 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
15508 ** Read input from *in and process it. If *in==0 then input
15509 ** is interactive - the user is typing it it. Otherwise, input
15510 ** is coming from a file or device. A prompt is issued and history
15511 ** is saved only if input is interactive. An interrupt signal will
15512 ** cause this routine to exit immediately, unless input is interactive.
15514 ** Return the number of errors.
15516 static int process_input(ShellState *p, FILE *in){
15517 char *zLine = 0; /* A single input line */
15518 char *zSql = 0; /* Accumulated SQL text */
15519 int nLine; /* Length of current line */
15520 int nSql = 0; /* Bytes of zSql[] used */
15521 int nAlloc = 0; /* Allocated zSql[] space */
15522 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
15523 int rc; /* Error code */
15524 int errCnt = 0; /* Number of errors seen */
15525 int lineno = 0; /* Current line number */
15526 int startline = 0; /* Line number for start of current input */
15528 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
15530 zLine = one_input_line(in, zLine, nSql>0);
15533 if( in==0 && stdin_is_interactive ) printf("\n");
15536 if( seenInterrupt ){
15541 if( nSql==0 && _all_whitespace(zLine) ){
15542 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
15545 if( zLine && (zLine[0]=='.' || zLine[0]=='#') && nSql==0 ){
15546 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
15547 if( zLine[0]=='.' ){
15548 rc = do_meta_command(zLine, p);
15549 if( rc==2 ){ /* exit requested */
15557 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
15558 memcpy(zLine,";",2);
15560 nLine = strlen30(zLine);
15561 if( nSql+nLine+2>=nAlloc ){
15562 nAlloc = nSql+nLine+100;
15563 zSql = realloc(zSql, nAlloc);
15564 if( zSql==0 ) shell_out_of_memory();
15569 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
15570 assert( nAlloc>0 && zSql!=0 );
15571 memcpy(zSql, zLine+i, nLine+1-i);
15572 startline = lineno;
15575 zSql[nSql++] = '\n';
15576 memcpy(zSql+nSql, zLine, nLine+1);
15579 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
15580 && sqlite3_complete(zSql) ){
15581 errCnt += runOneSqlLine(p, zSql, in, startline);
15589 }else if( nSql && _all_whitespace(zSql) ){
15590 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
15594 if( nSql && !_all_whitespace(zSql) ){
15595 errCnt += runOneSqlLine(p, zSql, in, startline);
15603 ** Return a pathname which is the user's home directory. A
15604 ** 0 return indicates an error of some kind.
15606 static char *find_home_dir(int clearFlag){
15607 static char *home_dir = NULL;
15613 if( home_dir ) return home_dir;
15615 #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
15616 && !defined(__RTP__) && !defined(_WRS_KERNEL)
15618 struct passwd *pwent;
15619 uid_t uid = getuid();
15620 if( (pwent=getpwuid(uid)) != NULL) {
15621 home_dir = pwent->pw_dir;
15626 #if defined(_WIN32_WCE)
15627 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
15632 #if defined(_WIN32) || defined(WIN32)
15634 home_dir = getenv("USERPROFILE");
15639 home_dir = getenv("HOME");
15642 #if defined(_WIN32) || defined(WIN32)
15644 char *zDrive, *zPath;
15646 zDrive = getenv("HOMEDRIVE");
15647 zPath = getenv("HOMEPATH");
15648 if( zDrive && zPath ){
15649 n = strlen30(zDrive) + strlen30(zPath) + 1;
15650 home_dir = malloc( n );
15651 if( home_dir==0 ) return 0;
15652 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
15659 #endif /* !_WIN32_WCE */
15662 int n = strlen30(home_dir) + 1;
15663 char *z = malloc( n );
15664 if( z ) memcpy(z, home_dir, n);
15672 ** Read input from the file given by sqliterc_override. Or if that
15673 ** parameter is NULL, take input from ~/.sqliterc
15675 ** Returns the number of errors.
15677 static void process_sqliterc(
15678 ShellState *p, /* Configuration data */
15679 const char *sqliterc_override /* Name of config file. NULL to use default */
15681 char *home_dir = NULL;
15682 const char *sqliterc = sqliterc_override;
15686 if (sqliterc == NULL) {
15687 home_dir = find_home_dir(0);
15689 raw_printf(stderr, "-- warning: cannot find home directory;"
15690 " cannot read ~/.sqliterc\n");
15693 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
15696 in = fopen(sqliterc,"rb");
15698 if( stdin_is_interactive ){
15699 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
15701 process_input(p,in);
15704 sqlite3_free(zBuf);
15708 ** Show available command line options
15710 static const char zOptions[] =
15711 #if defined(SQLITE_HAVE_ZLIB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
15712 " -A ARGS... run \".archive ARGS\" and exit\n"
15714 " -append append the database to the end of the file\n"
15715 " -ascii set output mode to 'ascii'\n"
15716 " -bail stop after hitting an error\n"
15717 " -batch force batch I/O\n"
15718 " -column set output mode to 'column'\n"
15719 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
15720 " -csv set output mode to 'csv'\n"
15721 " -echo print commands before execution\n"
15722 " -init FILENAME read/process named file\n"
15723 " -[no]header turn headers on or off\n"
15724 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
15725 " -heap SIZE Size of heap for memsys3 or memsys5\n"
15727 " -help show this message\n"
15728 " -html set output mode to HTML\n"
15729 " -interactive force interactive I/O\n"
15730 " -line set output mode to 'line'\n"
15731 " -list set output mode to 'list'\n"
15732 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
15733 " -mmap N default mmap size set to N\n"
15734 #ifdef SQLITE_ENABLE_MULTIPLEX
15735 " -multiplex enable the multiplexor VFS\n"
15737 " -newline SEP set output row separator. Default: '\\n'\n"
15738 " -nullvalue TEXT set text string for NULL values. Default ''\n"
15739 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
15740 " -quote set output mode to 'quote'\n"
15741 " -readonly open the database read-only\n"
15742 " -separator SEP set output column separator. Default: '|'\n"
15743 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
15744 " -sorterref SIZE sorter references threshold size\n"
15746 " -stats print memory stats before each finalize\n"
15747 " -version show SQLite version\n"
15748 " -vfs NAME use NAME as the default VFS\n"
15749 #ifdef SQLITE_ENABLE_VFSTRACE
15750 " -vfstrace enable tracing of all VFS calls\n"
15752 #ifdef SQLITE_HAVE_ZLIB
15753 " -zip open the file as a ZIP Archive\n"
15756 static void usage(int showDetail){
15757 utf8_printf(stderr,
15758 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
15759 "FILENAME is the name of an SQLite database. A new database is created\n"
15760 "if the file does not previously exist.\n", Argv0);
15762 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
15764 raw_printf(stderr, "Use the -help option for additional information\n");
15770 ** Internal check: Verify that the SQLite is uninitialized. Print a
15771 ** error message if it is initialized.
15773 static void verify_uninitialized(void){
15774 if( sqlite3_config(-1)==SQLITE_MISUSE ){
15775 utf8_printf(stdout, "WARNING: attempt to configure SQLite after"
15776 " initialization.\n");
15781 ** Initialize the state information in data
15783 static void main_init(ShellState *data) {
15784 memset(data, 0, sizeof(*data));
15785 data->normalMode = data->cMode = data->mode = MODE_List;
15786 data->autoExplain = 1;
15787 memcpy(data->colSeparator,SEP_Column, 2);
15788 memcpy(data->rowSeparator,SEP_Row, 2);
15789 data->showHeader = 0;
15790 data->shellFlgs = SHFLG_Lookaside;
15791 verify_uninitialized();
15792 sqlite3_config(SQLITE_CONFIG_URI, 1);
15793 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
15794 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
15795 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
15796 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
15800 ** Output text to the console in a font that attracts extra attention.
15803 static void printBold(const char *zText){
15804 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
15805 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
15806 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
15807 SetConsoleTextAttribute(out,
15808 FOREGROUND_RED|FOREGROUND_INTENSITY
15810 printf("%s", zText);
15811 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
15814 static void printBold(const char *zText){
15815 printf("\033[1m%s\033[0m", zText);
15820 ** Get the argument to an --option. Throw an error and die if no argument
15823 static char *cmdline_option_value(int argc, char **argv, int i){
15825 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
15826 argv[0], argv[argc-1]);
15832 #ifndef SQLITE_SHELL_IS_UTF8
15833 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
15834 # define SQLITE_SHELL_IS_UTF8 (0)
15836 # define SQLITE_SHELL_IS_UTF8 (1)
15840 #if SQLITE_SHELL_IS_UTF8
15841 int SQLITE_CDECL main(int argc, char **argv){
15843 int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
15848 const char *zInitFile = 0;
15851 int warnInmemoryDb = 0;
15855 const char *zVfs = 0; /* Value of -vfs command-line option */
15856 #if !SQLITE_SHELL_IS_UTF8
15857 char **argvToFree = 0;
15858 int argcToFree = 0;
15861 setBinaryMode(stdin, 0);
15862 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
15863 stdin_is_interactive = isatty(0);
15864 stdout_is_console = isatty(1);
15866 #if !defined(_WIN32_WCE)
15867 if( getenv("SQLITE_DEBUG_BREAK") ){
15868 if( isatty(0) && isatty(2) ){
15870 "attach debugger to process %d and press any key to continue.\n",
15874 #if defined(_WIN32) || defined(WIN32)
15876 #elif defined(SIGTRAP)
15883 #if USE_SYSTEM_SQLITE+0!=1
15884 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
15885 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
15886 sqlite3_sourceid(), SQLITE_SOURCE_ID);
15892 /* On Windows, we must translate command-line arguments into UTF-8.
15893 ** The SQLite memory allocator subsystem has to be enabled in order to
15894 ** do this. But we want to run an sqlite3_shutdown() afterwards so that
15895 ** subsequent sqlite3_config() calls will work. So copy all results into
15896 ** memory that does not come from the SQLite memory allocator.
15898 #if !SQLITE_SHELL_IS_UTF8
15899 sqlite3_initialize();
15900 argvToFree = malloc(sizeof(argv[0])*argc*2);
15902 argv = argvToFree + argc;
15903 if( argv==0 ) shell_out_of_memory();
15904 for(i=0; i<argc; i++){
15905 char *z = sqlite3_win32_unicode_to_utf8(wargv[i]);
15907 if( z==0 ) shell_out_of_memory();
15908 n = (int)strlen(z);
15909 argv[i] = malloc( n+1 );
15910 if( argv[i]==0 ) shell_out_of_memory();
15911 memcpy(argv[i], z, n+1);
15912 argvToFree[i] = argv[i];
15915 sqlite3_shutdown();
15918 assert( argc>=1 && argv && argv[0] );
15921 /* Make sure we have a valid signal handler early, before anything
15925 signal(SIGINT, interrupt_handler);
15926 #elif (defined(_WIN32) || defined(WIN32)) && !defined(_WIN32_WCE)
15927 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
15930 #ifdef SQLITE_SHELL_DBNAME_PROC
15932 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
15933 ** of a C-function that will provide the name of the database file. Use
15934 ** this compile-time option to embed this shell program in larger
15935 ** applications. */
15936 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
15937 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
15938 warnInmemoryDb = 0;
15942 /* Do an initial pass through the command-line argument to locate
15943 ** the name of the database file, the name of the initialization file,
15944 ** the size of the alternative malloc heap,
15945 ** and the first command to execute.
15947 verify_uninitialized();
15948 for(i=1; i<argc; i++){
15952 if( data.zDbFilename==0 ){
15953 data.zDbFilename = z;
15955 /* Excesss arguments are interpreted as SQL (or dot-commands) and
15956 ** mean that nothing is read from stdin */
15959 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
15960 if( azCmd==0 ) shell_out_of_memory();
15964 if( z[1]=='-' ) z++;
15965 if( strcmp(z,"-separator")==0
15966 || strcmp(z,"-nullvalue")==0
15967 || strcmp(z,"-newline")==0
15968 || strcmp(z,"-cmd")==0
15970 (void)cmdline_option_value(argc, argv, ++i);
15971 }else if( strcmp(z,"-init")==0 ){
15972 zInitFile = cmdline_option_value(argc, argv, ++i);
15973 }else if( strcmp(z,"-batch")==0 ){
15974 /* Need to check for batch mode here to so we can avoid printing
15975 ** informational messages (like from process_sqliterc) before
15976 ** we do the actual processing of arguments later in a second pass.
15978 stdin_is_interactive = 0;
15979 }else if( strcmp(z,"-heap")==0 ){
15980 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
15982 sqlite3_int64 szHeap;
15984 zSize = cmdline_option_value(argc, argv, ++i);
15985 szHeap = integerValue(zSize);
15986 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
15987 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
15989 (void)cmdline_option_value(argc, argv, ++i);
15991 }else if( strcmp(z,"-pagecache")==0 ){
15993 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
15994 if( sz>70000 ) sz = 70000;
15996 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
15997 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
15998 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
15999 data.shellFlgs |= SHFLG_Pagecache;
16000 }else if( strcmp(z,"-lookaside")==0 ){
16002 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
16004 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
16006 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
16007 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
16008 #ifdef SQLITE_ENABLE_VFSTRACE
16009 }else if( strcmp(z,"-vfstrace")==0 ){
16010 extern int vfstrace_register(
16011 const char *zTraceName,
16012 const char *zOldVfsName,
16013 int (*xOut)(const char*,void*),
16017 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
16019 #ifdef SQLITE_ENABLE_MULTIPLEX
16020 }else if( strcmp(z,"-multiplex")==0 ){
16021 extern int sqlite3_multiple_initialize(const char*,int);
16022 sqlite3_multiplex_initialize(0, 1);
16024 }else if( strcmp(z,"-mmap")==0 ){
16025 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
16026 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
16027 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
16028 }else if( strcmp(z,"-sorterref")==0 ){
16029 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
16030 sqlite3_config(SQLITE_CONFIG_SORTERREF_SIZE, (int)sz);
16032 }else if( strcmp(z,"-vfs")==0 ){
16033 zVfs = cmdline_option_value(argc, argv, ++i);
16034 #ifdef SQLITE_HAVE_ZLIB
16035 }else if( strcmp(z,"-zip")==0 ){
16036 data.openMode = SHELL_OPEN_ZIPFILE;
16038 }else if( strcmp(z,"-append")==0 ){
16039 data.openMode = SHELL_OPEN_APPENDVFS;
16040 }else if( strcmp(z,"-readonly")==0 ){
16041 data.openMode = SHELL_OPEN_READONLY;
16042 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16043 }else if( strncmp(z, "-A",2)==0 ){
16044 /* All remaining command-line arguments are passed to the ".archive"
16045 ** command, so ignore them */
16050 verify_uninitialized();
16053 #ifdef SQLITE_SHELL_INIT_PROC
16055 /* If the SQLITE_SHELL_INIT_PROC macro is defined, then it is the name
16056 ** of a C-function that will perform initialization actions on SQLite that
16057 ** occur just before or after sqlite3_initialize(). Use this compile-time
16058 ** option to embed this shell program in larger applications. */
16059 extern void SQLITE_SHELL_INIT_PROC(void);
16060 SQLITE_SHELL_INIT_PROC();
16063 /* All the sqlite3_config() calls have now been made. So it is safe
16064 ** to call sqlite3_initialize() and process any command line -vfs option. */
16065 sqlite3_initialize();
16069 sqlite3_vfs *pVfs = sqlite3_vfs_find(zVfs);
16071 sqlite3_vfs_register(pVfs, 1);
16073 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
16078 if( data.zDbFilename==0 ){
16079 #ifndef SQLITE_OMIT_MEMORYDB
16080 data.zDbFilename = ":memory:";
16081 warnInmemoryDb = argc==1;
16083 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
16088 sqlite3_appendvfs_init(0,0,0);
16090 /* Go ahead and open the database file if it already exists. If the
16091 ** file does not exist, delay opening it. This prevents empty database
16092 ** files from being created if a user mistypes the database name argument
16093 ** to the sqlite command-line tool.
16095 if( access(data.zDbFilename, 0)==0 ){
16099 /* Process the initialization file if there is one. If no -init option
16100 ** is given on the command line, look for a file named ~/.sqliterc and
16101 ** try to process it.
16103 process_sqliterc(&data,zInitFile);
16105 /* Make a second pass through the command-line argument and set
16106 ** options. This second pass is delayed until after the initialization
16107 ** file is processed so that the command-line arguments will override
16108 ** settings in the initialization file.
16110 for(i=1; i<argc; i++){
16112 if( z[0]!='-' ) continue;
16113 if( z[1]=='-' ){ z++; }
16114 if( strcmp(z,"-init")==0 ){
16116 }else if( strcmp(z,"-html")==0 ){
16117 data.mode = MODE_Html;
16118 }else if( strcmp(z,"-list")==0 ){
16119 data.mode = MODE_List;
16120 }else if( strcmp(z,"-quote")==0 ){
16121 data.mode = MODE_Quote;
16122 }else if( strcmp(z,"-line")==0 ){
16123 data.mode = MODE_Line;
16124 }else if( strcmp(z,"-column")==0 ){
16125 data.mode = MODE_Column;
16126 }else if( strcmp(z,"-csv")==0 ){
16127 data.mode = MODE_Csv;
16128 memcpy(data.colSeparator,",",2);
16129 #ifdef SQLITE_HAVE_ZLIB
16130 }else if( strcmp(z,"-zip")==0 ){
16131 data.openMode = SHELL_OPEN_ZIPFILE;
16133 }else if( strcmp(z,"-append")==0 ){
16134 data.openMode = SHELL_OPEN_APPENDVFS;
16135 }else if( strcmp(z,"-readonly")==0 ){
16136 data.openMode = SHELL_OPEN_READONLY;
16137 }else if( strcmp(z,"-ascii")==0 ){
16138 data.mode = MODE_Ascii;
16139 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
16141 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
16143 }else if( strcmp(z,"-separator")==0 ){
16144 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
16145 "%s",cmdline_option_value(argc,argv,++i));
16146 }else if( strcmp(z,"-newline")==0 ){
16147 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
16148 "%s",cmdline_option_value(argc,argv,++i));
16149 }else if( strcmp(z,"-nullvalue")==0 ){
16150 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
16151 "%s",cmdline_option_value(argc,argv,++i));
16152 }else if( strcmp(z,"-header")==0 ){
16153 data.showHeader = 1;
16154 }else if( strcmp(z,"-noheader")==0 ){
16155 data.showHeader = 0;
16156 }else if( strcmp(z,"-echo")==0 ){
16157 ShellSetFlag(&data, SHFLG_Echo);
16158 }else if( strcmp(z,"-eqp")==0 ){
16159 data.autoEQP = AUTOEQP_on;
16160 }else if( strcmp(z,"-eqpfull")==0 ){
16161 data.autoEQP = AUTOEQP_full;
16162 }else if( strcmp(z,"-stats")==0 ){
16164 }else if( strcmp(z,"-scanstats")==0 ){
16165 data.scanstatsOn = 1;
16166 }else if( strcmp(z,"-backslash")==0 ){
16167 /* Undocumented command-line option: -backslash
16168 ** Causes C-style backslash escapes to be evaluated in SQL statements
16169 ** prior to sending the SQL into SQLite. Useful for injecting
16170 ** crazy bytes in the middle of SQL statements for testing and debugging.
16172 ShellSetFlag(&data, SHFLG_Backslash);
16173 }else if( strcmp(z,"-bail")==0 ){
16175 }else if( strcmp(z,"-version")==0 ){
16176 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
16178 }else if( strcmp(z,"-interactive")==0 ){
16179 stdin_is_interactive = 1;
16180 }else if( strcmp(z,"-batch")==0 ){
16181 stdin_is_interactive = 0;
16182 }else if( strcmp(z,"-heap")==0 ){
16184 }else if( strcmp(z,"-pagecache")==0 ){
16186 }else if( strcmp(z,"-lookaside")==0 ){
16188 }else if( strcmp(z,"-mmap")==0 ){
16190 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
16191 }else if( strcmp(z,"-sorterref")==0 ){
16194 }else if( strcmp(z,"-vfs")==0 ){
16196 #ifdef SQLITE_ENABLE_VFSTRACE
16197 }else if( strcmp(z,"-vfstrace")==0 ){
16200 #ifdef SQLITE_ENABLE_MULTIPLEX
16201 }else if( strcmp(z,"-multiplex")==0 ){
16204 }else if( strcmp(z,"-help")==0 ){
16206 }else if( strcmp(z,"-cmd")==0 ){
16207 /* Run commands that follow -cmd first and separately from commands
16208 ** that simply appear on the command-line. This seems goofy. It would
16209 ** be better if all commands ran in the order that they appear. But
16210 ** we retain the goofy behavior for historical compatibility. */
16211 if( i==argc-1 ) break;
16212 z = cmdline_option_value(argc,argv,++i);
16214 rc = do_meta_command(z, &data);
16215 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
16218 rc = shell_exec(&data, z, &zErrMsg);
16220 utf8_printf(stderr,"Error: %s\n", zErrMsg);
16221 if( bail_on_error ) return rc!=0 ? rc : 1;
16223 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
16224 if( bail_on_error ) return rc;
16227 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
16228 }else if( strncmp(z, "-A", 2)==0 ){
16230 utf8_printf(stderr, "Error: cannot mix regular SQL or dot-commands"
16231 " with \"%s\"\n", z);
16234 open_db(&data, OPEN_DB_ZIPFILE);
16237 arDotCommand(&data, 1, argv+(i-1), argc-(i-1));
16239 arDotCommand(&data, 1, argv+i, argc-i);
16245 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
16246 raw_printf(stderr,"Use -help for a list of options.\n");
16249 data.cMode = data.mode;
16253 /* Run all arguments that do not begin with '-' as if they were separate
16254 ** command-line inputs, except for the argToSkip argument which contains
16255 ** the database filename.
16257 for(i=0; i<nCmd; i++){
16258 if( azCmd[i][0]=='.' ){
16259 rc = do_meta_command(azCmd[i], &data);
16260 if( rc ) return rc==2 ? 0 : rc;
16263 rc = shell_exec(&data, azCmd[i], &zErrMsg);
16265 utf8_printf(stderr,"Error: %s\n", zErrMsg);
16266 return rc!=0 ? rc : 1;
16268 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
16275 /* Run commands received from standard input
16277 if( stdin_is_interactive ){
16279 char *zHistory = 0;
16282 "SQLite version %s %.19s\n" /*extra-version-info*/
16283 "Enter \".help\" for usage hints.\n",
16284 sqlite3_libversion(), sqlite3_sourceid()
16286 if( warnInmemoryDb ){
16287 printf("Connected to a ");
16288 printBold("transient in-memory database");
16289 printf(".\nUse \".open FILENAME\" to reopen on a "
16290 "persistent database.\n");
16292 zHome = find_home_dir(0);
16294 nHistory = strlen30(zHome) + 20;
16295 if( (zHistory = malloc(nHistory))!=0 ){
16296 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
16299 if( zHistory ){ shell_read_history(zHistory); }
16300 #if HAVE_READLINE || HAVE_EDITLINE
16301 rl_attempted_completion_function = readline_completion;
16302 #elif HAVE_LINENOISE
16303 linenoiseSetCompletionCallback(linenoise_completion);
16305 rc = process_input(&data, 0);
16307 shell_stifle_history(2000);
16308 shell_write_history(zHistory);
16312 rc = process_input(&data, stdin);
16315 set_table_name(&data, 0);
16317 session_close_all(&data);
16320 sqlite3_free(data.zFreeOnClose);
16322 output_reset(&data);
16323 data.doXdgOpen = 0;
16324 clearTempFile(&data);
16325 #if !SQLITE_SHELL_IS_UTF8
16326 for(i=0; i<argcToFree; i++) free(argvToFree[i]);
16329 /* Clear the global data structure so that valgrind will detect memory
16331 memset(&data, 0, sizeof(data));