andre@0: /* andre@0: ** 2001 September 15 andre@0: ** andre@0: ** The author disclaims copyright to this source code. In place of andre@0: ** a legal notice, here is a blessing: andre@0: ** andre@0: ** May you do good and not evil. andre@0: ** May you find forgiveness for yourself and forgive others. andre@0: ** May you share freely, never taking more than you give. andre@0: ** andre@0: ************************************************************************* andre@0: ** This file contains code to implement the "sqlite" command line andre@0: ** utility for accessing SQLite databases. andre@0: */ andre@0: #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) andre@0: /* This needs to come before any includes for MSVC compiler */ andre@0: #define _CRT_SECURE_NO_WARNINGS andre@0: #endif andre@0: andre@0: /* andre@0: ** Enable large-file support for fopen() and friends on unix. andre@0: */ andre@0: #ifndef SQLITE_DISABLE_LFS andre@0: # define _LARGE_FILE 1 andre@0: # ifndef _FILE_OFFSET_BITS andre@0: # define _FILE_OFFSET_BITS 64 andre@0: # endif andre@0: # define _LARGEFILE_SOURCE 1 andre@0: #endif andre@0: andre@0: #include andre@0: #include andre@0: #include andre@0: #include andre@0: #include "sqlite3.h" andre@0: #include andre@0: #include andre@0: andre@0: #if !defined(_WIN32) && !defined(WIN32) andre@0: # include andre@0: # if !defined(__RTP__) && !defined(_WRS_KERNEL) andre@0: # include andre@0: # endif andre@0: # include andre@0: # include andre@0: #endif andre@0: andre@0: #if defined(HAVE_READLINE) && HAVE_READLINE!=0 andre@0: # include andre@0: # include andre@0: #else andre@0: # undef HAVE_READLINE andre@0: #endif andre@0: #if defined(HAVE_EDITLINE) && !defined(HAVE_READLINE) andre@0: # define HAVE_READLINE 1 andre@0: # include andre@0: #endif andre@0: #if !defined(HAVE_READLINE) andre@0: # define add_history(X) andre@0: # define read_history(X) andre@0: # define write_history(X) andre@0: # define stifle_history(X) andre@0: #endif andre@0: andre@0: #if defined(_WIN32) || defined(WIN32) andre@0: # include andre@0: #define isatty(h) _isatty(h) andre@0: #ifndef access andre@0: # define access(f,m) _access((f),(m)) andre@0: #endif andre@0: #undef popen andre@0: #define popen _popen andre@0: #undef pclose andre@0: #define pclose _pclose andre@0: #else andre@0: /* Make sure isatty() has a prototype. andre@0: */ andre@0: extern int isatty(int); andre@0: andre@0: /* popen and pclose are not C89 functions and so are sometimes omitted from andre@0: ** the header */ andre@0: extern FILE *popen(const char*,const char*); andre@0: extern int pclose(FILE*); andre@0: #endif andre@0: andre@0: #if defined(_WIN32_WCE) andre@0: /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() andre@0: * thus we always assume that we have a console. That can be andre@0: * overridden with the -batch command line option. andre@0: */ andre@0: #define isatty(x) 1 andre@0: #endif andre@0: andre@0: /* ctype macros that work with signed characters */ andre@0: #define IsSpace(X) isspace((unsigned char)X) andre@0: #define IsDigit(X) isdigit((unsigned char)X) andre@0: #define ToLower(X) (char)tolower((unsigned char)X) andre@0: andre@0: andre@0: /* True if the timer is enabled */ andre@0: static int enableTimer = 0; andre@0: andre@0: /* Return the current wall-clock time */ andre@0: static sqlite3_int64 timeOfDay(void){ andre@0: static sqlite3_vfs *clockVfs = 0; andre@0: sqlite3_int64 t; andre@0: if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); andre@0: if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){ andre@0: clockVfs->xCurrentTimeInt64(clockVfs, &t); andre@0: }else{ andre@0: double r; andre@0: clockVfs->xCurrentTime(clockVfs, &r); andre@0: t = (sqlite3_int64)(r*86400000.0); andre@0: } andre@0: return t; andre@0: } andre@0: andre@0: #if !defined(_WIN32) && !defined(WIN32) && !defined(_WRS_KERNEL) \ andre@0: && !defined(__minux) andre@0: #include andre@0: #include andre@0: andre@0: /* Saved resource information for the beginning of an operation */ andre@0: static struct rusage sBegin; /* CPU time at start */ andre@0: static sqlite3_int64 iBegin; /* Wall-clock time at start */ andre@0: andre@0: /* andre@0: ** Begin timing an operation andre@0: */ andre@0: static void beginTimer(void){ andre@0: if( enableTimer ){ andre@0: getrusage(RUSAGE_SELF, &sBegin); andre@0: iBegin = timeOfDay(); andre@0: } andre@0: } andre@0: andre@0: /* Return the difference of two time_structs in seconds */ andre@0: static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ andre@0: return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + andre@0: (double)(pEnd->tv_sec - pStart->tv_sec); andre@0: } andre@0: andre@0: /* andre@0: ** Print the timing results. andre@0: */ andre@0: static void endTimer(void){ andre@0: if( enableTimer ){ andre@0: struct rusage sEnd; andre@0: sqlite3_int64 iEnd = timeOfDay(); andre@0: getrusage(RUSAGE_SELF, &sEnd); andre@0: printf("Run Time: real %.3f user %f sys %f\n", andre@0: (iEnd - iBegin)*0.001, andre@0: timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), andre@0: timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); andre@0: } andre@0: } andre@0: andre@0: #define BEGIN_TIMER beginTimer() andre@0: #define END_TIMER endTimer() andre@0: #define HAS_TIMER 1 andre@0: andre@0: #elif (defined(_WIN32) || defined(WIN32)) andre@0: andre@0: #include andre@0: andre@0: /* Saved resource information for the beginning of an operation */ andre@0: static HANDLE hProcess; andre@0: static FILETIME ftKernelBegin; andre@0: static FILETIME ftUserBegin; andre@0: static sqlite3_int64 ftWallBegin; andre@0: typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); andre@0: static GETPROCTIMES getProcessTimesAddr = NULL; andre@0: andre@0: /* andre@0: ** Check to see if we have timer support. Return 1 if necessary andre@0: ** support found (or found previously). andre@0: */ andre@0: static int hasTimer(void){ andre@0: if( getProcessTimesAddr ){ andre@0: return 1; andre@0: } else { andre@0: /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions. andre@0: ** See if the version we are running on has it, and if it does, save off andre@0: ** a pointer to it and the current process handle. andre@0: */ andre@0: hProcess = GetCurrentProcess(); andre@0: if( hProcess ){ andre@0: HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); andre@0: if( NULL != hinstLib ){ andre@0: getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); andre@0: if( NULL != getProcessTimesAddr ){ andre@0: return 1; andre@0: } andre@0: FreeLibrary(hinstLib); andre@0: } andre@0: } andre@0: } andre@0: return 0; andre@0: } andre@0: andre@0: /* andre@0: ** Begin timing an operation andre@0: */ andre@0: static void beginTimer(void){ andre@0: if( enableTimer && getProcessTimesAddr ){ andre@0: FILETIME ftCreation, ftExit; andre@0: getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin); andre@0: ftWallBegin = timeOfDay(); andre@0: } andre@0: } andre@0: andre@0: /* Return the difference of two FILETIME structs in seconds */ andre@0: static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ andre@0: sqlite_int64 i64Start = *((sqlite_int64 *) pStart); andre@0: sqlite_int64 i64End = *((sqlite_int64 *) pEnd); andre@0: return (double) ((i64End - i64Start) / 10000000.0); andre@0: } andre@0: andre@0: /* andre@0: ** Print the timing results. andre@0: */ andre@0: static void endTimer(void){ andre@0: if( enableTimer && getProcessTimesAddr){ andre@0: FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; andre@0: sqlite3_int64 ftWallEnd = timeOfDay(); andre@0: getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd); andre@0: printf("Run Time: real %.3f user %f sys %f\n", andre@0: (ftWallEnd - ftWallBegin)*0.001, andre@0: timeDiff(&ftUserBegin, &ftUserEnd), andre@0: timeDiff(&ftKernelBegin, &ftKernelEnd)); andre@0: } andre@0: } andre@0: andre@0: #define BEGIN_TIMER beginTimer() andre@0: #define END_TIMER endTimer() andre@0: #define HAS_TIMER hasTimer() andre@0: andre@0: #else andre@0: #define BEGIN_TIMER andre@0: #define END_TIMER andre@0: #define HAS_TIMER 0 andre@0: #endif andre@0: andre@0: /* andre@0: ** Used to prevent warnings about unused parameters andre@0: */ andre@0: #define UNUSED_PARAMETER(x) (void)(x) andre@0: andre@0: /* andre@0: ** If the following flag is set, then command execution stops andre@0: ** at an error if we are not interactive. andre@0: */ andre@0: static int bail_on_error = 0; andre@0: andre@0: /* andre@0: ** Threat stdin as an interactive input if the following variable andre@0: ** is true. Otherwise, assume stdin is connected to a file or pipe. andre@0: */ andre@0: static int stdin_is_interactive = 1; andre@0: andre@0: /* andre@0: ** The following is the open SQLite database. We make a pointer andre@0: ** to this database a static variable so that it can be accessed andre@0: ** by the SIGINT handler to interrupt database processing. andre@0: */ andre@0: static sqlite3 *db = 0; andre@0: andre@0: /* andre@0: ** True if an interrupt (Control-C) has been received. andre@0: */ andre@0: static volatile int seenInterrupt = 0; andre@0: andre@0: /* andre@0: ** This is the name of our program. It is set in main(), used andre@0: ** in a number of other places, mostly for error messages. andre@0: */ andre@0: static char *Argv0; andre@0: andre@0: /* andre@0: ** Prompt strings. Initialized in main. Settable with andre@0: ** .prompt main continue andre@0: */ andre@0: static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ andre@0: static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ andre@0: andre@0: /* andre@0: ** Write I/O traces to the following stream. andre@0: */ andre@0: #ifdef SQLITE_ENABLE_IOTRACE andre@0: static FILE *iotrace = 0; andre@0: #endif andre@0: andre@0: /* andre@0: ** This routine works like printf in that its first argument is a andre@0: ** format string and subsequent arguments are values to be substituted andre@0: ** in place of % fields. The result of formatting this string andre@0: ** is written to iotrace. andre@0: */ andre@0: #ifdef SQLITE_ENABLE_IOTRACE andre@0: static void iotracePrintf(const char *zFormat, ...){ andre@0: va_list ap; andre@0: char *z; andre@0: if( iotrace==0 ) return; andre@0: va_start(ap, zFormat); andre@0: z = sqlite3_vmprintf(zFormat, ap); andre@0: va_end(ap); andre@0: fprintf(iotrace, "%s", z); andre@0: sqlite3_free(z); andre@0: } andre@0: #endif andre@0: andre@0: andre@0: /* andre@0: ** Determines if a string is a number of not. andre@0: */ andre@0: static int isNumber(const char *z, int *realnum){ andre@0: if( *z=='-' || *z=='+' ) z++; andre@0: if( !IsDigit(*z) ){ andre@0: return 0; andre@0: } andre@0: z++; andre@0: if( realnum ) *realnum = 0; andre@0: while( IsDigit(*z) ){ z++; } andre@0: if( *z=='.' ){ andre@0: z++; andre@0: if( !IsDigit(*z) ) return 0; andre@0: while( IsDigit(*z) ){ z++; } andre@0: if( realnum ) *realnum = 1; andre@0: } andre@0: if( *z=='e' || *z=='E' ){ andre@0: z++; andre@0: if( *z=='+' || *z=='-' ) z++; andre@0: if( !IsDigit(*z) ) return 0; andre@0: while( IsDigit(*z) ){ z++; } andre@0: if( realnum ) *realnum = 1; andre@0: } andre@0: return *z==0; andre@0: } andre@0: andre@0: /* andre@0: ** A global char* and an SQL function to access its current value andre@0: ** from within an SQL statement. This program used to use the andre@0: ** sqlite_exec_printf() API to substitue a string into an SQL statement. andre@0: ** The correct way to do this with sqlite3 is to use the bind API, but andre@0: ** since the shell is built around the callback paradigm it would be a lot andre@0: ** of work. Instead just use this hack, which is quite harmless. andre@0: */ andre@0: static const char *zShellStatic = 0; andre@0: static void shellstaticFunc( andre@0: sqlite3_context *context, andre@0: int argc, andre@0: sqlite3_value **argv andre@0: ){ andre@0: assert( 0==argc ); andre@0: assert( zShellStatic ); andre@0: UNUSED_PARAMETER(argc); andre@0: UNUSED_PARAMETER(argv); andre@0: sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); andre@0: } andre@0: andre@0: andre@0: /* andre@0: ** This routine reads a line of text from FILE in, stores andre@0: ** the text in memory obtained from malloc() and returns a pointer andre@0: ** to the text. NULL is returned at end of file, or if malloc() andre@0: ** fails. andre@0: ** andre@0: ** If zLine is not NULL then it is a malloced buffer returned from andre@0: ** a previous call to this routine that may be reused. andre@0: */ andre@0: static char *local_getline(char *zLine, FILE *in){ andre@0: int nLine = zLine==0 ? 0 : 100; andre@0: int n = 0; andre@0: andre@0: while( 1 ){ andre@0: if( n+100>nLine ){ andre@0: nLine = nLine*2 + 100; andre@0: zLine = realloc(zLine, nLine); andre@0: if( zLine==0 ) return 0; andre@0: } andre@0: if( fgets(&zLine[n], nLine - n, in)==0 ){ andre@0: if( n==0 ){ andre@0: free(zLine); andre@0: return 0; andre@0: } andre@0: zLine[n] = 0; andre@0: break; andre@0: } andre@0: while( zLine[n] ) n++; andre@0: if( n>0 && zLine[n-1]=='\n' ){ andre@0: n--; andre@0: if( n>0 && zLine[n-1]=='\r' ) n--; andre@0: zLine[n] = 0; andre@0: break; andre@0: } andre@0: } andre@0: return zLine; andre@0: } andre@0: andre@0: /* andre@0: ** Retrieve a single line of input text. andre@0: ** andre@0: ** If in==0 then read from standard input and prompt before each line. andre@0: ** If isContinuation is true, then a continuation prompt is appropriate. andre@0: ** If isContinuation is zero, then the main prompt should be used. andre@0: ** andre@0: ** If zPrior is not NULL then it is a buffer from a prior call to this andre@0: ** routine that can be reused. andre@0: ** andre@0: ** The result is stored in space obtained from malloc() and must either andre@0: ** be freed by the caller or else passed back into this routine via the andre@0: ** zPrior argument for reuse. andre@0: */ andre@0: static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ andre@0: char *zPrompt; andre@0: char *zResult; andre@0: if( in!=0 ){ andre@0: zResult = local_getline(zPrior, in); andre@0: }else{ andre@0: zPrompt = isContinuation ? continuePrompt : mainPrompt; andre@0: #if defined(HAVE_READLINE) andre@0: free(zPrior); andre@0: zResult = readline(zPrompt); andre@0: if( zResult && *zResult ) add_history(zResult); andre@0: #else andre@0: printf("%s", zPrompt); andre@0: fflush(stdout); andre@0: zResult = local_getline(zPrior, stdin); andre@0: #endif andre@0: } andre@0: return zResult; andre@0: } andre@0: andre@0: struct previous_mode_data { andre@0: int valid; /* Is there legit data in here? */ andre@0: int mode; andre@0: int showHeader; andre@0: int colWidth[100]; andre@0: }; andre@0: andre@0: /* andre@0: ** An pointer to an instance of this structure is passed from andre@0: ** the main program to the callback. This is used to communicate andre@0: ** state and mode information. andre@0: */ andre@0: struct callback_data { andre@0: sqlite3 *db; /* The database */ andre@0: int echoOn; /* True to echo input commands */ andre@0: int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ andre@0: int statsOn; /* True to display memory stats before each finalize */ andre@0: int outCount; /* Revert to stdout when reaching zero */ andre@0: int cnt; /* Number of records displayed so far */ andre@0: FILE *out; /* Write results here */ andre@0: FILE *traceOut; /* Output for sqlite3_trace() */ andre@0: int nErr; /* Number of errors seen */ andre@0: int mode; /* An output mode setting */ andre@0: int writableSchema; /* True if PRAGMA writable_schema=ON */ andre@0: int showHeader; /* True to show column names in List or Column mode */ andre@0: char *zDestTable; /* Name of destination table when MODE_Insert */ andre@0: char separator[20]; /* Separator character for MODE_List */ andre@0: int colWidth[100]; /* Requested width of each column when in column mode*/ andre@0: int actualWidth[100]; /* Actual width of each column */ andre@0: char nullvalue[20]; /* The text to print when a NULL comes back from andre@0: ** the database */ andre@0: struct previous_mode_data explainPrev; andre@0: /* Holds the mode information just before andre@0: ** .explain ON */ andre@0: char outfile[FILENAME_MAX]; /* Filename for *out */ andre@0: const char *zDbFilename; /* name of the database file */ andre@0: char *zFreeOnClose; /* Filename to free when closing */ andre@0: const char *zVfs; /* Name of VFS to use */ andre@0: sqlite3_stmt *pStmt; /* Current statement if any. */ andre@0: FILE *pLog; /* Write log output here */ andre@0: int *aiIndent; /* Array of indents used in MODE_Explain */ andre@0: int nIndent; /* Size of array aiIndent[] */ andre@0: int iIndent; /* Index of current op in aiIndent[] */ andre@0: }; andre@0: andre@0: /* andre@0: ** These are the allowed modes. andre@0: */ andre@0: #define MODE_Line 0 /* One column per line. Blank line between records */ andre@0: #define MODE_Column 1 /* One record per line in neat columns */ andre@0: #define MODE_List 2 /* One record per line with a separator */ andre@0: #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ andre@0: #define MODE_Html 4 /* Generate an XHTML table */ andre@0: #define MODE_Insert 5 /* Generate SQL "insert" statements */ andre@0: #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */ andre@0: #define MODE_Csv 7 /* Quote strings, numbers are plain */ andre@0: #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */ andre@0: andre@0: static const char *modeDescr[] = { andre@0: "line", andre@0: "column", andre@0: "list", andre@0: "semi", andre@0: "html", andre@0: "insert", andre@0: "tcl", andre@0: "csv", andre@0: "explain", andre@0: }; andre@0: andre@0: /* andre@0: ** Number of elements in an array andre@0: */ andre@0: #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) andre@0: andre@0: /* andre@0: ** Compute a string length that is limited to what can be stored in andre@0: ** lower 30 bits of a 32-bit signed integer. andre@0: */ andre@0: static int strlen30(const char *z){ andre@0: const char *z2 = z; andre@0: while( *z2 ){ z2++; } andre@0: return 0x3fffffff & (int)(z2 - z); andre@0: } andre@0: andre@0: /* andre@0: ** A callback for the sqlite3_log() interface. andre@0: */ andre@0: static void shellLog(void *pArg, int iErrCode, const char *zMsg){ andre@0: struct callback_data *p = (struct callback_data*)pArg; andre@0: if( p->pLog==0 ) return; andre@0: fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); andre@0: fflush(p->pLog); andre@0: } andre@0: andre@0: /* andre@0: ** Output the given string as a hex-encoded blob (eg. X'1234' ) andre@0: */ andre@0: static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ andre@0: int i; andre@0: char *zBlob = (char *)pBlob; andre@0: fprintf(out,"X'"); andre@0: for(i=0; i0 ){ andre@0: fprintf(out,"%.*s",i,z); andre@0: } andre@0: if( z[i]=='<' ){ andre@0: fprintf(out,"<"); andre@0: }else if( z[i]=='&' ){ andre@0: fprintf(out,"&"); andre@0: }else if( z[i]=='>' ){ andre@0: fprintf(out,">"); andre@0: }else if( z[i]=='\"' ){ andre@0: fprintf(out,"""); andre@0: }else if( z[i]=='\'' ){ andre@0: fprintf(out,"'"); andre@0: }else{ andre@0: break; andre@0: } andre@0: z += i + 1; andre@0: } andre@0: } andre@0: andre@0: /* andre@0: ** If a field contains any character identified by a 1 in the following andre@0: ** array, then the string must be quoted for CSV. andre@0: */ andre@0: static const char needCsvQuote[] = { andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, andre@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, andre@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, andre@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, andre@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, andre@0: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, andre@0: }; andre@0: andre@0: /* andre@0: ** Output a single term of CSV. Actually, p->separator is used for andre@0: ** the separator, which may or may not be a comma. p->nullvalue is andre@0: ** the null value. Strings are quoted if necessary. andre@0: */ andre@0: static void output_csv(struct callback_data *p, const char *z, int bSep){ andre@0: FILE *out = p->out; andre@0: if( z==0 ){ andre@0: fprintf(out,"%s",p->nullvalue); andre@0: }else{ andre@0: int i; andre@0: int nSep = strlen30(p->separator); andre@0: for(i=0; z[i]; i++){ andre@0: if( needCsvQuote[((unsigned char*)z)[i]] andre@0: || (z[i]==p->separator[0] && andre@0: (nSep==1 || memcmp(z, p->separator, nSep)==0)) ){ andre@0: i = 0; andre@0: break; andre@0: } andre@0: } andre@0: if( i==0 ){ andre@0: putc('"', out); andre@0: for(i=0; z[i]; i++){ andre@0: if( z[i]=='"' ) putc('"', out); andre@0: putc(z[i], out); andre@0: } andre@0: putc('"', out); andre@0: }else{ andre@0: fprintf(out, "%s", z); andre@0: } andre@0: } andre@0: if( bSep ){ andre@0: fprintf(p->out, "%s", p->separator); andre@0: } andre@0: } andre@0: andre@0: #ifdef SIGINT andre@0: /* andre@0: ** This routine runs when the user presses Ctrl-C andre@0: */ andre@0: static void interrupt_handler(int NotUsed){ andre@0: UNUSED_PARAMETER(NotUsed); andre@0: seenInterrupt++; andre@0: if( seenInterrupt>2 ) exit(1); andre@0: if( db ) sqlite3_interrupt(db); andre@0: } andre@0: #endif andre@0: andre@0: /* andre@0: ** This is the callback routine that the shell andre@0: ** invokes for each row of a query result. andre@0: */ andre@0: static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){ andre@0: int i; andre@0: struct callback_data *p = (struct callback_data*)pArg; andre@0: andre@0: switch( p->mode ){ andre@0: case MODE_Line: { andre@0: int w = 5; andre@0: if( azArg==0 ) break; andre@0: for(i=0; iw ) w = len; andre@0: } andre@0: if( p->cnt++>0 ) fprintf(p->out,"\n"); andre@0: for(i=0; iout,"%*s = %s\n", w, azCol[i], andre@0: azArg[i] ? azArg[i] : p->nullvalue); andre@0: } andre@0: break; andre@0: } andre@0: case MODE_Explain: andre@0: case MODE_Column: { andre@0: if( p->cnt++==0 ){ andre@0: for(i=0; icolWidth) ){ andre@0: w = p->colWidth[i]; andre@0: }else{ andre@0: w = 0; andre@0: } andre@0: if( w==0 ){ andre@0: w = strlen30(azCol[i] ? azCol[i] : ""); andre@0: if( w<10 ) w = 10; andre@0: n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue); andre@0: if( wactualWidth) ){ andre@0: p->actualWidth[i] = w; andre@0: } andre@0: if( p->showHeader ){ andre@0: if( w<0 ){ andre@0: fprintf(p->out,"%*.*s%s",-w,-w,azCol[i], i==nArg-1 ? "\n": " "); andre@0: }else{ andre@0: fprintf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? "\n": " "); andre@0: } andre@0: } andre@0: } andre@0: if( p->showHeader ){ andre@0: for(i=0; iactualWidth) ){ andre@0: w = p->actualWidth[i]; andre@0: if( w<0 ) w = -w; andre@0: }else{ andre@0: w = 10; andre@0: } andre@0: fprintf(p->out,"%-*.*s%s",w,w,"-----------------------------------" andre@0: "----------------------------------------------------------", andre@0: i==nArg-1 ? "\n": " "); andre@0: } andre@0: } andre@0: } andre@0: if( azArg==0 ) break; andre@0: for(i=0; iactualWidth) ){ andre@0: w = p->actualWidth[i]; andre@0: }else{ andre@0: w = 10; andre@0: } andre@0: if( p->mode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){ andre@0: w = strlen30(azArg[i]); andre@0: } andre@0: if( i==1 && p->aiIndent && p->pStmt ){ andre@0: if( p->iIndentnIndent ){ andre@0: fprintf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); andre@0: } andre@0: p->iIndent++; andre@0: } andre@0: if( w<0 ){ andre@0: fprintf(p->out,"%*.*s%s",-w,-w, andre@0: azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); andre@0: }else{ andre@0: fprintf(p->out,"%-*.*s%s",w,w, andre@0: azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); andre@0: } andre@0: } andre@0: break; andre@0: } andre@0: case MODE_Semi: andre@0: case MODE_List: { andre@0: if( p->cnt++==0 && p->showHeader ){ andre@0: for(i=0; iout,"%s%s",azCol[i], i==nArg-1 ? "\n" : p->separator); andre@0: } andre@0: } andre@0: if( azArg==0 ) break; andre@0: for(i=0; inullvalue; andre@0: fprintf(p->out, "%s", z); andre@0: if( iout, "%s", p->separator); andre@0: }else if( p->mode==MODE_Semi ){ andre@0: fprintf(p->out, ";\n"); andre@0: }else{ andre@0: fprintf(p->out, "\n"); andre@0: } andre@0: } andre@0: break; andre@0: } andre@0: case MODE_Html: { andre@0: if( p->cnt++==0 && p->showHeader ){ andre@0: fprintf(p->out,""); andre@0: for(i=0; iout,""); andre@0: output_html_string(p->out, azCol[i]); andre@0: fprintf(p->out,"\n"); andre@0: } andre@0: fprintf(p->out,"\n"); andre@0: } andre@0: if( azArg==0 ) break; andre@0: fprintf(p->out,""); andre@0: for(i=0; iout,""); andre@0: output_html_string(p->out, azArg[i] ? azArg[i] : p->nullvalue); andre@0: fprintf(p->out,"\n"); andre@0: } andre@0: fprintf(p->out,"\n"); andre@0: break; andre@0: } andre@0: case MODE_Tcl: { andre@0: if( p->cnt++==0 && p->showHeader ){ andre@0: for(i=0; iout,azCol[i] ? azCol[i] : ""); andre@0: if(iout, "%s", p->separator); andre@0: } andre@0: fprintf(p->out,"\n"); andre@0: } andre@0: if( azArg==0 ) break; andre@0: for(i=0; iout, azArg[i] ? azArg[i] : p->nullvalue); andre@0: if(iout, "%s", p->separator); andre@0: } andre@0: fprintf(p->out,"\n"); andre@0: break; andre@0: } andre@0: case MODE_Csv: { andre@0: if( p->cnt++==0 && p->showHeader ){ andre@0: for(i=0; iout,"\n"); andre@0: } andre@0: if( azArg==0 ) break; andre@0: for(i=0; iout,"\n"); andre@0: break; andre@0: } andre@0: case MODE_Insert: { andre@0: p->cnt++; andre@0: if( azArg==0 ) break; andre@0: fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable); andre@0: for(i=0; i0 ? ",": ""; andre@0: if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ andre@0: fprintf(p->out,"%sNULL",zSep); andre@0: }else if( aiType && aiType[i]==SQLITE_TEXT ){ andre@0: if( zSep[0] ) fprintf(p->out,"%s",zSep); andre@0: output_quoted_string(p->out, azArg[i]); andre@0: }else if( aiType && (aiType[i]==SQLITE_INTEGER andre@0: || aiType[i]==SQLITE_FLOAT) ){ andre@0: fprintf(p->out,"%s%s",zSep, azArg[i]); andre@0: }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ andre@0: const void *pBlob = sqlite3_column_blob(p->pStmt, i); andre@0: int nBlob = sqlite3_column_bytes(p->pStmt, i); andre@0: if( zSep[0] ) fprintf(p->out,"%s",zSep); andre@0: output_hex_blob(p->out, pBlob, nBlob); andre@0: }else if( isNumber(azArg[i], 0) ){ andre@0: fprintf(p->out,"%s%s",zSep, azArg[i]); andre@0: }else{ andre@0: if( zSep[0] ) fprintf(p->out,"%s",zSep); andre@0: output_quoted_string(p->out, azArg[i]); andre@0: } andre@0: } andre@0: fprintf(p->out,");\n"); andre@0: break; andre@0: } andre@0: } andre@0: return 0; andre@0: } andre@0: andre@0: /* andre@0: ** This is the callback routine that the SQLite library andre@0: ** invokes for each row of a query result. andre@0: */ andre@0: static int callback(void *pArg, int nArg, char **azArg, char **azCol){ andre@0: /* since we don't have type info, call the shell_callback with a NULL value */ andre@0: return shell_callback(pArg, nArg, azArg, azCol, NULL); andre@0: } andre@0: andre@0: /* andre@0: ** Set the destination table field of the callback_data structure to andre@0: ** the name of the table given. Escape any quote characters in the andre@0: ** table name. andre@0: */ andre@0: static void set_table_name(struct callback_data *p, const char *zName){ andre@0: int i, n; andre@0: int needQuote; andre@0: char *z; andre@0: andre@0: if( p->zDestTable ){ andre@0: free(p->zDestTable); andre@0: p->zDestTable = 0; andre@0: } andre@0: if( zName==0 ) return; andre@0: needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; andre@0: for(i=n=0; zName[i]; i++, n++){ andre@0: if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ andre@0: needQuote = 1; andre@0: if( zName[i]=='\'' ) n++; andre@0: } andre@0: } andre@0: if( needQuote ) n += 2; andre@0: z = p->zDestTable = malloc( n+1 ); andre@0: if( z==0 ){ andre@0: fprintf(stderr,"Error: out of memory\n"); andre@0: exit(1); andre@0: } andre@0: n = 0; andre@0: if( needQuote ) z[n++] = '\''; andre@0: for(i=0; zName[i]; i++){ andre@0: z[n++] = zName[i]; andre@0: if( zName[i]=='\'' ) z[n++] = '\''; andre@0: } andre@0: if( needQuote ) z[n++] = '\''; andre@0: z[n] = 0; andre@0: } andre@0: andre@0: /* zIn is either a pointer to a NULL-terminated string in memory obtained andre@0: ** from malloc(), or a NULL pointer. The string pointed to by zAppend is andre@0: ** added to zIn, and the result returned in memory obtained from malloc(). andre@0: ** zIn, if it was not NULL, is freed. andre@0: ** andre@0: ** If the third argument, quote, is not '\0', then it is used as a andre@0: ** quote character for zAppend. andre@0: */ andre@0: static char *appendText(char *zIn, char const *zAppend, char quote){ andre@0: int len; andre@0: int i; andre@0: int nAppend = strlen30(zAppend); andre@0: int nIn = (zIn?strlen30(zIn):0); andre@0: andre@0: len = nAppend+nIn+1; andre@0: if( quote ){ andre@0: len += 2; andre@0: for(i=0; idb, zSelect, -1, &pSelect, 0); andre@0: if( rc!=SQLITE_OK || !pSelect ){ andre@0: fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); andre@0: if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; andre@0: return rc; andre@0: } andre@0: rc = sqlite3_step(pSelect); andre@0: nResult = sqlite3_column_count(pSelect); andre@0: while( rc==SQLITE_ROW ){ andre@0: if( zFirstRow ){ andre@0: fprintf(p->out, "%s", zFirstRow); andre@0: zFirstRow = 0; andre@0: } andre@0: z = (const char*)sqlite3_column_text(pSelect, 0); andre@0: fprintf(p->out, "%s", z); andre@0: for(i=1; iout, ",%s", sqlite3_column_text(pSelect, i)); andre@0: } andre@0: if( z==0 ) z = ""; andre@0: while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; andre@0: if( z[0] ){ andre@0: fprintf(p->out, "\n;\n"); andre@0: }else{ andre@0: fprintf(p->out, ";\n"); andre@0: } andre@0: rc = sqlite3_step(pSelect); andre@0: } andre@0: rc = sqlite3_finalize(pSelect); andre@0: if( rc!=SQLITE_OK ){ andre@0: fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); andre@0: if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; andre@0: } andre@0: return rc; andre@0: } andre@0: andre@0: /* andre@0: ** Allocate space and save off current error string. andre@0: */ andre@0: static char *save_err_msg( andre@0: sqlite3 *db /* Database to query */ andre@0: ){ andre@0: int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); andre@0: char *zErrMsg = sqlite3_malloc(nErrMsg); andre@0: if( zErrMsg ){ andre@0: memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); andre@0: } andre@0: return zErrMsg; andre@0: } andre@0: andre@0: /* andre@0: ** Display memory stats. andre@0: */ andre@0: static int display_stats( andre@0: sqlite3 *db, /* Database to query */ andre@0: struct callback_data *pArg, /* Pointer to struct callback_data */ andre@0: int bReset /* True to reset the stats */ andre@0: ){ andre@0: int iCur; andre@0: int iHiwtr; andre@0: andre@0: if( pArg && pArg->out ){ andre@0: andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr); andre@0: /* andre@0: ** Not currently used by the CLI. andre@0: ** iHiwtr = iCur = -1; andre@0: ** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); andre@0: ** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr); andre@0: */ andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); andre@0: /* andre@0: ** Not currently used by the CLI. andre@0: ** iHiwtr = iCur = -1; andre@0: ** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); andre@0: ** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr); andre@0: */ andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr); andre@0: #ifdef YYTRACKMAXSTACKDEPTH andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr); andre@0: #endif andre@0: } andre@0: andre@0: if( pArg && pArg->out && db ){ andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); andre@0: fprintf(pArg->out, "Page cache hits: %d\n", iCur); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); andre@0: fprintf(pArg->out, "Page cache misses: %d\n", iCur); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); andre@0: fprintf(pArg->out, "Page cache writes: %d\n", iCur); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); andre@0: iHiwtr = iCur = -1; andre@0: sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); andre@0: fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); andre@0: } andre@0: andre@0: if( pArg && pArg->out && db && pArg->pStmt ){ andre@0: iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); andre@0: fprintf(pArg->out, "Fullscan Steps: %d\n", iCur); andre@0: iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); andre@0: fprintf(pArg->out, "Sort Operations: %d\n", iCur); andre@0: iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset); andre@0: fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur); andre@0: iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); andre@0: fprintf(pArg->out, "Virtual Machine Steps: %d\n", iCur); andre@0: } andre@0: andre@0: return 0; andre@0: } andre@0: andre@0: /* andre@0: ** Parameter azArray points to a zero-terminated array of strings. zStr andre@0: ** points to a single nul-terminated string. Return non-zero if zStr andre@0: ** is equal, according to strcmp(), to any of the strings in the array. andre@0: ** Otherwise, return zero. andre@0: */ andre@0: static int str_in_array(const char *zStr, const char **azArray){ andre@0: int i; andre@0: for(i=0; azArray[i]; i++){ andre@0: if( 0==strcmp(zStr, azArray[i]) ) return 1; andre@0: } andre@0: return 0; andre@0: } andre@0: andre@0: /* andre@0: ** If compiled statement pSql appears to be an EXPLAIN statement, allocate andre@0: ** and populate the callback_data.aiIndent[] array with the number of andre@0: ** spaces each opcode should be indented before it is output. andre@0: ** andre@0: ** The indenting rules are: andre@0: ** andre@0: ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent andre@0: ** all opcodes that occur between the p2 jump destination and the opcode andre@0: ** itself by 2 spaces. andre@0: ** andre@0: ** * For each "Goto", if the jump destination is earlier in the program andre@0: ** and ends on one of: andre@0: ** Yield SeekGt SeekLt RowSetRead Rewind andre@0: ** or if the P1 parameter is one instead of zero, andre@0: ** then indent all opcodes between the earlier instruction andre@0: ** and "Goto" by 2 spaces. andre@0: */ andre@0: static void explain_data_prepare(struct callback_data *p, sqlite3_stmt *pSql){ andre@0: const char *zSql; /* The text of the SQL statement */ andre@0: const char *z; /* Used to check if this is an EXPLAIN */ andre@0: int *abYield = 0; /* True if op is an OP_Yield */ andre@0: int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ andre@0: int iOp; /* Index of operation in p->aiIndent[] */ andre@0: andre@0: const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", andre@0: "NextIfOpen", "PrevIfOpen", 0 }; andre@0: const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", "Rewind", 0 }; andre@0: const char *azGoto[] = { "Goto", 0 }; andre@0: andre@0: /* Try to figure out if this is really an EXPLAIN statement. If this andre@0: ** cannot be verified, return early. */ andre@0: zSql = sqlite3_sql(pSql); andre@0: if( zSql==0 ) return; andre@0: for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); andre@0: if( sqlite3_strnicmp(z, "explain", 7) ) return; andre@0: andre@0: for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ andre@0: int i; andre@0: int iAddr = sqlite3_column_int(pSql, 0); andre@0: const char *zOp = (const char*)sqlite3_column_text(pSql, 1); andre@0: andre@0: /* Set p2 to the P2 field of the current opcode. Then, assuming that andre@0: ** p2 is an instruction address, set variable p2op to the index of that andre@0: ** instruction in the aiIndent[] array. p2 and p2op may be different if andre@0: ** the current instruction is part of a sub-program generated by an andre@0: ** SQL trigger or foreign key. */ andre@0: int p2 = sqlite3_column_int(pSql, 3); andre@0: int p2op = (p2 + (iOp-iAddr)); andre@0: andre@0: /* Grow the p->aiIndent array as required */ andre@0: if( iOp>=nAlloc ){ andre@0: nAlloc += 100; andre@0: p->aiIndent = (int*)sqlite3_realloc(p->aiIndent, nAlloc*sizeof(int)); andre@0: abYield = (int*)sqlite3_realloc(abYield, nAlloc*sizeof(int)); andre@0: } andre@0: abYield[iOp] = str_in_array(zOp, azYield); andre@0: p->aiIndent[iOp] = 0; andre@0: p->nIndent = iOp+1; andre@0: andre@0: if( str_in_array(zOp, azNext) ){ andre@0: for(i=p2op; iaiIndent[i] += 2; andre@0: } andre@0: if( str_in_array(zOp, azGoto) && p2opnIndent andre@0: && (abYield[p2op] || sqlite3_column_int(pSql, 2)) andre@0: ){ andre@0: for(i=p2op+1; iaiIndent[i] += 2; andre@0: } andre@0: } andre@0: andre@0: p->iIndent = 0; andre@0: sqlite3_free(abYield); andre@0: sqlite3_reset(pSql); andre@0: } andre@0: andre@0: /* andre@0: ** Free the array allocated by explain_data_prepare(). andre@0: */ andre@0: static void explain_data_delete(struct callback_data *p){ andre@0: sqlite3_free(p->aiIndent); andre@0: p->aiIndent = 0; andre@0: p->nIndent = 0; andre@0: p->iIndent = 0; andre@0: } andre@0: andre@0: /* andre@0: ** Execute a statement or set of statements. Print andre@0: ** any result rows/columns depending on the current mode andre@0: ** set via the supplied callback. andre@0: ** andre@0: ** This is very similar to SQLite's built-in sqlite3_exec() andre@0: ** function except it takes a slightly different callback andre@0: ** and callback data argument. andre@0: */ andre@0: static int shell_exec( andre@0: sqlite3 *db, /* An open database */ andre@0: const char *zSql, /* SQL to be evaluated */ andre@0: int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ andre@0: /* (not the same as sqlite3_exec) */ andre@0: struct callback_data *pArg, /* Pointer to struct callback_data */ andre@0: char **pzErrMsg /* Error msg written here */ andre@0: ){ andre@0: sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ andre@0: int rc = SQLITE_OK; /* Return Code */ andre@0: int rc2; andre@0: const char *zLeftover; /* Tail of unprocessed SQL */ andre@0: andre@0: if( pzErrMsg ){ andre@0: *pzErrMsg = NULL; andre@0: } andre@0: andre@0: while( zSql[0] && (SQLITE_OK == rc) ){ andre@0: rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); andre@0: if( SQLITE_OK != rc ){ andre@0: if( pzErrMsg ){ andre@0: *pzErrMsg = save_err_msg(db); andre@0: } andre@0: }else{ andre@0: if( !pStmt ){ andre@0: /* this happens for a comment or white-space */ andre@0: zSql = zLeftover; andre@0: while( IsSpace(zSql[0]) ) zSql++; andre@0: continue; andre@0: } andre@0: andre@0: /* save off the prepared statment handle and reset row count */ andre@0: if( pArg ){ andre@0: pArg->pStmt = pStmt; andre@0: pArg->cnt = 0; andre@0: } andre@0: andre@0: /* echo the sql statement if echo on */ andre@0: if( pArg && pArg->echoOn ){ andre@0: const char *zStmtSql = sqlite3_sql(pStmt); andre@0: fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); andre@0: } andre@0: andre@0: /* Show the EXPLAIN QUERY PLAN if .eqp is on */ andre@0: if( pArg && pArg->autoEQP ){ andre@0: sqlite3_stmt *pExplain; andre@0: char *zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", sqlite3_sql(pStmt)); andre@0: rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); andre@0: if( rc==SQLITE_OK ){ andre@0: while( sqlite3_step(pExplain)==SQLITE_ROW ){ andre@0: fprintf(pArg->out,"--EQP-- %d,", sqlite3_column_int(pExplain, 0)); andre@0: fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1)); andre@0: fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2)); andre@0: fprintf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3)); andre@0: } andre@0: } andre@0: sqlite3_finalize(pExplain); andre@0: sqlite3_free(zEQP); andre@0: } andre@0: andre@0: /* Output TESTCTRL_EXPLAIN text of requested */ andre@0: if( pArg && pArg->mode==MODE_Explain ){ andre@0: const char *zExplain = 0; andre@0: sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain); andre@0: if( zExplain && zExplain[0] ){ andre@0: fprintf(pArg->out, "%s", zExplain); andre@0: } andre@0: } andre@0: andre@0: /* If the shell is currently in ".explain" mode, gather the extra andre@0: ** data required to add indents to the output.*/ andre@0: if( pArg && pArg->mode==MODE_Explain ){ andre@0: explain_data_prepare(pArg, pStmt); andre@0: } andre@0: andre@0: /* perform the first step. this will tell us if we andre@0: ** have a result set or not and how wide it is. andre@0: */ andre@0: rc = sqlite3_step(pStmt); andre@0: /* if we have a result set... */ andre@0: if( SQLITE_ROW == rc ){ andre@0: /* if we have a callback... */ andre@0: if( xCallback ){ andre@0: /* allocate space for col name ptr, value ptr, and type */ andre@0: int nCol = sqlite3_column_count(pStmt); andre@0: void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1); andre@0: if( !pData ){ andre@0: rc = SQLITE_NOMEM; andre@0: }else{ andre@0: char **azCols = (char **)pData; /* Names of result columns */ andre@0: char **azVals = &azCols[nCol]; /* Results */ andre@0: int *aiTypes = (int *)&azVals[nCol]; /* Result types */ andre@0: int i, x; andre@0: assert(sizeof(int) <= sizeof(char *)); andre@0: /* save off ptrs to column names */ andre@0: for(i=0; imode==MODE_Insert ){ andre@0: azVals[i] = ""; andre@0: }else{ andre@0: azVals[i] = (char*)sqlite3_column_text(pStmt, i); andre@0: } andre@0: if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ andre@0: rc = SQLITE_NOMEM; andre@0: break; /* from for */ andre@0: } andre@0: } /* end for */ andre@0: andre@0: /* if data and types extracted successfully... */ andre@0: if( SQLITE_ROW == rc ){ andre@0: /* call the supplied callback with the result row data */ andre@0: if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){ andre@0: rc = SQLITE_ABORT; andre@0: }else{ andre@0: rc = sqlite3_step(pStmt); andre@0: } andre@0: } andre@0: } while( SQLITE_ROW == rc ); andre@0: sqlite3_free(pData); andre@0: } andre@0: }else{ andre@0: do{ andre@0: rc = sqlite3_step(pStmt); andre@0: } while( rc == SQLITE_ROW ); andre@0: } andre@0: } andre@0: andre@0: explain_data_delete(pArg); andre@0: andre@0: /* print usage stats if stats on */ andre@0: if( pArg && pArg->statsOn ){ andre@0: display_stats(db, pArg, 0); andre@0: } andre@0: andre@0: /* Finalize the statement just executed. If this fails, save a andre@0: ** copy of the error message. Otherwise, set zSql to point to the andre@0: ** next statement to execute. */ andre@0: rc2 = sqlite3_finalize(pStmt); andre@0: if( rc!=SQLITE_NOMEM ) rc = rc2; andre@0: if( rc==SQLITE_OK ){ andre@0: zSql = zLeftover; andre@0: while( IsSpace(zSql[0]) ) zSql++; andre@0: }else if( pzErrMsg ){ andre@0: *pzErrMsg = save_err_msg(db); andre@0: } andre@0: andre@0: /* clear saved stmt handle */ andre@0: if( pArg ){ andre@0: pArg->pStmt = NULL; andre@0: } andre@0: } andre@0: } /* end while */ andre@0: andre@0: return rc; andre@0: } andre@0: andre@0: andre@0: /* andre@0: ** This is a different callback routine used for dumping the database. andre@0: ** Each row received by this callback consists of a table name, andre@0: ** the table type ("index" or "table") and SQL to create the table. andre@0: ** This routine should print text sufficient to recreate the table. andre@0: */ andre@0: static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ andre@0: int rc; andre@0: const char *zTable; andre@0: const char *zType; andre@0: const char *zSql; andre@0: const char *zPrepStmt = 0; andre@0: struct callback_data *p = (struct callback_data *)pArg; andre@0: andre@0: UNUSED_PARAMETER(azCol); andre@0: if( nArg!=3 ) return 1; andre@0: zTable = azArg[0]; andre@0: zType = azArg[1]; andre@0: zSql = azArg[2]; andre@0: andre@0: if( strcmp(zTable, "sqlite_sequence")==0 ){ andre@0: zPrepStmt = "DELETE FROM sqlite_sequence;\n"; andre@0: }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ andre@0: fprintf(p->out, "ANALYZE sqlite_master;\n"); andre@0: }else if( strncmp(zTable, "sqlite_", 7)==0 ){ andre@0: return 0; andre@0: }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ andre@0: char *zIns; andre@0: if( !p->writableSchema ){ andre@0: fprintf(p->out, "PRAGMA writable_schema=ON;\n"); andre@0: p->writableSchema = 1; andre@0: } andre@0: zIns = sqlite3_mprintf( andre@0: "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" andre@0: "VALUES('table','%q','%q',0,'%q');", andre@0: zTable, zTable, zSql); andre@0: fprintf(p->out, "%s\n", zIns); andre@0: sqlite3_free(zIns); andre@0: return 0; andre@0: }else{ andre@0: fprintf(p->out, "%s;\n", zSql); andre@0: } andre@0: andre@0: if( strcmp(zType, "table")==0 ){ andre@0: sqlite3_stmt *pTableInfo = 0; andre@0: char *zSelect = 0; andre@0: char *zTableInfo = 0; andre@0: char *zTmp = 0; andre@0: int nRow = 0; andre@0: andre@0: zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); andre@0: zTableInfo = appendText(zTableInfo, zTable, '"'); andre@0: zTableInfo = appendText(zTableInfo, ");", 0); andre@0: andre@0: rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0); andre@0: free(zTableInfo); andre@0: if( rc!=SQLITE_OK || !pTableInfo ){ andre@0: return 1; andre@0: } andre@0: andre@0: zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); andre@0: /* Always quote the table name, even if it appears to be pure ascii, andre@0: ** in case it is a keyword. Ex: INSERT INTO "table" ... */ andre@0: zTmp = appendText(zTmp, zTable, '"'); andre@0: if( zTmp ){ andre@0: zSelect = appendText(zSelect, zTmp, '\''); andre@0: free(zTmp); andre@0: } andre@0: zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); andre@0: rc = sqlite3_step(pTableInfo); andre@0: while( rc==SQLITE_ROW ){ andre@0: const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); andre@0: zSelect = appendText(zSelect, "quote(", 0); andre@0: zSelect = appendText(zSelect, zText, '"'); andre@0: rc = sqlite3_step(pTableInfo); andre@0: if( rc==SQLITE_ROW ){ andre@0: zSelect = appendText(zSelect, "), ", 0); andre@0: }else{ andre@0: zSelect = appendText(zSelect, ") ", 0); andre@0: } andre@0: nRow++; andre@0: } andre@0: rc = sqlite3_finalize(pTableInfo); andre@0: if( rc!=SQLITE_OK || nRow==0 ){ andre@0: free(zSelect); andre@0: return 1; andre@0: } andre@0: zSelect = appendText(zSelect, "|| ')' FROM ", 0); andre@0: zSelect = appendText(zSelect, zTable, '"'); andre@0: andre@0: rc = run_table_dump_query(p, zSelect, zPrepStmt); andre@0: if( rc==SQLITE_CORRUPT ){ andre@0: zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); andre@0: run_table_dump_query(p, zSelect, 0); andre@0: } andre@0: free(zSelect); andre@0: } andre@0: return 0; andre@0: } andre@0: andre@0: /* andre@0: ** Run zQuery. Use dump_callback() as the callback routine so that andre@0: ** the contents of the query are output as SQL statements. andre@0: ** andre@0: ** If we get a SQLITE_CORRUPT error, rerun the query after appending andre@0: ** "ORDER BY rowid DESC" to the end. andre@0: */ andre@0: static int run_schema_dump_query( andre@0: struct callback_data *p, andre@0: const char *zQuery andre@0: ){ andre@0: int rc; andre@0: char *zErr = 0; andre@0: rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); andre@0: if( rc==SQLITE_CORRUPT ){ andre@0: char *zQ2; andre@0: int len = strlen30(zQuery); andre@0: fprintf(p->out, "/****** CORRUPTION ERROR *******/\n"); andre@0: if( zErr ){ andre@0: fprintf(p->out, "/****** %s ******/\n", zErr); andre@0: sqlite3_free(zErr); andre@0: zErr = 0; andre@0: } andre@0: zQ2 = malloc( len+100 ); andre@0: if( zQ2==0 ) return rc; andre@0: sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); andre@0: rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); andre@0: if( rc ){ andre@0: fprintf(p->out, "/****** ERROR: %s ******/\n", zErr); andre@0: }else{ andre@0: rc = SQLITE_CORRUPT; andre@0: } andre@0: sqlite3_free(zErr); andre@0: free(zQ2); andre@0: } andre@0: return rc; andre@0: } andre@0: andre@0: /* andre@0: ** Text of a help message andre@0: */ andre@0: static char zHelp[] = andre@0: ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" andre@0: ".bail on|off Stop after hitting an error. Default OFF\n" andre@0: ".clone NEWDB Clone data into NEWDB from the existing database\n" andre@0: ".databases List names and files of attached databases\n" andre@0: ".dump ?TABLE? ... Dump the database in an SQL text format\n" andre@0: " If TABLE specified, only dump tables matching\n" andre@0: " LIKE pattern TABLE.\n" andre@0: ".echo on|off Turn command echo on or off\n" andre@0: ".exit Exit this program\n" andre@0: ".explain ?on|off? Turn output mode suitable for EXPLAIN on or off.\n" andre@0: " With no args, it turns EXPLAIN on.\n" andre@0: ".headers on|off Turn display of headers on or off\n" andre@0: ".help Show this message\n" andre@0: ".import FILE TABLE Import data from FILE into TABLE\n" andre@0: ".indices ?TABLE? Show names of all indices\n" andre@0: " If TABLE specified, only show indices for tables\n" andre@0: " matching LIKE pattern TABLE.\n" andre@0: #ifdef SQLITE_ENABLE_IOTRACE andre@0: ".iotrace FILE Enable I/O diagnostic logging to FILE\n" andre@0: #endif andre@0: #ifndef SQLITE_OMIT_LOAD_EXTENSION andre@0: ".load FILE ?ENTRY? Load an extension library\n" andre@0: #endif andre@0: ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" andre@0: ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" andre@0: " csv Comma-separated values\n" andre@0: " column Left-aligned columns. (See .width)\n" andre@0: " html HTML code\n" andre@0: " insert SQL insert statements for TABLE\n" andre@0: " line One value per line\n" andre@0: " list Values delimited by .separator string\n" andre@0: " tabs Tab-separated values\n" andre@0: " tcl TCL list elements\n" andre@0: ".nullvalue STRING Use STRING in place of NULL values\n" andre@0: ".once FILENAME Output for the next SQL command only to FILENAME\n" andre@0: ".open ?FILENAME? Close existing database and reopen FILENAME\n" andre@0: ".output ?FILENAME? Send output to FILENAME or stdout\n" andre@0: ".print STRING... Print literal STRING\n" andre@0: ".prompt MAIN CONTINUE Replace the standard prompts\n" andre@0: ".quit Exit this program\n" andre@0: ".read FILENAME Execute SQL in FILENAME\n" andre@0: ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" andre@0: ".save FILE Write in-memory database into FILE\n" andre@0: ".schema ?TABLE? Show the CREATE statements\n" andre@0: " If TABLE specified, only show tables matching\n" andre@0: " LIKE pattern TABLE.\n" andre@0: ".separator STRING Change separator used by output mode and .import\n" andre@0: ".shell CMD ARGS... Run CMD ARGS... in a system shell\n" andre@0: ".show Show the current values for various settings\n" andre@0: ".stats on|off Turn stats on or off\n" andre@0: ".system CMD ARGS... Run CMD ARGS... in a system shell\n" andre@0: ".tables ?TABLE? List names of tables\n" andre@0: " If TABLE specified, only list tables matching\n" andre@0: " LIKE pattern TABLE.\n" andre@0: ".timeout MS Try opening locked tables for MS milliseconds\n" andre@0: ".timer on|off Turn SQL timer on or off\n" andre@0: ".trace FILE|off Output each SQL statement as it is run\n" andre@0: ".vfsname ?AUX? Print the name of the VFS stack\n" andre@0: ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" andre@0: " Negative values right-justify\n" andre@0: ; andre@0: andre@0: /* Forward reference */ andre@0: static int process_input(struct callback_data *p, FILE *in); andre@0: andre@0: /* andre@0: ** Make sure the database is open. If it is not, then open it. If andre@0: ** the database fails to open, print an error message and exit. andre@0: */ andre@0: static void open_db(struct callback_data *p, int keepAlive){ andre@0: if( p->db==0 ){ andre@0: sqlite3_initialize(); andre@0: sqlite3_open(p->zDbFilename, &p->db); andre@0: db = p->db; andre@0: if( db && sqlite3_errcode(db)==SQLITE_OK ){ andre@0: sqlite3_create_function(db, "shellstatic", 0, SQLITE_UTF8, 0, andre@0: shellstaticFunc, 0, 0); andre@0: } andre@0: if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){ andre@0: fprintf(stderr,"Error: unable to open database \"%s\": %s\n", andre@0: p->zDbFilename, sqlite3_errmsg(db)); andre@0: if( keepAlive ) return; andre@0: exit(1); andre@0: } andre@0: #ifndef SQLITE_OMIT_LOAD_EXTENSION andre@0: sqlite3_enable_load_extension(p->db, 1); andre@0: #endif andre@0: } andre@0: } andre@0: andre@0: /* andre@0: ** Do C-language style dequoting. andre@0: ** andre@0: ** \t -> tab andre@0: ** \n -> newline andre@0: ** \r -> carriage return andre@0: ** \" -> " andre@0: ** \NNN -> ascii character NNN in octal andre@0: ** \\ -> backslash andre@0: */ andre@0: static void resolve_backslashes(char *z){ andre@0: int i, j; andre@0: char c; andre@0: while( *z && *z!='\\' ) z++; andre@0: for(i=j=0; (c = z[i])!=0; i++, j++){ andre@0: if( c=='\\' ){ andre@0: c = z[++i]; andre@0: if( c=='n' ){ andre@0: c = '\n'; andre@0: }else if( c=='t' ){ andre@0: c = '\t'; andre@0: }else if( c=='r' ){ andre@0: c = '\r'; andre@0: }else if( c=='\\' ){ andre@0: c = '\\'; andre@0: }else if( c>='0' && c<='7' ){ andre@0: c -= '0'; andre@0: if( z[i+1]>='0' && z[i+1]<='7' ){ andre@0: i++; andre@0: c = (c<<3) + z[i] - '0'; andre@0: if( z[i+1]>='0' && z[i+1]<='7' ){ andre@0: i++; andre@0: c = (c<<3) + z[i] - '0'; andre@0: } andre@0: } andre@0: } andre@0: } andre@0: z[j] = c; andre@0: } andre@0: if( j='0' && c<='9' ) return c - '0'; andre@0: if( c>='a' && c<='f' ) return c - 'a' + 10; andre@0: if( c>='A' && c<='F' ) return c - 'A' + 10; andre@0: return -1; andre@0: } andre@0: andre@0: /* andre@0: ** Interpret zArg as an integer value, possibly with suffixes. andre@0: */ andre@0: static sqlite3_int64 integerValue(const char *zArg){ andre@0: sqlite3_int64 v = 0; andre@0: static const struct { char *zSuffix; int iMult; } aMult[] = { andre@0: { "KiB", 1024 }, andre@0: { "MiB", 1024*1024 }, andre@0: { "GiB", 1024*1024*1024 }, andre@0: { "KB", 1000 }, andre@0: { "MB", 1000000 }, andre@0: { "GB", 1000000000 }, andre@0: { "K", 1000 }, andre@0: { "M", 1000000 }, andre@0: { "G", 1000000000 }, andre@0: }; andre@0: int i; andre@0: int isNeg = 0; andre@0: if( zArg[0]=='-' ){ andre@0: isNeg = 1; andre@0: zArg++; andre@0: }else if( zArg[0]=='+' ){ andre@0: zArg++; andre@0: } andre@0: if( zArg[0]=='0' && zArg[1]=='x' ){ andre@0: int x; andre@0: zArg += 2; andre@0: while( (x = hexDigitValue(zArg[0]))>=0 ){ andre@0: v = (v<<4) + x; andre@0: zArg++; andre@0: } andre@0: }else{ andre@0: while( IsDigit(zArg[0]) ){ andre@0: v = v*10 + zArg[0] - '0'; andre@0: zArg++; andre@0: } andre@0: } andre@0: for(i=0; i=0; i++){} andre@0: }else{ andre@0: for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} andre@0: } andre@0: if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); andre@0: if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ andre@0: return 1; andre@0: } andre@0: if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ andre@0: return 0; andre@0: } andre@0: fprintf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", andre@0: zArg); andre@0: return 0; andre@0: } andre@0: andre@0: /* andre@0: ** Close an output file, assuming it is not stderr or stdout andre@0: */ andre@0: static void output_file_close(FILE *f){ andre@0: if( f && f!=stdout && f!=stderr ) fclose(f); andre@0: } andre@0: andre@0: /* andre@0: ** Try to open an output file. The names "stdout" and "stderr" are andre@0: ** recognized and do the right thing. NULL is returned if the output andre@0: ** filename is "off". andre@0: */ andre@0: static FILE *output_file_open(const char *zFile){ andre@0: FILE *f; andre@0: if( strcmp(zFile,"stdout")==0 ){ andre@0: f = stdout; andre@0: }else if( strcmp(zFile, "stderr")==0 ){ andre@0: f = stderr; andre@0: }else if( strcmp(zFile, "off")==0 ){ andre@0: f = 0; andre@0: }else{ andre@0: f = fopen(zFile, "wb"); andre@0: if( f==0 ){ andre@0: fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); andre@0: } andre@0: } andre@0: return f; andre@0: } andre@0: andre@0: /* andre@0: ** A routine for handling output from sqlite3_trace(). andre@0: */ andre@0: static void sql_trace_callback(void *pArg, const char *z){ andre@0: FILE *f = (FILE*)pArg; andre@0: if( f ) fprintf(f, "%s\n", z); andre@0: } andre@0: andre@0: /* andre@0: ** A no-op routine that runs with the ".breakpoint" doc-command. This is andre@0: ** a useful spot to set a debugger breakpoint. andre@0: */ andre@0: static void test_breakpoint(void){ andre@0: static int nCall = 0; andre@0: nCall++; andre@0: } andre@0: andre@0: /* andre@0: ** An object used to read a CSV file andre@0: */ andre@0: typedef struct CSVReader CSVReader; andre@0: struct CSVReader { andre@0: const char *zFile; /* Name of the input file */ andre@0: FILE *in; /* Read the CSV text from this input stream */ andre@0: char *z; /* Accumulated text for a field */ andre@0: int n; /* Number of bytes in z */ andre@0: int nAlloc; /* Space allocated for z[] */ andre@0: int nLine; /* Current line number */ andre@0: int cTerm; /* Character that terminated the most recent field */ andre@0: int cSeparator; /* The separator character. (Usually ",") */ andre@0: }; andre@0: andre@0: /* Append a single byte to z[] */ andre@0: static void csv_append_char(CSVReader *p, int c){ andre@0: if( p->n+1>=p->nAlloc ){ andre@0: p->nAlloc += p->nAlloc + 100; andre@0: p->z = sqlite3_realloc(p->z, p->nAlloc); andre@0: if( p->z==0 ){ andre@0: fprintf(stderr, "out of memory\n"); andre@0: exit(1); andre@0: } andre@0: } andre@0: p->z[p->n++] = (char)c; andre@0: } andre@0: andre@0: /* Read a single field of CSV text. Compatible with rfc4180 and extended andre@0: ** with the option of having a separator other than ",". andre@0: ** andre@0: ** + Input comes from p->in. andre@0: ** + Store results in p->z of length p->n. Space to hold p->z comes andre@0: ** from sqlite3_malloc(). andre@0: ** + Use p->cSep as the separator. The default is ",". andre@0: ** + Keep track of the line number in p->nLine. andre@0: ** + Store the character that terminates the field in p->cTerm. Store andre@0: ** EOF on end-of-file. andre@0: ** + Report syntax errors on stderr andre@0: */ andre@0: static char *csv_read_one_field(CSVReader *p){ andre@0: int c, pc, ppc; andre@0: int cSep = p->cSeparator; andre@0: p->n = 0; andre@0: c = fgetc(p->in); andre@0: if( c==EOF || seenInterrupt ){ andre@0: p->cTerm = EOF; andre@0: return 0; andre@0: } andre@0: if( c=='"' ){ andre@0: int startLine = p->nLine; andre@0: int cQuote = c; andre@0: pc = ppc = 0; andre@0: while( 1 ){ andre@0: c = fgetc(p->in); andre@0: if( c=='\n' ) p->nLine++; andre@0: if( c==cQuote ){ andre@0: if( pc==cQuote ){ andre@0: pc = 0; andre@0: continue; andre@0: } andre@0: } andre@0: if( (c==cSep && pc==cQuote) andre@0: || (c=='\n' && pc==cQuote) andre@0: || (c=='\n' && pc=='\r' && ppc==cQuote) andre@0: || (c==EOF && pc==cQuote) andre@0: ){ andre@0: do{ p->n--; }while( p->z[p->n]!=cQuote ); andre@0: p->cTerm = c; andre@0: break; andre@0: } andre@0: if( pc==cQuote && c!='\r' ){ andre@0: fprintf(stderr, "%s:%d: unescaped %c character\n", andre@0: p->zFile, p->nLine, cQuote); andre@0: } andre@0: if( c==EOF ){ andre@0: fprintf(stderr, "%s:%d: unterminated %c-quoted field\n", andre@0: p->zFile, startLine, cQuote); andre@0: p->cTerm = EOF; andre@0: break; andre@0: } andre@0: csv_append_char(p, c); andre@0: ppc = pc; andre@0: pc = c; andre@0: } andre@0: }else{ andre@0: while( c!=EOF && c!=cSep && c!='\n' ){ andre@0: csv_append_char(p, c); andre@0: c = fgetc(p->in); andre@0: } andre@0: if( c=='\n' ){ andre@0: p->nLine++; andre@0: if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; andre@0: } andre@0: p->cTerm = c; andre@0: } andre@0: if( p->z ) p->z[p->n] = 0; andre@0: return p->z; andre@0: } andre@0: andre@0: /* andre@0: ** Try to transfer data for table zTable. If an error is seen while andre@0: ** moving forward, try to go backwards. The backwards movement won't andre@0: ** work for WITHOUT ROWID tables. andre@0: */ andre@0: static void tryToCloneData( andre@0: struct callback_data *p, andre@0: sqlite3 *newDb, andre@0: const char *zTable andre@0: ){ andre@0: sqlite3_stmt *pQuery = 0; andre@0: sqlite3_stmt *pInsert = 0; andre@0: char *zQuery = 0; andre@0: char *zInsert = 0; andre@0: int rc; andre@0: int i, j, n; andre@0: int nTable = (int)strlen(zTable); andre@0: int k = 0; andre@0: int cnt = 0; andre@0: const int spinRate = 10000; andre@0: andre@0: zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); andre@0: rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); andre@0: if( rc ){ andre@0: fprintf(stderr, "Error %d: %s on [%s]\n", andre@0: sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), andre@0: zQuery); andre@0: goto end_data_xfer; andre@0: } andre@0: n = sqlite3_column_count(pQuery); andre@0: zInsert = sqlite3_malloc(200 + nTable + n*3); andre@0: if( zInsert==0 ){ andre@0: fprintf(stderr, "out of memory\n"); andre@0: goto end_data_xfer; andre@0: } andre@0: sqlite3_snprintf(200+nTable,zInsert, andre@0: "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); andre@0: i = (int)strlen(zInsert); andre@0: for(j=1; jdb, zQuery, -1, &pQuery, 0); andre@0: if( rc ){ andre@0: fprintf(stderr, "Warning: cannot step \"%s\" backwards", zTable); andre@0: break; andre@0: } andre@0: } /* End for(k=0...) */ andre@0: andre@0: end_data_xfer: andre@0: sqlite3_finalize(pQuery); andre@0: sqlite3_finalize(pInsert); andre@0: sqlite3_free(zQuery); andre@0: sqlite3_free(zInsert); andre@0: } andre@0: andre@0: andre@0: /* andre@0: ** Try to transfer all rows of the schema that match zWhere. For andre@0: ** each row, invoke xForEach() on the object defined by that row. andre@0: ** If an error is encountered while moving forward through the andre@0: ** sqlite_master table, try again moving backwards. andre@0: */ andre@0: static void tryToCloneSchema( andre@0: struct callback_data *p, andre@0: sqlite3 *newDb, andre@0: const char *zWhere, andre@0: void (*xForEach)(struct callback_data*,sqlite3*,const char*) andre@0: ){ andre@0: sqlite3_stmt *pQuery = 0; andre@0: char *zQuery = 0; andre@0: int rc; andre@0: const unsigned char *zName; andre@0: const unsigned char *zSql; andre@0: char *zErrMsg = 0; andre@0: andre@0: zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" andre@0: " WHERE %s", zWhere); andre@0: rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); andre@0: if( rc ){ andre@0: fprintf(stderr, "Error: (%d) %s on [%s]\n", andre@0: sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), andre@0: zQuery); andre@0: goto end_schema_xfer; andre@0: } andre@0: while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ andre@0: zName = sqlite3_column_text(pQuery, 0); andre@0: zSql = sqlite3_column_text(pQuery, 1); andre@0: printf("%s... ", zName); fflush(stdout); andre@0: sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); andre@0: if( zErrMsg ){ andre@0: fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); andre@0: sqlite3_free(zErrMsg); andre@0: zErrMsg = 0; andre@0: } andre@0: if( xForEach ){ andre@0: xForEach(p, newDb, (const char*)zName); andre@0: } andre@0: printf("done\n"); andre@0: } andre@0: if( rc!=SQLITE_DONE ){ andre@0: sqlite3_finalize(pQuery); andre@0: sqlite3_free(zQuery); andre@0: zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" andre@0: " WHERE %s ORDER BY rowid DESC", zWhere); andre@0: rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); andre@0: if( rc ){ andre@0: fprintf(stderr, "Error: (%d) %s on [%s]\n", andre@0: sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), andre@0: zQuery); andre@0: goto end_schema_xfer; andre@0: } andre@0: while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ andre@0: zName = sqlite3_column_text(pQuery, 0); andre@0: zSql = sqlite3_column_text(pQuery, 1); andre@0: printf("%s... ", zName); fflush(stdout); andre@0: sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); andre@0: if( zErrMsg ){ andre@0: fprintf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); andre@0: sqlite3_free(zErrMsg); andre@0: zErrMsg = 0; andre@0: } andre@0: if( xForEach ){ andre@0: xForEach(p, newDb, (const char*)zName); andre@0: } andre@0: printf("done\n"); andre@0: } andre@0: } andre@0: end_schema_xfer: andre@0: sqlite3_finalize(pQuery); andre@0: sqlite3_free(zQuery); andre@0: } andre@0: andre@0: /* andre@0: ** Open a new database file named "zNewDb". Try to recover as much information andre@0: ** as possible out of the main database (which might be corrupt) and write it andre@0: ** into zNewDb. andre@0: */ andre@0: static void tryToClone(struct callback_data *p, const char *zNewDb){ andre@0: int rc; andre@0: sqlite3 *newDb = 0; andre@0: if( access(zNewDb,0)==0 ){ andre@0: fprintf(stderr, "File \"%s\" already exists.\n", zNewDb); andre@0: return; andre@0: } andre@0: rc = sqlite3_open(zNewDb, &newDb); andre@0: if( rc ){ andre@0: fprintf(stderr, "Cannot create output database: %s\n", andre@0: sqlite3_errmsg(newDb)); andre@0: }else{ andre@0: sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); andre@0: sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); andre@0: tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); andre@0: tryToCloneSchema(p, newDb, "type!='table'", 0); andre@0: sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); andre@0: sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); andre@0: } andre@0: sqlite3_close(newDb); andre@0: } andre@0: andre@0: /* andre@0: ** Change the output file back to stdout andre@0: */ andre@0: static void output_reset(struct callback_data *p){ andre@0: if( p->outfile[0]=='|' ){ andre@0: pclose(p->out); andre@0: }else{ andre@0: output_file_close(p->out); andre@0: } andre@0: p->outfile[0] = 0; andre@0: p->out = stdout; andre@0: } andre@0: andre@0: /* andre@0: ** If an input line begins with "." then invoke this routine to andre@0: ** process that line. andre@0: ** andre@0: ** Return 1 on error, 2 to exit, and 0 otherwise. andre@0: */ andre@0: static int do_meta_command(char *zLine, struct callback_data *p){ andre@0: int i = 1; andre@0: int nArg = 0; andre@0: int n, c; andre@0: int rc = 0; andre@0: char *azArg[50]; andre@0: andre@0: /* Parse the input line into tokens. andre@0: */ andre@0: while( zLine[i] && nArg=3 && strncmp(azArg[0], "backup", n)==0) andre@0: || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) andre@0: ){ andre@0: const char *zDestFile = 0; andre@0: const char *zDb = 0; andre@0: sqlite3 *pDest; andre@0: sqlite3_backup *pBackup; andre@0: int j; andre@0: for(j=1; jdb, zDb); andre@0: if( pBackup==0 ){ andre@0: fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); andre@0: sqlite3_close(pDest); andre@0: return 1; andre@0: } andre@0: while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} andre@0: sqlite3_backup_finish(pBackup); andre@0: if( rc==SQLITE_DONE ){ andre@0: rc = 0; andre@0: }else{ andre@0: fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); andre@0: rc = 1; andre@0: } andre@0: sqlite3_close(pDest); andre@0: }else andre@0: andre@0: if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: bail_on_error = booleanValue(azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .bail on|off\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: /* The undocumented ".breakpoint" command causes a call to the no-op andre@0: ** routine named test_breakpoint(). andre@0: */ andre@0: if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ andre@0: test_breakpoint(); andre@0: }else andre@0: andre@0: if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: tryToClone(p, azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .clone FILENAME\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ andre@0: struct callback_data data; andre@0: char *zErrMsg = 0; andre@0: open_db(p, 0); andre@0: memcpy(&data, p, sizeof(data)); andre@0: data.showHeader = 1; andre@0: data.mode = MODE_Column; andre@0: data.colWidth[0] = 3; andre@0: data.colWidth[1] = 15; andre@0: data.colWidth[2] = 58; andre@0: data.cnt = 0; andre@0: sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg); andre@0: if( zErrMsg ){ andre@0: fprintf(stderr,"Error: %s\n", zErrMsg); andre@0: sqlite3_free(zErrMsg); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ andre@0: open_db(p, 0); andre@0: /* When playing back a "dump", the content might appear in an order andre@0: ** which causes immediate foreign key constraints to be violated. andre@0: ** So disable foreign-key constraint enforcement to prevent problems. */ andre@0: if( nArg!=1 && nArg!=2 ){ andre@0: fprintf(stderr, "Usage: .dump ?LIKE-PATTERN?\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: fprintf(p->out, "PRAGMA foreign_keys=OFF;\n"); andre@0: fprintf(p->out, "BEGIN TRANSACTION;\n"); andre@0: p->writableSchema = 0; andre@0: sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); andre@0: p->nErr = 0; andre@0: if( nArg==1 ){ andre@0: run_schema_dump_query(p, andre@0: "SELECT name, type, sql FROM sqlite_master " andre@0: "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" andre@0: ); andre@0: run_schema_dump_query(p, andre@0: "SELECT name, type, sql FROM sqlite_master " andre@0: "WHERE name=='sqlite_sequence'" andre@0: ); andre@0: run_table_dump_query(p, andre@0: "SELECT sql FROM sqlite_master " andre@0: "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 andre@0: ); andre@0: }else{ andre@0: int i; andre@0: for(i=1; iwritableSchema ){ andre@0: fprintf(p->out, "PRAGMA writable_schema=OFF;\n"); andre@0: p->writableSchema = 0; andre@0: } andre@0: sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); andre@0: sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); andre@0: fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); andre@0: }else andre@0: andre@0: if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: p->echoOn = booleanValue(azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .echo on|off\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: p->autoEQP = booleanValue(azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .eqp on|off\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ andre@0: if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); andre@0: rc = 2; andre@0: }else andre@0: andre@0: if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ andre@0: int val = nArg>=2 ? booleanValue(azArg[1]) : 1; andre@0: if(val == 1) { andre@0: if(!p->explainPrev.valid) { andre@0: p->explainPrev.valid = 1; andre@0: p->explainPrev.mode = p->mode; andre@0: p->explainPrev.showHeader = p->showHeader; andre@0: memcpy(p->explainPrev.colWidth,p->colWidth,sizeof(p->colWidth)); andre@0: } andre@0: /* We could put this code under the !p->explainValid andre@0: ** condition so that it does not execute if we are already in andre@0: ** explain mode. However, always executing it allows us an easy andre@0: ** was to reset to explain mode in case the user previously andre@0: ** did an .explain followed by a .width, .mode or .header andre@0: ** command. andre@0: */ andre@0: p->mode = MODE_Explain; andre@0: p->showHeader = 1; andre@0: memset(p->colWidth,0,sizeof(p->colWidth)); andre@0: p->colWidth[0] = 4; /* addr */ andre@0: p->colWidth[1] = 13; /* opcode */ andre@0: p->colWidth[2] = 4; /* P1 */ andre@0: p->colWidth[3] = 4; /* P2 */ andre@0: p->colWidth[4] = 4; /* P3 */ andre@0: p->colWidth[5] = 13; /* P4 */ andre@0: p->colWidth[6] = 2; /* P5 */ andre@0: p->colWidth[7] = 13; /* Comment */ andre@0: }else if (p->explainPrev.valid) { andre@0: p->explainPrev.valid = 0; andre@0: p->mode = p->explainPrev.mode; andre@0: p->showHeader = p->explainPrev.showHeader; andre@0: memcpy(p->colWidth,p->explainPrev.colWidth,sizeof(p->colWidth)); andre@0: } andre@0: }else andre@0: andre@0: if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: p->showHeader = booleanValue(azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .headers on|off\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ andre@0: fprintf(p->out, "%s", zHelp); andre@0: }else andre@0: andre@0: if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ andre@0: char *zTable; /* Insert data into this table */ andre@0: char *zFile; /* Name of file to extra content from */ andre@0: sqlite3_stmt *pStmt = NULL; /* A statement */ andre@0: int nCol; /* Number of columns in the table */ andre@0: int nByte; /* Number of bytes in an SQL string */ andre@0: int i, j; /* Loop counters */ andre@0: int needCommit; /* True to COMMIT or ROLLBACK at end */ andre@0: int nSep; /* Number of bytes in p->separator[] */ andre@0: char *zSql; /* An SQL statement */ andre@0: CSVReader sCsv; /* Reader context */ andre@0: int (*xCloser)(FILE*); /* Procedure to close th3 connection */ andre@0: andre@0: if( nArg!=3 ){ andre@0: fprintf(stderr, "Usage: .import FILE TABLE\n"); andre@0: goto meta_command_exit; andre@0: } andre@0: zFile = azArg[1]; andre@0: zTable = azArg[2]; andre@0: seenInterrupt = 0; andre@0: memset(&sCsv, 0, sizeof(sCsv)); andre@0: open_db(p, 0); andre@0: nSep = strlen30(p->separator); andre@0: if( nSep==0 ){ andre@0: fprintf(stderr, "Error: non-null separator required for import\n"); andre@0: return 1; andre@0: } andre@0: if( nSep>1 ){ andre@0: fprintf(stderr, "Error: multi-character separators not allowed" andre@0: " for import\n"); andre@0: return 1; andre@0: } andre@0: sCsv.zFile = zFile; andre@0: sCsv.nLine = 1; andre@0: if( sCsv.zFile[0]=='|' ){ andre@0: sCsv.in = popen(sCsv.zFile+1, "r"); andre@0: sCsv.zFile = ""; andre@0: xCloser = pclose; andre@0: }else{ andre@0: sCsv.in = fopen(sCsv.zFile, "rb"); andre@0: xCloser = fclose; andre@0: } andre@0: if( sCsv.in==0 ){ andre@0: fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); andre@0: return 1; andre@0: } andre@0: sCsv.cSeparator = p->separator[0]; andre@0: zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); andre@0: if( zSql==0 ){ andre@0: fprintf(stderr, "Error: out of memory\n"); andre@0: xCloser(sCsv.in); andre@0: return 1; andre@0: } andre@0: nByte = strlen30(zSql); andre@0: rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); andre@0: csv_append_char(&sCsv, 0); /* To ensure sCsv.z is allocated */ andre@0: if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(db))==0 ){ andre@0: char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); andre@0: char cSep = '('; andre@0: while( csv_read_one_field(&sCsv) ){ andre@0: zCreate = sqlite3_mprintf("%z%c\n \"%s\" TEXT", zCreate, cSep, sCsv.z); andre@0: cSep = ','; andre@0: if( sCsv.cTerm!=sCsv.cSeparator ) break; andre@0: } andre@0: if( cSep=='(' ){ andre@0: sqlite3_free(zCreate); andre@0: sqlite3_free(sCsv.z); andre@0: xCloser(sCsv.in); andre@0: fprintf(stderr,"%s: empty file\n", sCsv.zFile); andre@0: return 1; andre@0: } andre@0: zCreate = sqlite3_mprintf("%z\n)", zCreate); andre@0: rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); andre@0: sqlite3_free(zCreate); andre@0: if( rc ){ andre@0: fprintf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, andre@0: sqlite3_errmsg(db)); andre@0: sqlite3_free(sCsv.z); andre@0: xCloser(sCsv.in); andre@0: return 1; andre@0: } andre@0: rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); andre@0: } andre@0: sqlite3_free(zSql); andre@0: if( rc ){ andre@0: if (pStmt) sqlite3_finalize(pStmt); andre@0: fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); andre@0: xCloser(sCsv.in); andre@0: return 1; andre@0: } andre@0: nCol = sqlite3_column_count(pStmt); andre@0: sqlite3_finalize(pStmt); andre@0: pStmt = 0; andre@0: if( nCol==0 ) return 0; /* no columns, no error */ andre@0: zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 ); andre@0: if( zSql==0 ){ andre@0: fprintf(stderr, "Error: out of memory\n"); andre@0: xCloser(sCsv.in); andre@0: return 1; andre@0: } andre@0: sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); andre@0: j = strlen30(zSql); andre@0: for(i=1; idb, zSql, -1, &pStmt, 0); andre@0: sqlite3_free(zSql); andre@0: if( rc ){ andre@0: fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db)); andre@0: if (pStmt) sqlite3_finalize(pStmt); andre@0: xCloser(sCsv.in); andre@0: return 1; andre@0: } andre@0: needCommit = sqlite3_get_autocommit(db); andre@0: if( needCommit ) sqlite3_exec(db, "BEGIN", 0, 0, 0); andre@0: do{ andre@0: int startLine = sCsv.nLine; andre@0: for(i=0; i=nCol ){ andre@0: sqlite3_step(pStmt); andre@0: rc = sqlite3_reset(pStmt); andre@0: if( rc!=SQLITE_OK ){ andre@0: fprintf(stderr, "%s:%d: INSERT failed: %s\n", sCsv.zFile, startLine, andre@0: sqlite3_errmsg(db)); andre@0: } andre@0: } andre@0: }while( sCsv.cTerm!=EOF ); andre@0: andre@0: xCloser(sCsv.in); andre@0: sqlite3_free(sCsv.z); andre@0: sqlite3_finalize(pStmt); andre@0: if( needCommit ) sqlite3_exec(db, "COMMIT", 0, 0, 0); andre@0: }else andre@0: andre@0: if( c=='i' && strncmp(azArg[0], "indices", n)==0 ){ andre@0: struct callback_data data; andre@0: char *zErrMsg = 0; andre@0: open_db(p, 0); andre@0: memcpy(&data, p, sizeof(data)); andre@0: data.showHeader = 0; andre@0: data.mode = MODE_List; andre@0: if( nArg==1 ){ andre@0: rc = sqlite3_exec(p->db, andre@0: "SELECT name FROM sqlite_master " andre@0: "WHERE type='index' AND name NOT LIKE 'sqlite_%' " andre@0: "UNION ALL " andre@0: "SELECT name FROM sqlite_temp_master " andre@0: "WHERE type='index' " andre@0: "ORDER BY 1", andre@0: callback, &data, &zErrMsg andre@0: ); andre@0: }else if( nArg==2 ){ andre@0: zShellStatic = azArg[1]; andre@0: rc = sqlite3_exec(p->db, andre@0: "SELECT name FROM sqlite_master " andre@0: "WHERE type='index' AND tbl_name LIKE shellstatic() " andre@0: "UNION ALL " andre@0: "SELECT name FROM sqlite_temp_master " andre@0: "WHERE type='index' AND tbl_name LIKE shellstatic() " andre@0: "ORDER BY 1", andre@0: callback, &data, &zErrMsg andre@0: ); andre@0: zShellStatic = 0; andre@0: }else{ andre@0: fprintf(stderr, "Usage: .indices ?LIKE-PATTERN?\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: if( zErrMsg ){ andre@0: fprintf(stderr,"Error: %s\n", zErrMsg); andre@0: sqlite3_free(zErrMsg); andre@0: rc = 1; andre@0: }else if( rc != SQLITE_OK ){ andre@0: fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: #ifdef SQLITE_ENABLE_IOTRACE andre@0: if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ andre@0: extern void (*sqlite3IoTrace)(const char*, ...); andre@0: if( iotrace && iotrace!=stdout ) fclose(iotrace); andre@0: iotrace = 0; andre@0: if( nArg<2 ){ andre@0: sqlite3IoTrace = 0; andre@0: }else if( strcmp(azArg[1], "-")==0 ){ andre@0: sqlite3IoTrace = iotracePrintf; andre@0: iotrace = stdout; andre@0: }else{ andre@0: iotrace = fopen(azArg[1], "w"); andre@0: if( iotrace==0 ){ andre@0: fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); andre@0: sqlite3IoTrace = 0; andre@0: rc = 1; andre@0: }else{ andre@0: sqlite3IoTrace = iotracePrintf; andre@0: } andre@0: } andre@0: }else andre@0: #endif andre@0: andre@0: #ifndef SQLITE_OMIT_LOAD_EXTENSION andre@0: if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ andre@0: const char *zFile, *zProc; andre@0: char *zErrMsg = 0; andre@0: if( nArg<2 ){ andre@0: fprintf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: zFile = azArg[1]; andre@0: zProc = nArg>=3 ? azArg[2] : 0; andre@0: open_db(p, 0); andre@0: rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); andre@0: if( rc!=SQLITE_OK ){ andre@0: fprintf(stderr, "Error: %s\n", zErrMsg); andre@0: sqlite3_free(zErrMsg); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: #endif andre@0: andre@0: if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ andre@0: if( nArg!=2 ){ andre@0: fprintf(stderr, "Usage: .log FILENAME\n"); andre@0: rc = 1; andre@0: }else{ andre@0: const char *zFile = azArg[1]; andre@0: output_file_close(p->pLog); andre@0: p->pLog = output_file_open(zFile); andre@0: } andre@0: }else andre@0: andre@0: if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ andre@0: const char *zMode = nArg>=2 ? azArg[1] : ""; andre@0: int n2 = (int)strlen(zMode); andre@0: int c2 = zMode[0]; andre@0: if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ andre@0: p->mode = MODE_Line; andre@0: }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ andre@0: p->mode = MODE_Column; andre@0: }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ andre@0: p->mode = MODE_List; andre@0: }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ andre@0: p->mode = MODE_Html; andre@0: }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ andre@0: p->mode = MODE_Tcl; andre@0: sqlite3_snprintf(sizeof(p->separator), p->separator, " "); andre@0: }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ andre@0: p->mode = MODE_Csv; andre@0: sqlite3_snprintf(sizeof(p->separator), p->separator, ","); andre@0: }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ andre@0: p->mode = MODE_List; andre@0: sqlite3_snprintf(sizeof(p->separator), p->separator, "\t"); andre@0: }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ andre@0: p->mode = MODE_Insert; andre@0: set_table_name(p, nArg>=3 ? azArg[2] : "table"); andre@0: }else { andre@0: fprintf(stderr,"Error: mode should be one of: " andre@0: "column csv html insert line list tabs tcl\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: sqlite3_snprintf(sizeof(p->nullvalue), p->nullvalue, andre@0: "%.*s", (int)ArraySize(p->nullvalue)-1, azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .nullvalue STRING\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ andre@0: sqlite3 *savedDb = p->db; andre@0: const char *zSavedFilename = p->zDbFilename; andre@0: char *zNewFilename = 0; andre@0: p->db = 0; andre@0: if( nArg>=2 ){ andre@0: p->zDbFilename = zNewFilename = sqlite3_mprintf("%s", azArg[1]); andre@0: } andre@0: open_db(p, 1); andre@0: if( p->db!=0 ){ andre@0: sqlite3_close(savedDb); andre@0: sqlite3_free(p->zFreeOnClose); andre@0: p->zFreeOnClose = zNewFilename; andre@0: }else{ andre@0: sqlite3_free(zNewFilename); andre@0: p->db = savedDb; andre@0: p->zDbFilename = zSavedFilename; andre@0: } andre@0: }else andre@0: andre@0: if( c=='o' andre@0: && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0) andre@0: ){ andre@0: const char *zFile = nArg>=2 ? azArg[1] : "stdout"; andre@0: if( nArg>2 ){ andre@0: fprintf(stderr, "Usage: .%s FILE\n", azArg[0]); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: if( n>1 && strncmp(azArg[0], "once", n)==0 ){ andre@0: if( nArg<2 ){ andre@0: fprintf(stderr, "Usage: .once FILE\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: p->outCount = 2; andre@0: }else{ andre@0: p->outCount = 0; andre@0: } andre@0: output_reset(p); andre@0: if( zFile[0]=='|' ){ andre@0: p->out = popen(zFile + 1, "w"); andre@0: if( p->out==0 ){ andre@0: fprintf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); andre@0: p->out = stdout; andre@0: rc = 1; andre@0: }else{ andre@0: sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); andre@0: } andre@0: }else{ andre@0: p->out = output_file_open(zFile); andre@0: if( p->out==0 ){ andre@0: if( strcmp(zFile,"off")!=0 ){ andre@0: fprintf(stderr,"Error: cannot write to \"%s\"\n", zFile); andre@0: } andre@0: p->out = stdout; andre@0: rc = 1; andre@0: } else { andre@0: sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); andre@0: } andre@0: } andre@0: }else andre@0: andre@0: if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ andre@0: int i; andre@0: for(i=1; i1 ) fprintf(p->out, " "); andre@0: fprintf(p->out, "%s", azArg[i]); andre@0: } andre@0: fprintf(p->out, "\n"); andre@0: }else andre@0: andre@0: if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ andre@0: if( nArg >= 2) { andre@0: strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); andre@0: } andre@0: if( nArg >= 3) { andre@0: strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); andre@0: } andre@0: }else andre@0: andre@0: if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ andre@0: rc = 2; andre@0: }else andre@0: andre@0: if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ andre@0: FILE *alt; andre@0: if( nArg!=2 ){ andre@0: fprintf(stderr, "Usage: .read FILE\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: alt = fopen(azArg[1], "rb"); andre@0: if( alt==0 ){ andre@0: fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); andre@0: rc = 1; andre@0: }else{ andre@0: rc = process_input(p, alt); andre@0: fclose(alt); andre@0: } andre@0: }else andre@0: andre@0: if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ andre@0: const char *zSrcFile; andre@0: const char *zDb; andre@0: sqlite3 *pSrc; andre@0: sqlite3_backup *pBackup; andre@0: int nTimeout = 0; andre@0: andre@0: if( nArg==2 ){ andre@0: zSrcFile = azArg[1]; andre@0: zDb = "main"; andre@0: }else if( nArg==3 ){ andre@0: zSrcFile = azArg[2]; andre@0: zDb = azArg[1]; andre@0: }else{ andre@0: fprintf(stderr, "Usage: .restore ?DB? FILE\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: rc = sqlite3_open(zSrcFile, &pSrc); andre@0: if( rc!=SQLITE_OK ){ andre@0: fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); andre@0: sqlite3_close(pSrc); andre@0: return 1; andre@0: } andre@0: open_db(p, 0); andre@0: pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); andre@0: if( pBackup==0 ){ andre@0: fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); andre@0: sqlite3_close(pSrc); andre@0: return 1; andre@0: } andre@0: while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK andre@0: || rc==SQLITE_BUSY ){ andre@0: if( rc==SQLITE_BUSY ){ andre@0: if( nTimeout++ >= 3 ) break; andre@0: sqlite3_sleep(100); andre@0: } andre@0: } andre@0: sqlite3_backup_finish(pBackup); andre@0: if( rc==SQLITE_DONE ){ andre@0: rc = 0; andre@0: }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ andre@0: fprintf(stderr, "Error: source database is busy\n"); andre@0: rc = 1; andre@0: }else{ andre@0: fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); andre@0: rc = 1; andre@0: } andre@0: sqlite3_close(pSrc); andre@0: }else andre@0: andre@0: if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ andre@0: struct callback_data data; andre@0: char *zErrMsg = 0; andre@0: open_db(p, 0); andre@0: memcpy(&data, p, sizeof(data)); andre@0: data.showHeader = 0; andre@0: data.mode = MODE_Semi; andre@0: if( nArg==2 ){ andre@0: int i; andre@0: for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]); andre@0: if( strcmp(azArg[1],"sqlite_master")==0 ){ andre@0: char *new_argv[2], *new_colv[2]; andre@0: new_argv[0] = "CREATE TABLE sqlite_master (\n" andre@0: " type text,\n" andre@0: " name text,\n" andre@0: " tbl_name text,\n" andre@0: " rootpage integer,\n" andre@0: " sql text\n" andre@0: ")"; andre@0: new_argv[1] = 0; andre@0: new_colv[0] = "sql"; andre@0: new_colv[1] = 0; andre@0: callback(&data, 1, new_argv, new_colv); andre@0: rc = SQLITE_OK; andre@0: }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ andre@0: char *new_argv[2], *new_colv[2]; andre@0: new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" andre@0: " type text,\n" andre@0: " name text,\n" andre@0: " tbl_name text,\n" andre@0: " rootpage integer,\n" andre@0: " sql text\n" andre@0: ")"; andre@0: new_argv[1] = 0; andre@0: new_colv[0] = "sql"; andre@0: new_colv[1] = 0; andre@0: callback(&data, 1, new_argv, new_colv); andre@0: rc = SQLITE_OK; andre@0: }else{ andre@0: zShellStatic = azArg[1]; andre@0: rc = sqlite3_exec(p->db, andre@0: "SELECT sql FROM " andre@0: " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" andre@0: " FROM sqlite_master UNION ALL" andre@0: " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " andre@0: "WHERE lower(tbl_name) LIKE shellstatic()" andre@0: " AND type!='meta' AND sql NOTNULL " andre@0: "ORDER BY rowid", andre@0: callback, &data, &zErrMsg); andre@0: zShellStatic = 0; andre@0: } andre@0: }else if( nArg==1 ){ andre@0: rc = sqlite3_exec(p->db, andre@0: "SELECT sql FROM " andre@0: " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" andre@0: " FROM sqlite_master UNION ALL" andre@0: " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " andre@0: "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'" andre@0: "ORDER BY rowid", andre@0: callback, &data, &zErrMsg andre@0: ); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .schema ?LIKE-PATTERN?\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: if( zErrMsg ){ andre@0: fprintf(stderr,"Error: %s\n", zErrMsg); andre@0: sqlite3_free(zErrMsg); andre@0: rc = 1; andre@0: }else if( rc != SQLITE_OK ){ andre@0: fprintf(stderr,"Error: querying schema information\n"); andre@0: rc = 1; andre@0: }else{ andre@0: rc = 0; andre@0: } andre@0: }else andre@0: andre@0: #ifdef SQLITE_DEBUG andre@0: /* Undocumented commands for internal testing. Subject to change andre@0: ** without notice. */ andre@0: if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ andre@0: if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ andre@0: int i, v; andre@0: for(i=1; iout, "%s: %d 0x%x\n", azArg[i], v, v); andre@0: } andre@0: } andre@0: if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ andre@0: int i; sqlite3_int64 v; andre@0: for(i=1; iout, "%s", zBuf); andre@0: } andre@0: } andre@0: }else andre@0: #endif andre@0: andre@0: if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: sqlite3_snprintf(sizeof(p->separator), p->separator, andre@0: "%.*s", (int)sizeof(p->separator)-1, azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .separator STRING\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='s' andre@0: && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) andre@0: ){ andre@0: char *zCmd; andre@0: int i; andre@0: if( nArg<2 ){ andre@0: fprintf(stderr, "Usage: .system COMMAND\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); andre@0: for(i=2; iout,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off"); andre@0: fprintf(p->out,"%9.9s: %s\n","eqp", p->autoEQP ? "on" : "off"); andre@0: fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off"); andre@0: fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off"); andre@0: fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]); andre@0: fprintf(p->out,"%9.9s: ", "nullvalue"); andre@0: output_c_string(p->out, p->nullvalue); andre@0: fprintf(p->out, "\n"); andre@0: fprintf(p->out,"%9.9s: %s\n","output", andre@0: strlen30(p->outfile) ? p->outfile : "stdout"); andre@0: fprintf(p->out,"%9.9s: ", "separator"); andre@0: output_c_string(p->out, p->separator); andre@0: fprintf(p->out, "\n"); andre@0: fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off"); andre@0: fprintf(p->out,"%9.9s: ","width"); andre@0: for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { andre@0: fprintf(p->out,"%d ",p->colWidth[i]); andre@0: } andre@0: fprintf(p->out,"\n"); andre@0: }else andre@0: andre@0: if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: p->statsOn = booleanValue(azArg[1]); andre@0: }else{ andre@0: fprintf(stderr, "Usage: .stats on|off\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){ andre@0: sqlite3_stmt *pStmt; andre@0: char **azResult; andre@0: int nRow, nAlloc; andre@0: char *zSql = 0; andre@0: int ii; andre@0: open_db(p, 0); andre@0: rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); andre@0: if( rc ) return rc; andre@0: zSql = sqlite3_mprintf( andre@0: "SELECT name FROM sqlite_master" andre@0: " WHERE type IN ('table','view')" andre@0: " AND name NOT LIKE 'sqlite_%%'" andre@0: " AND name LIKE ?1"); andre@0: while( sqlite3_step(pStmt)==SQLITE_ROW ){ andre@0: const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); andre@0: if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue; andre@0: if( strcmp(zDbName,"temp")==0 ){ andre@0: zSql = sqlite3_mprintf( andre@0: "%z UNION ALL " andre@0: "SELECT 'temp.' || name FROM sqlite_temp_master" andre@0: " WHERE type IN ('table','view')" andre@0: " AND name NOT LIKE 'sqlite_%%'" andre@0: " AND name LIKE ?1", zSql); andre@0: }else{ andre@0: zSql = sqlite3_mprintf( andre@0: "%z UNION ALL " andre@0: "SELECT '%q.' || name FROM \"%w\".sqlite_master" andre@0: " WHERE type IN ('table','view')" andre@0: " AND name NOT LIKE 'sqlite_%%'" andre@0: " AND name LIKE ?1", zSql, zDbName, zDbName); andre@0: } andre@0: } andre@0: sqlite3_finalize(pStmt); andre@0: zSql = sqlite3_mprintf("%z ORDER BY 1", zSql); andre@0: rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); andre@0: sqlite3_free(zSql); andre@0: if( rc ) return rc; andre@0: nRow = nAlloc = 0; andre@0: azResult = 0; andre@0: if( nArg>1 ){ andre@0: sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); andre@0: }else{ andre@0: sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); andre@0: } andre@0: while( sqlite3_step(pStmt)==SQLITE_ROW ){ andre@0: if( nRow>=nAlloc ){ andre@0: char **azNew; andre@0: int n = nAlloc*2 + 10; andre@0: azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n); andre@0: if( azNew==0 ){ andre@0: fprintf(stderr, "Error: out of memory\n"); andre@0: break; andre@0: } andre@0: nAlloc = n; andre@0: azResult = azNew; andre@0: } andre@0: azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); andre@0: if( azResult[nRow] ) nRow++; andre@0: } andre@0: sqlite3_finalize(pStmt); andre@0: if( nRow>0 ){ andre@0: int len, maxlen = 0; andre@0: int i, j; andre@0: int nPrintCol, nPrintRow; andre@0: for(i=0; imaxlen ) maxlen = len; andre@0: } andre@0: nPrintCol = 80/(maxlen+2); andre@0: if( nPrintCol<1 ) nPrintCol = 1; andre@0: nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; andre@0: for(i=0; iout, "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j] : ""); andre@0: } andre@0: fprintf(p->out, "\n"); andre@0: } andre@0: } andre@0: for(ii=0; ii=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){ andre@0: static const struct { andre@0: const char *zCtrlName; /* Name of a test-control option */ andre@0: int ctrlCode; /* Integer code for that option */ andre@0: } aCtrl[] = { andre@0: { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE }, andre@0: { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE }, andre@0: { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET }, andre@0: { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST }, andre@0: { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL }, andre@0: { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS }, andre@0: { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE }, andre@0: { "assert", SQLITE_TESTCTRL_ASSERT }, andre@0: { "always", SQLITE_TESTCTRL_ALWAYS }, andre@0: { "reserve", SQLITE_TESTCTRL_RESERVE }, andre@0: { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS }, andre@0: { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD }, andre@0: { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC }, andre@0: { "byteorder", SQLITE_TESTCTRL_BYTEORDER }, andre@0: }; andre@0: int testctrl = -1; andre@0: int rc = 0; andre@0: int i, n; andre@0: open_db(p, 0); andre@0: andre@0: /* convert testctrl text option to value. allow any unique prefix andre@0: ** of the option name, or a numerical value. */ andre@0: n = strlen30(azArg[1]); andre@0: for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){ andre@0: if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){ andre@0: if( testctrl<0 ){ andre@0: testctrl = aCtrl[i].ctrlCode; andre@0: }else{ andre@0: fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]); andre@0: testctrl = -1; andre@0: break; andre@0: } andre@0: } andre@0: } andre@0: if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]); andre@0: if( (testctrlSQLITE_TESTCTRL_LAST) ){ andre@0: fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]); andre@0: }else{ andre@0: switch(testctrl){ andre@0: andre@0: /* sqlite3_test_control(int, db, int) */ andre@0: case SQLITE_TESTCTRL_OPTIMIZATIONS: andre@0: case SQLITE_TESTCTRL_RESERVE: andre@0: if( nArg==3 ){ andre@0: int opt = (int)strtol(azArg[2], 0, 0); andre@0: rc = sqlite3_test_control(testctrl, p->db, opt); andre@0: fprintf(p->out, "%d (0x%08x)\n", rc, rc); andre@0: } else { andre@0: fprintf(stderr,"Error: testctrl %s takes a single int option\n", andre@0: azArg[1]); andre@0: } andre@0: break; andre@0: andre@0: /* sqlite3_test_control(int) */ andre@0: case SQLITE_TESTCTRL_PRNG_SAVE: andre@0: case SQLITE_TESTCTRL_PRNG_RESTORE: andre@0: case SQLITE_TESTCTRL_PRNG_RESET: andre@0: case SQLITE_TESTCTRL_BYTEORDER: andre@0: if( nArg==2 ){ andre@0: rc = sqlite3_test_control(testctrl); andre@0: fprintf(p->out, "%d (0x%08x)\n", rc, rc); andre@0: } else { andre@0: fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]); andre@0: } andre@0: break; andre@0: andre@0: /* sqlite3_test_control(int, uint) */ andre@0: case SQLITE_TESTCTRL_PENDING_BYTE: andre@0: if( nArg==3 ){ andre@0: unsigned int opt = (unsigned int)integerValue(azArg[2]); andre@0: rc = sqlite3_test_control(testctrl, opt); andre@0: fprintf(p->out, "%d (0x%08x)\n", rc, rc); andre@0: } else { andre@0: fprintf(stderr,"Error: testctrl %s takes a single unsigned" andre@0: " int option\n", azArg[1]); andre@0: } andre@0: break; andre@0: andre@0: /* sqlite3_test_control(int, int) */ andre@0: case SQLITE_TESTCTRL_ASSERT: andre@0: case SQLITE_TESTCTRL_ALWAYS: andre@0: if( nArg==3 ){ andre@0: int opt = booleanValue(azArg[2]); andre@0: rc = sqlite3_test_control(testctrl, opt); andre@0: fprintf(p->out, "%d (0x%08x)\n", rc, rc); andre@0: } else { andre@0: fprintf(stderr,"Error: testctrl %s takes a single int option\n", andre@0: azArg[1]); andre@0: } andre@0: break; andre@0: andre@0: /* sqlite3_test_control(int, char *) */ andre@0: #ifdef SQLITE_N_KEYWORD andre@0: case SQLITE_TESTCTRL_ISKEYWORD: andre@0: if( nArg==3 ){ andre@0: const char *opt = azArg[2]; andre@0: rc = sqlite3_test_control(testctrl, opt); andre@0: fprintf(p->out, "%d (0x%08x)\n", rc, rc); andre@0: } else { andre@0: fprintf(stderr,"Error: testctrl %s takes a single char * option\n", andre@0: azArg[1]); andre@0: } andre@0: break; andre@0: #endif andre@0: andre@0: case SQLITE_TESTCTRL_BITVEC_TEST: andre@0: case SQLITE_TESTCTRL_FAULT_INSTALL: andre@0: case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: andre@0: case SQLITE_TESTCTRL_SCRATCHMALLOC: andre@0: default: andre@0: fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n", andre@0: azArg[1]); andre@0: break; andre@0: } andre@0: } andre@0: }else andre@0: andre@0: if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ andre@0: open_db(p, 0); andre@0: sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); andre@0: }else andre@0: andre@0: if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ andre@0: if( nArg==2 ){ andre@0: enableTimer = booleanValue(azArg[1]); andre@0: if( enableTimer && !HAS_TIMER ){ andre@0: fprintf(stderr, "Error: timer not available on this system.\n"); andre@0: enableTimer = 0; andre@0: } andre@0: }else{ andre@0: fprintf(stderr, "Usage: .timer on|off\n"); andre@0: rc = 1; andre@0: } andre@0: }else andre@0: andre@0: if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ andre@0: open_db(p, 0); andre@0: output_file_close(p->traceOut); andre@0: if( nArg!=2 ){ andre@0: fprintf(stderr, "Usage: .trace FILE|off\n"); andre@0: rc = 1; andre@0: goto meta_command_exit; andre@0: } andre@0: p->traceOut = output_file_open(azArg[1]); andre@0: #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) andre@0: if( p->traceOut==0 ){ andre@0: sqlite3_trace(p->db, 0, 0); andre@0: }else{ andre@0: sqlite3_trace(p->db, sql_trace_callback, p->traceOut); andre@0: } andre@0: #endif andre@0: }else andre@0: andre@0: if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ andre@0: fprintf(p->out, "SQLite %s %s\n" /*extra-version-info*/, andre@0: sqlite3_libversion(), sqlite3_sourceid()); andre@0: }else andre@0: andre@0: if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ andre@0: const char *zDbName = nArg==2 ? azArg[1] : "main"; andre@0: char *zVfsName = 0; andre@0: if( p->db ){ andre@0: sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); andre@0: if( zVfsName ){ andre@0: fprintf(p->out, "%s\n", zVfsName); andre@0: sqlite3_free(zVfsName); andre@0: } andre@0: } andre@0: }else andre@0: andre@0: #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) andre@0: if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ andre@0: extern int sqlite3WhereTrace; andre@0: sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; andre@0: }else andre@0: #endif andre@0: andre@0: if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ andre@0: int j; andre@0: assert( nArg<=ArraySize(azArg) ); andre@0: for(j=1; jcolWidth); j++){ andre@0: p->colWidth[j-1] = (int)integerValue(azArg[j]); andre@0: } andre@0: }else andre@0: andre@0: { andre@0: fprintf(stderr, "Error: unknown command or invalid arguments: " andre@0: " \"%s\". Enter \".help\" for help\n", azArg[0]); andre@0: rc = 1; andre@0: } andre@0: andre@0: meta_command_exit: andre@0: if( p->outCount ){ andre@0: p->outCount--; andre@0: if( p->outCount==0 ) output_reset(p); andre@0: } andre@0: return rc; andre@0: } andre@0: andre@0: /* andre@0: ** Return TRUE if a semicolon occurs anywhere in the first N characters andre@0: ** of string z[]. andre@0: */ andre@0: static int line_contains_semicolon(const char *z, int N){ andre@0: int i; andre@0: for(i=0; iout); andre@0: zLine = one_input_line(in, zLine, nSql>0); andre@0: if( zLine==0 ){ andre@0: /* End of input */ andre@0: if( stdin_is_interactive ) printf("\n"); andre@0: break; andre@0: } andre@0: if( seenInterrupt ){ andre@0: if( in!=0 ) break; andre@0: seenInterrupt = 0; andre@0: } andre@0: lineno++; andre@0: if( nSql==0 && _all_whitespace(zLine) ){ andre@0: if( p->echoOn ) printf("%s\n", zLine); andre@0: continue; andre@0: } andre@0: if( zLine && zLine[0]=='.' && nSql==0 ){ andre@0: if( p->echoOn ) printf("%s\n", zLine); andre@0: rc = do_meta_command(zLine, p); andre@0: if( rc==2 ){ /* exit requested */ andre@0: break; andre@0: }else if( rc ){ andre@0: errCnt++; andre@0: } andre@0: continue; andre@0: } andre@0: if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ andre@0: memcpy(zLine,";",2); andre@0: } andre@0: nLine = strlen30(zLine); andre@0: if( nSql+nLine+2>=nAlloc ){ andre@0: nAlloc = nSql+nLine+100; andre@0: zSql = realloc(zSql, nAlloc); andre@0: if( zSql==0 ){ andre@0: fprintf(stderr, "Error: out of memory\n"); andre@0: exit(1); andre@0: } andre@0: } andre@0: nSqlPrior = nSql; andre@0: if( nSql==0 ){ andre@0: int i; andre@0: for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} andre@0: assert( nAlloc>0 && zSql!=0 ); andre@0: memcpy(zSql, zLine+i, nLine+1-i); andre@0: startline = lineno; andre@0: nSql = nLine-i; andre@0: }else{ andre@0: zSql[nSql++] = '\n'; andre@0: memcpy(zSql+nSql, zLine, nLine+1); andre@0: nSql += nLine; andre@0: } andre@0: if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) andre@0: && sqlite3_complete(zSql) ){ andre@0: p->cnt = 0; andre@0: open_db(p, 0); andre@0: BEGIN_TIMER; andre@0: rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg); andre@0: END_TIMER; andre@0: if( rc || zErrMsg ){ andre@0: char zPrefix[100]; andre@0: if( in!=0 || !stdin_is_interactive ){ andre@0: sqlite3_snprintf(sizeof(zPrefix), zPrefix, andre@0: "Error: near line %d:", startline); andre@0: }else{ andre@0: sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); andre@0: } andre@0: if( zErrMsg!=0 ){ andre@0: fprintf(stderr, "%s %s\n", zPrefix, zErrMsg); andre@0: sqlite3_free(zErrMsg); andre@0: zErrMsg = 0; andre@0: }else{ andre@0: fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); andre@0: } andre@0: errCnt++; andre@0: } andre@0: nSql = 0; andre@0: if( p->outCount ){ andre@0: output_reset(p); andre@0: p->outCount = 0; andre@0: } andre@0: }else if( nSql && _all_whitespace(zSql) ){ andre@0: if( p->echoOn ) printf("%s\n", zSql); andre@0: nSql = 0; andre@0: } andre@0: } andre@0: if( nSql ){ andre@0: if( !_all_whitespace(zSql) ){ andre@0: fprintf(stderr, "Error: incomplete SQL: %s\n", zSql); andre@0: } andre@0: free(zSql); andre@0: } andre@0: free(zLine); andre@0: return errCnt>0; andre@0: } andre@0: andre@0: /* andre@0: ** Return a pathname which is the user's home directory. A andre@0: ** 0 return indicates an error of some kind. andre@0: */ andre@0: static char *find_home_dir(void){ andre@0: static char *home_dir = NULL; andre@0: if( home_dir ) return home_dir; andre@0: andre@0: #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL) andre@0: { andre@0: struct passwd *pwent; andre@0: uid_t uid = getuid(); andre@0: if( (pwent=getpwuid(uid)) != NULL) { andre@0: home_dir = pwent->pw_dir; andre@0: } andre@0: } andre@0: #endif andre@0: andre@0: #if defined(_WIN32_WCE) andre@0: /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() andre@0: */ andre@0: home_dir = "/"; andre@0: #else andre@0: andre@0: #if defined(_WIN32) || defined(WIN32) andre@0: if (!home_dir) { andre@0: home_dir = getenv("USERPROFILE"); andre@0: } andre@0: #endif andre@0: andre@0: if (!home_dir) { andre@0: home_dir = getenv("HOME"); andre@0: } andre@0: andre@0: #if defined(_WIN32) || defined(WIN32) andre@0: if (!home_dir) { andre@0: char *zDrive, *zPath; andre@0: int n; andre@0: zDrive = getenv("HOMEDRIVE"); andre@0: zPath = getenv("HOMEPATH"); andre@0: if( zDrive && zPath ){ andre@0: n = strlen30(zDrive) + strlen30(zPath) + 1; andre@0: home_dir = malloc( n ); andre@0: if( home_dir==0 ) return 0; andre@0: sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); andre@0: return home_dir; andre@0: } andre@0: home_dir = "c:\\"; andre@0: } andre@0: #endif andre@0: andre@0: #endif /* !_WIN32_WCE */ andre@0: andre@0: if( home_dir ){ andre@0: int n = strlen30(home_dir) + 1; andre@0: char *z = malloc( n ); andre@0: if( z ) memcpy(z, home_dir, n); andre@0: home_dir = z; andre@0: } andre@0: andre@0: return home_dir; andre@0: } andre@0: andre@0: /* andre@0: ** Read input from the file given by sqliterc_override. Or if that andre@0: ** parameter is NULL, take input from ~/.sqliterc andre@0: ** andre@0: ** Returns the number of errors. andre@0: */ andre@0: static int process_sqliterc( andre@0: struct callback_data *p, /* Configuration data */ andre@0: const char *sqliterc_override /* Name of config file. NULL to use default */ andre@0: ){ andre@0: char *home_dir = NULL; andre@0: const char *sqliterc = sqliterc_override; andre@0: char *zBuf = 0; andre@0: FILE *in = NULL; andre@0: int rc = 0; andre@0: andre@0: if (sqliterc == NULL) { andre@0: home_dir = find_home_dir(); andre@0: if( home_dir==0 ){ andre@0: #if !defined(__RTP__) && !defined(_WRS_KERNEL) andre@0: fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0); andre@0: #endif andre@0: return 1; andre@0: } andre@0: sqlite3_initialize(); andre@0: zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); andre@0: sqliterc = zBuf; andre@0: } andre@0: in = fopen(sqliterc,"rb"); andre@0: if( in ){ andre@0: if( stdin_is_interactive ){ andre@0: fprintf(stderr,"-- Loading resources from %s\n",sqliterc); andre@0: } andre@0: rc = process_input(p,in); andre@0: fclose(in); andre@0: } andre@0: sqlite3_free(zBuf); andre@0: return rc; andre@0: } andre@0: andre@0: /* andre@0: ** Show available command line options andre@0: */ andre@0: static const char zOptions[] = andre@0: " -bail stop after hitting an error\n" andre@0: " -batch force batch I/O\n" andre@0: " -column set output mode to 'column'\n" andre@0: " -cmd COMMAND run \"COMMAND\" before reading stdin\n" andre@0: " -csv set output mode to 'csv'\n" andre@0: " -echo print commands before execution\n" andre@0: " -init FILENAME read/process named file\n" andre@0: " -[no]header turn headers on or off\n" andre@0: #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) andre@0: " -heap SIZE Size of heap for memsys3 or memsys5\n" andre@0: #endif andre@0: " -help show this message\n" andre@0: " -html set output mode to HTML\n" andre@0: " -interactive force interactive I/O\n" andre@0: " -line set output mode to 'line'\n" andre@0: " -list set output mode to 'list'\n" andre@0: " -mmap N default mmap size set to N\n" andre@0: #ifdef SQLITE_ENABLE_MULTIPLEX andre@0: " -multiplex enable the multiplexor VFS\n" andre@0: #endif andre@0: " -nullvalue TEXT set text string for NULL values. Default ''\n" andre@0: " -separator SEP set output field separator. Default: '|'\n" andre@0: " -stats print memory stats before each finalize\n" andre@0: " -version show SQLite version\n" andre@0: " -vfs NAME use NAME as the default VFS\n" andre@0: #ifdef SQLITE_ENABLE_VFSTRACE andre@0: " -vfstrace enable tracing of all VFS calls\n" andre@0: #endif andre@0: ; andre@0: static void usage(int showDetail){ andre@0: fprintf(stderr, andre@0: "Usage: %s [OPTIONS] FILENAME [SQL]\n" andre@0: "FILENAME is the name of an SQLite database. A new database is created\n" andre@0: "if the file does not previously exist.\n", Argv0); andre@0: if( showDetail ){ andre@0: fprintf(stderr, "OPTIONS include:\n%s", zOptions); andre@0: }else{ andre@0: fprintf(stderr, "Use the -help option for additional information\n"); andre@0: } andre@0: exit(1); andre@0: } andre@0: andre@0: /* andre@0: ** Initialize the state information in data andre@0: */ andre@0: static void main_init(struct callback_data *data) { andre@0: memset(data, 0, sizeof(*data)); andre@0: data->mode = MODE_List; andre@0: memcpy(data->separator,"|", 2); andre@0: data->showHeader = 0; andre@0: sqlite3_config(SQLITE_CONFIG_URI, 1); andre@0: sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); andre@0: sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); andre@0: sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); andre@0: sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); andre@0: } andre@0: andre@0: /* andre@0: ** Output text to the console in a font that attracts extra attention. andre@0: */ andre@0: #ifdef _WIN32 andre@0: static void printBold(const char *zText){ andre@0: HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); andre@0: CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; andre@0: GetConsoleScreenBufferInfo(out, &defaultScreenInfo); andre@0: SetConsoleTextAttribute(out, andre@0: FOREGROUND_RED|FOREGROUND_INTENSITY andre@0: ); andre@0: printf("%s", zText); andre@0: SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); andre@0: } andre@0: #else andre@0: static void printBold(const char *zText){ andre@0: printf("\033[1m%s\033[0m", zText); andre@0: } andre@0: #endif andre@0: andre@0: /* andre@0: ** Get the argument to an --option. Throw an error and die if no argument andre@0: ** is available. andre@0: */ andre@0: static char *cmdline_option_value(int argc, char **argv, int i){ andre@0: if( i==argc ){ andre@0: fprintf(stderr, "%s: Error: missing argument to %s\n", andre@0: argv[0], argv[argc-1]); andre@0: exit(1); andre@0: } andre@0: return argv[i]; andre@0: } andre@0: andre@0: int main(int argc, char **argv){ andre@0: char *zErrMsg = 0; andre@0: struct callback_data data; andre@0: const char *zInitFile = 0; andre@0: char *zFirstCmd = 0; andre@0: int i; andre@0: int rc = 0; andre@0: int warnInmemoryDb = 0; andre@0: andre@0: #if USE_SYSTEM_SQLITE+0!=1 andre@0: if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){ andre@0: fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", andre@0: sqlite3_sourceid(), SQLITE_SOURCE_ID); andre@0: exit(1); andre@0: } andre@0: #endif andre@0: Argv0 = argv[0]; andre@0: main_init(&data); andre@0: stdin_is_interactive = isatty(0); andre@0: andre@0: /* Make sure we have a valid signal handler early, before anything andre@0: ** else is done. andre@0: */ andre@0: #ifdef SIGINT andre@0: signal(SIGINT, interrupt_handler); andre@0: #endif andre@0: andre@0: /* Do an initial pass through the command-line argument to locate andre@0: ** the name of the database file, the name of the initialization file, andre@0: ** the size of the alternative malloc heap, andre@0: ** and the first command to execute. andre@0: */ andre@0: for(i=1; i0x7fff0000 ) szHeap = 0x7fff0000; andre@0: sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); andre@0: #endif andre@0: #ifdef SQLITE_ENABLE_VFSTRACE andre@0: }else if( strcmp(z,"-vfstrace")==0 ){ andre@0: extern int vfstrace_register( andre@0: const char *zTraceName, andre@0: const char *zOldVfsName, andre@0: int (*xOut)(const char*,void*), andre@0: void *pOutArg, andre@0: int makeDefault andre@0: ); andre@0: vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); andre@0: #endif andre@0: #ifdef SQLITE_ENABLE_MULTIPLEX andre@0: }else if( strcmp(z,"-multiplex")==0 ){ andre@0: extern int sqlite3_multiple_initialize(const char*,int); andre@0: sqlite3_multiplex_initialize(0, 1); andre@0: #endif andre@0: }else if( strcmp(z,"-mmap")==0 ){ andre@0: sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); andre@0: sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); andre@0: }else if( strcmp(z,"-vfs")==0 ){ andre@0: sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i)); andre@0: if( pVfs ){ andre@0: sqlite3_vfs_register(pVfs, 1); andre@0: }else{ andre@0: fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]); andre@0: exit(1); andre@0: } andre@0: } andre@0: } andre@0: if( data.zDbFilename==0 ){ andre@0: #ifndef SQLITE_OMIT_MEMORYDB andre@0: data.zDbFilename = ":memory:"; andre@0: warnInmemoryDb = argc==1; andre@0: #else andre@0: fprintf(stderr,"%s: Error: no database filename specified\n", Argv0); andre@0: return 1; andre@0: #endif andre@0: #ifdef SQLITE_SHELL_DBNAME_PROC andre@0: { extern void SQLITE_SHELL_DBNAME_PROC(const char**); andre@0: SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); andre@0: warnInmemoryDb = 0; } andre@0: #endif andre@0: } andre@0: data.out = stdout; andre@0: andre@0: /* Go ahead and open the database file if it already exists. If the andre@0: ** file does not exist, delay opening it. This prevents empty database andre@0: ** files from being created if a user mistypes the database name argument andre@0: ** to the sqlite command-line tool. andre@0: */ andre@0: if( access(data.zDbFilename, 0)==0 ){ andre@0: open_db(&data, 0); andre@0: } andre@0: andre@0: /* Process the initialization file if there is one. If no -init option andre@0: ** is given on the command line, look for a file named ~/.sqliterc and andre@0: ** try to process it. andre@0: */ andre@0: rc = process_sqliterc(&data,zInitFile); andre@0: if( rc>0 ){ andre@0: return rc; andre@0: } andre@0: andre@0: /* Make a second pass through the command-line argument and set andre@0: ** options. This second pass is delayed until after the initialization andre@0: ** file is processed so that the command-line arguments will override andre@0: ** settings in the initialization file. andre@0: */ andre@0: for(i=1; i