From ce3aaf38aae8abd2a92751bada87a627f07ea2b4 Mon Sep 17 00:00:00 2001 From: Charles Yin Date: Tue, 19 Jul 2011 10:53:34 +1000 Subject: Update sqlite to 3.7.7.1 Updated sqlite3.h, sqlite3.c and shell.c from sqlite.org SHA1 for sqlite3.c: d47594b8a02f6cf58e91fb673e96cb1b397aace0 Task-number: QTBUG-16607 Reviewed-by: Michael Goddard (cherry picked from commit 0cb9b95beb9949ec31c5c67fd360c4b463472efe) Change-Id: I56c5ce8db178ab850992812d6f8ff7e74eb9b7dc Reviewed-on: http://codereview.qt.nokia.com/1806 Reviewed-by: Charles Yin Reviewed-by: Qt Sanity Bot --- src/3rdparty/sqlite/shell.c | 1229 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 1028 insertions(+), 201 deletions(-) (limited to 'src/3rdparty/sqlite/shell.c') diff --git a/src/3rdparty/sqlite/shell.c b/src/3rdparty/sqlite/shell.c index 99f8f95adc..a54c922e87 100644 --- a/src/3rdparty/sqlite/shell.c +++ b/src/3rdparty/sqlite/shell.c @@ -11,9 +11,12 @@ ************************************************************************* ** This file contains code to implement the "sqlite" command line ** utility for accessing SQLite databases. -** -** $Id: shell.c,v 1.178 2008/05/05 16:27:24 drh Exp $ */ +#if defined(_WIN32) || defined(WIN32) +/* This needs to come before any includes for MSVC compiler */ +#define _CRT_SECURE_NO_WARNINGS +#endif + #include #include #include @@ -24,7 +27,9 @@ #if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) # include -# include +# if !defined(__RTP__) && !defined(_WRS_KERNEL) +# include +# endif # include # include #endif @@ -33,10 +38,14 @@ # include #endif +#ifdef HAVE_EDITLINE +# include +#endif #if defined(HAVE_READLINE) && HAVE_READLINE==1 # include # include -#else +#endif +#if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1) # define readline(p) local_getline(p,stdin) # define add_history(X) # define read_history(X) @@ -46,6 +55,8 @@ #if defined(_WIN32) || defined(WIN32) # include +#define isatty(h) _isatty(h) +#define access(f,m) _access((f),(m)) #else /* Make sure isatty() has a prototype. */ @@ -60,16 +71,16 @@ extern int isatty(); #define isatty(x) 1 #endif -#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) +/* True if the timer is enabled */ +static int enableTimer = 0; + +#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(__RTP__) && !defined(_WRS_KERNEL) #include #include /* Saved resource information for the beginning of an operation */ static struct rusage sBegin; -/* True if the timer is enabled */ -static int enableTimer = 0; - /* ** Begin timing an operation */ @@ -79,10 +90,10 @@ static void beginTimer(void){ } } -/* Return the difference of two time_structs in microseconds */ -static int timeDiff(struct timeval *pStart, struct timeval *pEnd){ - return (pEnd->tv_usec - pStart->tv_usec) + - 1000000*(pEnd->tv_sec - pStart->tv_sec); +/* Return the difference of two time_structs in seconds */ +static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ + return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + + (double)(pEnd->tv_sec - pStart->tv_sec); } /* @@ -93,19 +104,97 @@ static void endTimer(void){ struct rusage sEnd; getrusage(RUSAGE_SELF, &sEnd); printf("CPU Time: user %f sys %f\n", - 0.000001*timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), - 0.000001*timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); + timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), + timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); } } + #define BEGIN_TIMER beginTimer() #define END_TIMER endTimer() #define HAS_TIMER 1 + +#elif (defined(_WIN32) || defined(WIN32)) + +#include + +/* Saved resource information for the beginning of an operation */ +static HANDLE hProcess; +static FILETIME ftKernelBegin; +static FILETIME ftUserBegin; +typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); +static GETPROCTIMES getProcessTimesAddr = NULL; + +/* +** Check to see if we have timer support. Return 1 if necessary +** support found (or found previously). +*/ +static int hasTimer(void){ + if( getProcessTimesAddr ){ + return 1; + } else { + /* GetProcessTimes() isn't supported in WIN95 and some other Windows versions. + ** See if the version we are running on has it, and if it does, save off + ** a pointer to it and the current process handle. + */ + hProcess = GetCurrentProcess(); + if( hProcess ){ + HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); + if( NULL != hinstLib ){ + getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); + if( NULL != getProcessTimesAddr ){ + return 1; + } + FreeLibrary(hinstLib); + } + } + } + return 0; +} + +/* +** Begin timing an operation +*/ +static void beginTimer(void){ + if( enableTimer && getProcessTimesAddr ){ + FILETIME ftCreation, ftExit; + getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelBegin, &ftUserBegin); + } +} + +/* Return the difference of two FILETIME structs in seconds */ +static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ + sqlite_int64 i64Start = *((sqlite_int64 *) pStart); + sqlite_int64 i64End = *((sqlite_int64 *) pEnd); + return (double) ((i64End - i64Start) / 10000000.0); +} + +/* +** Print the timing results. +*/ +static void endTimer(void){ + if( enableTimer && getProcessTimesAddr){ + FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; + getProcessTimesAddr(hProcess, &ftCreation, &ftExit, &ftKernelEnd, &ftUserEnd); + printf("CPU Time: user %f sys %f\n", + timeDiff(&ftUserBegin, &ftUserEnd), + timeDiff(&ftKernelBegin, &ftKernelEnd)); + } +} + +#define BEGIN_TIMER beginTimer() +#define END_TIMER endTimer() +#define HAS_TIMER hasTimer() + #else #define BEGIN_TIMER #define END_TIMER #define HAS_TIMER 0 #endif +/* +** Used to prevent warnings about unused parameters +*/ +#define UNUSED_PARAMETER(x) (void)(x) /* ** If the following flag is set, then command execution stops @@ -214,6 +303,8 @@ static void shellstaticFunc( ){ assert( 0==argc ); assert( zShellStatic ); + UNUSED_PARAMETER(argc); + UNUSED_PARAMETER(argv); sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); } @@ -260,6 +351,7 @@ static char *local_getline(char *zPrompt, FILE *in){ while( zLine[n] ){ n++; } if( n>0 && zLine[n-1]=='\n' ){ n--; + if( n>0 && zLine[n-1]=='\r' ) n--; zLine[n] = 0; eol = 1; } @@ -305,8 +397,9 @@ struct previous_mode_data { ** state and mode information. */ struct callback_data { - sqlite3 *db; /* The database */ + sqlite3 *db; /* The database */ int echoOn; /* True to echo input commands */ + int statsOn; /* True to display memory stats before each finalize */ int cnt; /* Number of records displayed so far */ FILE *out; /* Write results here */ int mode; /* An output mode setting */ @@ -323,6 +416,9 @@ struct callback_data { ** .explain ON */ char outfile[FILENAME_MAX]; /* Filename for *out */ const char *zDbFilename; /* name of the database file */ + const char *zVfs; /* Name of VFS to use */ + sqlite3_stmt *pStmt; /* Current statement if any. */ + FILE *pLog; /* Write log output here */ }; /* @@ -353,7 +449,38 @@ static const char *modeDescr[] = { /* ** Number of elements in an array */ -#define ArraySize(X) (sizeof(X)/sizeof(X[0])) +#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) + +/* +** Compute a string length that is limited to what can be stored in +** lower 30 bits of a 32-bit signed integer. +*/ +static int strlen30(const char *z){ + const char *z2 = z; + while( *z2 ){ z2++; } + return 0x3fffffff & (int)(z2 - z); +} + +/* +** A callback for the sqlite3_log() interface. +*/ +static void shellLog(void *pArg, int iErrCode, const char *zMsg){ + struct callback_data *p = (struct callback_data*)pArg; + if( p->pLog==0 ) return; + fprintf(p->pLog, "(%d) %s\n", iErrCode, zMsg); + fflush(p->pLog); +} + +/* +** Output the given string as a hex-encoded blob (eg. X'1234' ) +*/ +static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ + int i; + char *zBlob = (char *)pBlob; + fprintf(out,"X'"); + for(i=0; i0 ){ fprintf(out,"%.*s",i,z); } @@ -428,6 +561,12 @@ static void output_html_string(FILE *out, const char *z){ fprintf(out,"<"); }else if( z[i]=='&' ){ fprintf(out,"&"); + }else if( z[i]=='>' ){ + fprintf(out,">"); + }else if( z[i]=='\"' ){ + fprintf(out,"""); + }else if( z[i]=='\'' ){ + fprintf(out,"'"); }else{ break; } @@ -470,7 +609,7 @@ static void output_csv(struct callback_data *p, const char *z, int bSep){ fprintf(out,"%s",p->nullvalue); }else{ int i; - int nSep = strlen(p->separator); + int nSep = strlen30(p->separator); for(i=0; z[i]; i++){ if( needCsvQuote[((unsigned char*)z)[i]] || (z[i]==p->separator[0] && @@ -500,24 +639,26 @@ static void output_csv(struct callback_data *p, const char *z, int bSep){ ** This routine runs when the user presses Ctrl-C */ static void interrupt_handler(int NotUsed){ + UNUSED_PARAMETER(NotUsed); seenInterrupt = 1; if( db ) sqlite3_interrupt(db); } #endif /* -** This is the callback routine that the SQLite library +** This is the callback routine that the shell ** invokes for each row of a query result. */ -static int callback(void *pArg, int nArg, char **azArg, char **azCol){ +static int shell_callback(void *pArg, int nArg, char **azArg, char **azCol, int *aiType){ int i; struct callback_data *p = (struct callback_data*)pArg; + switch( p->mode ){ case MODE_Line: { int w = 5; if( azArg==0 ) break; for(i=0; iw ) w = len; } if( p->cnt++>0 ) fprintf(p->out,"\n"); @@ -538,9 +679,9 @@ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ w = 0; } if( w<=0 ){ - w = strlen(azCol[i] ? azCol[i] : ""); + w = strlen30(azCol[i] ? azCol[i] : ""); if( w<10 ) w = 10; - n = strlen(azArg && azArg[i] ? azArg[i] : p->nullvalue); + n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullvalue); if( wactualWidth) ){ @@ -572,8 +713,9 @@ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ }else{ w = 10; } - if( p->mode==MODE_Explain && azArg[i] && strlen(azArg[i])>w ){ - w = strlen(azArg[i]); + if( p->mode==MODE_Explain && azArg[i] && + strlen30(azArg[i])>w ){ + w = strlen30(azArg[i]); } fprintf(p->out,"%-*.*s%s",w,w, azArg[i] ? azArg[i] : p->nullvalue, i==nArg-1 ? "\n": " "); @@ -606,7 +748,9 @@ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ if( p->cnt++==0 && p->showHeader ){ fprintf(p->out,""); for(i=0; iout,"%s",azCol[i]); + fprintf(p->out,""); + output_html_string(p->out, azCol[i]); + fprintf(p->out,"\n"); } fprintf(p->out,"\n"); } @@ -651,12 +795,23 @@ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ break; } case MODE_Insert: { + p->cnt++; if( azArg==0 ) break; fprintf(p->out,"INSERT INTO %s VALUES(",p->zDestTable); for(i=0; i0 ? ",": ""; - if( azArg[i]==0 ){ + if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ fprintf(p->out,"%sNULL",zSep); + }else if( aiType && aiType[i]==SQLITE_TEXT ){ + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_quoted_string(p->out, azArg[i]); + }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){ + fprintf(p->out,"%s%s",zSep, azArg[i]); + }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ + const void *pBlob = sqlite3_column_blob(p->pStmt, i); + int nBlob = sqlite3_column_bytes(p->pStmt, i); + if( zSep[0] ) fprintf(p->out,"%s",zSep); + output_hex_blob(p->out, pBlob, nBlob); }else if( isNumber(azArg[i], 0) ){ fprintf(p->out,"%s%s",zSep, azArg[i]); }else{ @@ -671,6 +826,15 @@ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ return 0; } +/* +** This is the callback routine that the SQLite library +** invokes for each row of a query result. +*/ +static int callback(void *pArg, int nArg, char **azArg, char **azCol){ + /* since we don't have type info, call the shell_callback with a NULL value */ + return shell_callback(pArg, nArg, azArg, azCol, NULL); +} + /* ** Set the destination table field of the callback_data structure to ** the name of the table given. Escape any quote characters in the @@ -696,7 +860,7 @@ static void set_table_name(struct callback_data *p, const char *zName){ if( needQuote ) n += 2; z = p->zDestTable = malloc( n+1 ); if( z==0 ){ - fprintf(stderr,"Out of memory!\n"); + fprintf(stderr,"Error: out of memory\n"); exit(1); } n = 0; @@ -720,8 +884,8 @@ static void set_table_name(struct callback_data *p, const char *zName){ static char *appendText(char *zIn, char const *zAppend, char quote){ int len; int i; - int nAppend = strlen(zAppend); - int nIn = (zIn?strlen(zIn):0); + int nAppend = strlen30(zAppend); + int nIn = (zIn?strlen30(zIn):0); len = nAppend+nIn+1; if( quote ){ @@ -762,7 +926,12 @@ static char *appendText(char *zIn, char const *zAppend, char quote){ ** This is used, for example, to show the schema of the database by ** querying the SQLITE_MASTER table. */ -static int run_table_dump_query(FILE *out, sqlite3 *db, const char *zSelect){ +static int run_table_dump_query( + FILE *out, /* Send output here */ + sqlite3 *db, /* Database to query */ + const char *zSelect, /* SELECT statement to extract content */ + const char *zFirstRow /* Print before first row, if not NULL */ +){ sqlite3_stmt *pSelect; int rc; rc = sqlite3_prepare(db, zSelect, -1, &pSelect, 0); @@ -771,12 +940,246 @@ static int run_table_dump_query(FILE *out, sqlite3 *db, const char *zSelect){ } rc = sqlite3_step(pSelect); while( rc==SQLITE_ROW ){ + if( zFirstRow ){ + fprintf(out, "%s", zFirstRow); + zFirstRow = 0; + } fprintf(out, "%s;\n", sqlite3_column_text(pSelect, 0)); rc = sqlite3_step(pSelect); } return sqlite3_finalize(pSelect); } +/* +** Allocate space and save off current error string. +*/ +static char *save_err_msg( + sqlite3 *db /* Database to query */ +){ + int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); + char *zErrMsg = sqlite3_malloc(nErrMsg); + if( zErrMsg ){ + memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); + } + return zErrMsg; +} + +/* +** Display memory stats. +*/ +static int display_stats( + sqlite3 *db, /* Database to query */ + struct callback_data *pArg, /* Pointer to struct callback_data */ + int bReset /* True to reset the stats */ +){ + int iCur; + int iHiwtr; + + if( pArg && pArg->out ){ + + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr); +/* +** Not currently used by the CLI. +** iHiwtr = iCur = -1; +** sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); +** fprintf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr); +*/ + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); +/* +** Not currently used by the CLI. +** iHiwtr = iCur = -1; +** sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); +** fprintf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr); +*/ + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr); +#ifdef YYTRACKMAXSTACKDEPTH + iHiwtr = iCur = -1; + sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr); +#endif + } + + if( pArg && pArg->out && db ){ + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); + sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); + iHiwtr = iCur = -1; + sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); + fprintf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); + } + + if( pArg && pArg->out && db && pArg->pStmt ){ + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); + fprintf(pArg->out, "Fullscan Steps: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); + fprintf(pArg->out, "Sort Operations: %d\n", iCur); + iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX, bReset); + fprintf(pArg->out, "Autoindex Inserts: %d\n", iCur); + } + + return 0; +} + +/* +** Execute a statement or set of statements. Print +** any result rows/columns depending on the current mode +** set via the supplied callback. +** +** This is very similar to SQLite's built-in sqlite3_exec() +** function except it takes a slightly different callback +** and callback data argument. +*/ +static int shell_exec( + sqlite3 *db, /* An open database */ + const char *zSql, /* SQL to be evaluated */ + int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ + /* (not the same as sqlite3_exec) */ + struct callback_data *pArg, /* Pointer to struct callback_data */ + char **pzErrMsg /* Error msg written here */ +){ + sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ + int rc = SQLITE_OK; /* Return Code */ + const char *zLeftover; /* Tail of unprocessed SQL */ + + if( pzErrMsg ){ + *pzErrMsg = NULL; + } + + while( zSql[0] && (SQLITE_OK == rc) ){ + rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); + if( SQLITE_OK != rc ){ + if( pzErrMsg ){ + *pzErrMsg = save_err_msg(db); + } + }else{ + if( !pStmt ){ + /* this happens for a comment or white-space */ + zSql = zLeftover; + while( isspace(zSql[0]) ) zSql++; + continue; + } + + /* save off the prepared statment handle and reset row count */ + if( pArg ){ + pArg->pStmt = pStmt; + pArg->cnt = 0; + } + + /* echo the sql statement if echo on */ + if( pArg && pArg->echoOn ){ + const char *zStmtSql = sqlite3_sql(pStmt); + fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); + } + + /* perform the first step. this will tell us if we + ** have a result set or not and how wide it is. + */ + rc = sqlite3_step(pStmt); + /* if we have a result set... */ + if( SQLITE_ROW == rc ){ + /* if we have a callback... */ + if( xCallback ){ + /* allocate space for col name ptr, value ptr, and type */ + int nCol = sqlite3_column_count(pStmt); + void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1); + if( !pData ){ + rc = SQLITE_NOMEM; + }else{ + char **azCols = (char **)pData; /* Names of result columns */ + char **azVals = &azCols[nCol]; /* Results */ + int *aiTypes = (int *)&azVals[nCol]; /* Result types */ + int i; + assert(sizeof(int) <= sizeof(char *)); + /* save off ptrs to column names */ + for(i=0; istatsOn ){ + display_stats(db, pArg, 0); + } + + /* Finalize the statement just executed. If this fails, save a + ** copy of the error message. Otherwise, set zSql to point to the + ** next statement to execute. */ + rc = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ){ + zSql = zLeftover; + while( isspace(zSql[0]) ) zSql++; + }else if( pzErrMsg ){ + *pzErrMsg = save_err_msg(db); + } + + /* clear saved stmt handle */ + if( pArg ){ + pArg->pStmt = NULL; + } + } + } /* end while */ + + return rc; +} + /* ** This is a different callback routine used for dumping the database. @@ -789,15 +1192,17 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ const char *zTable; const char *zType; const char *zSql; + const char *zPrepStmt = 0; struct callback_data *p = (struct callback_data *)pArg; + UNUSED_PARAMETER(azCol); if( nArg!=3 ) return 1; zTable = azArg[0]; zType = azArg[1]; zSql = azArg[2]; if( strcmp(zTable, "sqlite_sequence")==0 ){ - fprintf(p->out, "DELETE FROM sqlite_sequence;\n"); + zPrepStmt = "DELETE FROM sqlite_sequence;\n"; }else if( strcmp(zTable, "sqlite_stat1")==0 ){ fprintf(p->out, "ANALYZE sqlite_master;\n"); }else if( strncmp(zTable, "sqlite_", 7)==0 ){ @@ -824,13 +1229,14 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ char *zSelect = 0; char *zTableInfo = 0; char *zTmp = 0; + int nRow = 0; zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); zTableInfo = appendText(zTableInfo, zTable, '"'); zTableInfo = appendText(zTableInfo, ");", 0); rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0); - if( zTableInfo ) free(zTableInfo); + free(zTableInfo); if( rc!=SQLITE_OK || !pTableInfo ){ return 1; } @@ -852,19 +1258,20 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ }else{ zSelect = appendText(zSelect, ") ", 0); } + nRow++; } rc = sqlite3_finalize(pTableInfo); - if( rc!=SQLITE_OK ){ - if( zSelect ) free(zSelect); + if( rc!=SQLITE_OK || nRow==0 ){ + free(zSelect); return 1; } zSelect = appendText(zSelect, "|| ')' FROM ", 0); zSelect = appendText(zSelect, zTable, '"'); - rc = run_table_dump_query(p->out, p->db, zSelect); + rc = run_table_dump_query(p->out, p->db, zSelect, zPrepStmt); if( rc==SQLITE_CORRUPT ){ zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); - rc = run_table_dump_query(p->out, p->db, zSelect); + rc = run_table_dump_query(p->out, p->db, zSelect, 0); } if( zSelect ) free(zSelect); } @@ -887,7 +1294,7 @@ static int run_schema_dump_query( rc = sqlite3_exec(p->db, zQuery, dump_callback, p, pzErrMsg); if( rc==SQLITE_CORRUPT ){ char *zQ2; - int len = strlen(zQuery); + int len = strlen30(zQuery); if( pzErrMsg ) sqlite3_free(*pzErrMsg); zQ2 = malloc( len+100 ); if( zQ2==0 ) return rc; @@ -902,22 +1309,29 @@ static int run_schema_dump_query( ** Text of a help message */ static char zHelp[] = + ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" ".bail ON|OFF Stop after hitting an error. Default OFF\n" ".databases List names and files of attached databases\n" ".dump ?TABLE? ... Dump the database in an SQL text format\n" + " If TABLE specified, only dump tables matching\n" + " LIKE pattern TABLE.\n" ".echo ON|OFF Turn command echo on or off\n" ".exit Exit this program\n" - ".explain ON|OFF Turn output mode suitable for EXPLAIN on or off.\n" + ".explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off.\n" + " With no args, it turns EXPLAIN on.\n" ".header(s) ON|OFF Turn display of headers on or off\n" ".help Show this message\n" ".import FILE TABLE Import data from FILE into TABLE\n" - ".indices TABLE Show names of all indices on TABLE\n" + ".indices ?TABLE? Show names of all indices\n" + " If TABLE specified, only show indices for tables\n" + " matching LIKE pattern TABLE.\n" #ifdef SQLITE_ENABLE_IOTRACE ".iotrace FILE Enable I/O diagnostic logging to FILE\n" #endif #ifndef SQLITE_OMIT_LOAD_EXTENSION ".load FILE ?ENTRY? Load an extension library\n" #endif + ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" " csv Comma-separated values\n" " column Left-aligned columns. (See .width)\n" @@ -933,15 +1347,22 @@ static char zHelp[] = ".prompt MAIN CONTINUE Replace the standard prompts\n" ".quit Exit this program\n" ".read FILENAME Execute SQL in FILENAME\n" + ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" ".schema ?TABLE? Show the CREATE statements\n" + " If TABLE specified, only show tables matching\n" + " LIKE pattern TABLE.\n" ".separator STRING Change separator used by output mode and .import\n" ".show Show the current values for various settings\n" - ".tables ?PATTERN? List names of tables matching a LIKE pattern\n" + ".stats ON|OFF Turn stats on or off\n" + ".tables ?TABLE? List names of tables\n" + " If TABLE specified, only list tables matching\n" + " LIKE pattern TABLE.\n" ".timeout MS Try opening locked tables for MS milliseconds\n" -#if HAS_TIMER + ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" +; + +static char zTimerHelp[] = ".timer ON|OFF Turn the CPU timer measurement on or off\n" -#endif - ".width NUM NUM ... Set column widths for \"column\" mode\n" ; /* Forward reference */ @@ -960,7 +1381,7 @@ static void open_db(struct callback_data *p){ shellstaticFunc, 0, 0); } if( db==0 || SQLITE_OK!=sqlite3_errcode(db) ){ - fprintf(stderr,"Unable to open database \"%s\": %s\n", + fprintf(stderr,"Error: unable to open database \"%s\": %s\n", p->zDbFilename, sqlite3_errmsg(db)); exit(1); } @@ -980,7 +1401,8 @@ static void open_db(struct callback_data *p){ ** \\ -> backslash */ static void resolve_backslashes(char *z){ - int i, j, c; + int i, j; + char c; for(i=j=0; (c = z[i])!=0; i++, j++){ if( c=='\\' ){ c = z[++i]; @@ -1014,7 +1436,7 @@ static int booleanValue(char *zArg){ int val = atoi(zArg); int j; for(j=0; zArg[j]; j++){ - zArg[j] = tolower(zArg[j]); + zArg[j] = (char)tolower(zArg[j]); } if( strcmp(zArg,"on")==0 ){ val = 1; @@ -1060,14 +1482,50 @@ static int do_meta_command(char *zLine, struct callback_data *p){ /* Process the input line. */ - if( nArg==0 ) return rc; - n = strlen(azArg[0]); + if( nArg==0 ) return 0; /* no tokens, no error */ + n = strlen30(azArg[0]); c = azArg[0][0]; - if( c=='b' && n>1 && strncmp(azArg[0], "bail", n)==0 && nArg>1 ){ + if( c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0 && nArg>1 && nArg<4){ + const char *zDestFile; + const char *zDb; + sqlite3 *pDest; + sqlite3_backup *pBackup; + if( nArg==2 ){ + zDestFile = azArg[1]; + zDb = "main"; + }else{ + zDestFile = azArg[2]; + zDb = azArg[1]; + } + rc = sqlite3_open(zDestFile, &pDest); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zDestFile); + sqlite3_close(pDest); + return 1; + } + open_db(p); + pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); + if( pBackup==0 ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); + sqlite3_close(pDest); + return 1; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = 0; + }else{ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); + rc = 1; + } + sqlite3_close(pDest); + }else + + if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 && nArg>1 && nArg<3 ){ bail_on_error = booleanValue(azArg[1]); }else - if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ + if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 && nArg==1 ){ struct callback_data data; char *zErrMsg = 0; open_db(p); @@ -1082,22 +1540,32 @@ static int do_meta_command(char *zLine, struct callback_data *p){ if( zErrMsg ){ fprintf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); + rc = 1; } }else - if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ + if( c=='d' && strncmp(azArg[0], "dump", n)==0 && nArg<3 ){ char *zErrMsg = 0; open_db(p); + /* When playing back a "dump", the content might appear in an order + ** which causes immediate foreign key constraints to be violated. + ** So disable foreign-key constraint enforcement to prevent problems. */ + fprintf(p->out, "PRAGMA foreign_keys=OFF;\n"); fprintf(p->out, "BEGIN TRANSACTION;\n"); p->writableSchema = 0; + sqlite3_exec(p->db, "PRAGMA writable_schema=ON", 0, 0, 0); if( nArg==1 ){ run_schema_dump_query(p, "SELECT name, type, sql FROM sqlite_master " - "WHERE sql NOT NULL AND type=='table'", 0 + "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'", 0 + ); + run_schema_dump_query(p, + "SELECT name, type, sql FROM sqlite_master " + "WHERE name=='sqlite_sequence'", 0 ); run_table_dump_query(p->out, p->db, "SELECT sql FROM sqlite_master " - "WHERE sql NOT NULL AND type IN ('index','trigger','view')" + "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 ); }else{ int i; @@ -1111,7 +1579,7 @@ static int do_meta_command(char *zLine, struct callback_data *p){ "SELECT sql FROM sqlite_master " "WHERE sql NOT NULL" " AND type IN ('index','trigger','view')" - " AND tbl_name LIKE shellstatic()" + " AND tbl_name LIKE shellstatic()", 0 ); zShellStatic = 0; } @@ -1120,6 +1588,7 @@ static int do_meta_command(char *zLine, struct callback_data *p){ fprintf(p->out, "PRAGMA writable_schema=OFF;\n"); p->writableSchema = 0; } + sqlite3_exec(p->db, "PRAGMA writable_schema=OFF", 0, 0, 0); if( zErrMsg ){ fprintf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); @@ -1128,15 +1597,15 @@ static int do_meta_command(char *zLine, struct callback_data *p){ } }else - if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){ + if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){ p->echoOn = booleanValue(azArg[1]); }else - if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ + if( c=='e' && strncmp(azArg[0], "exit", n)==0 && nArg==1 ){ rc = 2; }else - if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ + if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){ int val = nArg>=2 ? booleanValue(azArg[1]) : 1; if(val == 1) { if(!p->explainPrev.valid) { @@ -1172,19 +1641,21 @@ static int do_meta_command(char *zLine, struct callback_data *p){ }else if( c=='h' && (strncmp(azArg[0], "header", n)==0 || - strncmp(azArg[0], "headers", n)==0 )&& nArg>1 ){ + strncmp(azArg[0], "headers", n)==0) && nArg>1 && nArg<3 ){ p->showHeader = booleanValue(azArg[1]); }else if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ - fprintf(stderr,zHelp); + fprintf(stderr,"%s",zHelp); + if( HAS_TIMER ){ + fprintf(stderr,"%s",zTimerHelp); + } }else - if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg>=3 ){ + if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){ char *zTable = azArg[2]; /* Insert data into this table */ char *zFile = azArg[1]; /* The file from which to extract data */ - sqlite3_stmt *pStmt; /* A statement */ - int rc; /* Result code */ + sqlite3_stmt *pStmt = NULL; /* A statement */ int nCol; /* Number of columns in the table */ int nByte; /* Number of bytes in an SQL string */ int i, j; /* Loop counters */ @@ -1197,29 +1668,35 @@ static int do_meta_command(char *zLine, struct callback_data *p){ int lineno = 0; /* Line number of input file */ open_db(p); - nSep = strlen(p->separator); + nSep = strlen30(p->separator); if( nSep==0 ){ - fprintf(stderr, "non-null separator required for import\n"); - return 0; + fprintf(stderr, "Error: non-null separator required for import\n"); + return 1; } zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable); - if( zSql==0 ) return 0; - nByte = strlen(zSql); + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + return 1; + } + nByte = strlen30(zSql); rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ){ + if (pStmt) sqlite3_finalize(pStmt); fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db)); - nCol = 0; - rc = 1; - }else{ - nCol = sqlite3_column_count(pStmt); + return 1; } + nCol = sqlite3_column_count(pStmt); sqlite3_finalize(pStmt); - if( nCol==0 ) return 0; + pStmt = 0; + if( nCol==0 ) return 0; /* no columns, no error */ zSql = malloc( nByte + 20 + nCol*2 ); - if( zSql==0 ) return 0; + if( zSql==0 ){ + fprintf(stderr, "Error: out of memory\n"); + return 1; + } sqlite3_snprintf(nByte+20, zSql, "INSERT INTO '%q' VALUES(?", zTable); - j = strlen(zSql); + j = strlen30(zSql); for(i=1; idb, "BEGIN", 0, 0, 0); zCommit = "COMMIT"; @@ -1260,13 +1739,16 @@ static int do_meta_command(char *zLine, struct callback_data *p){ z += nSep-1; } } - } + } /* end for */ *z = 0; if( i+1!=nCol ){ - fprintf(stderr,"%s line %d: expected %d columns of data but found %d\n", - zFile, lineno, nCol, i+1); + fprintf(stderr, + "Error: %s line %d: expected %d columns of data but found %d\n", + zFile, lineno, nCol, i+1); zCommit = "ROLLBACK"; - break; + free(zLine); + rc = 1; + break; /* from while */ } for(i=0; idb, zCommit, 0, 0, 0); }else - if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg>1 ){ + if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){ struct callback_data data; char *zErrMsg = 0; open_db(p); memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.mode = MODE_List; - zShellStatic = azArg[1]; - sqlite3_exec(p->db, - "SELECT name FROM sqlite_master " - "WHERE type='index' AND tbl_name LIKE shellstatic() " - "UNION ALL " - "SELECT name FROM sqlite_temp_master " - "WHERE type='index' AND tbl_name LIKE shellstatic() " - "ORDER BY 1", - callback, &data, &zErrMsg - ); - zShellStatic = 0; + if( nArg==1 ){ + rc = sqlite3_exec(p->db, + "SELECT name FROM sqlite_master " + "WHERE type='index' AND name NOT LIKE 'sqlite_%' " + "UNION ALL " + "SELECT name FROM sqlite_temp_master " + "WHERE type='index' " + "ORDER BY 1", + callback, &data, &zErrMsg + ); + }else{ + zShellStatic = azArg[1]; + rc = sqlite3_exec(p->db, + "SELECT name FROM sqlite_master " + "WHERE type='index' AND tbl_name LIKE shellstatic() " + "UNION ALL " + "SELECT name FROM sqlite_temp_master " + "WHERE type='index' AND tbl_name LIKE shellstatic() " + "ORDER BY 1", + callback, &data, &zErrMsg + ); + zShellStatic = 0; + } if( zErrMsg ){ fprintf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n"); + rc = 1; } }else @@ -1324,8 +1822,9 @@ static int do_meta_command(char *zLine, struct callback_data *p){ }else{ iotrace = fopen(azArg[1], "w"); if( iotrace==0 ){ - fprintf(stderr, "cannot open \"%s\"\n", azArg[1]); + fprintf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); sqlite3IoTrace = 0; + rc = 1; }else{ sqlite3IoTrace = iotracePrintf; } @@ -1337,51 +1836,79 @@ static int do_meta_command(char *zLine, struct callback_data *p){ if( c=='l' && strncmp(azArg[0], "load", n)==0 && nArg>=2 ){ const char *zFile, *zProc; char *zErrMsg = 0; - int rc; zFile = azArg[1]; zProc = nArg>=3 ? azArg[2] : 0; open_db(p); rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); if( rc!=SQLITE_OK ){ - fprintf(stderr, "%s\n", zErrMsg); + fprintf(stderr, "Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; } }else #endif - if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg>=2 ){ - int n2 = strlen(azArg[1]); - if( strncmp(azArg[1],"line",n2)==0 + if( c=='l' && strncmp(azArg[0], "log", n)==0 && nArg>=2 ){ + const char *zFile = azArg[1]; + if( p->pLog && p->pLog!=stdout && p->pLog!=stderr ){ + fclose(p->pLog); + p->pLog = 0; + } + if( strcmp(zFile,"stdout")==0 ){ + p->pLog = stdout; + }else if( strcmp(zFile, "stderr")==0 ){ + p->pLog = stderr; + }else if( strcmp(zFile, "off")==0 ){ + p->pLog = 0; + }else{ + p->pLog = fopen(zFile, "w"); + if( p->pLog==0 ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zFile); + } + } + }else + + if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==2 ){ + int n2 = strlen30(azArg[1]); + if( (n2==4 && strncmp(azArg[1],"line",n2)==0) || - strncmp(azArg[1],"lines",n2)==0 ){ + (n2==5 && strncmp(azArg[1],"lines",n2)==0) ){ p->mode = MODE_Line; - }else if( strncmp(azArg[1],"column",n2)==0 + }else if( (n2==6 && strncmp(azArg[1],"column",n2)==0) || - strncmp(azArg[1],"columns",n2)==0 ){ + (n2==7 && strncmp(azArg[1],"columns",n2)==0) ){ p->mode = MODE_Column; - }else if( strncmp(azArg[1],"list",n2)==0 ){ + }else if( n2==4 && strncmp(azArg[1],"list",n2)==0 ){ p->mode = MODE_List; - }else if( strncmp(azArg[1],"html",n2)==0 ){ + }else if( n2==4 && strncmp(azArg[1],"html",n2)==0 ){ p->mode = MODE_Html; - }else if( strncmp(azArg[1],"tcl",n2)==0 ){ + }else if( n2==3 && strncmp(azArg[1],"tcl",n2)==0 ){ p->mode = MODE_Tcl; - }else if( strncmp(azArg[1],"csv",n2)==0 ){ + }else if( n2==3 && strncmp(azArg[1],"csv",n2)==0 ){ p->mode = MODE_Csv; sqlite3_snprintf(sizeof(p->separator), p->separator, ","); - }else if( strncmp(azArg[1],"tabs",n2)==0 ){ + }else if( n2==4 && strncmp(azArg[1],"tabs",n2)==0 ){ p->mode = MODE_List; sqlite3_snprintf(sizeof(p->separator), p->separator, "\t"); - }else if( strncmp(azArg[1],"insert",n2)==0 ){ + }else if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ p->mode = MODE_Insert; - if( nArg>=3 ){ - set_table_name(p, azArg[2]); - }else{ - set_table_name(p, "table"); - } + set_table_name(p, "table"); }else { - fprintf(stderr,"mode should be one of: " + fprintf(stderr,"Error: mode should be one of: " "column csv html insert line list tabs tcl\n"); + rc = 1; + } + }else + + if( c=='m' && strncmp(azArg[0], "mode", n)==0 && nArg==3 ){ + int n2 = strlen30(azArg[1]); + if( n2==6 && strncmp(azArg[1],"insert",n2)==0 ){ + p->mode = MODE_Insert; + set_table_name(p, azArg[2]); + }else { + fprintf(stderr, "Error: invalid arguments: " + " \"%s\". Enter \".help\" for help\n", azArg[2]); + rc = 1; } }else @@ -1400,8 +1927,9 @@ static int do_meta_command(char *zLine, struct callback_data *p){ }else{ p->out = fopen(azArg[1], "wb"); if( p->out==0 ){ - fprintf(stderr,"can't write to \"%s\"\n", azArg[1]); + fprintf(stderr,"Error: cannot write to \"%s\"\n", azArg[1]); p->out = stdout; + rc = 1; } else { sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", azArg[1]); } @@ -1417,21 +1945,69 @@ static int do_meta_command(char *zLine, struct callback_data *p){ } }else - if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ + if( c=='q' && strncmp(azArg[0], "quit", n)==0 && nArg==1 ){ rc = 2; }else - if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){ + if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 && nArg==2 ){ FILE *alt = fopen(azArg[1], "rb"); if( alt==0 ){ - fprintf(stderr,"can't open \"%s\"\n", azArg[1]); + fprintf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); + rc = 1; }else{ - process_input(p, alt); + rc = process_input(p, alt); fclose(alt); } }else - if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ + if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 && nArg>1 && nArg<4){ + const char *zSrcFile; + const char *zDb; + sqlite3 *pSrc; + sqlite3_backup *pBackup; + int nTimeout = 0; + + if( nArg==2 ){ + zSrcFile = azArg[1]; + zDb = "main"; + }else{ + zSrcFile = azArg[2]; + zDb = azArg[1]; + } + rc = sqlite3_open(zSrcFile, &pSrc); + if( rc!=SQLITE_OK ){ + fprintf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); + sqlite3_close(pSrc); + return 1; + } + open_db(p); + pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); + if( pBackup==0 ){ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); + sqlite3_close(pSrc); + return 1; + } + while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK + || rc==SQLITE_BUSY ){ + if( rc==SQLITE_BUSY ){ + if( nTimeout++ >= 3 ) break; + sqlite3_sleep(100); + } + } + sqlite3_backup_finish(pBackup); + if( rc==SQLITE_DONE ){ + rc = 0; + }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ + fprintf(stderr, "Error: source database is busy\n"); + rc = 1; + }else{ + fprintf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); + rc = 1; + } + sqlite3_close(pSrc); + }else + + if( c=='s' && strncmp(azArg[0], "schema", n)==0 && nArg<3 ){ struct callback_data data; char *zErrMsg = 0; open_db(p); @@ -1440,7 +2016,7 @@ static int do_meta_command(char *zLine, struct callback_data *p){ data.mode = MODE_Semi; if( nArg>1 ){ int i; - for(i=0; azArg[1][i]; i++) azArg[1][i] = tolower(azArg[1][i]); + for(i=0; azArg[1][i]; i++) azArg[1][i] = (char)tolower(azArg[1][i]); if( strcmp(azArg[1],"sqlite_master")==0 ){ char *new_argv[2], *new_colv[2]; new_argv[0] = "CREATE TABLE sqlite_master (\n" @@ -1454,6 +2030,7 @@ static int do_meta_command(char *zLine, struct callback_data *p){ new_colv[0] = "sql"; new_colv[1] = 0; callback(&data, 1, new_argv, new_colv); + rc = SQLITE_OK; }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ char *new_argv[2], *new_colv[2]; new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" @@ -1467,22 +2044,25 @@ static int do_meta_command(char *zLine, struct callback_data *p){ new_colv[0] = "sql"; new_colv[1] = 0; callback(&data, 1, new_argv, new_colv); + rc = SQLITE_OK; }else{ zShellStatic = azArg[1]; - sqlite3_exec(p->db, + rc = sqlite3_exec(p->db, "SELECT sql FROM " - " (SELECT * FROM sqlite_master UNION ALL" - " SELECT * FROM sqlite_temp_master) " + " (SELECT sql sql, type type, tbl_name tbl_name, name name" + " FROM sqlite_master UNION ALL" + " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) " "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL " "ORDER BY substr(type,2,1), name", callback, &data, &zErrMsg); zShellStatic = 0; } }else{ - sqlite3_exec(p->db, + rc = sqlite3_exec(p->db, "SELECT sql FROM " - " (SELECT * FROM sqlite_master UNION ALL" - " SELECT * FROM sqlite_temp_master) " + " (SELECT sql sql, type type, tbl_name tbl_name, name name" + " FROM sqlite_master UNION ALL" + " SELECT sql, type, tbl_name, name FROM sqlite_temp_master) " "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%'" "ORDER BY substr(type,2,1), name", callback, &data, &zErrMsg @@ -1491,6 +2071,12 @@ static int do_meta_command(char *zLine, struct callback_data *p){ if( zErrMsg ){ fprintf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying schema information\n"); + rc = 1; + }else{ + rc = 0; } }else @@ -1499,7 +2085,7 @@ static int do_meta_command(char *zLine, struct callback_data *p){ "%.*s", (int)sizeof(p->separator)-1, azArg[1]); }else - if( c=='s' && strncmp(azArg[0], "show", n)==0){ + if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){ int i; fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off"); fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off"); @@ -1509,10 +2095,11 @@ static int do_meta_command(char *zLine, struct callback_data *p){ output_c_string(p->out, p->nullvalue); fprintf(p->out, "\n"); fprintf(p->out,"%9.9s: %s\n","output", - strlen(p->outfile) ? p->outfile : "stdout"); + strlen30(p->outfile) ? p->outfile : "stdout"); fprintf(p->out,"%9.9s: ", "separator"); output_c_string(p->out, p->separator); fprintf(p->out, "\n"); + fprintf(p->out,"%9.9s: %s\n","stats", p->statsOn ? "on" : "off"); fprintf(p->out,"%9.9s: ","width"); for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { fprintf(p->out,"%d ",p->colWidth[i]); @@ -1520,15 +2107,19 @@ static int do_meta_command(char *zLine, struct callback_data *p){ fprintf(p->out,"\n"); }else - if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){ + if( c=='s' && strncmp(azArg[0], "stats", n)==0 && nArg>1 && nArg<3 ){ + p->statsOn = booleanValue(azArg[1]); + }else + + if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 && nArg<3 ){ char **azResult; - int nRow, rc; + int nRow; char *zErrMsg; open_db(p); if( nArg==1 ){ rc = sqlite3_get_table(p->db, "SELECT name FROM sqlite_master " - "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'" + "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' " "UNION ALL " "SELECT name FROM sqlite_temp_master " "WHERE type IN ('table','view') " @@ -1539,10 +2130,10 @@ static int do_meta_command(char *zLine, struct callback_data *p){ zShellStatic = azArg[1]; rc = sqlite3_get_table(p->db, "SELECT name FROM sqlite_master " - "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' " + "WHERE type IN ('table','view') AND name LIKE shellstatic() " "UNION ALL " "SELECT name FROM sqlite_temp_master " - "WHERE type IN ('table','view') AND name LIKE '%'||shellstatic()||'%' " + "WHERE type IN ('table','view') AND name LIKE shellstatic() " "ORDER BY 1", &azResult, &nRow, 0, &zErrMsg ); @@ -1551,14 +2142,17 @@ static int do_meta_command(char *zLine, struct callback_data *p){ if( zErrMsg ){ fprintf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); - } - if( rc==SQLITE_OK ){ + rc = 1; + }else if( rc != SQLITE_OK ){ + fprintf(stderr,"Error: querying sqlite_master and sqlite_temp_master\n"); + rc = 1; + }else{ int len, maxlen = 0; int i, j; int nPrintCol, nPrintRow; for(i=1; i<=nRow; i++){ if( azResult[i]==0 ) continue; - len = strlen(azResult[i]); + len = strlen30(azResult[i]); if( len>maxlen ) maxlen = len; } nPrintCol = 80/(maxlen+2); @@ -1571,24 +2165,149 @@ static int do_meta_command(char *zLine, struct callback_data *p){ } printf("\n"); } - }else{ - rc = 1; } sqlite3_free_table(azResult); }else - if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg>=2 ){ + if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){ + static const struct { + const char *zCtrlName; /* Name of a test-control option */ + int ctrlCode; /* Integer code for that option */ + } aCtrl[] = { + { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE }, + { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE }, + { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET }, + { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST }, + { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL }, + { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS }, + { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE }, + { "assert", SQLITE_TESTCTRL_ASSERT }, + { "always", SQLITE_TESTCTRL_ALWAYS }, + { "reserve", SQLITE_TESTCTRL_RESERVE }, + { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS }, + { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD }, + { "pghdrsz", SQLITE_TESTCTRL_PGHDRSZ }, + { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC }, + }; + int testctrl = -1; + int rc = 0; + int i, n; + open_db(p); + + /* convert testctrl text option to value. allow any unique prefix + ** of the option name, or a numerical value. */ + n = strlen30(azArg[1]); + for(i=0; i<(int)(sizeof(aCtrl)/sizeof(aCtrl[0])); i++){ + if( strncmp(azArg[1], aCtrl[i].zCtrlName, n)==0 ){ + if( testctrl<0 ){ + testctrl = aCtrl[i].ctrlCode; + }else{ + fprintf(stderr, "ambiguous option name: \"%s\"\n", azArg[i]); + testctrl = -1; + break; + } + } + } + if( testctrl<0 ) testctrl = atoi(azArg[1]); + if( (testctrlSQLITE_TESTCTRL_LAST) ){ + fprintf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]); + }else{ + switch(testctrl){ + + /* sqlite3_test_control(int, db, int) */ + case SQLITE_TESTCTRL_OPTIMIZATIONS: + case SQLITE_TESTCTRL_RESERVE: + if( nArg==3 ){ + int opt = (int)strtol(azArg[2], 0, 0); + rc = sqlite3_test_control(testctrl, p->db, opt); + printf("%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single int option\n", + azArg[1]); + } + break; + + /* sqlite3_test_control(int) */ + case SQLITE_TESTCTRL_PRNG_SAVE: + case SQLITE_TESTCTRL_PRNG_RESTORE: + case SQLITE_TESTCTRL_PRNG_RESET: + case SQLITE_TESTCTRL_PGHDRSZ: + if( nArg==2 ){ + rc = sqlite3_test_control(testctrl); + printf("%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]); + } + break; + + /* sqlite3_test_control(int, uint) */ + case SQLITE_TESTCTRL_PENDING_BYTE: + if( nArg==3 ){ + unsigned int opt = (unsigned int)atoi(azArg[2]); + rc = sqlite3_test_control(testctrl, opt); + printf("%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single unsigned" + " int option\n", azArg[1]); + } + break; + + /* sqlite3_test_control(int, int) */ + case SQLITE_TESTCTRL_ASSERT: + case SQLITE_TESTCTRL_ALWAYS: + if( nArg==3 ){ + int opt = atoi(azArg[2]); + rc = sqlite3_test_control(testctrl, opt); + printf("%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single int option\n", + azArg[1]); + } + break; + + /* sqlite3_test_control(int, char *) */ +#ifdef SQLITE_N_KEYWORD + case SQLITE_TESTCTRL_ISKEYWORD: + if( nArg==3 ){ + const char *opt = azArg[2]; + rc = sqlite3_test_control(testctrl, opt); + printf("%d (0x%08x)\n", rc, rc); + } else { + fprintf(stderr,"Error: testctrl %s takes a single char * option\n", + azArg[1]); + } + break; +#endif + + case SQLITE_TESTCTRL_BITVEC_TEST: + case SQLITE_TESTCTRL_FAULT_INSTALL: + case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: + case SQLITE_TESTCTRL_SCRATCHMALLOC: + default: + fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n", + azArg[1]); + break; + } + } + }else + + if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 && nArg==2 ){ open_db(p); sqlite3_busy_timeout(p->db, atoi(azArg[1])); }else - -#if HAS_TIMER - if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 && nArg>1 ){ + + if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 + && nArg==2 + ){ enableTimer = booleanValue(azArg[1]); }else -#endif + + if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ + printf("SQLite %s %s\n", + sqlite3_libversion(), sqlite3_sourceid()); + }else - if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ + if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){ int j; assert( nArg<=ArraySize(azArg) ); for(j=1; jcolWidth); j++){ @@ -1596,10 +2315,10 @@ static int do_meta_command(char *zLine, struct callback_data *p){ } }else - { - fprintf(stderr, "unknown command or invalid arguments: " + fprintf(stderr, "Error: unknown command or invalid arguments: " " \"%s\". Enter \".help\" for help\n", azArg[0]); + rc = 1; } return rc; @@ -1646,7 +2365,9 @@ static int _all_whitespace(const char *z){ */ static int _is_command_terminator(const char *zLine){ while( isspace(*(unsigned char*)zLine) ){ zLine++; }; - if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ) return 1; /* Oracle */ + if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ + return 1; /* Oracle */ + } if( tolower(zLine[0])=='g' && tolower(zLine[1])=='o' && _all_whitespace(&zLine[2]) ){ return 1; /* SQL Server */ @@ -1654,6 +2375,20 @@ static int _is_command_terminator(const char *zLine){ return 0; } +/* +** Return true if zSql is a complete SQL statement. Return false if it +** ends in the middle of a string literal or C-style comment. +*/ +static int _is_complete(char *zSql, int nSql){ + int rc; + if( zSql==0 ) return 1; + zSql[nSql] = ';'; + zSql[nSql+1] = 0; + rc = sqlite3_complete(zSql); + zSql[nSql] = 0; + return rc; +} + /* ** Read input from *in and process it. If *in==0 then input ** is interactive - the user is typing it it. Otherwise, input @@ -1686,18 +2421,18 @@ static int process_input(struct callback_data *p, FILE *in){ seenInterrupt = 0; } lineno++; - if( p->echoOn ) printf("%s\n", zLine); if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue; if( zLine && zLine[0]=='.' && nSql==0 ){ + if( p->echoOn ) printf("%s\n", zLine); rc = do_meta_command(zLine, p); - if( rc==2 ){ + if( rc==2 ){ /* exit requested */ break; }else if( rc ){ errCnt++; } continue; } - if( _is_command_terminator(zLine) ){ + if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){ memcpy(zLine,";",2); } nSqlPrior = nSql; @@ -1705,20 +2440,20 @@ static int process_input(struct callback_data *p, FILE *in){ int i; for(i=0; zLine[i] && isspace((unsigned char)zLine[i]); i++){} if( zLine[i]!=0 ){ - nSql = strlen(zLine); - zSql = malloc( nSql+1 ); + nSql = strlen30(zLine); + zSql = malloc( nSql+3 ); if( zSql==0 ){ - fprintf(stderr, "out of memory\n"); + fprintf(stderr, "Error: out of memory\n"); exit(1); } memcpy(zSql, zLine, nSql+1); startline = lineno; } }else{ - int len = strlen(zLine); - zSql = realloc( zSql, nSql + len + 2 ); + int len = strlen30(zLine); + zSql = realloc( zSql, nSql + len + 4 ); if( zSql==0 ){ - fprintf(stderr,"%s: out of memory!\n", Argv0); + fprintf(stderr,"Error: out of memory\n"); exit(1); } zSql[nSql++] = '\n'; @@ -1730,22 +2465,22 @@ static int process_input(struct callback_data *p, FILE *in){ p->cnt = 0; open_db(p); BEGIN_TIMER; - rc = sqlite3_exec(p->db, zSql, callback, p, &zErrMsg); + rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg); END_TIMER; if( rc || zErrMsg ){ char zPrefix[100]; if( in!=0 || !stdin_is_interactive ){ sqlite3_snprintf(sizeof(zPrefix), zPrefix, - "SQL error near line %d:", startline); + "Error: near line %d:", startline); }else{ - sqlite3_snprintf(sizeof(zPrefix), zPrefix, "SQL error:"); + sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); } if( zErrMsg!=0 ){ - printf("%s %s\n", zPrefix, zErrMsg); + fprintf(stderr, "%s %s\n", zPrefix, zErrMsg); sqlite3_free(zErrMsg); zErrMsg = 0; }else{ - printf("%s %s\n", zPrefix, sqlite3_errmsg(p->db)); + fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); } errCnt++; } @@ -1755,7 +2490,9 @@ static int process_input(struct callback_data *p, FILE *in){ } } if( zSql ){ - if( !_all_whitespace(zSql) ) printf("Incomplete SQL: %s\n", zSql); + if( !_all_whitespace(zSql) ){ + fprintf(stderr, "Error: incomplete SQL: %s\n", zSql); + } free(zSql); } free(zLine); @@ -1771,7 +2508,7 @@ static int process_input(struct callback_data *p, FILE *in){ static char *find_home_dir(void){ char *home_dir = NULL; -#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) +#if !defined(_WIN32) && !defined(WIN32) && !defined(__OS2__) && !defined(_WIN32_WCE) && !defined(__RTP__) && !defined(_WRS_KERNEL) struct passwd *pwent; uid_t uid = getuid(); if( (pwent=getpwuid(uid)) != NULL) { @@ -1802,7 +2539,7 @@ static char *find_home_dir(void){ zDrive = getenv("HOMEDRIVE"); zPath = getenv("HOMEPATH"); if( zDrive && zPath ){ - n = strlen(zDrive) + strlen(zPath) + 1; + n = strlen30(zDrive) + strlen30(zPath) + 1; home_dir = malloc( n ); if( home_dir==0 ) return 0; sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); @@ -1815,7 +2552,7 @@ static char *find_home_dir(void){ #endif /* !_WIN32_WCE */ if( home_dir ){ - int n = strlen(home_dir) + 1; + int n = strlen30(home_dir) + 1; char *z = malloc( n ); if( z ) memcpy(z, home_dir, n); home_dir = z; @@ -1827,8 +2564,10 @@ static char *find_home_dir(void){ /* ** Read input from the file given by sqliterc_override. Or if that ** parameter is NULL, take input from ~/.sqliterc +** +** Returns the number of errors. */ -static void process_sqliterc( +static int process_sqliterc( struct callback_data *p, /* Configuration data */ const char *sqliterc_override /* Name of config file. NULL to use default */ ){ @@ -1837,18 +2576,21 @@ static void process_sqliterc( char *zBuf = 0; FILE *in = NULL; int nBuf; + int rc = 0; if (sqliterc == NULL) { home_dir = find_home_dir(); if( home_dir==0 ){ - fprintf(stderr,"%s: cannot locate your home directory!\n", Argv0); - return; +#if !defined(__RTP__) && !defined(_WRS_KERNEL) + fprintf(stderr,"%s: Error: cannot locate your home directory\n", Argv0); +#endif + return 1; } - nBuf = strlen(home_dir) + 16; + nBuf = strlen30(home_dir) + 16; zBuf = malloc( nBuf ); if( zBuf==0 ){ - fprintf(stderr,"%s: out of memory!\n", Argv0); - exit(1); + fprintf(stderr,"%s: Error: out of memory\n",Argv0); + return 1; } sqlite3_snprintf(nBuf, zBuf,"%s/.sqliterc",home_dir); free(home_dir); @@ -1857,19 +2599,20 @@ static void process_sqliterc( in = fopen(sqliterc,"rb"); if( in ){ if( stdin_is_interactive ){ - printf("-- Loading resources from %s\n",sqliterc); + fprintf(stderr,"-- Loading resources from %s\n",sqliterc); } - process_input(p,in); + rc = process_input(p,in); fclose(in); } free(zBuf); - return; + return rc; } /* ** Show available command line options */ static const char zOptions[] = + " -help show this message\n" " -init filename read/process named file\n" " -echo print commands before execution\n" " -[no]header turn headers on or off\n" @@ -1882,8 +2625,13 @@ static const char zOptions[] = " -line set output mode to 'line'\n" " -list set output mode to 'list'\n" " -separator 'x' set output field separator (|)\n" + " -stats print memory stats before each finalize\n" " -nullvalue 'text' set text string for NULL values\n" " -version show SQLite version\n" + " -vfs NAME use NAME as the default VFS\n" +#ifdef SQLITE_ENABLE_VFSTRACE + " -vfstrace enable tracing of all VFS calls\n" +#endif ; static void usage(int showDetail){ fprintf(stderr, @@ -1906,8 +2654,11 @@ static void main_init(struct callback_data *data) { data->mode = MODE_List; memcpy(data->separator,"|", 2); data->showHeader = 0; + sqlite3_config(SQLITE_CONFIG_URI, 1); + sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); + sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); } int main(int argc, char **argv){ @@ -1918,6 +2669,11 @@ int main(int argc, char **argv){ int i; int rc = 0; + if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){ + fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", + sqlite3_sourceid(), SQLITE_SOURCE_ID); + exit(1); + } Argv0 = argv[0]; main_init(&data); stdin_is_interactive = isatty(0); @@ -1931,6 +2687,7 @@ int main(int argc, char **argv){ /* Do an initial pass through the command-line argument to locate ** the name of the database file, the name of the initialization file, + ** the size of the alternative malloc heap, ** and the first command to execute. */ for(i=1; i0x7fff0000 ) szHeap = 0x7fff0000; +#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) + sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); +#endif +#ifdef SQLITE_ENABLE_VFSTRACE + }else if( strcmp(argv[i],"-vfstrace")==0 ){ + extern int vfstrace_register( + const char *zTraceName, + const char *zOldVfsName, + int (*xOut)(const char*,void*), + void *pOutArg, + int makeDefault + ); + vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); +#endif + }else if( strcmp(argv[i],"-vfs")==0 ){ + sqlite3_vfs *pVfs = sqlite3_vfs_find(argv[++i]); + if( pVfs ){ + sqlite3_vfs_register(pVfs, 1); + }else{ + fprintf(stderr, "no such VFS: \"%s\"\n", argv[i]); + exit(1); + } } } if( i0 ){ + return rc; + } /* Make a second pass through the command-line argument and set ** options. This second pass is delayed until after the initialization @@ -2008,10 +2814,20 @@ int main(int argc, char **argv){ memcpy(data.separator,",",2); }else if( strcmp(z,"-separator")==0 ){ i++; + if(i>=argc){ + fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z); + fprintf(stderr,"Use -help for a list of options.\n"); + return 1; + } sqlite3_snprintf(sizeof(data.separator), data.separator, "%.*s",(int)sizeof(data.separator)-1,argv[i]); }else if( strcmp(z,"-nullvalue")==0 ){ i++; + if(i>=argc){ + fprintf(stderr,"%s: Error: missing argument for option: %s\n", Argv0, z); + fprintf(stderr,"Use -help for a list of options.\n"); + return 1; + } sqlite3_snprintf(sizeof(data.nullvalue), data.nullvalue, "%.*s",(int)sizeof(data.nullvalue)-1,argv[i]); }else if( strcmp(z,"-header")==0 ){ @@ -2020,19 +2836,27 @@ int main(int argc, char **argv){ data.showHeader = 0; }else if( strcmp(z,"-echo")==0 ){ data.echoOn = 1; + }else if( strcmp(z,"-stats")==0 ){ + data.statsOn = 1; }else if( strcmp(z,"-bail")==0 ){ bail_on_error = 1; }else if( strcmp(z,"-version")==0 ){ - printf("%s\n", sqlite3_libversion()); + printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); return 0; }else if( strcmp(z,"-interactive")==0 ){ stdin_is_interactive = 1; }else if( strcmp(z,"-batch")==0 ){ stdin_is_interactive = 0; + }else if( strcmp(z,"-heap")==0 ){ + i++; + }else if( strcmp(z,"-vfs")==0 ){ + i++; + }else if( strcmp(z,"-vfstrace")==0 ){ + i++; }else if( strcmp(z,"-help")==0 || strcmp(z, "--help")==0 ){ usage(1); }else{ - fprintf(stderr,"%s: unknown option: %s\n", Argv0, z); + fprintf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); fprintf(stderr,"Use -help for a list of options.\n"); return 1; } @@ -2042,15 +2866,16 @@ int main(int argc, char **argv){ /* Run just the command that follows the database name */ if( zFirstCmd[0]=='.' ){ - do_meta_command(zFirstCmd, &data); - exit(0); + rc = do_meta_command(zFirstCmd, &data); }else{ - int rc; open_db(&data); - rc = sqlite3_exec(data.db, zFirstCmd, callback, &data, &zErrMsg); - if( rc!=0 && zErrMsg!=0 ){ - fprintf(stderr,"SQL error: %s\n", zErrMsg); - exit(1); + rc = shell_exec(data.db, zFirstCmd, shell_callback, &data, &zErrMsg); + if( zErrMsg!=0 ){ + fprintf(stderr,"Error: %s\n", zErrMsg); + return rc!=0 ? rc : 1; + }else if( rc!=0 ){ + fprintf(stderr,"Error: unable to process SQL \"%s\"\n", zFirstCmd); + return rc; } } }else{ @@ -2061,13 +2886,17 @@ int main(int argc, char **argv){ char *zHistory = 0; int nHistory; printf( - "SQLite version %s\n" - "Enter \".help\" for instructions\n", - sqlite3_libversion() + "SQLite version %s %.19s\n" + "Enter \".help\" for instructions\n" + "Enter SQL statements terminated with a \";\"\n", + sqlite3_libversion(), sqlite3_sourceid() ); zHome = find_home_dir(); - if( zHome && (zHistory = malloc(nHistory = strlen(zHome)+20))!=0 ){ - sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); + if( zHome ){ + nHistory = strlen30(zHome) + 20; + if( (zHistory = malloc(nHistory))!=0 ){ + sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); + } } #if defined(HAVE_READLINE) && HAVE_READLINE==1 if( zHistory ) read_history(zHistory); @@ -2084,10 +2913,8 @@ int main(int argc, char **argv){ } } set_table_name(&data, 0); - if( db ){ - if( sqlite3_close(db)!=SQLITE_OK ){ - fprintf(stderr,"error closing database: %s\n", sqlite3_errmsg(db)); - } + if( data.db ){ + sqlite3_close(data.db); } return rc; } -- cgit v1.2.3