blob: 04f37809cc8147565df2a12f345ba3f544794c3d [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
drh75897232000-05-29 14:26:00 +000014*/
mistachkina3b2ff52011-09-16 20:16:36 +000015#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
shane18e526c2008-12-10 22:30:24 +000016/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
drh36f7dd32011-10-13 16:02:17 +000020/*
mistachkin2318d332015-01-12 18:02:52 +000021** If requested, include the SQLite compiler options file for MSVC.
22*/
23#if defined(INCLUDE_MSVC_H)
24#include "msvc.h"
25#endif
26
27/*
drh8cd5b252015-03-02 22:06:43 +000028** No support for loadable extensions in VxWorks.
29*/
drhada3f2b2015-03-23 21:32:50 +000030#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000031# define SQLITE_OMIT_LOAD_EXTENSION 1
32#endif
33
34/*
drh36f7dd32011-10-13 16:02:17 +000035** Enable large-file support for fopen() and friends on unix.
36*/
37#ifndef SQLITE_DISABLE_LFS
38# define _LARGE_FILE 1
39# ifndef _FILE_OFFSET_BITS
40# define _FILE_OFFSET_BITS 64
41# endif
42# define _LARGEFILE_SOURCE 1
43#endif
44
drh75897232000-05-29 14:26:00 +000045#include <stdlib.h>
46#include <string.h>
47#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000048#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000049#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000050#if SQLITE_USER_AUTHENTICATION
51# include "sqlite3userauth.h"
52#endif
drh75897232000-05-29 14:26:00 +000053#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000054#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000055
drh83905c92012-06-21 13:00:37 +000056#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000057# include <signal.h>
chw97185482008-11-17 08:05:31 +000058# if !defined(__RTP__) && !defined(_WRS_KERNEL)
59# include <pwd.h>
60# endif
drhdd45df82002-04-18 12:39:03 +000061# include <unistd.h>
62# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000063#endif
drh75897232000-05-29 14:26:00 +000064
drh0ede9eb2015-01-10 16:49:23 +000065#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000066# include <readline/readline.h>
67# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +000068#endif
danfd34d6d2015-02-25 10:54:53 +000069
drh0ede9eb2015-01-10 16:49:23 +000070#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +000071# include <editline/readline.h>
72#endif
danfd34d6d2015-02-25 10:54:53 +000073
74#if HAVE_EDITLINE || HAVE_READLINE
75
76# define shell_add_history(X) add_history(X)
77# define shell_read_history(X) read_history(X)
78# define shell_write_history(X) write_history(X)
79# define shell_stifle_history(X) stifle_history(X)
80# define shell_readline(X) readline(X)
81
82#elif HAVE_LINENOISE
83
84# include "linenoise.h"
85# define shell_add_history(X) linenoiseHistoryAdd(X)
86# define shell_read_history(X) linenoiseHistoryLoad(X)
87# define shell_write_history(X) linenoiseHistorySave(X)
88# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89# define shell_readline(X) linenoise(X)
90
91#else
92
mistachkin1fe36bb2016-04-04 02:16:44 +000093# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +000094# define shell_write_history(X)
95# define shell_stifle_history(X)
96
97# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +000098#endif
99
danfd34d6d2015-02-25 10:54:53 +0000100
adamd2e8464a2006-09-06 21:39:40 +0000101#if defined(_WIN32) || defined(WIN32)
102# include <io.h>
drh6976c212014-07-24 12:09:47 +0000103# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000104# define isatty(h) _isatty(h)
105# ifndef access
106# define access(f,m) _access((f),(m))
107# endif
108# undef popen
109# define popen _popen
110# undef pclose
111# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000112#else
mistachkin073664d2015-06-17 18:57:37 +0000113 /* Make sure isatty() has a prototype. */
114 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000115
mistachkin073664d2015-06-17 18:57:37 +0000116# if !defined(__RTP__) && !defined(_WRS_KERNEL)
117 /* popen and pclose are not C89 functions and so are
118 ** sometimes omitted from the <stdio.h> header */
119 extern FILE *popen(const char*,const char*);
120 extern int pclose(FILE*);
121# else
122# define SQLITE_OMIT_POPEN 1
123# endif
mistachkinf6418892013-08-28 01:54:12 +0000124#endif
drh53371f92013-07-25 17:07:03 +0000125
chw65d3c132007-11-12 21:09:10 +0000126#if defined(_WIN32_WCE)
127/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128 * thus we always assume that we have a console. That can be
129 * overridden with the -batch command line option.
130 */
131#define isatty(x) 1
132#endif
133
drhf0693c82011-10-11 20:41:54 +0000134/* ctype macros that work with signed characters */
135#define IsSpace(X) isspace((unsigned char)X)
136#define IsDigit(X) isdigit((unsigned char)X)
137#define ToLower(X) (char)tolower((unsigned char)X)
138
mistachkin1fe36bb2016-04-04 02:16:44 +0000139#if defined(_WIN32) || defined(WIN32)
140#include <windows.h>
141
142/* string conversion routines only needed on Win32 */
143extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
144extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000146extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000147#endif
148
drh047d4532015-01-18 20:30:23 +0000149/* On Windows, we normally run with output mode of TEXT so that \n characters
150** are automatically translated into \r\n. However, this behavior needs
151** to be disabled in some cases (ex: when generating CSV output and when
152** rendering quoted strings that contain \n characters). The following
153** routines take care of that.
154*/
155#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000156static void setBinaryMode(FILE *file, int isOutput){
157 if( isOutput ) fflush(file);
158 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000159}
mistachkin1fe36bb2016-04-04 02:16:44 +0000160static void setTextMode(FILE *file, int isOutput){
161 if( isOutput ) fflush(file);
162 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000163}
164#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000165# define setBinaryMode(X,Y)
166# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000167#endif
168
drh43408312013-10-30 12:43:36 +0000169
170/* True if the timer is enabled */
171static int enableTimer = 0;
172
173/* Return the current wall-clock time */
174static sqlite3_int64 timeOfDay(void){
175 static sqlite3_vfs *clockVfs = 0;
176 sqlite3_int64 t;
177 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000178 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000179 clockVfs->xCurrentTimeInt64(clockVfs, &t);
180 }else{
181 double r;
182 clockVfs->xCurrentTime(clockVfs, &r);
183 t = (sqlite3_int64)(r*86400000.0);
184 }
185 return t;
186}
187
drh91eb93c2015-03-03 19:56:20 +0000188#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000189#include <sys/time.h>
190#include <sys/resource.h>
191
drh91eb93c2015-03-03 19:56:20 +0000192/* VxWorks does not support getrusage() as far as we can determine */
193#if defined(_WRS_KERNEL) || defined(__RTP__)
194struct rusage {
195 struct timeval ru_utime; /* user CPU time used */
196 struct timeval ru_stime; /* system CPU time used */
197};
198#define getrusage(A,B) memset(B,0,sizeof(*B))
199#endif
200
drhda108222009-02-25 19:07:24 +0000201/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000202static struct rusage sBegin; /* CPU time at start */
203static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000204
drhda108222009-02-25 19:07:24 +0000205/*
206** Begin timing an operation
207*/
208static void beginTimer(void){
209 if( enableTimer ){
210 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000211 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000212 }
213}
214
215/* Return the difference of two time_structs in seconds */
216static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000217 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000218 (double)(pEnd->tv_sec - pStart->tv_sec);
219}
220
221/*
222** Print the timing results.
223*/
224static void endTimer(void){
225 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000226 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000227 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000228 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000229 printf("Run Time: real %.3f user %f sys %f\n",
230 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000231 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
232 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
233 }
234}
shaneb320ccd2009-10-21 03:42:58 +0000235
drhda108222009-02-25 19:07:24 +0000236#define BEGIN_TIMER beginTimer()
237#define END_TIMER endTimer()
238#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000239
240#elif (defined(_WIN32) || defined(WIN32))
241
shaneb320ccd2009-10-21 03:42:58 +0000242/* Saved resource information for the beginning of an operation */
243static HANDLE hProcess;
244static FILETIME ftKernelBegin;
245static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000246static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000247typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
248 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000249static GETPROCTIMES getProcessTimesAddr = NULL;
250
shaneb320ccd2009-10-21 03:42:58 +0000251/*
252** Check to see if we have timer support. Return 1 if necessary
253** support found (or found previously).
254*/
255static int hasTimer(void){
256 if( getProcessTimesAddr ){
257 return 1;
258 } else {
drh4ace5362014-11-10 14:42:28 +0000259 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260 ** versions. See if the version we are running on has it, and if it
261 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000262 */
263 hProcess = GetCurrentProcess();
264 if( hProcess ){
265 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
266 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000267 getProcessTimesAddr =
268 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000269 if( NULL != getProcessTimesAddr ){
270 return 1;
271 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000272 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000273 }
274 }
275 }
276 return 0;
277}
278
279/*
280** Begin timing an operation
281*/
282static void beginTimer(void){
283 if( enableTimer && getProcessTimesAddr ){
284 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000285 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
286 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000287 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000288 }
289}
290
291/* Return the difference of two FILETIME structs in seconds */
292static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
293 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
294 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
295 return (double) ((i64End - i64Start) / 10000000.0);
296}
297
298/*
299** Print the timing results.
300*/
301static void endTimer(void){
302 if( enableTimer && getProcessTimesAddr){
303 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000304 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000305 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000306 printf("Run Time: real %.3f user %f sys %f\n",
307 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000308 timeDiff(&ftUserBegin, &ftUserEnd),
309 timeDiff(&ftKernelBegin, &ftKernelEnd));
310 }
311}
312
313#define BEGIN_TIMER beginTimer()
314#define END_TIMER endTimer()
315#define HAS_TIMER hasTimer()
316
drhda108222009-02-25 19:07:24 +0000317#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000318#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000319#define END_TIMER
320#define HAS_TIMER 0
321#endif
322
shanec0688ea2009-03-05 03:48:06 +0000323/*
324** Used to prevent warnings about unused parameters
325*/
326#define UNUSED_PARAMETER(x) (void)(x)
327
drhe91d16b2008-12-08 18:27:31 +0000328/*
drhc49f44e2006-10-26 18:15:42 +0000329** If the following flag is set, then command execution stops
330** at an error if we are not interactive.
331*/
332static int bail_on_error = 0;
333
334/*
drhc28490c2006-10-26 14:25:58 +0000335** Threat stdin as an interactive input if the following variable
336** is true. Otherwise, assume stdin is connected to a file or pipe.
337*/
338static int stdin_is_interactive = 1;
339
340/*
drhe05461c2015-12-30 13:36:57 +0000341** On Windows systems we have to know if standard output is a console
342** in order to translate UTF-8 into MBCS. The following variable is
343** true if translation is required.
344*/
345static int stdout_is_console = 1;
346
347/*
drh4c504392000-10-16 22:06:40 +0000348** The following is the open SQLite database. We make a pointer
349** to this database a static variable so that it can be accessed
350** by the SIGINT handler to interrupt database processing.
351*/
mistachkin8e189222015-04-19 21:43:16 +0000352static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000353
354/*
drh67505e72002-04-19 12:34:06 +0000355** True if an interrupt (Control-C) has been received.
356*/
drh43617e92006-03-06 20:55:46 +0000357static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000358
359/*
persicom7e2dfdd2002-04-18 02:46:52 +0000360** This is the name of our program. It is set in main(), used
361** in a number of other places, mostly for error messages.
362*/
363static char *Argv0;
364
365/*
366** Prompt strings. Initialized in main. Settable with
367** .prompt main continue
368*/
369static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
370static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
371
drhb0603412007-02-28 04:47:26 +0000372/*
mistachkin710b33b2016-01-03 18:59:28 +0000373** Render output like fprintf(). Except, if the output is going to the
374** console and if this is running on a Windows machine, translate the
375** output from UTF-8 into MBCS.
376*/
377#if defined(_WIN32) || defined(WIN32)
378void utf8_printf(FILE *out, const char *zFormat, ...){
379 va_list ap;
380 va_start(ap, zFormat);
381 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000382 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000383 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000384 sqlite3_free(z1);
385 fputs(z2, out);
386 sqlite3_free(z2);
387 }else{
388 vfprintf(out, zFormat, ap);
389 }
390 va_end(ap);
391}
392#elif !defined(utf8_printf)
393# define utf8_printf fprintf
394#endif
395
396/*
397** Render output like fprintf(). This should not be used on anything that
398** includes string formatting (e.g. "%s").
399*/
400#if !defined(raw_printf)
401# define raw_printf fprintf
402#endif
403
404/*
drhb0603412007-02-28 04:47:26 +0000405** Write I/O traces to the following stream.
406*/
rsebe0a9092007-07-30 18:24:38 +0000407#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000408static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000409#endif
drhb0603412007-02-28 04:47:26 +0000410
411/*
412** This routine works like printf in that its first argument is a
413** format string and subsequent arguments are values to be substituted
414** in place of % fields. The result of formatting this string
415** is written to iotrace.
416*/
rsebe0a9092007-07-30 18:24:38 +0000417#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000418static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000419 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000420 char *z;
drhb0603412007-02-28 04:47:26 +0000421 if( iotrace==0 ) return;
422 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000423 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000424 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000425 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000426 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000427}
rsebe0a9092007-07-30 18:24:38 +0000428#endif
drhb0603412007-02-28 04:47:26 +0000429
drh44c2eb12003-04-30 11:38:26 +0000430
persicom7e2dfdd2002-04-18 02:46:52 +0000431/*
drh83965662003-04-17 02:54:13 +0000432** Determines if a string is a number of not.
433*/
danielk19772e588c72005-12-09 14:25:08 +0000434static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000435 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000436 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000437 return 0;
438 }
439 z++;
440 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000441 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000442 if( *z=='.' ){
443 z++;
drhf0693c82011-10-11 20:41:54 +0000444 if( !IsDigit(*z) ) return 0;
445 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000446 if( realnum ) *realnum = 1;
447 }
448 if( *z=='e' || *z=='E' ){
449 z++;
450 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000451 if( !IsDigit(*z) ) return 0;
452 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000453 if( realnum ) *realnum = 1;
454 }
455 return *z==0;
456}
drh83965662003-04-17 02:54:13 +0000457
458/*
drhe05461c2015-12-30 13:36:57 +0000459** Compute a string length that is limited to what can be stored in
460** lower 30 bits of a 32-bit signed integer.
461*/
462static int strlen30(const char *z){
463 const char *z2 = z;
464 while( *z2 ){ z2++; }
465 return 0x3fffffff & (int)(z2 - z);
466}
467
468/*
drhfeac5f82004-08-01 00:10:45 +0000469** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000470** the text in memory obtained from malloc() and returns a pointer
471** to the text. NULL is returned at end of file, or if malloc()
472** fails.
473**
drh9f099fd2013-08-06 14:01:46 +0000474** If zLine is not NULL then it is a malloced buffer returned from
475** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000476*/
drh9f099fd2013-08-06 14:01:46 +0000477static char *local_getline(char *zLine, FILE *in){
478 int nLine = zLine==0 ? 0 : 100;
479 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000480
drhb07028f2011-10-14 21:49:18 +0000481 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000482 if( n+100>nLine ){
483 nLine = nLine*2 + 100;
484 zLine = realloc(zLine, nLine);
485 if( zLine==0 ) return 0;
486 }
drhdaffd0e2001-04-11 14:28:42 +0000487 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000488 if( n==0 ){
489 free(zLine);
490 return 0;
491 }
492 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000493 break;
494 }
drh9f099fd2013-08-06 14:01:46 +0000495 while( zLine[n] ) n++;
496 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000497 n--;
shaneh13b36022009-12-17 21:07:15 +0000498 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000499 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000500 break;
drh8e7e7a22000-05-30 18:45:23 +0000501 }
502 }
drhe05461c2015-12-30 13:36:57 +0000503#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000504 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000505 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000506 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000507 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000508 if( zTrans ){
509 int nTrans = strlen30(zTrans)+1;
510 if( nTrans>nLine ){
511 zLine = realloc(zLine, nTrans);
512 if( zLine==0 ){
513 sqlite3_free(zTrans);
514 return 0;
515 }
516 }
517 memcpy(zLine, zTrans, nTrans);
518 sqlite3_free(zTrans);
519 }
520 }
521#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000522 return zLine;
523}
524
525/*
drhc28490c2006-10-26 14:25:58 +0000526** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000527**
drh9f099fd2013-08-06 14:01:46 +0000528** If in==0 then read from standard input and prompt before each line.
529** If isContinuation is true, then a continuation prompt is appropriate.
530** If isContinuation is zero, then the main prompt should be used.
531**
532** If zPrior is not NULL then it is a buffer from a prior call to this
533** routine that can be reused.
534**
535** The result is stored in space obtained from malloc() and must either
536** be freed by the caller or else passed back into this routine via the
537** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000538*/
drh9f099fd2013-08-06 14:01:46 +0000539static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000540 char *zPrompt;
541 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000542 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000543 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000544 }else{
drh9f099fd2013-08-06 14:01:46 +0000545 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000546#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000547 printf("%s", zPrompt);
548 fflush(stdout);
549 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000550#else
551 free(zPrior);
552 zResult = shell_readline(zPrompt);
553 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000554#endif
drh9f099fd2013-08-06 14:01:46 +0000555 }
drh8e7e7a22000-05-30 18:45:23 +0000556 return zResult;
557}
drhf42d3182017-03-08 12:25:18 +0000558/*
559** A variable length string to which one can append text.
560*/
561typedef struct ShellText ShellText;
562struct ShellText {
563 char *z;
564 int n;
565 int nAlloc;
566};
567
568/*
569** Initialize and destroy a ShellText object
570*/
571static void initText(ShellText *p){
572 memset(p, 0, sizeof(*p));
573}
574static void freeText(ShellText *p){
575 free(p->z);
576 initText(p);
577}
578
579/* zIn is either a pointer to a NULL-terminated string in memory obtained
580** from malloc(), or a NULL pointer. The string pointed to by zAppend is
581** added to zIn, and the result returned in memory obtained from malloc().
582** zIn, if it was not NULL, is freed.
583**
584** If the third argument, quote, is not '\0', then it is used as a
585** quote character for zAppend.
586*/
587static void appendText(ShellText *p, char const *zAppend, char quote){
588 int len;
589 int i;
590 int nAppend = strlen30(zAppend);
591
592 len = nAppend+p->n+1;
593 if( quote ){
594 len += 2;
595 for(i=0; i<nAppend; i++){
596 if( zAppend[i]==quote ) len++;
597 }
598 }
599
600 if( p->n+len>=p->nAlloc ){
601 p->nAlloc = p->nAlloc*2 + len + 20;
602 p->z = realloc(p->z, p->nAlloc);
603 if( p->z==0 ){
604 memset(p, 0, sizeof(*p));
605 return;
606 }
607 }
608
609 if( quote ){
610 char *zCsr = p->z+p->n;
611 *zCsr++ = quote;
612 for(i=0; i<nAppend; i++){
613 *zCsr++ = zAppend[i];
614 if( zAppend[i]==quote ) *zCsr++ = quote;
615 }
616 *zCsr++ = quote;
617 p->n = (int)(zCsr - p->z);
618 *zCsr = '\0';
619 }else{
620 memcpy(p->z+p->n, zAppend, nAppend);
621 p->n += nAppend;
622 p->z[p->n] = '\0';
623 }
624}
625
626/*
627** Attempt to determine if identifier zName needs to be quoted, either
628** because it contains non-alphanumeric characters, or because it is an
629** SQLite keyword. Be conservative in this estimate: When in doubt assume
630** that quoting is required.
631**
632** Return '"' if quoting is required. Return 0 if no quoting is required.
633*/
634static char quoteChar(const char *zName){
635 /* All SQLite keywords, in alphabetical order */
636 static const char *azKeywords[] = {
637 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
638 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
639 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
640 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
641 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
642 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
643 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
644 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
645 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
646 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
647 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
648 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
649 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
650 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
651 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
652 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
653 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
654 "WITH", "WITHOUT",
655 };
656 int i, lwr, upr, mid, c;
657 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
658 for(i=0; zName[i]; i++){
659 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
660 }
661 lwr = 0;
662 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
663 while( lwr<=upr ){
664 mid = (lwr+upr)/2;
665 c = sqlite3_stricmp(azKeywords[mid], zName);
666 if( c==0 ) return '"';
667 if( c<0 ){
668 lwr = mid+1;
669 }else{
670 upr = mid-1;
671 }
672 }
673 return 0;
674}
drh8e7e7a22000-05-30 18:45:23 +0000675
drh1554bc82017-03-08 16:10:34 +0000676/******************************************************************************
677** SHA3 hash implementation copied from ../ext/misc/shathree.c
678*/
679typedef sqlite3_uint64 u64;
680/*
681** Macros to determine whether the machine is big or little endian,
682** and whether or not that determination is run-time or compile-time.
683**
684** For best performance, an attempt is made to guess at the byte-order
685** using C-preprocessor macros. If that is unsuccessful, or if
686** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
687** at run-time.
688*/
689#ifndef SHA3_BYTEORDER
690# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
691 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
692 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
693 defined(__arm__)
694# define SHA3_BYTEORDER 1234
695# elif defined(sparc) || defined(__ppc__)
696# define SHA3_BYTEORDER 4321
697# else
698# define SHA3_BYTEORDER 0
699# endif
700#endif
701
702
703/*
704** State structure for a SHA3 hash in progress
705*/
706typedef struct SHA3Context SHA3Context;
707struct SHA3Context {
708 union {
709 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
710 unsigned char x[1600]; /* ... or 1600 bytes */
711 } u;
712 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
713 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
714 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
715};
716
717/*
718** A single step of the Keccak mixing function for a 1600-bit state
719*/
720static void KeccakF1600Step(SHA3Context *p){
721 int i;
722 u64 B0, B1, B2, B3, B4;
723 u64 C0, C1, C2, C3, C4;
724 u64 D0, D1, D2, D3, D4;
725 static const u64 RC[] = {
726 0x0000000000000001ULL, 0x0000000000008082ULL,
727 0x800000000000808aULL, 0x8000000080008000ULL,
728 0x000000000000808bULL, 0x0000000080000001ULL,
729 0x8000000080008081ULL, 0x8000000000008009ULL,
730 0x000000000000008aULL, 0x0000000000000088ULL,
731 0x0000000080008009ULL, 0x000000008000000aULL,
732 0x000000008000808bULL, 0x800000000000008bULL,
733 0x8000000000008089ULL, 0x8000000000008003ULL,
734 0x8000000000008002ULL, 0x8000000000000080ULL,
735 0x000000000000800aULL, 0x800000008000000aULL,
736 0x8000000080008081ULL, 0x8000000000008080ULL,
737 0x0000000080000001ULL, 0x8000000080008008ULL
738 };
739# define A00 (p->u.s[0])
740# define A01 (p->u.s[1])
741# define A02 (p->u.s[2])
742# define A03 (p->u.s[3])
743# define A04 (p->u.s[4])
744# define A10 (p->u.s[5])
745# define A11 (p->u.s[6])
746# define A12 (p->u.s[7])
747# define A13 (p->u.s[8])
748# define A14 (p->u.s[9])
749# define A20 (p->u.s[10])
750# define A21 (p->u.s[11])
751# define A22 (p->u.s[12])
752# define A23 (p->u.s[13])
753# define A24 (p->u.s[14])
754# define A30 (p->u.s[15])
755# define A31 (p->u.s[16])
756# define A32 (p->u.s[17])
757# define A33 (p->u.s[18])
758# define A34 (p->u.s[19])
759# define A40 (p->u.s[20])
760# define A41 (p->u.s[21])
761# define A42 (p->u.s[22])
762# define A43 (p->u.s[23])
763# define A44 (p->u.s[24])
764# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
765
766 for(i=0; i<24; i+=4){
767 C0 = A00^A10^A20^A30^A40;
768 C1 = A01^A11^A21^A31^A41;
769 C2 = A02^A12^A22^A32^A42;
770 C3 = A03^A13^A23^A33^A43;
771 C4 = A04^A14^A24^A34^A44;
772 D0 = C4^ROL64(C1, 1);
773 D1 = C0^ROL64(C2, 1);
774 D2 = C1^ROL64(C3, 1);
775 D3 = C2^ROL64(C4, 1);
776 D4 = C3^ROL64(C0, 1);
777
778 B0 = (A00^D0);
779 B1 = ROL64((A11^D1), 44);
780 B2 = ROL64((A22^D2), 43);
781 B3 = ROL64((A33^D3), 21);
782 B4 = ROL64((A44^D4), 14);
783 A00 = B0 ^((~B1)& B2 );
784 A00 ^= RC[i];
785 A11 = B1 ^((~B2)& B3 );
786 A22 = B2 ^((~B3)& B4 );
787 A33 = B3 ^((~B4)& B0 );
788 A44 = B4 ^((~B0)& B1 );
789
790 B2 = ROL64((A20^D0), 3);
791 B3 = ROL64((A31^D1), 45);
792 B4 = ROL64((A42^D2), 61);
793 B0 = ROL64((A03^D3), 28);
794 B1 = ROL64((A14^D4), 20);
795 A20 = B0 ^((~B1)& B2 );
796 A31 = B1 ^((~B2)& B3 );
797 A42 = B2 ^((~B3)& B4 );
798 A03 = B3 ^((~B4)& B0 );
799 A14 = B4 ^((~B0)& B1 );
800
801 B4 = ROL64((A40^D0), 18);
802 B0 = ROL64((A01^D1), 1);
803 B1 = ROL64((A12^D2), 6);
804 B2 = ROL64((A23^D3), 25);
805 B3 = ROL64((A34^D4), 8);
806 A40 = B0 ^((~B1)& B2 );
807 A01 = B1 ^((~B2)& B3 );
808 A12 = B2 ^((~B3)& B4 );
809 A23 = B3 ^((~B4)& B0 );
810 A34 = B4 ^((~B0)& B1 );
811
812 B1 = ROL64((A10^D0), 36);
813 B2 = ROL64((A21^D1), 10);
814 B3 = ROL64((A32^D2), 15);
815 B4 = ROL64((A43^D3), 56);
816 B0 = ROL64((A04^D4), 27);
817 A10 = B0 ^((~B1)& B2 );
818 A21 = B1 ^((~B2)& B3 );
819 A32 = B2 ^((~B3)& B4 );
820 A43 = B3 ^((~B4)& B0 );
821 A04 = B4 ^((~B0)& B1 );
822
823 B3 = ROL64((A30^D0), 41);
824 B4 = ROL64((A41^D1), 2);
825 B0 = ROL64((A02^D2), 62);
826 B1 = ROL64((A13^D3), 55);
827 B2 = ROL64((A24^D4), 39);
828 A30 = B0 ^((~B1)& B2 );
829 A41 = B1 ^((~B2)& B3 );
830 A02 = B2 ^((~B3)& B4 );
831 A13 = B3 ^((~B4)& B0 );
832 A24 = B4 ^((~B0)& B1 );
833
834 C0 = A00^A20^A40^A10^A30;
835 C1 = A11^A31^A01^A21^A41;
836 C2 = A22^A42^A12^A32^A02;
837 C3 = A33^A03^A23^A43^A13;
838 C4 = A44^A14^A34^A04^A24;
839 D0 = C4^ROL64(C1, 1);
840 D1 = C0^ROL64(C2, 1);
841 D2 = C1^ROL64(C3, 1);
842 D3 = C2^ROL64(C4, 1);
843 D4 = C3^ROL64(C0, 1);
844
845 B0 = (A00^D0);
846 B1 = ROL64((A31^D1), 44);
847 B2 = ROL64((A12^D2), 43);
848 B3 = ROL64((A43^D3), 21);
849 B4 = ROL64((A24^D4), 14);
850 A00 = B0 ^((~B1)& B2 );
851 A00 ^= RC[i+1];
852 A31 = B1 ^((~B2)& B3 );
853 A12 = B2 ^((~B3)& B4 );
854 A43 = B3 ^((~B4)& B0 );
855 A24 = B4 ^((~B0)& B1 );
856
857 B2 = ROL64((A40^D0), 3);
858 B3 = ROL64((A21^D1), 45);
859 B4 = ROL64((A02^D2), 61);
860 B0 = ROL64((A33^D3), 28);
861 B1 = ROL64((A14^D4), 20);
862 A40 = B0 ^((~B1)& B2 );
863 A21 = B1 ^((~B2)& B3 );
864 A02 = B2 ^((~B3)& B4 );
865 A33 = B3 ^((~B4)& B0 );
866 A14 = B4 ^((~B0)& B1 );
867
868 B4 = ROL64((A30^D0), 18);
869 B0 = ROL64((A11^D1), 1);
870 B1 = ROL64((A42^D2), 6);
871 B2 = ROL64((A23^D3), 25);
872 B3 = ROL64((A04^D4), 8);
873 A30 = B0 ^((~B1)& B2 );
874 A11 = B1 ^((~B2)& B3 );
875 A42 = B2 ^((~B3)& B4 );
876 A23 = B3 ^((~B4)& B0 );
877 A04 = B4 ^((~B0)& B1 );
878
879 B1 = ROL64((A20^D0), 36);
880 B2 = ROL64((A01^D1), 10);
881 B3 = ROL64((A32^D2), 15);
882 B4 = ROL64((A13^D3), 56);
883 B0 = ROL64((A44^D4), 27);
884 A20 = B0 ^((~B1)& B2 );
885 A01 = B1 ^((~B2)& B3 );
886 A32 = B2 ^((~B3)& B4 );
887 A13 = B3 ^((~B4)& B0 );
888 A44 = B4 ^((~B0)& B1 );
889
890 B3 = ROL64((A10^D0), 41);
891 B4 = ROL64((A41^D1), 2);
892 B0 = ROL64((A22^D2), 62);
893 B1 = ROL64((A03^D3), 55);
894 B2 = ROL64((A34^D4), 39);
895 A10 = B0 ^((~B1)& B2 );
896 A41 = B1 ^((~B2)& B3 );
897 A22 = B2 ^((~B3)& B4 );
898 A03 = B3 ^((~B4)& B0 );
899 A34 = B4 ^((~B0)& B1 );
900
901 C0 = A00^A40^A30^A20^A10;
902 C1 = A31^A21^A11^A01^A41;
903 C2 = A12^A02^A42^A32^A22;
904 C3 = A43^A33^A23^A13^A03;
905 C4 = A24^A14^A04^A44^A34;
906 D0 = C4^ROL64(C1, 1);
907 D1 = C0^ROL64(C2, 1);
908 D2 = C1^ROL64(C3, 1);
909 D3 = C2^ROL64(C4, 1);
910 D4 = C3^ROL64(C0, 1);
911
912 B0 = (A00^D0);
913 B1 = ROL64((A21^D1), 44);
914 B2 = ROL64((A42^D2), 43);
915 B3 = ROL64((A13^D3), 21);
916 B4 = ROL64((A34^D4), 14);
917 A00 = B0 ^((~B1)& B2 );
918 A00 ^= RC[i+2];
919 A21 = B1 ^((~B2)& B3 );
920 A42 = B2 ^((~B3)& B4 );
921 A13 = B3 ^((~B4)& B0 );
922 A34 = B4 ^((~B0)& B1 );
923
924 B2 = ROL64((A30^D0), 3);
925 B3 = ROL64((A01^D1), 45);
926 B4 = ROL64((A22^D2), 61);
927 B0 = ROL64((A43^D3), 28);
928 B1 = ROL64((A14^D4), 20);
929 A30 = B0 ^((~B1)& B2 );
930 A01 = B1 ^((~B2)& B3 );
931 A22 = B2 ^((~B3)& B4 );
932 A43 = B3 ^((~B4)& B0 );
933 A14 = B4 ^((~B0)& B1 );
934
935 B4 = ROL64((A10^D0), 18);
936 B0 = ROL64((A31^D1), 1);
937 B1 = ROL64((A02^D2), 6);
938 B2 = ROL64((A23^D3), 25);
939 B3 = ROL64((A44^D4), 8);
940 A10 = B0 ^((~B1)& B2 );
941 A31 = B1 ^((~B2)& B3 );
942 A02 = B2 ^((~B3)& B4 );
943 A23 = B3 ^((~B4)& B0 );
944 A44 = B4 ^((~B0)& B1 );
945
946 B1 = ROL64((A40^D0), 36);
947 B2 = ROL64((A11^D1), 10);
948 B3 = ROL64((A32^D2), 15);
949 B4 = ROL64((A03^D3), 56);
950 B0 = ROL64((A24^D4), 27);
951 A40 = B0 ^((~B1)& B2 );
952 A11 = B1 ^((~B2)& B3 );
953 A32 = B2 ^((~B3)& B4 );
954 A03 = B3 ^((~B4)& B0 );
955 A24 = B4 ^((~B0)& B1 );
956
957 B3 = ROL64((A20^D0), 41);
958 B4 = ROL64((A41^D1), 2);
959 B0 = ROL64((A12^D2), 62);
960 B1 = ROL64((A33^D3), 55);
961 B2 = ROL64((A04^D4), 39);
962 A20 = B0 ^((~B1)& B2 );
963 A41 = B1 ^((~B2)& B3 );
964 A12 = B2 ^((~B3)& B4 );
965 A33 = B3 ^((~B4)& B0 );
966 A04 = B4 ^((~B0)& B1 );
967
968 C0 = A00^A30^A10^A40^A20;
969 C1 = A21^A01^A31^A11^A41;
970 C2 = A42^A22^A02^A32^A12;
971 C3 = A13^A43^A23^A03^A33;
972 C4 = A34^A14^A44^A24^A04;
973 D0 = C4^ROL64(C1, 1);
974 D1 = C0^ROL64(C2, 1);
975 D2 = C1^ROL64(C3, 1);
976 D3 = C2^ROL64(C4, 1);
977 D4 = C3^ROL64(C0, 1);
978
979 B0 = (A00^D0);
980 B1 = ROL64((A01^D1), 44);
981 B2 = ROL64((A02^D2), 43);
982 B3 = ROL64((A03^D3), 21);
983 B4 = ROL64((A04^D4), 14);
984 A00 = B0 ^((~B1)& B2 );
985 A00 ^= RC[i+3];
986 A01 = B1 ^((~B2)& B3 );
987 A02 = B2 ^((~B3)& B4 );
988 A03 = B3 ^((~B4)& B0 );
989 A04 = B4 ^((~B0)& B1 );
990
991 B2 = ROL64((A10^D0), 3);
992 B3 = ROL64((A11^D1), 45);
993 B4 = ROL64((A12^D2), 61);
994 B0 = ROL64((A13^D3), 28);
995 B1 = ROL64((A14^D4), 20);
996 A10 = B0 ^((~B1)& B2 );
997 A11 = B1 ^((~B2)& B3 );
998 A12 = B2 ^((~B3)& B4 );
999 A13 = B3 ^((~B4)& B0 );
1000 A14 = B4 ^((~B0)& B1 );
1001
1002 B4 = ROL64((A20^D0), 18);
1003 B0 = ROL64((A21^D1), 1);
1004 B1 = ROL64((A22^D2), 6);
1005 B2 = ROL64((A23^D3), 25);
1006 B3 = ROL64((A24^D4), 8);
1007 A20 = B0 ^((~B1)& B2 );
1008 A21 = B1 ^((~B2)& B3 );
1009 A22 = B2 ^((~B3)& B4 );
1010 A23 = B3 ^((~B4)& B0 );
1011 A24 = B4 ^((~B0)& B1 );
1012
1013 B1 = ROL64((A30^D0), 36);
1014 B2 = ROL64((A31^D1), 10);
1015 B3 = ROL64((A32^D2), 15);
1016 B4 = ROL64((A33^D3), 56);
1017 B0 = ROL64((A34^D4), 27);
1018 A30 = B0 ^((~B1)& B2 );
1019 A31 = B1 ^((~B2)& B3 );
1020 A32 = B2 ^((~B3)& B4 );
1021 A33 = B3 ^((~B4)& B0 );
1022 A34 = B4 ^((~B0)& B1 );
1023
1024 B3 = ROL64((A40^D0), 41);
1025 B4 = ROL64((A41^D1), 2);
1026 B0 = ROL64((A42^D2), 62);
1027 B1 = ROL64((A43^D3), 55);
1028 B2 = ROL64((A44^D4), 39);
1029 A40 = B0 ^((~B1)& B2 );
1030 A41 = B1 ^((~B2)& B3 );
1031 A42 = B2 ^((~B3)& B4 );
1032 A43 = B3 ^((~B4)& B0 );
1033 A44 = B4 ^((~B0)& B1 );
1034 }
1035}
1036
1037/*
1038** Initialize a new hash. iSize determines the size of the hash
1039** in bits and should be one of 224, 256, 384, or 512. Or iSize
1040** can be zero to use the default hash size of 256 bits.
1041*/
1042static void SHA3Init(SHA3Context *p, int iSize){
1043 memset(p, 0, sizeof(*p));
1044 if( iSize>=128 && iSize<=512 ){
1045 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1046 }else{
1047 p->nRate = (1600 - 2*256)/8;
1048 }
1049#if SHA3_BYTEORDER==1234
1050 /* Known to be little-endian at compile-time. No-op */
1051#elif SHA3_BYTEORDER==4321
1052 p->ixMask = 7; /* Big-endian */
1053#else
1054 {
1055 static unsigned int one = 1;
1056 if( 1==*(unsigned char*)&one ){
1057 /* Little endian. No byte swapping. */
1058 p->ixMask = 0;
1059 }else{
1060 /* Big endian. Byte swap. */
1061 p->ixMask = 7;
1062 }
1063 }
1064#endif
1065}
1066
1067/*
1068** Make consecutive calls to the SHA3Update function to add new content
1069** to the hash
1070*/
1071static void SHA3Update(
1072 SHA3Context *p,
1073 const unsigned char *aData,
1074 unsigned int nData
1075){
1076 unsigned int i = 0;
1077#if SHA3_BYTEORDER==1234
1078 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1079 for(; i+7<nData; i+=8){
1080 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1081 p->nLoaded += 8;
1082 if( p->nLoaded>=p->nRate ){
1083 KeccakF1600Step(p);
1084 p->nLoaded = 0;
1085 }
1086 }
1087 }
1088#endif
1089 for(; i<nData; i++){
1090#if SHA3_BYTEORDER==1234
1091 p->u.x[p->nLoaded] ^= aData[i];
1092#elif SHA3_BYTEORDER==4321
1093 p->u.x[p->nLoaded^0x07] ^= aData[i];
1094#else
1095 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1096#endif
1097 p->nLoaded++;
1098 if( p->nLoaded==p->nRate ){
1099 KeccakF1600Step(p);
1100 p->nLoaded = 0;
1101 }
1102 }
1103}
1104
1105/*
1106** After all content has been added, invoke SHA3Final() to compute
1107** the final hash. The function returns a pointer to the binary
1108** hash value.
1109*/
1110static unsigned char *SHA3Final(SHA3Context *p){
1111 unsigned int i;
1112 if( p->nLoaded==p->nRate-1 ){
1113 const unsigned char c1 = 0x86;
1114 SHA3Update(p, &c1, 1);
1115 }else{
1116 const unsigned char c2 = 0x06;
1117 const unsigned char c3 = 0x80;
1118 SHA3Update(p, &c2, 1);
1119 p->nLoaded = p->nRate - 1;
1120 SHA3Update(p, &c3, 1);
1121 }
1122 for(i=0; i<p->nRate; i++){
1123 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1124 }
1125 return &p->u.x[p->nRate];
1126}
1127
1128/*
1129** Implementation of the sha3(X,SIZE) function.
1130**
1131** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
1132** size is 256. If X is a BLOB, it is hashed as is.
1133** For all other non-NULL types of input, X is converted into a UTF-8 string
1134** and the string is hashed without the trailing 0x00 terminator. The hash
1135** of a NULL value is NULL.
1136*/
1137static void sha3Func(
1138 sqlite3_context *context,
1139 int argc,
1140 sqlite3_value **argv
1141){
1142 SHA3Context cx;
1143 int eType = sqlite3_value_type(argv[0]);
1144 int nByte = sqlite3_value_bytes(argv[0]);
1145 int iSize;
1146 if( argc==1 ){
1147 iSize = 256;
1148 }else{
1149 iSize = sqlite3_value_int(argv[1]);
1150 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1151 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1152 "384 512", -1);
1153 return;
1154 }
1155 }
1156 if( eType==SQLITE_NULL ) return;
1157 SHA3Init(&cx, iSize);
1158 if( eType==SQLITE_BLOB ){
1159 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1160 }else{
1161 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1162 }
1163 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1164}
1165
1166/* Compute a string using sqlite3_vsnprintf() with a maximum length
1167** of 50 bytes and add it to the hash.
1168*/
1169static void hash_step_vformat(
1170 SHA3Context *p, /* Add content to this context */
1171 const char *zFormat,
1172 ...
1173){
1174 va_list ap;
1175 int n;
1176 char zBuf[50];
1177 va_start(ap, zFormat);
1178 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1179 va_end(ap);
1180 n = (int)strlen(zBuf);
1181 SHA3Update(p, (unsigned char*)zBuf, n);
1182}
1183
1184/*
1185** Implementation of the sha3_query(SQL,SIZE) function.
1186**
1187** This function compiles and runs the SQL statement(s) given in the
1188** argument. The results are hashed using a SIZE-bit SHA3. The default
1189** size is 256.
1190**
1191** The format of the byte stream that is hashed is summarized as follows:
1192**
1193** S<n>:<sql>
1194** R
1195** N
1196** I<int>
1197** F<ieee-float>
1198** B<size>:<bytes>
1199** T<size>:<text>
1200**
1201** <sql> is the original SQL text for each statement run and <n> is
1202** the size of that text. The SQL text is UTF-8. A single R character
1203** occurs before the start of each row. N means a NULL value.
1204** I mean an 8-byte little-endian integer <int>. F is a floating point
1205** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1206** B means blobs of <size> bytes. T means text rendered as <size>
1207** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1208** text integers.
1209**
1210** For each SQL statement in the X input, there is one S segment. Each
1211** S segment is followed by zero or more R segments, one for each row in the
1212** result set. After each R, there are one or more N, I, F, B, or T segments,
1213** one for each column in the result set. Segments are concatentated directly
1214** with no delimiters of any kind.
1215*/
1216static void sha3QueryFunc(
1217 sqlite3_context *context,
1218 int argc,
1219 sqlite3_value **argv
1220){
1221 sqlite3 *db = sqlite3_context_db_handle(context);
1222 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1223 sqlite3_stmt *pStmt = 0;
1224 int nCol; /* Number of columns in the result set */
1225 int i; /* Loop counter */
1226 int rc;
1227 int n;
1228 const char *z;
1229 SHA3Context cx;
1230 int iSize;
1231
1232 if( argc==1 ){
1233 iSize = 256;
1234 }else{
1235 iSize = sqlite3_value_int(argv[1]);
1236 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1237 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1238 "384 512", -1);
1239 return;
1240 }
1241 }
1242 if( zSql==0 ) return;
1243 SHA3Init(&cx, iSize);
1244 while( zSql[0] ){
1245 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1246 if( rc ){
1247 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1248 zSql, sqlite3_errmsg(db));
1249 sqlite3_finalize(pStmt);
1250 sqlite3_result_error(context, zMsg, -1);
1251 sqlite3_free(zMsg);
1252 return;
1253 }
1254 if( !sqlite3_stmt_readonly(pStmt) ){
1255 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1256 sqlite3_finalize(pStmt);
1257 sqlite3_result_error(context, zMsg, -1);
1258 sqlite3_free(zMsg);
1259 return;
1260 }
1261 nCol = sqlite3_column_count(pStmt);
1262 z = sqlite3_sql(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00001263 if( z==0 ){
1264 sqlite3_finalize(pStmt);
1265 continue;
1266 }
drh1554bc82017-03-08 16:10:34 +00001267 n = (int)strlen(z);
1268 hash_step_vformat(&cx,"S%d:",n);
1269 SHA3Update(&cx,(unsigned char*)z,n);
1270
1271 /* Compute a hash over the result of the query */
1272 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1273 SHA3Update(&cx,(const unsigned char*)"R",1);
1274 for(i=0; i<nCol; i++){
1275 switch( sqlite3_column_type(pStmt,i) ){
1276 case SQLITE_NULL: {
1277 SHA3Update(&cx, (const unsigned char*)"N",1);
1278 break;
1279 }
1280 case SQLITE_INTEGER: {
1281 sqlite3_uint64 u;
1282 int j;
1283 unsigned char x[9];
1284 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1285 memcpy(&u, &v, 8);
1286 for(j=8; j>=1; j--){
1287 x[j] = u & 0xff;
1288 u >>= 8;
1289 }
1290 x[0] = 'I';
1291 SHA3Update(&cx, x, 9);
1292 break;
1293 }
1294 case SQLITE_FLOAT: {
1295 sqlite3_uint64 u;
1296 int j;
1297 unsigned char x[9];
1298 double r = sqlite3_column_double(pStmt,i);
1299 memcpy(&u, &r, 8);
1300 for(j=8; j>=1; j--){
1301 x[j] = u & 0xff;
1302 u >>= 8;
1303 }
1304 x[0] = 'F';
1305 SHA3Update(&cx,x,9);
1306 break;
1307 }
1308 case SQLITE_TEXT: {
1309 int n2 = sqlite3_column_bytes(pStmt, i);
1310 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1311 hash_step_vformat(&cx,"T%d:",n2);
1312 SHA3Update(&cx, z2, n2);
1313 break;
1314 }
1315 case SQLITE_BLOB: {
1316 int n2 = sqlite3_column_bytes(pStmt, i);
1317 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1318 hash_step_vformat(&cx,"B%d:",n2);
1319 SHA3Update(&cx, z2, n2);
1320 break;
1321 }
1322 }
1323 }
1324 }
1325 sqlite3_finalize(pStmt);
1326 }
1327 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1328}
1329/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1330********************************************************************************/
1331
drhe6229612014-08-18 15:08:26 +00001332#if defined(SQLITE_ENABLE_SESSION)
1333/*
1334** State information for a single open session
1335*/
1336typedef struct OpenSession OpenSession;
1337struct OpenSession {
1338 char *zName; /* Symbolic name for this session */
1339 int nFilter; /* Number of xFilter rejection GLOB patterns */
1340 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1341 sqlite3_session *p; /* The open session */
1342};
1343#endif
1344
drhdcd87a92014-08-18 13:45:42 +00001345/*
mistachkin1fe36bb2016-04-04 02:16:44 +00001346** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00001347** saved so that it can be restored by ".explain off"
1348*/
1349typedef struct SavedModeInfo SavedModeInfo;
1350struct SavedModeInfo {
1351 int valid; /* Is there legit data in here? */
1352 int mode; /* Mode prior to ".explain on" */
1353 int showHeader; /* The ".header" setting prior to ".explain on" */
1354 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00001355};
drh45e29d82006-11-20 16:21:10 +00001356
drh8e7e7a22000-05-30 18:45:23 +00001357/*
drhdcd87a92014-08-18 13:45:42 +00001358** State information about the database connection is contained in an
1359** instance of the following structure.
drh75897232000-05-29 14:26:00 +00001360*/
drhdcd87a92014-08-18 13:45:42 +00001361typedef struct ShellState ShellState;
1362struct ShellState {
shane626a6e42009-10-22 17:30:15 +00001363 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00001364 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00001365 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00001366 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00001367 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00001368 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00001369 int cnt; /* Number of records displayed so far */
1370 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00001371 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00001372 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00001373 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00001374 int cMode; /* temporary output mode for the current query */
1375 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00001376 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00001377 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00001378 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00001379 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00001380 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00001381 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00001382 char colSeparator[20]; /* Column separator character for several modes */
1383 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00001384 int colWidth[100]; /* Requested width of each column when in column mode*/
1385 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00001386 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00001387 ** the database */
drh44c2eb12003-04-30 11:38:26 +00001388 char outfile[FILENAME_MAX]; /* Filename for *out */
1389 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00001390 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00001391 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00001392 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00001393 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00001394 int *aiIndent; /* Array of indents used in MODE_Explain */
1395 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00001396 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00001397#if defined(SQLITE_ENABLE_SESSION)
1398 int nSession; /* Number of active sessions */
1399 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1400#endif
drh75897232000-05-29 14:26:00 +00001401};
1402
1403/*
drh44dec872014-08-30 15:49:25 +00001404** These are the allowed shellFlgs values
1405*/
drhe6e1d122017-03-09 13:50:49 +00001406#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1407#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1408#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1409#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1410#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1411#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1412#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1413
1414/*
1415** Macros for testing and setting shellFlgs
1416*/
1417#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1418#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1419#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00001420
1421/*
drh75897232000-05-29 14:26:00 +00001422** These are the allowed modes.
1423*/
drh967e8b72000-06-21 13:59:10 +00001424#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00001425#define MODE_Column 1 /* One record per line in neat columns */
1426#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00001427#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1428#define MODE_Html 4 /* Generate an XHTML table */
1429#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00001430#define MODE_Quote 6 /* Quote values as for SQL */
1431#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1432#define MODE_Csv 8 /* Quote strings, numbers are plain */
1433#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1434#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1435#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00001436
drh66ce4d02008-02-15 17:38:06 +00001437static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00001438 "line",
1439 "column",
1440 "list",
1441 "semi",
1442 "html",
drhfeac5f82004-08-01 00:10:45 +00001443 "insert",
drh41f5f6e2016-10-21 17:39:30 +00001444 "quote",
drhfeac5f82004-08-01 00:10:45 +00001445 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00001446 "csv",
drh66ce4d02008-02-15 17:38:06 +00001447 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00001448 "ascii",
drh4926fec2016-04-13 15:33:42 +00001449 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00001450};
drh75897232000-05-29 14:26:00 +00001451
1452/*
mistachkinfad42082014-07-24 22:13:12 +00001453** These are the column/row/line separators used by the various
1454** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00001455*/
mistachkinfad42082014-07-24 22:13:12 +00001456#define SEP_Column "|"
1457#define SEP_Row "\n"
1458#define SEP_Tab "\t"
1459#define SEP_Space " "
1460#define SEP_Comma ","
1461#define SEP_CrLf "\r\n"
1462#define SEP_Unit "\x1F"
1463#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00001464
1465/*
drh75897232000-05-29 14:26:00 +00001466** Number of elements in an array
1467*/
drh902b9ee2008-12-05 17:17:07 +00001468#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00001469
1470/*
drh127f9d72010-02-23 01:47:00 +00001471** A callback for the sqlite3_log() interface.
1472*/
1473static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00001474 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00001475 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00001476 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00001477 fflush(p->pLog);
1478}
1479
1480/*
shane626a6e42009-10-22 17:30:15 +00001481** Output the given string as a hex-encoded blob (eg. X'1234' )
1482*/
1483static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1484 int i;
1485 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00001486 raw_printf(out,"X'");
1487 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1488 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00001489}
1490
1491/*
drh28bd4bc2000-06-15 15:57:22 +00001492** Output the given string as a quoted string using SQL quoting conventions.
1493*/
1494static void output_quoted_string(FILE *out, const char *z){
1495 int i;
1496 int nSingle = 0;
mistachkin1fe36bb2016-04-04 02:16:44 +00001497 setBinaryMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001498 for(i=0; z[i]; i++){
1499 if( z[i]=='\'' ) nSingle++;
drh28bd4bc2000-06-15 15:57:22 +00001500 }
1501 if( nSingle==0 ){
drhe05461c2015-12-30 13:36:57 +00001502 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00001503 }else{
mistachkinaae280e2015-12-31 19:06:24 +00001504 raw_printf(out,"'");
drh28bd4bc2000-06-15 15:57:22 +00001505 while( *z ){
1506 for(i=0; z[i] && z[i]!='\''; i++){}
1507 if( i==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00001508 raw_printf(out,"''");
drh28bd4bc2000-06-15 15:57:22 +00001509 z++;
1510 }else if( z[i]=='\'' ){
drhe05461c2015-12-30 13:36:57 +00001511 utf8_printf(out,"%.*s''",i,z);
drh28bd4bc2000-06-15 15:57:22 +00001512 z += i+1;
1513 }else{
drhe05461c2015-12-30 13:36:57 +00001514 utf8_printf(out,"%s",z);
drh28bd4bc2000-06-15 15:57:22 +00001515 break;
1516 }
1517 }
mistachkinaae280e2015-12-31 19:06:24 +00001518 raw_printf(out,"'");
drh28bd4bc2000-06-15 15:57:22 +00001519 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001520 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001521}
1522
1523/*
drhfeac5f82004-08-01 00:10:45 +00001524** Output the given string as a quoted according to C or TCL quoting rules.
1525*/
1526static void output_c_string(FILE *out, const char *z){
1527 unsigned int c;
1528 fputc('"', out);
1529 while( (c = *(z++))!=0 ){
1530 if( c=='\\' ){
1531 fputc(c, out);
1532 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00001533 }else if( c=='"' ){
1534 fputc('\\', out);
1535 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00001536 }else if( c=='\t' ){
1537 fputc('\\', out);
1538 fputc('t', out);
1539 }else if( c=='\n' ){
1540 fputc('\\', out);
1541 fputc('n', out);
1542 }else if( c=='\r' ){
1543 fputc('\\', out);
1544 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00001545 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00001546 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00001547 }else{
1548 fputc(c, out);
1549 }
1550 }
1551 fputc('"', out);
1552}
1553
1554/*
drhc08a4f12000-06-15 16:49:48 +00001555** Output the given string with characters that are special to
1556** HTML escaped.
1557*/
1558static void output_html_string(FILE *out, const char *z){
1559 int i;
drhc3d6ba42014-01-13 20:38:35 +00001560 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00001561 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00001562 for(i=0; z[i]
1563 && z[i]!='<'
1564 && z[i]!='&'
1565 && z[i]!='>'
1566 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00001567 && z[i]!='\'';
1568 i++){}
drhc08a4f12000-06-15 16:49:48 +00001569 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00001570 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00001571 }
1572 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00001573 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00001574 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00001575 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00001576 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00001577 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00001578 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00001579 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00001580 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00001581 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00001582 }else{
1583 break;
1584 }
1585 z += i + 1;
1586 }
1587}
1588
1589/*
drhc49f44e2006-10-26 18:15:42 +00001590** If a field contains any character identified by a 1 in the following
1591** array, then the string must be quoted for CSV.
1592*/
1593static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00001594 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1595 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1596 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1597 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1598 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1599 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1600 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1601 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1602 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1603 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1604 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1605 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1606 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1607 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1608 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1609 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00001610};
1611
1612/*
mistachkindd11f2d2014-12-11 04:49:46 +00001613** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00001614** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00001615** the null value. Strings are quoted if necessary. The separator
1616** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00001617*/
drhdcd87a92014-08-18 13:45:42 +00001618static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00001619 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00001620 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00001621 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00001622 }else{
drhc49f44e2006-10-26 18:15:42 +00001623 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00001624 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00001625 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00001626 if( needCsvQuote[((unsigned char*)z)[i]]
1627 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00001628 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00001629 i = 0;
1630 break;
1631 }
1632 }
1633 if( i==0 ){
1634 putc('"', out);
1635 for(i=0; z[i]; i++){
1636 if( z[i]=='"' ) putc('"', out);
1637 putc(z[i], out);
1638 }
1639 putc('"', out);
1640 }else{
drhe05461c2015-12-30 13:36:57 +00001641 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00001642 }
drh8e64d1c2004-10-07 00:32:39 +00001643 }
1644 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00001645 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001646 }
1647}
1648
danielk19774af00c62005-01-23 23:43:21 +00001649#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00001650/*
drh4c504392000-10-16 22:06:40 +00001651** This routine runs when the user presses Ctrl-C
1652*/
1653static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00001654 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00001655 seenInterrupt++;
1656 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00001657 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00001658}
danielk19774af00c62005-01-23 23:43:21 +00001659#endif
drh4c504392000-10-16 22:06:40 +00001660
drha0daa752016-09-16 11:53:10 +00001661#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00001662/*
drhde613c62016-04-04 17:23:10 +00001663** When the ".auth ON" is set, the following authorizer callback is
1664** invoked. It always returns SQLITE_OK.
1665*/
1666static int shellAuth(
1667 void *pClientData,
1668 int op,
1669 const char *zA1,
1670 const char *zA2,
1671 const char *zA3,
1672 const char *zA4
1673){
1674 ShellState *p = (ShellState*)pClientData;
1675 static const char *azAction[] = { 0,
1676 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1677 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1678 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1679 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1680 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1681 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1682 "PRAGMA", "READ", "SELECT",
1683 "TRANSACTION", "UPDATE", "ATTACH",
1684 "DETACH", "ALTER_TABLE", "REINDEX",
1685 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1686 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1687 };
1688 int i;
1689 const char *az[4];
1690 az[0] = zA1;
1691 az[1] = zA2;
1692 az[2] = zA3;
1693 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00001694 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00001695 for(i=0; i<4; i++){
1696 raw_printf(p->out, " ");
1697 if( az[i] ){
1698 output_c_string(p->out, az[i]);
1699 }else{
1700 raw_printf(p->out, "NULL");
1701 }
1702 }
1703 raw_printf(p->out, "\n");
1704 return SQLITE_OK;
1705}
drha0daa752016-09-16 11:53:10 +00001706#endif
mistachkin8145fc62016-09-16 20:39:21 +00001707
drh79f20e92016-12-13 23:22:39 +00001708/*
1709** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1710**
1711** This routine converts some CREATE TABLE statements for shadow tables
1712** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1713*/
1714static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1715 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1716 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1717 }else{
1718 utf8_printf(out, "%s%s", z, zTail);
1719 }
1720}
1721static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1722 char c = z[n];
1723 z[n] = 0;
1724 printSchemaLine(out, z, zTail);
1725 z[n] = c;
1726}
drhde613c62016-04-04 17:23:10 +00001727
1728/*
shane626a6e42009-10-22 17:30:15 +00001729** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00001730** invokes for each row of a query result.
1731*/
drh4ace5362014-11-10 14:42:28 +00001732static int shell_callback(
1733 void *pArg,
1734 int nArg, /* Number of result columns */
1735 char **azArg, /* Text of each result column */
1736 char **azCol, /* Column names */
1737 int *aiType /* Column types */
1738){
drh75897232000-05-29 14:26:00 +00001739 int i;
drhdcd87a92014-08-18 13:45:42 +00001740 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00001741
drh700c2522016-02-09 18:39:25 +00001742 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00001743 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00001744 int w = 5;
drh6a535342001-10-19 16:44:56 +00001745 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00001746 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00001747 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00001748 if( len>w ) w = len;
1749 }
drhe05461c2015-12-30 13:36:57 +00001750 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001751 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001752 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00001753 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001754 }
1755 break;
1756 }
danielk19770d78bae2008-01-03 07:09:48 +00001757 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00001758 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00001759 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1760 const int *colWidth;
1761 int showHdr;
1762 char *rowSep;
1763 if( p->cMode==MODE_Column ){
1764 colWidth = p->colWidth;
1765 showHdr = p->showHeader;
1766 rowSep = p->rowSeparator;
1767 }else{
1768 colWidth = aExplainWidths;
1769 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00001770 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00001771 }
drha0c66f52000-07-29 13:20:21 +00001772 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00001773 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00001774 int w, n;
1775 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00001776 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00001777 }else{
danielk19770d78bae2008-01-03 07:09:48 +00001778 w = 0;
drh75897232000-05-29 14:26:00 +00001779 }
drh078b1fd2012-09-21 13:40:02 +00001780 if( w==0 ){
drh4f21c4a2008-12-10 22:15:00 +00001781 w = strlen30(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00001782 if( w<10 ) w = 10;
mistachkin44b99f72014-12-11 03:29:14 +00001783 n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00001784 if( w<n ) w = n;
1785 }
1786 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00001787 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00001788 }
drh700c2522016-02-09 18:39:25 +00001789 if( showHdr ){
drh078b1fd2012-09-21 13:40:02 +00001790 if( w<0 ){
drhe05461c2015-12-30 13:36:57 +00001791 utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
drh700c2522016-02-09 18:39:25 +00001792 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001793 }else{
drhe05461c2015-12-30 13:36:57 +00001794 utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
drh700c2522016-02-09 18:39:25 +00001795 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001796 }
drha0c66f52000-07-29 13:20:21 +00001797 }
1798 }
drh700c2522016-02-09 18:39:25 +00001799 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00001800 for(i=0; i<nArg; i++){
1801 int w;
1802 if( i<ArraySize(p->actualWidth) ){
1803 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00001804 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00001805 }else{
1806 w = 10;
1807 }
mistachkinaae280e2015-12-31 19:06:24 +00001808 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00001809 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00001810 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00001811 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001812 }
drh75897232000-05-29 14:26:00 +00001813 }
1814 }
drh6a535342001-10-19 16:44:56 +00001815 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00001816 for(i=0; i<nArg; i++){
1817 int w;
drha0c66f52000-07-29 13:20:21 +00001818 if( i<ArraySize(p->actualWidth) ){
1819 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00001820 }else{
1821 w = 10;
1822 }
drh700c2522016-02-09 18:39:25 +00001823 if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
drh4f21c4a2008-12-10 22:15:00 +00001824 w = strlen30(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00001825 }
dana98bf362013-11-13 18:35:01 +00001826 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00001827 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00001828 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00001829 }
danc4650bb2013-11-18 08:41:06 +00001830 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00001831 }
drh078b1fd2012-09-21 13:40:02 +00001832 if( w<0 ){
drhe05461c2015-12-30 13:36:57 +00001833 utf8_printf(p->out,"%*.*s%s",-w,-w,
mistachkin44b99f72014-12-11 03:29:14 +00001834 azArg[i] ? azArg[i] : p->nullValue,
drh700c2522016-02-09 18:39:25 +00001835 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001836 }else{
drhe05461c2015-12-30 13:36:57 +00001837 utf8_printf(p->out,"%-*.*s%s",w,w,
mistachkin44b99f72014-12-11 03:29:14 +00001838 azArg[i] ? azArg[i] : p->nullValue,
drh700c2522016-02-09 18:39:25 +00001839 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001840 }
drh75897232000-05-29 14:26:00 +00001841 }
1842 break;
1843 }
drh4926fec2016-04-13 15:33:42 +00001844 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00001845 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00001846 break;
1847 }
1848 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1849 char *z;
drh07d683f2016-04-13 21:00:36 +00001850 int j;
drh4926fec2016-04-13 15:33:42 +00001851 int nParen = 0;
1852 char cEnd = 0;
1853 char c;
1854 int nLine = 0;
1855 assert( nArg==1 );
1856 if( azArg[0]==0 ) break;
1857 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1858 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1859 ){
1860 utf8_printf(p->out, "%s;\n", azArg[0]);
1861 break;
1862 }
1863 z = sqlite3_mprintf("%s", azArg[0]);
1864 j = 0;
1865 for(i=0; IsSpace(z[i]); i++){}
1866 for(; (c = z[i])!=0; i++){
1867 if( IsSpace(c) ){
1868 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1869 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1870 j--;
1871 }
1872 z[j++] = c;
1873 }
1874 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1875 z[j] = 0;
1876 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00001877 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00001878 if( c==cEnd ){
1879 cEnd = 0;
1880 }else if( c=='"' || c=='\'' || c=='`' ){
1881 cEnd = c;
1882 }else if( c=='[' ){
1883 cEnd = ']';
1884 }else if( c=='(' ){
1885 nParen++;
1886 }else if( c==')' ){
1887 nParen--;
1888 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00001889 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00001890 j = 0;
1891 }
1892 }
1893 z[j++] = c;
1894 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1895 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00001896 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00001897 j = 0;
1898 nLine++;
1899 while( IsSpace(z[i+1]) ){ i++; }
1900 }
1901 }
1902 z[j] = 0;
1903 }
drh79f20e92016-12-13 23:22:39 +00001904 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00001905 sqlite3_free(z);
1906 break;
1907 }
drh75897232000-05-29 14:26:00 +00001908 case MODE_List: {
1909 if( p->cnt++==0 && p->showHeader ){
1910 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001911 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00001912 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00001913 }
1914 }
drh6a535342001-10-19 16:44:56 +00001915 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00001916 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00001917 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00001918 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00001919 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00001920 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00001921 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00001922 }else{
drhe05461c2015-12-30 13:36:57 +00001923 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00001924 }
drh75897232000-05-29 14:26:00 +00001925 }
1926 break;
1927 }
drh1e5d0e92000-05-31 23:33:17 +00001928 case MODE_Html: {
1929 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00001930 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00001931 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00001932 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00001933 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00001934 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00001935 }
mistachkinaae280e2015-12-31 19:06:24 +00001936 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00001937 }
drh6a535342001-10-19 16:44:56 +00001938 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00001939 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00001940 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00001941 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00001942 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00001943 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00001944 }
mistachkinaae280e2015-12-31 19:06:24 +00001945 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00001946 break;
1947 }
drhfeac5f82004-08-01 00:10:45 +00001948 case MODE_Tcl: {
1949 if( p->cnt++==0 && p->showHeader ){
1950 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00001951 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00001952 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00001953 }
drhe05461c2015-12-30 13:36:57 +00001954 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00001955 }
1956 if( azArg==0 ) break;
1957 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00001958 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00001959 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00001960 }
drhe05461c2015-12-30 13:36:57 +00001961 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00001962 break;
1963 }
drh8e64d1c2004-10-07 00:32:39 +00001964 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00001965 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00001966 if( p->cnt++==0 && p->showHeader ){
1967 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00001968 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00001969 }
drhe05461c2015-12-30 13:36:57 +00001970 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001971 }
drh40253262014-10-17 21:35:05 +00001972 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00001973 for(i=0; i<nArg; i++){
1974 output_csv(p, azArg[i], i<nArg-1);
1975 }
drhe05461c2015-12-30 13:36:57 +00001976 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001977 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001978 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00001979 break;
1980 }
drh41f5f6e2016-10-21 17:39:30 +00001981 case MODE_Quote:
drh28bd4bc2000-06-15 15:57:22 +00001982 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00001983 if( azArg==0 ) break;
drh41f5f6e2016-10-21 17:39:30 +00001984 if( p->cMode==MODE_Insert ){
1985 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
1986 if( p->showHeader ){
1987 raw_printf(p->out,"(");
1988 for(i=0; i<nArg; i++){
1989 char *zSep = i>0 ? ",": "";
1990 utf8_printf(p->out, "%s%s", zSep, azCol[i]);
1991 }
1992 raw_printf(p->out,")");
mistachkin151c75a2015-04-07 21:16:40 +00001993 }
drh41f5f6e2016-10-21 17:39:30 +00001994 raw_printf(p->out," VALUES(");
drh59ce2c42016-11-03 13:12:28 +00001995 }else if( p->cnt==0 && p->showHeader ){
1996 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00001997 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00001998 output_quoted_string(p->out, azCol[i]);
1999 }
mistachkin2f9a6132016-11-11 05:19:45 +00002000 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002001 }
drh59ce2c42016-11-03 13:12:28 +00002002 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002003 for(i=0; i<nArg; i++){
2004 char *zSep = i>0 ? ",": "";
shanead6b8d02009-10-22 18:12:58 +00002005 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
mistachkinaae280e2015-12-31 19:06:24 +00002006 utf8_printf(p->out,"%sNULL",zSep);
shanead6b8d02009-10-22 18:12:58 +00002007 }else if( aiType && aiType[i]==SQLITE_TEXT ){
mistachkinaae280e2015-12-31 19:06:24 +00002008 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
shanead6b8d02009-10-22 18:12:58 +00002009 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002010 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drhe05461c2015-12-30 13:36:57 +00002011 utf8_printf(p->out,"%s%s",zSep, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002012 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2013 char z[50];
2014 double r = sqlite3_column_double(p->pStmt, i);
2015 sqlite3_snprintf(50,z,"%!.20g", r);
2016 raw_printf(p->out, "%s%s", zSep, z);
shane626a6e42009-10-22 17:30:15 +00002017 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2018 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2019 int nBlob = sqlite3_column_bytes(p->pStmt, i);
mistachkinaae280e2015-12-31 19:06:24 +00002020 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
shane626a6e42009-10-22 17:30:15 +00002021 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002022 }else if( isNumber(azArg[i], 0) ){
drhe05461c2015-12-30 13:36:57 +00002023 utf8_printf(p->out,"%s%s",zSep, azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002024 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002025 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
drh28bd4bc2000-06-15 15:57:22 +00002026 output_quoted_string(p->out, azArg[i]);
2027 }
2028 }
drh41f5f6e2016-10-21 17:39:30 +00002029 raw_printf(p->out,p->cMode==MODE_Quote?"\n":");\n");
drh6a535342001-10-19 16:44:56 +00002030 break;
drh28bd4bc2000-06-15 15:57:22 +00002031 }
mistachkin636bf9f2014-07-19 20:15:16 +00002032 case MODE_Ascii: {
2033 if( p->cnt++==0 && p->showHeader ){
2034 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002035 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2036 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002037 }
drhe05461c2015-12-30 13:36:57 +00002038 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002039 }
2040 if( azArg==0 ) break;
2041 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002042 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2043 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002044 }
drhe05461c2015-12-30 13:36:57 +00002045 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002046 break;
2047 }
persicom1d0b8722002-04-18 02:53:04 +00002048 }
drh75897232000-05-29 14:26:00 +00002049 return 0;
2050}
2051
2052/*
shane626a6e42009-10-22 17:30:15 +00002053** This is the callback routine that the SQLite library
2054** invokes for each row of a query result.
2055*/
2056static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2057 /* since we don't have type info, call the shell_callback with a NULL value */
2058 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2059}
2060
drhfb546af2017-03-09 22:00:33 +00002061/*
2062** This is the callback routine from sqlite3_exec() that appends all
2063** output onto the end of a ShellText object.
2064*/
2065static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2066 ShellText *p = (ShellText*)pArg;
2067 int i;
2068 if( p->n ) appendText(p, "|", 0);
2069 for(i=0; i<nArg; i++){
2070 if( i ) appendText(p, ",", 0);
2071 if( azArg[i] ) appendText(p, azArg[i], 0);
2072 }
2073 return 0;
2074}
2075
2076/*
2077** Generate an appropriate SELFTEST table in the main database.
2078*/
2079static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00002080 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00002081 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00002082 "SAVEPOINT selftest_init;\n"
2083 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00002084 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2085 " op TEXT,\n" /* Operator: memo run */
2086 " cmd TEXT,\n" /* Command text */
2087 " ans TEXT\n" /* Desired answer */
2088 ");"
drhf157d102017-03-10 01:05:38 +00002089 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2090 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2091 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2092 " 'memo','Tests generated by --init');\n"
2093 "INSERT INTO [_shell$self]\n"
2094 " SELECT 'run',\n"
2095 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2096 "FROM sqlite_master ORDER BY 2'',224))',\n"
2097 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2098 "FROM sqlite_master ORDER BY 2',224));\n"
2099 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002100 " SELECT 'run',"
2101 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2102 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2103 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2104 " FROM (\n"
2105 " SELECT name FROM sqlite_master\n"
2106 " WHERE type='table'\n"
2107 " AND name<>'selftest'\n"
2108 " AND coalesce(rootpage,0)>0\n"
2109 " )\n"
2110 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00002111 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002112 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00002113 "INSERT INTO selftest(tno,op,cmd,ans)"
2114 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2115 "DROP TABLE [_shell$self];"
2116 ,0,0,&zErrMsg);
2117 if( zErrMsg ){
2118 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2119 sqlite3_free(zErrMsg);
2120 }
2121 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00002122}
2123
drhf42d3182017-03-08 12:25:18 +00002124
shane626a6e42009-10-22 17:30:15 +00002125/*
drhdcd87a92014-08-18 13:45:42 +00002126** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00002127** the name of the table given. Escape any quote characters in the
2128** table name.
2129*/
drhdcd87a92014-08-18 13:45:42 +00002130static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00002131 int i, n;
drhf42d3182017-03-08 12:25:18 +00002132 int cQuote;
drh33048c02001-10-01 14:29:22 +00002133 char *z;
2134
2135 if( p->zDestTable ){
2136 free(p->zDestTable);
2137 p->zDestTable = 0;
2138 }
2139 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00002140 cQuote = quoteChar(zName);
2141 n = strlen30(zName);
2142 if( cQuote ) n += 2;
drh33048c02001-10-01 14:29:22 +00002143 z = p->zDestTable = malloc( n+1 );
2144 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002145 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00002146 exit(1);
2147 }
2148 n = 0;
drhf42d3182017-03-08 12:25:18 +00002149 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002150 for(i=0; zName[i]; i++){
2151 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00002152 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002153 }
drhf42d3182017-03-08 12:25:18 +00002154 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002155 z[n] = 0;
2156}
2157
drhdd3d4592004-08-30 01:54:05 +00002158
2159/*
drhb21a8e42012-01-28 21:08:51 +00002160** Execute a query statement that will generate SQL output. Print
2161** the result columns, comma-separated, on a line and then add a
2162** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00002163**
drhb21a8e42012-01-28 21:08:51 +00002164** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00002165** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00002166** "--" comment occurs at the end of the statement, the comment
2167** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00002168*/
drh157e29a2009-05-21 15:15:00 +00002169static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00002170 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00002171 const char *zSelect, /* SELECT statement to extract content */
2172 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00002173){
drhdd3d4592004-08-30 01:54:05 +00002174 sqlite3_stmt *pSelect;
2175 int rc;
drhb21a8e42012-01-28 21:08:51 +00002176 int nResult;
2177 int i;
2178 const char *z;
drhc7181902014-02-27 15:04:13 +00002179 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00002180 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00002181 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2182 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002183 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00002184 return rc;
2185 }
2186 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00002187 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00002188 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00002189 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00002190 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00002191 zFirstRow = 0;
2192 }
drhb21a8e42012-01-28 21:08:51 +00002193 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00002194 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00002195 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00002196 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00002197 }
2198 if( z==0 ) z = "";
2199 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2200 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00002201 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00002202 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002203 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00002204 }
drhdd3d4592004-08-30 01:54:05 +00002205 rc = sqlite3_step(pSelect);
2206 }
drh2f464a02011-10-13 00:41:49 +00002207 rc = sqlite3_finalize(pSelect);
2208 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00002209 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2210 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002211 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00002212 }
2213 return rc;
drhdd3d4592004-08-30 01:54:05 +00002214}
2215
shane626a6e42009-10-22 17:30:15 +00002216/*
2217** Allocate space and save off current error string.
2218*/
2219static char *save_err_msg(
2220 sqlite3 *db /* Database to query */
2221){
2222 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00002223 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00002224 if( zErrMsg ){
2225 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2226 }
2227 return zErrMsg;
2228}
2229
drh34784902016-02-27 17:12:36 +00002230#ifdef __linux__
2231/*
2232** Attempt to display I/O stats on Linux using /proc/PID/io
2233*/
2234static void displayLinuxIoStats(FILE *out){
2235 FILE *in;
2236 char z[200];
2237 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2238 in = fopen(z, "rb");
2239 if( in==0 ) return;
2240 while( fgets(z, sizeof(z), in)!=0 ){
2241 static const struct {
2242 const char *zPattern;
2243 const char *zDesc;
2244 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00002245 { "rchar: ", "Bytes received by read():" },
2246 { "wchar: ", "Bytes sent to write():" },
2247 { "syscr: ", "Read() system calls:" },
2248 { "syscw: ", "Write() system calls:" },
2249 { "read_bytes: ", "Bytes read from storage:" },
2250 { "write_bytes: ", "Bytes written to storage:" },
2251 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00002252 };
2253 int i;
2254 for(i=0; i<ArraySize(aTrans); i++){
2255 int n = (int)strlen(aTrans[i].zPattern);
2256 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00002257 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00002258 break;
2259 }
2260 }
2261 }
2262 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00002263}
drh34784902016-02-27 17:12:36 +00002264#endif
2265
drha2df53b2017-03-10 14:36:10 +00002266/*
2267** Display a single line of status using 64-bit values.
2268*/
2269static void displayStatLine(
2270 ShellState *p, /* The shell context */
2271 char *zLabel, /* Label for this one line */
2272 char *zFormat, /* Format for the result */
2273 int iStatusCtrl, /* Which status to display */
2274 int bReset /* True to reset the stats */
2275){
2276 sqlite3_int64 iCur = -1;
2277 sqlite3_int64 iHiwtr = -1;
2278 int i, nPercent;
2279 char zLine[200];
2280 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2281 for(i=0, nPercent=0; zFormat[i]; i++){
2282 if( zFormat[i]=='%' ) nPercent++;
2283 }
2284 if( nPercent>1 ){
2285 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2286 }else{
2287 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2288 }
2289 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2290}
drh34784902016-02-27 17:12:36 +00002291
shane626a6e42009-10-22 17:30:15 +00002292/*
shaneh642d8b82010-07-28 16:05:34 +00002293** Display memory stats.
2294*/
2295static int display_stats(
2296 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00002297 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00002298 int bReset /* True to reset the stats */
2299){
2300 int iCur;
2301 int iHiwtr;
2302
2303 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00002304 displayStatLine(pArg, "Memory Used:",
2305 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2306 displayStatLine(pArg, "Number of Outstanding Allocations:",
2307 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00002308 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00002309 displayStatLine(pArg, "Number of Pcache Pages Used:",
2310 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002311 }
drha2df53b2017-03-10 14:36:10 +00002312 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2313 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh44dec872014-08-30 15:49:25 +00002314 if( pArg->shellFlgs & SHFLG_Scratch ){
drha2df53b2017-03-10 14:36:10 +00002315 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2316 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002317 }
drha2df53b2017-03-10 14:36:10 +00002318 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2319 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2320 displayStatLine(pArg, "Largest Allocation:",
2321 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2322 displayStatLine(pArg, "Largest Pcache Allocation:",
2323 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2324 displayStatLine(pArg, "Largest Scratch Allocation:",
2325 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002326#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00002327 displayStatLine(pArg, "Deepest Parser Stack:",
2328 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002329#endif
2330 }
2331
2332 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00002333 if( pArg->shellFlgs & SHFLG_Lookaside ){
2334 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00002335 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2336 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002337 raw_printf(pArg->out,
2338 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00002339 iCur, iHiwtr);
2340 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2341 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002342 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2343 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002344 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2345 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002346 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2347 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002348 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2349 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002350 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2351 iHiwtr);
drh44dec872014-08-30 15:49:25 +00002352 }
shaneh642d8b82010-07-28 16:05:34 +00002353 iHiwtr = iCur = -1;
2354 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002355 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2356 iCur);
drh4ace5362014-11-10 14:42:28 +00002357 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00002358 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00002359 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00002360 iHiwtr = iCur = -1;
2361 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002362 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002363 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00002364 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002365 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00002366 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00002367 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002368 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002369 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002370 iHiwtr = iCur = -1;
2371 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002372 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002373 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002374 }
2375
2376 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00002377 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2378 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002379 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002380 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002381 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00002382 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002383 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00002384 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002385 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002386 }
2387
drh34784902016-02-27 17:12:36 +00002388#ifdef __linux__
2389 displayLinuxIoStats(pArg->out);
2390#endif
2391
dan5a790282015-08-07 20:06:14 +00002392 /* Do not remove this machine readable comment: extra-stats-output-here */
2393
shaneh642d8b82010-07-28 16:05:34 +00002394 return 0;
2395}
2396
2397/*
dan8d1edb92014-11-05 09:07:28 +00002398** Display scan stats.
2399*/
2400static void display_scanstats(
2401 sqlite3 *db, /* Database to query */
2402 ShellState *pArg /* Pointer to ShellState */
2403){
drhf5ed7ad2015-06-15 14:43:25 +00002404#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2405 UNUSED_PARAMETER(db);
2406 UNUSED_PARAMETER(pArg);
2407#else
drh15f23c22014-11-06 12:46:16 +00002408 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00002409 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00002410 mx = 0;
2411 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00002412 double rEstLoop = 1.0;
2413 for(i=n=0; 1; i++){
2414 sqlite3_stmt *p = pArg->pStmt;
2415 sqlite3_int64 nLoop, nVisit;
2416 double rEst;
2417 int iSid;
2418 const char *zExplain;
2419 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2420 break;
2421 }
2422 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00002423 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00002424 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00002425 if( n==0 ){
2426 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00002427 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00002428 }
drh42f30bc2014-11-06 12:08:21 +00002429 n++;
2430 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2431 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2432 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00002433 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00002434 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00002435 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00002436 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00002437 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00002438 );
dan8d1edb92014-11-05 09:07:28 +00002439 }
dan8d1edb92014-11-05 09:07:28 +00002440 }
mistachkinaae280e2015-12-31 19:06:24 +00002441 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00002442#endif
dan8d1edb92014-11-05 09:07:28 +00002443}
2444
2445/*
dana98bf362013-11-13 18:35:01 +00002446** Parameter azArray points to a zero-terminated array of strings. zStr
2447** points to a single nul-terminated string. Return non-zero if zStr
2448** is equal, according to strcmp(), to any of the strings in the array.
2449** Otherwise, return zero.
2450*/
2451static int str_in_array(const char *zStr, const char **azArray){
2452 int i;
2453 for(i=0; azArray[i]; i++){
2454 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2455 }
2456 return 0;
2457}
2458
2459/*
2460** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00002461** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00002462** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00002463**
2464** The indenting rules are:
2465**
2466** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2467** all opcodes that occur between the p2 jump destination and the opcode
2468** itself by 2 spaces.
2469**
drh01752bc2013-11-14 23:59:33 +00002470** * For each "Goto", if the jump destination is earlier in the program
2471** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00002472** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00002473** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00002474** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00002475** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00002476*/
drhdcd87a92014-08-18 13:45:42 +00002477static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00002478 const char *zSql; /* The text of the SQL statement */
2479 const char *z; /* Used to check if this is an EXPLAIN */
2480 int *abYield = 0; /* True if op is an OP_Yield */
2481 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00002482 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00002483
drh8ad0de32014-03-20 18:45:27 +00002484 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2485 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00002486 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2487 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00002488 const char *azGoto[] = { "Goto", 0 };
2489
2490 /* Try to figure out if this is really an EXPLAIN statement. If this
2491 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00002492 if( sqlite3_column_count(pSql)!=8 ){
2493 p->cMode = p->mode;
2494 return;
2495 }
dana98bf362013-11-13 18:35:01 +00002496 zSql = sqlite3_sql(pSql);
2497 if( zSql==0 ) return;
2498 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00002499 if( sqlite3_strnicmp(z, "explain", 7) ){
2500 p->cMode = p->mode;
2501 return;
2502 }
dana98bf362013-11-13 18:35:01 +00002503
2504 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2505 int i;
danc4650bb2013-11-18 08:41:06 +00002506 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00002507 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00002508
2509 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2510 ** p2 is an instruction address, set variable p2op to the index of that
2511 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2512 ** the current instruction is part of a sub-program generated by an
2513 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00002514 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00002515 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00002516
2517 /* Grow the p->aiIndent array as required */
2518 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00002519 if( iOp==0 ){
2520 /* Do further verfication that this is explain output. Abort if
2521 ** it is not */
2522 static const char *explainCols[] = {
2523 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2524 int jj;
2525 for(jj=0; jj<ArraySize(explainCols); jj++){
2526 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2527 p->cMode = p->mode;
2528 sqlite3_reset(pSql);
2529 return;
2530 }
2531 }
2532 }
dana98bf362013-11-13 18:35:01 +00002533 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00002534 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2535 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00002536 }
2537 abYield[iOp] = str_in_array(zOp, azYield);
2538 p->aiIndent[iOp] = 0;
2539 p->nIndent = iOp+1;
2540
2541 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00002542 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002543 }
drhfe705102014-03-06 13:38:37 +00002544 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2545 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2546 ){
drheacd29d2016-04-15 15:03:27 +00002547 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002548 }
2549 }
2550
danc4650bb2013-11-18 08:41:06 +00002551 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002552 sqlite3_free(abYield);
2553 sqlite3_reset(pSql);
2554}
2555
2556/*
2557** Free the array allocated by explain_data_prepare().
2558*/
drhdcd87a92014-08-18 13:45:42 +00002559static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00002560 sqlite3_free(p->aiIndent);
2561 p->aiIndent = 0;
2562 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00002563 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002564}
2565
2566/*
drheacd29d2016-04-15 15:03:27 +00002567** Disable and restore .wheretrace and .selecttrace settings.
2568*/
2569#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2570extern int sqlite3SelectTrace;
2571static int savedSelectTrace;
2572#endif
2573#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2574extern int sqlite3WhereTrace;
2575static int savedWhereTrace;
2576#endif
2577static void disable_debug_trace_modes(void){
2578#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2579 savedSelectTrace = sqlite3SelectTrace;
2580 sqlite3SelectTrace = 0;
2581#endif
2582#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2583 savedWhereTrace = sqlite3WhereTrace;
2584 sqlite3WhereTrace = 0;
2585#endif
2586}
2587static void restore_debug_trace_modes(void){
2588#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2589 sqlite3SelectTrace = savedSelectTrace;
2590#endif
2591#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2592 sqlite3WhereTrace = savedWhereTrace;
2593#endif
2594}
2595
2596/*
2597** Run a prepared statement
2598*/
2599static void exec_prepared_stmt(
2600 ShellState *pArg, /* Pointer to ShellState */
2601 sqlite3_stmt *pStmt, /* Statment to run */
2602 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2603){
2604 int rc;
2605
2606 /* perform the first step. this will tell us if we
2607 ** have a result set or not and how wide it is.
2608 */
2609 rc = sqlite3_step(pStmt);
2610 /* if we have a result set... */
2611 if( SQLITE_ROW == rc ){
2612 /* if we have a callback... */
2613 if( xCallback ){
2614 /* allocate space for col name ptr, value ptr, and type */
2615 int nCol = sqlite3_column_count(pStmt);
2616 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2617 if( !pData ){
2618 rc = SQLITE_NOMEM;
2619 }else{
2620 char **azCols = (char **)pData; /* Names of result columns */
2621 char **azVals = &azCols[nCol]; /* Results */
2622 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2623 int i, x;
2624 assert(sizeof(int) <= sizeof(char *));
2625 /* save off ptrs to column names */
2626 for(i=0; i<nCol; i++){
2627 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2628 }
2629 do{
2630 /* extract the data and data types */
2631 for(i=0; i<nCol; i++){
2632 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2633 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2634 azVals[i] = "";
2635 }else{
2636 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2637 }
2638 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2639 rc = SQLITE_NOMEM;
2640 break; /* from for */
2641 }
2642 } /* end for */
2643
2644 /* if data and types extracted successfully... */
2645 if( SQLITE_ROW == rc ){
2646 /* call the supplied callback with the result row data */
2647 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2648 rc = SQLITE_ABORT;
2649 }else{
2650 rc = sqlite3_step(pStmt);
2651 }
2652 }
2653 } while( SQLITE_ROW == rc );
2654 sqlite3_free(pData);
2655 }
2656 }else{
2657 do{
2658 rc = sqlite3_step(pStmt);
2659 } while( rc == SQLITE_ROW );
2660 }
2661 }
2662}
2663
2664/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002665** Execute a statement or set of statements. Print
2666** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00002667** set via the supplied callback.
2668**
mistachkin1fe36bb2016-04-04 02:16:44 +00002669** This is very similar to SQLite's built-in sqlite3_exec()
2670** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00002671** and callback data argument.
2672*/
2673static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00002674 sqlite3 *db, /* An open database */
2675 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00002676 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00002677 /* (not the same as sqlite3_exec) */
2678 ShellState *pArg, /* Pointer to ShellState */
2679 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00002680){
dan4564ced2010-01-05 04:59:56 +00002681 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2682 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00002683 int rc2;
dan4564ced2010-01-05 04:59:56 +00002684 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00002685
2686 if( pzErrMsg ){
2687 *pzErrMsg = NULL;
2688 }
2689
shaneb9fc17d2009-10-22 21:23:35 +00002690 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00002691 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00002692 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2693 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00002694 if( pzErrMsg ){
2695 *pzErrMsg = save_err_msg(db);
2696 }
2697 }else{
shaneb9fc17d2009-10-22 21:23:35 +00002698 if( !pStmt ){
2699 /* this happens for a comment or white-space */
2700 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002701 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00002702 continue;
2703 }
drheacd29d2016-04-15 15:03:27 +00002704 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00002705 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00002706 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00002707
shaneh642d8b82010-07-28 16:05:34 +00002708 /* save off the prepared statment handle and reset row count */
2709 if( pArg ){
2710 pArg->pStmt = pStmt;
2711 pArg->cnt = 0;
2712 }
2713
shanehb7977c52010-01-18 18:17:10 +00002714 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00002715 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00002716 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00002717 }
shanehb7977c52010-01-18 18:17:10 +00002718
drhefbf3b12014-02-28 20:47:24 +00002719 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00002720 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00002721 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00002722 char *zEQP;
2723 disable_debug_trace_modes();
2724 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00002725 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2726 if( rc==SQLITE_OK ){
2727 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00002728 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2729 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2730 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00002731 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00002732 }
2733 }
2734 sqlite3_finalize(pExplain);
2735 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00002736 if( pArg->autoEQP>=2 ){
2737 /* Also do an EXPLAIN for ".eqp full" mode */
2738 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2739 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2740 if( rc==SQLITE_OK ){
2741 pArg->cMode = MODE_Explain;
2742 explain_data_prepare(pArg, pExplain);
2743 exec_prepared_stmt(pArg, pExplain, xCallback);
2744 explain_data_delete(pArg);
2745 }
2746 sqlite3_finalize(pExplain);
2747 sqlite3_free(zEQP);
2748 }
2749 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00002750 }
2751
drh700c2522016-02-09 18:39:25 +00002752 if( pArg ){
2753 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00002754 if( pArg->autoExplain
2755 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00002756 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00002757 ){
2758 pArg->cMode = MODE_Explain;
2759 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002760
drh700c2522016-02-09 18:39:25 +00002761 /* If the shell is currently in ".explain" mode, gather the extra
2762 ** data required to add indents to the output.*/
2763 if( pArg->cMode==MODE_Explain ){
2764 explain_data_prepare(pArg, pStmt);
2765 }
dana98bf362013-11-13 18:35:01 +00002766 }
2767
drheacd29d2016-04-15 15:03:27 +00002768 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00002769 explain_data_delete(pArg);
2770
shaneh642d8b82010-07-28 16:05:34 +00002771 /* print usage stats if stats on */
2772 if( pArg && pArg->statsOn ){
2773 display_stats(db, pArg, 0);
2774 }
2775
dan8d1edb92014-11-05 09:07:28 +00002776 /* print loop-counters if required */
2777 if( pArg && pArg->scanstatsOn ){
2778 display_scanstats(db, pArg);
2779 }
2780
mistachkin1fe36bb2016-04-04 02:16:44 +00002781 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00002782 ** copy of the error message. Otherwise, set zSql to point to the
2783 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00002784 rc2 = sqlite3_finalize(pStmt);
2785 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00002786 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00002787 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002788 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00002789 }else if( pzErrMsg ){
2790 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00002791 }
shaneh642d8b82010-07-28 16:05:34 +00002792
2793 /* clear saved stmt handle */
2794 if( pArg ){
2795 pArg->pStmt = NULL;
2796 }
shane626a6e42009-10-22 17:30:15 +00002797 }
shaneb9fc17d2009-10-22 21:23:35 +00002798 } /* end while */
shane626a6e42009-10-22 17:30:15 +00002799
2800 return rc;
2801}
2802
drhe611f142017-03-08 11:44:00 +00002803/*
2804** Release memory previously allocated by tableColumnList().
2805*/
2806static void freeColumnList(char **azCol){
2807 int i;
2808 for(i=1; azCol[i]; i++){
2809 sqlite3_free(azCol[i]);
2810 }
2811 /* azCol[0] is a static string */
2812 sqlite3_free(azCol);
2813}
2814
2815/*
2816** Return a list of pointers to strings which are the names of all
2817** columns in table zTab. The memory to hold the names is dynamically
2818** allocated and must be released by the caller using a subsequent call
2819** to freeColumnList().
2820**
2821** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2822** value that needs to be preserved, then azCol[0] is filled in with the
2823** name of the rowid column.
2824**
2825** The first regular column in the table is azCol[1]. The list is terminated
2826** by an entry with azCol[i]==0.
2827*/
2828static char **tableColumnList(ShellState *p, const char *zTab){
2829 char **azCol = 0;
2830 sqlite3_stmt *pStmt;
2831 char *zSql;
2832 int nCol = 0;
2833 int nAlloc = 0;
2834 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2835 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00002836 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00002837 int rc;
2838
2839 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2840 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2841 sqlite3_free(zSql);
2842 if( rc ) return 0;
2843 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2844 if( nCol>=nAlloc-2 ){
2845 nAlloc = nAlloc*2 + nCol + 10;
2846 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2847 if( azCol==0 ){
2848 raw_printf(stderr, "Error: out of memory\n");
2849 exit(1);
2850 }
2851 }
2852 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2853 if( sqlite3_column_int(pStmt, 5) ){
2854 nPK++;
2855 if( nPK==1
2856 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2857 "INTEGER")==0
2858 ){
2859 isIPK = 1;
2860 }else{
2861 isIPK = 0;
2862 }
2863 }
2864 }
2865 sqlite3_finalize(pStmt);
2866 azCol[0] = 0;
2867 azCol[nCol+1] = 0;
2868
2869 /* The decision of whether or not a rowid really needs to be preserved
2870 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2871 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2872 ** rowids on tables where the rowid is inaccessible because there are other
2873 ** columns in the table named "rowid", "_rowid_", and "oid".
2874 */
2875 if( preserveRowid && isIPK ){
2876 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2877 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2878 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2879 ** ROWID aliases. To distinguish these cases, check to see if
2880 ** there is a "pk" entry in "PRAGMA index_list". There will be
2881 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2882 */
2883 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2884 " WHERE origin='pk'", zTab);
2885 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2886 sqlite3_free(zSql);
2887 if( rc ){
2888 freeColumnList(azCol);
2889 return 0;
2890 }
2891 rc = sqlite3_step(pStmt);
2892 sqlite3_finalize(pStmt);
2893 preserveRowid = rc==SQLITE_ROW;
2894 }
2895 if( preserveRowid ){
2896 /* Only preserve the rowid if we can find a name to use for the
2897 ** rowid */
2898 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2899 int i, j;
2900 for(j=0; j<3; j++){
2901 for(i=1; i<=nCol; i++){
2902 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2903 }
2904 if( i>nCol ){
2905 /* At this point, we know that azRowid[j] is not the name of any
2906 ** ordinary column in the table. Verify that azRowid[j] is a valid
2907 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2908 ** tables will fail this last check */
2909 int rc;
2910 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2911 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2912 break;
2913 }
2914 }
2915 }
2916 return azCol;
2917}
2918
drh33048c02001-10-01 14:29:22 +00002919/*
drhf8563c02017-03-09 18:13:52 +00002920** Toggle the reverse_unordered_selects setting.
2921*/
2922static void toggleSelectOrder(sqlite3 *db){
2923 sqlite3_stmt *pStmt = 0;
2924 int iSetting = 0;
2925 char zStmt[100];
2926 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2927 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2928 iSetting = sqlite3_column_int(pStmt, 0);
2929 }
2930 sqlite3_finalize(pStmt);
2931 sqlite3_snprintf(sizeof(zStmt), zStmt,
2932 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2933 sqlite3_exec(db, zStmt, 0, 0, 0);
2934}
2935
2936/*
drh4c653a02000-06-07 01:27:47 +00002937** This is a different callback routine used for dumping the database.
2938** Each row received by this callback consists of a table name,
2939** the table type ("index" or "table") and SQL to create the table.
2940** This routine should print text sufficient to recreate the table.
2941*/
2942static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
danielk19772a02e332004-06-05 08:04:36 +00002943 int rc;
2944 const char *zTable;
2945 const char *zType;
2946 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00002947 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00002948
drh902b9ee2008-12-05 17:17:07 +00002949 UNUSED_PARAMETER(azCol);
drh4c653a02000-06-07 01:27:47 +00002950 if( nArg!=3 ) return 1;
danielk19772a02e332004-06-05 08:04:36 +00002951 zTable = azArg[0];
2952 zType = azArg[1];
2953 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00002954
drh00b950d2005-09-11 02:03:03 +00002955 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00002956 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00002957 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002958 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00002959 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
2960 return 0;
drh45e29d82006-11-20 16:21:10 +00002961 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
2962 char *zIns;
2963 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00002964 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00002965 p->writableSchema = 1;
2966 }
2967 zIns = sqlite3_mprintf(
2968 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
2969 "VALUES('table','%q','%q',0,'%q');",
2970 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00002971 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00002972 sqlite3_free(zIns);
2973 return 0;
drh00b950d2005-09-11 02:03:03 +00002974 }else{
drh79f20e92016-12-13 23:22:39 +00002975 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00002976 }
danielk19772a02e332004-06-05 08:04:36 +00002977
2978 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00002979 ShellText sSelect;
2980 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00002981 char **azCol;
2982 int i;
2983 char *savedDestTable;
2984 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00002985
drhe611f142017-03-08 11:44:00 +00002986 azCol = tableColumnList(p, zTable);
2987 if( azCol==0 ){
2988 p->nErr++;
2989 return 0;
danielk19772a02e332004-06-05 08:04:36 +00002990 }
2991
drhbf92ec02012-03-22 12:50:34 +00002992 /* Always quote the table name, even if it appears to be pure ascii,
2993 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00002994 initText(&sTable);
2995 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00002996 /* If preserving the rowid, add a column list after the table name.
2997 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
2998 ** instead of the usual "INSERT INTO tab VALUES(...)".
2999 */
3000 if( azCol[0] ){
3001 appendText(&sTable, "(", 0);
3002 appendText(&sTable, azCol[0], 0);
3003 for(i=1; azCol[i]; i++){
3004 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003005 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003006 }
drhe611f142017-03-08 11:44:00 +00003007 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003008 }
danielk19772a02e332004-06-05 08:04:36 +00003009
drhe611f142017-03-08 11:44:00 +00003010 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003011 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003012 appendText(&sSelect, "SELECT ", 0);
3013 if( azCol[0] ){
3014 appendText(&sSelect, azCol[0], 0);
3015 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003016 }
drhe611f142017-03-08 11:44:00 +00003017 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003018 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003019 if( azCol[i+1] ){
3020 appendText(&sSelect, ",", 0);
3021 }
3022 }
3023 freeColumnList(azCol);
3024 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003025 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003026
3027 savedDestTable = p->zDestTable;
3028 savedMode = p->mode;
3029 p->zDestTable = sTable.z;
3030 p->mode = p->cMode = MODE_Insert;
3031 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003032 if( (rc&0xff)==SQLITE_CORRUPT ){
3033 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3034 toggleSelectOrder(p->db);
3035 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3036 toggleSelectOrder(p->db);
3037 }
drhe611f142017-03-08 11:44:00 +00003038 p->zDestTable = savedDestTable;
3039 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003040 freeText(&sTable);
3041 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003042 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003043 }
drh4c653a02000-06-07 01:27:47 +00003044 return 0;
3045}
3046
3047/*
drh45e29d82006-11-20 16:21:10 +00003048** Run zQuery. Use dump_callback() as the callback routine so that
3049** the contents of the query are output as SQL statements.
3050**
drhdd3d4592004-08-30 01:54:05 +00003051** If we get a SQLITE_CORRUPT error, rerun the query after appending
3052** "ORDER BY rowid DESC" to the end.
3053*/
3054static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003055 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003056 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003057){
3058 int rc;
drh2f464a02011-10-13 00:41:49 +00003059 char *zErr = 0;
3060 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003061 if( rc==SQLITE_CORRUPT ){
3062 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00003063 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00003064 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00003065 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00003066 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003067 sqlite3_free(zErr);
3068 zErr = 0;
3069 }
drhdd3d4592004-08-30 01:54:05 +00003070 zQ2 = malloc( len+100 );
3071 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00003072 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00003073 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3074 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003075 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003076 }else{
3077 rc = SQLITE_CORRUPT;
3078 }
3079 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00003080 free(zQ2);
3081 }
3082 return rc;
3083}
3084
3085/*
drh75897232000-05-29 14:26:00 +00003086** Text of a help message
3087*/
persicom1d0b8722002-04-18 02:53:04 +00003088static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00003089#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00003090 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00003091#endif
drh9ff849f2009-02-04 20:55:57 +00003092 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00003093 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00003094 ".binary on|off Turn binary output on or off. Default OFF\n"
drhdf12f1c2015-12-07 21:46:19 +00003095 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00003096 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00003097 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00003098 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00003099 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00003100 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00003101 " If TABLE specified, only dump tables matching\n"
3102 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00003103 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00003104 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00003105 ".exit Exit this program\n"
drh700c2522016-02-09 18:39:25 +00003106 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
drh4926fec2016-04-13 15:33:42 +00003107 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003108 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003109 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003110 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003111#ifndef SQLITE_OMIT_TEST_CONTROL
3112 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3113#endif
drh0e55db12015-02-06 14:51:13 +00003114 ".indexes ?TABLE? Show names of all indexes\n"
3115 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003116 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003117#ifdef SQLITE_ENABLE_IOTRACE
3118 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3119#endif
drh1a513372015-05-02 17:40:23 +00003120 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003121 ".lint OPTIONS Report potential schema issues. Options:\n"
3122 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003123#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003124 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003125#endif
drh127f9d72010-02-23 01:47:00 +00003126 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003127 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003128 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003129 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003130 " column Left-aligned columns. (See .width)\n"
3131 " html HTML <table> code\n"
3132 " insert SQL insert statements for TABLE\n"
3133 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003134 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003135 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003136 " tabs Tab-separated values\n"
3137 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003138 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003139 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkin8145fc62016-09-16 20:39:21 +00003140 ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
drhcd0509e2016-09-16 00:26:08 +00003141 " The --new starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003142 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003143 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003144 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003145 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003146 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003147 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003148 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003149 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003150 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3151 " Add --indent for pretty-printing\n"
mistachkine0d68852014-12-11 03:12:33 +00003152 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3153 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003154#if defined(SQLITE_ENABLE_SESSION)
3155 ".session CMD ... Create or control sessions\n"
3156#endif
drh1554bc82017-03-08 16:10:34 +00003157 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003158 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003159 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003160 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003161 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003162 ".tables ?TABLE? List names of tables\n"
3163 " If TABLE specified, only list tables matching\n"
3164 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003165 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003166 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003167 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003168 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003169 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003170 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003171 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003172 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003173 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003174;
3175
drhe6229612014-08-18 15:08:26 +00003176#if defined(SQLITE_ENABLE_SESSION)
3177/*
3178** Print help information for the ".sessions" command
3179*/
3180void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003181 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003182 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3183 "If ?NAME? is omitted, the first defined session is used.\n"
3184 "Subcommands:\n"
3185 " attach TABLE Attach TABLE\n"
3186 " changeset FILE Write a changeset into FILE\n"
3187 " close Close one session\n"
3188 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003189 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003190 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3191 " isempty Query whether the session is empty\n"
3192 " list List currently open session names\n"
3193 " open DB NAME Open a new session on DB\n"
3194 " patchset FILE Write a patchset into FILE\n"
3195 );
3196}
3197#endif
3198
3199
drhdaffd0e2001-04-11 14:28:42 +00003200/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003201static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003202
drh2db82112016-09-15 21:35:24 +00003203/*
dan11da0022016-12-17 08:18:05 +00003204** Read the content of file zName into memory obtained from sqlite3_malloc64()
3205** and return a pointer to the buffer. The caller is responsible for freeing
3206** the memory.
drh2db82112016-09-15 21:35:24 +00003207**
dan11da0022016-12-17 08:18:05 +00003208** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3209** read.
3210**
3211** For convenience, a nul-terminator byte is always appended to the data read
3212** from the file before the buffer is returned. This byte is not included in
3213** the final value of (*pnByte), if applicable.
3214**
3215** NULL is returned if any error is encountered. The final value of *pnByte
3216** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003217*/
dan11da0022016-12-17 08:18:05 +00003218static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003219 FILE *in = fopen(zName, "rb");
3220 long nIn;
drhd1459152016-09-16 19:11:03 +00003221 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003222 char *pBuf;
3223 if( in==0 ) return 0;
3224 fseek(in, 0, SEEK_END);
3225 nIn = ftell(in);
3226 rewind(in);
drhd1459152016-09-16 19:11:03 +00003227 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003228 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003229 nRead = fread(pBuf, nIn, 1, in);
3230 fclose(in);
3231 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003232 sqlite3_free(pBuf);
3233 return 0;
3234 }
drhd1459152016-09-16 19:11:03 +00003235 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003236 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003237 return pBuf;
3238}
3239
drhba5b0932014-07-24 12:39:59 +00003240/*
3241** Implementation of the "readfile(X)" SQL function. The entire content
3242** of the file named X is read and returned as a BLOB. NULL is returned
3243** if the file does not exist or is unreadable.
3244*/
3245static void readfileFunc(
3246 sqlite3_context *context,
3247 int argc,
3248 sqlite3_value **argv
3249){
3250 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003251 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003252 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003253
drhf5ed7ad2015-06-15 14:43:25 +00003254 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003255 zName = (const char*)sqlite3_value_text(argv[0]);
3256 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003257 pBuf = readFile(zName, &nBuf);
3258 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003259}
3260
3261/*
3262** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3263** is written into file X. The number of bytes written is returned. Or
3264** NULL is returned if something goes wrong, such as being unable to open
3265** file X for writing.
3266*/
3267static void writefileFunc(
3268 sqlite3_context *context,
3269 int argc,
3270 sqlite3_value **argv
3271){
3272 FILE *out;
3273 const char *z;
drhba5b0932014-07-24 12:39:59 +00003274 sqlite3_int64 rc;
3275 const char *zFile;
3276
drhf5ed7ad2015-06-15 14:43:25 +00003277 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003278 zFile = (const char*)sqlite3_value_text(argv[0]);
3279 if( zFile==0 ) return;
3280 out = fopen(zFile, "wb");
3281 if( out==0 ) return;
3282 z = (const char*)sqlite3_value_blob(argv[1]);
3283 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003284 rc = 0;
3285 }else{
drh490fe862014-08-11 14:21:32 +00003286 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003287 }
3288 fclose(out);
3289 sqlite3_result_int64(context, rc);
3290}
drhdaffd0e2001-04-11 14:28:42 +00003291
drhe6229612014-08-18 15:08:26 +00003292#if defined(SQLITE_ENABLE_SESSION)
3293/*
3294** Close a single OpenSession object and release all of its associated
3295** resources.
3296*/
3297static void session_close(OpenSession *pSession){
3298 int i;
3299 sqlite3session_delete(pSession->p);
3300 sqlite3_free(pSession->zName);
3301 for(i=0; i<pSession->nFilter; i++){
3302 sqlite3_free(pSession->azFilter[i]);
3303 }
3304 sqlite3_free(pSession->azFilter);
3305 memset(pSession, 0, sizeof(OpenSession));
3306}
3307#endif
3308
3309/*
drh51b55a32016-04-04 12:38:05 +00003310** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003311*/
drhe6229612014-08-18 15:08:26 +00003312#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003313static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003314 int i;
3315 for(i=0; i<p->nSession; i++){
3316 session_close(&p->aSession[i]);
3317 }
3318 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003319}
drh51b55a32016-04-04 12:38:05 +00003320#else
3321# define session_close_all(X)
3322#endif
drhe6229612014-08-18 15:08:26 +00003323
drh75897232000-05-29 14:26:00 +00003324/*
drh03168ca2014-08-18 20:01:31 +00003325** Implementation of the xFilter function for an open session. Omit
3326** any tables named by ".session filter" but let all other table through.
3327*/
3328#if defined(SQLITE_ENABLE_SESSION)
3329static int session_filter(void *pCtx, const char *zTab){
3330 OpenSession *pSession = (OpenSession*)pCtx;
3331 int i;
3332 for(i=0; i<pSession->nFilter; i++){
3333 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3334 }
3335 return 1;
3336}
3337#endif
3338
3339/*
drh44c2eb12003-04-30 11:38:26 +00003340** Make sure the database is open. If it is not, then open it. If
3341** the database fails to open, print an error message and exit.
3342*/
drhdcd87a92014-08-18 13:45:42 +00003343static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003344 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003345 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003346 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003347 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003348 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003349 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003350 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003351 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003352 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003353 }
drhc2e87a32006-06-27 15:16:14 +00003354#ifndef SQLITE_OMIT_LOAD_EXTENSION
3355 sqlite3_enable_load_extension(p->db, 1);
3356#endif
mistachkin8e189222015-04-19 21:43:16 +00003357 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003358 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003359 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003360 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003361 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3362 sha3Func, 0, 0);
3363 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3364 sha3Func, 0, 0);
3365 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3366 sha3QueryFunc, 0, 0);
3367 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3368 sha3QueryFunc, 0, 0);
drh44c2eb12003-04-30 11:38:26 +00003369 }
3370}
3371
3372/*
drhfeac5f82004-08-01 00:10:45 +00003373** Do C-language style dequoting.
3374**
mistachkinf21979d2015-01-18 05:35:01 +00003375** \a -> alarm
3376** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003377** \t -> tab
3378** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003379** \v -> vertical tab
3380** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003381** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003382** \s -> space
drh4c56b992013-06-27 13:26:55 +00003383** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003384** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003385** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003386** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003387*/
3388static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003389 int i, j;
3390 char c;
drhc2ce0be2014-05-29 12:36:14 +00003391 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003392 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003393 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003394 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003395 if( c=='a' ){
3396 c = '\a';
3397 }else if( c=='b' ){
3398 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003399 }else if( c=='t' ){
3400 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003401 }else if( c=='n' ){
3402 c = '\n';
3403 }else if( c=='v' ){
3404 c = '\v';
3405 }else if( c=='f' ){
3406 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003407 }else if( c=='r' ){
3408 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003409 }else if( c=='"' ){
3410 c = '"';
3411 }else if( c=='\'' ){
3412 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003413 }else if( c=='\\' ){
3414 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003415 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003416 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003417 if( z[i+1]>='0' && z[i+1]<='7' ){
3418 i++;
3419 c = (c<<3) + z[i] - '0';
3420 if( z[i+1]>='0' && z[i+1]<='7' ){
3421 i++;
3422 c = (c<<3) + z[i] - '0';
3423 }
3424 }
3425 }
3426 }
3427 z[j] = c;
3428 }
drhc2ce0be2014-05-29 12:36:14 +00003429 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003430}
3431
3432/*
drh348d19c2013-06-03 12:47:43 +00003433** Return the value of a hexadecimal digit. Return -1 if the input
3434** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003435*/
drh348d19c2013-06-03 12:47:43 +00003436static int hexDigitValue(char c){
3437 if( c>='0' && c<='9' ) return c - '0';
3438 if( c>='a' && c<='f' ) return c - 'a' + 10;
3439 if( c>='A' && c<='F' ) return c - 'A' + 10;
3440 return -1;
drhc28490c2006-10-26 14:25:58 +00003441}
3442
3443/*
drh7d9f3942013-04-03 01:26:54 +00003444** Interpret zArg as an integer value, possibly with suffixes.
3445*/
3446static sqlite3_int64 integerValue(const char *zArg){
3447 sqlite3_int64 v = 0;
3448 static const struct { char *zSuffix; int iMult; } aMult[] = {
3449 { "KiB", 1024 },
3450 { "MiB", 1024*1024 },
3451 { "GiB", 1024*1024*1024 },
3452 { "KB", 1000 },
3453 { "MB", 1000000 },
3454 { "GB", 1000000000 },
3455 { "K", 1000 },
3456 { "M", 1000000 },
3457 { "G", 1000000000 },
3458 };
3459 int i;
3460 int isNeg = 0;
3461 if( zArg[0]=='-' ){
3462 isNeg = 1;
3463 zArg++;
3464 }else if( zArg[0]=='+' ){
3465 zArg++;
3466 }
drh348d19c2013-06-03 12:47:43 +00003467 if( zArg[0]=='0' && zArg[1]=='x' ){
3468 int x;
3469 zArg += 2;
3470 while( (x = hexDigitValue(zArg[0]))>=0 ){
3471 v = (v<<4) + x;
3472 zArg++;
3473 }
3474 }else{
3475 while( IsDigit(zArg[0]) ){
3476 v = v*10 + zArg[0] - '0';
3477 zArg++;
3478 }
drh7d9f3942013-04-03 01:26:54 +00003479 }
drhc2bed0a2013-05-24 11:57:50 +00003480 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003481 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3482 v *= aMult[i].iMult;
3483 break;
3484 }
3485 }
3486 return isNeg? -v : v;
3487}
3488
3489/*
drh348d19c2013-06-03 12:47:43 +00003490** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3491** for TRUE and FALSE. Return the integer value if appropriate.
3492*/
drhe6e1d122017-03-09 13:50:49 +00003493static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003494 int i;
3495 if( zArg[0]=='0' && zArg[1]=='x' ){
3496 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3497 }else{
3498 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3499 }
3500 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3501 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3502 return 1;
3503 }
3504 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3505 return 0;
3506 }
mistachkinaae280e2015-12-31 19:06:24 +00003507 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003508 zArg);
3509 return 0;
3510}
3511
3512/*
drhe6e1d122017-03-09 13:50:49 +00003513** Set or clear a shell flag according to a boolean value.
3514*/
3515static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3516 if( booleanValue(zArg) ){
3517 ShellSetFlag(p, mFlag);
3518 }else{
3519 ShellClearFlag(p, mFlag);
3520 }
3521}
3522
3523/*
drh42f64e52012-04-04 16:56:23 +00003524** Close an output file, assuming it is not stderr or stdout
3525*/
3526static void output_file_close(FILE *f){
3527 if( f && f!=stdout && f!=stderr ) fclose(f);
3528}
3529
3530/*
3531** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003532** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003533** filename is "off".
3534*/
3535static FILE *output_file_open(const char *zFile){
3536 FILE *f;
3537 if( strcmp(zFile,"stdout")==0 ){
3538 f = stdout;
3539 }else if( strcmp(zFile, "stderr")==0 ){
3540 f = stderr;
3541 }else if( strcmp(zFile, "off")==0 ){
3542 f = 0;
3543 }else{
3544 f = fopen(zFile, "wb");
3545 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003546 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003547 }
3548 }
3549 return f;
3550}
3551
drhd12602a2016-12-07 15:49:02 +00003552#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003553#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003554/*
3555** A routine for handling output from sqlite3_trace().
3556*/
drh4b363a52016-07-23 20:27:41 +00003557static int sql_trace_callback(
3558 unsigned mType,
3559 void *pArg,
3560 void *pP,
3561 void *pX
3562){
drh42f64e52012-04-04 16:56:23 +00003563 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003564 UNUSED_PARAMETER(mType);
3565 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003566 if( f ){
drh4b363a52016-07-23 20:27:41 +00003567 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003568 int i = (int)strlen(z);
3569 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003570 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003571 }
drh4b363a52016-07-23 20:27:41 +00003572 return 0;
drh42f64e52012-04-04 16:56:23 +00003573}
drhc10b9da2016-11-20 17:59:59 +00003574#endif
3575#endif
drh42f64e52012-04-04 16:56:23 +00003576
3577/*
drhd8621b92012-04-17 09:09:33 +00003578** A no-op routine that runs with the ".breakpoint" doc-command. This is
3579** a useful spot to set a debugger breakpoint.
3580*/
3581static void test_breakpoint(void){
3582 static int nCall = 0;
3583 nCall++;
3584}
3585
3586/*
mistachkin636bf9f2014-07-19 20:15:16 +00003587** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003588*/
mistachkin636bf9f2014-07-19 20:15:16 +00003589typedef struct ImportCtx ImportCtx;
3590struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003591 const char *zFile; /* Name of the input file */
3592 FILE *in; /* Read the CSV text from this input stream */
3593 char *z; /* Accumulated text for a field */
3594 int n; /* Number of bytes in z */
3595 int nAlloc; /* Space allocated for z[] */
3596 int nLine; /* Current line number */
3597 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003598 int cColSep; /* The column separator character. (Usually ",") */
3599 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003600};
3601
3602/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003603static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003604 if( p->n+1>=p->nAlloc ){
3605 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003606 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003607 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003608 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003609 exit(1);
3610 }
3611 }
3612 p->z[p->n++] = (char)c;
3613}
3614
3615/* Read a single field of CSV text. Compatible with rfc4180 and extended
3616** with the option of having a separator other than ",".
3617**
3618** + Input comes from p->in.
3619** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003620** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003621** + Use p->cSep as the column separator. The default is ",".
3622** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003623** + Keep track of the line number in p->nLine.
3624** + Store the character that terminates the field in p->cTerm. Store
3625** EOF on end-of-file.
3626** + Report syntax errors on stderr
3627*/
mistachkin44723ce2015-03-21 02:22:37 +00003628static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003629 int c;
3630 int cSep = p->cColSep;
3631 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003632 p->n = 0;
3633 c = fgetc(p->in);
3634 if( c==EOF || seenInterrupt ){
3635 p->cTerm = EOF;
3636 return 0;
3637 }
3638 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003639 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003640 int startLine = p->nLine;
3641 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003642 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003643 while( 1 ){
3644 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003645 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003646 if( c==cQuote ){
3647 if( pc==cQuote ){
3648 pc = 0;
3649 continue;
3650 }
3651 }
3652 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003653 || (c==rSep && pc==cQuote)
3654 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003655 || (c==EOF && pc==cQuote)
3656 ){
3657 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003658 p->cTerm = c;
3659 break;
3660 }
3661 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003662 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003663 p->zFile, p->nLine, cQuote);
3664 }
3665 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003666 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003667 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003668 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003669 break;
3670 }
mistachkin636bf9f2014-07-19 20:15:16 +00003671 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003672 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003673 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003674 }
drhdb95f682013-06-26 22:46:00 +00003675 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00003676 while( c!=EOF && c!=cSep && c!=rSep ){
3677 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003678 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003679 }
mistachkin636bf9f2014-07-19 20:15:16 +00003680 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003681 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003682 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003683 }
drhdb95f682013-06-26 22:46:00 +00003684 p->cTerm = c;
3685 }
drh8dd675e2013-07-12 21:09:24 +00003686 if( p->z ) p->z[p->n] = 0;
drhdb95f682013-06-26 22:46:00 +00003687 return p->z;
3688}
3689
mistachkin636bf9f2014-07-19 20:15:16 +00003690/* Read a single field of ASCII delimited text.
3691**
3692** + Input comes from p->in.
3693** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003694** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003695** + Use p->cSep as the column separator. The default is "\x1F".
3696** + Use p->rSep as the row separator. The default is "\x1E".
3697** + Keep track of the row number in p->nLine.
3698** + Store the character that terminates the field in p->cTerm. Store
3699** EOF on end-of-file.
3700** + Report syntax errors on stderr
3701*/
mistachkin44723ce2015-03-21 02:22:37 +00003702static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003703 int c;
3704 int cSep = p->cColSep;
3705 int rSep = p->cRowSep;
3706 p->n = 0;
3707 c = fgetc(p->in);
3708 if( c==EOF || seenInterrupt ){
3709 p->cTerm = EOF;
3710 return 0;
3711 }
3712 while( c!=EOF && c!=cSep && c!=rSep ){
3713 import_append_char(p, c);
3714 c = fgetc(p->in);
3715 }
3716 if( c==rSep ){
3717 p->nLine++;
3718 }
3719 p->cTerm = c;
3720 if( p->z ) p->z[p->n] = 0;
3721 return p->z;
3722}
3723
drhdb95f682013-06-26 22:46:00 +00003724/*
drh4bbcf102014-02-06 02:46:08 +00003725** Try to transfer data for table zTable. If an error is seen while
3726** moving forward, try to go backwards. The backwards movement won't
3727** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003728*/
mistachkine31ae902014-02-06 01:15:29 +00003729static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003730 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003731 sqlite3 *newDb,
3732 const char *zTable
3733){
mistachkin1fe36bb2016-04-04 02:16:44 +00003734 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003735 sqlite3_stmt *pInsert = 0;
3736 char *zQuery = 0;
3737 char *zInsert = 0;
3738 int rc;
3739 int i, j, n;
3740 int nTable = (int)strlen(zTable);
3741 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003742 int cnt = 0;
3743 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003744
3745 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3746 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3747 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003748 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003749 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3750 zQuery);
3751 goto end_data_xfer;
3752 }
3753 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00003754 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00003755 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003756 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00003757 goto end_data_xfer;
3758 }
3759 sqlite3_snprintf(200+nTable,zInsert,
3760 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3761 i = (int)strlen(zInsert);
3762 for(j=1; j<n; j++){
3763 memcpy(zInsert+i, ",?", 2);
3764 i += 2;
3765 }
3766 memcpy(zInsert+i, ");", 3);
3767 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3768 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003769 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003770 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3771 zQuery);
3772 goto end_data_xfer;
3773 }
3774 for(k=0; k<2; k++){
3775 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3776 for(i=0; i<n; i++){
3777 switch( sqlite3_column_type(pQuery, i) ){
3778 case SQLITE_NULL: {
3779 sqlite3_bind_null(pInsert, i+1);
3780 break;
3781 }
3782 case SQLITE_INTEGER: {
3783 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3784 break;
3785 }
3786 case SQLITE_FLOAT: {
3787 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3788 break;
3789 }
3790 case SQLITE_TEXT: {
3791 sqlite3_bind_text(pInsert, i+1,
3792 (const char*)sqlite3_column_text(pQuery,i),
3793 -1, SQLITE_STATIC);
3794 break;
3795 }
3796 case SQLITE_BLOB: {
3797 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3798 sqlite3_column_bytes(pQuery,i),
3799 SQLITE_STATIC);
3800 break;
3801 }
3802 }
3803 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00003804 rc = sqlite3_step(pInsert);
3805 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00003806 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00003807 sqlite3_errmsg(newDb));
3808 }
drh3350ce92014-02-06 00:49:12 +00003809 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00003810 cnt++;
3811 if( (cnt%spinRate)==0 ){
3812 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3813 fflush(stdout);
3814 }
drh3350ce92014-02-06 00:49:12 +00003815 } /* End while */
3816 if( rc==SQLITE_DONE ) break;
3817 sqlite3_finalize(pQuery);
3818 sqlite3_free(zQuery);
3819 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3820 zTable);
3821 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3822 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003823 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00003824 break;
drh3350ce92014-02-06 00:49:12 +00003825 }
3826 } /* End for(k=0...) */
3827
3828end_data_xfer:
3829 sqlite3_finalize(pQuery);
3830 sqlite3_finalize(pInsert);
3831 sqlite3_free(zQuery);
3832 sqlite3_free(zInsert);
3833}
3834
3835
3836/*
3837** Try to transfer all rows of the schema that match zWhere. For
3838** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00003839** If an error is encountered while moving forward through the
3840** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00003841*/
mistachkine31ae902014-02-06 01:15:29 +00003842static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00003843 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003844 sqlite3 *newDb,
3845 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00003846 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00003847){
3848 sqlite3_stmt *pQuery = 0;
3849 char *zQuery = 0;
3850 int rc;
3851 const unsigned char *zName;
3852 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00003853 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00003854
3855 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3856 " WHERE %s", zWhere);
3857 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3858 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003859 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003860 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3861 zQuery);
3862 goto end_schema_xfer;
3863 }
3864 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3865 zName = sqlite3_column_text(pQuery, 0);
3866 zSql = sqlite3_column_text(pQuery, 1);
3867 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00003868 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3869 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00003870 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00003871 sqlite3_free(zErrMsg);
3872 zErrMsg = 0;
3873 }
drh3350ce92014-02-06 00:49:12 +00003874 if( xForEach ){
3875 xForEach(p, newDb, (const char*)zName);
3876 }
3877 printf("done\n");
3878 }
3879 if( rc!=SQLITE_DONE ){
3880 sqlite3_finalize(pQuery);
3881 sqlite3_free(zQuery);
3882 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3883 " WHERE %s ORDER BY rowid DESC", zWhere);
3884 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3885 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003886 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003887 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3888 zQuery);
3889 goto end_schema_xfer;
3890 }
3891 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3892 zName = sqlite3_column_text(pQuery, 0);
3893 zSql = sqlite3_column_text(pQuery, 1);
3894 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00003895 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3896 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00003897 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00003898 sqlite3_free(zErrMsg);
3899 zErrMsg = 0;
3900 }
drh3350ce92014-02-06 00:49:12 +00003901 if( xForEach ){
3902 xForEach(p, newDb, (const char*)zName);
3903 }
3904 printf("done\n");
3905 }
3906 }
3907end_schema_xfer:
3908 sqlite3_finalize(pQuery);
3909 sqlite3_free(zQuery);
3910}
3911
3912/*
3913** Open a new database file named "zNewDb". Try to recover as much information
3914** as possible out of the main database (which might be corrupt) and write it
3915** into zNewDb.
3916*/
drhdcd87a92014-08-18 13:45:42 +00003917static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00003918 int rc;
3919 sqlite3 *newDb = 0;
3920 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003921 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00003922 return;
3923 }
3924 rc = sqlite3_open(zNewDb, &newDb);
3925 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003926 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00003927 sqlite3_errmsg(newDb));
3928 }else{
drh54d0d2d2014-04-03 00:32:13 +00003929 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00003930 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00003931 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3932 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00003933 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00003934 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00003935 }
3936 sqlite3_close(newDb);
3937}
3938
3939/*
drhc2ce0be2014-05-29 12:36:14 +00003940** Change the output file back to stdout
3941*/
drhdcd87a92014-08-18 13:45:42 +00003942static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00003943 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00003944#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00003945 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00003946#endif
drhc2ce0be2014-05-29 12:36:14 +00003947 }else{
3948 output_file_close(p->out);
3949 }
3950 p->outfile[0] = 0;
3951 p->out = stdout;
3952}
3953
3954/*
drhf7502f02015-02-06 14:19:44 +00003955** Run an SQL command and return the single integer result.
3956*/
3957static int db_int(ShellState *p, const char *zSql){
3958 sqlite3_stmt *pStmt;
3959 int res = 0;
3960 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3961 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
3962 res = sqlite3_column_int(pStmt,0);
3963 }
3964 sqlite3_finalize(pStmt);
3965 return res;
3966}
3967
3968/*
3969** Convert a 2-byte or 4-byte big-endian integer into a native integer
3970*/
drha0620ac2016-07-13 13:05:13 +00003971static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00003972 return (a[0]<<8) + a[1];
3973}
drha0620ac2016-07-13 13:05:13 +00003974static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00003975 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
3976}
3977
3978/*
3979** Implementation of the ".info" command.
3980**
3981** Return 1 on error, 2 to exit, and 0 otherwise.
3982*/
drh0e55db12015-02-06 14:51:13 +00003983static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00003984 static const struct { const char *zName; int ofst; } aField[] = {
3985 { "file change counter:", 24 },
3986 { "database page count:", 28 },
3987 { "freelist page count:", 36 },
3988 { "schema cookie:", 40 },
3989 { "schema format:", 44 },
3990 { "default cache size:", 48 },
3991 { "autovacuum top root:", 52 },
3992 { "incremental vacuum:", 64 },
3993 { "text encoding:", 56 },
3994 { "user version:", 60 },
3995 { "application id:", 68 },
3996 { "software version:", 96 },
3997 };
drh0e55db12015-02-06 14:51:13 +00003998 static const struct { const char *zName; const char *zSql; } aQuery[] = {
3999 { "number of tables:",
4000 "SELECT count(*) FROM %s WHERE type='table'" },
4001 { "number of indexes:",
4002 "SELECT count(*) FROM %s WHERE type='index'" },
4003 { "number of triggers:",
4004 "SELECT count(*) FROM %s WHERE type='trigger'" },
4005 { "number of views:",
4006 "SELECT count(*) FROM %s WHERE type='view'" },
4007 { "schema size:",
4008 "SELECT total(length(sql)) FROM %s" },
4009 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004010 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004011 int i;
4012 char *zSchemaTab;
4013 char *zDb = nArg>=2 ? azArg[1] : "main";
4014 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004015 open_db(p, 0);
4016 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004017 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004018 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4019 return 1;
4020 }
4021 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4022 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004023 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004024 return 1;
4025 }
4026 i = get2byteInt(aHdr+16);
4027 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004028 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4029 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4030 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4031 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004032 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004033 int ofst = aField[i].ofst;
4034 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004035 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004036 switch( ofst ){
4037 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004038 if( val==1 ) raw_printf(p->out, " (utf8)");
4039 if( val==2 ) raw_printf(p->out, " (utf16le)");
4040 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004041 }
4042 }
mistachkinaae280e2015-12-31 19:06:24 +00004043 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004044 }
drh0e55db12015-02-06 14:51:13 +00004045 if( zDb==0 ){
4046 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4047 }else if( strcmp(zDb,"temp")==0 ){
4048 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4049 }else{
4050 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4051 }
drhf5ed7ad2015-06-15 14:43:25 +00004052 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004053 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4054 int val = db_int(p, zSql);
4055 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004056 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004057 }
4058 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004059 return 0;
4060}
4061
dand95bb392015-09-30 11:19:05 +00004062/*
4063** Print the current sqlite3_errmsg() value to stderr and return 1.
4064*/
4065static int shellDatabaseError(sqlite3 *db){
4066 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004067 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004068 return 1;
4069}
4070
4071/*
4072** Print an out-of-memory message to stderr and return 1.
4073*/
4074static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004075 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004076 return 1;
4077}
drhf7502f02015-02-06 14:19:44 +00004078
drh2db82112016-09-15 21:35:24 +00004079/*
4080** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4081** if they match and FALSE (0) if they do not match.
4082**
4083** Globbing rules:
4084**
4085** '*' Matches any sequence of zero or more characters.
4086**
4087** '?' Matches exactly one character.
4088**
4089** [...] Matches one character from the enclosed list of
4090** characters.
4091**
4092** [^...] Matches one character not in the enclosed list.
4093**
4094** '#' Matches any sequence of one or more digits with an
4095** optional + or - sign in front
4096**
4097** ' ' Any span of whitespace matches any other span of
4098** whitespace.
4099**
4100** Extra whitespace at the end of z[] is ignored.
4101*/
4102static int testcase_glob(const char *zGlob, const char *z){
4103 int c, c2;
4104 int invert;
4105 int seen;
4106
4107 while( (c = (*(zGlob++)))!=0 ){
4108 if( IsSpace(c) ){
4109 if( !IsSpace(*z) ) return 0;
4110 while( IsSpace(*zGlob) ) zGlob++;
4111 while( IsSpace(*z) ) z++;
4112 }else if( c=='*' ){
4113 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4114 if( c=='?' && (*(z++))==0 ) return 0;
4115 }
4116 if( c==0 ){
4117 return 1;
4118 }else if( c=='[' ){
4119 while( *z && testcase_glob(zGlob-1,z)==0 ){
4120 z++;
4121 }
4122 return (*z)!=0;
4123 }
4124 while( (c2 = (*(z++)))!=0 ){
4125 while( c2!=c ){
4126 c2 = *(z++);
4127 if( c2==0 ) return 0;
4128 }
4129 if( testcase_glob(zGlob,z) ) return 1;
4130 }
4131 return 0;
4132 }else if( c=='?' ){
4133 if( (*(z++))==0 ) return 0;
4134 }else if( c=='[' ){
4135 int prior_c = 0;
4136 seen = 0;
4137 invert = 0;
4138 c = *(z++);
4139 if( c==0 ) return 0;
4140 c2 = *(zGlob++);
4141 if( c2=='^' ){
4142 invert = 1;
4143 c2 = *(zGlob++);
4144 }
4145 if( c2==']' ){
4146 if( c==']' ) seen = 1;
4147 c2 = *(zGlob++);
4148 }
4149 while( c2 && c2!=']' ){
4150 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4151 c2 = *(zGlob++);
4152 if( c>=prior_c && c<=c2 ) seen = 1;
4153 prior_c = 0;
4154 }else{
4155 if( c==c2 ){
4156 seen = 1;
4157 }
4158 prior_c = c2;
4159 }
4160 c2 = *(zGlob++);
4161 }
4162 if( c2==0 || (seen ^ invert)==0 ) return 0;
4163 }else if( c=='#' ){
4164 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4165 if( !IsDigit(z[0]) ) return 0;
4166 z++;
4167 while( IsDigit(z[0]) ){ z++; }
4168 }else{
4169 if( c!=(*(z++)) ) return 0;
4170 }
4171 }
4172 while( IsSpace(*z) ){ z++; }
4173 return *z==0;
4174}
drh2db82112016-09-15 21:35:24 +00004175
4176
drhf7502f02015-02-06 14:19:44 +00004177/*
drh4926fec2016-04-13 15:33:42 +00004178** Compare the string as a command-line option with either one or two
4179** initial "-" characters.
4180*/
4181static int optionMatch(const char *zStr, const char *zOpt){
4182 if( zStr[0]!='-' ) return 0;
4183 zStr++;
4184 if( zStr[0]=='-' ) zStr++;
4185 return strcmp(zStr, zOpt)==0;
4186}
4187
4188/*
drhcd0509e2016-09-16 00:26:08 +00004189** Delete a file.
4190*/
4191int shellDeleteFile(const char *zFilename){
4192 int rc;
4193#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004194 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004195 rc = _wunlink(z);
4196 sqlite3_free(z);
4197#else
4198 rc = unlink(zFilename);
4199#endif
4200 return rc;
4201}
4202
dan35ac58e2016-12-14 19:28:27 +00004203
dan35ac58e2016-12-14 19:28:27 +00004204/*
dandd9e0be2016-12-16 16:44:27 +00004205** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004206** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004207** called with four arguments - the parent table name, the parent column name,
4208** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004209**
4210** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4211**
4212** If either of the named tables or columns do not exist, this function
4213** returns an empty string. An empty string is also returned if both tables
4214** and columns exist but have the same default collation sequence. Or,
4215** if both exist but the default collation sequences are different, this
4216** function returns the string " COLLATE <parent-collation>", where
4217** <parent-collation> is the default collation sequence of the parent column.
4218*/
4219static void shellFkeyCollateClause(
4220 sqlite3_context *pCtx,
4221 int nVal,
4222 sqlite3_value **apVal
4223){
4224 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4225 const char *zParent;
4226 const char *zParentCol;
4227 const char *zParentSeq;
4228 const char *zChild;
4229 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004230 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004231 int rc;
4232
4233 assert( nVal==4 );
4234 zParent = (const char*)sqlite3_value_text(apVal[0]);
4235 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4236 zChild = (const char*)sqlite3_value_text(apVal[2]);
4237 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4238
4239 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4240 rc = sqlite3_table_column_metadata(
4241 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4242 );
4243 if( rc==SQLITE_OK ){
4244 rc = sqlite3_table_column_metadata(
4245 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4246 );
4247 }
4248
4249 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4250 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4251 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4252 sqlite3_free(z);
4253 }
4254}
4255
4256
4257/*
dan3c7ebeb2016-12-16 17:28:56 +00004258** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004259*/
dan3c7ebeb2016-12-16 17:28:56 +00004260static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004261 ShellState *pState, /* Current shell tool state */
4262 char **azArg, /* Array of arguments passed to dot command */
4263 int nArg /* Number of entries in azArg[] */
4264){
dandd9e0be2016-12-16 16:44:27 +00004265 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4266 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004267 int bVerbose = 0; /* If -verbose is present */
4268 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004269 int i; /* To iterate through azArg[] */
4270 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4271 int rc; /* Return code */
4272 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004273
dandd9e0be2016-12-16 16:44:27 +00004274 /*
4275 ** This SELECT statement returns one row for each foreign key constraint
4276 ** in the schema of the main database. The column values are:
4277 **
4278 ** 0. The text of an SQL statement similar to:
4279 **
4280 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4281 **
4282 ** This is the same SELECT that the foreign keys implementation needs
4283 ** to run internally on child tables. If there is an index that can
4284 ** be used to optimize this query, then it can also be used by the FK
4285 ** implementation to optimize DELETE or UPDATE statements on the parent
4286 ** table.
4287 **
4288 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4289 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4290 ** contains an index that can be used to optimize the query.
4291 **
4292 ** 2. Human readable text that describes the child table and columns. e.g.
4293 **
4294 ** "child_table(child_key1, child_key2)"
4295 **
4296 ** 3. Human readable text that describes the parent table and columns. e.g.
4297 **
4298 ** "parent_table(parent_key1, parent_key2)"
4299 **
4300 ** 4. A full CREATE INDEX statement for an index that could be used to
4301 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4302 **
4303 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4304 **
4305 ** 5. The name of the parent table.
4306 **
4307 ** These six values are used by the C logic below to generate the report.
4308 */
dan35ac58e2016-12-14 19:28:27 +00004309 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004310 "SELECT "
4311 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4312 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
4313 " || fkey_collate_clause(f.[table], f.[to], s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004314 ", "
dandd9e0be2016-12-16 16:44:27 +00004315 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004316 " || group_concat('*=?', ' AND ') || ')'"
4317 ", "
dandd9e0be2016-12-16 16:44:27 +00004318 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004319 ", "
dandd9e0be2016-12-16 16:44:27 +00004320 " f.[table] || '(' || group_concat(COALESCE(f.[to], "
4321 " (SELECT name FROM pragma_table_info(f.[table]) WHERE pk=seq+1)"
dan35ac58e2016-12-14 19:28:27 +00004322 " )) || ')'"
4323 ", "
dandd9e0be2016-12-16 16:44:27 +00004324 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4325 " || ' ON ' || quote(s.name) || '('"
4326 " || group_concat(quote(f.[from]) ||"
4327 " fkey_collate_clause(f.[table], f.[to], s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004328 " || ');'"
danf9647b62016-12-15 06:01:40 +00004329 ", "
dandd9e0be2016-12-16 16:44:27 +00004330 " f.[table] "
dan35ac58e2016-12-14 19:28:27 +00004331
dandd9e0be2016-12-16 16:44:27 +00004332 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
4333 "GROUP BY s.name, f.id "
4334 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004335 ;
4336
dan3c7ebeb2016-12-16 17:28:56 +00004337 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004338 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004339 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4340 bVerbose = 1;
4341 }
4342 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4343 bGroupByParent = 1;
4344 zIndent = " ";
4345 }
4346 else{
dan3c7ebeb2016-12-16 17:28:56 +00004347 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4348 azArg[0], azArg[1]
4349 );
danf9647b62016-12-15 06:01:40 +00004350 return SQLITE_ERROR;
4351 }
dan35ac58e2016-12-14 19:28:27 +00004352 }
dan35ac58e2016-12-14 19:28:27 +00004353
4354 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004355 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4356 0, shellFkeyCollateClause, 0, 0
4357 );
dan35ac58e2016-12-14 19:28:27 +00004358
4359
4360 if( rc==SQLITE_OK ){
4361 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4362 }
danf9647b62016-12-15 06:01:40 +00004363 if( rc==SQLITE_OK ){
4364 sqlite3_bind_int(pSql, 1, bGroupByParent);
4365 }
dan35ac58e2016-12-14 19:28:27 +00004366
4367 if( rc==SQLITE_OK ){
4368 int rc2;
danf9647b62016-12-15 06:01:40 +00004369 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004370 while( SQLITE_ROW==sqlite3_step(pSql) ){
4371 int res = -1;
4372 sqlite3_stmt *pExplain = 0;
4373 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4374 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4375 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4376 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4377 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004378 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004379
4380 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4381 if( rc!=SQLITE_OK ) break;
4382 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4383 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
4384 res = (0==sqlite3_strglob(zGlob, zPlan));
4385 }
4386 rc = sqlite3_finalize(pExplain);
4387 if( rc!=SQLITE_OK ) break;
4388
4389 if( res<0 ){
4390 raw_printf(stderr, "Error: internal error");
4391 break;
danf9647b62016-12-15 06:01:40 +00004392 }else{
4393 if( bGroupByParent
4394 && (bVerbose || res==0)
4395 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4396 ){
4397 raw_printf(out, "-- Parent table %s\n", zParent);
4398 sqlite3_free(zPrev);
4399 zPrev = sqlite3_mprintf("%s", zParent);
4400 }
4401
4402 if( res==0 ){
4403 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4404 }else if( bVerbose ){
4405 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4406 zIndent, zFrom, zTarget
4407 );
4408 }
dan35ac58e2016-12-14 19:28:27 +00004409 }
4410 }
danf9647b62016-12-15 06:01:40 +00004411 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004412
4413 if( rc!=SQLITE_OK ){
4414 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4415 }
4416
4417 rc2 = sqlite3_finalize(pSql);
4418 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4419 rc = rc2;
4420 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4421 }
4422 }else{
4423 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4424 }
4425
4426 return rc;
4427}
dan3c7ebeb2016-12-16 17:28:56 +00004428
dan35ac58e2016-12-14 19:28:27 +00004429/*
dan3c7ebeb2016-12-16 17:28:56 +00004430** Implementation of ".lint" dot command.
4431*/
4432static int lintDotCommand(
4433 ShellState *pState, /* Current shell tool state */
4434 char **azArg, /* Array of arguments passed to dot command */
4435 int nArg /* Number of entries in azArg[] */
4436){
4437 int n;
drh96ada592016-12-29 19:48:46 +00004438 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004439 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4440 return lintFkeyIndexes(pState, azArg, nArg);
4441
4442 usage:
4443 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4444 raw_printf(stderr, "Where sub-commands are:\n");
4445 raw_printf(stderr, " fkey-indexes\n");
4446 return SQLITE_ERROR;
4447}
4448
dan35ac58e2016-12-14 19:28:27 +00004449
drhcd0509e2016-09-16 00:26:08 +00004450/*
drh75897232000-05-29 14:26:00 +00004451** If an input line begins with "." then invoke this routine to
4452** process that line.
drh67505e72002-04-19 12:34:06 +00004453**
drh47ad6842006-11-08 12:25:42 +00004454** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004455*/
drhdcd87a92014-08-18 13:45:42 +00004456static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004457 int h = 1;
drh75897232000-05-29 14:26:00 +00004458 int nArg = 0;
4459 int n, c;
drh67505e72002-04-19 12:34:06 +00004460 int rc = 0;
drh75897232000-05-29 14:26:00 +00004461 char *azArg[50];
4462
4463 /* Parse the input line into tokens.
4464 */
mistachkin8e189222015-04-19 21:43:16 +00004465 while( zLine[h] && nArg<ArraySize(azArg) ){
4466 while( IsSpace(zLine[h]) ){ h++; }
4467 if( zLine[h]==0 ) break;
4468 if( zLine[h]=='\'' || zLine[h]=='"' ){
4469 int delim = zLine[h++];
4470 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004471 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004472 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004473 h++;
drh4c56b992013-06-27 13:26:55 +00004474 }
mistachkin8e189222015-04-19 21:43:16 +00004475 if( zLine[h]==delim ){
4476 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004477 }
drhfeac5f82004-08-01 00:10:45 +00004478 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004479 }else{
mistachkin8e189222015-04-19 21:43:16 +00004480 azArg[nArg++] = &zLine[h];
4481 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4482 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004483 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004484 }
4485 }
4486
4487 /* Process the input line.
4488 */
shane9bd1b442009-10-23 01:27:39 +00004489 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004490 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004491 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004492
drha0daa752016-09-16 11:53:10 +00004493#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004494 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4495 if( nArg!=2 ){
4496 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4497 rc = 1;
4498 goto meta_command_exit;
4499 }
4500 open_db(p, 0);
4501 if( booleanValue(azArg[1]) ){
4502 sqlite3_set_authorizer(p->db, shellAuth, p);
4503 }else{
4504 sqlite3_set_authorizer(p->db, 0, 0);
4505 }
4506 }else
drha0daa752016-09-16 11:53:10 +00004507#endif
drhde613c62016-04-04 17:23:10 +00004508
drh5c7976f2014-02-10 19:59:27 +00004509 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4510 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4511 ){
drhbc46f022013-01-23 18:53:23 +00004512 const char *zDestFile = 0;
4513 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004514 sqlite3 *pDest;
4515 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004516 int j;
4517 for(j=1; j<nArg; j++){
4518 const char *z = azArg[j];
4519 if( z[0]=='-' ){
4520 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004521 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004522 {
mistachkinaae280e2015-12-31 19:06:24 +00004523 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004524 return 1;
4525 }
4526 }else if( zDestFile==0 ){
4527 zDestFile = azArg[j];
4528 }else if( zDb==0 ){
4529 zDb = zDestFile;
4530 zDestFile = azArg[j];
4531 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004532 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004533 return 1;
4534 }
drh9ff849f2009-02-04 20:55:57 +00004535 }
drhbc46f022013-01-23 18:53:23 +00004536 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004537 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004538 return 1;
4539 }
4540 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004541 rc = sqlite3_open(zDestFile, &pDest);
4542 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004543 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004544 sqlite3_close(pDest);
4545 return 1;
4546 }
drh05782482013-10-24 15:20:20 +00004547 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004548 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4549 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004550 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004551 sqlite3_close(pDest);
4552 return 1;
4553 }
4554 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4555 sqlite3_backup_finish(pBackup);
4556 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004557 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004558 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004559 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004560 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004561 }
4562 sqlite3_close(pDest);
4563 }else
4564
drhc2ce0be2014-05-29 12:36:14 +00004565 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4566 if( nArg==2 ){
4567 bail_on_error = booleanValue(azArg[1]);
4568 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004569 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004570 rc = 1;
4571 }
drhc49f44e2006-10-26 18:15:42 +00004572 }else
4573
mistachkinf21979d2015-01-18 05:35:01 +00004574 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4575 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004576 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004577 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004578 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004579 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004580 }
mistachkinf21979d2015-01-18 05:35:01 +00004581 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004582 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004583 rc = 1;
4584 }
4585 }else
4586
drhd8621b92012-04-17 09:09:33 +00004587 /* The undocumented ".breakpoint" command causes a call to the no-op
4588 ** routine named test_breakpoint().
4589 */
4590 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4591 test_breakpoint();
4592 }else
4593
drhdf12f1c2015-12-07 21:46:19 +00004594 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4595 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004596 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004597 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004598 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004599 rc = 1;
4600 }
4601 }else
4602
drh2db82112016-09-15 21:35:24 +00004603 /* Cancel output redirection, if it is currently set (by .testcase)
4604 ** Then read the content of the testcase-out.txt file and compare against
4605 ** azArg[1]. If there are differences, report an error and exit.
4606 */
4607 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4608 char *zRes = 0;
4609 output_reset(p);
4610 if( nArg!=2 ){
4611 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004612 rc = 2;
dan11da0022016-12-17 08:18:05 +00004613 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004614 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4615 rc = 2;
4616 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004617 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004618 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4619 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004620 rc = 2;
drh760c8162016-09-16 02:52:22 +00004621 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004622 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004623 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004624 }
4625 sqlite3_free(zRes);
4626 }else
drh2db82112016-09-15 21:35:24 +00004627
drhc2ce0be2014-05-29 12:36:14 +00004628 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4629 if( nArg==2 ){
4630 tryToClone(p, azArg[1]);
4631 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004632 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004633 rc = 1;
4634 }
mistachkine31ae902014-02-06 01:15:29 +00004635 }else
4636
drhc2ce0be2014-05-29 12:36:14 +00004637 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004638 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004639 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004640 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004641 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004642 data.showHeader = 0;
4643 data.cMode = data.mode = MODE_List;
4644 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004645 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004646 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4647 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004648 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004649 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004650 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004651 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004652 }
4653 }else
4654
drh0e55db12015-02-06 14:51:13 +00004655 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4656 rc = shell_dbinfo_command(p, nArg, azArg);
4657 }else
4658
drhc2ce0be2014-05-29 12:36:14 +00004659 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004660 const char *zLike = 0;
4661 int i;
drhe6e1d122017-03-09 13:50:49 +00004662 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004663 for(i=1; i<nArg; i++){
4664 if( azArg[i][0]=='-' ){
4665 const char *z = azArg[i]+1;
4666 if( z[0]=='-' ) z++;
4667 if( strcmp(z,"preserve-rowids")==0 ){
drhe6e1d122017-03-09 13:50:49 +00004668 ShellSetFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004669 }else
4670 {
4671 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4672 rc = 1;
4673 goto meta_command_exit;
4674 }
4675 }else if( zLike ){
4676 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4677 rc = 1;
4678 goto meta_command_exit;
4679 }else{
4680 zLike = azArg[i];
4681 }
4682 }
drh05782482013-10-24 15:20:20 +00004683 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004684 /* When playing back a "dump", the content might appear in an order
4685 ** which causes immediate foreign key constraints to be violated.
4686 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004687 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4688 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004689 p->writableSchema = 0;
drhe611f142017-03-08 11:44:00 +00004690 /* Set writable_schema=ON since doing so forces SQLite to initialize
4691 ** as much of the schema as it can even if the sqlite_master table is
4692 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004693 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004694 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004695 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004696 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004697 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004698 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004699 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004700 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004701 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004702 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004703 );
drh2f464a02011-10-13 00:41:49 +00004704 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004705 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004706 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004707 );
drh4c653a02000-06-07 01:27:47 +00004708 }else{
drhe611f142017-03-08 11:44:00 +00004709 char *zSql;
4710 zSql = sqlite3_mprintf(
4711 "SELECT name, type, sql FROM sqlite_master "
4712 "WHERE tbl_name LIKE %Q AND type=='table'"
4713 " AND sql NOT NULL", zLike);
4714 run_schema_dump_query(p,zSql);
4715 sqlite3_free(zSql);
4716 zSql = sqlite3_mprintf(
4717 "SELECT sql FROM sqlite_master "
4718 "WHERE sql NOT NULL"
4719 " AND type IN ('index','trigger','view')"
4720 " AND tbl_name LIKE %Q", zLike);
4721 run_table_dump_query(p, zSql, 0);
4722 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00004723 }
drh45e29d82006-11-20 16:21:10 +00004724 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00004725 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00004726 p->writableSchema = 0;
4727 }
drh56197952011-10-13 16:30:13 +00004728 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4729 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00004730 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh4c653a02000-06-07 01:27:47 +00004731 }else
drh75897232000-05-29 14:26:00 +00004732
drhc2ce0be2014-05-29 12:36:14 +00004733 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4734 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004735 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00004736 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004737 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004738 rc = 1;
4739 }
drhdaffd0e2001-04-11 14:28:42 +00004740 }else
4741
drhc2ce0be2014-05-29 12:36:14 +00004742 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4743 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00004744 if( strcmp(azArg[1],"full")==0 ){
4745 p->autoEQP = 2;
4746 }else{
4747 p->autoEQP = booleanValue(azArg[1]);
4748 }
drhc2ce0be2014-05-29 12:36:14 +00004749 }else{
drheacd29d2016-04-15 15:03:27 +00004750 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00004751 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00004752 }
drhefbf3b12014-02-28 20:47:24 +00004753 }else
4754
drhd3ac7d92013-01-25 18:33:43 +00004755 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00004756 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00004757 rc = 2;
drh75897232000-05-29 14:26:00 +00004758 }else
4759
drhc2ce0be2014-05-29 12:36:14 +00004760 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00004761 int val = 1;
4762 if( nArg>=2 ){
4763 if( strcmp(azArg[1],"auto")==0 ){
4764 val = 99;
4765 }else{
4766 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00004767 }
drh700c2522016-02-09 18:39:25 +00004768 }
4769 if( val==1 && p->mode!=MODE_Explain ){
4770 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00004771 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00004772 p->autoExplain = 0;
4773 }else if( val==0 ){
4774 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4775 p->autoExplain = 0;
4776 }else if( val==99 ){
4777 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4778 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00004779 }
drh75897232000-05-29 14:26:00 +00004780 }else
4781
drhc1971542014-06-23 23:28:13 +00004782 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004783 ShellState data;
drhc1971542014-06-23 23:28:13 +00004784 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00004785 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00004786 memcpy(&data, p, sizeof(data));
4787 data.showHeader = 0;
4788 data.cMode = data.mode = MODE_Semi;
4789 if( nArg==2 && optionMatch(azArg[1], "indent") ){
4790 data.cMode = data.mode = MODE_Pretty;
4791 nArg = 1;
4792 }
drhc1971542014-06-23 23:28:13 +00004793 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00004794 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00004795 rc = 1;
4796 goto meta_command_exit;
4797 }
4798 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00004799 rc = sqlite3_exec(p->db,
4800 "SELECT sql FROM"
4801 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4802 " FROM sqlite_master UNION ALL"
4803 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00004804 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00004805 "ORDER BY rowid",
4806 callback, &data, &zErrMsg
4807 );
drh56f674c2014-07-18 14:43:29 +00004808 if( rc==SQLITE_OK ){
4809 sqlite3_stmt *pStmt;
4810 rc = sqlite3_prepare_v2(p->db,
4811 "SELECT rowid FROM sqlite_master"
4812 " WHERE name GLOB 'sqlite_stat[134]'",
4813 -1, &pStmt, 0);
4814 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4815 sqlite3_finalize(pStmt);
4816 }
4817 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004818 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00004819 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004820 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00004821 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4822 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00004823 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00004824 data.zDestTable = "sqlite_stat1";
4825 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4826 shell_callback, &data,&zErrMsg);
4827 data.zDestTable = "sqlite_stat3";
4828 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4829 shell_callback, &data,&zErrMsg);
4830 data.zDestTable = "sqlite_stat4";
4831 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4832 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00004833 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00004834 }
drhc1971542014-06-23 23:28:13 +00004835 }else
4836
drhc2ce0be2014-05-29 12:36:14 +00004837 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4838 if( nArg==2 ){
4839 p->showHeader = booleanValue(azArg[1]);
4840 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004841 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004842 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00004843 }
drh75897232000-05-29 14:26:00 +00004844 }else
4845
drhc2ce0be2014-05-29 12:36:14 +00004846 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004847 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00004848 }else
4849
4850 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00004851 char *zTable; /* Insert data into this table */
4852 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00004853 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00004854 int nCol; /* Number of columns in the table */
4855 int nByte; /* Number of bytes in an SQL string */
4856 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00004857 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00004858 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00004859 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00004860 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00004861 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4862 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00004863
drhc2ce0be2014-05-29 12:36:14 +00004864 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00004865 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00004866 goto meta_command_exit;
4867 }
drh01f37542014-05-31 15:43:33 +00004868 zFile = azArg[1];
4869 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00004870 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00004871 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00004872 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00004873 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00004874 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004875 raw_printf(stderr,
4876 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00004877 return 1;
drhfeac5f82004-08-01 00:10:45 +00004878 }
drhdb95f682013-06-26 22:46:00 +00004879 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00004880 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00004881 " for import\n");
4882 return 1;
4883 }
mistachkin636bf9f2014-07-19 20:15:16 +00004884 nSep = strlen30(p->rowSeparator);
4885 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004886 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00004887 return 1;
4888 }
mistachkine0d68852014-12-11 03:12:33 +00004889 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4890 /* When importing CSV (only), if the row separator is set to the
4891 ** default output row separator, change it to the default input
4892 ** row separator. This avoids having to maintain different input
4893 ** and output row separators. */
4894 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4895 nSep = strlen30(p->rowSeparator);
4896 }
mistachkin636bf9f2014-07-19 20:15:16 +00004897 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00004898 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00004899 " for import\n");
4900 return 1;
4901 }
4902 sCtx.zFile = zFile;
4903 sCtx.nLine = 1;
4904 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004905#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00004906 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00004907 return 1;
4908#else
mistachkin636bf9f2014-07-19 20:15:16 +00004909 sCtx.in = popen(sCtx.zFile+1, "r");
4910 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00004911 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00004912#endif
drh5bde8162013-06-27 14:07:53 +00004913 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00004914 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00004915 xCloser = fclose;
4916 }
mistachkin636bf9f2014-07-19 20:15:16 +00004917 if( p->mode==MODE_Ascii ){
4918 xRead = ascii_read_one_field;
4919 }else{
4920 xRead = csv_read_one_field;
4921 }
4922 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004923 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00004924 return 1;
4925 }
mistachkin636bf9f2014-07-19 20:15:16 +00004926 sCtx.cColSep = p->colSeparator[0];
4927 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00004928 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00004929 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004930 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00004931 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00004932 return 1;
4933 }
drh4f21c4a2008-12-10 22:15:00 +00004934 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00004935 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00004936 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00004937 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00004938 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
4939 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00004940 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00004941 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00004942 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00004943 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00004944 }
drh5bde8162013-06-27 14:07:53 +00004945 if( cSep=='(' ){
4946 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00004947 sqlite3_free(sCtx.z);
4948 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00004949 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00004950 return 1;
4951 }
drhdb95f682013-06-26 22:46:00 +00004952 zCreate = sqlite3_mprintf("%z\n)", zCreate);
4953 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
4954 sqlite3_free(zCreate);
4955 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004956 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00004957 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00004958 sqlite3_free(sCtx.z);
4959 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00004960 return 1;
4961 }
drhc7181902014-02-27 15:04:13 +00004962 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00004963 }
drhfeac5f82004-08-01 00:10:45 +00004964 sqlite3_free(zSql);
4965 if( rc ){
shane916f9612009-10-23 00:37:15 +00004966 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00004967 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00004968 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00004969 return 1;
drhfeac5f82004-08-01 00:10:45 +00004970 }
shane916f9612009-10-23 00:37:15 +00004971 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00004972 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00004973 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00004974 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00004975 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00004976 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004977 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00004978 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00004979 return 1;
4980 }
drhdb95f682013-06-26 22:46:00 +00004981 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00004982 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00004983 for(i=1; i<nCol; i++){
4984 zSql[j++] = ',';
4985 zSql[j++] = '?';
4986 }
4987 zSql[j++] = ')';
4988 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00004989 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00004990 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00004991 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004992 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00004993 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00004994 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00004995 return 1;
drhfeac5f82004-08-01 00:10:45 +00004996 }
mistachkin8e189222015-04-19 21:43:16 +00004997 needCommit = sqlite3_get_autocommit(p->db);
4998 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00004999 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005000 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005001 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005002 char *z = xRead(&sCtx);
5003 /*
5004 ** Did we reach end-of-file before finding any columns?
5005 ** If so, stop instead of NULL filling the remaining columns.
5006 */
drhdb95f682013-06-26 22:46:00 +00005007 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005008 /*
5009 ** Did we reach end-of-file OR end-of-line before finding any
5010 ** columns in ASCII mode? If so, stop instead of NULL filling
5011 ** the remaining columns.
5012 */
5013 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005014 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005015 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005016 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005017 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005018 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005019 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005020 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005021 }
drhfeac5f82004-08-01 00:10:45 +00005022 }
mistachkin636bf9f2014-07-19 20:15:16 +00005023 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005024 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005025 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005026 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005027 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005028 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005029 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005030 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005031 }
drhdb95f682013-06-26 22:46:00 +00005032 if( i>=nCol ){
5033 sqlite3_step(pStmt);
5034 rc = sqlite3_reset(pStmt);
5035 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005036 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5037 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005038 }
5039 }
mistachkin636bf9f2014-07-19 20:15:16 +00005040 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005041
mistachkin636bf9f2014-07-19 20:15:16 +00005042 xCloser(sCtx.in);
5043 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005044 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005045 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005046 }else
5047
drhd12602a2016-12-07 15:49:02 +00005048#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005049 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5050 char *zSql;
5051 char *zCollist = 0;
5052 sqlite3_stmt *pStmt;
5053 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005054 int i;
drh16eb5942016-11-03 13:01:38 +00005055 if( nArg!=3 ){
5056 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5057 rc = 1;
5058 goto meta_command_exit;
5059 }
5060 open_db(p, 0);
5061 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5062 " WHERE name='%q' AND type='index'", azArg[1]);
5063 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5064 sqlite3_free(zSql);
5065 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5066 tnum = sqlite3_column_int(pStmt, 0);
5067 }
5068 sqlite3_finalize(pStmt);
5069 if( tnum==0 ){
5070 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5071 rc = 1;
5072 goto meta_command_exit;
5073 }
5074 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5075 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5076 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005077 i = 0;
drh16eb5942016-11-03 13:01:38 +00005078 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005079 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005080 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005081 i++;
5082 if( zCol==0 ){
5083 if( sqlite3_column_int(pStmt,1)==-1 ){
5084 zCol = "_ROWID_";
5085 }else{
5086 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5087 zCol = zLabel;
5088 }
5089 }
drh16eb5942016-11-03 13:01:38 +00005090 if( zCollist==0 ){
5091 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5092 }else{
5093 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5094 }
5095 }
5096 sqlite3_finalize(pStmt);
5097 zSql = sqlite3_mprintf(
5098 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5099 azArg[2], zCollist, zCollist);
5100 sqlite3_free(zCollist);
5101 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5102 if( rc==SQLITE_OK ){
5103 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5104 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5105 if( rc ){
5106 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5107 }else{
5108 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005109 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005110 "WARNING: writing to an imposter table will corrupt the index!\n"
5111 );
5112 }
5113 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005114 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005115 rc = 1;
5116 }
5117 sqlite3_free(zSql);
5118 }else
5119#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5120
drhae5e4452007-05-03 17:18:36 +00005121#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005122 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005123 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005124 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5125 iotrace = 0;
5126 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005127 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005128 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005129 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005130 iotrace = stdout;
5131 }else{
5132 iotrace = fopen(azArg[1], "w");
5133 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005134 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005135 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005136 rc = 1;
drhb0603412007-02-28 04:47:26 +00005137 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005138 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005139 }
5140 }
5141 }else
drhae5e4452007-05-03 17:18:36 +00005142#endif
drh16eb5942016-11-03 13:01:38 +00005143
drh1a513372015-05-02 17:40:23 +00005144 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5145 static const struct {
5146 const char *zLimitName; /* Name of a limit */
5147 int limitCode; /* Integer code for that limit */
5148 } aLimit[] = {
5149 { "length", SQLITE_LIMIT_LENGTH },
5150 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5151 { "column", SQLITE_LIMIT_COLUMN },
5152 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5153 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5154 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5155 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5156 { "attached", SQLITE_LIMIT_ATTACHED },
5157 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5158 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5159 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5160 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5161 };
5162 int i, n2;
5163 open_db(p, 0);
5164 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005165 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005166 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005167 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5168 }
5169 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005170 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005171 rc = 1;
5172 goto meta_command_exit;
5173 }else{
5174 int iLimit = -1;
5175 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005176 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005177 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5178 if( iLimit<0 ){
5179 iLimit = i;
5180 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005181 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005182 rc = 1;
5183 goto meta_command_exit;
5184 }
5185 }
5186 }
5187 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005188 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005189 "enter \".limits\" with no arguments for a list.\n",
5190 azArg[1]);
5191 rc = 1;
5192 goto meta_command_exit;
5193 }
5194 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005195 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5196 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005197 }
5198 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5199 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5200 }
5201 }else
drhb0603412007-02-28 04:47:26 +00005202
dan3c7ebeb2016-12-16 17:28:56 +00005203 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005204 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005205 lintDotCommand(p, azArg, nArg);
5206 }else
5207
drh70df4fe2006-06-13 15:12:21 +00005208#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005209 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005210 const char *zFile, *zProc;
5211 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005212 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005213 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005214 rc = 1;
5215 goto meta_command_exit;
5216 }
drh1e397f82006-06-08 15:28:43 +00005217 zFile = azArg[1];
5218 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005219 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005220 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5221 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005222 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005223 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005224 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005225 }
5226 }else
drh70df4fe2006-06-13 15:12:21 +00005227#endif
drh1e397f82006-06-08 15:28:43 +00005228
drhc2ce0be2014-05-29 12:36:14 +00005229 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5230 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005231 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005232 rc = 1;
5233 }else{
5234 const char *zFile = azArg[1];
5235 output_file_close(p->pLog);
5236 p->pLog = output_file_open(zFile);
5237 }
drh127f9d72010-02-23 01:47:00 +00005238 }else
5239
drhc2ce0be2014-05-29 12:36:14 +00005240 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5241 const char *zMode = nArg>=2 ? azArg[1] : "";
5242 int n2 = (int)strlen(zMode);
5243 int c2 = zMode[0];
5244 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005245 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005246 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005247 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005248 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005249 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005250 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005251 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005252 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5253 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005254 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005255 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005256 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005257 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005258 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005259 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005260 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005261 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005262 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005263 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005264 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005265 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005266 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005267 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005268 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005269 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005270 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5271 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005272 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5273 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005274 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5275 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drhdaffd0e2001-04-11 14:28:42 +00005276 }else {
mistachkinaae280e2015-12-31 19:06:24 +00005277 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005278 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005279 rc = 1;
drh75897232000-05-29 14:26:00 +00005280 }
drh700c2522016-02-09 18:39:25 +00005281 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005282 }else
5283
drhc2ce0be2014-05-29 12:36:14 +00005284 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5285 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005286 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5287 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005288 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005289 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005290 rc = 1;
5291 }
5292 }else
5293
drh05782482013-10-24 15:20:20 +00005294 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005295 char *zNewFilename; /* Name of the database file to open */
5296 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005297 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005298 /* Close the existing database */
5299 session_close_all(p);
5300 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005301 p->db = 0;
dan21472212017-03-01 11:30:27 +00005302 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005303 sqlite3_free(p->zFreeOnClose);
5304 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005305 /* Check for command-line arguments */
5306 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5307 const char *z = azArg[iName];
5308 if( optionMatch(z,"new") ){
5309 newFlag = 1;
5310 }else if( z[0]=='-' ){
5311 utf8_printf(stderr, "unknown option: %s\n", z);
5312 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005313 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005314 }
drhcd0509e2016-09-16 00:26:08 +00005315 }
5316 /* If a filename is specified, try to open it first */
5317 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5318 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005319 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005320 p->zDbFilename = zNewFilename;
5321 open_db(p, 1);
5322 if( p->db==0 ){
5323 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5324 sqlite3_free(zNewFilename);
5325 }else{
5326 p->zFreeOnClose = zNewFilename;
5327 }
5328 }
5329 if( p->db==0 ){
5330 /* As a fall-back open a TEMP database */
5331 p->zDbFilename = 0;
5332 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005333 }
5334 }else
5335
drhc2ce0be2014-05-29 12:36:14 +00005336 if( c=='o'
5337 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5338 ){
5339 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5340 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005341 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005342 rc = 1;
5343 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005344 }
drhc2ce0be2014-05-29 12:36:14 +00005345 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5346 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005347 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005348 rc = 1;
5349 goto meta_command_exit;
5350 }
5351 p->outCount = 2;
5352 }else{
5353 p->outCount = 0;
5354 }
5355 output_reset(p);
5356 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005357#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005358 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005359 rc = 1;
5360 p->out = stdout;
5361#else
drhc2ce0be2014-05-29 12:36:14 +00005362 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005363 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005364 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005365 p->out = stdout;
5366 rc = 1;
5367 }else{
drhc2ce0be2014-05-29 12:36:14 +00005368 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005369 }
drh8cd5b252015-03-02 22:06:43 +00005370#endif
drh75897232000-05-29 14:26:00 +00005371 }else{
drhc2ce0be2014-05-29 12:36:14 +00005372 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005373 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005374 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005375 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005376 }
drh75897232000-05-29 14:26:00 +00005377 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005378 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005379 } else {
drhc2ce0be2014-05-29 12:36:14 +00005380 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005381 }
5382 }
5383 }else
5384
drh078b1fd2012-09-21 13:40:02 +00005385 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5386 int i;
5387 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005388 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005389 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005390 }
mistachkinaae280e2015-12-31 19:06:24 +00005391 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005392 }else
5393
drhc2ce0be2014-05-29 12:36:14 +00005394 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005395 if( nArg >= 2) {
5396 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5397 }
5398 if( nArg >= 3) {
5399 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5400 }
5401 }else
5402
drhc2ce0be2014-05-29 12:36:14 +00005403 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005404 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005405 }else
5406
drhc2ce0be2014-05-29 12:36:14 +00005407 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5408 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005409 if( nArg!=2 ){
5410 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005411 rc = 1;
5412 goto meta_command_exit;
5413 }
drh4e8142c2016-11-11 14:54:22 +00005414 alt = fopen(azArg[1], "rb");
5415 if( alt==0 ){
5416 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5417 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005418 }else{
drh4e8142c2016-11-11 14:54:22 +00005419 rc = process_input(p, alt);
5420 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005421 }
5422 }else
5423
drhc2ce0be2014-05-29 12:36:14 +00005424 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005425 const char *zSrcFile;
5426 const char *zDb;
5427 sqlite3 *pSrc;
5428 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005429 int nTimeout = 0;
5430
drh9ff849f2009-02-04 20:55:57 +00005431 if( nArg==2 ){
5432 zSrcFile = azArg[1];
5433 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005434 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005435 zSrcFile = azArg[2];
5436 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005437 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005438 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005439 rc = 1;
5440 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005441 }
5442 rc = sqlite3_open(zSrcFile, &pSrc);
5443 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005444 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005445 sqlite3_close(pSrc);
5446 return 1;
5447 }
drh05782482013-10-24 15:20:20 +00005448 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005449 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5450 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005451 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005452 sqlite3_close(pSrc);
5453 return 1;
5454 }
drhdc2c4912009-02-04 22:46:47 +00005455 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5456 || rc==SQLITE_BUSY ){
5457 if( rc==SQLITE_BUSY ){
5458 if( nTimeout++ >= 3 ) break;
5459 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005460 }
5461 }
5462 sqlite3_backup_finish(pBackup);
5463 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005464 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005465 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005466 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005467 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005468 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005469 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005470 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005471 }
5472 sqlite3_close(pSrc);
5473 }else
5474
dan8d1edb92014-11-05 09:07:28 +00005475
5476 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5477 if( nArg==2 ){
5478 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005479#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005480 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005481#endif
dan8d1edb92014-11-05 09:07:28 +00005482 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005483 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005484 rc = 1;
5485 }
5486 }else
5487
drhc2ce0be2014-05-29 12:36:14 +00005488 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005489 ShellState data;
drh75897232000-05-29 14:26:00 +00005490 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00005491 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005492 memcpy(&data, p, sizeof(data));
5493 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005494 data.cMode = data.mode = MODE_Semi;
drh4926fec2016-04-13 15:33:42 +00005495 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5496 data.cMode = data.mode = MODE_Pretty;
5497 nArg--;
5498 if( nArg==2 ) azArg[1] = azArg[2];
5499 }
5500 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005501 int i;
drhf0693c82011-10-11 20:41:54 +00005502 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005503 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005504 char *new_argv[2], *new_colv[2];
5505 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5506 " type text,\n"
5507 " name text,\n"
5508 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005509 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005510 " sql text\n"
5511 ")";
5512 new_argv[1] = 0;
5513 new_colv[0] = "sql";
5514 new_colv[1] = 0;
5515 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005516 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005517 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005518 char *new_argv[2], *new_colv[2];
5519 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5520 " type text,\n"
5521 " name text,\n"
5522 " tbl_name text,\n"
5523 " rootpage integer,\n"
5524 " sql text\n"
5525 ")";
5526 new_argv[1] = 0;
5527 new_colv[0] = "sql";
5528 new_colv[1] = 0;
5529 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005530 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005531 }else{
drhe611f142017-03-08 11:44:00 +00005532 char *zSql;
5533 zSql = sqlite3_mprintf(
drhe0bc4042002-06-25 01:09:11 +00005534 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005535 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005536 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005537 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drhe611f142017-03-08 11:44:00 +00005538 "WHERE lower(tbl_name) LIKE %Q"
drh6ac7a582011-11-04 00:35:56 +00005539 " AND type!='meta' AND sql NOTNULL "
drhe611f142017-03-08 11:44:00 +00005540 "ORDER BY rowid", azArg[1]);
5541 rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
5542 sqlite3_free(zSql);
drha18c5682000-10-08 22:20:57 +00005543 }
drhc2ce0be2014-05-29 12:36:14 +00005544 }else if( nArg==1 ){
shane9bd1b442009-10-23 01:27:39 +00005545 rc = sqlite3_exec(p->db,
drhe0bc4042002-06-25 01:09:11 +00005546 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005547 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005548 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005549 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005550 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drh1ba00292013-05-06 21:01:06 +00005551 "ORDER BY rowid",
drha18c5682000-10-08 22:20:57 +00005552 callback, &data, &zErrMsg
5553 );
drhc2ce0be2014-05-29 12:36:14 +00005554 }else{
drh4926fec2016-04-13 15:33:42 +00005555 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005556 rc = 1;
5557 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005558 }
drh75897232000-05-29 14:26:00 +00005559 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005560 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005561 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005562 rc = 1;
5563 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005564 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005565 rc = 1;
5566 }else{
5567 rc = 0;
drh75897232000-05-29 14:26:00 +00005568 }
5569 }else
5570
drhabd4c722014-09-20 18:18:33 +00005571#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5572 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005573 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005574 }else
5575#endif
5576
drhe6229612014-08-18 15:08:26 +00005577#if defined(SQLITE_ENABLE_SESSION)
5578 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5579 OpenSession *pSession = &p->aSession[0];
5580 char **azCmd = &azArg[1];
5581 int iSes = 0;
5582 int nCmd = nArg - 1;
5583 int i;
5584 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005585 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005586 if( nArg>=3 ){
5587 for(iSes=0; iSes<p->nSession; iSes++){
5588 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5589 }
5590 if( iSes<p->nSession ){
5591 pSession = &p->aSession[iSes];
5592 azCmd++;
5593 nCmd--;
5594 }else{
5595 pSession = &p->aSession[0];
5596 iSes = 0;
5597 }
5598 }
5599
drh3a67b042014-08-18 17:56:31 +00005600 /* .session attach TABLE
5601 ** Invoke the sqlite3session_attach() interface to attach a particular
5602 ** table so that it is never filtered.
5603 */
5604 if( strcmp(azCmd[0],"attach")==0 ){
5605 if( nCmd!=2 ) goto session_syntax_error;
5606 if( pSession->p==0 ){
5607 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005608 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005609 }else{
5610 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5611 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005612 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005613 rc = 0;
5614 }
5615 }
5616 }else
5617
5618 /* .session changeset FILE
5619 ** .session patchset FILE
5620 ** Write a changeset or patchset into a file. The file is overwritten.
5621 */
5622 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5623 FILE *out = 0;
5624 if( nCmd!=2 ) goto session_syntax_error;
5625 if( pSession->p==0 ) goto session_not_open;
5626 out = fopen(azCmd[1], "wb");
5627 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005628 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005629 }else{
5630 int szChng;
5631 void *pChng;
5632 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005633 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005634 }else{
drh2967e0c2014-08-19 00:26:17 +00005635 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5636 }
5637 if( rc ){
5638 printf("Error: error code %d\n", rc);
5639 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005640 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005641 if( pChng
drh3a67b042014-08-18 17:56:31 +00005642 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005643 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005644 szChng);
5645 }
5646 sqlite3_free(pChng);
5647 fclose(out);
5648 }
5649 }else
5650
drhe6229612014-08-18 15:08:26 +00005651 /* .session close
5652 ** Close the identified session
5653 */
5654 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005655 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005656 if( p->nSession ){
5657 session_close(pSession);
5658 p->aSession[iSes] = p->aSession[--p->nSession];
5659 }
5660 }else
5661
drh03168ca2014-08-18 20:01:31 +00005662 /* .session enable ?BOOLEAN?
5663 ** Query or set the enable flag
5664 */
5665 if( strcmp(azCmd[0], "enable")==0 ){
5666 int ii;
5667 if( nCmd>2 ) goto session_syntax_error;
5668 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5669 if( p->nSession ){
5670 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005671 utf8_printf(p->out, "session %s enable flag = %d\n",
5672 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005673 }
5674 }else
5675
5676 /* .session filter GLOB ....
5677 ** Set a list of GLOB patterns of table names to be excluded.
5678 */
5679 if( strcmp(azCmd[0], "filter")==0 ){
5680 int ii, nByte;
5681 if( nCmd<2 ) goto session_syntax_error;
5682 if( p->nSession ){
5683 for(ii=0; ii<pSession->nFilter; ii++){
5684 sqlite3_free(pSession->azFilter[ii]);
5685 }
5686 sqlite3_free(pSession->azFilter);
5687 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5688 pSession->azFilter = sqlite3_malloc( nByte );
5689 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005690 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00005691 exit(1);
5692 }
5693 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005694 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00005695 }
5696 pSession->nFilter = ii-1;
5697 }
5698 }else
5699
5700 /* .session indirect ?BOOLEAN?
5701 ** Query or set the indirect flag
5702 */
5703 if( strcmp(azCmd[0], "indirect")==0 ){
5704 int ii;
5705 if( nCmd>2 ) goto session_syntax_error;
5706 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5707 if( p->nSession ){
5708 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005709 utf8_printf(p->out, "session %s indirect flag = %d\n",
5710 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005711 }
5712 }else
5713
5714 /* .session isempty
5715 ** Determine if the session is empty
5716 */
5717 if( strcmp(azCmd[0], "isempty")==0 ){
5718 int ii;
5719 if( nCmd!=1 ) goto session_syntax_error;
5720 if( p->nSession ){
5721 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00005722 utf8_printf(p->out, "session %s isempty flag = %d\n",
5723 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005724 }
5725 }else
5726
drhe6229612014-08-18 15:08:26 +00005727 /* .session list
5728 ** List all currently open sessions
5729 */
5730 if( strcmp(azCmd[0],"list")==0 ){
5731 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00005732 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00005733 }
5734 }else
5735
5736 /* .session open DB NAME
5737 ** Open a new session called NAME on the attached database DB.
5738 ** DB is normally "main".
5739 */
5740 if( strcmp(azCmd[0],"open")==0 ){
5741 char *zName;
5742 if( nCmd!=3 ) goto session_syntax_error;
5743 zName = azCmd[2];
5744 if( zName[0]==0 ) goto session_syntax_error;
5745 for(i=0; i<p->nSession; i++){
5746 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005747 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00005748 goto meta_command_exit;
5749 }
5750 }
5751 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00005752 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00005753 goto meta_command_exit;
5754 }
5755 pSession = &p->aSession[p->nSession];
5756 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5757 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005758 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005759 rc = 0;
drhe6229612014-08-18 15:08:26 +00005760 goto meta_command_exit;
5761 }
drh03168ca2014-08-18 20:01:31 +00005762 pSession->nFilter = 0;
5763 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00005764 p->nSession++;
5765 pSession->zName = sqlite3_mprintf("%s", zName);
5766 }else
5767 /* If no command name matches, show a syntax error */
5768 session_syntax_error:
5769 session_help(p);
5770 }else
5771#endif
5772
drh340f5822013-06-27 13:01:21 +00005773#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00005774 /* Undocumented commands for internal testing. Subject to change
5775 ** without notice. */
5776 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5777 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5778 int i, v;
5779 for(i=1; i<nArg; i++){
5780 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00005781 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00005782 }
5783 }
5784 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5785 int i; sqlite3_int64 v;
5786 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00005787 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00005788 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00005789 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00005790 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00005791 }
5792 }
5793 }else
drh340f5822013-06-27 13:01:21 +00005794#endif
drh348d19c2013-06-03 12:47:43 +00005795
drhfb546af2017-03-09 22:00:33 +00005796 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5797 int bIsInit = 0; /* True to initialize the SELFTEST table */
5798 int bVerbose = 0; /* Verbose output */
5799 int bSelftestExists; /* True if SELFTEST already exists */
5800 char **azTest = 0; /* Content of the SELFTEST table */
5801 int nRow = 0; /* Number of rows in the SELFTEST table */
5802 int nCol = 4; /* Number of columns in the SELFTEST table */
5803 int i; /* Loop counter */
5804 int nTest = 0; /* Number of tests runs */
5805 int nErr = 0; /* Number of errors seen */
5806 ShellText str; /* Answer for a query */
5807 static char *azDefaultTest[] = {
5808 0, 0, 0, 0,
5809 "0", "memo", "Missing SELFTEST table - default checks only", "",
5810 "1", "run", "PRAGMA integrity_check", "ok"
5811 };
5812 static const int nDefaultRow = 2;
5813
5814 open_db(p,0);
5815 for(i=1; i<nArg; i++){
5816 const char *z = azArg[i];
5817 if( z[0]=='-' && z[1]=='-' ) z++;
5818 if( strcmp(z,"-init")==0 ){
5819 bIsInit = 1;
5820 }else
5821 if( strcmp(z,"-v")==0 ){
5822 bVerbose++;
5823 }else
5824 {
5825 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5826 azArg[i], azArg[0]);
5827 raw_printf(stderr, "Should be one of: --init -v\n");
5828 rc = 1;
5829 goto meta_command_exit;
5830 }
5831 }
5832 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5833 != SQLITE_OK ){
5834 bSelftestExists = 0;
5835 }else{
5836 bSelftestExists = 1;
5837 }
5838 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00005839 createSelftestTable(p);
5840 bSelftestExists = 1;
5841 }
5842 if( bSelftestExists ){
5843 rc = sqlite3_get_table(p->db,
5844 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5845 &azTest, &nRow, &nCol, 0);
5846 if( rc ){
5847 raw_printf(stderr, "Error querying the selftest table\n");
5848 rc = 1;
5849 sqlite3_free_table(azTest);
5850 goto meta_command_exit;
5851 }else if( nRow==0 ){
5852 sqlite3_free_table(azTest);
5853 azTest = azDefaultTest;
5854 nRow = nDefaultRow;
5855 }
5856 }else{
5857 azTest = azDefaultTest;
5858 nRow = nDefaultRow;
5859 }
5860 initText(&str);
5861 appendText(&str, "x", 0);
5862 for(i=1; i<=nRow; i++){
5863 int tno = atoi(azTest[i*nCol]);
5864 const char *zOp = azTest[i*nCol+1];
5865 const char *zSql = azTest[i*nCol+2];
5866 const char *zAns = azTest[i*nCol+3];
5867
5868 if( bVerbose>0 ){
5869 char *zQuote = sqlite3_mprintf("%q", zSql);
5870 printf("%d: %s %s\n", tno, zOp, zSql);
5871 sqlite3_free(zQuote);
5872 }
5873 if( strcmp(zOp,"memo")==0 ){
5874 utf8_printf(p->out, "%s\n", zSql);
5875 }else
5876 if( strcmp(zOp,"run")==0 ){
5877 char *zErrMsg = 0;
5878 str.n = 0;
5879 str.z[0] = 0;
5880 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5881 nTest++;
5882 if( bVerbose ){
5883 utf8_printf(p->out, "Result: %s\n", str.z);
5884 }
5885 if( rc || zErrMsg ){
5886 nErr++;
5887 rc = 1;
5888 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5889 sqlite3_free(zErrMsg);
5890 }else if( strcmp(zAns,str.z)!=0 ){
5891 nErr++;
5892 rc = 1;
5893 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5894 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
5895 }
5896 }else
5897 {
5898 utf8_printf(stderr,
5899 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5900 rc = 1;
5901 break;
5902 }
5903 }
5904 freeText(&str);
5905 if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
5906 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5907 }else
5908
drhc2ce0be2014-05-29 12:36:14 +00005909 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00005910 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005911 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00005912 rc = 1;
5913 }
drh6976c212014-07-24 12:09:47 +00005914 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00005915 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00005916 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00005917 }
5918 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00005919 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5920 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00005921 }
drh75897232000-05-29 14:26:00 +00005922 }else
5923
drh1554bc82017-03-08 16:10:34 +00005924 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5925 const char *zLike = 0; /* Which table to checksum. 0 means everything */
5926 int i; /* Loop counter */
5927 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00005928 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00005929 int iSize = 224; /* Hash algorithm to use */
5930 int bDebug = 0; /* Only show the query that would have run */
5931 sqlite3_stmt *pStmt; /* For querying tables names */
5932 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00005933 char *zSep; /* Separator */
5934 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00005935 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00005936 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00005937 for(i=1; i<nArg; i++){
5938 const char *z = azArg[i];
5939 if( z[0]=='-' ){
5940 z++;
5941 if( z[0]=='-' ) z++;
5942 if( strcmp(z,"schema")==0 ){
5943 bSchema = 1;
5944 }else
5945 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
5946 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
5947 ){
5948 iSize = atoi(&z[5]);
5949 }else
5950 if( strcmp(z,"debug")==0 ){
5951 bDebug = 1;
5952 }else
5953 {
5954 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00005955 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00005956 raw_printf(stderr, "Should be one of: --schema"
5957 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
5958 rc = 1;
5959 goto meta_command_exit;
5960 }
5961 }else if( zLike ){
5962 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
5963 rc = 1;
5964 goto meta_command_exit;
5965 }else{
5966 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00005967 bSeparate = 1;
5968 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00005969 }
5970 }
5971 if( bSchema ){
5972 zSql = "SELECT lower(name) FROM sqlite_master"
5973 " WHERE type='table' AND coalesce(rootpage,0)>1"
5974 " UNION ALL SELECT 'sqlite_master'"
5975 " ORDER BY 1 collate nocase";
5976 }else{
5977 zSql = "SELECT lower(name) FROM sqlite_master"
5978 " WHERE type='table' AND coalesce(rootpage,0)>1"
5979 " AND name NOT LIKE 'sqlite_%'"
5980 " ORDER BY 1 collate nocase";
5981 }
5982 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5983 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00005984 initText(&sSql);
5985 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
5986 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00005987 while( SQLITE_ROW==sqlite3_step(pStmt) ){
5988 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
5989 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
5990 if( strncmp(zTab, "sqlite_",7)!=0 ){
5991 appendText(&sQuery,"SELECT * FROM ", 0);
5992 appendText(&sQuery,zTab,'"');
5993 appendText(&sQuery," NOT INDEXED;", 0);
5994 }else if( strcmp(zTab, "sqlite_master")==0 ){
5995 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
5996 " ORDER BY name;", 0);
5997 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
5998 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
5999 " ORDER BY name;", 0);
6000 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6001 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6002 " ORDER BY tbl,idx;", 0);
6003 }else if( strcmp(zTab, "sqlite_stat3")==0
6004 || strcmp(zTab, "sqlite_stat4")==0 ){
6005 appendText(&sQuery, "SELECT * FROM ", 0);
6006 appendText(&sQuery, zTab, 0);
6007 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6008 }
drh3ee83ef2017-03-08 17:56:54 +00006009 appendText(&sSql, zSep, 0);
6010 appendText(&sSql, sQuery.z, '\'');
6011 sQuery.n = 0;
6012 appendText(&sSql, ",", 0);
6013 appendText(&sSql, zTab, '\'');
6014 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006015 }
6016 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006017 if( bSeparate ){
6018 zSql = sqlite3_mprintf(
6019 "%s))"
6020 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6021 " FROM [sha3sum$query]",
6022 sSql.z, iSize);
6023 }else{
6024 zSql = sqlite3_mprintf(
6025 "%s))"
6026 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6027 " FROM [sha3sum$query]",
6028 sSql.z, iSize);
6029 }
drh1554bc82017-03-08 16:10:34 +00006030 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006031 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006032 if( bDebug ){
6033 utf8_printf(p->out, "%s\n", zSql);
6034 }else{
6035 shell_exec(p->db, zSql, shell_callback, p, 0);
6036 }
6037 sqlite3_free(zSql);
6038 }else
6039
drh62cdde52014-05-28 20:22:28 +00006040 if( c=='s'
6041 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006042 ){
6043 char *zCmd;
drh54027102014-08-06 14:36:53 +00006044 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006045 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006046 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006047 rc = 1;
6048 goto meta_command_exit;
6049 }
drhdcb3e3d2014-05-29 03:17:29 +00006050 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006051 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006052 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6053 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006054 }
drh54027102014-08-06 14:36:53 +00006055 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006056 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006057 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006058 }else
6059
drhc2ce0be2014-05-29 12:36:14 +00006060 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006061 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006062 int i;
drhc2ce0be2014-05-29 12:36:14 +00006063 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006064 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006065 rc = 1;
6066 goto meta_command_exit;
6067 }
drhe6e1d122017-03-09 13:50:49 +00006068 utf8_printf(p->out, "%12.12s: %s\n","echo",
6069 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006070 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006071 utf8_printf(p->out, "%12.12s: %s\n","explain",
6072 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006073 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006074 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6075 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006076 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006077 raw_printf(p->out, "\n");
6078 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006079 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006080 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006081 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006082 raw_printf(p->out, "\n");
6083 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006084 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006085 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006086 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006087 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006088 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006089 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006090 }
mistachkinaae280e2015-12-31 19:06:24 +00006091 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006092 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6093 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006094 }else
6095
drhc2ce0be2014-05-29 12:36:14 +00006096 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6097 if( nArg==2 ){
6098 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006099 }else if( nArg==1 ){
6100 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006101 }else{
drh34784902016-02-27 17:12:36 +00006102 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006103 rc = 1;
6104 }
shaneh642d8b82010-07-28 16:05:34 +00006105 }else
6106
drh6a5a4202016-12-24 21:32:40 +00006107 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6108 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6109 || strncmp(azArg[0], "indexes", n)==0) )
6110 ){
drh98781232012-04-23 12:38:05 +00006111 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006112 char **azResult;
drh98781232012-04-23 12:38:05 +00006113 int nRow, nAlloc;
6114 char *zSql = 0;
6115 int ii;
drh05782482013-10-24 15:20:20 +00006116 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006117 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006118 if( rc ) return shellDatabaseError(p->db);
6119
6120 /* Create an SQL statement to query for the list of tables in the
6121 ** main and all attached databases where the table name matches the
6122 ** LIKE pattern bound to variable "?1". */
drh6a5a4202016-12-24 21:32:40 +00006123 if( c=='t' ){
6124 zSql = sqlite3_mprintf(
6125 "SELECT name FROM sqlite_master"
6126 " WHERE type IN ('table','view')"
6127 " AND name NOT LIKE 'sqlite_%%'"
6128 " AND name LIKE ?1");
6129 }else if( nArg>2 ){
6130 /* It is an historical accident that the .indexes command shows an error
6131 ** when called with the wrong number of arguments whereas the .tables
6132 ** command does not. */
6133 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6134 rc = 1;
6135 goto meta_command_exit;
6136 }else{
6137 zSql = sqlite3_mprintf(
6138 "SELECT name FROM sqlite_master"
6139 " WHERE type='index'"
6140 " AND tbl_name LIKE ?1");
6141 }
drha4b81d22016-12-24 18:04:28 +00006142 for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006143 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drha4b81d22016-12-24 18:04:28 +00006144 if( zDbName==0 || ii==0 ) continue;
drh6a5a4202016-12-24 21:32:40 +00006145 if( c=='t' ){
drh98781232012-04-23 12:38:05 +00006146 zSql = sqlite3_mprintf(
6147 "%z UNION ALL "
6148 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6149 " WHERE type IN ('table','view')"
6150 " AND name NOT LIKE 'sqlite_%%'"
6151 " AND name LIKE ?1", zSql, zDbName, zDbName);
drh6a5a4202016-12-24 21:32:40 +00006152 }else{
6153 zSql = sqlite3_mprintf(
6154 "%z UNION ALL "
6155 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6156 " WHERE type='index'"
6157 " AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
drh98781232012-04-23 12:38:05 +00006158 }
drha50da102000-08-08 20:19:09 +00006159 }
dand95bb392015-09-30 11:19:05 +00006160 rc = sqlite3_finalize(pStmt);
6161 if( zSql && rc==SQLITE_OK ){
6162 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6163 if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6164 }
drh98781232012-04-23 12:38:05 +00006165 sqlite3_free(zSql);
dand95bb392015-09-30 11:19:05 +00006166 if( !zSql ) return shellNomemError();
6167 if( rc ) return shellDatabaseError(p->db);
6168
6169 /* Run the SQL statement prepared by the above block. Store the results
6170 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006171 nRow = nAlloc = 0;
6172 azResult = 0;
6173 if( nArg>1 ){
6174 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006175 }else{
drh98781232012-04-23 12:38:05 +00006176 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6177 }
6178 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6179 if( nRow>=nAlloc ){
6180 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006181 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006182 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006183 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006184 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006185 break;
6186 }
mistachkin8e189222015-04-19 21:43:16 +00006187 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006188 azResult = azNew;
6189 }
6190 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006191 if( 0==azResult[nRow] ){
6192 rc = shellNomemError();
6193 break;
6194 }
6195 nRow++;
drh98781232012-04-23 12:38:05 +00006196 }
dand95bb392015-09-30 11:19:05 +00006197 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6198 rc = shellDatabaseError(p->db);
6199 }
6200
6201 /* Pretty-print the contents of array azResult[] to the output */
6202 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006203 int len, maxlen = 0;
6204 int i, j;
6205 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006206 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006207 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006208 if( len>maxlen ) maxlen = len;
6209 }
6210 nPrintCol = 80/(maxlen+2);
6211 if( nPrintCol<1 ) nPrintCol = 1;
6212 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6213 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006214 for(j=i; j<nRow; j+=nPrintRow){
6215 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006216 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6217 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006218 }
mistachkinaae280e2015-12-31 19:06:24 +00006219 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006220 }
6221 }
dand95bb392015-09-30 11:19:05 +00006222
drh98781232012-04-23 12:38:05 +00006223 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6224 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006225 }else
6226
drh2db82112016-09-15 21:35:24 +00006227 /* Begin redirecting output to the file "testcase-out.txt" */
6228 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6229 output_reset(p);
6230 p->out = output_file_open("testcase-out.txt");
6231 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006232 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006233 }
drh760c8162016-09-16 02:52:22 +00006234 if( nArg>=2 ){
6235 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6236 }else{
6237 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6238 }
drh2db82112016-09-15 21:35:24 +00006239 }else
drh2db82112016-09-15 21:35:24 +00006240
drhd12602a2016-12-07 15:49:02 +00006241#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006242 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006243 static const struct {
6244 const char *zCtrlName; /* Name of a test-control option */
6245 int ctrlCode; /* Integer code for that option */
6246 } aCtrl[] = {
6247 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6248 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6249 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6250 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6251 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6252 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6253 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6254 { "assert", SQLITE_TESTCTRL_ASSERT },
6255 { "always", SQLITE_TESTCTRL_ALWAYS },
6256 { "reserve", SQLITE_TESTCTRL_RESERVE },
6257 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6258 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006259 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006260 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006261 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006262 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006263 };
shaneh96887e12011-02-10 21:08:58 +00006264 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006265 int rc2 = 0;
6266 int i, n2;
drh05782482013-10-24 15:20:20 +00006267 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006268
drhd416fe72011-03-17 16:45:50 +00006269 /* convert testctrl text option to value. allow any unique prefix
6270 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006271 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006272 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006273 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006274 if( testctrl<0 ){
6275 testctrl = aCtrl[i].ctrlCode;
6276 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006277 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006278 testctrl = -1;
6279 break;
6280 }
6281 }
6282 }
drh348d19c2013-06-03 12:47:43 +00006283 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006284 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006285 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006286 }else{
6287 switch(testctrl){
6288
6289 /* sqlite3_test_control(int, db, int) */
6290 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006291 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006292 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006293 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006294 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006295 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006296 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006297 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006298 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006299 }
6300 break;
6301
6302 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006303 case SQLITE_TESTCTRL_PRNG_SAVE:
6304 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006305 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006306 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006307 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006308 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006309 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006310 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006311 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6312 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006313 }
6314 break;
6315
6316 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006317 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006318 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006319 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006320 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006321 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006322 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006323 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006324 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006325 }
6326 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006327
shaneh96887e12011-02-10 21:08:58 +00006328 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006329 case SQLITE_TESTCTRL_ASSERT:
6330 case SQLITE_TESTCTRL_ALWAYS:
6331 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006332 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006333 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006334 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006335 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006336 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006337 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006338 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006339 }
6340 break;
6341
6342 /* sqlite3_test_control(int, char *) */
6343#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006344 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006345 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006346 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006347 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006348 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006349 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006350 utf8_printf(stderr,
6351 "Error: testctrl %s takes a single char * option\n",
6352 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006353 }
6354 break;
6355#endif
6356
drh1ffede82015-01-30 20:59:27 +00006357 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006358 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006359 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006360 azArg[2],
drh8964b342015-01-29 17:54:52 +00006361 integerValue(azArg[3]),
6362 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006363 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006364 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006365 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006366 }
6367 break;
6368
mistachkin1fe36bb2016-04-04 02:16:44 +00006369 case SQLITE_TESTCTRL_BITVEC_TEST:
6370 case SQLITE_TESTCTRL_FAULT_INSTALL:
6371 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6372 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006373 default:
mistachkinaae280e2015-12-31 19:06:24 +00006374 utf8_printf(stderr,
6375 "Error: CLI support for testctrl %s not implemented\n",
6376 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006377 break;
6378 }
6379 }
6380 }else
drhf1969722017-02-17 23:52:00 +00006381#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006382
drhc2ce0be2014-05-29 12:36:14 +00006383 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006384 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006385 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006386 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006387
drhc2ce0be2014-05-29 12:36:14 +00006388 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6389 if( nArg==2 ){
6390 enableTimer = booleanValue(azArg[1]);
6391 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006392 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006393 enableTimer = 0;
6394 }
6395 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006396 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006397 rc = 1;
6398 }
shanehe2aa9d72009-11-06 17:20:17 +00006399 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006400
drhc2ce0be2014-05-29 12:36:14 +00006401 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006402 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006403 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006404 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006405 rc = 1;
6406 goto meta_command_exit;
6407 }
drh657b4a82015-03-19 13:30:41 +00006408 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006409 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006410#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006411 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006412 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006413 }else{
drh4b363a52016-07-23 20:27:41 +00006414 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006415 }
6416#endif
6417 }else
6418
drhf442e332014-09-10 19:01:14 +00006419#if SQLITE_USER_AUTHENTICATION
6420 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6421 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006422 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006423 rc = 1;
6424 goto meta_command_exit;
6425 }
drh7883ecf2014-09-11 16:19:31 +00006426 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006427 if( strcmp(azArg[1],"login")==0 ){
6428 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006429 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006430 rc = 1;
6431 goto meta_command_exit;
6432 }
drhd39c40f2014-09-11 00:27:53 +00006433 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6434 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006435 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006436 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006437 rc = 1;
6438 }
6439 }else if( strcmp(azArg[1],"add")==0 ){
6440 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006441 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006442 rc = 1;
6443 goto meta_command_exit;
6444 }
drhd39c40f2014-09-11 00:27:53 +00006445 rc = sqlite3_user_add(p->db, azArg[2],
6446 azArg[3], (int)strlen(azArg[3]),
6447 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006448 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006449 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006450 rc = 1;
6451 }
6452 }else if( strcmp(azArg[1],"edit")==0 ){
6453 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006454 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006455 rc = 1;
6456 goto meta_command_exit;
6457 }
drhd39c40f2014-09-11 00:27:53 +00006458 rc = sqlite3_user_change(p->db, azArg[2],
6459 azArg[3], (int)strlen(azArg[3]),
6460 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006461 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006462 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006463 rc = 1;
6464 }
6465 }else if( strcmp(azArg[1],"delete")==0 ){
6466 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006467 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006468 rc = 1;
6469 goto meta_command_exit;
6470 }
6471 rc = sqlite3_user_delete(p->db, azArg[2]);
6472 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006473 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006474 rc = 1;
6475 }
6476 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006477 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006478 rc = 1;
6479 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006480 }
drhf442e332014-09-10 19:01:14 +00006481 }else
6482#endif /* SQLITE_USER_AUTHENTICATION */
6483
drh9fd301b2011-06-03 13:28:22 +00006484 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006485 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006486 sqlite3_libversion(), sqlite3_sourceid());
6487 }else
6488
drh790f2872015-11-28 18:06:36 +00006489 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6490 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006491 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006492 if( p->db ){
6493 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6494 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006495 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6496 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6497 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6498 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006499 }
6500 }
6501 }else
6502
drhb19e7352016-01-12 19:37:20 +00006503 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6504 sqlite3_vfs *pVfs;
6505 sqlite3_vfs *pCurrent = 0;
6506 if( p->db ){
6507 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6508 }
6509 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6510 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6511 pVfs==pCurrent ? " <--- CURRENT" : "");
6512 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6513 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6514 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6515 if( pVfs->pNext ){
6516 raw_printf(p->out, "-----------------------------------\n");
6517 }
6518 }
6519 }else
6520
drhde60fc22011-12-14 17:53:36 +00006521 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6522 const char *zDbName = nArg==2 ? azArg[1] : "main";
6523 char *zVfsName = 0;
6524 if( p->db ){
6525 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6526 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006527 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006528 sqlite3_free(zVfsName);
6529 }
6530 }
6531 }else
6532
drhcef4fc82012-09-21 22:50:45 +00006533#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6534 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006535 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006536 }else
6537#endif
6538
drhc2ce0be2014-05-29 12:36:14 +00006539 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006540 int j;
drh43617e92006-03-06 20:55:46 +00006541 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006542 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006543 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006544 }
6545 }else
6546
6547 {
mistachkinaae280e2015-12-31 19:06:24 +00006548 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006549 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006550 rc = 1;
drh75897232000-05-29 14:26:00 +00006551 }
drh67505e72002-04-19 12:34:06 +00006552
drhc2ce0be2014-05-29 12:36:14 +00006553meta_command_exit:
6554 if( p->outCount ){
6555 p->outCount--;
6556 if( p->outCount==0 ) output_reset(p);
6557 }
drh67505e72002-04-19 12:34:06 +00006558 return rc;
drh75897232000-05-29 14:26:00 +00006559}
6560
drh67505e72002-04-19 12:34:06 +00006561/*
drh91a66392007-09-07 01:12:32 +00006562** Return TRUE if a semicolon occurs anywhere in the first N characters
6563** of string z[].
drh324ccef2003-02-05 14:06:20 +00006564*/
drh9f099fd2013-08-06 14:01:46 +00006565static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006566 int i;
6567 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6568 return 0;
drh324ccef2003-02-05 14:06:20 +00006569}
6570
6571/*
drh70c7a4b2003-04-26 03:03:06 +00006572** Test to see if a line consists entirely of whitespace.
6573*/
6574static int _all_whitespace(const char *z){
6575 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006576 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006577 if( *z=='/' && z[1]=='*' ){
6578 z += 2;
6579 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6580 if( *z==0 ) return 0;
6581 z++;
6582 continue;
6583 }
6584 if( *z=='-' && z[1]=='-' ){
6585 z += 2;
6586 while( *z && *z!='\n' ){ z++; }
6587 if( *z==0 ) return 1;
6588 continue;
6589 }
6590 return 0;
6591 }
6592 return 1;
6593}
6594
6595/*
drha9b17162003-04-29 18:01:28 +00006596** Return TRUE if the line typed in is an SQL command terminator other
6597** than a semi-colon. The SQL Server style "go" command is understood
6598** as is the Oracle "/".
6599*/
drh9f099fd2013-08-06 14:01:46 +00006600static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006601 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006602 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6603 return 1; /* Oracle */
6604 }
drhf0693c82011-10-11 20:41:54 +00006605 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006606 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006607 return 1; /* SQL Server */
6608 }
6609 return 0;
6610}
6611
6612/*
drh233a5312008-12-18 22:25:13 +00006613** Return true if zSql is a complete SQL statement. Return false if it
6614** ends in the middle of a string literal or C-style comment.
6615*/
drh9f099fd2013-08-06 14:01:46 +00006616static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006617 int rc;
6618 if( zSql==0 ) return 1;
6619 zSql[nSql] = ';';
6620 zSql[nSql+1] = 0;
6621 rc = sqlite3_complete(zSql);
6622 zSql[nSql] = 0;
6623 return rc;
6624}
6625
6626/*
drh4e8142c2016-11-11 14:54:22 +00006627** Run a single line of SQL
6628*/
6629static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6630 int rc;
6631 char *zErrMsg = 0;
6632
6633 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006634 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006635 BEGIN_TIMER;
6636 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6637 END_TIMER;
6638 if( rc || zErrMsg ){
6639 char zPrefix[100];
6640 if( in!=0 || !stdin_is_interactive ){
6641 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6642 "Error: near line %d:", startline);
6643 }else{
6644 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6645 }
6646 if( zErrMsg!=0 ){
6647 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6648 sqlite3_free(zErrMsg);
6649 zErrMsg = 0;
6650 }else{
6651 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6652 }
6653 return 1;
drhe6e1d122017-03-09 13:50:49 +00006654 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006655 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6656 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6657 }
6658 return 0;
6659}
6660
6661
6662/*
drh67505e72002-04-19 12:34:06 +00006663** Read input from *in and process it. If *in==0 then input
6664** is interactive - the user is typing it it. Otherwise, input
6665** is coming from a file or device. A prompt is issued and history
6666** is saved only if input is interactive. An interrupt signal will
6667** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006668**
6669** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006670*/
drhdcd87a92014-08-18 13:45:42 +00006671static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006672 char *zLine = 0; /* A single input line */
6673 char *zSql = 0; /* Accumulated SQL text */
6674 int nLine; /* Length of current line */
6675 int nSql = 0; /* Bytes of zSql[] used */
6676 int nAlloc = 0; /* Allocated zSql[] space */
6677 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006678 int rc; /* Error code */
6679 int errCnt = 0; /* Number of errors seen */
6680 int lineno = 0; /* Current line number */
6681 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006682
6683 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6684 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006685 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006686 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006687 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006688 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006689 break;
drhc49f44e2006-10-26 18:15:42 +00006690 }
drh67505e72002-04-19 12:34:06 +00006691 if( seenInterrupt ){
6692 if( in!=0 ) break;
6693 seenInterrupt = 0;
6694 }
drhc28490c2006-10-26 14:25:58 +00006695 lineno++;
drh849a9d92013-12-21 15:46:06 +00006696 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006697 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006698 continue;
6699 }
drh2af0b2d2002-02-21 02:25:02 +00006700 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006701 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006702 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006703 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006704 break;
6705 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006706 errCnt++;
6707 }
drhdaffd0e2001-04-11 14:28:42 +00006708 continue;
6709 }
drh9f099fd2013-08-06 14:01:46 +00006710 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00006711 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00006712 }
drh9f099fd2013-08-06 14:01:46 +00006713 nLine = strlen30(zLine);
6714 if( nSql+nLine+2>=nAlloc ){
6715 nAlloc = nSql+nLine+100;
6716 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00006717 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006718 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00006719 exit(1);
6720 }
drhdaffd0e2001-04-11 14:28:42 +00006721 }
drh9f099fd2013-08-06 14:01:46 +00006722 nSqlPrior = nSql;
6723 if( nSql==0 ){
6724 int i;
6725 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00006726 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00006727 memcpy(zSql, zLine+i, nLine+1-i);
6728 startline = lineno;
6729 nSql = nLine-i;
6730 }else{
6731 zSql[nSql++] = '\n';
6732 memcpy(zSql+nSql, zLine, nLine+1);
6733 nSql += nLine;
6734 }
6735 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00006736 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00006737 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006738 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00006739 if( p->outCount ){
6740 output_reset(p);
6741 p->outCount = 0;
6742 }
drh9f099fd2013-08-06 14:01:46 +00006743 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00006744 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00006745 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00006746 }
6747 }
drh4e8142c2016-11-11 14:54:22 +00006748 if( nSql && !_all_whitespace(zSql) ){
6749 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006750 }
drh1f9ca2c2015-08-25 16:57:52 +00006751 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00006752 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00006753 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00006754}
6755
drh67505e72002-04-19 12:34:06 +00006756/*
6757** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00006758** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00006759*/
drhd1459152016-09-16 19:11:03 +00006760static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00006761 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00006762 if( clearFlag ){
6763 free(home_dir);
6764 home_dir = 0;
6765 return 0;
6766 }
drh85e72432012-04-11 11:38:53 +00006767 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00006768
drh4ace5362014-11-10 14:42:28 +00006769#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6770 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00006771 {
6772 struct passwd *pwent;
6773 uid_t uid = getuid();
6774 if( (pwent=getpwuid(uid)) != NULL) {
6775 home_dir = pwent->pw_dir;
6776 }
drh67505e72002-04-19 12:34:06 +00006777 }
6778#endif
6779
chw65d3c132007-11-12 21:09:10 +00006780#if defined(_WIN32_WCE)
6781 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6782 */
drh85e72432012-04-11 11:38:53 +00006783 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00006784#else
6785
drh83905c92012-06-21 13:00:37 +00006786#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00006787 if (!home_dir) {
6788 home_dir = getenv("USERPROFILE");
6789 }
6790#endif
6791
drh67505e72002-04-19 12:34:06 +00006792 if (!home_dir) {
6793 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00006794 }
6795
drh83905c92012-06-21 13:00:37 +00006796#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00006797 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00006798 char *zDrive, *zPath;
6799 int n;
6800 zDrive = getenv("HOMEDRIVE");
6801 zPath = getenv("HOMEPATH");
6802 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00006803 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00006804 home_dir = malloc( n );
6805 if( home_dir==0 ) return 0;
6806 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6807 return home_dir;
6808 }
6809 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00006810 }
6811#endif
6812
chw65d3c132007-11-12 21:09:10 +00006813#endif /* !_WIN32_WCE */
6814
drh67505e72002-04-19 12:34:06 +00006815 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00006816 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00006817 char *z = malloc( n );
6818 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00006819 home_dir = z;
6820 }
drhe98d4fa2002-04-21 19:06:22 +00006821
drh67505e72002-04-19 12:34:06 +00006822 return home_dir;
6823}
6824
6825/*
6826** Read input from the file given by sqliterc_override. Or if that
6827** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00006828**
6829** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00006830*/
drh534f4df2015-02-28 14:03:35 +00006831static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00006832 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00006833 const char *sqliterc_override /* Name of config file. NULL to use default */
6834){
persicom7e2dfdd2002-04-18 02:46:52 +00006835 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00006836 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00006837 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00006838 FILE *in = NULL;
6839
6840 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00006841 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00006842 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006843 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00006844 " cannot read ~/.sqliterc\n");
6845 return;
drhe98d4fa2002-04-21 19:06:22 +00006846 }
drh2f3de322012-06-27 16:41:31 +00006847 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00006848 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6849 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00006850 }
drha1f9b5e2004-02-14 16:31:02 +00006851 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00006852 if( in ){
drhc28490c2006-10-26 14:25:58 +00006853 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00006854 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00006855 }
drh534f4df2015-02-28 14:03:35 +00006856 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00006857 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00006858 }
drh85e72432012-04-11 11:38:53 +00006859 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00006860}
6861
drh67505e72002-04-19 12:34:06 +00006862/*
drhe1e38c42003-05-04 18:30:59 +00006863** Show available command line options
6864*/
mistachkin1fe36bb2016-04-04 02:16:44 +00006865static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00006866 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00006867 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00006868 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00006869 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00006870 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00006871 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00006872 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00006873 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00006874 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00006875#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6876 " -heap SIZE Size of heap for memsys3 or memsys5\n"
6877#endif
drhcc3b4f82012-02-07 14:13:50 +00006878 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00006879 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00006880 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00006881 " -line set output mode to 'line'\n"
6882 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00006883 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00006884 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00006885#ifdef SQLITE_ENABLE_MULTIPLEX
6886 " -multiplex enable the multiplexor VFS\n"
6887#endif
mistachkine0d68852014-12-11 03:12:33 +00006888 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00006889 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00006890 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
6891 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00006892 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00006893 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00006894 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00006895 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00006896#ifdef SQLITE_ENABLE_VFSTRACE
6897 " -vfstrace enable tracing of all VFS calls\n"
6898#endif
drhe1e38c42003-05-04 18:30:59 +00006899;
6900static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00006901 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00006902 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00006903 "FILENAME is the name of an SQLite database. A new database is created\n"
6904 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00006905 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00006906 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00006907 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006908 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00006909 }
6910 exit(1);
6911}
6912
6913/*
drh67505e72002-04-19 12:34:06 +00006914** Initialize the state information in data
6915*/
drhdcd87a92014-08-18 13:45:42 +00006916static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00006917 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00006918 data->normalMode = data->cMode = data->mode = MODE_List;
6919 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00006920 memcpy(data->colSeparator,SEP_Column, 2);
6921 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00006922 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00006923 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00006924 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00006925 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00006926 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00006927 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6928 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00006929}
6930
drh98d312f2012-10-25 15:23:14 +00006931/*
drh5c7976f2014-02-10 19:59:27 +00006932** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00006933*/
6934#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00006935static void printBold(const char *zText){
6936 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
6937 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
6938 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
6939 SetConsoleTextAttribute(out,
6940 FOREGROUND_RED|FOREGROUND_INTENSITY
6941 );
6942 printf("%s", zText);
6943 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00006944}
6945#else
drh5c7976f2014-02-10 19:59:27 +00006946static void printBold(const char *zText){
6947 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00006948}
6949#endif
6950
6951/*
drh98d312f2012-10-25 15:23:14 +00006952** Get the argument to an --option. Throw an error and die if no argument
6953** is available.
6954*/
6955static char *cmdline_option_value(int argc, char **argv, int i){
6956 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00006957 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00006958 argv[0], argv[argc-1]);
6959 exit(1);
6960 }
6961 return argv[i];
6962}
6963
mistachkin1fe36bb2016-04-04 02:16:44 +00006964#ifndef SQLITE_SHELL_IS_UTF8
6965# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
6966# define SQLITE_SHELL_IS_UTF8 (0)
6967# else
6968# define SQLITE_SHELL_IS_UTF8 (1)
6969# endif
6970#endif
6971
6972#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00006973int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00006974#else
6975int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00006976 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00006977#endif
drh75897232000-05-29 14:26:00 +00006978 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00006979 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00006980 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00006981 int i;
drhc28490c2006-10-26 14:25:58 +00006982 int rc = 0;
drhb3735912014-02-10 16:13:42 +00006983 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00006984 int readStdin = 1;
6985 int nCmd = 0;
6986 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00006987
mistachkin1fe36bb2016-04-04 02:16:44 +00006988 setBinaryMode(stdin, 0);
6989 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00006990 stdin_is_interactive = isatty(0);
6991 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00006992
drh69b30ab2014-02-27 15:11:52 +00006993#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00006994 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006995 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00006996 sqlite3_sourceid(), SQLITE_SOURCE_ID);
6997 exit(1);
6998 }
drhc7181902014-02-27 15:04:13 +00006999#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007000 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007001#if !SQLITE_SHELL_IS_UTF8
7002 sqlite3_initialize();
7003 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7004 if( argv==0 ){
7005 raw_printf(stderr, "out of memory\n");
7006 exit(1);
7007 }
7008 for(i=0; i<argc; i++){
7009 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7010 if( argv[i]==0 ){
7011 raw_printf(stderr, "out of memory\n");
7012 exit(1);
7013 }
7014 }
7015#endif
mistachkin1810f222016-04-04 02:33:34 +00007016 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007017 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007018
drh44c2eb12003-04-30 11:38:26 +00007019 /* Make sure we have a valid signal handler early, before anything
7020 ** else is done.
7021 */
drh4c504392000-10-16 22:06:40 +00007022#ifdef SIGINT
7023 signal(SIGINT, interrupt_handler);
7024#endif
drh44c2eb12003-04-30 11:38:26 +00007025
drhac5649a2014-11-28 13:35:03 +00007026#ifdef SQLITE_SHELL_DBNAME_PROC
7027 {
7028 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7029 ** of a C-function that will provide the name of the database file. Use
7030 ** this compile-time option to embed this shell program in larger
7031 ** applications. */
7032 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7033 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7034 warnInmemoryDb = 0;
7035 }
7036#endif
7037
drh22fbcb82004-02-01 01:22:50 +00007038 /* Do an initial pass through the command-line argument to locate
7039 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007040 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007041 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007042 */
drh98d312f2012-10-25 15:23:14 +00007043 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007044 char *z;
drhc28490c2006-10-26 14:25:58 +00007045 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007046 if( z[0]!='-' ){
7047 if( data.zDbFilename==0 ){
7048 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007049 }else{
7050 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7051 ** mean that nothing is read from stdin */
7052 readStdin = 0;
7053 nCmd++;
7054 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7055 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007056 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007057 exit(1);
7058 }
7059 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007060 }
drh98d312f2012-10-25 15:23:14 +00007061 }
drhcc3b4f82012-02-07 14:13:50 +00007062 if( z[1]=='-' ) z++;
7063 if( strcmp(z,"-separator")==0
7064 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007065 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007066 || strcmp(z,"-cmd")==0
7067 ){
drh98d312f2012-10-25 15:23:14 +00007068 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007069 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007070 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007071 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007072 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007073 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007074 ** we do the actual processing of arguments later in a second pass.
7075 */
shanef69573d2009-10-24 02:06:14 +00007076 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007077 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007078#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007079 const char *zSize;
7080 sqlite3_int64 szHeap;
7081
drh98d312f2012-10-25 15:23:14 +00007082 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007083 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007084 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007085 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007086#else
7087 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007088#endif
drh44dec872014-08-30 15:49:25 +00007089 }else if( strcmp(z,"-scratch")==0 ){
7090 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007091 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007092 if( sz>400000 ) sz = 400000;
7093 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007094 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007095 if( n>10 ) n = 10;
7096 if( n<1 ) n = 1;
7097 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7098 data.shellFlgs |= SHFLG_Scratch;
7099 }else if( strcmp(z,"-pagecache")==0 ){
7100 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007101 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007102 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007103 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007104 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007105 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7106 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007107 data.shellFlgs |= SHFLG_Pagecache;
7108 }else if( strcmp(z,"-lookaside")==0 ){
7109 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007110 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007111 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007112 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007113 if( n<0 ) n = 0;
7114 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7115 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007116#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007117 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007118 extern int vfstrace_register(
7119 const char *zTraceName,
7120 const char *zOldVfsName,
7121 int (*xOut)(const char*,void*),
7122 void *pOutArg,
7123 int makeDefault
7124 );
drh2b625e22011-03-16 17:05:28 +00007125 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007126#endif
drh6f25e892011-07-08 17:02:57 +00007127#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007128 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007129 extern int sqlite3_multiple_initialize(const char*,int);
7130 sqlite3_multiplex_initialize(0, 1);
7131#endif
drh7d9f3942013-04-03 01:26:54 +00007132 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007133 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7134 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007135 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007136 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007137 if( pVfs ){
7138 sqlite3_vfs_register(pVfs, 1);
7139 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007140 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007141 exit(1);
7142 }
drh44c2eb12003-04-30 11:38:26 +00007143 }
7144 }
drh98d312f2012-10-25 15:23:14 +00007145 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007146#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007147 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007148 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007149#else
mistachkinaae280e2015-12-31 19:06:24 +00007150 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007151 return 1;
drh01b41712005-08-29 23:06:23 +00007152#endif
drh98d312f2012-10-25 15:23:14 +00007153 }
7154 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007155
drh44c2eb12003-04-30 11:38:26 +00007156 /* Go ahead and open the database file if it already exists. If the
7157 ** file does not exist, delay opening it. This prevents empty database
7158 ** files from being created if a user mistypes the database name argument
7159 ** to the sqlite command-line tool.
7160 */
drhc8d74412004-08-31 23:41:26 +00007161 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007162 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007163 }
7164
drh22fbcb82004-02-01 01:22:50 +00007165 /* Process the initialization file if there is one. If no -init option
7166 ** is given on the command line, look for a file named ~/.sqliterc and
7167 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007168 */
drh534f4df2015-02-28 14:03:35 +00007169 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007170
drh22fbcb82004-02-01 01:22:50 +00007171 /* Make a second pass through the command-line argument and set
7172 ** options. This second pass is delayed until after the initialization
7173 ** file is processed so that the command-line arguments will override
7174 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007175 */
drh98d312f2012-10-25 15:23:14 +00007176 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007177 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007178 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007179 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007180 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007181 i++;
7182 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007183 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007184 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007185 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007186 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007187 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007188 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007189 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007190 }else if( strcmp(z,"-csv")==0 ){
7191 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007192 memcpy(data.colSeparator,",",2);
7193 }else if( strcmp(z,"-ascii")==0 ){
7194 data.mode = MODE_Ascii;
7195 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007196 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007197 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007198 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007199 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007200 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007201 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007202 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007203 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007204 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007205 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007206 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007207 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007208 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007209 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007210 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007211 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007212 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007213 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007214 }else if( strcmp(z,"-eqp")==0 ){
7215 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007216 }else if( strcmp(z,"-eqpfull")==0 ){
7217 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007218 }else if( strcmp(z,"-stats")==0 ){
7219 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007220 }else if( strcmp(z,"-scanstats")==0 ){
7221 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007222 }else if( strcmp(z,"-backslash")==0 ){
7223 /* Undocumented command-line option: -backslash
7224 ** Causes C-style backslash escapes to be evaluated in SQL statements
7225 ** prior to sending the SQL into SQLite. Useful for injecting
7226 ** crazy bytes in the middle of SQL statements for testing and debugging.
7227 */
drhe6e1d122017-03-09 13:50:49 +00007228 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007229 }else if( strcmp(z,"-bail")==0 ){
7230 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007231 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007232 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007233 return 0;
drhc28490c2006-10-26 14:25:58 +00007234 }else if( strcmp(z,"-interactive")==0 ){
7235 stdin_is_interactive = 1;
7236 }else if( strcmp(z,"-batch")==0 ){
7237 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007238 }else if( strcmp(z,"-heap")==0 ){
7239 i++;
drh44dec872014-08-30 15:49:25 +00007240 }else if( strcmp(z,"-scratch")==0 ){
7241 i+=2;
7242 }else if( strcmp(z,"-pagecache")==0 ){
7243 i+=2;
7244 }else if( strcmp(z,"-lookaside")==0 ){
7245 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007246 }else if( strcmp(z,"-mmap")==0 ){
7247 i++;
drha7e61d82011-03-12 17:02:57 +00007248 }else if( strcmp(z,"-vfs")==0 ){
7249 i++;
drh6f25e892011-07-08 17:02:57 +00007250#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007251 }else if( strcmp(z,"-vfstrace")==0 ){
7252 i++;
drh6f25e892011-07-08 17:02:57 +00007253#endif
7254#ifdef SQLITE_ENABLE_MULTIPLEX
7255 }else if( strcmp(z,"-multiplex")==0 ){
7256 i++;
7257#endif
drhcc3b4f82012-02-07 14:13:50 +00007258 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007259 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007260 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007261 /* Run commands that follow -cmd first and separately from commands
7262 ** that simply appear on the command-line. This seems goofy. It would
7263 ** be better if all commands ran in the order that they appear. But
7264 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007265 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007266 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007267 if( z[0]=='.' ){
7268 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007269 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007270 }else{
drh05782482013-10-24 15:20:20 +00007271 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007272 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7273 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007274 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007275 if( bail_on_error ) return rc!=0 ? rc : 1;
7276 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007277 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007278 if( bail_on_error ) return rc;
7279 }
7280 }
drh1e5d0e92000-05-31 23:33:17 +00007281 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007282 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7283 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007284 return 1;
7285 }
drh700c2522016-02-09 18:39:25 +00007286 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007287 }
drh44c2eb12003-04-30 11:38:26 +00007288
drhac5649a2014-11-28 13:35:03 +00007289 if( !readStdin ){
7290 /* Run all arguments that do not begin with '-' as if they were separate
7291 ** command-line inputs, except for the argToSkip argument which contains
7292 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007293 */
drhac5649a2014-11-28 13:35:03 +00007294 for(i=0; i<nCmd; i++){
7295 if( azCmd[i][0]=='.' ){
7296 rc = do_meta_command(azCmd[i], &data);
7297 if( rc ) return rc==2 ? 0 : rc;
7298 }else{
7299 open_db(&data, 0);
7300 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7301 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007302 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007303 return rc!=0 ? rc : 1;
7304 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007305 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007306 return rc;
7307 }
drh6ff13852001-11-25 13:18:23 +00007308 }
drh75897232000-05-29 14:26:00 +00007309 }
drhac5649a2014-11-28 13:35:03 +00007310 free(azCmd);
drh75897232000-05-29 14:26:00 +00007311 }else{
drh44c2eb12003-04-30 11:38:26 +00007312 /* Run commands received from standard input
7313 */
drhc28490c2006-10-26 14:25:58 +00007314 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007315 char *zHome;
7316 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007317 int nHistory;
drh75897232000-05-29 14:26:00 +00007318 printf(
drh743e0032011-12-12 16:51:50 +00007319 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007320 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007321 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007322 );
drhb3735912014-02-10 16:13:42 +00007323 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007324 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007325 printBold("transient in-memory database");
7326 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007327 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007328 }
drhd1459152016-09-16 19:11:03 +00007329 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007330 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007331 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007332 if( (zHistory = malloc(nHistory))!=0 ){
7333 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7334 }
drh67505e72002-04-19 12:34:06 +00007335 }
drhf5ed7ad2015-06-15 14:43:25 +00007336 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007337 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007338 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007339 shell_stifle_history(100);
7340 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007341 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007342 }
drhdaffd0e2001-04-11 14:28:42 +00007343 }else{
drhc28490c2006-10-26 14:25:58 +00007344 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007345 }
7346 }
drh33048c02001-10-01 14:29:22 +00007347 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007348 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007349 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007350 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007351 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007352 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007353 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007354#if !SQLITE_SHELL_IS_UTF8
7355 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7356 sqlite3_free(argv);
7357#endif
drhc28490c2006-10-26 14:25:58 +00007358 return rc;
drh75897232000-05-29 14:26:00 +00007359}