| /* |
| ** 2001 September 15 |
| ** |
| ** The author disclaims copyright to this source code. In place of |
| ** a legal notice, here is a blessing: |
| ** |
| ** May you do good and not evil. |
| ** May you find forgiveness for yourself and forgive others. |
| ** May you share freely, never taking more than you give. |
| ** |
| ************************************************************************* |
| ** This file contains code to implement the "sqlite" command line |
| ** utility for accessing SQLite databases. |
| */ |
| #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) |
| /* This needs to come before any includes for MSVC compiler */ |
| #define _CRT_SECURE_NO_WARNINGS |
| #endif |
| |
| /* |
| ** If requested, include the SQLite compiler options file for MSVC. |
| */ |
| #if defined(INCLUDE_MSVC_H) |
| #include "msvc.h" |
| #endif |
| |
| /* |
| ** No support for loadable extensions in VxWorks. |
| */ |
| #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION |
| # define SQLITE_OMIT_LOAD_EXTENSION 1 |
| #endif |
| |
| /* |
| ** Enable large-file support for fopen() and friends on unix. |
| */ |
| #ifndef SQLITE_DISABLE_LFS |
| # define _LARGE_FILE 1 |
| # ifndef _FILE_OFFSET_BITS |
| # define _FILE_OFFSET_BITS 64 |
| # endif |
| # define _LARGEFILE_SOURCE 1 |
| #endif |
| |
| #include <stdlib.h> |
| #include <string.h> |
| #include <stdio.h> |
| #include <assert.h> |
| #include "sqlite3.h" |
| #if SQLITE_USER_AUTHENTICATION |
| # include "sqlite3userauth.h" |
| #endif |
| #include <ctype.h> |
| #include <stdarg.h> |
| // Begin Android Add |
| #ifndef NO_ANDROID_FUNCS |
| #include <sqlite3_android.h> |
| #endif |
| // End Android Add |
| |
| #if !defined(_WIN32) && !defined(WIN32) |
| # include <signal.h> |
| # if !defined(__RTP__) && !defined(_WRS_KERNEL) |
| # include <pwd.h> |
| # endif |
| # include <unistd.h> |
| # include <sys/types.h> |
| #endif |
| |
| #if HAVE_READLINE |
| # include <readline/readline.h> |
| # include <readline/history.h> |
| #endif |
| |
| #if HAVE_EDITLINE |
| # include <editline/readline.h> |
| #endif |
| |
| #if HAVE_EDITLINE || HAVE_READLINE |
| |
| # define shell_add_history(X) add_history(X) |
| # define shell_read_history(X) read_history(X) |
| # define shell_write_history(X) write_history(X) |
| # define shell_stifle_history(X) stifle_history(X) |
| # define shell_readline(X) readline(X) |
| |
| #elif HAVE_LINENOISE |
| |
| # include "linenoise.h" |
| # define shell_add_history(X) linenoiseHistoryAdd(X) |
| # define shell_read_history(X) linenoiseHistoryLoad(X) |
| # define shell_write_history(X) linenoiseHistorySave(X) |
| # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) |
| # define shell_readline(X) linenoise(X) |
| |
| #else |
| |
| # define shell_read_history(X) |
| # define shell_write_history(X) |
| # define shell_stifle_history(X) |
| |
| # define SHELL_USE_LOCAL_GETLINE 1 |
| #endif |
| |
| |
| #if defined(_WIN32) || defined(WIN32) |
| # include <io.h> |
| # include <fcntl.h> |
| #define isatty(h) _isatty(h) |
| #ifndef access |
| # define access(f,m) _access((f),(m)) |
| #endif |
| #undef popen |
| #define popen _popen |
| #undef pclose |
| #define pclose _pclose |
| #else |
| /* Make sure isatty() has a prototype. |
| */ |
| extern int isatty(int); |
| |
| #if !defined(__RTP__) && !defined(_WRS_KERNEL) |
| /* popen and pclose are not C89 functions and so are sometimes omitted from |
| ** the <stdio.h> header */ |
| extern FILE *popen(const char*,const char*); |
| extern int pclose(FILE*); |
| #else |
| # define SQLITE_OMIT_POPEN 1 |
| #endif |
| |
| #endif |
| |
| #if defined(_WIN32_WCE) |
| /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() |
| * thus we always assume that we have a console. That can be |
| * overridden with the -batch command line option. |
| */ |
| #define isatty(x) 1 |
| #endif |
| |
| /* ctype macros that work with signed characters */ |
| #define IsSpace(X) isspace((unsigned char)X) |
| #define IsDigit(X) isdigit((unsigned char)X) |
| #define ToLower(X) (char)tolower((unsigned char)X) |
| |
| /* On Windows, we normally run with output mode of TEXT so that \n characters |
| ** are automatically translated into \r\n. However, this behavior needs |
| ** to be disabled in some cases (ex: when generating CSV output and when |
| ** rendering quoted strings that contain \n characters). The following |
| ** routines take care of that. |
| */ |
| #if defined(_WIN32) || defined(WIN32) |
| static void setBinaryMode(FILE *out){ |
| fflush(out); |
| _setmode(_fileno(out), _O_BINARY); |
| } |
| static void setTextMode(FILE *out){ |
| fflush(out); |
| _setmode(_fileno(out), _O_TEXT); |
| } |
| #else |
| # define setBinaryMode(X) |
| # define setTextMode(X) |
| #endif |
| |
| |
| /* True if the timer is enabled */ |
| static int enableTimer = 0; |
| |
| /* Return the current wall-clock time */ |
| static sqlite3_int64 timeOfDay(void){ |
| static sqlite3_vfs *clockVfs = 0; |
| sqlite3_int64 t; |
| if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); |
| if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){ |
| clockVfs->xCurrentTimeInt64(clockVfs, &t); |
| }else{ |
| double r; |
| clockVfs->xCurrentTime(clockVfs, &r); |
| t = (sqlite3_int64)(r*86400000.0); |
| } |
| return t; |
| } |
| |
| #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) |
| #include <sys/time.h> |
| #include <sys/resource.h> |
| |
| /* VxWorks does not support getrusage() as far as we can determine */ |
| #if defined(_WRS_KERNEL) || defined(__RTP__) |
| struct rusage { |
| struct timeval ru_utime; /* user CPU time used */ |
| struct timeval ru_stime; /* system CPU time used */ |
| }; |
| #define getrusage(A,B) memset(B,0,sizeof(*B)) |
| #endif |
| |
| /* Saved resource information for the beginning of an operation */ |
| static struct rusage sBegin; /* CPU time at start */ |
| static sqlite3_int64 iBegin; /* Wall-clock time at start */ |
| |
| /* |
| ** Begin timing an operation |
| */ |
| static void beginTimer(void){ |
| if( enableTimer ){ |
| getrusage(RUSAGE_SELF, &sBegin); |
| iBegin = timeOfDay(); |
| } |
| } |
| |
| /* Return the difference of two time_structs in seconds */ |
| static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ |
| return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + |
| (double)(pEnd->tv_sec - pStart->tv_sec); |
| } |
| |
| /* |
| ** Print the timing results. |
| */ |
| static void endTimer(void){ |
| if( enableTimer ){ |
| sqlite3_int64 iEnd = timeOfDay(); |
| struct rusage sEnd; |
| getrusage(RUSAGE_SELF, &sEnd); |
| printf("Run Time: real %.3f user %f sys %f\n", |
| (iEnd - iBegin)*0.001, |
| timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), |
| timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); |
| } |
| } |
| |
| #define BEGIN_TIMER beginTimer() |
| #define END_TIMER endTimer() |
| #define HAS_TIMER 1 |
| |
| #elif (defined(_WIN32) || defined(WIN32)) |
| |
| #include <windows.h> |
| |
| /* Saved resource information for the beginning of an operation */ |
| static HANDLE hProcess; |
| static FILETIME ftKernelBegin; |
| static FILETIME ftUserBegin; |
| static sqlite3_int64 ftWallBegin; |
| typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, |
| LPFILETIME, LPFILETIME); |
| static GETPROCTIMES getProcessTimesAddr = NULL; |
| |
| /* |
| ** Check to see if we have timer support. Return 1 if necessary |
| ** support found (or found previously). |
| */ |
| static int hasTimer(void){ |
| if( getProcessTimesAddr ){ |
| return 1; |
| } else { |
| /* GetProcessTimes() isn't supported in WIN95 and some other Windows |
| ** versions. See if the version we are running on has it, and if it |
| ** does, save off a pointer to it and the current process handle. |
| */ |
| hProcess = GetCurrentProcess(); |
| if( hProcess ){ |
| HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); |
| if( NULL != hinstLib ){ |
| getProcessTimesAddr = |
| (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); |
| if( NULL != getProcessTimesAddr ){ |
| return 1; |
| } |
| FreeLibrary(hinstLib); |
| } |
| } |
| } |
| return 0; |
| } |
| |
| /* |
| ** Begin timing an operation |
| */ |
| static void beginTimer(void){ |
| if( enableTimer && getProcessTimesAddr ){ |
| FILETIME ftCreation, ftExit; |
| getProcessTimesAddr(hProcess,&ftCreation,&ftExit, |
| &ftKernelBegin,&ftUserBegin); |
| ftWallBegin = timeOfDay(); |
| } |
| } |
| |
| /* Return the difference of two FILETIME structs in seconds */ |
| static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ |
| sqlite_int64 i64Start = *((sqlite_int64 *) pStart); |
| sqlite_int64 i64End = *((sqlite_int64 *) pEnd); |
| return (double) ((i64End - i64Start) / 10000000.0); |
| } |
| |
| /* |
| ** Print the timing results. |
| */ |
| static void endTimer(void){ |
| if( enableTimer && getProcessTimesAddr){ |
| FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; |
| sqlite3_int64 ftWallEnd = timeOfDay(); |
| getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); |
| printf("Run Time: real %.3f user %f sys %f\n", |
| (ftWallEnd - ftWallBegin)*0.001, |
| timeDiff(&ftUserBegin, &ftUserEnd), |
| timeDiff(&ftKernelBegin, &ftKernelEnd)); |
| } |
| } |
| |
| #define BEGIN_TIMER beginTimer() |
| #define END_TIMER endTimer() |
| #define HAS_TIMER hasTimer() |
| |
| #else |
| #define BEGIN_TIMER |
| #define END_TIMER |
| #define HAS_TIMER 0 |
| #endif |
| |
| /* |
| ** Used to prevent warnings about unused parameters |
| */ |
| #define UNUSED_PARAMETER(x) (void)(x) |
| |
| /* |
| ** If the following flag is set, then command execution stops |
| ** at an error if we are not interactive. |
| */ |
| static int bail_on_error = 0; |
| |
| /* |
| ** Threat stdin as an interactive input if the following variable |
| ** is true. Otherwise, assume stdin is connected to a file or pipe. |
| */ |
| static int stdin_is_interactive = 1; |
| |
| /* |
| ** The following is the open SQLite database. We make a pointer |
| ** to this database a static variable so that it can be accessed |
| ** by the SIGINT handler to interrupt database processing. |
| */ |
| static sqlite3 *globalDb = 0; |
| |
| /* |
| ** True if an interrupt (Control-C) has been received. |
| */ |
| static volatile int seenInterrupt = 0; |
| |
| /* |
| ** This is the name of our program. It is set in main(), used |
| ** in a number of other places, mostly for error messages. |
| */ |
| static char *Argv0; |
| |
| /* |
| ** Prompt strings. Initialized in main. Settable with |
| ** .prompt main continue |
| */ |
| static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ |
| static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ |
| |
| /* |
| ** Write I/O traces to the following stream. |
| */ |
| #ifdef SQLITE_ENABLE_IOTRACE |
| static FILE *iotrace = 0; |
| #endif |
| |
| /* |
| ** This routine works like printf in that its first argument is a |
| ** format string and subsequent arguments are values to be substituted |
| ** in place of % fields. The result of formatting this string |
| ** is written to iotrace. |
| */ |
| #ifdef SQLITE_ENABLE_IOTRACE |
| static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ |
| va_list ap; |
| char *z; |
| if( iotrace==0 ) return; |
| va_start(ap, zFormat); |
| z = sqlite3_vmprintf(zFormat, ap); |
| va_end(ap); |
| fprintf(iotrace, "%s", z); |
| sqlite3_free(z); |
| } |
| #endif |
| |
| |
| /* |
| ** Determines if a string is a number of not. |
| */ |
| static int isNumber(const char *z, int *realnum){ |
| if( *z=='-' || *z=='+' ) z++; |
| if( !IsDigit(*z) ){ |
| return 0; |
| } |
| z++; |
| if( realnum ) *realnum = 0; |
| while( IsDigit(*z) ){ z++; } |
| if( *z=='.' ){ |
| z++; |
| if( !IsDigit(*z) ) return 0; |
| while( IsDigit(*z) ){ z++; } |
| if( realnum ) *realnum = 1; |
| } |
| if( *z=='e' || *z=='E' ){ |
| z++; |
| if( *z=='+' || *z=='-' ) z++; |
| if( !IsDigit(*z) ) return 0; |
| while( IsDigit(*z) ){ z++; } |
| if( realnum ) *realnum = 1; |
| } |
| return *z==0; |
| } |
| |
| /* |
| ** A global char* and an SQL function to access its current value |
| ** from within an SQL statement. This program used to use the |
| ** sqlite_exec_printf() API to substitue a string into an SQL statement. |
| ** The correct way to do this with sqlite3 is to use the bind API, but |
| ** since the shell is built around the callback paradigm it would be a lot |
| ** of work. Instead just use this hack, which is quite harmless. |
| */ |
| static const char *zShellStatic = 0; |
| static void shellstaticFunc( |
| sqlite3_context *context, |
| int argc, |
| sqlite3_value **argv |
| ){ |
| assert( 0==argc ); |
| assert( zShellStatic ); |
| UNUSED_PARAMETER(argc); |
| UNUSED_PARAMETER(argv); |
| sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); |
| } |
| |
| |
| /* |
| ** This routine reads a line of text from FILE in, stores |
| ** the text in memory obtained from malloc() and returns a pointer |
| ** to the text. NULL is returned at end of file, or if malloc() |
| ** fails. |
| ** |
| ** If zLine is not NULL then it is a malloced buffer returned from |
| ** a previous call to this routine that may be reused. |
| */ |
| static char *local_getline(char *zLine, FILE *in){ |
| int nLine = zLine==0 ? 0 : 100; |
| int n = 0; |
| |
| while( 1 ){ |
| if( n+100>nLine ){ |
| nLine = nLine*2 + 100; |
| zLine = realloc(zLine, nLine); |
| if( zLine==0 ) return 0; |
| } |
| if( fgets(&zLine[n], nLine - n, in)==0 ){ |
| if( n==0 ){ |
| free(zLine); |
| return 0; |
| } |
| zLine[n] = 0; |
| break; |
| } |
| while( zLine[n] ) n++; |
| if( n>0 && zLine[n-1]=='\n' ){ |
| n--; |
| if( n>0 && zLine[n-1]=='\r' ) n--; |
| zLine[n] = 0; |
| break; |
| } |
| } |
| return zLine; |
| } |
| |
| /* |
| ** Retrieve a single line of input text. |
| ** |
| ** If in==0 then read from standard input and prompt before each line. |
| ** If isContinuation is true, then a continuation prompt is appropriate. |
| ** If isContinuation is zero, then the main prompt should be used. |
| ** |
| ** If zPrior is not NULL then it is a buffer from a prior call to this |
| ** routine that can be reused. |
| ** |
| ** The result is stored in space obtained from malloc() and must either |
| ** be freed by the caller or else passed back into this routine via the |
| ** zPrior argument for reuse. |
| */ |
| static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ |
| char *zPrompt; |
| char *zResult; |
| if( in!=0 ){ |
| zResult = local_getline(zPrior, in); |
| }else{ |
| zPrompt = isContinuation ? continuePrompt : mainPrompt; |
| #if SHELL_USE_LOCAL_GETLINE |
| printf("%s", zPrompt); |
| fflush(stdout); |
| zResult = local_getline(zPrior, stdin); |
| #else |
| free(zPrior); |
| zResult = shell_readline(zPrompt); |
| if( zResult && *zResult ) shell_add_history(zResult); |
| #endif |
| } |
| return zResult; |
| } |
| |
| /* |
| ** Shell output mode information from before ".explain on", |
| ** saved so that it can be restored by ".explain off" |
| */ |
| typedef struct SavedModeInfo SavedModeInfo; |
| struct SavedModeInfo { |
| int valid; /* Is there legit data in here? */ |
| int mode; /* Mode prior to ".explain on" */ |
| int showHeader; /* The ".header" setting prior to ".explain on" */ |
| int colWidth[100]; /* Column widths prior to ".explain on" */ |
| }; |
| |
| /* |
| ** State information about the database connection is contained in an |
| ** instance of the following structure. |
| */ |
| typedef struct ShellState ShellState; |
| struct ShellState { |
| sqlite3 *db; /* The database */ |
| int echoOn; /* True to echo input commands */ |
| int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ |
| int statsOn; /* True to display memory stats before each finalize */ |
| int scanstatsOn; /* True to display scan stats before each finalize */ |
| int backslashOn; /* Resolve C-style \x escapes in SQL input text */ |
| int outCount; /* Revert to stdout when reaching zero */ |
| int cnt; /* Number of records displayed so far */ |
| FILE *out; /* Write results here */ |
| FILE *traceOut; /* Output for sqlite3_trace() */ |
| int nErr; /* Number of errors seen */ |
| int mode; /* An output mode setting */ |
| int writableSchema; /* True if PRAGMA writable_schema=ON */ |
| int showHeader; /* True to show column names in List or Column mode */ |
| unsigned shellFlgs; /* Various flags */ |
| char *zDestTable; /* Name of destination table when MODE_Insert */ |
| char colSeparator[20]; /* Column separator character for several modes */ |
| char rowSeparator[20]; /* Row separator character for MODE_Ascii */ |
| int colWidth[100]; /* Requested width of each column when in column mode*/ |
| int actualWidth[100]; /* Actual width of each column */ |
| char nullValue[20]; /* The text to print when a NULL comes back from |
| ** the database */ |
| SavedModeInfo normalMode;/* Holds the mode just before .explain ON */ |
| char outfile[FILENAME_MAX]; /* Filename for *out */ |
| const char *zDbFilename; /* name of the database file */ |
| char *zFreeOnClose; /* Filename to free when closing */ |
| const char *zVfs; /* Name of VFS to use */ |
| sqlite3_stmt *pStmt; /* Current statement if any. */ |
| FILE *pLog; /* Write log output here */ |
| int *aiIndent; /* Array of indents used in MODE_Explain */ |
| int nIndent; /* Size of array aiIndent[] */ |
| int iIndent; /* Index of current op in aiIndent[] */ |
| }; |
| |
| /* |
| ** These are the allowed shellFlgs values |
| */ |
| #define SHFLG_Scratch 0x00001 /* The --scratch option is used */ |
| #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */ |
| #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */ |
| |
| /* |
| ** These are the allowed modes. |
| */ |
| #define MODE_Line 0 /* One column per line. Blank line between records */ |
| #define MODE_Column 1 /* One record per line in neat columns */ |
| #define MODE_List 2 /* One record per line with a separator */ |
| #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ |
| #define MODE_Html 4 /* Generate an XHTML table */ |
| #define MODE_Insert 5 /* Generate SQL "insert" statements */ |
| #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */ |
| #define MODE_Csv 7 /* Quote strings, numbers are plain */ |
| #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */ |
| #define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */ |
| |
| static const char *modeDescr[] = { |
| "line", |
| "column", |
| "list", |
| "semi", |
| "html", |
| "insert", |
| "tcl", |
| "csv", |
| "explain", |
| "ascii", |
| }; |
| |
| /* |
| ** These are the column/row/line separators used by the various |
| ** import/export modes. |
| */ |
| #define SEP_Column "|" |
| #define SEP_Row "\n" |
| #define SEP_Tab "\t" |
| #define SEP_Space " " |
| #define SEP_Comma "," |
| #define SEP_CrLf "\r\n" |
| #define SEP_Unit "\x1F" |
| #define SEP_Record "\x1E" |
| |
| /* |
| ** Number of elements in an array |
| */ |
| #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) |
| |
| /* |
| ** Compute a string length that is limited to what can be stored in |
| ** lower 30 bits of a 32-bit signed integer. |
| */ |
| static int strlen30(const char *z){ |
| const char *z2 = z; |
| while( *z2 ){ z2++; } |
| return 0x3fffffff & (int)(z2 - z); |
| } |
| |
| /* |
| ** A callback for the sqlite3_log() interface. |
| */ |
| static void shellLog(void *pArg, int iErrCode, const char *zMsg){ |
| ShellState *p = (ShellState*)pArg; |
| if( p->pLog==0 ) return; |
| fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); |
| fflush(p->pLog); |
| } |
| |
| /* |
| ** Output the given string as a hex-encoded blob (eg. X'1234' ) |
| */ |
| static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ |
| int i; |
| char *zBlob = (char *)pBlob; |
| fprintf(out,"X'"); |
| for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]&0xff); } |
| fprintf(out,"'"); |
| } |
| |
| /* |
| ** Output the given string as a quoted string using SQL quoting conventions. |
| */ |
| static void output_quoted_string(FILE *out, const char *z){ |
| int i; |
| int nSingle = 0; |
| setBinaryMode(out); |
| for(i=0; z[i]; i++){ |
| if( z[i]=='\'' ) nSingle++; |
| } |
| if( nSingle==0 ){ |
| fprintf(out,"'%s'",z); |
| }else{ |
| fprintf(out,"'"); |
| while( *z ){ |
| for(i=0; z[i] && z[i]!='\''; i++){} |
| if( i==0 ){ |
| fprintf(out,"''"); |
| z++; |
| }else if( z[i]=='\'' ){ |
| fprintf(out,"%.*s''",i,z); |
| z += i+1; |
| }else{ |
| fprintf(out,"%s",z); |
| break; |
| } |
| } |
| fprintf(out,"'"); |
| } |
| setTextMode(out); |
| } |
| |
| /* |
| ** Output the given string as a quoted according to C or TCL quoting rules. |
| */ |
| static void output_c_string(FILE *out, const char *z){ |
| unsigned int c; |
| fputc('"', out); |
| while( (c = *(z++))!=0 ){ |
| if( c=='\\' ){ |
| fputc(c, out); |
| fputc(c, out); |
| }else if( c=='"' ){ |
| fputc('\\', out); |
| fputc('"', out); |
| }else if( c=='\t' ){ |
| fputc('\\', out); |
| fputc('t', out); |
| }else if( c=='\n' ){ |
| fputc('\\', out); |
| fputc('n', out); |
| }else if( c=='\r' ){ |
| fputc('\\', out); |
| fputc('r', out); |
| }else if( !isprint(c&0xff) ){ |
| fprintf(out, "\\%03o", c&0xff); |
| }else{ |
| fputc(c, out); |
| } |
| } |
| fputc('"', out); |
| } |
| |
| /* |
| ** Output the given string with characters that are special to |
| ** HTML escaped. |
| */ |
| static void output_html_string(FILE *out, const char *z){ |
| int i; |
| if( z==0 ) z = ""; |
| while( *z ){ |
| for(i=0; z[i] |
| && z[i]!='<' |
| && z[i]!='&' |
| && z[i]!='>' |
| && z[i]!='\"' |
| && z[i]!='\''; |
| i++){} |
| if( i>0 ){ |
| fprintf(out,"%.*s",i,z); |
| } |
| if( z[i]=='<' ){ |
| fprintf(out,"<"); |
| }else if( z[i]=='&' ){ |
| fprintf(out,"&"); |
| }else if( z[i]=='>' ){ |
| fprintf(out,">"); |
| }else if( z[i]=='\"' ){ |
| fprintf(out,"""); |
| }else if( z[i]=='\'' ){ |
| fprintf(out,"'"); |
| }else{ |
| break; |
| } |
| z += i + 1; |
| } |
| } |
| |
| /* |
| ** If a field contains any character identified by a 1 in the following |
| ** array, then the string must be quoted for CSV. |
| */ |
| static const char needCsvQuote[] = { |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
| }; |
| |
| /* |
| ** Output a single term of CSV. Actually, p->colSeparator is used for |
| ** the separator, which may or may not be a comma. p->nullValue is |
| ** the null value. Strings are quoted if necessary. The separator |
| ** is only issued if bSep is true. |
| */ |
| static void output_csv(ShellState *p, const char *z, int bSep){ |
| FILE *out = p->out; |
| if( z==0 ){ |
| fprintf(out,"%s",p->nullValue); |
| }else{ |
| int i; |
| int nSep = strlen30(p->colSeparator); |
| for(i=0; z[i]; i++){ |
| if( needCsvQuote[((unsigned char*)z)[i]] |
| || (z[i]==p->colSeparator[0] && |
| (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ |
| i = 0; |
| break; |
| } |
| } |
| if( i==0 ){ |
| putc('"', out); |
| for(i=0; z[i]; i++){ |
| if( z[i]=='"' ) putc('"', out); |
| putc(z[i], out); |
| } |
| putc('"', out); |
| }else{ |
| fprintf(out, "%s", z); |
| } |
| } |
| if( bSep ){ |
| fprintf(p->out, "%s", p->colSeparator); |
| } |
| } |
| |
| #ifdef SIGINT |
| /* |
| ** This routine runs when the user presses Ctrl-C |
| */ |
| static void interrupt_handler(int NotUsed){ |
| UNUSED_PARAMETER(NotUsed); |
| seenInterrupt++; |
| if( seenInterrupt>2 ) exit(1); |
| if( globalDb ) sqlite3_interrupt(globalDb); |
| } |
| #endif |
| |
| /* |
| ** This is the callback routine that the shell |
| ** invokes for each row of a query result. |
| */ |
| static int shell_callback( |
| void *pArg, |
| int nArg, /* Number of result columns */ |
| char **azArg, /* Text of each result column */ |
| char **azCol, /* Column names */ |
| int *aiType /* Column types */ |
| ){ |
| int i; |
| ShellState *p = (ShellState*)pArg; |
| |
| switch( p->mode ){ |
| case MODE_Line: { |
| int w = 5; |
| if( azArg==0 ) break; |
| for(i=0; i<nArg; i++){ |
| int len = strlen30(azCol[i] ? azCol[i] : ""); |
| if( len>w ) w = len; |
| } |
| if( p->cnt++>0 ) fprintf(p->out, "%s", p->rowSeparator); |
| for(i=0; i<nArg; i++){ |
| fprintf(p->out,"%*s = %s%s", w, azCol[i], |
| azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); |
| } |
| break; |
| } |
| case MODE_Explain: |
| case MODE_Column: { |
| if( p->cnt++==0 ){ |
| for(i=0; i<nArg; i++){ |
| int w, n; |
| if( i<ArraySize(p->colWidth) ){ |
| w = p->colWidth[i]; |
| }else{ |
| w = 0; |
| } |
| if( w==0 ){ |
| w = strlen30(azCol[i] ? azCol[i] : ""); |
| if( w<10 ) w = 10; |
| n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue); |
| if( w<n ) w = n; |
| } |
| if( i<ArraySize(p->actualWidth) ){ |
| p->actualWidth[i] = w; |
| } |
| if( p->showHeader ){ |
| if( w<0 ){ |
| fprintf(p->out,"%*.*s%s",-w,-w,azCol[i], |
| i==nArg-1 ? p->rowSeparator : " "); |
| }else{ |
| fprintf(p->out,"%-*.*s%s",w,w,azCol[i], |
| i==nArg-1 ? p->rowSeparator : " "); |
| } |
| } |
| } |
| if( p->showHeader ){ |
| for(i=0; i<nArg; i++){ |
| int w; |
| if( i<ArraySize(p->actualWidth) ){ |
| w = p->actualWidth[i]; |
| if( w<0 ) w = -w; |
| }else{ |
| w = 10; |
| } |
| fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------" |
| "----------------------------------------------------------", |
| i==nArg-1 ? p->rowSeparator : " "); |
| } |
| } |
| } |
| if( azArg==0 ) break; |
| for(i=0; i<nArg; i++){ |
| int w; |
| if( i<ArraySize(p->actualWidth) ){ |
| w = p->actualWidth[i]; |
| }else{ |
| w = 10; |
| } |
| if( p->mode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){ |
| w = strlen30(azArg[i]); |
| } |
| if( i==1 && p->aiIndent && p->pStmt ){ |
| if( p->iIndent<p->nIndent ){ |
| fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); |
| } |
| p->iIndent++; |
| } |
| if( w<0 ){ |
| fprintf(p->out,"%*.*s%s",-w,-w, |
| azArg[i] ? azArg[i] : p->nullValue, |
| i==nArg-1 ? p->rowSeparator : " "); |
| }else{ |
| fprintf(p->out,"%-*.*s%s",w,w, |
| azArg[i] ? azArg[i] : p->nullValue, |
| i==nArg-1 ? p->rowSeparator : " "); |
| } |
| } |
| break; |
| } |
| case MODE_Semi: |
| case MODE_List: { |
| if( p->cnt++==0 && p->showHeader ){ |
| for(i=0; i<nArg; i++){ |
| fprintf(p->out,"%s%s",azCol[i], |
| i==nArg-1 ? p->rowSeparator : p->colSeparator); |
| } |
| } |
| if( azArg==0 ) break; |
| for(i=0; i<nArg; i++){ |
| char *z = azArg[i]; |
| if( z==0 ) z = p->nullValue; |
| fprintf(p->out, "%s", z); |
| if( i<nArg-1 ){ |
| fprintf(p->out, "%s", p->colSeparator); |
| }else if( p->mode==MODE_Semi ){ |
| fprintf(p->out, ";%s", p->rowSeparator); |
| }else{ |
| fprintf(p->out, "%s", p->rowSeparator); |
| } |
| } |
| break; |
| } |
| case MODE_Html: { |
| if( p->cnt++==0 && p->showHeader ){ |
| fprintf(p->out,"<TR>"); |
| for(i=0; i<nArg; i++){ |
| fprintf(p->out,"<TH>"); |
| output_html_string(p->out, azCol[i]); |
| fprintf(p->out,"</TH>\n"); |
| } |
| fprintf(p->out,"</TR>\n"); |
| } |
| if( azArg==0 ) break; |
| fprintf(p->out,"<TR>"); |
| for(i=0; i<nArg; i++){ |
| fprintf(p->out,"<TD>"); |
| output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); |
| fprintf(p->out,"</TD>\n"); |
| } |
| fprintf(p->out,"</TR>\n"); |
| break; |
| } |
| case MODE_Tcl: { |
| if( p->cnt++==0 && p->showHeader ){ |
| for(i=0; i<nArg; i++){ |
| output_c_string(p->out,azCol[i] ? azCol[i] : ""); |
| if(i<nArg-1) fprintf(p->out, "%s", p->colSeparator); |
| } |
| fprintf(p->out, "%s", p->rowSeparator); |
| } |
| if( azArg==0 ) break; |
| for(i=0; i<nArg; i++){ |
| output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); |
| if(i<nArg-1) fprintf(p->out, "%s", p->colSeparator); |
| } |
| fprintf(p->out, "%s", p->rowSeparator); |
| break; |
| } |
| case MODE_Csv: { |
| setBinaryMode(p->out); |
| if( p->cnt++==0 && p->showHeader ){ |
| for(i=0; i<nArg; i++){ |
| output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); |
| } |
| fprintf(p->out, "%s", p->rowSeparator); |
| } |
| if( nArg>0 ){ |
| for(i=0; i<nArg; i++){ |
| output_csv(p, azArg[i], i<nArg-1); |
| } |
| fprintf(p->out, "%s", p->rowSeparator); |
| } |
| setTextMode(p->out); |
| break; |
| } |
| case MODE_Insert: { |
| p->cnt++; |
| if( azArg==0 ) break; |
| fprintf(p->out,"INSERT INTO %s",p->zDestTable); |
| if( p->showHeader ){ |
| fprintf(p->out,"("); |
| for(i=0; i<nArg; i++){ |
| char *zSep = i>0 ? ",": ""; |
| fprintf(p->out, "%s%s", zSep, azCol[i]); |
| } |
| fprintf(p->out,")"); |
| } |
| fprintf(p->out," VALUES("); |
| for(i=0; i<nArg; i++){ |
| char *zSep = i>0 ? ",": ""; |
| if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ |
| fprintf(p->out,"%sNULL",zSep); |
| }else if( aiType && aiType[i]==SQLITE_TEXT ){ |
| if( zSep[0] ) fprintf(p->out,"%s",zSep); |
| output_quoted_string(p->out, azArg[i]); |
| }else if( aiType && (aiType[i]==SQLITE_INTEGER |
| || aiType[i]==SQLITE_FLOAT) ){ |
| fprintf(p->out,"%s%s",zSep, azArg[i]); |
| }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ |
| const void *pBlob = sqlite3_column_blob(p->pStmt, i); |
| int nBlob = sqlite3_column_bytes(p->pStmt, i); |
| if( zSep[0] ) fprintf(p->out,"%s",zSep); |
| output_hex_blob(p->out, pBlob, nBlob); |
| }else if( isNumber(azArg[i], 0) ){ |
| fprintf(p->out,"%s%s",zSep, azArg[i]); |
| }else{ |
| if( zSep[0] ) fprintf(p->out,"%s",zSep); |
| output_quoted_string(p->out, azArg[i]); |
| } |
| } |
| fprintf(p->out,");\n"); |
| break; |
| } |
| case MODE_Ascii: { |
| if( p->cnt++==0 && p->showHeader ){ |
| for(i=0; i<nArg; i++){ |
| if( i>0 ) fprintf(p->out, "%s", p->colSeparator); |
| fprintf(p->out,"%s",azCol[i] ? azCol[i] : ""); |
| } |
| fprintf(p->out, "%s", p->rowSeparator); |
| } |
| if( azArg==0 ) break; |
| for(i=0; i<nArg; i++){ |
| if( i>0 ) fprintf(p->out, "%s", p->colSeparator); |
| fprintf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); |
| } |
| fprintf(p->out, "%s", p->rowSeparator); |
| break; |
| } |
| } |
| return 0; |
| } |
| |
| /* |
| ** This is the callback routine that the SQLite library |
| ** invokes for each row of a query result. |
| */ |
| static int callback(void *pArg, int nArg, char **azArg, char **azCol){ |
| /* since we don't have type info, call the shell_callback with a NULL value */ |
| return shell_callback(pArg, nArg, azArg, azCol, NULL); |
| } |
| |
| /* |
| ** Set the destination table field of the ShellState structure to |
| ** the name of the table given. Escape any quote characters in the |
| ** table name. |
| */ |
| static void set_table_name(ShellState *p, const char *zName){ |
| int i, n; |
| int needQuote; |
| char *z; |
| |
| if( p->zDestTable ){ |
| free(p->zDestTable); |
| p->zDestTable = 0; |
| } |
| if( zName==0 ) return; |
| needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; |
| for(i=n=0; zName[i]; i++, n++){ |
| if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ |
| needQuote = 1; |
| if( zName[i]=='\'' ) n++; |
| } |
| } |
| if( needQuote ) n += 2; |
| z = p->zDestTable = malloc( n+1 ); |
| if( z==0 ){ |
| fprintf(stderr,"Error: out of memory\n"); |
| exit(1); |
| } |
| n = 0; |
| if( needQuote ) z[n++] = '\''; |
| for(i=0; zName[i]; i++){ |
| z[n++] = zName[i]; |
| if( zName[i]=='\'' ) z[n++] = '\''; |
| } |
| if( needQuote ) z[n++] = '\''; |
| z[n] = 0; |
| } |
| |
| /* zIn is either a pointer to a NULL-terminated string in memory obtained |
| ** from malloc(), or a NULL pointer. The string pointed to by zAppend is |
| ** added to zIn, and the result returned in memory obtained from malloc(). |
| ** zIn, if it was not NULL, is freed. |
| ** |
| ** If the third argument, quote, is not '\0', then it is used as a |
| ** quote character for zAppend. |
| */ |
| static char *appendText(char *zIn, char const *zAppend, char quote){ |
| int len; |
| int i; |
| int nAppend = strlen30(zAppend); |
| int nIn = (zIn?strlen30(zIn):0); |
| |
| len = nAppend+nIn+1; |
| if( quote ){ |
| len += 2; |
| for(i=0; i<nAppend; i++){ |
| if( zAppend[i]==quote ) len++; |
| } |
| } |
| |
| zIn = (char *)realloc(zIn, len); |
| if( !zIn ){ |
| return 0; |
| } |
| |
| if( quote ){ |
| char *zCsr = &zIn[nIn]; |
| *zCsr++ = quote; |
| for(i=0; i<nAppend; i++){ |
| *zCsr++ = zAppend[i]; |
| if( zAppend[i]==quote ) *zCsr++ = quote; |
| } |
| *zCsr++ = quote; |
| *zCsr++ = '\0'; |
| assert( (zCsr-zIn)==len ); |
| }else{ |
| memcpy(&zIn[nIn], zAppend, nAppend); |
| zIn[len-1] = '\0'; |
| } |
| |
| return zIn; |
| } |
| |
| |
| /* |
| ** Execute a query statement that will generate SQL output. Print |
| ** the result columns, comma-separated, on a line and then add a |
| ** semicolon terminator to the end of that line. |
| ** |
| ** If the number of columns is 1 and that column contains text "--" |
| ** then write the semicolon on a separate line. That way, if a |
| ** "--" comment occurs at the end of the statement, the comment |
| ** won't consume the semicolon terminator. |
| */ |
| static int run_table_dump_query( |
| ShellState *p, /* Query context */ |
| const char *zSelect, /* SELECT statement to extract content */ |
| const char *zFirstRow /* Print before first row, if not NULL */ |
| ){ |
| sqlite3_stmt *pSelect; |
| int rc; |
| int nResult; |
| int i; |
| const char *z; |
| rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); |
| if( rc!=SQLITE_OK || !pSelect ){ |
| fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); |
| if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; |
| return rc; |
| } |
| rc = sqlite3_step(pSelect); |
| nResult = sqlite3_column_count(pSelect); |
| while( rc==SQLITE_ROW ){ |
| if( zFirstRow ){ |
| fprintf(p->out, "%s", zFirstRow); |
| zFirstRow = 0; |
| } |
| z = (const char*)sqlite3_column_text(pSelect, 0); |
| fprintf(p->out, "%s", z); |
| for(i=1; i<nResult; i++){ |
| fprintf(p->out, ",%s", sqlite3_column_text(pSelect, i)); |
| } |
| if( z==0 ) z = ""; |
| while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; |
| if( z[0] ){ |
| fprintf(p->out, "\n;\n"); |
| }else{ |
| fprintf(p->out, ";\n"); |
| } |
| rc = sqlite3_step(pSelect); |
| } |
| rc = sqlite3_finalize(pSelect); |
| if( rc!=SQLITE_OK ){ |
| fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); |
| if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; |
| } |
| return rc; |
| } |
| |
| /* |
| ** Allocate space and save off current error string. |
| */ |
| static char *save_err_msg( |
| sqlite3 *db /* Database to query */ |
| ){ |
| int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); |
| char *zErrMsg = sqlite3_malloc64(nErrMsg); |
| if( zErrMsg ){ |
| memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); |
| } |
| return zErrMsg; |
| } |
| |
| /* |
| ** Display memory stats. |
| */ |
| static int display_stats( |
| sqlite3 *db, /* Database to query */ |
| ShellState *pArg, /* Pointer to ShellState */ |
| int bReset /* True to reset the stats */ |
| ){ |
| int iCur; |
| int iHiwtr; |
| |
| if( pArg && pArg->out ){ |
| |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, |
| "Memory Used: %d (max %d) bytes\n", |
| iCur, iHiwtr); |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", |
| iCur, iHiwtr); |
| if( pArg->shellFlgs & SHFLG_Pagecache ){ |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, |
| "Number of Pcache Pages Used: %d (max %d) pages\n", |
| iCur, iHiwtr); |
| } |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, |
| "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", |
| iCur, iHiwtr); |
| if( pArg->shellFlgs & SHFLG_Scratch ){ |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", |
| iCur, iHiwtr); |
| } |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, |
| "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", |
| iCur, iHiwtr); |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Largest Allocation: %d bytes\n", |
| iHiwtr); |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", |
| iHiwtr); |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", |
| iHiwtr); |
| #ifdef YYTRACKMAXSTACKDEPTH |
| iHiwtr = iCur = -1; |
| sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", |
| iCur, iHiwtr); |
| #endif |
| } |
| |
| if( pArg && pArg->out && db ){ |
| if( pArg->shellFlgs & SHFLG_Lookaside ){ |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, |
| &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", |
| iCur, iHiwtr); |
| sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, |
| &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); |
| sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, |
| &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); |
| sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, |
| &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); |
| } |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Pager Heap Usage: %d bytes\n",iCur); |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); |
| fprintf(pArg->out, "Page cache hits: %d\n", iCur); |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); |
| fprintf(pArg->out, "Page cache misses: %d\n", iCur); |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); |
| fprintf(pArg->out, "Page cache writes: %d\n", iCur); |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Schema Heap Usage: %d bytes\n",iCur); |
| iHiwtr = iCur = -1; |
| sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); |
| fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",iCur); |
| } |
| |
| if( pArg && pArg->out && db && pArg->pStmt ){ |
| iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, |
| bReset); |
| fprintf(pArg->out, "Fullscan Steps: %d\n", iCur); |
| iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); |
| fprintf(pArg->out, "Sort Operations: %d\n", iCur); |
| iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); |
| fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur); |
| iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); |
| fprintf(pArg->out, "Virtual Machine Steps: %d\n", iCur); |
| } |
| |
| return 0; |
| } |
| |
| /* |
| ** Display scan stats. |
| */ |
| static void display_scanstats( |
| sqlite3 *db, /* Database to query */ |
| ShellState *pArg /* Pointer to ShellState */ |
| ){ |
| #ifdef SQLITE_ENABLE_STMT_SCANSTATUS |
| int i, k, n, mx; |
| fprintf(pArg->out, "-------- scanstats --------\n"); |
| mx = 0; |
| for(k=0; k<=mx; k++){ |
| double rEstLoop = 1.0; |
| for(i=n=0; 1; i++){ |
| sqlite3_stmt *p = pArg->pStmt; |
| sqlite3_int64 nLoop, nVisit; |
| double rEst; |
| int iSid; |
| const char *zExplain; |
| if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ |
| break; |
| } |
| sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); |
| if( iSid>mx ) mx = iSid; |
| if( iSid!=k ) continue; |
| if( n==0 ){ |
| rEstLoop = (double)nLoop; |
| if( k>0 ) fprintf(pArg->out, "-------- subquery %d -------\n", k); |
| } |
| n++; |
| sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); |
| sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); |
| sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); |
| fprintf(pArg->out, "Loop %2d: %s\n", n, zExplain); |
| rEstLoop *= rEst; |
| fprintf(pArg->out, |
| " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", |
| nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst |
| ); |
| } |
| } |
| fprintf(pArg->out, "---------------------------\n"); |
| #endif |
| } |
| |
| /* |
| ** Parameter azArray points to a zero-terminated array of strings. zStr |
| ** points to a single nul-terminated string. Return non-zero if zStr |
| ** is equal, according to strcmp(), to any of the strings in the array. |
| ** Otherwise, return zero. |
| */ |
| static int str_in_array(const char *zStr, const char **azArray){ |
| int i; |
| for(i=0; azArray[i]; i++){ |
| if( 0==strcmp(zStr, azArray[i]) ) return 1; |
| } |
| return 0; |
| } |
| |
| /* |
| ** If compiled statement pSql appears to be an EXPLAIN statement, allocate |
| ** and populate the ShellState.aiIndent[] array with the number of |
| ** spaces each opcode should be indented before it is output. |
| ** |
| ** The indenting rules are: |
| ** |
| ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent |
| ** all opcodes that occur between the p2 jump destination and the opcode |
| ** itself by 2 spaces. |
| ** |
| ** * For each "Goto", if the jump destination is earlier in the program |
| ** and ends on one of: |
| ** Yield SeekGt SeekLt RowSetRead Rewind |
| ** or if the P1 parameter is one instead of zero, |
| ** then indent all opcodes between the earlier instruction |
| ** and "Goto" by 2 spaces. |
| */ |
| static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ |
| const char *zSql; /* The text of the SQL statement */ |
| const char *z; /* Used to check if this is an EXPLAIN */ |
| int *abYield = 0; /* True if op is an OP_Yield */ |
| int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ |
| int iOp; /* Index of operation in p->aiIndent[] */ |
| |
| const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", |
| "NextIfOpen", "PrevIfOpen", 0 }; |
| const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", |
| "Rewind", 0 }; |
| const char *azGoto[] = { "Goto", 0 }; |
| |
| /* Try to figure out if this is really an EXPLAIN statement. If this |
| ** cannot be verified, return early. */ |
| zSql = sqlite3_sql(pSql); |
| if( zSql==0 ) return; |
| for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); |
| if( sqlite3_strnicmp(z, "explain", 7) ) return; |
| |
| for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ |
| int i; |
| int iAddr = sqlite3_column_int(pSql, 0); |
| const char *zOp = (const char*)sqlite3_column_text(pSql, 1); |
| |
| /* Set p2 to the P2 field of the current opcode. Then, assuming that |
| ** p2 is an instruction address, set variable p2op to the index of that |
| ** instruction in the aiIndent[] array. p2 and p2op may be different if |
| ** the current instruction is part of a sub-program generated by an |
| ** SQL trigger or foreign key. */ |
| int p2 = sqlite3_column_int(pSql, 3); |
| int p2op = (p2 + (iOp-iAddr)); |
| |
| /* Grow the p->aiIndent array as required */ |
| if( iOp>=nAlloc ){ |
| nAlloc += 100; |
| p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); |
| abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); |
| } |
| abYield[iOp] = str_in_array(zOp, azYield); |
| p->aiIndent[iOp] = 0; |
| p->nIndent = iOp+1; |
| |
| if( str_in_array(zOp, azNext) ){ |
| for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; |
| } |
| if( str_in_array(zOp, azGoto) && p2op<p->nIndent |
| && (abYield[p2op] || sqlite3_column_int(pSql, 2)) |
| ){ |
| for(i=p2op+1; i<iOp; i++) p->aiIndent[i] += 2; |
| } |
| } |
| |
| p->iIndent = 0; |
| sqlite3_free(abYield); |
| sqlite3_reset(pSql); |
| } |
| |
| /* |
| ** Free the array allocated by explain_data_prepare(). |
| */ |
| static void explain_data_delete(ShellState *p){ |
| sqlite3_free(p->aiIndent); |
| p->aiIndent = 0; |
| p->nIndent = 0; |
| p->iIndent = 0; |
| } |
| |
| /* |
| ** Execute a statement or set of statements. Print |
| ** any result rows/columns depending on the current mode |
| ** set via the supplied callback. |
| ** |
| ** This is very similar to SQLite's built-in sqlite3_exec() |
| ** function except it takes a slightly different callback |
| ** and callback data argument. |
| */ |
| static int shell_exec( |
| sqlite3 *db, /* An open database */ |
| const char *zSql, /* SQL to be evaluated */ |
| int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ |
| /* (not the same as sqlite3_exec) */ |
| ShellState *pArg, /* Pointer to ShellState */ |
| char **pzErrMsg /* Error msg written here */ |
| ){ |
| sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ |
| int rc = SQLITE_OK; /* Return Code */ |
| int rc2; |
| const char *zLeftover; /* Tail of unprocessed SQL */ |
| |
| if( pzErrMsg ){ |
| *pzErrMsg = NULL; |
| } |
| |
| while( zSql[0] && (SQLITE_OK == rc) ){ |
| rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); |
| if( SQLITE_OK != rc ){ |
| if( pzErrMsg ){ |
| *pzErrMsg = save_err_msg(db); |
| } |
| }else{ |
| if( !pStmt ){ |
| /* this happens for a comment or white-space */ |
| zSql = zLeftover; |
| while( IsSpace(zSql[0]) ) zSql++; |
| continue; |
| } |
| |
| /* save off the prepared statment handle and reset row count */ |
| if( pArg ){ |
| pArg->pStmt = pStmt; |
| pArg->cnt = 0; |
| } |
| |
| /* echo the sql statement if echo on */ |
| if( pArg && pArg->echoOn ){ |
| const char *zStmtSql = sqlite3_sql(pStmt); |
| fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); |
| } |
| |
| /* Show the EXPLAIN QUERY PLAN if .eqp is on */ |
| if( pArg && pArg->autoEQP ){ |
| sqlite3_stmt *pExplain; |
| char *zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", |
| sqlite3_sql(pStmt)); |
| rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); |
| if( rc==SQLITE_OK ){ |
| while( sqlite3_step(pExplain)==SQLITE_ROW ){ |
| fprintf(pArg->out,"--EQP-- %d,", sqlite3_column_int(pExplain, 0)); |
| fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1)); |
| fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2)); |
| fprintf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3)); |
| } |
| } |
| sqlite3_finalize(pExplain); |
| sqlite3_free(zEQP); |
| } |
| |
| /* If the shell is currently in ".explain" mode, gather the extra |
| ** data required to add indents to the output.*/ |
| if( pArg && pArg->mode==MODE_Explain ){ |
| explain_data_prepare(pArg, pStmt); |
| } |
| |
| /* perform the first step. this will tell us if we |
| ** have a result set or not and how wide it is. |
| */ |
| rc = sqlite3_step(pStmt); |
| /* if we have a result set... */ |
| if( SQLITE_ROW == rc ){ |
| /* if we have a callback... */ |
| if( xCallback ){ |
| /* allocate space for col name ptr, value ptr, and type */ |
| int nCol = sqlite3_column_count(pStmt); |
| void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); |
| if( !pData ){ |
| rc = SQLITE_NOMEM; |
| }else{ |
| char **azCols = (char **)pData; /* Names of result columns */ |
| char **azVals = &azCols[nCol]; /* Results */ |
| int *aiTypes = (int *)&azVals[nCol]; /* Result types */ |
| int i, x; |
| assert(sizeof(int) <= sizeof(char *)); |
| /* save off ptrs to column names */ |
| for(i=0; i<nCol; i++){ |
| azCols[i] = (char *)sqlite3_column_name(pStmt, i); |
| } |
| do{ |
| /* extract the data and data types */ |
| for(i=0; i<nCol; i++){ |
| aiTypes[i] = x = sqlite3_column_type(pStmt, i); |
| if( x==SQLITE_BLOB && pArg && pArg->mode==MODE_Insert ){ |
| azVals[i] = ""; |
| }else{ |
| azVals[i] = (char*)sqlite3_column_text(pStmt, i); |
| } |
| if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ |
| rc = SQLITE_NOMEM; |
| break; /* from for */ |
| } |
| } /* end for */ |
| |
| /* if data and types extracted successfully... */ |
| if( SQLITE_ROW == rc ){ |
| /* call the supplied callback with the result row data */ |
| if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){ |
| rc = SQLITE_ABORT; |
| }else{ |
| rc = sqlite3_step(pStmt); |
| } |
| } |
| } while( SQLITE_ROW == rc ); |
| sqlite3_free(pData); |
| } |
| }else{ |
| do{ |
| rc = sqlite3_step(pStmt); |
| } while( rc == SQLITE_ROW ); |
| } |
| } |
| |
| explain_data_delete(pArg); |
| |
| /* print usage stats if stats on */ |
| if( pArg && pArg->statsOn ){ |
| display_stats(db, pArg, 0); |
| } |
| |
| /* print loop-counters if required */ |
| if( pArg && pArg->scanstatsOn ){ |
| display_scanstats(db, pArg); |
| } |
| |
| /* Finalize the statement just executed. If this fails, save a |
| ** copy of the error message. Otherwise, set zSql to point to the |
| ** next statement to execute. */ |
| rc2 = sqlite3_finalize(pStmt); |
| if( rc!=SQLITE_NOMEM ) rc = rc2; |
| if( rc==SQLITE_OK ){ |
| zSql = zLeftover; |
| while( IsSpace(zSql[0]) ) zSql++; |
| }else if( pzErrMsg ){ |
| *pzErrMsg = save_err_msg(db); |
| } |
| |
| /* clear saved stmt handle */ |
| if( pArg ){ |
| pArg->pStmt = NULL; |
| } |
| } |
| } /* end while */ |
| |
| return rc; |
| } |
| |
| |
| /* |
| ** This is a different callback routine used for dumping the database. |
| ** Each row received by this callback consists of a table name, |
| ** the table type ("index" or "table") and SQL to create the table. |
| ** This routine should print text sufficient to recreate the table. |
| */ |
| static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ |
| int rc; |
| const char *zTable; |
| const char *zType; |
| const char *zSql; |
| const char *zPrepStmt = 0; |
| ShellState *p = (ShellState *)pArg; |
| |
| UNUSED_PARAMETER(azCol); |
| if( nArg!=3 ) return 1; |
| zTable = azArg[0]; |
| zType = azArg[1]; |
| zSql = azArg[2]; |
| |
| if( strcmp(zTable, "sqlite_sequence")==0 ){ |
| zPrepStmt = "DELETE FROM sqlite_sequence;\n"; |
| }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ |
| fprintf(p->out, "ANALYZE sqlite_master;\n"); |
| }else if( strncmp(zTable, "sqlite_", 7)==0 ){ |
| return 0; |
| }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ |
| char *zIns; |
| if( !p->writableSchema ){ |
| fprintf(p->out, "PRAGMA writable_schema=ON;\n"); |
| p->writableSchema = 1; |
| } |
| zIns = sqlite3_mprintf( |
| "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" |
| "VALUES('table','%q','%q',0,'%q');", |
| zTable, zTable, zSql); |
| fprintf(p->out, "%s\n", zIns); |
| sqlite3_free(zIns); |
| return 0; |
| }else{ |
| fprintf(p->out, "%s;\n", zSql); |
| } |
| |
| if( strcmp(zType, "table")==0 ){ |
| sqlite3_stmt *pTableInfo = 0; |
| char *zSelect = 0; |
| char *zTableInfo = 0; |
| char *zTmp = 0; |
| int nRow = 0; |
| |
| zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); |
| zTableInfo = appendText(zTableInfo, zTable, '"'); |
| zTableInfo = appendText(zTableInfo, ");", 0); |
| |
| rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0); |
| free(zTableInfo); |
| if( rc!=SQLITE_OK || !pTableInfo ){ |
| return 1; |
| } |
| |
| zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); |
| /* Always quote the table name, even if it appears to be pure ascii, |
| ** in case it is a keyword. Ex: INSERT INTO "table" ... */ |
| zTmp = appendText(zTmp, zTable, '"'); |
| if( zTmp ){ |
| zSelect = appendText(zSelect, zTmp, '\''); |
| free(zTmp); |
| } |
| zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); |
| rc = sqlite3_step(pTableInfo); |
| while( rc==SQLITE_ROW ){ |
| const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); |
| zSelect = appendText(zSelect, "quote(", 0); |
| zSelect = appendText(zSelect, zText, '"'); |
| rc = sqlite3_step(pTableInfo); |
| if( rc==SQLITE_ROW ){ |
| zSelect = appendText(zSelect, "), ", 0); |
| }else{ |
| zSelect = appendText(zSelect, ") ", 0); |
| } |
| nRow++; |
| } |
| rc = sqlite3_finalize(pTableInfo); |
| if( rc!=SQLITE_OK || nRow==0 ){ |
| free(zSelect); |
| return 1; |
| } |
| zSelect = appendText(zSelect, "|| ')' FROM ", 0); |
| zSelect = appendText(zSelect, zTable, '"'); |
| |
| rc = run_table_dump_query(p, zSelect, zPrepStmt); |
| if( rc==SQLITE_CORRUPT ){ |
| zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); |
| run_table_dump_query(p, zSelect, 0); |
| } |
| free(zSelect); |
| } |
| return 0; |
| } |
| |
| /* |
| ** Run zQuery. Use dump_callback() as the callback routine so that |
| ** the contents of the query are output as SQL statements. |
| ** |
| ** If we get a SQLITE_CORRUPT error, rerun the query after appending |
| ** "ORDER BY rowid DESC" to the end. |
| */ |
| static int run_schema_dump_query( |
| ShellState *p, |
| const char *zQuery |
| ){ |
| int rc; |
| char *zErr = 0; |
| rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); |
| if( rc==SQLITE_CORRUPT ){ |
| char *zQ2; |
| int len = strlen30(zQuery); |
| fprintf(p->out, "/****** CORRUPTION ERROR *******/\n"); |
| if( zErr ){ |
| fprintf(p->out, "/****** %s ******/\n", zErr); |
| sqlite3_free(zErr); |
| zErr = 0; |
| } |
| zQ2 = malloc( len+100 ); |
| if( zQ2==0 ) return rc; |
| sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); |
| rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); |
| if( rc ){ |
| fprintf(p->out, "/****** ERROR: %s ******/\n", zErr); |
| }else{ |
| rc = SQLITE_CORRUPT; |
| } |
| sqlite3_free(zErr); |
| free(zQ2); |
| } |
| return rc; |
| } |
| |
| /* |
| ** Text of a help message |
| */ |
| static char zHelp[] = |
| ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" |
| ".bail on|off Stop after hitting an error. Default OFF\n" |
| ".binary on|off Turn binary output on or off. Default OFF\n" |
| ".clone NEWDB Clone data into NEWDB from the existing database\n" |
| ".databases List names and files of attached databases\n" |
| ".dbinfo ?DB? Show status information about the database\n" |
| ".dump ?TABLE? ... Dump the database in an SQL text format\n" |
| " If TABLE specified, only dump tables matching\n" |
| " LIKE pattern TABLE.\n" |
| ".echo on|off Turn command echo on or off\n" |
| ".eqp on|off Enable or disable automatic EXPLAIN QUERY PLAN\n" |
| ".exit Exit this program\n" |
| ".explain ?on|off? Turn output mode suitable for EXPLAIN on or off.\n" |
| " With no args, it turns EXPLAIN on.\n" |
| ".fullschema Show schema and the content of sqlite_stat tables\n" |
| ".headers on|off Turn display of headers on or off\n" |
| ".help Show this message\n" |
| ".import FILE TABLE Import data from FILE into TABLE\n" |
| ".indexes ?TABLE? Show names of all indexes\n" |
| " If TABLE specified, only show indexes for tables\n" |
| " matching LIKE pattern TABLE.\n" |
| #ifdef SQLITE_ENABLE_IOTRACE |
| ".iotrace FILE Enable I/O diagnostic logging to FILE\n" |
| #endif |
| ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n" |
| #ifndef SQLITE_OMIT_LOAD_EXTENSION |
| ".load FILE ?ENTRY? Load an extension library\n" |
| #endif |
| ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" |
| ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" |
| " ascii Columns/rows delimited by 0x1F and 0x1E\n" |
| " csv Comma-separated values\n" |
| " column Left-aligned columns. (See .width)\n" |
| " html HTML <table> code\n" |
| " insert SQL insert statements for TABLE\n" |
| " line One value per line\n" |
| " list Values delimited by .separator strings\n" |
| " tabs Tab-separated values\n" |
| " tcl TCL list elements\n" |
| ".nullvalue STRING Use STRING in place of NULL values\n" |
| ".once FILENAME Output for the next SQL command only to FILENAME\n" |
| ".open ?FILENAME? Close existing database and reopen FILENAME\n" |
| ".output ?FILENAME? Send output to FILENAME or stdout\n" |
| ".print STRING... Print literal STRING\n" |
| ".prompt MAIN CONTINUE Replace the standard prompts\n" |
| ".quit Exit this program\n" |
| ".read FILENAME Execute SQL in FILENAME\n" |
| ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" |
| ".save FILE Write in-memory database into FILE\n" |
| ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n" |
| ".schema ?TABLE? Show the CREATE statements\n" |
| " If TABLE specified, only show tables matching\n" |
| " LIKE pattern TABLE.\n" |
| ".separator COL ?ROW? Change the column separator and optionally the row\n" |
| " separator for both the output mode and .import\n" |
| ".shell CMD ARGS... Run CMD ARGS... in a system shell\n" |
| ".show Show the current values for various settings\n" |
| ".stats on|off Turn stats on or off\n" |
| ".system CMD ARGS... Run CMD ARGS... in a system shell\n" |
| ".tables ?TABLE? List names of tables\n" |
| " If TABLE specified, only list tables matching\n" |
| " LIKE pattern TABLE.\n" |
| ".timeout MS Try opening locked tables for MS milliseconds\n" |
| ".timer on|off Turn SQL timer on or off\n" |
| ".trace FILE|off Output each SQL statement as it is run\n" |
| ".vfsname ?AUX? Print the name of the VFS stack\n" |
| ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" |
| " Negative values right-justify\n" |
| ; |
| |
| /* Forward reference */ |
| static int process_input(ShellState *p, FILE *in); |
| /* |
| ** Implementation of the "readfile(X)" SQL function. The entire content |
| ** of the file named X is read and returned as a BLOB. NULL is returned |
| ** if the file does not exist or is unreadable. |
| */ |
| static void readfileFunc( |
| sqlite3_context *context, |
| int argc, |
| sqlite3_value **argv |
| ){ |
| const char *zName; |
| FILE *in; |
| long nIn; |
| void *pBuf; |
| |
| zName = (const char*)sqlite3_value_text(argv[0]); |
| if( zName==0 ) return; |
| in = fopen(zName, "rb"); |
| if( in==0 ) return; |
| fseek(in, 0, SEEK_END); |
| nIn = ftell(in); |
| rewind(in); |
| pBuf = sqlite3_malloc64( nIn ); |
| if( pBuf && 1==fread(pBuf, nIn, 1, in) ){ |
| sqlite3_result_blob(context, pBuf, nIn, sqlite3_free); |
| }else{ |
| sqlite3_free(pBuf); |
| } |
| fclose(in); |
| } |
| |
| /* |
| ** Implementation of the "writefile(X,Y)" SQL function. The argument Y |
| ** is written into file X. The number of bytes written is returned. Or |
| ** NULL is returned if something goes wrong, such as being unable to open |
| ** file X for writing. |
| */ |
| static void writefileFunc( |
| sqlite3_context *context, |
| int argc, |
| sqlite3_value **argv |
| ){ |
| FILE *out; |
| const char *z; |
| sqlite3_int64 rc; |
| const char *zFile; |
| |
| zFile = (const char*)sqlite3_value_text(argv[0]); |
| if( zFile==0 ) return; |
| out = fopen(zFile, "wb"); |
| if( out==0 ) return; |
| z = (const char*)sqlite3_value_blob(argv[1]); |
| if( z==0 ){ |
| rc = 0; |
| }else{ |
| rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out); |
| } |
| fclose(out); |
| sqlite3_result_int64(context, rc); |
| } |
| |
| /* |
| ** Make sure the database is open. If it is not, then open it. If |
| ** the database fails to open, print an error message and exit. |
| */ |
| static void open_db(ShellState *p, int keepAlive){ |
| if( p->db==0 ){ |
| sqlite3_initialize(); |
| sqlite3_open(p->zDbFilename, &p->db); |
| globalDb = p->db; |
| if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){ |
| sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0, |
| shellstaticFunc, 0, 0); |
| } |
| if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ |
| fprintf(stderr,"Error: unable to open database \"%s\": %s\n", |
| p->zDbFilename, sqlite3_errmsg(p->db)); |
| if( keepAlive ) return; |
| exit(1); |
| } |
| #ifndef SQLITE_OMIT_LOAD_EXTENSION |
| sqlite3_enable_load_extension(p->db, 1); |
| #endif |
| sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0, |
| readfileFunc, 0, 0); |
| sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0, |
| writefileFunc, 0, 0); |
| |
| // Begin Android Add |
| #ifndef NO_ANDROID_FUNCS |
| int err = register_localized_collators(p->db, "en_US", 0); |
| if (err != SQLITE_OK) { |
| fprintf(stderr, "register_localized_collators() failed\n"); |
| exit(1); |
| } |
| err = register_android_functions(p->db, 0); |
| if (err != SQLITE_OK) { |
| fprintf(stderr, "register_android_functions() failed\n"); |
| exit(1); |
| } |
| #endif |
| // End Android Add |
| } |
| } |
| |
| /* |
| ** Do C-language style dequoting. |
| ** |
| ** \a -> alarm |
| ** \b -> backspace |
| ** \t -> tab |
| ** \n -> newline |
| ** \v -> vertical tab |
| ** \f -> form feed |
| ** \r -> carriage return |
| ** \s -> space |
| ** \" -> " |
| ** \' -> ' |
| ** \\ -> backslash |
| ** \NNN -> ascii character NNN in octal |
| */ |
| static void resolve_backslashes(char *z){ |
| int i, j; |
| char c; |
| while( *z && *z!='\\' ) z++; |
| for(i=j=0; (c = z[i])!=0; i++, j++){ |
| if( c=='\\' && z[i+1]!=0 ){ |
| c = z[++i]; |
| if( c=='a' ){ |
| c = '\a'; |
| }else if( c=='b' ){ |
| c = '\b'; |
| }else if( c=='t' ){ |
| c = '\t'; |
| }else if( c=='n' ){ |
| c = '\n'; |
| }else if( c=='v' ){ |
| c = '\v'; |
| }else if( c=='f' ){ |
| c = '\f'; |
| }else if( c=='r' ){ |
| c = '\r'; |
| }else if( c=='"' ){ |
| c = '"'; |
| }else if( c=='\'' ){ |
| c = '\''; |
| }else if( c=='\\' ){ |
| c = '\\'; |
| }else if( c>='0' && c<='7' ){ |
| c -= '0'; |
| if( z[i+1]>='0' && z[i+1]<='7' ){ |
| i++; |
| c = (c<<3) + z[i] - '0'; |
| if( z[i+1]>='0' && z[i+1]<='7' ){ |
| i++; |
| c = (c<<3) + z[i] - '0'; |
| } |
| } |
| } |
| } |
| z[j] = c; |
| } |
| if( j<i ) z[j] = 0; |
| } |
| |
| /* |
| ** Return the value of a hexadecimal digit. Return -1 if the input |
| ** is not a hex digit. |
| */ |
| static int hexDigitValue(char c){ |
| if( c>='0' && c<='9' ) return c - '0'; |
| if( c>='a' && c<='f' ) return c - 'a' + 10; |
| if( c>='A' && c<='F' ) return c - 'A' + 10; |
| return -1; |
| } |
| |
| /* |
| ** Interpret zArg as an integer value, possibly with suffixes. |
| */ |
| static sqlite3_int64 integerValue(const char *zArg){ |
| sqlite3_int64 v = 0; |
| static const struct { char *zSuffix; int iMult; } aMult[] = { |
| { "KiB", 1024 }, |
| { "MiB", 1024*1024 }, |
| { "GiB", 1024*1024*1024 }, |
| { "KB", 1000 }, |
| { "MB", 1000000 }, |
| { "GB", 1000000000 }, |
| { "K", 1000 }, |
| { "M", 1000000 }, |
| { "G", 1000000000 }, |
| }; |
| int i; |
| int isNeg = 0; |
| if( zArg[0]=='-' ){ |
| isNeg = 1; |
| zArg++; |
| }else if( zArg[0]=='+' ){ |
| zArg++; |
| } |
| if( zArg[0]=='0' && zArg[1]=='x' ){ |
| int x; |
| zArg += 2; |
| while( (x = hexDigitValue(zArg[0]))>=0 ){ |
| v = (v<<4) + x; |
| zArg++; |
| } |
| }else{ |
| while( IsDigit(zArg[0]) ){ |
| v = v*10 + zArg[0] - '0'; |
| zArg++; |
| } |
| } |
| for(i=0; i<ArraySize(aMult); i++){ |
| if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ |
| v *= aMult[i].iMult; |
| break; |
| } |
| } |
| return isNeg? -v : v; |
| } |
| |
| /* |
| ** Interpret zArg as either an integer or a boolean value. Return 1 or 0 |
| ** for TRUE and FALSE. Return the integer value if appropriate. |
| */ |
| static int booleanValue(char *zArg){ |
| int i; |
| if( zArg[0]=='0' && zArg[1]=='x' ){ |
| for(i=2; hexDigitValue(zArg[i])>=0; i++){} |
| }else{ |
| for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} |
| } |
| if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); |
| if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ |
| return 1; |
| } |
| if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ |
| return 0; |
| } |
| fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", |
| zArg); |
| return 0; |
| } |
| |
| /* |
| ** Close an output file, assuming it is not stderr or stdout |
| */ |
| static void output_file_close(FILE *f){ |
| if( f && f!=stdout && f!=stderr ) fclose(f); |
| } |
| |
| /* |
| ** Try to open an output file. The names "stdout" and "stderr" are |
| ** recognized and do the right thing. NULL is returned if the output |
| ** filename is "off". |
| */ |
| static FILE *output_file_open(const char *zFile){ |
| FILE *f; |
| if( strcmp(zFile,"stdout")==0 ){ |
| f = stdout; |
| }else if( strcmp(zFile, "stderr")==0 ){ |
| f = stderr; |
| }else if( strcmp(zFile, "off")==0 ){ |
| f = 0; |
| }else{ |
| f = fopen(zFile, "wb"); |
| if( f==0 ){ |
| fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); |
| } |
| } |
| return f; |
| } |
| |
| /* |
| ** A routine for handling output from sqlite3_trace(). |
| */ |
| static void sql_trace_callback(void *pArg, const char *z){ |
| FILE *f = (FILE*)pArg; |
| if( f ){ |
| int i = (int)strlen(z); |
| while( i>0 && z[i-1]==';' ){ i--; } |
| fprintf(f, "%.*s;\n", i, z); |
| } |
| } |
| |
| /* |
| ** A no-op routine that runs with the ".breakpoint" doc-command. This is |
| ** a useful spot to set a debugger breakpoint. |
| */ |
| static void test_breakpoint(void){ |
| static int nCall = 0; |
| nCall++; |
| } |
| |
| /* |
| ** An object used to read a CSV and other files for import. |
| */ |
| typedef struct ImportCtx ImportCtx; |
| struct ImportCtx { |
| const char *zFile; /* Name of the input file */ |
| FILE *in; /* Read the CSV text from this input stream */ |
| char *z; /* Accumulated text for a field */ |
| int n; /* Number of bytes in z */ |
| int nAlloc; /* Space allocated for z[] */ |
| int nLine; /* Current line number */ |
| int cTerm; /* Character that terminated the most recent field */ |
| int cColSep; /* The column separator character. (Usually ",") */ |
| int cRowSep; /* The row separator character. (Usually "\n") */ |
| }; |
| |
| /* Append a single byte to z[] */ |
| static void import_append_char(ImportCtx *p, int c){ |
| if( p->n+1>=p->nAlloc ){ |
| p->nAlloc += p->nAlloc + 100; |
| p->z = sqlite3_realloc64(p->z, p->nAlloc); |
| if( p->z==0 ){ |
| fprintf(stderr, "out of memory\n"); |
| exit(1); |
| } |
| } |
| p->z[p->n++] = (char)c; |
| } |
| |
| /* Read a single field of CSV text. Compatible with rfc4180 and extended |
| ** with the option of having a separator other than ",". |
| ** |
| ** + Input comes from p->in. |
| ** + Store results in p->z of length p->n. Space to hold p->z comes |
| ** from sqlite3_malloc64(). |
| ** + Use p->cSep as the column separator. The default is ",". |
| ** + Use p->rSep as the row separator. The default is "\n". |
| ** + Keep track of the line number in p->nLine. |
| ** + Store the character that terminates the field in p->cTerm. Store |
| ** EOF on end-of-file. |
| ** + Report syntax errors on stderr |
| */ |
| static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ |
| int c; |
| int cSep = p->cColSep; |
| int rSep = p->cRowSep; |
| p->n = 0; |
| c = fgetc(p->in); |
| if( c==EOF || seenInterrupt ){ |
| p->cTerm = EOF; |
| return 0; |
| } |
| if( c=='"' ){ |
| int pc, ppc; |
| int startLine = p->nLine; |
| int cQuote = c; |
| pc = ppc = 0; |
| while( 1 ){ |
| c = fgetc(p->in); |
| if( c==rSep ) p->nLine++; |
| if( c==cQuote ){ |
| if( pc==cQuote ){ |
| pc = 0; |
| continue; |
| } |
| } |
| if( (c==cSep && pc==cQuote) |
| || (c==rSep && pc==cQuote) |
| || (c==rSep && pc=='\r' && ppc==cQuote) |
| || (c==EOF && pc==cQuote) |
| ){ |
| do{ p->n--; }while( p->z[p->n]!=cQuote ); |
| p->cTerm = c; |
| break; |
| } |
| if( pc==cQuote && c!='\r' ){ |
| fprintf(stderr, "%s:%d: unescaped %c character\n", |
| p->zFile, p->nLine, cQuote); |
| } |
| if( c==EOF ){ |
| fprintf(stderr, "%s:%d: unterminated %c-quoted field\n", |
| p->zFile, startLine, cQuote); |
| p->cTerm = c; |
| break; |
| } |
| import_append_char(p, c); |
| ppc = pc; |
| pc = c; |
| } |
| }else{ |
| while( c!=EOF && c!=cSep && c!=rSep ){ |
| import_append_char(p, c); |
| c = fgetc(p->in); |
| } |
| if( c==rSep ){ |
| p->nLine++; |
| if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; |
| } |
| p->cTerm = c; |
| } |
| if( p->z ) p->z[p->n] = 0; |
| return p->z; |
| } |
| |
| /* Read a single field of ASCII delimited text. |
| ** |
| ** + Input comes from p->in. |
| ** + Store results in p->z of length p->n. Space to hold p->z comes |
| ** from sqlite3_malloc64(). |
| ** + Use p->cSep as the column separator. The default is "\x1F". |
| ** + Use p->rSep as the row separator. The default is "\x1E". |
| ** + Keep track of the row number in p->nLine. |
| ** + Store the character that terminates the field in p->cTerm. Store |
| ** EOF on end-of-file. |
| ** + Report syntax errors on stderr |
| */ |
| static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ |
| int c; |
| int cSep = p->cColSep; |
| int rSep = p->cRowSep; |
| p->n = 0; |
| c = fgetc(p->in); |
| if( c==EOF || seenInterrupt ){ |
| p->cTerm = EOF; |
| return 0; |
| } |
| while( c!=EOF && c!=cSep && c!=rSep ){ |
| import_append_char(p, c); |
| c = fgetc(p->in); |
| } |
| if( c==rSep ){ |
| p->nLine++; |
| } |
| p->cTerm = c; |
| if( p->z ) p->z[p->n] = 0; |
| return p->z; |
| } |
| |
| /* |
| ** Try to transfer data for table zTable. If an error is seen while |
| ** moving forward, try to go backwards. The backwards movement won't |
| ** work for WITHOUT ROWID tables. |
| */ |
| static void tryToCloneData( |
| ShellState *p, |
| sqlite3 *newDb, |
| const char *zTable |
| ){ |
| sqlite3_stmt *pQuery = 0; |
| sqlite3_stmt *pInsert = 0; |
| char *zQuery = 0; |
| char *zInsert = 0; |
| int rc; |
| int i, j, n; |
| int nTable = (int)strlen(zTable); |
| int k = 0; |
| int cnt = 0; |
| const int spinRate = 10000; |
| |
| zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); |
| rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); |
| if( rc ){ |
| fprintf(stderr, "Error %d: %s on [%s]\n", |
| sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), |
| zQuery); |
| goto end_data_xfer; |
| } |
| n = sqlite3_column_count(pQuery); |
| zInsert = sqlite3_malloc64(200 + nTable + n*3); |
| if( zInsert==0 ){ |
| fprintf(stderr, "out of memory\n"); |
| goto end_data_xfer; |
| } |
| sqlite3_snprintf(200+nTable,zInsert, |
| "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); |
| i = (int)strlen(zInsert); |
| for(j=1; j<n; j++){ |
| memcpy(zInsert+i, ",?", 2); |
| i += 2; |
| } |
| memcpy(zInsert+i, ");", 3); |
| rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); |
| if( rc ){ |
| fprintf(stderr, "Error %d: %s on [%s]\n", |
| sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), |
| zQuery); |
| goto end_data_xfer; |
| } |
| for(k=0; k<2; k++){ |
| while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ |
| for(i=0; i<n; i++){ |
| switch( sqlite3_column_type(pQuery, i) ){ |
| case SQLITE_NULL: { |
| sqlite3_bind_null(pInsert, i+1); |
| break; |
| } |
| case SQLITE_INTEGER: { |
| sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); |
| break; |
| } |
| case SQLITE_FLOAT: { |
| sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); |
| break; |
| } |
| case SQLITE_TEXT: { |
| sqlite3_bind_text(pInsert, i+1, |
| (const char*)sqlite3_column_text(pQuery,i), |
| -1, SQLITE_STATIC); |
| break; |
| } |
| case SQLITE_BLOB: { |
| sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), |
| sqlite3_column_bytes(pQuery,i), |
| SQLITE_STATIC); |
| break; |
| } |
| } |
| } /* End for */ |
| rc = sqlite3_step(pInsert); |
| if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ |
| fprintf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), |
| sqlite3_errmsg(newDb)); |
| } |
| sqlite3_reset(pInsert); |
| cnt++; |
| if( (cnt%spinRate)==0 ){ |
| printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); |
| fflush(stdout); |
| } |
| } /* End while */ |
| if( rc==SQLITE_DONE ) break; |
| sqlite3_finalize(pQuery); |
| sqlite3_free(zQuery); |
| zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", |
| zTable); |
| rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); |
| if( rc ){ |
| fprintf(stderr, "Warning: cannot step \"%s\" backwards", zTable); |
| break; |
| } |
| } /* End for(k=0...) */ |
| |
| end_data_xfer: |
| sqlite3_finalize(pQuery); |
| sqlite3_finalize(pInsert); |
| sqlite3_free(zQuery); |
| sqlite3_free(zInsert); |
| } |
| |
| |
| /* |
| ** Try to transfer all rows of the schema that match zWhere. For |
| ** each row, invoke xForEach() on the object defined by that row. |
| ** If an error is encountered while moving forward through the |
| ** sqlite_master table, try again moving backwards. |
| */ |
| static void tryToCloneSchema( |
| ShellState *p, |
| sqlite3 *newDb, |
| const char *zWhere, |
| void (*xForEach)(ShellState*,sqlite3*,const char*) |
| ){ |
| sqlite3_stmt *pQuery = 0; |
| char *zQuery = 0; |
| int rc; |
| const unsigned char *zName; |
| const unsigned char *zSql; |
| char *zErrMsg = 0; |
| |
| zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" |
| " WHERE %s", zWhere); |
| rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); |
| if( rc ){ |
| fprintf(stderr, "Error: (%d) %s on [%s]\n", |
| sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), |
| zQuery); |
| goto end_schema_xfer; |
| } |
| while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ |
| zName = sqlite3_column_text(pQuery, 0); |
| zSql = sqlite3_column_text(pQuery, 1); |
| printf("%s... ", zName); fflush(stdout); |
| sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); |
| if( zErrMsg ){ |
| fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); |
| sqlite3_free(zErrMsg); |
| zErrMsg = 0; |
| } |
| if( xForEach ){ |
| xForEach(p, newDb, (const char*)zName); |
| } |
| printf("done\n"); |
| } |
| if( rc!=SQLITE_DONE ){ |
| sqlite3_finalize(pQuery); |
| sqlite3_free(zQuery); |
| zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" |
| " WHERE %s ORDER BY rowid DESC", zWhere); |
| rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); |
| if( rc ){ |
| fprintf(stderr, "Error: (%d) %s on [%s]\n", |
| sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), |
| zQuery); |
| goto end_schema_xfer; |
| } |
| while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ |
| zName = sqlite3_column_text(pQuery, 0); |
| zSql = sqlite3_column_text(pQuery, 1); |
| printf("%s... ", zName); fflush(stdout); |
| sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); |
| if( zErrMsg ){ |
| fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); |
| sqlite3_free(zErrMsg); |
| zErrMsg = 0; |
| } |
| if( xForEach ){ |
| xForEach(p, newDb, (const char*)zName); |
| } |
| printf("done\n"); |
| } |
| } |
| end_schema_xfer: |
| sqlite3_finalize(pQuery); |
| sqlite3_free(zQuery); |
| } |
| |
| /* |
| ** Open a new database file named "zNewDb". Try to recover as much information |
| ** as possible out of the main database (which might be corrupt) and write it |
| ** into zNewDb. |
| */ |
| static void tryToClone(ShellState *p, const char *zNewDb){ |
| int rc; |
| sqlite3 *newDb = 0; |
| if( access(zNewDb,0)==0 ){ |
| fprintf(stderr, "File \"%s\" already exists.\n", zNewDb); |
| return; |
| } |
| rc = sqlite3_open(zNewDb, &newDb); |
| if( rc ){ |
| fprintf(stderr, "Cannot create output database: %s\n", |
| sqlite3_errmsg(newDb)); |
| }else{ |
| sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); |
| sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); |
| tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); |
| tryToCloneSchema(p, newDb, "type!='table'", 0); |
| sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); |
| sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); |
| } |
| sqlite3_close(newDb); |
| } |
| |
| /* |
| ** Change the output file back to stdout |
| */ |
| static void output_reset(ShellState *p){ |
| if( p->outfile[0]=='|' ){ |
| #ifndef SQLITE_OMIT_POPEN |
| pclose(p->out); |
| #endif |
| }else{ |
| output_file_close(p->out); |
| } |
| p->outfile[0] = 0; |
| p->out = stdout; |
| } |
| |
| /* |
| ** Run an SQL command and return the single integer result. |
| */ |
| static int db_int(ShellState *p, const char *zSql){ |
| sqlite3_stmt *pStmt; |
| int res = 0; |
| sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); |
| if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ |
| res = sqlite3_column_int(pStmt,0); |
| } |
| sqlite3_finalize(pStmt); |
| return res; |
| } |
| |
| /* |
| ** Convert a 2-byte or 4-byte big-endian integer into a native integer |
| */ |
| unsigned int get2byteInt(unsigned char *a){ |
| return (a[0]<<8) + a[1]; |
| } |
| unsigned int get4byteInt(unsigned char *a){ |
| return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; |
| } |
| |
| /* |
| ** Implementation of the ".info" command. |
| ** |
| ** Return 1 on error, 2 to exit, and 0 otherwise. |
| */ |
| static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ |
| static const struct { const char |