Files
sqlcipher/src/shell.c
T

5812 lines
177 KiB
C
Raw Normal View History

2008-07-30 09:15:43 -04:00
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement the "sqlite" command line
** utility for accessing SQLite databases.
*/
2011-12-26 14:52:17 -05:00
#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
2009-02-20 15:33:35 -05:00
/* This needs to come before any includes for MSVC compiler */
#define _CRT_SECURE_NO_WARNINGS
#endif
2015-03-20 09:04:26 -05:00
/*
** If requested, include the SQLite compiler options file for MSVC.
*/
#if defined(INCLUDE_MSVC_H)
#include "msvc.h"
#endif
2015-07-10 14:14:29 -05:00
/*
** No support for loadable extensions in VxWorks.
*/
#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
# define SQLITE_OMIT_LOAD_EXTENSION 1
#endif
2011-12-26 14:52:17 -05:00
/*
** Enable large-file support for fopen() and friends on unix.
*/
#ifndef SQLITE_DISABLE_LFS
# define _LARGE_FILE 1
# ifndef _FILE_OFFSET_BITS
# define _FILE_OFFSET_BITS 64
# endif
# define _LARGEFILE_SOURCE 1
#endif
2008-07-30 09:15:43 -04:00
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "sqlite3.h"
2015-03-20 09:04:26 -05:00
#if SQLITE_USER_AUTHENTICATION
# include "sqlite3userauth.h"
#endif
2008-07-30 09:15:43 -04:00
#include <ctype.h>
#include <stdarg.h>
2012-11-15 18:45:58 -05:00
#if !defined(_WIN32) && !defined(WIN32)
2008-07-30 09:15:43 -04:00
# include <signal.h>
2009-02-20 15:33:35 -05:00
# if !defined(__RTP__) && !defined(_WRS_KERNEL)
# include <pwd.h>
# endif
2008-07-30 09:15:43 -04:00
# include <unistd.h>
# include <sys/types.h>
#endif
2015-03-20 09:04:26 -05:00
#if HAVE_READLINE
2008-07-30 09:15:43 -04:00
# include <readline/readline.h>
# include <readline/history.h>
2011-02-16 16:14:46 -05:00
#endif
2015-03-20 09:04:26 -05:00
#if HAVE_EDITLINE
2014-04-04 10:16:20 -05:00
# include <editline/readline.h>
#endif
2015-03-20 09:04:26 -05:00
#if HAVE_EDITLINE || HAVE_READLINE
# define shell_add_history(X) add_history(X)
# define shell_read_history(X) read_history(X)
# define shell_write_history(X) write_history(X)
# define shell_stifle_history(X) stifle_history(X)
# define shell_readline(X) readline(X)
#elif HAVE_LINENOISE
# include "linenoise.h"
# define shell_add_history(X) linenoiseHistoryAdd(X)
# define shell_read_history(X) linenoiseHistoryLoad(X)
# define shell_write_history(X) linenoiseHistorySave(X)
# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
# define shell_readline(X) linenoise(X)
#else
2016-12-05 14:29:15 -06:00
# define shell_read_history(X)
2015-03-20 09:04:26 -05:00
# define shell_write_history(X)
# define shell_stifle_history(X)
# define SHELL_USE_LOCAL_GETLINE 1
2008-07-30 09:15:43 -04:00
#endif
2015-03-20 09:04:26 -05:00
2008-07-30 09:15:43 -04:00
#if defined(_WIN32) || defined(WIN32)
# include <io.h>
2014-09-30 08:40:45 -05:00
# include <fcntl.h>
2016-02-23 09:07:39 -06:00
# define isatty(h) _isatty(h)
# ifndef access
# define access(f,m) _access((f),(m))
# endif
# undef popen
# define popen _popen
# undef pclose
# define pclose _pclose
2008-07-30 09:15:43 -04:00
#else
2016-02-23 09:07:39 -06:00
/* Make sure isatty() has a prototype. */
extern int isatty(int);
2015-07-10 14:14:29 -05:00
2016-02-23 09:07:39 -06:00
# if !defined(__RTP__) && !defined(_WRS_KERNEL)
/* popen and pclose are not C89 functions and so are
** sometimes omitted from the <stdio.h> header */
extern FILE *popen(const char*,const char*);
extern int pclose(FILE*);
# else
# define SQLITE_OMIT_POPEN 1
# endif
2014-04-04 10:16:20 -05:00
#endif
2013-08-29 08:11:18 -05:00
2008-07-30 09:15:43 -04:00
#if defined(_WIN32_WCE)
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
* thus we always assume that we have a console. That can be
* overridden with the -batch command line option.
*/
#define isatty(x) 1
#endif
2011-12-26 14:52:17 -05:00
/* ctype macros that work with signed characters */
#define IsSpace(X) isspace((unsigned char)X)
#define IsDigit(X) isdigit((unsigned char)X)
#define ToLower(X) (char)tolower((unsigned char)X)
2016-12-05 14:29:15 -06:00
#if defined(_WIN32) || defined(WIN32)
#include <windows.h>
/* string conversion routines only needed on Win32 */
extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
#endif
2015-07-10 14:14:29 -05:00
/* On Windows, we normally run with output mode of TEXT so that \n characters
** are automatically translated into \r\n. However, this behavior needs
** to be disabled in some cases (ex: when generating CSV output and when
** rendering quoted strings that contain \n characters). The following
** routines take care of that.
*/
#if defined(_WIN32) || defined(WIN32)
2016-12-05 14:29:15 -06:00
static void setBinaryMode(FILE *file, int isOutput){
if( isOutput ) fflush(file);
_setmode(_fileno(file), _O_BINARY);
2015-07-10 14:14:29 -05:00
}
2016-12-05 14:29:15 -06:00
static void setTextMode(FILE *file, int isOutput){
if( isOutput ) fflush(file);
_setmode(_fileno(file), _O_TEXT);
2015-07-10 14:14:29 -05:00
}
#else
2016-12-05 14:29:15 -06:00
# define setBinaryMode(X,Y)
# define setTextMode(X,Y)
2015-07-10 14:14:29 -05:00
#endif
2014-04-04 10:16:20 -05:00
/* True if the timer is enabled */
static int enableTimer = 0;
/* Return the current wall-clock time */
static sqlite3_int64 timeOfDay(void){
static sqlite3_vfs *clockVfs = 0;
sqlite3_int64 t;
if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
2016-02-23 09:07:39 -06:00
if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
2014-04-04 10:16:20 -05:00
clockVfs->xCurrentTimeInt64(clockVfs, &t);
}else{
double r;
clockVfs->xCurrentTime(clockVfs, &r);
t = (sqlite3_int64)(r*86400000.0);
}
return t;
}
2015-07-10 14:14:29 -05:00
#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
2008-07-30 09:15:43 -04:00
#include <sys/time.h>
#include <sys/resource.h>
2015-07-10 14:14:29 -05:00
/* VxWorks does not support getrusage() as far as we can determine */
#if defined(_WRS_KERNEL) || defined(__RTP__)
struct rusage {
struct timeval ru_utime; /* user CPU time used */
struct timeval ru_stime; /* system CPU time used */
};
#define getrusage(A,B) memset(B,0,sizeof(*B))
#endif
2008-07-30 09:15:43 -04:00
/* Saved resource information for the beginning of an operation */
2014-04-04 10:16:20 -05:00
static struct rusage sBegin; /* CPU time at start */
static sqlite3_int64 iBegin; /* Wall-clock time at start */
2008-07-30 09:15:43 -04:00
/*
** Begin timing an operation
*/
static void beginTimer(void){
if( enableTimer ){
getrusage(RUSAGE_SELF, &sBegin);
2014-04-04 10:16:20 -05:00
iBegin = timeOfDay();
2008-07-30 09:15:43 -04:00
}
}
/* Return the difference of two time_structs in seconds */
static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
2016-12-05 14:29:15 -06:00
return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
2008-07-30 09:15:43 -04:00
(double)(pEnd->tv_sec - pStart->tv_sec);
}
/*
** Print the timing results.
*/
static void endTimer(void){
if( enableTimer ){
2014-04-04 10:16:20 -05:00
sqlite3_int64 iEnd = timeOfDay();
2015-07-10 14:14:29 -05:00
struct rusage sEnd;
2008-07-30 09:15:43 -04:00
getrusage(RUSAGE_SELF, &sEnd);
2014-04-04 10:16:20 -05:00
printf("Run Time: real %.3f user %f sys %f\n",
(iEnd - iBegin)*0.001,
2008-07-30 09:15:43 -04:00
timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
}
}
2009-12-03 16:24:07 -05:00
2008-07-30 09:15:43 -04:00
#define BEGIN_TIMER beginTimer()
#define END_TIMER endTimer()
#define HAS_TIMER 1
2009-12-03 16:24:07 -05:00
#elif (defined(_WIN32) || defined(WIN32))
/* Saved resource information for the beginning of an operation */
static HANDLE hProcess;
static FILETIME ftKernelBegin;
static FILETIME ftUserBegin;
2014-04-04 10:16:20 -05:00
static sqlite3_int64 ftWallBegin;
2015-03-20 09:04:26 -05:00
typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
LPFILETIME, LPFILETIME);
2009-12-03 16:24:07 -05:00
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 {
2015-03-20 09:04:26 -05:00
/* 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.
2009-12-03 16:24:07 -05:00
*/
hProcess = GetCurrentProcess();
if( hProcess ){
HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
if( NULL != hinstLib ){
2015-03-20 09:04:26 -05:00
getProcessTimesAddr =
(GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
2009-12-03 16:24:07 -05:00
if( NULL != getProcessTimesAddr ){
return 1;
}
2016-12-05 14:29:15 -06:00
FreeLibrary(hinstLib);
2009-12-03 16:24:07 -05:00
}
}
}
return 0;
}
/*
** Begin timing an operation
*/
static void beginTimer(void){
if( enableTimer && getProcessTimesAddr ){
FILETIME ftCreation, ftExit;
2015-03-20 09:04:26 -05:00
getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
&ftKernelBegin,&ftUserBegin);
2014-04-04 10:16:20 -05:00
ftWallBegin = timeOfDay();
2009-12-03 16:24:07 -05:00
}
}
/* 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;
2014-04-04 10:16:20 -05:00
sqlite3_int64 ftWallEnd = timeOfDay();
2015-03-20 09:04:26 -05:00
getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
2014-04-04 10:16:20 -05:00
printf("Run Time: real %.3f user %f sys %f\n",
(ftWallEnd - ftWallBegin)*0.001,
2009-12-03 16:24:07 -05:00
timeDiff(&ftUserBegin, &ftUserEnd),
timeDiff(&ftKernelBegin, &ftKernelEnd));
}
}
#define BEGIN_TIMER beginTimer()
#define END_TIMER endTimer()
#define HAS_TIMER hasTimer()
2008-07-30 09:15:43 -04:00
#else
2016-12-05 14:29:15 -06:00
#define BEGIN_TIMER
2008-07-30 09:15:43 -04:00
#define END_TIMER
#define HAS_TIMER 0
#endif
2009-02-20 15:33:35 -05:00
/*
** Used to prevent warnings about unused parameters
*/
#define UNUSED_PARAMETER(x) (void)(x)
2008-07-30 09:15:43 -04:00
/*
** If the following flag is set, then command execution stops
** at an error if we are not interactive.
*/
static int bail_on_error = 0;
/*
** Threat stdin as an interactive input if the following variable
** is true. Otherwise, assume stdin is connected to a file or pipe.
*/
static int stdin_is_interactive = 1;
2016-02-23 09:07:39 -06:00
/*
** On Windows systems we have to know if standard output is a console
** in order to translate UTF-8 into MBCS. The following variable is
** true if translation is required.
*/
static int stdout_is_console = 1;
2008-07-30 09:15:43 -04:00
/*
** The following is the open SQLite database. We make a pointer
** to this database a static variable so that it can be accessed
** by the SIGINT handler to interrupt database processing.
*/
2015-07-10 14:14:29 -05:00
static sqlite3 *globalDb = 0;
2008-07-30 09:15:43 -04:00
/*
** True if an interrupt (Control-C) has been received.
*/
static volatile int seenInterrupt = 0;
/*
** This is the name of our program. It is set in main(), used
** in a number of other places, mostly for error messages.
*/
static char *Argv0;
/*
** Prompt strings. Initialized in main. Settable with
** .prompt main continue
*/
static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
2016-12-05 14:29:15 -06:00
/*
** Render output like fprintf(). Except, if the output is going to the
** console and if this is running on a Windows machine, translate the
** output from UTF-8 into MBCS.
*/
#if defined(_WIN32) || defined(WIN32)
void utf8_printf(FILE *out, const char *zFormat, ...){
va_list ap;
va_start(ap, zFormat);
if( stdout_is_console && (out==stdout || out==stderr) ){
char *z1 = sqlite3_vmprintf(zFormat, ap);
char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
sqlite3_free(z1);
fputs(z2, out);
sqlite3_free(z2);
}else{
vfprintf(out, zFormat, ap);
}
va_end(ap);
}
#elif !defined(utf8_printf)
# define utf8_printf fprintf
#endif
/*
** Render output like fprintf(). This should not be used on anything that
** includes string formatting (e.g. "%s").
*/
#if !defined(raw_printf)
# define raw_printf fprintf
#endif
2008-07-30 09:15:43 -04:00
/*
** Write I/O traces to the following stream.
*/
#ifdef SQLITE_ENABLE_IOTRACE
static FILE *iotrace = 0;
#endif
/*
** This routine works like printf in that its first argument is a
** format string and subsequent arguments are values to be substituted
** in place of % fields. The result of formatting this string
** is written to iotrace.
*/
#ifdef SQLITE_ENABLE_IOTRACE
2015-07-10 14:14:29 -05:00
static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
2008-07-30 09:15:43 -04:00
va_list ap;
char *z;
if( iotrace==0 ) return;
va_start(ap, zFormat);
z = sqlite3_vmprintf(zFormat, ap);
va_end(ap);
2016-12-05 14:29:15 -06:00
utf8_printf(iotrace, "%s", z);
2008-07-30 09:15:43 -04:00
sqlite3_free(z);
}
#endif
/*
** Determines if a string is a number of not.
*/
static int isNumber(const char *z, int *realnum){
if( *z=='-' || *z=='+' ) z++;
2011-12-26 14:52:17 -05:00
if( !IsDigit(*z) ){
2008-07-30 09:15:43 -04:00
return 0;
}
z++;
if( realnum ) *realnum = 0;
2011-12-26 14:52:17 -05:00
while( IsDigit(*z) ){ z++; }
2008-07-30 09:15:43 -04:00
if( *z=='.' ){
z++;
2011-12-26 14:52:17 -05:00
if( !IsDigit(*z) ) return 0;
while( IsDigit(*z) ){ z++; }
2008-07-30 09:15:43 -04:00
if( realnum ) *realnum = 1;
}
if( *z=='e' || *z=='E' ){
z++;
if( *z=='+' || *z=='-' ) z++;
2011-12-26 14:52:17 -05:00
if( !IsDigit(*z) ) return 0;
while( IsDigit(*z) ){ z++; }
2008-07-30 09:15:43 -04:00
if( realnum ) *realnum = 1;
}
return *z==0;
}
/*
2016-12-05 14:29:15 -06:00
** A global char* and an SQL function to access its current value
** from within an SQL statement. This program used to use the
2008-07-30 09:15:43 -04:00
** sqlite_exec_printf() API to substitue a string into an SQL statement.
** The correct way to do this with sqlite3 is to use the bind API, but
** since the shell is built around the callback paradigm it would be a lot
** of work. Instead just use this hack, which is quite harmless.
*/
static const char *zShellStatic = 0;
static void shellstaticFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
assert( 0==argc );
assert( zShellStatic );
2009-02-20 15:33:35 -05:00
UNUSED_PARAMETER(argc);
UNUSED_PARAMETER(argv);
2008-07-30 09:15:43 -04:00
sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
}
2016-02-23 09:07:39 -06:00
/*
** 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);
}
2008-07-30 09:15:43 -04:00
/*
** This routine reads a line of text from FILE in, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text. NULL is returned at end of file, or if malloc()
** fails.
**
2013-08-29 08:11:18 -05:00
** If zLine is not NULL then it is a malloced buffer returned from
** a previous call to this routine that may be reused.
2008-07-30 09:15:43 -04:00
*/
2013-08-29 08:11:18 -05:00
static char *local_getline(char *zLine, FILE *in){
int nLine = zLine==0 ? 0 : 100;
int n = 0;
2008-07-30 09:15:43 -04:00
2011-12-26 14:52:17 -05:00
while( 1 ){
2008-07-30 09:15:43 -04:00
if( n+100>nLine ){
nLine = nLine*2 + 100;
zLine = realloc(zLine, nLine);
if( zLine==0 ) return 0;
}
if( fgets(&zLine[n], nLine - n, in)==0 ){
if( n==0 ){
free(zLine);
return 0;
}
zLine[n] = 0;
break;
}
2013-08-29 08:11:18 -05:00
while( zLine[n] ) n++;
if( n>0 && zLine[n-1]=='\n' ){
2008-07-30 09:15:43 -04:00
n--;
2010-05-18 12:22:17 -04:00
if( n>0 && zLine[n-1]=='\r' ) n--;
2008-07-30 09:15:43 -04:00
zLine[n] = 0;
2011-12-26 14:52:17 -05:00
break;
2008-07-30 09:15:43 -04:00
}
}
2016-02-23 09:07:39 -06:00
#if defined(_WIN32) || defined(WIN32)
2016-12-05 14:29:15 -06:00
/* For interactive input on Windows systems, translate the
2016-02-23 09:07:39 -06:00
** multi-byte characterset characters into UTF-8. */
2016-12-05 14:29:15 -06:00
if( stdin_is_interactive && in==stdin ){
char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
2016-02-23 09:07:39 -06:00
if( zTrans ){
int nTrans = strlen30(zTrans)+1;
if( nTrans>nLine ){
zLine = realloc(zLine, nTrans);
if( zLine==0 ){
sqlite3_free(zTrans);
return 0;
}
}
memcpy(zLine, zTrans, nTrans);
sqlite3_free(zTrans);
}
}
#endif /* defined(_WIN32) || defined(WIN32) */
2008-07-30 09:15:43 -04:00
return zLine;
}
/*
** Retrieve a single line of input text.
**
2013-08-29 08:11:18 -05:00
** If in==0 then read from standard input and prompt before each line.
** If isContinuation is true, then a continuation prompt is appropriate.
** If isContinuation is zero, then the main prompt should be used.
**
** If zPrior is not NULL then it is a buffer from a prior call to this
** routine that can be reused.
**
** The result is stored in space obtained from malloc() and must either
** be freed by the caller or else passed back into this routine via the
** zPrior argument for reuse.
2008-07-30 09:15:43 -04:00
*/
2013-08-29 08:11:18 -05:00
static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
2008-07-30 09:15:43 -04:00
char *zPrompt;
char *zResult;
if( in!=0 ){
2013-08-29 08:11:18 -05:00
zResult = local_getline(zPrior, in);
2008-07-30 09:15:43 -04:00
}else{
2013-08-29 08:11:18 -05:00
zPrompt = isContinuation ? continuePrompt : mainPrompt;
2015-03-20 09:04:26 -05:00
#if SHELL_USE_LOCAL_GETLINE
2013-08-29 08:11:18 -05:00
printf("%s", zPrompt);
fflush(stdout);
zResult = local_getline(zPrior, stdin);
2015-03-20 09:04:26 -05:00
#else
free(zPrior);
zResult = shell_readline(zPrompt);
if( zResult && *zResult ) shell_add_history(zResult);
2008-07-30 09:15:43 -04:00
#endif
2013-08-29 08:11:18 -05:00
}
2008-07-30 09:15:43 -04:00
return zResult;
}
2016-12-05 14:29:15 -06:00
#if defined(SQLITE_ENABLE_SESSION)
2016-02-23 09:07:39 -06:00
/*
2016-12-05 14:29:15 -06:00
** State information for a single open session
2016-02-23 09:07:39 -06:00
*/
2016-12-05 14:29:15 -06:00
typedef struct OpenSession OpenSession;
struct OpenSession {
char *zName; /* Symbolic name for this session */
int nFilter; /* Number of xFilter rejection GLOB patterns */
char **azFilter; /* Array of xFilter rejection GLOB patterns */
sqlite3_session *p; /* The open session */
};
2016-02-23 09:07:39 -06:00
#endif
/*
2016-12-05 14:29:15 -06:00
** Shell output mode information from before ".explain on",
2015-03-20 09:04:26 -05:00
** saved so that it can be restored by ".explain off"
*/
typedef struct SavedModeInfo SavedModeInfo;
struct SavedModeInfo {
int valid; /* Is there legit data in here? */
int mode; /* Mode prior to ".explain on" */
int showHeader; /* The ".header" setting prior to ".explain on" */
int colWidth[100]; /* Column widths prior to ".explain on" */
2008-07-30 09:15:43 -04:00
};
/*
2015-03-20 09:04:26 -05:00
** State information about the database connection is contained in an
** instance of the following structure.
2008-07-30 09:15:43 -04:00
*/
2015-03-20 09:04:26 -05:00
typedef struct ShellState ShellState;
struct ShellState {
2009-12-03 16:24:07 -05:00
sqlite3 *db; /* The database */
2008-07-30 09:15:43 -04:00
int echoOn; /* True to echo input commands */
2016-02-23 09:07:39 -06:00
int autoExplain; /* Automatically turn on .explain mode */
2014-09-30 08:40:45 -05:00
int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
2010-08-28 08:35:57 -04:00
int statsOn; /* True to display memory stats before each finalize */
2015-03-20 09:04:26 -05:00
int scanstatsOn; /* True to display scan stats before each finalize */
2016-02-23 09:07:39 -06:00
int countChanges; /* True to display change counts */
2015-07-10 14:14:29 -05:00
int backslashOn; /* Resolve C-style \x escapes in SQL input text */
2014-09-30 08:40:45 -05:00
int outCount; /* Revert to stdout when reaching zero */
2008-07-30 09:15:43 -04:00
int cnt; /* Number of records displayed so far */
FILE *out; /* Write results here */
2012-05-15 19:05:34 -04:00
FILE *traceOut; /* Output for sqlite3_trace() */
2011-12-26 14:52:17 -05:00
int nErr; /* Number of errors seen */
2008-07-30 09:15:43 -04:00
int mode; /* An output mode setting */
2016-02-23 09:07:39 -06:00
int cMode; /* temporary output mode for the current query */
int normalMode; /* Output mode before ".explain on" */
2008-07-30 09:15:43 -04:00
int writableSchema; /* True if PRAGMA writable_schema=ON */
int showHeader; /* True to show column names in List or Column mode */
2016-12-05 14:29:15 -06:00
int nCheck; /* Number of ".check" commands run */
2015-03-20 09:04:26 -05:00
unsigned shellFlgs; /* Various flags */
2008-07-30 09:15:43 -04:00
char *zDestTable; /* Name of destination table when MODE_Insert */
2016-12-05 14:29:15 -06:00
char zTestcase[30]; /* Name of current test case */
2015-03-20 09:04:26 -05:00
char colSeparator[20]; /* Column separator character for several modes */
char rowSeparator[20]; /* Row separator character for MODE_Ascii */
2008-07-30 09:15:43 -04:00
int colWidth[100]; /* Requested width of each column when in column mode*/
int actualWidth[100]; /* Actual width of each column */
2015-03-20 09:04:26 -05:00
char nullValue[20]; /* The text to print when a NULL comes back from
2008-07-30 09:15:43 -04:00
** the database */
char outfile[FILENAME_MAX]; /* Filename for *out */
const char *zDbFilename; /* name of the database file */
2014-04-04 10:16:20 -05:00
char *zFreeOnClose; /* Filename to free when closing */
2011-05-05 22:37:34 -04:00
const char *zVfs; /* Name of VFS to use */
2009-12-03 16:24:07 -05:00
sqlite3_stmt *pStmt; /* Current statement if any. */
2010-05-18 12:22:17 -04:00
FILE *pLog; /* Write log output here */
2014-04-04 10:16:20 -05:00
int *aiIndent; /* Array of indents used in MODE_Explain */
int nIndent; /* Size of array aiIndent[] */
int iIndent; /* Index of current op in aiIndent[] */
2016-12-05 14:29:15 -06:00
#if defined(SQLITE_ENABLE_SESSION)
int nSession; /* Number of active sessions */
OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
#endif
2008-07-30 09:15:43 -04:00
};
2015-03-20 09:04:26 -05:00
/*
** These are the allowed shellFlgs values
*/
#define SHFLG_Scratch 0x00001 /* The --scratch option is used */
#define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */
#define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */
2008-07-30 09:15:43 -04:00
/*
** These are the allowed modes.
*/
#define MODE_Line 0 /* One column per line. Blank line between records */
#define MODE_Column 1 /* One record per line in neat columns */
#define MODE_List 2 /* One record per line with a separator */
#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
#define MODE_Html 4 /* Generate an XHTML table */
#define MODE_Insert 5 /* Generate SQL "insert" statements */
#define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */
#define MODE_Csv 7 /* Quote strings, numbers are plain */
#define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */
2015-03-20 09:04:26 -05:00
#define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */
2016-12-05 14:29:15 -06:00
#define MODE_Pretty 10 /* Pretty-print schemas */
2008-07-30 09:15:43 -04:00
static const char *modeDescr[] = {
"line",
"column",
"list",
"semi",
"html",
"insert",
"tcl",
"csv",
"explain",
2015-03-20 09:04:26 -05:00
"ascii",
2016-12-05 14:29:15 -06:00
"prettyprint",
2008-07-30 09:15:43 -04:00
};
2015-03-20 09:04:26 -05:00
/*
** These are the column/row/line separators used by the various
** import/export modes.
*/
#define SEP_Column "|"
#define SEP_Row "\n"
#define SEP_Tab "\t"
#define SEP_Space " "
#define SEP_Comma ","
#define SEP_CrLf "\r\n"
#define SEP_Unit "\x1F"
#define SEP_Record "\x1E"
2008-07-30 09:15:43 -04:00
/*
** Number of elements in an array
*/
2009-02-20 15:33:35 -05:00
#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
2010-05-18 12:22:17 -04:00
/*
** A callback for the sqlite3_log() interface.
*/
static void shellLog(void *pArg, int iErrCode, const char *zMsg){
2015-03-20 09:04:26 -05:00
ShellState *p = (ShellState*)pArg;
2010-05-18 12:22:17 -04:00
if( p->pLog==0 ) return;
2016-02-23 09:07:39 -06:00
utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
2010-05-18 12:22:17 -04:00
fflush(p->pLog);
}
2009-12-03 16:24:07 -05:00
/*
** 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;
2016-02-23 09:07:39 -06:00
raw_printf(out,"X'");
for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
raw_printf(out,"'");
2009-12-03 16:24:07 -05:00
}
2008-07-30 09:15:43 -04:00
/*
** Output the given string as a quoted string using SQL quoting conventions.
*/
static void output_quoted_string(FILE *out, const char *z){
int i;
int nSingle = 0;
2016-12-05 14:29:15 -06:00
setBinaryMode(out, 1);
2008-07-30 09:15:43 -04:00
for(i=0; z[i]; i++){
if( z[i]=='\'' ) nSingle++;
}
if( nSingle==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(out,"'%s'",z);
2008-07-30 09:15:43 -04:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(out,"'");
2008-07-30 09:15:43 -04:00
while( *z ){
for(i=0; z[i] && z[i]!='\''; i++){}
if( i==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(out,"''");
2008-07-30 09:15:43 -04:00
z++;
}else if( z[i]=='\'' ){
2016-02-23 09:07:39 -06:00
utf8_printf(out,"%.*s''",i,z);
2008-07-30 09:15:43 -04:00
z += i+1;
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(out,"%s",z);
2008-07-30 09:15:43 -04:00
break;
}
}
2016-02-23 09:07:39 -06:00
raw_printf(out,"'");
2008-07-30 09:15:43 -04:00
}
2016-12-05 14:29:15 -06:00
setTextMode(out, 1);
2008-07-30 09:15:43 -04:00
}
/*
** Output the given string as a quoted according to C or TCL quoting rules.
*/
static void output_c_string(FILE *out, const char *z){
unsigned int c;
fputc('"', out);
while( (c = *(z++))!=0 ){
if( c=='\\' ){
fputc(c, out);
fputc(c, out);
2013-01-15 16:38:05 -06:00
}else if( c=='"' ){
fputc('\\', out);
fputc('"', out);
2008-07-30 09:15:43 -04:00
}else if( c=='\t' ){
fputc('\\', out);
fputc('t', out);
}else if( c=='\n' ){
fputc('\\', out);
fputc('n', out);
}else if( c=='\r' ){
fputc('\\', out);
fputc('r', out);
2014-04-04 10:16:20 -05:00
}else if( !isprint(c&0xff) ){
2016-02-23 09:07:39 -06:00
raw_printf(out, "\\%03o", c&0xff);
2008-07-30 09:15:43 -04:00
}else{
fputc(c, out);
}
}
fputc('"', out);
}
/*
** Output the given string with characters that are special to
** HTML escaped.
*/
static void output_html_string(FILE *out, const char *z){
int i;
2014-04-04 10:16:20 -05:00
if( z==0 ) z = "";
2008-07-30 09:15:43 -04:00
while( *z ){
2016-12-05 14:29:15 -06:00
for(i=0; z[i]
&& z[i]!='<'
&& z[i]!='&'
&& z[i]!='>'
&& z[i]!='\"'
2009-12-03 16:24:07 -05:00
&& z[i]!='\'';
i++){}
2008-07-30 09:15:43 -04:00
if( i>0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(out,"%.*s",i,z);
2008-07-30 09:15:43 -04:00
}
if( z[i]=='<' ){
2016-02-23 09:07:39 -06:00
raw_printf(out,"&lt;");
2008-07-30 09:15:43 -04:00
}else if( z[i]=='&' ){
2016-02-23 09:07:39 -06:00
raw_printf(out,"&amp;");
2009-12-03 16:24:07 -05:00
}else if( z[i]=='>' ){
2016-02-23 09:07:39 -06:00
raw_printf(out,"&gt;");
2009-12-03 16:24:07 -05:00
}else if( z[i]=='\"' ){
2016-02-23 09:07:39 -06:00
raw_printf(out,"&quot;");
2009-12-03 16:24:07 -05:00
}else if( z[i]=='\'' ){
2016-02-23 09:07:39 -06:00
raw_printf(out,"&#39;");
2008-07-30 09:15:43 -04:00
}else{
break;
}
z += i + 1;
}
}
/*
** If a field contains any character identified by a 1 in the following
** array, then the string must be quoted for CSV.
*/
static const char needCsvQuote[] = {
2016-12-05 14:29:15 -06:00
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2008-07-30 09:15:43 -04:00
};
/*
2015-03-20 09:04:26 -05:00
** Output a single term of CSV. Actually, p->colSeparator is used for
** the separator, which may or may not be a comma. p->nullValue is
2014-09-30 08:40:45 -05:00
** the null value. Strings are quoted if necessary. The separator
** is only issued if bSep is true.
2008-07-30 09:15:43 -04:00
*/
2015-03-20 09:04:26 -05:00
static void output_csv(ShellState *p, const char *z, int bSep){
2008-07-30 09:15:43 -04:00
FILE *out = p->out;
if( z==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(out,"%s",p->nullValue);
2008-07-30 09:15:43 -04:00
}else{
int i;
2015-03-20 09:04:26 -05:00
int nSep = strlen30(p->colSeparator);
2008-07-30 09:15:43 -04:00
for(i=0; z[i]; i++){
2016-12-05 14:29:15 -06:00
if( needCsvQuote[((unsigned char*)z)[i]]
|| (z[i]==p->colSeparator[0] &&
2015-03-20 09:04:26 -05:00
(nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
2008-07-30 09:15:43 -04:00
i = 0;
break;
}
}
if( i==0 ){
putc('"', out);
for(i=0; z[i]; i++){
if( z[i]=='"' ) putc('"', out);
putc(z[i], out);
}
putc('"', out);
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(out, "%s", z);
2008-07-30 09:15:43 -04:00
}
}
if( bSep ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->colSeparator);
2008-07-30 09:15:43 -04:00
}
}
#ifdef SIGINT
/*
** This routine runs when the user presses Ctrl-C
*/
static void interrupt_handler(int NotUsed){
2009-02-20 15:33:35 -05:00
UNUSED_PARAMETER(NotUsed);
2014-09-30 08:40:45 -05:00
seenInterrupt++;
if( seenInterrupt>2 ) exit(1);
2015-07-10 14:14:29 -05:00
if( globalDb ) sqlite3_interrupt(globalDb);
2008-07-30 09:15:43 -04:00
}
#endif
2016-12-05 14:29:15 -06:00
#ifndef SQLITE_OMIT_AUTHORIZATION
/*
** When the ".auth ON" is set, the following authorizer callback is
** invoked. It always returns SQLITE_OK.
*/
static int shellAuth(
void *pClientData,
int op,
const char *zA1,
const char *zA2,
const char *zA3,
const char *zA4
){
ShellState *p = (ShellState*)pClientData;
static const char *azAction[] = { 0,
"CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
"CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
"CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
"DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
"DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
"DROP_TRIGGER", "DROP_VIEW", "INSERT",
"PRAGMA", "READ", "SELECT",
"TRANSACTION", "UPDATE", "ATTACH",
"DETACH", "ALTER_TABLE", "REINDEX",
"ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
"FUNCTION", "SAVEPOINT", "RECURSIVE"
};
int i;
const char *az[4];
az[0] = zA1;
az[1] = zA2;
az[2] = zA3;
az[3] = zA4;
utf8_printf(p->out, "authorizer: %s", azAction[op]);
for(i=0; i<4; i++){
raw_printf(p->out, " ");
if( az[i] ){
output_c_string(p->out, az[i]);
}else{
raw_printf(p->out, "NULL");
}
}
raw_printf(p->out, "\n");
return SQLITE_OK;
}
#endif
2008-07-30 09:15:43 -04:00
/*
2009-12-03 16:24:07 -05:00
** This is the callback routine that the shell
2008-07-30 09:15:43 -04:00
** invokes for each row of a query result.
*/
2015-03-20 09:04:26 -05:00
static int shell_callback(
void *pArg,
int nArg, /* Number of result columns */
char **azArg, /* Text of each result column */
char **azCol, /* Column names */
int *aiType /* Column types */
){
2008-07-30 09:15:43 -04:00
int i;
2015-03-20 09:04:26 -05:00
ShellState *p = (ShellState*)pArg;
2009-12-03 16:24:07 -05:00
2016-02-23 09:07:39 -06:00
switch( p->cMode ){
2008-07-30 09:15:43 -04:00
case MODE_Line: {
int w = 5;
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
2009-02-20 15:33:35 -05:00
int len = strlen30(azCol[i] ? azCol[i] : "");
2008-07-30 09:15:43 -04:00
if( len>w ) w = len;
}
2016-02-23 09:07:39 -06:00
if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
2008-07-30 09:15:43 -04:00
for(i=0; i<nArg; i++){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
2015-03-20 09:04:26 -05:00
azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
2008-07-30 09:15:43 -04:00
}
break;
}
case MODE_Explain:
case MODE_Column: {
2016-02-23 09:07:39 -06:00
static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
const int *colWidth;
int showHdr;
char *rowSep;
if( p->cMode==MODE_Column ){
colWidth = p->colWidth;
showHdr = p->showHeader;
rowSep = p->rowSeparator;
}else{
colWidth = aExplainWidths;
showHdr = 1;
rowSep = SEP_Row;
}
2008-07-30 09:15:43 -04:00
if( p->cnt++==0 ){
for(i=0; i<nArg; i++){
int w, n;
if( i<ArraySize(p->colWidth) ){
2016-02-23 09:07:39 -06:00
w = colWidth[i];
2008-07-30 09:15:43 -04:00
}else{
w = 0;
}
2013-01-15 16:38:05 -06:00
if( w==0 ){
2009-02-20 15:33:35 -05:00
w = strlen30(azCol[i] ? azCol[i] : "");
2008-07-30 09:15:43 -04:00
if( w<10 ) w = 10;
2015-03-20 09:04:26 -05:00
n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
2008-07-30 09:15:43 -04:00
if( w<n ) w = n;
}
if( i<ArraySize(p->actualWidth) ){
p->actualWidth[i] = w;
}
2016-02-23 09:07:39 -06:00
if( showHdr ){
2013-01-15 16:38:05 -06:00
if( w<0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
i==nArg-1 ? rowSep : " ");
2013-01-15 16:38:05 -06:00
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
i==nArg-1 ? rowSep : " ");
2013-01-15 16:38:05 -06:00
}
2008-07-30 09:15:43 -04:00
}
}
2016-02-23 09:07:39 -06:00
if( showHdr ){
2008-07-30 09:15:43 -04:00
for(i=0; i<nArg; i++){
int w;
if( i<ArraySize(p->actualWidth) ){
w = p->actualWidth[i];
2013-01-15 16:38:05 -06:00
if( w<0 ) w = -w;
2008-07-30 09:15:43 -04:00
}else{
w = 10;
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%-*.*s%s",w,w,
"----------------------------------------------------------"
2008-07-30 09:15:43 -04:00
"----------------------------------------------------------",
2016-02-23 09:07:39 -06:00
i==nArg-1 ? rowSep : " ");
2008-07-30 09:15:43 -04:00
}
}
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
int w;
if( i<ArraySize(p->actualWidth) ){
w = p->actualWidth[i];
}else{
w = 10;
}
2016-02-23 09:07:39 -06:00
if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
2009-02-20 15:33:35 -05:00
w = strlen30(azArg[i]);
2008-07-30 09:15:43 -04:00
}
2014-04-04 10:16:20 -05:00
if( i==1 && p->aiIndent && p->pStmt ){
if( p->iIndent<p->nIndent ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
2014-04-04 10:16:20 -05:00
}
p->iIndent++;
}
2013-01-15 16:38:05 -06:00
if( w<0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%*.*s%s",-w,-w,
2015-03-20 09:04:26 -05:00
azArg[i] ? azArg[i] : p->nullValue,
2016-02-23 09:07:39 -06:00
i==nArg-1 ? rowSep : " ");
2013-01-15 16:38:05 -06:00
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%-*.*s%s",w,w,
2015-03-20 09:04:26 -05:00
azArg[i] ? azArg[i] : p->nullValue,
2016-02-23 09:07:39 -06:00
i==nArg-1 ? rowSep : " ");
2013-01-15 16:38:05 -06:00
}
2008-07-30 09:15:43 -04:00
}
break;
}
2016-12-05 14:29:15 -06:00
case MODE_Semi: { /* .schema and .fullschema output */
utf8_printf(p->out, "%s;\n", azArg[0]);
break;
}
case MODE_Pretty: { /* .schema and .fullschema with --indent */
char *z;
int j;
int nParen = 0;
char cEnd = 0;
char c;
int nLine = 0;
assert( nArg==1 );
if( azArg[0]==0 ) break;
if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
|| sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
){
utf8_printf(p->out, "%s;\n", azArg[0]);
break;
}
z = sqlite3_mprintf("%s", azArg[0]);
j = 0;
for(i=0; IsSpace(z[i]); i++){}
for(; (c = z[i])!=0; i++){
if( IsSpace(c) ){
if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
}else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
j--;
}
z[j++] = c;
}
while( j>0 && IsSpace(z[j-1]) ){ j--; }
z[j] = 0;
if( strlen30(z)>=79 ){
for(i=j=0; (c = z[i])!=0; i++){
if( c==cEnd ){
cEnd = 0;
}else if( c=='"' || c=='\'' || c=='`' ){
cEnd = c;
}else if( c=='[' ){
cEnd = ']';
}else if( c=='(' ){
nParen++;
}else if( c==')' ){
nParen--;
if( nLine>0 && nParen==0 && j>0 ){
utf8_printf(p->out, "%.*s\n", j, z);
j = 0;
}
}
z[j++] = c;
if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
if( c=='\n' ) j--;
utf8_printf(p->out, "%.*s\n ", j, z);
j = 0;
nLine++;
while( IsSpace(z[i+1]) ){ i++; }
}
}
z[j] = 0;
}
utf8_printf(p->out, "%s;\n", z);
sqlite3_free(z);
break;
}
2008-07-30 09:15:43 -04:00
case MODE_List: {
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%s%s",azCol[i],
2015-03-20 09:04:26 -05:00
i==nArg-1 ? p->rowSeparator : p->colSeparator);
2008-07-30 09:15:43 -04:00
}
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
char *z = azArg[i];
2015-03-20 09:04:26 -05:00
if( z==0 ) z = p->nullValue;
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", z);
2008-07-30 09:15:43 -04:00
if( i<nArg-1 ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->colSeparator);
2008-07-30 09:15:43 -04:00
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2008-07-30 09:15:43 -04:00
}
}
break;
}
case MODE_Html: {
if( p->cnt++==0 && p->showHeader ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"<TR>");
2008-07-30 09:15:43 -04:00
for(i=0; i<nArg; i++){
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"<TH>");
2009-12-03 16:24:07 -05:00
output_html_string(p->out, azCol[i]);
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"</TH>\n");
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"</TR>\n");
2008-07-30 09:15:43 -04:00
}
if( azArg==0 ) break;
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"<TR>");
2008-07-30 09:15:43 -04:00
for(i=0; i<nArg; i++){
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"<TD>");
2015-03-20 09:04:26 -05:00
output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"</TD>\n");
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"</TR>\n");
2008-07-30 09:15:43 -04:00
break;
}
case MODE_Tcl: {
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
output_c_string(p->out,azCol[i] ? azCol[i] : "");
2016-02-23 09:07:39 -06:00
if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2008-07-30 09:15:43 -04:00
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
2015-03-20 09:04:26 -05:00
output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
2016-02-23 09:07:39 -06:00
if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2008-07-30 09:15:43 -04:00
break;
}
case MODE_Csv: {
2016-12-05 14:29:15 -06:00
setBinaryMode(p->out, 1);
2008-07-30 09:15:43 -04:00
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2008-07-30 09:15:43 -04:00
}
2015-03-20 09:04:26 -05:00
if( nArg>0 ){
2014-09-30 08:40:45 -05:00
for(i=0; i<nArg; i++){
output_csv(p, azArg[i], i<nArg-1);
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2008-07-30 09:15:43 -04:00
}
2016-12-05 14:29:15 -06:00
setTextMode(p->out, 1);
2008-07-30 09:15:43 -04:00
break;
}
case MODE_Insert: {
2009-12-03 16:24:07 -05:00
p->cnt++;
2008-07-30 09:15:43 -04:00
if( azArg==0 ) break;
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2015-07-10 14:14:29 -05:00
if( p->showHeader ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out,"(");
2015-07-10 14:14:29 -05:00
for(i=0; i<nArg; i++){
char *zSep = i>0 ? ",": "";
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s%s", zSep, azCol[i]);
2015-07-10 14:14:29 -05:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out,")");
2015-07-10 14:14:29 -05:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out," VALUES(");
2008-07-30 09:15:43 -04:00
for(i=0; i<nArg; i++){
char *zSep = i>0 ? ",": "";
2009-12-03 16:24:07 -05:00
if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%sNULL",zSep);
2009-12-03 16:24:07 -05:00
}else if( aiType && aiType[i]==SQLITE_TEXT ){
2016-02-23 09:07:39 -06:00
if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2009-12-03 16:24:07 -05:00
output_quoted_string(p->out, azArg[i]);
2014-09-30 08:40:45 -05:00
}else if( aiType && (aiType[i]==SQLITE_INTEGER
|| aiType[i]==SQLITE_FLOAT) ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%s%s",zSep, azArg[i]);
2009-12-03 16:24:07 -05:00
}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);
2016-02-23 09:07:39 -06:00
if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2009-12-03 16:24:07 -05:00
output_hex_blob(p->out, pBlob, nBlob);
2008-07-30 09:15:43 -04:00
}else if( isNumber(azArg[i], 0) ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%s%s",zSep, azArg[i]);
2008-07-30 09:15:43 -04:00
}else{
2016-02-23 09:07:39 -06:00
if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
2008-07-30 09:15:43 -04:00
output_quoted_string(p->out, azArg[i]);
}
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out,");\n");
2008-07-30 09:15:43 -04:00
break;
}
2015-03-20 09:04:26 -05:00
case MODE_Ascii: {
if( p->cnt++==0 && p->showHeader ){
for(i=0; i<nArg; i++){
2016-02-23 09:07:39 -06:00
if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
2015-03-20 09:04:26 -05:00
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2015-03-20 09:04:26 -05:00
}
if( azArg==0 ) break;
for(i=0; i<nArg; i++){
2016-02-23 09:07:39 -06:00
if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
2015-03-20 09:04:26 -05:00
}
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", p->rowSeparator);
2015-03-20 09:04:26 -05:00
break;
}
2008-07-30 09:15:43 -04:00
}
return 0;
}
2009-12-03 16:24:07 -05:00
/*
** 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);
}
2008-07-30 09:15:43 -04:00
/*
2015-03-20 09:04:26 -05:00
** Set the destination table field of the ShellState structure to
2008-07-30 09:15:43 -04:00
** the name of the table given. Escape any quote characters in the
** table name.
*/
2015-03-20 09:04:26 -05:00
static void set_table_name(ShellState *p, const char *zName){
2008-07-30 09:15:43 -04:00
int i, n;
int needQuote;
char *z;
if( p->zDestTable ){
free(p->zDestTable);
p->zDestTable = 0;
}
if( zName==0 ) return;
needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
for(i=n=0; zName[i]; i++, n++){
if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
needQuote = 1;
if( zName[i]=='\'' ) n++;
}
}
if( needQuote ) n += 2;
z = p->zDestTable = malloc( n+1 );
if( z==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr,"Error: out of memory\n");
2008-07-30 09:15:43 -04:00
exit(1);
}
n = 0;
if( needQuote ) z[n++] = '\'';
for(i=0; zName[i]; i++){
z[n++] = zName[i];
if( zName[i]=='\'' ) z[n++] = '\'';
}
if( needQuote ) z[n++] = '\'';
z[n] = 0;
}
/* zIn is either a pointer to a NULL-terminated string in memory obtained
** from malloc(), or a NULL pointer. The string pointed to by zAppend is
** added to zIn, and the result returned in memory obtained from malloc().
** zIn, if it was not NULL, is freed.
**
2016-12-05 14:29:15 -06:00
** If the third argument, quote, is not '\0', then it is used as a
2008-07-30 09:15:43 -04:00
** quote character for zAppend.
*/
static char *appendText(char *zIn, char const *zAppend, char quote){
int len;
int i;
2009-02-20 15:33:35 -05:00
int nAppend = strlen30(zAppend);
int nIn = (zIn?strlen30(zIn):0);
2008-07-30 09:15:43 -04:00
len = nAppend+nIn+1;
if( quote ){
len += 2;
for(i=0; i<nAppend; i++){
if( zAppend[i]==quote ) len++;
}
}
zIn = (char *)realloc(zIn, len);
if( !zIn ){
return 0;
}
if( quote ){
char *zCsr = &zIn[nIn];
*zCsr++ = quote;
for(i=0; i<nAppend; i++){
*zCsr++ = zAppend[i];
if( zAppend[i]==quote ) *zCsr++ = quote;
}
*zCsr++ = quote;
*zCsr++ = '\0';
assert( (zCsr-zIn)==len );
}else{
memcpy(&zIn[nIn], zAppend, nAppend);
zIn[len-1] = '\0';
}
return zIn;
}
/*
2012-05-15 19:05:34 -04:00
** Execute a query statement that will generate SQL output. Print
** the result columns, comma-separated, on a line and then add a
** semicolon terminator to the end of that line.
2008-07-30 09:15:43 -04:00
**
2012-05-15 19:05:34 -04:00
** If the number of columns is 1 and that column contains text "--"
2016-12-05 14:29:15 -06:00
** then write the semicolon on a separate line. That way, if a
2012-05-15 19:05:34 -04:00
** "--" comment occurs at the end of the statement, the comment
** won't consume the semicolon terminator.
2008-07-30 09:15:43 -04:00
*/
2009-08-11 16:01:51 -04:00
static int run_table_dump_query(
2015-03-20 09:04:26 -05:00
ShellState *p, /* Query context */
2011-12-26 14:52:17 -05:00
const char *zSelect, /* SELECT statement to extract content */
const char *zFirstRow /* Print before first row, if not NULL */
2009-08-11 16:01:51 -04:00
){
2008-07-30 09:15:43 -04:00
sqlite3_stmt *pSelect;
int rc;
2012-05-15 19:05:34 -04:00
int nResult;
int i;
const char *z;
2014-04-04 10:16:20 -05:00
rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
2008-07-30 09:15:43 -04:00
if( rc!=SQLITE_OK || !pSelect ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
sqlite3_errmsg(p->db));
2014-04-04 10:16:20 -05:00
if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2008-07-30 09:15:43 -04:00
return rc;
}
rc = sqlite3_step(pSelect);
2012-05-15 19:05:34 -04:00
nResult = sqlite3_column_count(pSelect);
2008-07-30 09:15:43 -04:00
while( rc==SQLITE_ROW ){
2009-08-11 16:01:51 -04:00
if( zFirstRow ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", zFirstRow);
2009-08-11 16:01:51 -04:00
zFirstRow = 0;
}
2012-05-15 19:05:34 -04:00
z = (const char*)sqlite3_column_text(pSelect, 0);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", z);
2016-12-05 14:29:15 -06:00
for(i=1; i<nResult; i++){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
2012-05-15 19:05:34 -04:00
}
if( z==0 ) z = "";
while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
if( z[0] ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n;\n");
2012-05-15 19:05:34 -04:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(p->out, ";\n");
2016-12-05 14:29:15 -06:00
}
2008-07-30 09:15:43 -04:00
rc = sqlite3_step(pSelect);
}
2011-12-26 14:52:17 -05:00
rc = sqlite3_finalize(pSelect);
if( rc!=SQLITE_OK ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
sqlite3_errmsg(p->db));
2014-04-04 10:16:20 -05:00
if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
2011-12-26 14:52:17 -05:00
}
return rc;
2008-07-30 09:15:43 -04:00
}
2009-12-03 16:24:07 -05:00
/*
** 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));
2015-07-10 14:14:29 -05:00
char *zErrMsg = sqlite3_malloc64(nErrMsg);
2009-12-03 16:24:07 -05:00
if( zErrMsg ){
memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
}
return zErrMsg;
}
2016-12-05 14:29:15 -06:00
#ifdef __linux__
/*
** Attempt to display I/O stats on Linux using /proc/PID/io
*/
static void displayLinuxIoStats(FILE *out){
FILE *in;
char z[200];
sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
in = fopen(z, "rb");
if( in==0 ) return;
while( fgets(z, sizeof(z), in)!=0 ){
static const struct {
const char *zPattern;
const char *zDesc;
} aTrans[] = {
{ "rchar: ", "Bytes received by read():" },
{ "wchar: ", "Bytes sent to write():" },
{ "syscr: ", "Read() system calls:" },
{ "syscw: ", "Write() system calls:" },
{ "read_bytes: ", "Bytes read from storage:" },
{ "write_bytes: ", "Bytes written to storage:" },
{ "cancelled_write_bytes: ", "Cancelled write bytes:" },
};
int i;
for(i=0; i<ArraySize(aTrans); i++){
int n = (int)strlen(aTrans[i].zPattern);
if( strncmp(aTrans[i].zPattern, z, n)==0 ){
utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
break;
}
}
}
fclose(in);
}
#endif
2010-08-28 08:35:57 -04:00
/*
** Display memory stats.
*/
static int display_stats(
sqlite3 *db, /* Database to query */
2015-03-20 09:04:26 -05:00
ShellState *pArg, /* Pointer to ShellState */
2010-08-28 08:35:57 -04:00
int bReset /* True to reset the stats */
){
int iCur;
int iHiwtr;
if( pArg && pArg->out ){
2016-12-05 14:29:15 -06:00
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,
2015-03-20 09:04:26 -05:00
"Memory Used: %d (max %d) bytes\n",
iCur, iHiwtr);
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n",
2015-03-20 09:04:26 -05:00
iCur, iHiwtr);
if( pArg->shellFlgs & SHFLG_Pagecache ){
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,
2015-03-20 09:04:26 -05:00
"Number of Pcache Pages Used: %d (max %d) pages\n",
iCur, iHiwtr);
}
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,
2015-03-20 09:04:26 -05:00
"Number of Pcache Overflow Bytes: %d (max %d) bytes\n",
iCur, iHiwtr);
if( pArg->shellFlgs & SHFLG_Scratch ){
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,
"Number of Scratch Allocations Used: %d (max %d)\n",
2015-03-20 09:04:26 -05:00
iCur, iHiwtr);
}
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,
2015-03-20 09:04:26 -05:00
"Number of Scratch Overflow Bytes: %d (max %d) bytes\n",
iCur, iHiwtr);
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Largest Allocation: %d bytes\n",
2015-03-20 09:04:26 -05:00
iHiwtr);
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Largest Pcache Allocation: %d bytes\n",
2015-03-20 09:04:26 -05:00
iHiwtr);
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Largest Scratch Allocation: %d bytes\n",
2015-03-20 09:04:26 -05:00
iHiwtr);
2010-08-28 08:35:57 -04:00
#ifdef YYTRACKMAXSTACKDEPTH
iHiwtr = iCur = -1;
sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Deepest Parser Stack: %d (max %d)\n",
2015-03-20 09:04:26 -05:00
iCur, iHiwtr);
2010-08-28 08:35:57 -04:00
#endif
}
if( pArg && pArg->out && db ){
2015-03-20 09:04:26 -05:00
if( pArg->shellFlgs & SHFLG_Lookaside ){
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
&iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,
"Lookaside Slots Used: %d (max %d)\n",
2015-03-20 09:04:26 -05:00
iCur, iHiwtr);
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
&iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
iHiwtr);
2015-03-20 09:04:26 -05:00
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
&iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
iHiwtr);
2015-03-20 09:04:26 -05:00
sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
&iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
iHiwtr);
2015-03-20 09:04:26 -05:00
}
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
iCur);
2015-03-20 09:04:26 -05:00
iHiwtr = iCur = -1;
2011-12-26 14:52:17 -05:00
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
2011-12-26 14:52:17 -05:00
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
2016-12-05 14:29:15 -06:00
raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
2012-05-15 19:05:34 -04:00
sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
2016-12-05 14:29:15 -06:00
raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
2012-05-15 19:05:34 -04:00
iHiwtr = iCur = -1;
2010-08-28 08:35:57 -04:00
sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
2016-12-05 14:29:15 -06:00
iCur);
2010-08-28 08:35:57 -04:00
iHiwtr = iCur = -1;
sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
2016-12-05 14:29:15 -06:00
iCur);
2010-08-28 08:35:57 -04:00
}
if( pArg && pArg->out && db && pArg->pStmt ){
2015-03-20 09:04:26 -05:00
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
2010-08-28 08:35:57 -04:00
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
2015-03-20 09:04:26 -05:00
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
2013-08-29 08:11:18 -05:00
iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
2010-08-28 08:35:57 -04:00
}
2016-12-05 14:29:15 -06:00
#ifdef __linux__
displayLinuxIoStats(pArg->out);
#endif
2016-02-23 09:07:39 -06:00
/* Do not remove this machine readable comment: extra-stats-output-here */
2010-08-28 08:35:57 -04:00
return 0;
}
2015-03-20 09:04:26 -05:00
/*
** Display scan stats.
*/
static void display_scanstats(
sqlite3 *db, /* Database to query */
ShellState *pArg /* Pointer to ShellState */
){
2016-02-23 09:07:39 -06:00
#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
UNUSED_PARAMETER(db);
UNUSED_PARAMETER(pArg);
#else
2015-03-20 09:04:26 -05:00
int i, k, n, mx;
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "-------- scanstats --------\n");
2015-03-20 09:04:26 -05:00
mx = 0;
for(k=0; k<=mx; k++){
double rEstLoop = 1.0;
for(i=n=0; 1; i++){
sqlite3_stmt *p = pArg->pStmt;
sqlite3_int64 nLoop, nVisit;
double rEst;
int iSid;
const char *zExplain;
if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
break;
}
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
if( iSid>mx ) mx = iSid;
if( iSid!=k ) continue;
if( n==0 ){
rEstLoop = (double)nLoop;
2016-02-23 09:07:39 -06:00
if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
2015-03-20 09:04:26 -05:00
}
n++;
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
2016-02-23 09:07:39 -06:00
utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
2015-03-20 09:04:26 -05:00
rEstLoop *= rEst;
2016-12-05 14:29:15 -06:00
raw_printf(pArg->out,
2015-03-20 09:04:26 -05:00
" nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
);
}
}
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out, "---------------------------\n");
2015-03-20 09:04:26 -05:00
#endif
}
2014-04-04 10:16:20 -05:00
/*
** Parameter azArray points to a zero-terminated array of strings. zStr
** points to a single nul-terminated string. Return non-zero if zStr
** is equal, according to strcmp(), to any of the strings in the array.
** Otherwise, return zero.
*/
static int str_in_array(const char *zStr, const char **azArray){
int i;
for(i=0; azArray[i]; i++){
if( 0==strcmp(zStr, azArray[i]) ) return 1;
}
return 0;
}
/*
** If compiled statement pSql appears to be an EXPLAIN statement, allocate
2015-03-20 09:04:26 -05:00
** and populate the ShellState.aiIndent[] array with the number of
2016-12-05 14:29:15 -06:00
** spaces each opcode should be indented before it is output.
2014-04-04 10:16:20 -05:00
**
** The indenting rules are:
**
** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
** all opcodes that occur between the p2 jump destination and the opcode
** itself by 2 spaces.
**
** * For each "Goto", if the jump destination is earlier in the program
** and ends on one of:
** Yield SeekGt SeekLt RowSetRead Rewind
** or if the P1 parameter is one instead of zero,
** then indent all opcodes between the earlier instruction
** and "Goto" by 2 spaces.
*/
2015-03-20 09:04:26 -05:00
static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
2014-04-04 10:16:20 -05:00
const char *zSql; /* The text of the SQL statement */
const char *z; /* Used to check if this is an EXPLAIN */
int *abYield = 0; /* True if op is an OP_Yield */
int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
int iOp; /* Index of operation in p->aiIndent[] */
2014-09-30 08:40:45 -05:00
const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
"NextIfOpen", "PrevIfOpen", 0 };
2015-03-20 09:04:26 -05:00
const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
"Rewind", 0 };
2014-04-04 10:16:20 -05:00
const char *azGoto[] = { "Goto", 0 };
/* Try to figure out if this is really an EXPLAIN statement. If this
** cannot be verified, return early. */
2016-02-23 09:07:39 -06:00
if( sqlite3_column_count(pSql)!=8 ){
p->cMode = p->mode;
return;
}
2014-04-04 10:16:20 -05:00
zSql = sqlite3_sql(pSql);
if( zSql==0 ) return;
for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
2016-02-23 09:07:39 -06:00
if( sqlite3_strnicmp(z, "explain", 7) ){
p->cMode = p->mode;
return;
}
2014-04-04 10:16:20 -05:00
for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
int i;
int iAddr = sqlite3_column_int(pSql, 0);
const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
/* Set p2 to the P2 field of the current opcode. Then, assuming that
** p2 is an instruction address, set variable p2op to the index of that
** instruction in the aiIndent[] array. p2 and p2op may be different if
** the current instruction is part of a sub-program generated by an
** SQL trigger or foreign key. */
int p2 = sqlite3_column_int(pSql, 3);
int p2op = (p2 + (iOp-iAddr));
/* Grow the p->aiIndent array as required */
if( iOp>=nAlloc ){
2016-02-23 09:07:39 -06:00
if( iOp==0 ){
/* Do further verfication that this is explain output. Abort if
** it is not */
static const char *explainCols[] = {
"addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
int jj;
for(jj=0; jj<ArraySize(explainCols); jj++){
if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
p->cMode = p->mode;
sqlite3_reset(pSql);
return;
}
}
}
2014-04-04 10:16:20 -05:00
nAlloc += 100;
2015-07-10 14:14:29 -05:00
p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
2014-04-04 10:16:20 -05:00
}
abYield[iOp] = str_in_array(zOp, azYield);
p->aiIndent[iOp] = 0;
p->nIndent = iOp+1;
if( str_in_array(zOp, azNext) ){
for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
}
if( str_in_array(zOp, azGoto) && p2op<p->nIndent
&& (abYield[p2op] || sqlite3_column_int(pSql, 2))
){
2016-12-05 14:29:15 -06:00
for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
2014-04-04 10:16:20 -05:00
}
}
p->iIndent = 0;
sqlite3_free(abYield);
sqlite3_reset(pSql);
}
/*
** Free the array allocated by explain_data_prepare().
*/
2015-03-20 09:04:26 -05:00
static void explain_data_delete(ShellState *p){
2014-04-04 10:16:20 -05:00
sqlite3_free(p->aiIndent);
p->aiIndent = 0;
p->nIndent = 0;
p->iIndent = 0;
}
2009-12-03 16:24:07 -05:00
/*
2016-12-05 14:29:15 -06:00
** Disable and restore .wheretrace and .selecttrace settings.
*/
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
extern int sqlite3SelectTrace;
static int savedSelectTrace;
#endif
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
extern int sqlite3WhereTrace;
static int savedWhereTrace;
#endif
static void disable_debug_trace_modes(void){
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
savedSelectTrace = sqlite3SelectTrace;
sqlite3SelectTrace = 0;
#endif
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
savedWhereTrace = sqlite3WhereTrace;
sqlite3WhereTrace = 0;
#endif
}
static void restore_debug_trace_modes(void){
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
sqlite3SelectTrace = savedSelectTrace;
#endif
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
sqlite3WhereTrace = savedWhereTrace;
#endif
}
/*
** Run a prepared statement
*/
static void exec_prepared_stmt(
ShellState *pArg, /* Pointer to ShellState */
sqlite3_stmt *pStmt, /* Statment to run */
int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
){
int rc;
/* perform the first step. this will tell us if we
** have a result set or not and how wide it is.
*/
rc = sqlite3_step(pStmt);
/* if we have a result set... */
if( SQLITE_ROW == rc ){
/* if we have a callback... */
if( xCallback ){
/* allocate space for col name ptr, value ptr, and type */
int nCol = sqlite3_column_count(pStmt);
void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
if( !pData ){
rc = SQLITE_NOMEM;
}else{
char **azCols = (char **)pData; /* Names of result columns */
char **azVals = &azCols[nCol]; /* Results */
int *aiTypes = (int *)&azVals[nCol]; /* Result types */
int i, x;
assert(sizeof(int) <= sizeof(char *));
/* save off ptrs to column names */
for(i=0; i<nCol; i++){
azCols[i] = (char *)sqlite3_column_name(pStmt, i);
}
do{
/* extract the data and data types */
for(i=0; i<nCol; i++){
aiTypes[i] = x = sqlite3_column_type(pStmt, i);
if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
azVals[i] = "";
}else{
azVals[i] = (char*)sqlite3_column_text(pStmt, i);
}
if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
rc = SQLITE_NOMEM;
break; /* from for */
}
} /* end for */
/* if data and types extracted successfully... */
if( SQLITE_ROW == rc ){
/* call the supplied callback with the result row data */
if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
rc = SQLITE_ABORT;
}else{
rc = sqlite3_step(pStmt);
}
}
} while( SQLITE_ROW == rc );
sqlite3_free(pData);
}
}else{
do{
rc = sqlite3_step(pStmt);
} while( rc == SQLITE_ROW );
}
}
}
/*
** Execute a statement or set of statements. Print
** any result rows/columns depending on the current mode
2009-12-03 16:24:07 -05:00
** set via the supplied callback.
**
2016-12-05 14:29:15 -06:00
** This is very similar to SQLite's built-in sqlite3_exec()
** function except it takes a slightly different callback
2009-12-03 16:24:07 -05:00
** and callback data argument.
*/
static int shell_exec(
2015-03-20 09:04:26 -05:00
sqlite3 *db, /* An open database */
const char *zSql, /* SQL to be evaluated */
2009-12-03 16:24:07 -05:00
int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
2015-03-20 09:04:26 -05:00
/* (not the same as sqlite3_exec) */
ShellState *pArg, /* Pointer to ShellState */
char **pzErrMsg /* Error msg written here */
2009-12-03 16:24:07 -05:00
){
2010-05-18 12:22:17 -04:00
sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
int rc = SQLITE_OK; /* Return Code */
2011-12-26 14:52:17 -05:00
int rc2;
2010-05-18 12:22:17 -04:00
const char *zLeftover; /* Tail of unprocessed SQL */
2009-12-03 16:24:07 -05:00
if( pzErrMsg ){
*pzErrMsg = NULL;
}
while( zSql[0] && (SQLITE_OK == rc) ){
2016-12-05 14:29:15 -06:00
static const char *zStmtSql;
2009-12-03 16:24:07 -05:00
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;
2011-12-26 14:52:17 -05:00
while( IsSpace(zSql[0]) ) zSql++;
2009-12-03 16:24:07 -05:00
continue;
}
2016-12-05 14:29:15 -06:00
zStmtSql = sqlite3_sql(pStmt);
while( IsSpace(zStmtSql[0]) ) zStmtSql++;
2009-12-03 16:24:07 -05:00
2010-08-28 08:35:57 -04:00
/* save off the prepared statment handle and reset row count */
if( pArg ){
pArg->pStmt = pStmt;
pArg->cnt = 0;
}
2010-05-18 12:22:17 -04:00
/* echo the sql statement if echo on */
2010-08-28 08:35:57 -04:00
if( pArg && pArg->echoOn ){
2016-02-23 09:07:39 -06:00
utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
2010-05-18 12:22:17 -04:00
}
2014-04-04 10:16:20 -05:00
/* Show the EXPLAIN QUERY PLAN if .eqp is on */
2016-12-05 14:29:15 -06:00
if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
2014-04-04 10:16:20 -05:00
sqlite3_stmt *pExplain;
2016-12-05 14:29:15 -06:00
char *zEQP;
disable_debug_trace_modes();
zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
2014-04-04 10:16:20 -05:00
rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
if( rc==SQLITE_OK ){
while( sqlite3_step(pExplain)==SQLITE_ROW ){
2016-02-23 09:07:39 -06:00
raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
2014-04-04 10:16:20 -05:00
}
}
sqlite3_finalize(pExplain);
sqlite3_free(zEQP);
2016-12-05 14:29:15 -06:00
if( pArg->autoEQP>=2 ){
/* Also do an EXPLAIN for ".eqp full" mode */
zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
if( rc==SQLITE_OK ){
pArg->cMode = MODE_Explain;
explain_data_prepare(pArg, pExplain);
exec_prepared_stmt(pArg, pExplain, xCallback);
explain_data_delete(pArg);
}
sqlite3_finalize(pExplain);
sqlite3_free(zEQP);
}
restore_debug_trace_modes();
2014-04-04 10:16:20 -05:00
}
2016-02-23 09:07:39 -06:00
if( pArg ){
pArg->cMode = pArg->mode;
if( pArg->autoExplain
&& sqlite3_column_count(pStmt)==8
2016-12-05 14:29:15 -06:00
&& sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
2016-02-23 09:07:39 -06:00
){
pArg->cMode = MODE_Explain;
}
2016-12-05 14:29:15 -06:00
2016-02-23 09:07:39 -06:00
/* If the shell is currently in ".explain" mode, gather the extra
** data required to add indents to the output.*/
if( pArg->cMode==MODE_Explain ){
explain_data_prepare(pArg, pStmt);
}
2014-04-04 10:16:20 -05:00
}
2016-12-05 14:29:15 -06:00
exec_prepared_stmt(pArg, pStmt, xCallback);
2014-04-04 10:16:20 -05:00
explain_data_delete(pArg);
2010-08-28 08:35:57 -04:00
/* print usage stats if stats on */
if( pArg && pArg->statsOn ){
display_stats(db, pArg, 0);
}
2015-03-20 09:04:26 -05:00
/* print loop-counters if required */
if( pArg && pArg->scanstatsOn ){
display_scanstats(db, pArg);
}
2016-12-05 14:29:15 -06:00
/* Finalize the statement just executed. If this fails, save a
2010-05-18 12:22:17 -04:00
** copy of the error message. Otherwise, set zSql to point to the
** next statement to execute. */
2011-12-26 14:52:17 -05:00
rc2 = sqlite3_finalize(pStmt);
if( rc!=SQLITE_NOMEM ) rc = rc2;
2010-05-18 12:22:17 -04:00
if( rc==SQLITE_OK ){
2009-12-03 16:24:07 -05:00
zSql = zLeftover;
2011-12-26 14:52:17 -05:00
while( IsSpace(zSql[0]) ) zSql++;
2010-05-18 12:22:17 -04:00
}else if( pzErrMsg ){
*pzErrMsg = save_err_msg(db);
2009-12-03 16:24:07 -05:00
}
2010-08-28 08:35:57 -04:00
/* clear saved stmt handle */
if( pArg ){
pArg->pStmt = NULL;
}
2009-12-03 16:24:07 -05:00
}
} /* end while */
return rc;
}
2008-07-30 09:15:43 -04:00
/*
** This is a different callback routine used for dumping the database.
** Each row received by this callback consists of a table name,
** the table type ("index" or "table") and SQL to create the table.
** This routine should print text sufficient to recreate the table.
*/
static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
int rc;
const char *zTable;
const char *zType;
const char *zSql;
2009-08-11 16:01:51 -04:00
const char *zPrepStmt = 0;
2015-03-20 09:04:26 -05:00
ShellState *p = (ShellState *)pArg;
2008-07-30 09:15:43 -04:00
2009-02-20 15:33:35 -05:00
UNUSED_PARAMETER(azCol);
2008-07-30 09:15:43 -04:00
if( nArg!=3 ) return 1;
zTable = azArg[0];
zType = azArg[1];
zSql = azArg[2];
2016-12-05 14:29:15 -06:00
2008-07-30 09:15:43 -04:00
if( strcmp(zTable, "sqlite_sequence")==0 ){
2009-08-11 16:01:51 -04:00
zPrepStmt = "DELETE FROM sqlite_sequence;\n";
2014-04-04 10:16:20 -05:00
}else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "ANALYZE sqlite_master;\n");
2008-07-30 09:15:43 -04:00
}else if( strncmp(zTable, "sqlite_", 7)==0 ){
return 0;
}else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
char *zIns;
if( !p->writableSchema ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
2008-07-30 09:15:43 -04:00
p->writableSchema = 1;
}
zIns = sqlite3_mprintf(
"INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
"VALUES('table','%q','%q',0,'%q');",
zTable, zTable, zSql);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s\n", zIns);
2008-07-30 09:15:43 -04:00
sqlite3_free(zIns);
return 0;
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s;\n", zSql);
2008-07-30 09:15:43 -04:00
}
if( strcmp(zType, "table")==0 ){
sqlite3_stmt *pTableInfo = 0;
char *zSelect = 0;
char *zTableInfo = 0;
char *zTmp = 0;
2009-08-11 16:01:51 -04:00
int nRow = 0;
2016-12-05 14:29:15 -06:00
2008-07-30 09:15:43 -04:00
zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
zTableInfo = appendText(zTableInfo, zTable, '"');
zTableInfo = appendText(zTableInfo, ");", 0);
2014-04-04 10:16:20 -05:00
rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
2009-08-11 16:01:51 -04:00
free(zTableInfo);
2008-07-30 09:15:43 -04:00
if( rc!=SQLITE_OK || !pTableInfo ){
return 1;
}
zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
2012-05-15 19:05:34 -04:00
/* Always quote the table name, even if it appears to be pure ascii,
** in case it is a keyword. Ex: INSERT INTO "table" ... */
2008-07-30 09:15:43 -04:00
zTmp = appendText(zTmp, zTable, '"');
if( zTmp ){
zSelect = appendText(zSelect, zTmp, '\'');
2012-05-15 19:05:34 -04:00
free(zTmp);
2008-07-30 09:15:43 -04:00
}
zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
rc = sqlite3_step(pTableInfo);
while( rc==SQLITE_ROW ){
const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
zSelect = appendText(zSelect, "quote(", 0);
zSelect = appendText(zSelect, zText, '"');
rc = sqlite3_step(pTableInfo);
if( rc==SQLITE_ROW ){
2012-05-15 19:05:34 -04:00
zSelect = appendText(zSelect, "), ", 0);
2008-07-30 09:15:43 -04:00
}else{
zSelect = appendText(zSelect, ") ", 0);
}
2009-08-11 16:01:51 -04:00
nRow++;
2008-07-30 09:15:43 -04:00
}
rc = sqlite3_finalize(pTableInfo);
2009-08-11 16:01:51 -04:00
if( rc!=SQLITE_OK || nRow==0 ){
free(zSelect);
2008-07-30 09:15:43 -04:00
return 1;
}
zSelect = appendText(zSelect, "|| ')' FROM ", 0);
zSelect = appendText(zSelect, zTable, '"');
2011-12-26 14:52:17 -05:00
rc = run_table_dump_query(p, zSelect, zPrepStmt);
2008-07-30 09:15:43 -04:00
if( rc==SQLITE_CORRUPT ){
zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
2011-12-26 14:52:17 -05:00
run_table_dump_query(p, zSelect, 0);
2008-07-30 09:15:43 -04:00
}
2012-05-15 19:05:34 -04:00
free(zSelect);
2008-07-30 09:15:43 -04:00
}
return 0;
}
/*
** Run zQuery. Use dump_callback() as the callback routine so that
** the contents of the query are output as SQL statements.
**
** If we get a SQLITE_CORRUPT error, rerun the query after appending
** "ORDER BY rowid DESC" to the end.
*/
static int run_schema_dump_query(
2016-12-05 14:29:15 -06:00
ShellState *p,
2011-12-26 14:52:17 -05:00
const char *zQuery
2008-07-30 09:15:43 -04:00
){
int rc;
2011-12-26 14:52:17 -05:00
char *zErr = 0;
rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
2008-07-30 09:15:43 -04:00
if( rc==SQLITE_CORRUPT ){
char *zQ2;
2009-02-20 15:33:35 -05:00
int len = strlen30(zQuery);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
2011-12-26 14:52:17 -05:00
if( zErr ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "/****** %s ******/\n", zErr);
2011-12-26 14:52:17 -05:00
sqlite3_free(zErr);
zErr = 0;
}
2008-07-30 09:15:43 -04:00
zQ2 = malloc( len+100 );
if( zQ2==0 ) return rc;
2012-05-15 19:05:34 -04:00
sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
2011-12-26 14:52:17 -05:00
rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
2011-12-26 14:52:17 -05:00
}else{
rc = SQLITE_CORRUPT;
}
sqlite3_free(zErr);
2008-07-30 09:15:43 -04:00
free(zQ2);
}
return rc;
}
/*
** Text of a help message
*/
static char zHelp[] =
2016-12-05 14:29:15 -06:00
#ifndef SQLITE_OMIT_AUTHORIZATION
".auth ON|OFF Show authorizer callbacks\n"
#endif
2009-02-20 15:33:35 -05:00
".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
2014-09-30 08:40:45 -05:00
".bail on|off Stop after hitting an error. Default OFF\n"
2015-07-10 14:14:29 -05:00
".binary on|off Turn binary output on or off. Default OFF\n"
2016-02-23 09:07:39 -06:00
".changes on|off Show number of rows changed by SQL\n"
2016-12-05 14:29:15 -06:00
".check GLOB Fail if output since .testcase does not match\n"
2014-04-04 10:16:20 -05:00
".clone NEWDB Clone data into NEWDB from the existing database\n"
2008-07-30 09:15:43 -04:00
".databases List names and files of attached databases\n"
2015-07-10 14:14:29 -05:00
".dbinfo ?DB? Show status information about the database\n"
2008-07-30 09:15:43 -04:00
".dump ?TABLE? ... Dump the database in an SQL text format\n"
2009-12-03 16:24:07 -05:00
" If TABLE specified, only dump tables matching\n"
" LIKE pattern TABLE.\n"
2014-09-30 08:40:45 -05:00
".echo on|off Turn command echo on or off\n"
2016-12-05 14:29:15 -06:00
".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
2008-07-30 09:15:43 -04:00
".exit Exit this program\n"
2016-02-23 09:07:39 -06:00
".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
2016-12-05 14:29:15 -06:00
".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
2014-09-30 08:40:45 -05:00
".headers on|off Turn display of headers on or off\n"
2008-07-30 09:15:43 -04:00
".help Show this message\n"
".import FILE TABLE Import data from FILE into TABLE\n"
2015-07-10 14:14:29 -05:00
".indexes ?TABLE? Show names of all indexes\n"
" If TABLE specified, only show indexes for tables\n"
2009-12-03 16:24:07 -05:00
" matching LIKE pattern TABLE.\n"
2008-07-30 09:15:43 -04:00
#ifdef SQLITE_ENABLE_IOTRACE
".iotrace FILE Enable I/O diagnostic logging to FILE\n"
#endif
2015-07-10 14:14:29 -05:00
".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
2008-07-30 09:15:43 -04:00
#ifndef SQLITE_OMIT_LOAD_EXTENSION
".load FILE ?ENTRY? Load an extension library\n"
#endif
2010-05-18 12:22:17 -04:00
".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
2008-07-30 09:15:43 -04:00
".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
2015-03-20 09:04:26 -05:00
" ascii Columns/rows delimited by 0x1F and 0x1E\n"
2008-07-30 09:15:43 -04:00
" csv Comma-separated values\n"
" column Left-aligned columns. (See .width)\n"
" html HTML <table> code\n"
" insert SQL insert statements for TABLE\n"
" line One value per line\n"
2015-03-20 09:04:26 -05:00
" list Values delimited by .separator strings\n"
2008-07-30 09:15:43 -04:00
" tabs Tab-separated values\n"
" tcl TCL list elements\n"
2013-01-15 16:38:05 -06:00
".nullvalue STRING Use STRING in place of NULL values\n"
2014-09-30 08:40:45 -05:00
".once FILENAME Output for the next SQL command only to FILENAME\n"
2016-12-05 14:29:15 -06:00
".open ?--new? ?FILE? Close existing database and reopen FILE\n"
" The --new starts with an empty file\n"
2014-09-30 08:40:45 -05:00
".output ?FILENAME? Send output to FILENAME or stdout\n"
2013-01-15 16:38:05 -06:00
".print STRING... Print literal STRING\n"
2008-07-30 09:15:43 -04:00
".prompt MAIN CONTINUE Replace the standard prompts\n"
".quit Exit this program\n"
".read FILENAME Execute SQL in FILENAME\n"
2009-02-20 15:33:35 -05:00
".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
2014-04-04 10:16:20 -05:00
".save FILE Write in-memory database into FILE\n"
2015-03-20 09:04:26 -05:00
".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
2016-12-05 14:29:15 -06:00
".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
" Add --indent for pretty-printing\n"
2015-03-20 09:04:26 -05:00
".separator COL ?ROW? Change the column separator and optionally the row\n"
" separator for both the output mode and .import\n"
2016-12-05 14:29:15 -06:00
#if defined(SQLITE_ENABLE_SESSION)
".session CMD ... Create or control sessions\n"
#endif
2014-09-30 08:40:45 -05:00
".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
2008-07-30 09:15:43 -04:00
".show Show the current values for various settings\n"
2016-12-05 14:29:15 -06:00
".stats ?on|off? Show stats or turn stats on or off\n"
2014-09-30 08:40:45 -05:00
".system CMD ARGS... Run CMD ARGS... in a system shell\n"
2009-12-03 16:24:07 -05:00
".tables ?TABLE? List names of tables\n"
" If TABLE specified, only list tables matching\n"
" LIKE pattern TABLE.\n"
2016-12-05 14:29:15 -06:00
".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
2008-07-30 09:15:43 -04:00
".timeout MS Try opening locked tables for MS milliseconds\n"
2014-09-30 08:40:45 -05:00
".timer on|off Turn SQL timer on or off\n"
2012-05-15 19:05:34 -04:00
".trace FILE|off Output each SQL statement as it is run\n"
2016-02-23 09:07:39 -06:00
".vfsinfo ?AUX? Information about the top-level VFS\n"
".vfslist List all available VFSes\n"
2012-01-18 00:18:26 -05:00
".vfsname ?AUX? Print the name of the VFS stack\n"
2009-12-19 15:56:40 -05:00
".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
2014-09-30 08:40:45 -05:00
" Negative values right-justify\n"
2009-12-03 16:24:07 -05:00
;
2016-12-05 14:29:15 -06:00
#if defined(SQLITE_ENABLE_SESSION)
/*
** Print help information for the ".sessions" command
*/
void session_help(ShellState *p){
raw_printf(p->out,
".session ?NAME? SUBCOMMAND ?ARGS...?\n"
"If ?NAME? is omitted, the first defined session is used.\n"
"Subcommands:\n"
" attach TABLE Attach TABLE\n"
" changeset FILE Write a changeset into FILE\n"
" close Close one session\n"
" enable ?BOOLEAN? Set or query the enable bit\n"
" filter GLOB... Reject tables matching GLOBs\n"
" indirect ?BOOLEAN? Mark or query the indirect status\n"
" isempty Query whether the session is empty\n"
" list List currently open session names\n"
" open DB NAME Open a new session on DB\n"
" patchset FILE Write a patchset into FILE\n"
);
}
#endif
2008-07-30 09:15:43 -04:00
/* Forward reference */
2015-03-20 09:04:26 -05:00
static int process_input(ShellState *p, FILE *in);
2016-12-05 14:29:15 -06:00
/*
** Read the content of a file into memory obtained from sqlite3_malloc64().
** The caller is responsible for freeing the memory.
**
** NULL is returned if any error is encountered.
*/
static char *readFile(const char *zName){
FILE *in = fopen(zName, "rb");
long nIn;
size_t nRead;
char *pBuf;
if( in==0 ) return 0;
fseek(in, 0, SEEK_END);
nIn = ftell(in);
rewind(in);
pBuf = sqlite3_malloc64( nIn+1 );
if( pBuf==0 ) return 0;
nRead = fread(pBuf, nIn, 1, in);
fclose(in);
if( nRead!=1 ){
sqlite3_free(pBuf);
return 0;
}
pBuf[nIn] = 0;
return pBuf;
}
2014-09-30 08:40:45 -05:00
/*
** Implementation of the "readfile(X)" SQL function. The entire content
** of the file named X is read and returned as a BLOB. NULL is returned
** if the file does not exist or is unreadable.
*/
static void readfileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
const char *zName;
void *pBuf;
2016-02-23 09:07:39 -06:00
UNUSED_PARAMETER(argc);
2014-09-30 08:40:45 -05:00
zName = (const char*)sqlite3_value_text(argv[0]);
if( zName==0 ) return;
2016-12-05 14:29:15 -06:00
pBuf = readFile(zName);
if( pBuf ) sqlite3_result_blob(context, pBuf, -1, sqlite3_free);
2014-09-30 08:40:45 -05:00
}
/*
** Implementation of the "writefile(X,Y)" SQL function. The argument Y
** is written into file X. The number of bytes written is returned. Or
** NULL is returned if something goes wrong, such as being unable to open
** file X for writing.
*/
static void writefileFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv
){
FILE *out;
const char *z;
sqlite3_int64 rc;
const char *zFile;
2016-02-23 09:07:39 -06:00
UNUSED_PARAMETER(argc);
2014-09-30 08:40:45 -05:00
zFile = (const char*)sqlite3_value_text(argv[0]);
if( zFile==0 ) return;
out = fopen(zFile, "wb");
if( out==0 ) return;
z = (const char*)sqlite3_value_blob(argv[1]);
if( z==0 ){
rc = 0;
}else{
rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
}
fclose(out);
sqlite3_result_int64(context, rc);
}
2008-07-30 09:15:43 -04:00
2016-12-05 14:29:15 -06:00
#if defined(SQLITE_ENABLE_SESSION)
/*
** Close a single OpenSession object and release all of its associated
** resources.
*/
static void session_close(OpenSession *pSession){
int i;
sqlite3session_delete(pSession->p);
sqlite3_free(pSession->zName);
for(i=0; i<pSession->nFilter; i++){
sqlite3_free(pSession->azFilter[i]);
}
sqlite3_free(pSession->azFilter);
memset(pSession, 0, sizeof(OpenSession));
}
#endif
/*
** Close all OpenSession objects and release all associated resources.
*/
#if defined(SQLITE_ENABLE_SESSION)
static void session_close_all(ShellState *p){
int i;
for(i=0; i<p->nSession; i++){
session_close(&p->aSession[i]);
}
p->nSession = 0;
}
#else
# define session_close_all(X)
#endif
/*
** Implementation of the xFilter function for an open session. Omit
** any tables named by ".session filter" but let all other table through.
*/
#if defined(SQLITE_ENABLE_SESSION)
static int session_filter(void *pCtx, const char *zTab){
OpenSession *pSession = (OpenSession*)pCtx;
int i;
for(i=0; i<pSession->nFilter; i++){
if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
}
return 1;
}
#endif
2008-07-30 09:15:43 -04:00
/*
** Make sure the database is open. If it is not, then open it. If
** the database fails to open, print an error message and exit.
*/
2015-03-20 09:04:26 -05:00
static void open_db(ShellState *p, int keepAlive){
2008-07-30 09:15:43 -04:00
if( p->db==0 ){
2012-11-15 18:45:58 -05:00
sqlite3_initialize();
2008-07-30 09:15:43 -04:00
sqlite3_open(p->zDbFilename, &p->db);
2015-07-10 14:14:29 -05:00
globalDb = p->db;
if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){
sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0,
2008-07-30 09:15:43 -04:00
shellstaticFunc, 0, 0);
}
2015-07-10 14:14:29 -05:00
if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
2016-12-05 14:29:15 -06:00
utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
2015-07-10 14:14:29 -05:00
p->zDbFilename, sqlite3_errmsg(p->db));
2014-04-04 10:16:20 -05:00
if( keepAlive ) return;
2008-07-30 09:15:43 -04:00
exit(1);
}
#ifndef SQLITE_OMIT_LOAD_EXTENSION
sqlite3_enable_load_extension(p->db, 1);
#endif
2015-07-10 14:14:29 -05:00
sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
2014-09-30 08:40:45 -05:00
readfileFunc, 0, 0);
2015-07-10 14:14:29 -05:00
sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
2014-09-30 08:40:45 -05:00
writefileFunc, 0, 0);
2008-07-30 09:15:43 -04:00
}
}
/*
** Do C-language style dequoting.
**
2015-07-10 14:14:29 -05:00
** \a -> alarm
** \b -> backspace
2008-07-30 09:15:43 -04:00
** \t -> tab
** \n -> newline
2015-07-10 14:14:29 -05:00
** \v -> vertical tab
** \f -> form feed
2008-07-30 09:15:43 -04:00
** \r -> carriage return
2015-07-10 14:14:29 -05:00
** \s -> space
2013-08-29 08:11:18 -05:00
** \" -> "
2015-07-10 14:14:29 -05:00
** \' -> '
2008-07-30 09:15:43 -04:00
** \\ -> backslash
2015-07-10 14:14:29 -05:00
** \NNN -> ascii character NNN in octal
2008-07-30 09:15:43 -04:00
*/
static void resolve_backslashes(char *z){
2009-02-20 15:33:35 -05:00
int i, j;
char c;
2014-09-30 08:40:45 -05:00
while( *z && *z!='\\' ) z++;
2008-07-30 09:15:43 -04:00
for(i=j=0; (c = z[i])!=0; i++, j++){
2015-07-10 14:14:29 -05:00
if( c=='\\' && z[i+1]!=0 ){
2008-07-30 09:15:43 -04:00
c = z[++i];
2015-07-10 14:14:29 -05:00
if( c=='a' ){
c = '\a';
}else if( c=='b' ){
c = '\b';
2008-07-30 09:15:43 -04:00
}else if( c=='t' ){
c = '\t';
2015-07-10 14:14:29 -05:00
}else if( c=='n' ){
c = '\n';
}else if( c=='v' ){
c = '\v';
}else if( c=='f' ){
c = '\f';
2008-07-30 09:15:43 -04:00
}else if( c=='r' ){
c = '\r';
2015-07-10 14:14:29 -05:00
}else if( c=='"' ){
c = '"';
}else if( c=='\'' ){
c = '\'';
2013-08-29 08:11:18 -05:00
}else if( c=='\\' ){
c = '\\';
2008-07-30 09:15:43 -04:00
}else if( c>='0' && c<='7' ){
c -= '0';
if( z[i+1]>='0' && z[i+1]<='7' ){
i++;
c = (c<<3) + z[i] - '0';
if( z[i+1]>='0' && z[i+1]<='7' ){
i++;
c = (c<<3) + z[i] - '0';
}
}
}
}
z[j] = c;
}
2014-09-30 08:40:45 -05:00
if( j<i ) z[j] = 0;
2008-07-30 09:15:43 -04:00
}
/*
2013-08-29 08:11:18 -05:00
** Return the value of a hexadecimal digit. Return -1 if the input
** is not a hex digit.
2008-07-30 09:15:43 -04:00
*/
2013-08-29 08:11:18 -05:00
static int hexDigitValue(char c){
if( c>='0' && c<='9' ) return c - '0';
if( c>='a' && c<='f' ) return c - 'a' + 10;
if( c>='A' && c<='F' ) return c - 'A' + 10;
return -1;
2013-05-21 15:38:11 -05:00
}
/*
** Interpret zArg as an integer value, possibly with suffixes.
*/
static sqlite3_int64 integerValue(const char *zArg){
sqlite3_int64 v = 0;
static const struct { char *zSuffix; int iMult; } aMult[] = {
{ "KiB", 1024 },
{ "MiB", 1024*1024 },
{ "GiB", 1024*1024*1024 },
{ "KB", 1000 },
{ "MB", 1000000 },
{ "GB", 1000000000 },
{ "K", 1000 },
{ "M", 1000000 },
{ "G", 1000000000 },
};
int i;
int isNeg = 0;
if( zArg[0]=='-' ){
isNeg = 1;
zArg++;
}else if( zArg[0]=='+' ){
zArg++;
}
2013-08-29 08:11:18 -05:00
if( zArg[0]=='0' && zArg[1]=='x' ){
int x;
zArg += 2;
while( (x = hexDigitValue(zArg[0]))>=0 ){
v = (v<<4) + x;
zArg++;
}
}else{
while( IsDigit(zArg[0]) ){
v = v*10 + zArg[0] - '0';
zArg++;
}
2013-05-21 15:38:11 -05:00
}
2013-08-29 08:11:18 -05:00
for(i=0; i<ArraySize(aMult); i++){
2013-05-21 15:38:11 -05:00
if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
v *= aMult[i].iMult;
break;
}
}
return isNeg? -v : v;
2008-07-30 09:15:43 -04:00
}
2013-08-29 08:11:18 -05:00
/*
** Interpret zArg as either an integer or a boolean value. Return 1 or 0
** for TRUE and FALSE. Return the integer value if appropriate.
*/
static int booleanValue(char *zArg){
int i;
if( zArg[0]=='0' && zArg[1]=='x' ){
for(i=2; hexDigitValue(zArg[i])>=0; i++){}
}else{
for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
}
if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
return 1;
}
if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
return 0;
}
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
2013-08-29 08:11:18 -05:00
zArg);
return 0;
}
2012-05-15 19:05:34 -04:00
/*
** Close an output file, assuming it is not stderr or stdout
*/
static void output_file_close(FILE *f){
if( f && f!=stdout && f!=stderr ) fclose(f);
}
/*
** Try to open an output file. The names "stdout" and "stderr" are
2016-12-05 14:29:15 -06:00
** recognized and do the right thing. NULL is returned if the output
2012-05-15 19:05:34 -04:00
** filename is "off".
*/
static FILE *output_file_open(const char *zFile){
FILE *f;
if( strcmp(zFile,"stdout")==0 ){
f = stdout;
}else if( strcmp(zFile, "stderr")==0 ){
f = stderr;
}else if( strcmp(zFile, "off")==0 ){
f = 0;
}else{
f = fopen(zFile, "wb");
if( f==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
2012-05-15 19:05:34 -04:00
}
}
return f;
}
/*
** A routine for handling output from sqlite3_trace().
*/
2016-12-05 14:29:15 -06:00
static int sql_trace_callback(
unsigned mType,
void *pArg,
void *pP,
void *pX
){
2012-05-15 19:05:34 -04:00
FILE *f = (FILE*)pArg;
2016-12-05 14:29:15 -06:00
UNUSED_PARAMETER(mType);
UNUSED_PARAMETER(pP);
2015-03-20 09:04:26 -05:00
if( f ){
2016-12-05 14:29:15 -06:00
const char *z = (const char*)pX;
2015-03-20 09:04:26 -05:00
int i = (int)strlen(z);
while( i>0 && z[i-1]==';' ){ i--; }
2016-02-23 09:07:39 -06:00
utf8_printf(f, "%.*s;\n", i, z);
2015-03-20 09:04:26 -05:00
}
2016-12-05 14:29:15 -06:00
return 0;
2012-05-15 19:05:34 -04:00
}
/*
** A no-op routine that runs with the ".breakpoint" doc-command. This is
** a useful spot to set a debugger breakpoint.
*/
static void test_breakpoint(void){
static int nCall = 0;
nCall++;
}
2013-08-29 08:11:18 -05:00
/*
2015-03-20 09:04:26 -05:00
** An object used to read a CSV and other files for import.
2013-08-29 08:11:18 -05:00
*/
2015-03-20 09:04:26 -05:00
typedef struct ImportCtx ImportCtx;
struct ImportCtx {
2013-08-29 08:11:18 -05:00
const char *zFile; /* Name of the input file */
FILE *in; /* Read the CSV text from this input stream */
char *z; /* Accumulated text for a field */
int n; /* Number of bytes in z */
int nAlloc; /* Space allocated for z[] */
int nLine; /* Current line number */
int cTerm; /* Character that terminated the most recent field */
2015-03-20 09:04:26 -05:00
int cColSep; /* The column separator character. (Usually ",") */
int cRowSep; /* The row separator character. (Usually "\n") */
2013-08-29 08:11:18 -05:00
};
/* Append a single byte to z[] */
2015-03-20 09:04:26 -05:00
static void import_append_char(ImportCtx *p, int c){
2013-08-29 08:11:18 -05:00
if( p->n+1>=p->nAlloc ){
p->nAlloc += p->nAlloc + 100;
2015-07-10 14:14:29 -05:00
p->z = sqlite3_realloc64(p->z, p->nAlloc);
2013-08-29 08:11:18 -05:00
if( p->z==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "out of memory\n");
2013-08-29 08:11:18 -05:00
exit(1);
}
}
p->z[p->n++] = (char)c;
}
/* Read a single field of CSV text. Compatible with rfc4180 and extended
** with the option of having a separator other than ",".
**
** + Input comes from p->in.
** + Store results in p->z of length p->n. Space to hold p->z comes
2015-07-10 14:14:29 -05:00
** from sqlite3_malloc64().
2015-03-20 09:04:26 -05:00
** + Use p->cSep as the column separator. The default is ",".
** + Use p->rSep as the row separator. The default is "\n".
2013-08-29 08:11:18 -05:00
** + Keep track of the line number in p->nLine.
** + Store the character that terminates the field in p->cTerm. Store
** EOF on end-of-file.
** + Report syntax errors on stderr
*/
2015-07-10 14:14:29 -05:00
static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
2015-03-20 09:04:26 -05:00
int c;
int cSep = p->cColSep;
int rSep = p->cRowSep;
2013-08-29 08:11:18 -05:00
p->n = 0;
c = fgetc(p->in);
if( c==EOF || seenInterrupt ){
p->cTerm = EOF;
return 0;
}
if( c=='"' ){
2015-03-20 09:04:26 -05:00
int pc, ppc;
2013-08-29 08:11:18 -05:00
int startLine = p->nLine;
int cQuote = c;
2014-04-04 10:16:20 -05:00
pc = ppc = 0;
2013-08-29 08:11:18 -05:00
while( 1 ){
c = fgetc(p->in);
2015-03-20 09:04:26 -05:00
if( c==rSep ) p->nLine++;
2013-08-29 08:11:18 -05:00
if( c==cQuote ){
if( pc==cQuote ){
pc = 0;
continue;
}
}
if( (c==cSep && pc==cQuote)
2015-03-20 09:04:26 -05:00
|| (c==rSep && pc==cQuote)
|| (c==rSep && pc=='\r' && ppc==cQuote)
2013-08-29 08:11:18 -05:00
|| (c==EOF && pc==cQuote)
){
do{ p->n--; }while( p->z[p->n]!=cQuote );
p->cTerm = c;
break;
}
if( pc==cQuote && c!='\r' ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s:%d: unescaped %c character\n",
2013-08-29 08:11:18 -05:00
p->zFile, p->nLine, cQuote);
}
if( c==EOF ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
2013-08-29 08:11:18 -05:00
p->zFile, startLine, cQuote);
2015-03-20 09:04:26 -05:00
p->cTerm = c;
2013-08-29 08:11:18 -05:00
break;
}
2015-03-20 09:04:26 -05:00
import_append_char(p, c);
2014-04-04 10:16:20 -05:00
ppc = pc;
2013-08-29 08:11:18 -05:00
pc = c;
}
}else{
2015-03-20 09:04:26 -05:00
while( c!=EOF && c!=cSep && c!=rSep ){
import_append_char(p, c);
2013-08-29 08:11:18 -05:00
c = fgetc(p->in);
}
2015-03-20 09:04:26 -05:00
if( c==rSep ){
2013-08-29 08:11:18 -05:00
p->nLine++;
2014-04-04 10:16:20 -05:00
if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
2013-08-29 08:11:18 -05:00
}
p->cTerm = c;
}
if( p->z ) p->z[p->n] = 0;
return p->z;
}
2015-03-20 09:04:26 -05:00
/* Read a single field of ASCII delimited text.
**
** + Input comes from p->in.
** + Store results in p->z of length p->n. Space to hold p->z comes
2015-07-10 14:14:29 -05:00
** from sqlite3_malloc64().
2015-03-20 09:04:26 -05:00
** + Use p->cSep as the column separator. The default is "\x1F".
** + Use p->rSep as the row separator. The default is "\x1E".
** + Keep track of the row number in p->nLine.
** + Store the character that terminates the field in p->cTerm. Store
** EOF on end-of-file.
** + Report syntax errors on stderr
*/
2015-07-10 14:14:29 -05:00
static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
2015-03-20 09:04:26 -05:00
int c;
int cSep = p->cColSep;
int rSep = p->cRowSep;
p->n = 0;
c = fgetc(p->in);
if( c==EOF || seenInterrupt ){
p->cTerm = EOF;
return 0;
}
while( c!=EOF && c!=cSep && c!=rSep ){
import_append_char(p, c);
c = fgetc(p->in);
}
if( c==rSep ){
p->nLine++;
}
p->cTerm = c;
if( p->z ) p->z[p->n] = 0;
return p->z;
}
2014-04-04 10:16:20 -05:00
/*
** Try to transfer data for table zTable. If an error is seen while
** moving forward, try to go backwards. The backwards movement won't
** work for WITHOUT ROWID tables.
*/
static void tryToCloneData(
2015-03-20 09:04:26 -05:00
ShellState *p,
2014-04-04 10:16:20 -05:00
sqlite3 *newDb,
const char *zTable
){
2016-12-05 14:29:15 -06:00
sqlite3_stmt *pQuery = 0;
2014-04-04 10:16:20 -05:00
sqlite3_stmt *pInsert = 0;
char *zQuery = 0;
char *zInsert = 0;
int rc;
int i, j, n;
int nTable = (int)strlen(zTable);
int k = 0;
int cnt = 0;
const int spinRate = 10000;
zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error %d: %s on [%s]\n",
2014-04-04 10:16:20 -05:00
sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
zQuery);
goto end_data_xfer;
}
n = sqlite3_column_count(pQuery);
2015-07-10 14:14:29 -05:00
zInsert = sqlite3_malloc64(200 + nTable + n*3);
2014-04-04 10:16:20 -05:00
if( zInsert==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "out of memory\n");
2014-04-04 10:16:20 -05:00
goto end_data_xfer;
}
sqlite3_snprintf(200+nTable,zInsert,
"INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
i = (int)strlen(zInsert);
for(j=1; j<n; j++){
memcpy(zInsert+i, ",?", 2);
i += 2;
}
memcpy(zInsert+i, ");", 3);
rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error %d: %s on [%s]\n",
2014-04-04 10:16:20 -05:00
sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
zQuery);
goto end_data_xfer;
}
for(k=0; k<2; k++){
while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
for(i=0; i<n; i++){
switch( sqlite3_column_type(pQuery, i) ){
case SQLITE_NULL: {
sqlite3_bind_null(pInsert, i+1);
break;
}
case SQLITE_INTEGER: {
sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
break;
}
case SQLITE_FLOAT: {
sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
break;
}
case SQLITE_TEXT: {
sqlite3_bind_text(pInsert, i+1,
(const char*)sqlite3_column_text(pQuery,i),
-1, SQLITE_STATIC);
break;
}
case SQLITE_BLOB: {
sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
sqlite3_column_bytes(pQuery,i),
SQLITE_STATIC);
break;
}
}
} /* End for */
rc = sqlite3_step(pInsert);
if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
2014-04-04 10:16:20 -05:00
sqlite3_errmsg(newDb));
}
sqlite3_reset(pInsert);
cnt++;
if( (cnt%spinRate)==0 ){
printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
fflush(stdout);
}
} /* End while */
if( rc==SQLITE_DONE ) break;
sqlite3_finalize(pQuery);
sqlite3_free(zQuery);
zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
zTable);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
2014-04-04 10:16:20 -05:00
break;
}
} /* End for(k=0...) */
end_data_xfer:
sqlite3_finalize(pQuery);
sqlite3_finalize(pInsert);
sqlite3_free(zQuery);
sqlite3_free(zInsert);
}
/*
** Try to transfer all rows of the schema that match zWhere. For
** each row, invoke xForEach() on the object defined by that row.
** If an error is encountered while moving forward through the
** sqlite_master table, try again moving backwards.
*/
static void tryToCloneSchema(
2015-03-20 09:04:26 -05:00
ShellState *p,
2014-04-04 10:16:20 -05:00
sqlite3 *newDb,
const char *zWhere,
2015-03-20 09:04:26 -05:00
void (*xForEach)(ShellState*,sqlite3*,const char*)
2014-04-04 10:16:20 -05:00
){
sqlite3_stmt *pQuery = 0;
char *zQuery = 0;
int rc;
const unsigned char *zName;
const unsigned char *zSql;
char *zErrMsg = 0;
zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
" WHERE %s", zWhere);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
2014-04-04 10:16:20 -05:00
sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
zQuery);
goto end_schema_xfer;
}
while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
zName = sqlite3_column_text(pQuery, 0);
zSql = sqlite3_column_text(pQuery, 1);
printf("%s... ", zName); fflush(stdout);
sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
if( zErrMsg ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
2014-04-04 10:16:20 -05:00
sqlite3_free(zErrMsg);
zErrMsg = 0;
}
if( xForEach ){
xForEach(p, newDb, (const char*)zName);
}
printf("done\n");
}
if( rc!=SQLITE_DONE ){
sqlite3_finalize(pQuery);
sqlite3_free(zQuery);
zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
" WHERE %s ORDER BY rowid DESC", zWhere);
rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
2014-04-04 10:16:20 -05:00
sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
zQuery);
goto end_schema_xfer;
}
while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
zName = sqlite3_column_text(pQuery, 0);
zSql = sqlite3_column_text(pQuery, 1);
printf("%s... ", zName); fflush(stdout);
sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
if( zErrMsg ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
2014-04-04 10:16:20 -05:00
sqlite3_free(zErrMsg);
zErrMsg = 0;
}
if( xForEach ){
xForEach(p, newDb, (const char*)zName);
}
printf("done\n");
}
}
end_schema_xfer:
sqlite3_finalize(pQuery);
sqlite3_free(zQuery);
}
/*
** Open a new database file named "zNewDb". Try to recover as much information
** as possible out of the main database (which might be corrupt) and write it
** into zNewDb.
*/
2015-03-20 09:04:26 -05:00
static void tryToClone(ShellState *p, const char *zNewDb){
2014-04-04 10:16:20 -05:00
int rc;
sqlite3 *newDb = 0;
if( access(zNewDb,0)==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
2014-04-04 10:16:20 -05:00
return;
}
rc = sqlite3_open(zNewDb, &newDb);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Cannot create output database: %s\n",
2014-04-04 10:16:20 -05:00
sqlite3_errmsg(newDb));
}else{
2014-09-30 08:40:45 -05:00
sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
2014-04-04 10:16:20 -05:00
sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
tryToCloneSchema(p, newDb, "type!='table'", 0);
sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
2014-09-30 08:40:45 -05:00
sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
2014-04-04 10:16:20 -05:00
}
sqlite3_close(newDb);
}
2014-09-30 08:40:45 -05:00
/*
** Change the output file back to stdout
*/
2015-03-20 09:04:26 -05:00
static void output_reset(ShellState *p){
2014-09-30 08:40:45 -05:00
if( p->outfile[0]=='|' ){
2015-07-10 14:14:29 -05:00
#ifndef SQLITE_OMIT_POPEN
2014-09-30 08:40:45 -05:00
pclose(p->out);
2015-07-10 14:14:29 -05:00
#endif
2014-09-30 08:40:45 -05:00
}else{
output_file_close(p->out);
}
p->outfile[0] = 0;
p->out = stdout;
}
2015-07-10 14:14:29 -05:00
/*
** Run an SQL command and return the single integer result.
*/
static int db_int(ShellState *p, const char *zSql){
sqlite3_stmt *pStmt;
int res = 0;
sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
res = sqlite3_column_int(pStmt,0);
}
sqlite3_finalize(pStmt);
return res;
}
/*
** Convert a 2-byte or 4-byte big-endian integer into a native integer
*/
2016-12-05 14:29:15 -06:00
static unsigned int get2byteInt(unsigned char *a){
2015-07-10 14:14:29 -05:00
return (a[0]<<8) + a[1];
}
2016-12-05 14:29:15 -06:00
static unsigned int get4byteInt(unsigned char *a){
2015-07-10 14:14:29 -05:00
return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
}
/*
** Implementation of the ".info" command.
**
** Return 1 on error, 2 to exit, and 0 otherwise.
*/
static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
static const struct { const char *zName; int ofst; } aField[] = {
{ "file change counter:", 24 },
{ "database page count:", 28 },
{ "freelist page count:", 36 },
{ "schema cookie:", 40 },
{ "schema format:", 44 },
{ "default cache size:", 48 },
{ "autovacuum top root:", 52 },
{ "incremental vacuum:", 64 },
{ "text encoding:", 56 },
{ "user version:", 60 },
{ "application id:", 68 },
{ "software version:", 96 },
};
static const struct { const char *zName; const char *zSql; } aQuery[] = {
{ "number of tables:",
"SELECT count(*) FROM %s WHERE type='table'" },
{ "number of indexes:",
"SELECT count(*) FROM %s WHERE type='index'" },
{ "number of triggers:",
"SELECT count(*) FROM %s WHERE type='trigger'" },
{ "number of views:",
"SELECT count(*) FROM %s WHERE type='view'" },
{ "schema size:",
"SELECT total(length(sql)) FROM %s" },
};
2016-02-23 09:07:39 -06:00
sqlite3_file *pFile = 0;
2015-07-10 14:14:29 -05:00
int i;
char *zSchemaTab;
char *zDb = nArg>=2 ? azArg[1] : "main";
unsigned char aHdr[100];
open_db(p, 0);
if( p->db==0 ) return 1;
sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
return 1;
}
i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
if( i!=SQLITE_OK ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "unable to read database header\n");
2015-07-10 14:14:29 -05:00
return 1;
}
i = get2byteInt(aHdr+16);
if( i==1 ) i = 65536;
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
for(i=0; i<ArraySize(aField); i++){
2015-07-10 14:14:29 -05:00
int ofst = aField[i].ofst;
unsigned int val = get4byteInt(aHdr + ofst);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
2015-07-10 14:14:29 -05:00
switch( ofst ){
case 56: {
2016-12-05 14:29:15 -06:00
if( val==1 ) raw_printf(p->out, " (utf8)");
if( val==2 ) raw_printf(p->out, " (utf16le)");
if( val==3 ) raw_printf(p->out, " (utf16be)");
2015-07-10 14:14:29 -05:00
}
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
2015-07-10 14:14:29 -05:00
}
if( zDb==0 ){
zSchemaTab = sqlite3_mprintf("main.sqlite_master");
}else if( strcmp(zDb,"temp")==0 ){
zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
}else{
zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
}
2016-02-23 09:07:39 -06:00
for(i=0; i<ArraySize(aQuery); i++){
2015-07-10 14:14:29 -05:00
char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
int val = db_int(p, zSql);
sqlite3_free(zSql);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
2015-07-10 14:14:29 -05:00
}
sqlite3_free(zSchemaTab);
return 0;
}
2016-02-23 09:07:39 -06:00
/*
** Print the current sqlite3_errmsg() value to stderr and return 1.
*/
static int shellDatabaseError(sqlite3 *db){
const char *zErr = sqlite3_errmsg(db);
utf8_printf(stderr, "Error: %s\n", zErr);
return 1;
}
/*
** Print an out-of-memory message to stderr and return 1.
*/
static int shellNomemError(void){
raw_printf(stderr, "Error: out of memory\n");
return 1;
}
2015-07-10 14:14:29 -05:00
2016-12-05 14:29:15 -06:00
/*
** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
** if they match and FALSE (0) if they do not match.
**
** Globbing rules:
**
** '*' Matches any sequence of zero or more characters.
**
** '?' Matches exactly one character.
**
** [...] Matches one character from the enclosed list of
** characters.
**
** [^...] Matches one character not in the enclosed list.
**
** '#' Matches any sequence of one or more digits with an
** optional + or - sign in front
**
** ' ' Any span of whitespace matches any other span of
** whitespace.
**
** Extra whitespace at the end of z[] is ignored.
*/
static int testcase_glob(const char *zGlob, const char *z){
int c, c2;
int invert;
int seen;
while( (c = (*(zGlob++)))!=0 ){
if( IsSpace(c) ){
if( !IsSpace(*z) ) return 0;
while( IsSpace(*zGlob) ) zGlob++;
while( IsSpace(*z) ) z++;
}else if( c=='*' ){
while( (c=(*(zGlob++))) == '*' || c=='?' ){
if( c=='?' && (*(z++))==0 ) return 0;
}
if( c==0 ){
return 1;
}else if( c=='[' ){
while( *z && testcase_glob(zGlob-1,z)==0 ){
z++;
}
return (*z)!=0;
}
while( (c2 = (*(z++)))!=0 ){
while( c2!=c ){
c2 = *(z++);
if( c2==0 ) return 0;
}
if( testcase_glob(zGlob,z) ) return 1;
}
return 0;
}else if( c=='?' ){
if( (*(z++))==0 ) return 0;
}else if( c=='[' ){
int prior_c = 0;
seen = 0;
invert = 0;
c = *(z++);
if( c==0 ) return 0;
c2 = *(zGlob++);
if( c2=='^' ){
invert = 1;
c2 = *(zGlob++);
}
if( c2==']' ){
if( c==']' ) seen = 1;
c2 = *(zGlob++);
}
while( c2 && c2!=']' ){
if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
c2 = *(zGlob++);
if( c>=prior_c && c<=c2 ) seen = 1;
prior_c = 0;
}else{
if( c==c2 ){
seen = 1;
}
prior_c = c2;
}
c2 = *(zGlob++);
}
if( c2==0 || (seen ^ invert)==0 ) return 0;
}else if( c=='#' ){
if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
if( !IsDigit(z[0]) ) return 0;
z++;
while( IsDigit(z[0]) ){ z++; }
}else{
if( c!=(*(z++)) ) return 0;
}
}
while( IsSpace(*z) ){ z++; }
return *z==0;
}
/*
** Compare the string as a command-line option with either one or two
** initial "-" characters.
*/
static int optionMatch(const char *zStr, const char *zOpt){
if( zStr[0]!='-' ) return 0;
zStr++;
if( zStr[0]=='-' ) zStr++;
return strcmp(zStr, zOpt)==0;
}
/*
** Delete a file.
*/
int shellDeleteFile(const char *zFilename){
int rc;
#ifdef _WIN32
wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
rc = _wunlink(z);
sqlite3_free(z);
#else
rc = unlink(zFilename);
#endif
return rc;
}
2008-07-30 09:15:43 -04:00
/*
** If an input line begins with "." then invoke this routine to
** process that line.
**
** Return 1 on error, 2 to exit, and 0 otherwise.
*/
2015-03-20 09:04:26 -05:00
static int do_meta_command(char *zLine, ShellState *p){
2015-07-10 14:14:29 -05:00
int h = 1;
2008-07-30 09:15:43 -04:00
int nArg = 0;
int n, c;
int rc = 0;
char *azArg[50];
/* Parse the input line into tokens.
*/
2015-07-10 14:14:29 -05:00
while( zLine[h] && nArg<ArraySize(azArg) ){
while( IsSpace(zLine[h]) ){ h++; }
if( zLine[h]==0 ) break;
if( zLine[h]=='\'' || zLine[h]=='"' ){
int delim = zLine[h++];
azArg[nArg++] = &zLine[h];
2016-12-05 14:29:15 -06:00
while( zLine[h] && zLine[h]!=delim ){
2015-07-10 14:14:29 -05:00
if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
2016-12-05 14:29:15 -06:00
h++;
2013-08-29 08:11:18 -05:00
}
2015-07-10 14:14:29 -05:00
if( zLine[h]==delim ){
zLine[h++] = 0;
2008-07-30 09:15:43 -04:00
}
if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
}else{
2015-07-10 14:14:29 -05:00
azArg[nArg++] = &zLine[h];
while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
if( zLine[h] ) zLine[h++] = 0;
2008-07-30 09:15:43 -04:00
resolve_backslashes(azArg[nArg-1]);
}
}
/* Process the input line.
*/
2009-12-03 16:24:07 -05:00
if( nArg==0 ) return 0; /* no tokens, no error */
2009-02-20 15:33:35 -05:00
n = strlen30(azArg[0]);
2008-07-30 09:15:43 -04:00
c = azArg[0][0];
2016-12-05 14:29:15 -06:00
#ifndef SQLITE_OMIT_AUTHORIZATION
if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
if( nArg!=2 ){
raw_printf(stderr, "Usage: .auth ON|OFF\n");
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
if( booleanValue(azArg[1]) ){
sqlite3_set_authorizer(p->db, shellAuth, p);
}else{
sqlite3_set_authorizer(p->db, 0, 0);
}
}else
#endif
2014-04-04 10:16:20 -05:00
if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
|| (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
){
2013-05-21 15:38:11 -05:00
const char *zDestFile = 0;
const char *zDb = 0;
2009-02-20 15:33:35 -05:00
sqlite3 *pDest;
sqlite3_backup *pBackup;
2013-05-21 15:38:11 -05:00
int j;
for(j=1; j<nArg; j++){
const char *z = azArg[j];
if( z[0]=='-' ){
while( z[0]=='-' ) z++;
2013-08-29 08:11:18 -05:00
/* No options to process at this time */
2013-05-21 15:38:11 -05:00
{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
2013-05-21 15:38:11 -05:00
return 1;
}
}else if( zDestFile==0 ){
zDestFile = azArg[j];
}else if( zDb==0 ){
zDb = zDestFile;
zDestFile = azArg[j];
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "too many arguments to .backup\n");
2013-05-21 15:38:11 -05:00
return 1;
}
2009-02-20 15:33:35 -05:00
}
2013-05-21 15:38:11 -05:00
if( zDestFile==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "missing FILENAME argument on .backup\n");
2013-05-21 15:38:11 -05:00
return 1;
}
if( zDb==0 ) zDb = "main";
2009-02-20 15:33:35 -05:00
rc = sqlite3_open(zDestFile, &pDest);
if( rc!=SQLITE_OK ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
2009-02-20 15:33:35 -05:00
sqlite3_close(pDest);
return 1;
}
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2009-02-20 15:33:35 -05:00
pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
if( pBackup==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
2009-02-20 15:33:35 -05:00
sqlite3_close(pDest);
return 1;
}
while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
sqlite3_backup_finish(pBackup);
if( rc==SQLITE_DONE ){
2009-12-03 16:24:07 -05:00
rc = 0;
2009-02-20 15:33:35 -05:00
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
2009-12-03 16:24:07 -05:00
rc = 1;
2009-02-20 15:33:35 -05:00
}
sqlite3_close(pDest);
}else
2014-09-30 08:40:45 -05:00
if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
if( nArg==2 ){
bail_on_error = booleanValue(azArg[1]);
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .bail on|off\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
2008-07-30 09:15:43 -04:00
}else
2015-07-10 14:14:29 -05:00
if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
if( nArg==2 ){
if( booleanValue(azArg[1]) ){
2016-12-05 14:29:15 -06:00
setBinaryMode(p->out, 1);
2015-07-10 14:14:29 -05:00
}else{
2016-12-05 14:29:15 -06:00
setTextMode(p->out, 1);
2015-07-10 14:14:29 -05:00
}
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .binary on|off\n");
2015-07-10 14:14:29 -05:00
rc = 1;
}
}else
2012-05-15 19:05:34 -04:00
/* The undocumented ".breakpoint" command causes a call to the no-op
** routine named test_breakpoint().
*/
if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
test_breakpoint();
}else
2016-02-23 09:07:39 -06:00
if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
if( nArg==2 ){
p->countChanges = booleanValue(azArg[1]);
}else{
raw_printf(stderr, "Usage: .changes on|off\n");
rc = 1;
}
}else
2016-12-05 14:29:15 -06:00
/* Cancel output redirection, if it is currently set (by .testcase)
** Then read the content of the testcase-out.txt file and compare against
** azArg[1]. If there are differences, report an error and exit.
*/
if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
char *zRes = 0;
output_reset(p);
if( nArg!=2 ){
raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
rc = 2;
}else if( (zRes = readFile("testcase-out.txt"))==0 ){
raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
rc = 2;
}else if( testcase_glob(azArg[1],zRes)==0 ){
utf8_printf(stderr,
"testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
p->zTestcase, azArg[1], zRes);
rc = 2;
}else{
utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
p->nCheck++;
}
sqlite3_free(zRes);
}else
2014-09-30 08:40:45 -05:00
if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
if( nArg==2 ){
tryToClone(p, azArg[1]);
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .clone FILENAME\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
2014-04-04 10:16:20 -05:00
}else
2014-09-30 08:40:45 -05:00
if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
2015-03-20 09:04:26 -05:00
ShellState data;
2008-07-30 09:15:43 -04:00
char *zErrMsg = 0;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2008-07-30 09:15:43 -04:00
memcpy(&data, p, sizeof(data));
data.showHeader = 1;
2016-02-23 09:07:39 -06:00
data.cMode = data.mode = MODE_Column;
2008-07-30 09:15:43 -04:00
data.colWidth[0] = 3;
data.colWidth[1] = 15;
data.colWidth[2] = 58;
data.cnt = 0;
sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
if( zErrMsg ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: %s\n", zErrMsg);
2008-07-30 09:15:43 -04:00
sqlite3_free(zErrMsg);
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
}
}else
2015-07-10 14:14:29 -05:00
if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
rc = shell_dbinfo_command(p, nArg, azArg);
}else
2014-09-30 08:40:45 -05:00
if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2009-12-03 16:24:07 -05:00
/* 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. */
2014-09-30 08:40:45 -05:00
if( nArg!=1 && nArg!=2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
raw_printf(p->out, "BEGIN TRANSACTION;\n");
2008-07-30 09:15:43 -04:00
p->writableSchema = 0;
2011-12-26 14:52:17 -05:00
sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
p->nErr = 0;
2008-07-30 09:15:43 -04:00
if( nArg==1 ){
2016-12-05 14:29:15 -06:00
run_schema_dump_query(p,
2008-07-30 09:15:43 -04:00
"SELECT name, type, sql FROM sqlite_master "
2011-12-26 14:52:17 -05:00
"WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
2009-08-11 16:01:51 -04:00
);
2016-12-05 14:29:15 -06:00
run_schema_dump_query(p,
2009-08-11 16:01:51 -04:00
"SELECT name, type, sql FROM sqlite_master "
2011-12-26 14:52:17 -05:00
"WHERE name=='sqlite_sequence'"
2008-07-30 09:15:43 -04:00
);
2011-12-26 14:52:17 -05:00
run_table_dump_query(p,
2008-07-30 09:15:43 -04:00
"SELECT sql FROM sqlite_master "
2009-08-11 16:01:51 -04:00
"WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
2008-07-30 09:15:43 -04:00
);
}else{
int i;
for(i=1; i<nArg; i++){
zShellStatic = azArg[i];
run_schema_dump_query(p,
"SELECT name, type, sql FROM sqlite_master "
"WHERE tbl_name LIKE shellstatic() AND type=='table'"
2011-12-26 14:52:17 -05:00
" AND sql NOT NULL");
run_table_dump_query(p,
2008-07-30 09:15:43 -04:00
"SELECT sql FROM sqlite_master "
"WHERE sql NOT NULL"
" AND type IN ('index','trigger','view')"
2009-08-11 16:01:51 -04:00
" AND tbl_name LIKE shellstatic()", 0
2008-07-30 09:15:43 -04:00
);
zShellStatic = 0;
}
}
if( p->writableSchema ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
2008-07-30 09:15:43 -04:00
p->writableSchema = 0;
}
2011-12-26 14:52:17 -05:00
sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
2008-07-30 09:15:43 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
if( nArg==2 ){
p->echoOn = booleanValue(azArg[1]);
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .echo on|off\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
2008-07-30 09:15:43 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
if( nArg==2 ){
2016-12-05 14:29:15 -06:00
if( strcmp(azArg[1],"full")==0 ){
p->autoEQP = 2;
}else{
p->autoEQP = booleanValue(azArg[1]);
}
2014-09-30 08:40:45 -05:00
}else{
2016-12-05 14:29:15 -06:00
raw_printf(stderr, "Usage: .eqp on|off|full\n");
2014-09-30 08:40:45 -05:00
rc = 1;
2016-12-05 14:29:15 -06:00
}
2014-04-04 10:16:20 -05:00
}else
2013-05-21 15:38:11 -05:00
if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
2013-08-29 08:11:18 -05:00
if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
2008-07-30 09:15:43 -04:00
rc = 2;
}else
2014-09-30 08:40:45 -05:00
if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
2016-02-23 09:07:39 -06:00
int val = 1;
if( nArg>=2 ){
if( strcmp(azArg[1],"auto")==0 ){
val = 99;
}else{
val = booleanValue(azArg[1]);
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
}
if( val==1 && p->mode!=MODE_Explain ){
p->normalMode = p->mode;
2008-07-30 09:15:43 -04:00
p->mode = MODE_Explain;
2016-02-23 09:07:39 -06:00
p->autoExplain = 0;
}else if( val==0 ){
if( p->mode==MODE_Explain ) p->mode = p->normalMode;
p->autoExplain = 0;
}else if( val==99 ){
if( p->mode==MODE_Explain ) p->mode = p->normalMode;
p->autoExplain = 1;
2008-07-30 09:15:43 -04:00
}
}else
2014-09-30 08:40:45 -05:00
if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
2015-03-20 09:04:26 -05:00
ShellState data;
2014-09-30 08:40:45 -05:00
char *zErrMsg = 0;
int doStats = 0;
2016-12-05 14:29:15 -06:00
memcpy(&data, p, sizeof(data));
data.showHeader = 0;
data.cMode = data.mode = MODE_Semi;
if( nArg==2 && optionMatch(azArg[1], "indent") ){
data.cMode = data.mode = MODE_Pretty;
nArg = 1;
}
2014-09-30 08:40:45 -05:00
if( nArg!=1 ){
2016-12-05 14:29:15 -06:00
raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
rc = sqlite3_exec(p->db,
"SELECT sql FROM"
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
" FROM sqlite_master UNION ALL"
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2015-03-20 09:04:26 -05:00
"WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
2014-09-30 08:40:45 -05:00
"ORDER BY rowid",
callback, &data, &zErrMsg
);
if( rc==SQLITE_OK ){
sqlite3_stmt *pStmt;
rc = sqlite3_prepare_v2(p->db,
"SELECT rowid FROM sqlite_master"
" WHERE name GLOB 'sqlite_stat[134]'",
-1, &pStmt, 0);
doStats = sqlite3_step(pStmt)==SQLITE_ROW;
sqlite3_finalize(pStmt);
}
if( doStats==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "/* No STAT tables available */\n");
2014-09-30 08:40:45 -05:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "ANALYZE sqlite_master;\n");
2014-09-30 08:40:45 -05:00
sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
callback, &data, &zErrMsg);
2016-02-23 09:07:39 -06:00
data.cMode = data.mode = MODE_Insert;
2014-09-30 08:40:45 -05:00
data.zDestTable = "sqlite_stat1";
shell_exec(p->db, "SELECT * FROM sqlite_stat1",
shell_callback, &data,&zErrMsg);
data.zDestTable = "sqlite_stat3";
shell_exec(p->db, "SELECT * FROM sqlite_stat3",
shell_callback, &data,&zErrMsg);
data.zDestTable = "sqlite_stat4";
shell_exec(p->db, "SELECT * FROM sqlite_stat4",
shell_callback, &data, &zErrMsg);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "ANALYZE sqlite_master;\n");
2009-12-03 16:24:07 -05:00
}
2008-07-30 09:15:43 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
if( nArg==2 ){
p->showHeader = booleanValue(azArg[1]);
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .headers on|off\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
}else
if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", zHelp);
2014-09-30 08:40:45 -05:00
}else
if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
char *zTable; /* Insert data into this table */
char *zFile; /* Name of file to extra content from */
2009-12-03 16:24:07 -05:00
sqlite3_stmt *pStmt = NULL; /* A statement */
2008-07-30 09:15:43 -04:00
int nCol; /* Number of columns in the table */
int nByte; /* Number of bytes in an SQL string */
int i, j; /* Loop counters */
2013-08-29 08:11:18 -05:00
int needCommit; /* True to COMMIT or ROLLBACK at end */
2015-03-20 09:04:26 -05:00
int nSep; /* Number of bytes in p->colSeparator[] */
2008-07-30 09:15:43 -04:00
char *zSql; /* An SQL statement */
2015-03-20 09:04:26 -05:00
ImportCtx sCtx; /* Reader context */
2015-07-10 14:14:29 -05:00
char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
2008-07-30 09:15:43 -04:00
2014-09-30 08:40:45 -05:00
if( nArg!=3 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .import FILE TABLE\n");
2014-09-30 08:40:45 -05:00
goto meta_command_exit;
}
zFile = azArg[1];
zTable = azArg[2];
2013-08-29 08:11:18 -05:00
seenInterrupt = 0;
2015-03-20 09:04:26 -05:00
memset(&sCtx, 0, sizeof(sCtx));
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2015-03-20 09:04:26 -05:00
nSep = strlen30(p->colSeparator);
2008-07-30 09:15:43 -04:00
if( nSep==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr,
"Error: non-null column separator required for import\n");
2009-12-03 16:24:07 -05:00
return 1;
2008-07-30 09:15:43 -04:00
}
2013-08-29 08:11:18 -05:00
if( nSep>1 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: multi-character column separators not allowed"
2013-08-29 08:11:18 -05:00
" for import\n");
return 1;
}
2015-03-20 09:04:26 -05:00
nSep = strlen30(p->rowSeparator);
if( nSep==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: non-null row separator required for import\n");
2015-03-20 09:04:26 -05:00
return 1;
}
if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
/* When importing CSV (only), if the row separator is set to the
** default output row separator, change it to the default input
** row separator. This avoids having to maintain different input
** and output row separators. */
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
nSep = strlen30(p->rowSeparator);
}
if( nSep>1 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: multi-character row separators not allowed"
2015-03-20 09:04:26 -05:00
" for import\n");
return 1;
}
sCtx.zFile = zFile;
sCtx.nLine = 1;
if( sCtx.zFile[0]=='|' ){
2015-07-10 14:14:29 -05:00
#ifdef SQLITE_OMIT_POPEN
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: pipes are not supported in this OS\n");
2015-07-10 14:14:29 -05:00
return 1;
#else
2015-03-20 09:04:26 -05:00
sCtx.in = popen(sCtx.zFile+1, "r");
sCtx.zFile = "<pipe>";
2013-08-29 08:11:18 -05:00
xCloser = pclose;
2015-07-10 14:14:29 -05:00
#endif
2013-08-29 08:11:18 -05:00
}else{
2015-03-20 09:04:26 -05:00
sCtx.in = fopen(sCtx.zFile, "rb");
2013-08-29 08:11:18 -05:00
xCloser = fclose;
}
2015-03-20 09:04:26 -05:00
if( p->mode==MODE_Ascii ){
xRead = ascii_read_one_field;
}else{
xRead = csv_read_one_field;
}
if( sCtx.in==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
2013-08-29 08:11:18 -05:00
return 1;
}
2015-03-20 09:04:26 -05:00
sCtx.cColSep = p->colSeparator[0];
sCtx.cRowSep = p->rowSeparator[0];
2011-12-26 14:52:17 -05:00
zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
2009-12-03 16:24:07 -05:00
if( zSql==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: out of memory\n");
2015-03-20 09:04:26 -05:00
xCloser(sCtx.in);
2009-12-03 16:24:07 -05:00
return 1;
}
2009-02-20 15:33:35 -05:00
nByte = strlen30(zSql);
2014-04-04 10:16:20 -05:00
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2015-03-20 09:04:26 -05:00
import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
2015-07-10 14:14:29 -05:00
if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
2013-08-29 08:11:18 -05:00
char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
char cSep = '(';
2015-03-20 09:04:26 -05:00
while( xRead(&sCtx) ){
2016-12-05 14:29:15 -06:00
zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
2013-08-29 08:11:18 -05:00
cSep = ',';
2015-03-20 09:04:26 -05:00
if( sCtx.cTerm!=sCtx.cColSep ) break;
2013-08-29 08:11:18 -05:00
}
if( cSep=='(' ){
sqlite3_free(zCreate);
2015-03-20 09:04:26 -05:00
sqlite3_free(sCtx.z);
xCloser(sCtx.in);
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
2013-08-29 08:11:18 -05:00
return 1;
}
zCreate = sqlite3_mprintf("%z\n)", zCreate);
rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
sqlite3_free(zCreate);
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
2015-07-10 14:14:29 -05:00
sqlite3_errmsg(p->db));
2015-03-20 09:04:26 -05:00
sqlite3_free(sCtx.z);
xCloser(sCtx.in);
2013-08-29 08:11:18 -05:00
return 1;
}
2014-04-04 10:16:20 -05:00
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2013-08-29 08:11:18 -05:00
}
2008-07-30 09:15:43 -04:00
sqlite3_free(zSql);
if( rc ){
2009-12-03 16:24:07 -05:00
if (pStmt) sqlite3_finalize(pStmt);
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
2015-03-20 09:04:26 -05:00
xCloser(sCtx.in);
2009-12-03 16:24:07 -05:00
return 1;
2008-07-30 09:15:43 -04:00
}
2009-12-03 16:24:07 -05:00
nCol = sqlite3_column_count(pStmt);
2008-07-30 09:15:43 -04:00
sqlite3_finalize(pStmt);
2009-12-03 16:24:07 -05:00
pStmt = 0;
if( nCol==0 ) return 0; /* no columns, no error */
2015-07-10 14:14:29 -05:00
zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
2009-12-03 16:24:07 -05:00
if( zSql==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: out of memory\n");
2015-03-20 09:04:26 -05:00
xCloser(sCtx.in);
2009-12-03 16:24:07 -05:00
return 1;
}
2013-08-29 08:11:18 -05:00
sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
2009-02-20 15:33:35 -05:00
j = strlen30(zSql);
2008-07-30 09:15:43 -04:00
for(i=1; i<nCol; i++){
zSql[j++] = ',';
zSql[j++] = '?';
}
zSql[j++] = ')';
zSql[j] = 0;
2014-04-04 10:16:20 -05:00
rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2013-08-29 08:11:18 -05:00
sqlite3_free(zSql);
2008-07-30 09:15:43 -04:00
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2009-12-03 16:24:07 -05:00
if (pStmt) sqlite3_finalize(pStmt);
2015-03-20 09:04:26 -05:00
xCloser(sCtx.in);
2008-07-30 09:15:43 -04:00
return 1;
}
2015-07-10 14:14:29 -05:00
needCommit = sqlite3_get_autocommit(p->db);
if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
2013-08-29 08:11:18 -05:00
do{
2015-03-20 09:04:26 -05:00
int startLine = sCtx.nLine;
2008-07-30 09:15:43 -04:00
for(i=0; i<nCol; i++){
2015-03-20 09:04:26 -05:00
char *z = xRead(&sCtx);
/*
** Did we reach end-of-file before finding any columns?
** If so, stop instead of NULL filling the remaining columns.
*/
2013-08-29 08:11:18 -05:00
if( z==0 && i==0 ) break;
2015-03-20 09:04:26 -05:00
/*
** Did we reach end-of-file OR end-of-line before finding any
** columns in ASCII mode? If so, stop instead of NULL filling
** the remaining columns.
*/
if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
2013-08-29 08:11:18 -05:00
sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
2015-03-20 09:04:26 -05:00
if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
2013-08-29 08:11:18 -05:00
"filling the rest with NULL\n",
2015-03-20 09:04:26 -05:00
sCtx.zFile, startLine, nCol, i+1);
2015-07-10 14:14:29 -05:00
i += 2;
2014-09-30 08:40:45 -05:00
while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
2012-05-15 19:05:34 -04:00
}
2008-07-30 09:15:43 -04:00
}
2015-03-20 09:04:26 -05:00
if( sCtx.cTerm==sCtx.cColSep ){
2013-08-29 08:11:18 -05:00
do{
2015-03-20 09:04:26 -05:00
xRead(&sCtx);
2013-08-29 08:11:18 -05:00
i++;
2015-03-20 09:04:26 -05:00
}while( sCtx.cTerm==sCtx.cColSep );
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
2013-08-29 08:11:18 -05:00
"extras ignored\n",
2015-03-20 09:04:26 -05:00
sCtx.zFile, startLine, nCol, i);
2008-07-30 09:15:43 -04:00
}
2013-08-29 08:11:18 -05:00
if( i>=nCol ){
sqlite3_step(pStmt);
rc = sqlite3_reset(pStmt);
if( rc!=SQLITE_OK ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
startLine, sqlite3_errmsg(p->db));
2013-08-29 08:11:18 -05:00
}
}
2015-03-20 09:04:26 -05:00
}while( sCtx.cTerm!=EOF );
2013-08-29 08:11:18 -05:00
2015-03-20 09:04:26 -05:00
xCloser(sCtx.in);
sqlite3_free(sCtx.z);
2008-07-30 09:15:43 -04:00
sqlite3_finalize(pStmt);
2015-07-10 14:14:29 -05:00
if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
2008-07-30 09:15:43 -04:00
}else
2015-07-10 14:14:29 -05:00
if( c=='i' && (strncmp(azArg[0], "indices", n)==0
|| strncmp(azArg[0], "indexes", n)==0) ){
2015-03-20 09:04:26 -05:00
ShellState data;
2008-07-30 09:15:43 -04:00
char *zErrMsg = 0;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2008-07-30 09:15:43 -04:00
memcpy(&data, p, sizeof(data));
data.showHeader = 0;
2016-02-23 09:07:39 -06:00
data.cMode = data.mode = MODE_List;
2009-12-03 16:24:07 -05:00
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
);
2014-09-30 08:40:45 -05:00
}else if( nArg==2 ){
2009-12-03 16:24:07 -05:00
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;
2014-09-30 08:40:45 -05:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
2009-12-03 16:24:07 -05:00
}
2008-07-30 09:15:43 -04:00
if( zErrMsg ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: %s\n", zErrMsg);
2008-07-30 09:15:43 -04:00
sqlite3_free(zErrMsg);
2009-12-03 16:24:07 -05:00
rc = 1;
}else if( rc != SQLITE_OK ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr,
"Error: querying sqlite_master and sqlite_temp_master\n");
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
}
}else
#ifdef SQLITE_ENABLE_IOTRACE
if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
2015-07-10 14:14:29 -05:00
SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
2008-07-30 09:15:43 -04:00
if( iotrace && iotrace!=stdout ) fclose(iotrace);
iotrace = 0;
if( nArg<2 ){
sqlite3IoTrace = 0;
}else if( strcmp(azArg[1], "-")==0 ){
sqlite3IoTrace = iotracePrintf;
iotrace = stdout;
}else{
iotrace = fopen(azArg[1], "w");
if( iotrace==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
2008-07-30 09:15:43 -04:00
sqlite3IoTrace = 0;
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
}else{
sqlite3IoTrace = iotracePrintf;
}
}
}else
#endif
2015-07-10 14:14:29 -05:00
if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
static const struct {
const char *zLimitName; /* Name of a limit */
int limitCode; /* Integer code for that limit */
} aLimit[] = {
{ "length", SQLITE_LIMIT_LENGTH },
{ "sql_length", SQLITE_LIMIT_SQL_LENGTH },
{ "column", SQLITE_LIMIT_COLUMN },
{ "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
{ "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
{ "vdbe_op", SQLITE_LIMIT_VDBE_OP },
{ "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
{ "attached", SQLITE_LIMIT_ATTACHED },
{ "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
{ "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
{ "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
{ "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
};
int i, n2;
open_db(p, 0);
if( nArg==1 ){
2016-02-23 09:07:39 -06:00
for(i=0; i<ArraySize(aLimit); i++){
2016-12-05 14:29:15 -06:00
printf("%20s %d\n", aLimit[i].zLimitName,
2015-07-10 14:14:29 -05:00
sqlite3_limit(p->db, aLimit[i].limitCode, -1));
}
}else if( nArg>3 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
2015-07-10 14:14:29 -05:00
rc = 1;
goto meta_command_exit;
}else{
int iLimit = -1;
n2 = strlen30(azArg[1]);
2016-02-23 09:07:39 -06:00
for(i=0; i<ArraySize(aLimit); i++){
2015-07-10 14:14:29 -05:00
if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
if( iLimit<0 ){
iLimit = i;
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
2015-07-10 14:14:29 -05:00
rc = 1;
goto meta_command_exit;
}
}
}
if( iLimit<0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "unknown limit: \"%s\"\n"
2015-07-10 14:14:29 -05:00
"enter \".limits\" with no arguments for a list.\n",
azArg[1]);
rc = 1;
goto meta_command_exit;
}
if( nArg==3 ){
sqlite3_limit(p->db, aLimit[iLimit].limitCode,
(int)integerValue(azArg[2]));
}
printf("%20s %d\n", aLimit[iLimit].zLimitName,
sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
}
}else
2008-07-30 09:15:43 -04:00
#ifndef SQLITE_OMIT_LOAD_EXTENSION
2014-09-30 08:40:45 -05:00
if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
2008-07-30 09:15:43 -04:00
const char *zFile, *zProc;
char *zErrMsg = 0;
2014-09-30 08:40:45 -05:00
if( nArg<2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
2008-07-30 09:15:43 -04:00
zFile = azArg[1];
zProc = nArg>=3 ? azArg[2] : 0;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2008-07-30 09:15:43 -04:00
rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
if( rc!=SQLITE_OK ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\n", zErrMsg);
2008-07-30 09:15:43 -04:00
sqlite3_free(zErrMsg);
rc = 1;
}
}else
#endif
2014-09-30 08:40:45 -05:00
if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
if( nArg!=2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .log FILENAME\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}else{
const char *zFile = azArg[1];
output_file_close(p->pLog);
p->pLog = output_file_open(zFile);
}
2010-05-18 12:22:17 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
const char *zMode = nArg>=2 ? azArg[1] : "";
int n2 = (int)strlen(zMode);
int c2 = zMode[0];
if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_Line;
2014-09-30 08:40:45 -05:00
}else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_Column;
2014-09-30 08:40:45 -05:00
}else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_List;
2014-09-30 08:40:45 -05:00
}else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_Html;
2014-09-30 08:40:45 -05:00
}else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_Tcl;
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
2014-09-30 08:40:45 -05:00
}else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_Csv;
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
2014-09-30 08:40:45 -05:00
}else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_List;
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
2014-09-30 08:40:45 -05:00
}else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
2008-07-30 09:15:43 -04:00
p->mode = MODE_Insert;
2014-09-30 08:40:45 -05:00
set_table_name(p, nArg>=3 ? azArg[2] : "table");
2015-03-20 09:04:26 -05:00
}else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
p->mode = MODE_Ascii;
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
2008-07-30 09:15:43 -04:00
}else {
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: mode should be one of: "
2015-03-20 09:04:26 -05:00
"ascii column csv html insert line list tabs tcl\n");
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
p->cMode = p->mode;
2008-07-30 09:15:43 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
if( nArg==2 ){
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
"%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
2014-09-30 08:40:45 -05:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .nullvalue STRING\n");
2009-12-19 15:56:40 -05:00
rc = 1;
}
}else
2014-04-04 10:16:20 -05:00
if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
2016-12-05 14:29:15 -06:00
char *zNewFilename; /* Name of the database file to open */
int iName = 1; /* Index in azArg[] of the filename */
int newFlag = 0; /* True to delete file before opening */
/* Close the existing database */
session_close_all(p);
sqlite3_close(p->db);
2014-04-04 10:16:20 -05:00
p->db = 0;
2016-12-05 14:29:15 -06:00
sqlite3_free(p->zFreeOnClose);
p->zFreeOnClose = 0;
/* Check for command-line arguments */
for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
const char *z = azArg[iName];
if( optionMatch(z,"new") ){
newFlag = 1;
}else if( z[0]=='-' ){
utf8_printf(stderr, "unknown option: %s\n", z);
rc = 1;
goto meta_command_exit;
}
}
/* If a filename is specified, try to open it first */
zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
if( zNewFilename ){
if( newFlag ) shellDeleteFile(zNewFilename);
p->zDbFilename = zNewFilename;
open_db(p, 1);
if( p->db==0 ){
utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
sqlite3_free(zNewFilename);
}else{
p->zFreeOnClose = zNewFilename;
}
}
if( p->db==0 ){
/* As a fall-back open a TEMP database */
p->zDbFilename = 0;
open_db(p, 0);
2014-04-04 10:16:20 -05:00
}
}else
2014-09-30 08:40:45 -05:00
if( c=='o'
&& (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
){
const char *zFile = nArg>=2 ? azArg[1] : "stdout";
if( nArg>2 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
2012-05-15 19:05:34 -04:00
}
2014-09-30 08:40:45 -05:00
if( n>1 && strncmp(azArg[0], "once", n)==0 ){
if( nArg<2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .once FILE\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
p->outCount = 2;
}else{
p->outCount = 0;
}
output_reset(p);
if( zFile[0]=='|' ){
2015-07-10 14:14:29 -05:00
#ifdef SQLITE_OMIT_POPEN
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: pipes are not supported in this OS\n");
2015-07-10 14:14:29 -05:00
rc = 1;
p->out = stdout;
#else
2014-09-30 08:40:45 -05:00
p->out = popen(zFile + 1, "w");
2008-07-30 09:15:43 -04:00
if( p->out==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
2012-05-15 19:05:34 -04:00
p->out = stdout;
rc = 1;
}else{
2014-09-30 08:40:45 -05:00
sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
2012-05-15 19:05:34 -04:00
}
2015-07-10 14:14:29 -05:00
#endif
2012-05-15 19:05:34 -04:00
}else{
2014-09-30 08:40:45 -05:00
p->out = output_file_open(zFile);
2012-05-15 19:05:34 -04:00
if( p->out==0 ){
2014-09-30 08:40:45 -05:00
if( strcmp(zFile,"off")!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
2012-05-15 19:05:34 -04:00
}
2008-07-30 09:15:43 -04:00
p->out = stdout;
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
} else {
2014-09-30 08:40:45 -05:00
sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
2008-07-30 09:15:43 -04:00
}
}
}else
2013-01-15 16:38:05 -06:00
if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
int i;
for(i=1; i<nArg; i++){
2016-02-23 09:07:39 -06:00
if( i>1 ) raw_printf(p->out, " ");
utf8_printf(p->out, "%s", azArg[i]);
2013-01-15 16:38:05 -06:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
2013-01-15 16:38:05 -06:00
}else
2014-09-30 08:40:45 -05:00
if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
2008-07-30 09:15:43 -04:00
if( nArg >= 2) {
strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
}
if( nArg >= 3) {
strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
}
}else
2014-09-30 08:40:45 -05:00
if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
2008-07-30 09:15:43 -04:00
rc = 2;
}else
2014-09-30 08:40:45 -05:00
if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
FILE *alt;
if( nArg!=2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .read FILE\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
alt = fopen(azArg[1], "rb");
2008-07-30 09:15:43 -04:00
if( alt==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
}else{
2009-12-03 16:24:07 -05:00
rc = process_input(p, alt);
2008-07-30 09:15:43 -04:00
fclose(alt);
}
}else
2014-09-30 08:40:45 -05:00
if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
2009-02-20 15:33:35 -05:00
const char *zSrcFile;
const char *zDb;
sqlite3 *pSrc;
sqlite3_backup *pBackup;
int nTimeout = 0;
if( nArg==2 ){
zSrcFile = azArg[1];
zDb = "main";
2014-09-30 08:40:45 -05:00
}else if( nArg==3 ){
2009-02-20 15:33:35 -05:00
zSrcFile = azArg[2];
zDb = azArg[1];
2014-09-30 08:40:45 -05:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
2009-02-20 15:33:35 -05:00
}
rc = sqlite3_open(zSrcFile, &pSrc);
if( rc!=SQLITE_OK ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
2009-02-20 15:33:35 -05:00
sqlite3_close(pSrc);
return 1;
}
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2009-02-20 15:33:35 -05:00
pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
if( pBackup==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2009-02-20 15:33:35 -05:00
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 ){
2009-12-03 16:24:07 -05:00
rc = 0;
2009-02-20 15:33:35 -05:00
}else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: source database is busy\n");
2009-12-03 16:24:07 -05:00
rc = 1;
2009-02-20 15:33:35 -05:00
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
2009-12-03 16:24:07 -05:00
rc = 1;
2009-02-20 15:33:35 -05:00
}
sqlite3_close(pSrc);
}else
2015-03-20 09:04:26 -05:00
if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
if( nArg==2 ){
p->scanstatsOn = booleanValue(azArg[1]);
#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
2015-03-20 09:04:26 -05:00
#endif
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .scanstats on|off\n");
2015-03-20 09:04:26 -05:00
rc = 1;
}
}else
2014-09-30 08:40:45 -05:00
if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
2015-03-20 09:04:26 -05:00
ShellState data;
2008-07-30 09:15:43 -04:00
char *zErrMsg = 0;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2008-07-30 09:15:43 -04:00
memcpy(&data, p, sizeof(data));
data.showHeader = 0;
2016-02-23 09:07:39 -06:00
data.cMode = data.mode = MODE_Semi;
2016-12-05 14:29:15 -06:00
if( nArg>=2 && optionMatch(azArg[1], "indent") ){
data.cMode = data.mode = MODE_Pretty;
nArg--;
if( nArg==2 ) azArg[1] = azArg[2];
}
if( nArg==2 && azArg[1][0]!='-' ){
2008-07-30 09:15:43 -04:00
int i;
2011-12-26 14:52:17 -05:00
for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
2008-07-30 09:15:43 -04:00
if( strcmp(azArg[1],"sqlite_master")==0 ){
char *new_argv[2], *new_colv[2];
new_argv[0] = "CREATE TABLE sqlite_master (\n"
" type text,\n"
" name text,\n"
" tbl_name text,\n"
" rootpage integer,\n"
" sql text\n"
")";
new_argv[1] = 0;
new_colv[0] = "sql";
new_colv[1] = 0;
callback(&data, 1, new_argv, new_colv);
2009-12-03 16:24:07 -05:00
rc = SQLITE_OK;
2008-07-30 09:15:43 -04:00
}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"
" type text,\n"
" name text,\n"
" tbl_name text,\n"
" rootpage integer,\n"
" sql text\n"
")";
new_argv[1] = 0;
new_colv[0] = "sql";
new_colv[1] = 0;
callback(&data, 1, new_argv, new_colv);
2009-12-03 16:24:07 -05:00
rc = SQLITE_OK;
2008-07-30 09:15:43 -04:00
}else{
zShellStatic = azArg[1];
2009-12-03 16:24:07 -05:00
rc = sqlite3_exec(p->db,
2008-07-30 09:15:43 -04:00
"SELECT sql FROM "
2012-05-23 09:26:02 -04:00
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
2009-02-20 15:33:35 -05:00
" FROM sqlite_master UNION ALL"
2012-05-23 09:26:02 -04:00
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2012-01-18 00:18:26 -05:00
"WHERE lower(tbl_name) LIKE shellstatic()"
" AND type!='meta' AND sql NOTNULL "
2013-05-21 15:38:11 -05:00
"ORDER BY rowid",
2008-07-30 09:15:43 -04:00
callback, &data, &zErrMsg);
zShellStatic = 0;
}
2014-09-30 08:40:45 -05:00
}else if( nArg==1 ){
2009-12-03 16:24:07 -05:00
rc = sqlite3_exec(p->db,
2008-07-30 09:15:43 -04:00
"SELECT sql FROM "
2012-05-23 09:26:02 -04:00
" (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
2009-02-20 15:33:35 -05:00
" FROM sqlite_master UNION ALL"
2012-05-23 09:26:02 -04:00
" SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
2015-03-20 09:04:26 -05:00
"WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
2013-05-21 15:38:11 -05:00
"ORDER BY rowid",
2008-07-30 09:15:43 -04:00
callback, &data, &zErrMsg
);
2014-09-30 08:40:45 -05:00
}else{
2016-12-05 14:29:15 -06:00
raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
2008-07-30 09:15:43 -04:00
}
if( zErrMsg ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: %s\n", zErrMsg);
2008-07-30 09:15:43 -04:00
sqlite3_free(zErrMsg);
2009-12-03 16:24:07 -05:00
rc = 1;
}else if( rc != SQLITE_OK ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr,"Error: querying schema information\n");
2009-12-03 16:24:07 -05:00
rc = 1;
}else{
rc = 0;
2008-07-30 09:15:43 -04:00
}
}else
2015-03-20 09:04:26 -05:00
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
2015-07-10 14:14:29 -05:00
sqlite3SelectTrace = integerValue(azArg[1]);
2015-03-20 09:04:26 -05:00
}else
#endif
2016-12-05 14:29:15 -06:00
#if defined(SQLITE_ENABLE_SESSION)
if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
OpenSession *pSession = &p->aSession[0];
char **azCmd = &azArg[1];
int iSes = 0;
int nCmd = nArg - 1;
int i;
if( nArg<=1 ) goto session_syntax_error;
open_db(p, 0);
if( nArg>=3 ){
for(iSes=0; iSes<p->nSession; iSes++){
if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
}
if( iSes<p->nSession ){
pSession = &p->aSession[iSes];
azCmd++;
nCmd--;
}else{
pSession = &p->aSession[0];
iSes = 0;
}
}
/* .session attach TABLE
** Invoke the sqlite3session_attach() interface to attach a particular
** table so that it is never filtered.
*/
if( strcmp(azCmd[0],"attach")==0 ){
if( nCmd!=2 ) goto session_syntax_error;
if( pSession->p==0 ){
session_not_open:
raw_printf(stderr, "ERROR: No sessions are open\n");
}else{
rc = sqlite3session_attach(pSession->p, azCmd[1]);
if( rc ){
raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
rc = 0;
}
}
}else
/* .session changeset FILE
** .session patchset FILE
** Write a changeset or patchset into a file. The file is overwritten.
*/
if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
FILE *out = 0;
if( nCmd!=2 ) goto session_syntax_error;
if( pSession->p==0 ) goto session_not_open;
out = fopen(azCmd[1], "wb");
if( out==0 ){
utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
}else{
int szChng;
void *pChng;
if( azCmd[0][0]=='c' ){
rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
}else{
rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
}
if( rc ){
printf("Error: error code %d\n", rc);
rc = 0;
}
if( pChng
&& fwrite(pChng, szChng, 1, out)!=1 ){
raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
szChng);
}
sqlite3_free(pChng);
fclose(out);
}
}else
/* .session close
** Close the identified session
*/
if( strcmp(azCmd[0], "close")==0 ){
if( nCmd!=1 ) goto session_syntax_error;
if( p->nSession ){
session_close(pSession);
p->aSession[iSes] = p->aSession[--p->nSession];
}
}else
/* .session enable ?BOOLEAN?
** Query or set the enable flag
*/
if( strcmp(azCmd[0], "enable")==0 ){
int ii;
if( nCmd>2 ) goto session_syntax_error;
ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
if( p->nSession ){
ii = sqlite3session_enable(pSession->p, ii);
utf8_printf(p->out, "session %s enable flag = %d\n",
pSession->zName, ii);
}
}else
/* .session filter GLOB ....
** Set a list of GLOB patterns of table names to be excluded.
*/
if( strcmp(azCmd[0], "filter")==0 ){
int ii, nByte;
if( nCmd<2 ) goto session_syntax_error;
if( p->nSession ){
for(ii=0; ii<pSession->nFilter; ii++){
sqlite3_free(pSession->azFilter[ii]);
}
sqlite3_free(pSession->azFilter);
nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
pSession->azFilter = sqlite3_malloc( nByte );
if( pSession->azFilter==0 ){
raw_printf(stderr, "Error: out or memory\n");
exit(1);
}
for(ii=1; ii<nCmd; ii++){
pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
}
pSession->nFilter = ii-1;
}
}else
/* .session indirect ?BOOLEAN?
** Query or set the indirect flag
*/
if( strcmp(azCmd[0], "indirect")==0 ){
int ii;
if( nCmd>2 ) goto session_syntax_error;
ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
if( p->nSession ){
ii = sqlite3session_indirect(pSession->p, ii);
utf8_printf(p->out, "session %s indirect flag = %d\n",
pSession->zName, ii);
}
}else
/* .session isempty
** Determine if the session is empty
*/
if( strcmp(azCmd[0], "isempty")==0 ){
int ii;
if( nCmd!=1 ) goto session_syntax_error;
if( p->nSession ){
ii = sqlite3session_isempty(pSession->p);
utf8_printf(p->out, "session %s isempty flag = %d\n",
pSession->zName, ii);
}
}else
/* .session list
** List all currently open sessions
*/
if( strcmp(azCmd[0],"list")==0 ){
for(i=0; i<p->nSession; i++){
utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
}
}else
/* .session open DB NAME
** Open a new session called NAME on the attached database DB.
** DB is normally "main".
*/
if( strcmp(azCmd[0],"open")==0 ){
char *zName;
if( nCmd!=3 ) goto session_syntax_error;
zName = azCmd[2];
if( zName[0]==0 ) goto session_syntax_error;
for(i=0; i<p->nSession; i++){
if( strcmp(p->aSession[i].zName,zName)==0 ){
utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
goto meta_command_exit;
}
}
if( p->nSession>=ArraySize(p->aSession) ){
raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
goto meta_command_exit;
}
pSession = &p->aSession[p->nSession];
rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
if( rc ){
raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
rc = 0;
goto meta_command_exit;
}
pSession->nFilter = 0;
sqlite3session_table_filter(pSession->p, session_filter, pSession);
p->nSession++;
pSession->zName = sqlite3_mprintf("%s", zName);
}else
/* If no command name matches, show a syntax error */
session_syntax_error:
session_help(p);
}else
#endif
2015-03-20 09:04:26 -05:00
2013-08-29 08:11:18 -05:00
#ifdef SQLITE_DEBUG
/* Undocumented commands for internal testing. Subject to change
** without notice. */
if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
int i, v;
for(i=1; i<nArg; i++){
v = booleanValue(azArg[i]);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
2013-08-29 08:11:18 -05:00
}
}
if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
int i; sqlite3_int64 v;
for(i=1; i<nArg; i++){
char zBuf[200];
v = integerValue(azArg[i]);
2014-09-30 08:40:45 -05:00
sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s", zBuf);
2013-08-29 08:11:18 -05:00
}
}
}else
#endif
2014-09-30 08:40:45 -05:00
if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
if( nArg<2 || nArg>3 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
if( nArg>=2 ){
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
"%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
2014-09-30 08:40:45 -05:00
}
if( nArg>=3 ){
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
"%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
2014-09-30 08:40:45 -05:00
}
2008-07-30 09:15:43 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='s'
&& (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
){
char *zCmd;
int i, x;
if( nArg<2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .system COMMAND\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
for(i=2; i<nArg; i++){
zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
zCmd, azArg[i]);
}
x = system(zCmd);
sqlite3_free(zCmd);
2016-02-23 09:07:39 -06:00
if( x ) raw_printf(stderr, "System command returns %d\n", x);
2014-09-30 08:40:45 -05:00
}else
if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
2016-12-05 14:29:15 -06:00
static const char *azBool[] = { "off", "on", "full", "unk" };
2008-07-30 09:15:43 -04:00
int i;
2014-09-30 08:40:45 -05:00
if( nArg!=1 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .show\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
2016-12-05 14:29:15 -06:00
utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[p->echoOn!=0]);
utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%12.12s: %s\n","explain",
p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
2016-12-05 14:29:15 -06:00
utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
utf8_printf(p->out, "%12.12s: ", "nullvalue");
2015-03-20 09:04:26 -05:00
output_c_string(p->out, p->nullValue);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
utf8_printf(p->out,"%12.12s: %s\n","output",
2009-02-20 15:33:35 -05:00
strlen30(p->outfile) ? p->outfile : "stdout");
2016-02-23 09:07:39 -06:00
utf8_printf(p->out,"%12.12s: ", "colseparator");
2015-03-20 09:04:26 -05:00
output_c_string(p->out, p->colSeparator);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
utf8_printf(p->out,"%12.12s: ", "rowseparator");
2015-03-20 09:04:26 -05:00
output_c_string(p->out, p->rowSeparator);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
2016-12-05 14:29:15 -06:00
utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%12.12s: ", "width");
2008-07-30 09:15:43 -04:00
for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d ", p->colWidth[i]);
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
2016-12-05 14:29:15 -06:00
utf8_printf(p->out, "%12.12s: %s\n", "filename",
p->zDbFilename ? p->zDbFilename : "");
2008-07-30 09:15:43 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
if( nArg==2 ){
p->statsOn = booleanValue(azArg[1]);
2016-12-05 14:29:15 -06:00
}else if( nArg==1 ){
display_stats(p->db, p, 0);
2014-09-30 08:40:45 -05:00
}else{
2016-12-05 14:29:15 -06:00
raw_printf(stderr, "Usage: .stats ?on|off?\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
2010-08-28 08:35:57 -04:00
}else
2014-09-30 08:40:45 -05:00
if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
2012-05-15 19:05:34 -04:00
sqlite3_stmt *pStmt;
2008-07-30 09:15:43 -04:00
char **azResult;
2012-05-15 19:05:34 -04:00
int nRow, nAlloc;
char *zSql = 0;
int ii;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2012-05-15 19:05:34 -04:00
rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
2016-02-23 09:07:39 -06:00
if( rc ) return shellDatabaseError(p->db);
/* Create an SQL statement to query for the list of tables in the
** main and all attached databases where the table name matches the
** LIKE pattern bound to variable "?1". */
2012-05-15 19:05:34 -04:00
zSql = sqlite3_mprintf(
"SELECT name FROM sqlite_master"
" WHERE type IN ('table','view')"
" AND name NOT LIKE 'sqlite_%%'"
" AND name LIKE ?1");
2016-02-23 09:07:39 -06:00
while( zSql && sqlite3_step(pStmt)==SQLITE_ROW ){
2012-05-15 19:05:34 -04:00
const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
if( strcmp(zDbName,"temp")==0 ){
zSql = sqlite3_mprintf(
"%z UNION ALL "
"SELECT 'temp.' || name FROM sqlite_temp_master"
" WHERE type IN ('table','view')"
" AND name NOT LIKE 'sqlite_%%'"
" AND name LIKE ?1", zSql);
}else{
zSql = sqlite3_mprintf(
"%z UNION ALL "
"SELECT '%q.' || name FROM \"%w\".sqlite_master"
" WHERE type IN ('table','view')"
" AND name NOT LIKE 'sqlite_%%'"
" AND name LIKE ?1", zSql, zDbName, zDbName);
}
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
rc = sqlite3_finalize(pStmt);
if( zSql && rc==SQLITE_OK ){
zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
}
2012-05-15 19:05:34 -04:00
sqlite3_free(zSql);
2016-02-23 09:07:39 -06:00
if( !zSql ) return shellNomemError();
if( rc ) return shellDatabaseError(p->db);
/* Run the SQL statement prepared by the above block. Store the results
** as an array of nul-terminated strings in azResult[]. */
2012-05-15 19:05:34 -04:00
nRow = nAlloc = 0;
azResult = 0;
if( nArg>1 ){
sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
2009-12-03 16:24:07 -05:00
}else{
2012-05-15 19:05:34 -04:00
sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
}
while( sqlite3_step(pStmt)==SQLITE_ROW ){
if( nRow>=nAlloc ){
char **azNew;
2015-07-10 14:14:29 -05:00
int n2 = nAlloc*2 + 10;
azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
2012-05-15 19:05:34 -04:00
if( azNew==0 ){
2016-02-23 09:07:39 -06:00
rc = shellNomemError();
2012-05-15 19:05:34 -04:00
break;
}
2015-07-10 14:14:29 -05:00
nAlloc = n2;
2012-05-15 19:05:34 -04:00
azResult = azNew;
}
azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
2016-02-23 09:07:39 -06:00
if( 0==azResult[nRow] ){
rc = shellNomemError();
break;
}
nRow++;
2012-05-15 19:05:34 -04:00
}
2016-02-23 09:07:39 -06:00
if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
rc = shellDatabaseError(p->db);
}
/* Pretty-print the contents of array azResult[] to the output */
if( rc==0 && nRow>0 ){
2008-07-30 09:15:43 -04:00
int len, maxlen = 0;
int i, j;
int nPrintCol, nPrintRow;
2012-05-15 19:05:34 -04:00
for(i=0; i<nRow; i++){
2009-02-20 15:33:35 -05:00
len = strlen30(azResult[i]);
2008-07-30 09:15:43 -04:00
if( len>maxlen ) maxlen = len;
}
nPrintCol = 80/(maxlen+2);
if( nPrintCol<1 ) nPrintCol = 1;
nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
for(i=0; i<nPrintRow; i++){
2012-05-15 19:05:34 -04:00
for(j=i; j<nRow; j+=nPrintRow){
char *zSp = j<nPrintRow ? "" : " ";
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s%-*s", zSp, maxlen,
azResult[j] ? azResult[j]:"");
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "\n");
2008-07-30 09:15:43 -04:00
}
}
2016-02-23 09:07:39 -06:00
2012-05-15 19:05:34 -04:00
for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
sqlite3_free(azResult);
2008-07-30 09:15:43 -04:00
}else
2016-12-05 14:29:15 -06:00
/* Begin redirecting output to the file "testcase-out.txt" */
if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
output_reset(p);
p->out = output_file_open("testcase-out.txt");
if( p->out==0 ){
utf8_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
}
if( nArg>=2 ){
sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
}else{
sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
}
}else
2011-05-05 22:37:34 -04:00
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 },
{ "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
2014-09-30 08:40:45 -05:00
{ "byteorder", SQLITE_TESTCTRL_BYTEORDER },
2015-07-10 14:14:29 -05:00
{ "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
{ "imposter", SQLITE_TESTCTRL_IMPOSTER },
2011-05-05 22:37:34 -04:00
};
int testctrl = -1;
2015-07-10 14:14:29 -05:00
int rc2 = 0;
int i, n2;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2011-05-05 22:37:34 -04:00
/* convert testctrl text option to value. allow any unique prefix
** of the option name, or a numerical value. */
2015-07-10 14:14:29 -05:00
n2 = strlen30(azArg[1]);
2016-02-23 09:07:39 -06:00
for(i=0; i<ArraySize(aCtrl); i++){
2015-07-10 14:14:29 -05:00
if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
2011-05-05 22:37:34 -04:00
if( testctrl<0 ){
testctrl = aCtrl[i].ctrlCode;
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
2011-05-05 22:37:34 -04:00
testctrl = -1;
break;
}
}
}
2013-08-29 08:11:18 -05:00
if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
2011-05-05 22:37:34 -04:00
if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
2011-05-05 22:37:34 -04:00
}else{
switch(testctrl){
/* sqlite3_test_control(int, db, int) */
case SQLITE_TESTCTRL_OPTIMIZATIONS:
2016-12-05 14:29:15 -06:00
case SQLITE_TESTCTRL_RESERVE:
2011-05-05 22:37:34 -04:00
if( nArg==3 ){
2016-12-05 14:29:15 -06:00
int opt = (int)strtol(azArg[2], 0, 0);
2015-07-10 14:14:29 -05:00
rc2 = sqlite3_test_control(testctrl, p->db, opt);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
2011-05-05 22:37:34 -04:00
} else {
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
2011-05-05 22:37:34 -04:00
azArg[1]);
}
break;
/* sqlite3_test_control(int) */
2014-09-30 08:40:45 -05:00
case SQLITE_TESTCTRL_PRNG_SAVE:
case SQLITE_TESTCTRL_PRNG_RESTORE:
2011-05-05 22:37:34 -04:00
case SQLITE_TESTCTRL_PRNG_RESET:
2014-09-30 08:40:45 -05:00
case SQLITE_TESTCTRL_BYTEORDER:
2011-05-05 22:37:34 -04:00
if( nArg==2 ){
2015-07-10 14:14:29 -05:00
rc2 = sqlite3_test_control(testctrl);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
2011-05-05 22:37:34 -04:00
} else {
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: testctrl %s takes no options\n",
azArg[1]);
2011-05-05 22:37:34 -04:00
}
break;
/* sqlite3_test_control(int, uint) */
2016-12-05 14:29:15 -06:00
case SQLITE_TESTCTRL_PENDING_BYTE:
2011-05-05 22:37:34 -04:00
if( nArg==3 ){
2013-08-29 08:11:18 -05:00
unsigned int opt = (unsigned int)integerValue(azArg[2]);
2015-07-10 14:14:29 -05:00
rc2 = sqlite3_test_control(testctrl, opt);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
2011-05-05 22:37:34 -04:00
} else {
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
2011-05-05 22:37:34 -04:00
" int option\n", azArg[1]);
}
break;
2016-12-05 14:29:15 -06:00
2011-05-05 22:37:34 -04:00
/* sqlite3_test_control(int, int) */
2016-12-05 14:29:15 -06:00
case SQLITE_TESTCTRL_ASSERT:
case SQLITE_TESTCTRL_ALWAYS:
case SQLITE_TESTCTRL_NEVER_CORRUPT:
2011-05-05 22:37:34 -04:00
if( nArg==3 ){
2016-12-05 14:29:15 -06:00
int opt = booleanValue(azArg[2]);
2015-07-10 14:14:29 -05:00
rc2 = sqlite3_test_control(testctrl, opt);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
2011-05-05 22:37:34 -04:00
} else {
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
2011-05-05 22:37:34 -04:00
azArg[1]);
}
break;
/* sqlite3_test_control(int, char *) */
#ifdef SQLITE_N_KEYWORD
2016-12-05 14:29:15 -06:00
case SQLITE_TESTCTRL_ISKEYWORD:
2011-05-05 22:37:34 -04:00
if( nArg==3 ){
2016-12-05 14:29:15 -06:00
const char *opt = azArg[2];
2015-07-10 14:14:29 -05:00
rc2 = sqlite3_test_control(testctrl, opt);
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
2011-05-05 22:37:34 -04:00
} else {
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,
"Error: testctrl %s takes a single char * option\n",
azArg[1]);
2011-05-05 22:37:34 -04:00
}
break;
#endif
2015-07-10 14:14:29 -05:00
case SQLITE_TESTCTRL_IMPOSTER:
if( nArg==5 ){
2016-12-05 14:29:15 -06:00
rc2 = sqlite3_test_control(testctrl, p->db,
2015-07-10 14:14:29 -05:00
azArg[2],
integerValue(azArg[3]),
integerValue(azArg[4]));
2016-02-23 09:07:39 -06:00
raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
2015-07-10 14:14:29 -05:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
2015-07-10 14:14:29 -05:00
}
break;
2016-12-05 14:29:15 -06:00
case SQLITE_TESTCTRL_BITVEC_TEST:
case SQLITE_TESTCTRL_FAULT_INSTALL:
case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
case SQLITE_TESTCTRL_SCRATCHMALLOC:
2011-05-05 22:37:34 -04:00
default:
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,
"Error: CLI support for testctrl %s not implemented\n",
azArg[1]);
2011-05-05 22:37:34 -04:00
break;
}
}
}else
2014-09-30 08:40:45 -05:00
if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2014-09-30 08:40:45 -05:00
sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
2009-12-19 15:56:40 -05:00
}else
2016-12-05 14:29:15 -06:00
2014-09-30 08:40:45 -05:00
if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
if( nArg==2 ){
enableTimer = booleanValue(azArg[1]);
if( enableTimer && !HAS_TIMER ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: timer not available on this system.\n");
2014-09-30 08:40:45 -05:00
enableTimer = 0;
}
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .timer on|off\n");
2014-09-30 08:40:45 -05:00
rc = 1;
}
2009-12-19 15:56:40 -05:00
}else
2016-12-05 14:29:15 -06:00
2014-09-30 08:40:45 -05:00
if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2014-09-30 08:40:45 -05:00
if( nArg!=2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .trace FILE|off\n");
2014-09-30 08:40:45 -05:00
rc = 1;
goto meta_command_exit;
}
2015-07-10 14:14:29 -05:00
output_file_close(p->traceOut);
2012-05-15 19:05:34 -04:00
p->traceOut = output_file_open(azArg[1]);
2012-11-15 18:45:58 -05:00
#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
2012-05-15 19:05:34 -04:00
if( p->traceOut==0 ){
2016-12-05 14:29:15 -06:00
sqlite3_trace_v2(p->db, 0, 0, 0);
2012-05-15 19:05:34 -04:00
}else{
2016-12-05 14:29:15 -06:00
sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
2012-05-15 19:05:34 -04:00
}
#endif
}else
2015-03-20 09:04:26 -05:00
#if SQLITE_USER_AUTHENTICATION
if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
if( nArg<2 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
2015-03-20 09:04:26 -05:00
rc = 1;
goto meta_command_exit;
}
open_db(p, 0);
if( strcmp(azArg[1],"login")==0 ){
if( nArg!=4 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
2015-03-20 09:04:26 -05:00
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
(int)strlen(azArg[3]));
if( rc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
2015-03-20 09:04:26 -05:00
rc = 1;
}
}else if( strcmp(azArg[1],"add")==0 ){
if( nArg!=5 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
2015-03-20 09:04:26 -05:00
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_add(p->db, azArg[2],
azArg[3], (int)strlen(azArg[3]),
booleanValue(azArg[4]));
if( rc ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "User-Add failed: %d\n", rc);
2015-03-20 09:04:26 -05:00
rc = 1;
}
}else if( strcmp(azArg[1],"edit")==0 ){
if( nArg!=5 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
2015-03-20 09:04:26 -05:00
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_change(p->db, azArg[2],
azArg[3], (int)strlen(azArg[3]),
booleanValue(azArg[4]));
if( rc ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "User-Edit failed: %d\n", rc);
2015-03-20 09:04:26 -05:00
rc = 1;
}
}else if( strcmp(azArg[1],"delete")==0 ){
if( nArg!=3 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .user delete USER\n");
2015-03-20 09:04:26 -05:00
rc = 1;
goto meta_command_exit;
}
rc = sqlite3_user_delete(p->db, azArg[2]);
if( rc ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "User-Delete failed: %d\n", rc);
2015-03-20 09:04:26 -05:00
rc = 1;
}
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
2015-03-20 09:04:26 -05:00
rc = 1;
goto meta_command_exit;
2016-12-05 14:29:15 -06:00
}
2015-03-20 09:04:26 -05:00
}else
#endif /* SQLITE_USER_AUTHENTICATION */
2011-08-17 13:17:32 -04:00
if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
2011-08-17 13:17:32 -04:00
sqlite3_libversion(), sqlite3_sourceid());
}else
2016-02-23 09:07:39 -06:00
if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
const char *zDbName = nArg==2 ? azArg[1] : "main";
sqlite3_vfs *pVfs;
if( p->db ){
sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
if( pVfs ){
utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
}
}
}else
if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
sqlite3_vfs *pVfs;
sqlite3_vfs *pCurrent = 0;
if( p->db ){
sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
}
for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
pVfs==pCurrent ? " <--- CURRENT" : "");
raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
if( pVfs->pNext ){
raw_printf(p->out, "-----------------------------------\n");
}
}
}else
2012-01-18 00:18:26 -05:00
if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
const char *zDbName = nArg==2 ? azArg[1] : "main";
char *zVfsName = 0;
if( p->db ){
sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
if( zVfsName ){
2016-02-23 09:07:39 -06:00
utf8_printf(p->out, "%s\n", zVfsName);
2012-01-18 00:18:26 -05:00
sqlite3_free(zVfsName);
}
}
}else
2013-01-15 16:38:05 -06:00
#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
2014-09-30 08:40:45 -05:00
sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
2013-01-15 16:38:05 -06:00
}else
#endif
2014-09-30 08:40:45 -05:00
if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
2008-07-30 09:15:43 -04:00
int j;
assert( nArg<=ArraySize(azArg) );
for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
2013-08-29 08:11:18 -05:00
p->colWidth[j-1] = (int)integerValue(azArg[j]);
2008-07-30 09:15:43 -04:00
}
}else
{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: unknown command or invalid arguments: "
2008-07-30 09:15:43 -04:00
" \"%s\". Enter \".help\" for help\n", azArg[0]);
2009-12-03 16:24:07 -05:00
rc = 1;
2008-07-30 09:15:43 -04:00
}
2014-09-30 08:40:45 -05:00
meta_command_exit:
if( p->outCount ){
p->outCount--;
if( p->outCount==0 ) output_reset(p);
}
2008-07-30 09:15:43 -04:00
return rc;
}
/*
** Return TRUE if a semicolon occurs anywhere in the first N characters
** of string z[].
*/
2013-08-29 08:11:18 -05:00
static int line_contains_semicolon(const char *z, int N){
2008-07-30 09:15:43 -04:00
int i;
for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
return 0;
}
/*
** Test to see if a line consists entirely of whitespace.
*/
static int _all_whitespace(const char *z){
for(; *z; z++){
2011-12-26 14:52:17 -05:00
if( IsSpace(z[0]) ) continue;
2008-07-30 09:15:43 -04:00
if( *z=='/' && z[1]=='*' ){
z += 2;
while( *z && (*z!='*' || z[1]!='/') ){ z++; }
if( *z==0 ) return 0;
z++;
continue;
}
if( *z=='-' && z[1]=='-' ){
z += 2;
while( *z && *z!='\n' ){ z++; }
if( *z==0 ) return 1;
continue;
}
return 0;
}
return 1;
}
/*
** Return TRUE if the line typed in is an SQL command terminator other
** than a semi-colon. The SQL Server style "go" command is understood
** as is the Oracle "/".
*/
2013-08-29 08:11:18 -05:00
static int line_is_command_terminator(const char *zLine){
2011-12-26 14:52:17 -05:00
while( IsSpace(zLine[0]) ){ zLine++; };
2009-02-20 15:33:35 -05:00
if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
return 1; /* Oracle */
}
2011-12-26 14:52:17 -05:00
if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
2008-07-30 09:15:43 -04:00
&& _all_whitespace(&zLine[2]) ){
return 1; /* SQL Server */
}
return 0;
}
2009-02-20 15:33:35 -05:00
/*
** 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.
*/
2013-08-29 08:11:18 -05:00
static int line_is_complete(char *zSql, int nSql){
2009-02-20 15:33:35 -05:00
int rc;
if( zSql==0 ) return 1;
zSql[nSql] = ';';
zSql[nSql+1] = 0;
rc = sqlite3_complete(zSql);
zSql[nSql] = 0;
return rc;
}
2008-07-30 09:15:43 -04:00
/*
** Read input from *in and process it. If *in==0 then input
** is interactive - the user is typing it it. Otherwise, input
** is coming from a file or device. A prompt is issued and history
** is saved only if input is interactive. An interrupt signal will
** cause this routine to exit immediately, unless input is interactive.
**
** Return the number of errors.
*/
2015-03-20 09:04:26 -05:00
static int process_input(ShellState *p, FILE *in){
2013-08-29 08:11:18 -05:00
char *zLine = 0; /* A single input line */
char *zSql = 0; /* Accumulated SQL text */
int nLine; /* Length of current line */
int nSql = 0; /* Bytes of zSql[] used */
int nAlloc = 0; /* Allocated zSql[] space */
int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
char *zErrMsg; /* Error message returned */
int rc; /* Error code */
int errCnt = 0; /* Number of errors seen */
int lineno = 0; /* Current line number */
int startline = 0; /* Line number for start of current input */
2008-07-30 09:15:43 -04:00
while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
fflush(p->out);
2013-08-29 08:11:18 -05:00
zLine = one_input_line(in, zLine, nSql>0);
2008-07-30 09:15:43 -04:00
if( zLine==0 ){
2012-05-15 19:05:34 -04:00
/* End of input */
2016-12-05 14:29:15 -06:00
if( in==0 && stdin_is_interactive ) printf("\n");
2012-05-15 19:05:34 -04:00
break;
2008-07-30 09:15:43 -04:00
}
if( seenInterrupt ){
if( in!=0 ) break;
seenInterrupt = 0;
}
lineno++;
2014-04-04 10:16:20 -05:00
if( nSql==0 && _all_whitespace(zLine) ){
if( p->echoOn ) printf("%s\n", zLine);
continue;
}
2008-07-30 09:15:43 -04:00
if( zLine && zLine[0]=='.' && nSql==0 ){
2009-12-03 16:24:07 -05:00
if( p->echoOn ) printf("%s\n", zLine);
2008-07-30 09:15:43 -04:00
rc = do_meta_command(zLine, p);
2009-12-03 16:24:07 -05:00
if( rc==2 ){ /* exit requested */
2008-07-30 09:15:43 -04:00
break;
}else if( rc ){
errCnt++;
}
continue;
}
2013-08-29 08:11:18 -05:00
if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
2008-07-30 09:15:43 -04:00
memcpy(zLine,";",2);
}
2013-08-29 08:11:18 -05:00
nLine = strlen30(zLine);
if( nSql+nLine+2>=nAlloc ){
nAlloc = nSql+nLine+100;
zSql = realloc(zSql, nAlloc);
2008-07-30 09:15:43 -04:00
if( zSql==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Error: out of memory\n");
2008-07-30 09:15:43 -04:00
exit(1);
}
}
2013-08-29 08:11:18 -05:00
nSqlPrior = nSql;
if( nSql==0 ){
int i;
for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
assert( nAlloc>0 && zSql!=0 );
memcpy(zSql, zLine+i, nLine+1-i);
startline = lineno;
nSql = nLine-i;
}else{
zSql[nSql++] = '\n';
memcpy(zSql+nSql, zLine, nLine+1);
nSql += nLine;
}
if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
2008-07-30 09:15:43 -04:00
&& sqlite3_complete(zSql) ){
p->cnt = 0;
2014-04-04 10:16:20 -05:00
open_db(p, 0);
2015-07-10 14:14:29 -05:00
if( p->backslashOn ) resolve_backslashes(zSql);
2008-07-30 09:15:43 -04:00
BEGIN_TIMER;
2009-12-03 16:24:07 -05:00
rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
2008-07-30 09:15:43 -04:00
END_TIMER;
if( rc || zErrMsg ){
char zPrefix[100];
if( in!=0 || !stdin_is_interactive ){
2016-12-05 14:29:15 -06:00
sqlite3_snprintf(sizeof(zPrefix), zPrefix,
2009-12-03 16:24:07 -05:00
"Error: near line %d:", startline);
2008-07-30 09:15:43 -04:00
}else{
2009-12-03 16:24:07 -05:00
sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
2008-07-30 09:15:43 -04:00
}
if( zErrMsg!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
2008-07-30 09:15:43 -04:00
sqlite3_free(zErrMsg);
zErrMsg = 0;
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
2008-07-30 09:15:43 -04:00
}
errCnt++;
2016-02-23 09:07:39 -06:00
}else if( p->countChanges ){
raw_printf(p->out, "changes: %3d total_changes: %d\n",
sqlite3_changes(p->db), sqlite3_total_changes(p->db));
2008-07-30 09:15:43 -04:00
}
nSql = 0;
2014-09-30 08:40:45 -05:00
if( p->outCount ){
output_reset(p);
p->outCount = 0;
}
2013-08-29 08:11:18 -05:00
}else if( nSql && _all_whitespace(zSql) ){
2014-04-04 10:16:20 -05:00
if( p->echoOn ) printf("%s\n", zSql);
2013-05-21 15:38:11 -05:00
nSql = 0;
2008-07-30 09:15:43 -04:00
}
}
2013-08-29 08:11:18 -05:00
if( nSql ){
2011-05-05 22:37:34 -04:00
if( !_all_whitespace(zSql) ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "Error: incomplete SQL: %s\n", zSql);
2015-03-20 09:04:26 -05:00
errCnt++;
2011-05-05 22:37:34 -04:00
}
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
free(zSql);
2008-07-30 09:15:43 -04:00
free(zLine);
2013-01-15 16:38:05 -06:00
return errCnt>0;
2008-07-30 09:15:43 -04:00
}
/*
** Return a pathname which is the user's home directory. A
2012-05-15 19:05:34 -04:00
** 0 return indicates an error of some kind.
2008-07-30 09:15:43 -04:00
*/
2016-12-05 14:29:15 -06:00
static char *find_home_dir(int clearFlag){
2012-05-15 19:05:34 -04:00
static char *home_dir = NULL;
2016-12-05 14:29:15 -06:00
if( clearFlag ){
free(home_dir);
home_dir = 0;
return 0;
}
2012-05-15 19:05:34 -04:00
if( home_dir ) return home_dir;
2008-07-30 09:15:43 -04:00
2015-03-20 09:04:26 -05:00
#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
&& !defined(__RTP__) && !defined(_WRS_KERNEL)
2012-11-15 18:45:58 -05:00
{
struct passwd *pwent;
uid_t uid = getuid();
if( (pwent=getpwuid(uid)) != NULL) {
home_dir = pwent->pw_dir;
}
2008-07-30 09:15:43 -04:00
}
#endif
#if defined(_WIN32_WCE)
/* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
*/
2012-05-15 19:05:34 -04:00
home_dir = "/";
2008-07-30 09:15:43 -04:00
#else
2012-11-15 18:45:58 -05:00
#if defined(_WIN32) || defined(WIN32)
2008-07-30 09:15:43 -04:00
if (!home_dir) {
home_dir = getenv("USERPROFILE");
}
#endif
if (!home_dir) {
home_dir = getenv("HOME");
}
2012-11-15 18:45:58 -05:00
#if defined(_WIN32) || defined(WIN32)
2008-07-30 09:15:43 -04:00
if (!home_dir) {
char *zDrive, *zPath;
int n;
zDrive = getenv("HOMEDRIVE");
zPath = getenv("HOMEPATH");
if( zDrive && zPath ){
2009-02-20 15:33:35 -05:00
n = strlen30(zDrive) + strlen30(zPath) + 1;
2008-07-30 09:15:43 -04:00
home_dir = malloc( n );
if( home_dir==0 ) return 0;
sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
return home_dir;
}
home_dir = "c:\\";
}
#endif
#endif /* !_WIN32_WCE */
if( home_dir ){
2009-02-20 15:33:35 -05:00
int n = strlen30(home_dir) + 1;
2008-07-30 09:15:43 -04:00
char *z = malloc( n );
if( z ) memcpy(z, home_dir, n);
home_dir = z;
}
return home_dir;
}
/*
** Read input from the file given by sqliterc_override. Or if that
** parameter is NULL, take input from ~/.sqliterc
2009-12-03 16:24:07 -05:00
**
** Returns the number of errors.
2008-07-30 09:15:43 -04:00
*/
2015-07-10 14:14:29 -05:00
static void process_sqliterc(
2015-03-20 09:04:26 -05:00
ShellState *p, /* Configuration data */
2008-07-30 09:15:43 -04:00
const char *sqliterc_override /* Name of config file. NULL to use default */
){
char *home_dir = NULL;
const char *sqliterc = sqliterc_override;
char *zBuf = 0;
FILE *in = NULL;
if (sqliterc == NULL) {
2016-12-05 14:29:15 -06:00
home_dir = find_home_dir(0);
2008-07-30 09:15:43 -04:00
if( home_dir==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "-- warning: cannot find home directory;"
2015-07-10 14:14:29 -05:00
" cannot read ~/.sqliterc\n");
return;
2008-07-30 09:15:43 -04:00
}
2012-11-15 18:45:58 -05:00
sqlite3_initialize();
2012-05-15 19:05:34 -04:00
zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
sqliterc = zBuf;
2008-07-30 09:15:43 -04:00
}
in = fopen(sqliterc,"rb");
if( in ){
if( stdin_is_interactive ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
2008-07-30 09:15:43 -04:00
}
2015-07-10 14:14:29 -05:00
process_input(p,in);
2008-07-30 09:15:43 -04:00
fclose(in);
}
2012-05-15 19:05:34 -04:00
sqlite3_free(zBuf);
2008-07-30 09:15:43 -04:00
}
/*
** Show available command line options
*/
2016-12-05 14:29:15 -06:00
static const char zOptions[] =
2015-03-20 09:04:26 -05:00
" -ascii set output mode to 'ascii'\n"
2008-07-30 09:15:43 -04:00
" -bail stop after hitting an error\n"
" -batch force batch I/O\n"
" -column set output mode to 'column'\n"
2013-01-15 16:38:05 -06:00
" -cmd COMMAND run \"COMMAND\" before reading stdin\n"
2008-07-30 09:15:43 -04:00
" -csv set output mode to 'csv'\n"
2012-05-15 19:05:34 -04:00
" -echo print commands before execution\n"
2013-01-15 16:38:05 -06:00
" -init FILENAME read/process named file\n"
2012-05-15 19:05:34 -04:00
" -[no]header turn headers on or off\n"
2013-01-15 16:38:05 -06:00
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
" -heap SIZE Size of heap for memsys3 or memsys5\n"
#endif
2012-05-15 19:05:34 -04:00
" -help show this message\n"
2008-07-30 09:15:43 -04:00
" -html set output mode to HTML\n"
2012-05-15 19:05:34 -04:00
" -interactive force interactive I/O\n"
2008-07-30 09:15:43 -04:00
" -line set output mode to 'line'\n"
" -list set output mode to 'list'\n"
2015-03-20 09:04:26 -05:00
" -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
2013-05-21 15:38:11 -05:00
" -mmap N default mmap size set to N\n"
2012-05-15 19:05:34 -04:00
#ifdef SQLITE_ENABLE_MULTIPLEX
" -multiplex enable the multiplexor VFS\n"
#endif
2015-03-20 09:04:26 -05:00
" -newline SEP set output row separator. Default: '\\n'\n"
2013-01-15 16:38:05 -06:00
" -nullvalue TEXT set text string for NULL values. Default ''\n"
2015-03-20 09:04:26 -05:00
" -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
" -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
" -separator SEP set output column separator. Default: '|'\n"
2010-08-28 08:35:57 -04:00
" -stats print memory stats before each finalize\n"
2008-07-30 09:15:43 -04:00
" -version show SQLite version\n"
2011-05-05 22:37:34 -04:00
" -vfs NAME use NAME as the default VFS\n"
#ifdef SQLITE_ENABLE_VFSTRACE
" -vfstrace enable tracing of all VFS calls\n"
#endif
2008-07-30 09:15:43 -04:00
;
static void usage(int showDetail){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,
2016-12-05 14:29:15 -06:00
"Usage: %s [OPTIONS] FILENAME [SQL]\n"
2008-07-30 09:15:43 -04:00
"FILENAME is the name of an SQLite database. A new database is created\n"
"if the file does not previously exist.\n", Argv0);
if( showDetail ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
2008-07-30 09:15:43 -04:00
}else{
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "Use the -help option for additional information\n");
2008-07-30 09:15:43 -04:00
}
exit(1);
}
/*
** Initialize the state information in data
*/
2015-03-20 09:04:26 -05:00
static void main_init(ShellState *data) {
2008-07-30 09:15:43 -04:00
memset(data, 0, sizeof(*data));
2016-02-23 09:07:39 -06:00
data->normalMode = data->cMode = data->mode = MODE_List;
data->autoExplain = 1;
2015-03-20 09:04:26 -05:00
memcpy(data->colSeparator,SEP_Column, 2);
memcpy(data->rowSeparator,SEP_Row, 2);
2008-07-30 09:15:43 -04:00
data->showHeader = 0;
2015-03-20 09:04:26 -05:00
data->shellFlgs = SHFLG_Lookaside;
2011-08-17 13:17:32 -04:00
sqlite3_config(SQLITE_CONFIG_URI, 1);
2010-05-18 12:22:17 -04:00
sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
2015-03-20 09:04:26 -05:00
sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
2008-07-30 09:15:43 -04:00
sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
}
2014-04-04 10:16:20 -05:00
/*
** Output text to the console in a font that attracts extra attention.
*/
#ifdef _WIN32
static void printBold(const char *zText){
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
SetConsoleTextAttribute(out,
FOREGROUND_RED|FOREGROUND_INTENSITY
);
printf("%s", zText);
SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
}
#else
static void printBold(const char *zText){
printf("\033[1m%s\033[0m", zText);
}
#endif
2013-01-15 16:38:05 -06:00
/*
** Get the argument to an --option. Throw an error and die if no argument
** is available.
*/
static char *cmdline_option_value(int argc, char **argv, int i){
if( i==argc ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "%s: Error: missing argument to %s\n",
2013-01-15 16:38:05 -06:00
argv[0], argv[argc-1]);
exit(1);
}
return argv[i];
}
2016-12-05 14:29:15 -06:00
#ifndef SQLITE_SHELL_IS_UTF8
# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
# define SQLITE_SHELL_IS_UTF8 (0)
# else
# define SQLITE_SHELL_IS_UTF8 (1)
# endif
#endif
#if SQLITE_SHELL_IS_UTF8
2015-07-10 14:14:29 -05:00
int SQLITE_CDECL main(int argc, char **argv){
2016-12-05 14:29:15 -06:00
#else
int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
char **argv;
#endif
2008-07-30 09:15:43 -04:00
char *zErrMsg = 0;
2015-03-20 09:04:26 -05:00
ShellState data;
2008-07-30 09:15:43 -04:00
const char *zInitFile = 0;
int i;
int rc = 0;
2014-04-04 10:16:20 -05:00
int warnInmemoryDb = 0;
2015-03-20 09:04:26 -05:00
int readStdin = 1;
int nCmd = 0;
char **azCmd = 0;
2008-07-30 09:15:43 -04:00
2016-12-05 14:29:15 -06:00
setBinaryMode(stdin, 0);
setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
stdin_is_interactive = isatty(0);
stdout_is_console = isatty(1);
2014-04-04 10:16:20 -05:00
#if USE_SYSTEM_SQLITE+0!=1
2011-08-17 13:17:32 -04:00
if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
2011-08-17 13:17:32 -04:00
sqlite3_sourceid(), SQLITE_SOURCE_ID);
exit(1);
}
2014-04-04 10:16:20 -05:00
#endif
2008-07-30 09:15:43 -04:00
main_init(&data);
2016-12-05 14:29:15 -06:00
#if !SQLITE_SHELL_IS_UTF8
sqlite3_initialize();
argv = sqlite3_malloc64(sizeof(argv[0])*argc);
if( argv==0 ){
raw_printf(stderr, "out of memory\n");
exit(1);
}
for(i=0; i<argc; i++){
argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
if( argv[i]==0 ){
raw_printf(stderr, "out of memory\n");
exit(1);
}
}
#endif
assert( argc>=1 && argv && argv[0] );
Argv0 = argv[0];
2008-07-30 09:15:43 -04:00
/* Make sure we have a valid signal handler early, before anything
** else is done.
*/
#ifdef SIGINT
signal(SIGINT, interrupt_handler);
#endif
2015-03-20 09:04:26 -05:00
#ifdef SQLITE_SHELL_DBNAME_PROC
{
/* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
** of a C-function that will provide the name of the database file. Use
** this compile-time option to embed this shell program in larger
** applications. */
extern void SQLITE_SHELL_DBNAME_PROC(const char**);
SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
warnInmemoryDb = 0;
}
#endif
2008-07-30 09:15:43 -04:00
/* Do an initial pass through the command-line argument to locate
** the name of the database file, the name of the initialization file,
2011-02-16 16:14:46 -05:00
** the size of the alternative malloc heap,
2008-07-30 09:15:43 -04:00
** and the first command to execute.
*/
2013-01-15 16:38:05 -06:00
for(i=1; i<argc; i++){
2008-07-30 09:15:43 -04:00
char *z;
z = argv[i];
2013-01-15 16:38:05 -06:00
if( z[0]!='-' ){
if( data.zDbFilename==0 ){
data.zDbFilename = z;
2015-03-20 09:04:26 -05:00
}else{
/* Excesss arguments are interpreted as SQL (or dot-commands) and
** mean that nothing is read from stdin */
readStdin = 0;
nCmd++;
azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
if( azCmd==0 ){
2016-02-23 09:07:39 -06:00
raw_printf(stderr, "out of memory\n");
2015-03-20 09:04:26 -05:00
exit(1);
}
azCmd[nCmd-1] = z;
2013-01-15 16:38:05 -06:00
}
}
2012-05-15 19:05:34 -04:00
if( z[1]=='-' ) z++;
if( strcmp(z,"-separator")==0
|| strcmp(z,"-nullvalue")==0
2014-09-30 08:40:45 -05:00
|| strcmp(z,"-newline")==0
2012-05-15 19:05:34 -04:00
|| strcmp(z,"-cmd")==0
){
2013-01-15 16:38:05 -06:00
(void)cmdline_option_value(argc, argv, ++i);
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-init")==0 ){
2013-01-15 16:38:05 -06:00
zInitFile = cmdline_option_value(argc, argv, ++i);
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-batch")==0 ){
2013-01-15 16:38:05 -06:00
/* Need to check for batch mode here to so we can avoid printing
2016-12-05 14:29:15 -06:00
** informational messages (like from process_sqliterc) before
2013-01-15 16:38:05 -06:00
** we do the actual processing of arguments later in a second pass.
*/
2009-12-03 16:24:07 -05:00
stdin_is_interactive = 0;
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-heap")==0 ){
2011-12-26 14:52:17 -05:00
#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
2011-02-16 16:14:46 -05:00
const char *zSize;
sqlite3_int64 szHeap;
2013-01-15 16:38:05 -06:00
zSize = cmdline_option_value(argc, argv, ++i);
2013-05-21 15:38:11 -05:00
szHeap = integerValue(zSize);
2011-02-16 16:14:46 -05:00
if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
2016-12-05 14:29:15 -06:00
#else
(void)cmdline_option_value(argc, argv, ++i);
2011-02-16 16:14:46 -05:00
#endif
2015-03-20 09:04:26 -05:00
}else if( strcmp(z,"-scratch")==0 ){
int n, sz;
sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( sz>400000 ) sz = 400000;
if( sz<2500 ) sz = 2500;
n = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( n>10 ) n = 10;
if( n<1 ) n = 1;
sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
data.shellFlgs |= SHFLG_Scratch;
}else if( strcmp(z,"-pagecache")==0 ){
int n, sz;
sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( sz>70000 ) sz = 70000;
2016-02-23 09:07:39 -06:00
if( sz<0 ) sz = 0;
2015-03-20 09:04:26 -05:00
n = (int)integerValue(cmdline_option_value(argc,argv,++i));
2016-02-23 09:07:39 -06:00
sqlite3_config(SQLITE_CONFIG_PAGECACHE,
(n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
2015-03-20 09:04:26 -05:00
data.shellFlgs |= SHFLG_Pagecache;
}else if( strcmp(z,"-lookaside")==0 ){
int n, sz;
sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( sz<0 ) sz = 0;
n = (int)integerValue(cmdline_option_value(argc,argv,++i));
if( n<0 ) n = 0;
sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
2011-05-05 22:37:34 -04:00
#ifdef SQLITE_ENABLE_VFSTRACE
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-vfstrace")==0 ){
2011-05-05 22:37:34 -04:00
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);
2011-12-26 14:52:17 -05:00
#endif
#ifdef SQLITE_ENABLE_MULTIPLEX
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-multiplex")==0 ){
2011-12-26 14:52:17 -05:00
extern int sqlite3_multiple_initialize(const char*,int);
sqlite3_multiplex_initialize(0, 1);
2011-05-05 22:37:34 -04:00
#endif
2013-05-21 15:38:11 -05:00
}else if( strcmp(z,"-mmap")==0 ){
sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-vfs")==0 ){
2013-01-15 16:38:05 -06:00
sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
2011-05-05 22:37:34 -04:00
if( pVfs ){
sqlite3_vfs_register(pVfs, 1);
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
2011-05-05 22:37:34 -04:00
exit(1);
}
2008-07-30 09:15:43 -04:00
}
}
2013-01-15 16:38:05 -06:00
if( data.zDbFilename==0 ){
2008-07-30 09:15:43 -04:00
#ifndef SQLITE_OMIT_MEMORYDB
data.zDbFilename = ":memory:";
2014-04-04 10:16:20 -05:00
warnInmemoryDb = argc==1;
2008-07-30 09:15:43 -04:00
#else
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
2009-12-03 16:24:07 -05:00
return 1;
2008-07-30 09:15:43 -04:00
#endif
2013-01-15 16:38:05 -06:00
}
data.out = stdout;
2008-07-30 09:15:43 -04:00
/* Go ahead and open the database file if it already exists. If the
** file does not exist, delay opening it. This prevents empty database
** files from being created if a user mistypes the database name argument
** to the sqlite command-line tool.
*/
if( access(data.zDbFilename, 0)==0 ){
2014-04-04 10:16:20 -05:00
open_db(&data, 0);
2008-07-30 09:15:43 -04:00
}
/* Process the initialization file if there is one. If no -init option
** is given on the command line, look for a file named ~/.sqliterc and
** try to process it.
*/
2015-07-10 14:14:29 -05:00
process_sqliterc(&data,zInitFile);
2008-07-30 09:15:43 -04:00
/* Make a second pass through the command-line argument and set
** options. This second pass is delayed until after the initialization
** file is processed so that the command-line arguments will override
** settings in the initialization file.
*/
2013-01-15 16:38:05 -06:00
for(i=1; i<argc; i++){
2008-07-30 09:15:43 -04:00
char *z = argv[i];
2013-01-15 16:38:05 -06:00
if( z[0]!='-' ) continue;
2008-07-30 09:15:43 -04:00
if( z[1]=='-' ){ z++; }
if( strcmp(z,"-init")==0 ){
i++;
}else if( strcmp(z,"-html")==0 ){
data.mode = MODE_Html;
}else if( strcmp(z,"-list")==0 ){
data.mode = MODE_List;
}else if( strcmp(z,"-line")==0 ){
data.mode = MODE_Line;
}else if( strcmp(z,"-column")==0 ){
data.mode = MODE_Column;
}else if( strcmp(z,"-csv")==0 ){
data.mode = MODE_Csv;
2015-03-20 09:04:26 -05:00
memcpy(data.colSeparator,",",2);
}else if( strcmp(z,"-ascii")==0 ){
data.mode = MODE_Ascii;
sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
SEP_Unit);
sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
SEP_Record);
2008-07-30 09:15:43 -04:00
}else if( strcmp(z,"-separator")==0 ){
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
2013-01-15 16:38:05 -06:00
"%s",cmdline_option_value(argc,argv,++i));
2014-09-30 08:40:45 -05:00
}else if( strcmp(z,"-newline")==0 ){
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
2014-09-30 08:40:45 -05:00
"%s",cmdline_option_value(argc,argv,++i));
2008-07-30 09:15:43 -04:00
}else if( strcmp(z,"-nullvalue")==0 ){
2015-03-20 09:04:26 -05:00
sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
2013-01-15 16:38:05 -06:00
"%s",cmdline_option_value(argc,argv,++i));
2008-07-30 09:15:43 -04:00
}else if( strcmp(z,"-header")==0 ){
data.showHeader = 1;
}else if( strcmp(z,"-noheader")==0 ){
data.showHeader = 0;
}else if( strcmp(z,"-echo")==0 ){
data.echoOn = 1;
2014-04-04 10:16:20 -05:00
}else if( strcmp(z,"-eqp")==0 ){
data.autoEQP = 1;
2016-12-05 14:29:15 -06:00
}else if( strcmp(z,"-eqpfull")==0 ){
data.autoEQP = 2;
2010-08-28 08:35:57 -04:00
}else if( strcmp(z,"-stats")==0 ){
data.statsOn = 1;
2015-03-20 09:04:26 -05:00
}else if( strcmp(z,"-scanstats")==0 ){
data.scanstatsOn = 1;
2015-07-10 14:14:29 -05:00
}else if( strcmp(z,"-backslash")==0 ){
/* Undocumented command-line option: -backslash
** Causes C-style backslash escapes to be evaluated in SQL statements
** prior to sending the SQL into SQLite. Useful for injecting
** crazy bytes in the middle of SQL statements for testing and debugging.
*/
data.backslashOn = 1;
2008-07-30 09:15:43 -04:00
}else if( strcmp(z,"-bail")==0 ){
bail_on_error = 1;
}else if( strcmp(z,"-version")==0 ){
2011-08-17 13:17:32 -04:00
printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
2008-07-30 09:15:43 -04:00
return 0;
}else if( strcmp(z,"-interactive")==0 ){
stdin_is_interactive = 1;
}else if( strcmp(z,"-batch")==0 ){
stdin_is_interactive = 0;
2011-02-16 16:14:46 -05:00
}else if( strcmp(z,"-heap")==0 ){
i++;
2015-03-20 09:04:26 -05:00
}else if( strcmp(z,"-scratch")==0 ){
i+=2;
}else if( strcmp(z,"-pagecache")==0 ){
i+=2;
}else if( strcmp(z,"-lookaside")==0 ){
i+=2;
2013-05-21 15:38:11 -05:00
}else if( strcmp(z,"-mmap")==0 ){
i++;
2011-05-05 22:37:34 -04:00
}else if( strcmp(z,"-vfs")==0 ){
i++;
2011-12-26 14:52:17 -05:00
#ifdef SQLITE_ENABLE_VFSTRACE
2011-05-05 22:37:34 -04:00
}else if( strcmp(z,"-vfstrace")==0 ){
i++;
2011-12-26 14:52:17 -05:00
#endif
#ifdef SQLITE_ENABLE_MULTIPLEX
}else if( strcmp(z,"-multiplex")==0 ){
i++;
#endif
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-help")==0 ){
2008-07-30 09:15:43 -04:00
usage(1);
2012-05-15 19:05:34 -04:00
}else if( strcmp(z,"-cmd")==0 ){
2015-03-20 09:04:26 -05:00
/* Run commands that follow -cmd first and separately from commands
** that simply appear on the command-line. This seems goofy. It would
** be better if all commands ran in the order that they appear. But
** we retain the goofy behavior for historical compatibility. */
2012-05-15 19:05:34 -04:00
if( i==argc-1 ) break;
2013-01-15 16:38:05 -06:00
z = cmdline_option_value(argc,argv,++i);
2012-05-15 19:05:34 -04:00
if( z[0]=='.' ){
rc = do_meta_command(z, &data);
2013-05-21 15:38:11 -05:00
if( rc && bail_on_error ) return rc==2 ? 0 : rc;
2012-05-15 19:05:34 -04:00
}else{
2014-04-04 10:16:20 -05:00
open_db(&data, 0);
2012-05-15 19:05:34 -04:00
rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
if( zErrMsg!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: %s\n", zErrMsg);
2012-05-15 19:05:34 -04:00
if( bail_on_error ) return rc!=0 ? rc : 1;
}else if( rc!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
2012-05-15 19:05:34 -04:00
if( bail_on_error ) return rc;
}
}
2008-07-30 09:15:43 -04:00
}else{
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
raw_printf(stderr,"Use -help for a list of options.\n");
2008-07-30 09:15:43 -04:00
return 1;
}
2016-02-23 09:07:39 -06:00
data.cMode = data.mode;
2008-07-30 09:15:43 -04:00
}
2015-03-20 09:04:26 -05:00
if( !readStdin ){
/* Run all arguments that do not begin with '-' as if they were separate
** command-line inputs, except for the argToSkip argument which contains
** the database filename.
2008-07-30 09:15:43 -04:00
*/
2015-03-20 09:04:26 -05:00
for(i=0; i<nCmd; i++){
if( azCmd[i][0]=='.' ){
rc = do_meta_command(azCmd[i], &data);
if( rc ) return rc==2 ? 0 : rc;
}else{
open_db(&data, 0);
rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
if( zErrMsg!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: %s\n", zErrMsg);
2015-03-20 09:04:26 -05:00
return rc!=0 ? rc : 1;
}else if( rc!=0 ){
2016-02-23 09:07:39 -06:00
utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
2015-03-20 09:04:26 -05:00
return rc;
}
2008-07-30 09:15:43 -04:00
}
}
2015-03-20 09:04:26 -05:00
free(azCmd);
2008-07-30 09:15:43 -04:00
}else{
/* Run commands received from standard input
*/
if( stdin_is_interactive ){
char *zHome;
char *zHistory = 0;
int nHistory;
printf(
2012-01-18 00:18:26 -05:00
"SQLite version %s %.19s\n" /*extra-version-info*/
2014-04-04 10:16:20 -05:00
"Enter \".help\" for usage hints.\n",
2011-08-17 13:17:32 -04:00
sqlite3_libversion(), sqlite3_sourceid()
2008-07-30 09:15:43 -04:00
);
2014-04-04 10:16:20 -05:00
if( warnInmemoryDb ){
printf("Connected to a ");
printBold("transient in-memory database");
printf(".\nUse \".open FILENAME\" to reopen on a "
"persistent database.\n");
}
2016-12-05 14:29:15 -06:00
zHome = find_home_dir(0);
2009-02-20 15:33:35 -05:00
if( zHome ){
nHistory = strlen30(zHome) + 20;
if( (zHistory = malloc(nHistory))!=0 ){
sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
}
2008-07-30 09:15:43 -04:00
}
2016-02-23 09:07:39 -06:00
if( zHistory ){ shell_read_history(zHistory); }
2008-07-30 09:15:43 -04:00
rc = process_input(&data, 0);
if( zHistory ){
2015-03-20 09:04:26 -05:00
shell_stifle_history(100);
shell_write_history(zHistory);
2008-07-30 09:15:43 -04:00
free(zHistory);
}
}else{
rc = process_input(&data, stdin);
}
}
set_table_name(&data, 0);
2010-07-22 09:16:22 -04:00
if( data.db ){
2016-12-05 14:29:15 -06:00
session_close_all(&data);
2011-02-16 16:14:46 -05:00
sqlite3_close(data.db);
2008-07-30 09:15:43 -04:00
}
2016-12-05 14:29:15 -06:00
sqlite3_free(data.zFreeOnClose);
find_home_dir(1);
#if !SQLITE_SHELL_IS_UTF8
for(i=0; i<argc; i++) sqlite3_free(argv[i]);
sqlite3_free(argv);
#endif
2008-07-30 09:15:43 -04:00
return rc;
}