blob: 490c922e60842a58701111af8a9a655e8c16674f [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/*
drhce13b992017-05-23 20:00:00 +000021** Warning pragmas copied from msvc.h in the core.
mistachkin2318d332015-01-12 18:02:52 +000022*/
drhce13b992017-05-23 20:00:00 +000023#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
mistachkin2318d332015-01-12 18:02:52 +000040
41/*
drh8cd5b252015-03-02 22:06:43 +000042** No support for loadable extensions in VxWorks.
43*/
drhada3f2b2015-03-23 21:32:50 +000044#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000045# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
drh36f7dd32011-10-13 16:02:17 +000049** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
drh75897232000-05-29 14:26:00 +000059#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000062#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000063#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000064#if SQLITE_USER_AUTHENTICATION
65# include "sqlite3userauth.h"
66#endif
drh75897232000-05-29 14:26:00 +000067#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000068#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000069
drh83905c92012-06-21 13:00:37 +000070#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000071# include <signal.h>
chw97185482008-11-17 08:05:31 +000072# if !defined(__RTP__) && !defined(_WRS_KERNEL)
73# include <pwd.h>
74# endif
drhdd45df82002-04-18 12:39:03 +000075# include <unistd.h>
76# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000077#endif
drh75897232000-05-29 14:26:00 +000078
drh0ede9eb2015-01-10 16:49:23 +000079#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000080# include <readline/readline.h>
81# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +000082#endif
danfd34d6d2015-02-25 10:54:53 +000083
drh0ede9eb2015-01-10 16:49:23 +000084#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +000085# include <editline/readline.h>
86#endif
danfd34d6d2015-02-25 10:54:53 +000087
88#if HAVE_EDITLINE || HAVE_READLINE
89
90# define shell_add_history(X) add_history(X)
91# define shell_read_history(X) read_history(X)
92# define shell_write_history(X) write_history(X)
93# define shell_stifle_history(X) stifle_history(X)
94# define shell_readline(X) readline(X)
95
96#elif HAVE_LINENOISE
97
98# include "linenoise.h"
99# define shell_add_history(X) linenoiseHistoryAdd(X)
100# define shell_read_history(X) linenoiseHistoryLoad(X)
101# define shell_write_history(X) linenoiseHistorySave(X)
102# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103# define shell_readline(X) linenoise(X)
104
105#else
106
mistachkin1fe36bb2016-04-04 02:16:44 +0000107# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +0000108# define shell_write_history(X)
109# define shell_stifle_history(X)
110
111# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +0000112#endif
113
danfd34d6d2015-02-25 10:54:53 +0000114
adamd2e8464a2006-09-06 21:39:40 +0000115#if defined(_WIN32) || defined(WIN32)
116# include <io.h>
drh6976c212014-07-24 12:09:47 +0000117# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000118# define isatty(h) _isatty(h)
119# ifndef access
120# define access(f,m) _access((f),(m))
121# endif
122# undef popen
123# define popen _popen
124# undef pclose
125# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000126#else
mistachkin073664d2015-06-17 18:57:37 +0000127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000129
mistachkin073664d2015-06-17 18:57:37 +0000130# if !defined(__RTP__) && !defined(_WRS_KERNEL)
131 /* popen and pclose are not C89 functions and so are
132 ** sometimes omitted from the <stdio.h> header */
133 extern FILE *popen(const char*,const char*);
134 extern int pclose(FILE*);
135# else
136# define SQLITE_OMIT_POPEN 1
137# endif
mistachkinf6418892013-08-28 01:54:12 +0000138#endif
drh53371f92013-07-25 17:07:03 +0000139
chw65d3c132007-11-12 21:09:10 +0000140#if defined(_WIN32_WCE)
141/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
144 */
145#define isatty(x) 1
146#endif
147
drhf0693c82011-10-11 20:41:54 +0000148/* ctype macros that work with signed characters */
149#define IsSpace(X) isspace((unsigned char)X)
150#define IsDigit(X) isdigit((unsigned char)X)
151#define ToLower(X) (char)tolower((unsigned char)X)
152
mistachkin1fe36bb2016-04-04 02:16:44 +0000153#if defined(_WIN32) || defined(WIN32)
154#include <windows.h>
155
156/* string conversion routines only needed on Win32 */
157extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
158extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000160extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000161#endif
162
drh047d4532015-01-18 20:30:23 +0000163/* On Windows, we normally run with output mode of TEXT so that \n characters
164** are automatically translated into \r\n. However, this behavior needs
165** to be disabled in some cases (ex: when generating CSV output and when
166** rendering quoted strings that contain \n characters). The following
167** routines take care of that.
168*/
169#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000170static void setBinaryMode(FILE *file, int isOutput){
171 if( isOutput ) fflush(file);
172 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000173}
mistachkin1fe36bb2016-04-04 02:16:44 +0000174static void setTextMode(FILE *file, int isOutput){
175 if( isOutput ) fflush(file);
176 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000177}
178#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000179# define setBinaryMode(X,Y)
180# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000181#endif
182
drh43408312013-10-30 12:43:36 +0000183
184/* True if the timer is enabled */
185static int enableTimer = 0;
186
187/* Return the current wall-clock time */
188static sqlite3_int64 timeOfDay(void){
189 static sqlite3_vfs *clockVfs = 0;
190 sqlite3_int64 t;
191 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000192 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000193 clockVfs->xCurrentTimeInt64(clockVfs, &t);
194 }else{
195 double r;
196 clockVfs->xCurrentTime(clockVfs, &r);
197 t = (sqlite3_int64)(r*86400000.0);
198 }
199 return t;
200}
201
drh91eb93c2015-03-03 19:56:20 +0000202#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000203#include <sys/time.h>
204#include <sys/resource.h>
205
drh91eb93c2015-03-03 19:56:20 +0000206/* VxWorks does not support getrusage() as far as we can determine */
207#if defined(_WRS_KERNEL) || defined(__RTP__)
208struct rusage {
209 struct timeval ru_utime; /* user CPU time used */
210 struct timeval ru_stime; /* system CPU time used */
211};
212#define getrusage(A,B) memset(B,0,sizeof(*B))
213#endif
214
drhda108222009-02-25 19:07:24 +0000215/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000216static struct rusage sBegin; /* CPU time at start */
217static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000218
drhda108222009-02-25 19:07:24 +0000219/*
220** Begin timing an operation
221*/
222static void beginTimer(void){
223 if( enableTimer ){
224 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000225 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000226 }
227}
228
229/* Return the difference of two time_structs in seconds */
230static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000231 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000232 (double)(pEnd->tv_sec - pStart->tv_sec);
233}
234
235/*
236** Print the timing results.
237*/
238static void endTimer(void){
239 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000240 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000241 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000242 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000243 printf("Run Time: real %.3f user %f sys %f\n",
244 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000245 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
246 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
247 }
248}
shaneb320ccd2009-10-21 03:42:58 +0000249
drhda108222009-02-25 19:07:24 +0000250#define BEGIN_TIMER beginTimer()
251#define END_TIMER endTimer()
252#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000253
254#elif (defined(_WIN32) || defined(WIN32))
255
shaneb320ccd2009-10-21 03:42:58 +0000256/* Saved resource information for the beginning of an operation */
257static HANDLE hProcess;
258static FILETIME ftKernelBegin;
259static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000260static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000261typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
262 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000263static GETPROCTIMES getProcessTimesAddr = NULL;
264
shaneb320ccd2009-10-21 03:42:58 +0000265/*
266** Check to see if we have timer support. Return 1 if necessary
267** support found (or found previously).
268*/
269static int hasTimer(void){
270 if( getProcessTimesAddr ){
271 return 1;
272 } else {
drh4ace5362014-11-10 14:42:28 +0000273 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274 ** versions. See if the version we are running on has it, and if it
275 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000276 */
277 hProcess = GetCurrentProcess();
278 if( hProcess ){
279 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
280 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000281 getProcessTimesAddr =
282 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000283 if( NULL != getProcessTimesAddr ){
284 return 1;
285 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000286 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000287 }
288 }
289 }
290 return 0;
291}
292
293/*
294** Begin timing an operation
295*/
296static void beginTimer(void){
297 if( enableTimer && getProcessTimesAddr ){
298 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000299 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
300 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000301 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000302 }
303}
304
305/* Return the difference of two FILETIME structs in seconds */
306static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
307 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
308 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
309 return (double) ((i64End - i64Start) / 10000000.0);
310}
311
312/*
313** Print the timing results.
314*/
315static void endTimer(void){
316 if( enableTimer && getProcessTimesAddr){
317 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000318 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000319 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000320 printf("Run Time: real %.3f user %f sys %f\n",
321 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000322 timeDiff(&ftUserBegin, &ftUserEnd),
323 timeDiff(&ftKernelBegin, &ftKernelEnd));
324 }
325}
326
327#define BEGIN_TIMER beginTimer()
328#define END_TIMER endTimer()
329#define HAS_TIMER hasTimer()
330
drhda108222009-02-25 19:07:24 +0000331#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000332#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000333#define END_TIMER
334#define HAS_TIMER 0
335#endif
336
shanec0688ea2009-03-05 03:48:06 +0000337/*
338** Used to prevent warnings about unused parameters
339*/
340#define UNUSED_PARAMETER(x) (void)(x)
341
drhe91d16b2008-12-08 18:27:31 +0000342/*
drhc49f44e2006-10-26 18:15:42 +0000343** If the following flag is set, then command execution stops
344** at an error if we are not interactive.
345*/
346static int bail_on_error = 0;
347
348/*
drhc28490c2006-10-26 14:25:58 +0000349** Threat stdin as an interactive input if the following variable
350** is true. Otherwise, assume stdin is connected to a file or pipe.
351*/
352static int stdin_is_interactive = 1;
353
354/*
drhe05461c2015-12-30 13:36:57 +0000355** On Windows systems we have to know if standard output is a console
356** in order to translate UTF-8 into MBCS. The following variable is
357** true if translation is required.
358*/
359static int stdout_is_console = 1;
360
361/*
drh4c504392000-10-16 22:06:40 +0000362** The following is the open SQLite database. We make a pointer
363** to this database a static variable so that it can be accessed
364** by the SIGINT handler to interrupt database processing.
365*/
mistachkin8e189222015-04-19 21:43:16 +0000366static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000367
368/*
drh67505e72002-04-19 12:34:06 +0000369** True if an interrupt (Control-C) has been received.
370*/
drh43617e92006-03-06 20:55:46 +0000371static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000372
373/*
persicom7e2dfdd2002-04-18 02:46:52 +0000374** This is the name of our program. It is set in main(), used
375** in a number of other places, mostly for error messages.
376*/
377static char *Argv0;
378
379/*
380** Prompt strings. Initialized in main. Settable with
381** .prompt main continue
382*/
383static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
384static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
385
drhb0603412007-02-28 04:47:26 +0000386/*
mistachkin710b33b2016-01-03 18:59:28 +0000387** Render output like fprintf(). Except, if the output is going to the
388** console and if this is running on a Windows machine, translate the
389** output from UTF-8 into MBCS.
390*/
391#if defined(_WIN32) || defined(WIN32)
392void utf8_printf(FILE *out, const char *zFormat, ...){
393 va_list ap;
394 va_start(ap, zFormat);
395 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000396 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000397 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000398 sqlite3_free(z1);
399 fputs(z2, out);
400 sqlite3_free(z2);
401 }else{
402 vfprintf(out, zFormat, ap);
403 }
404 va_end(ap);
405}
406#elif !defined(utf8_printf)
407# define utf8_printf fprintf
408#endif
409
410/*
411** Render output like fprintf(). This should not be used on anything that
412** includes string formatting (e.g. "%s").
413*/
414#if !defined(raw_printf)
415# define raw_printf fprintf
416#endif
417
418/*
drhb0603412007-02-28 04:47:26 +0000419** Write I/O traces to the following stream.
420*/
rsebe0a9092007-07-30 18:24:38 +0000421#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000422static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000423#endif
drhb0603412007-02-28 04:47:26 +0000424
425/*
426** This routine works like printf in that its first argument is a
427** format string and subsequent arguments are values to be substituted
428** in place of % fields. The result of formatting this string
429** is written to iotrace.
430*/
rsebe0a9092007-07-30 18:24:38 +0000431#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000432static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000433 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000434 char *z;
drhb0603412007-02-28 04:47:26 +0000435 if( iotrace==0 ) return;
436 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000437 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000438 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000439 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000440 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000441}
rsebe0a9092007-07-30 18:24:38 +0000442#endif
drhb0603412007-02-28 04:47:26 +0000443
drh6887e8f2017-04-17 13:18:42 +0000444/*
445** Output string zUtf to stream pOut as w characters. If w is negative,
446** then right-justify the text. W is the width in UTF-8 characters, not
447** in bytes. This is different from the %*.*s specification in printf
448** since with %*.*s the width is measured in bytes, not characters.
449*/
450static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
451 int i;
452 int n;
453 int aw = w<0 ? -w : w;
454 char zBuf[1000];
drhf8a2e8c2017-05-06 17:12:52 +0000455 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
drh6887e8f2017-04-17 13:18:42 +0000456 for(i=n=0; zUtf[i]; i++){
457 if( (zUtf[i]&0xc0)!=0x80 ){
458 n++;
459 if( n==aw ){
460 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
461 break;
462 }
463 }
464 }
465 if( n>=aw ){
466 utf8_printf(pOut, "%.*s", i, zUtf);
467 }else if( w<0 ){
468 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
469 }else{
470 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
471 }
472}
473
drh44c2eb12003-04-30 11:38:26 +0000474
persicom7e2dfdd2002-04-18 02:46:52 +0000475/*
drh83965662003-04-17 02:54:13 +0000476** Determines if a string is a number of not.
477*/
danielk19772e588c72005-12-09 14:25:08 +0000478static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000479 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000480 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000481 return 0;
482 }
483 z++;
484 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000485 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000486 if( *z=='.' ){
487 z++;
drhf0693c82011-10-11 20:41:54 +0000488 if( !IsDigit(*z) ) return 0;
489 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000490 if( realnum ) *realnum = 1;
491 }
492 if( *z=='e' || *z=='E' ){
493 z++;
494 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000495 if( !IsDigit(*z) ) return 0;
496 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000497 if( realnum ) *realnum = 1;
498 }
499 return *z==0;
500}
drh83965662003-04-17 02:54:13 +0000501
502/*
drhe05461c2015-12-30 13:36:57 +0000503** Compute a string length that is limited to what can be stored in
504** lower 30 bits of a 32-bit signed integer.
505*/
506static int strlen30(const char *z){
507 const char *z2 = z;
508 while( *z2 ){ z2++; }
509 return 0x3fffffff & (int)(z2 - z);
510}
511
512/*
drh64bf76d2017-06-05 12:29:26 +0000513** Return the length of a string in characters. Multibyte UTF8 characters
514** count as a single character.
515*/
516static int strlenChar(const char *z){
517 int n = 0;
518 while( *z ){
519 if( (0xc0&*(z++))!=0x80 ) n++;
520 }
521 return n;
522}
523
524/*
drhfeac5f82004-08-01 00:10:45 +0000525** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000526** the text in memory obtained from malloc() and returns a pointer
527** to the text. NULL is returned at end of file, or if malloc()
528** fails.
529**
drh9f099fd2013-08-06 14:01:46 +0000530** If zLine is not NULL then it is a malloced buffer returned from
531** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000532*/
drh9f099fd2013-08-06 14:01:46 +0000533static char *local_getline(char *zLine, FILE *in){
534 int nLine = zLine==0 ? 0 : 100;
535 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000536
drhb07028f2011-10-14 21:49:18 +0000537 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000538 if( n+100>nLine ){
539 nLine = nLine*2 + 100;
540 zLine = realloc(zLine, nLine);
541 if( zLine==0 ) return 0;
542 }
drhdaffd0e2001-04-11 14:28:42 +0000543 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000544 if( n==0 ){
545 free(zLine);
546 return 0;
547 }
548 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000549 break;
550 }
drh9f099fd2013-08-06 14:01:46 +0000551 while( zLine[n] ) n++;
552 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000553 n--;
shaneh13b36022009-12-17 21:07:15 +0000554 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000555 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000556 break;
drh8e7e7a22000-05-30 18:45:23 +0000557 }
558 }
drhe05461c2015-12-30 13:36:57 +0000559#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000560 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000561 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000562 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000563 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000564 if( zTrans ){
565 int nTrans = strlen30(zTrans)+1;
566 if( nTrans>nLine ){
567 zLine = realloc(zLine, nTrans);
568 if( zLine==0 ){
569 sqlite3_free(zTrans);
570 return 0;
571 }
572 }
573 memcpy(zLine, zTrans, nTrans);
574 sqlite3_free(zTrans);
575 }
576 }
577#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000578 return zLine;
579}
580
581/*
drhc28490c2006-10-26 14:25:58 +0000582** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000583**
drh9f099fd2013-08-06 14:01:46 +0000584** If in==0 then read from standard input and prompt before each line.
585** If isContinuation is true, then a continuation prompt is appropriate.
586** If isContinuation is zero, then the main prompt should be used.
587**
588** If zPrior is not NULL then it is a buffer from a prior call to this
589** routine that can be reused.
590**
591** The result is stored in space obtained from malloc() and must either
592** be freed by the caller or else passed back into this routine via the
593** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000594*/
drh9f099fd2013-08-06 14:01:46 +0000595static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000596 char *zPrompt;
597 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000598 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000599 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000600 }else{
drh9f099fd2013-08-06 14:01:46 +0000601 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000602#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000603 printf("%s", zPrompt);
604 fflush(stdout);
605 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000606#else
607 free(zPrior);
608 zResult = shell_readline(zPrompt);
609 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000610#endif
drh9f099fd2013-08-06 14:01:46 +0000611 }
drh8e7e7a22000-05-30 18:45:23 +0000612 return zResult;
613}
drhf42d3182017-03-08 12:25:18 +0000614/*
615** A variable length string to which one can append text.
616*/
617typedef struct ShellText ShellText;
618struct ShellText {
619 char *z;
620 int n;
621 int nAlloc;
622};
623
624/*
625** Initialize and destroy a ShellText object
626*/
627static void initText(ShellText *p){
628 memset(p, 0, sizeof(*p));
629}
630static void freeText(ShellText *p){
631 free(p->z);
632 initText(p);
633}
634
635/* zIn is either a pointer to a NULL-terminated string in memory obtained
636** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637** added to zIn, and the result returned in memory obtained from malloc().
638** zIn, if it was not NULL, is freed.
639**
640** If the third argument, quote, is not '\0', then it is used as a
641** quote character for zAppend.
642*/
643static void appendText(ShellText *p, char const *zAppend, char quote){
644 int len;
645 int i;
646 int nAppend = strlen30(zAppend);
647
648 len = nAppend+p->n+1;
649 if( quote ){
650 len += 2;
651 for(i=0; i<nAppend; i++){
652 if( zAppend[i]==quote ) len++;
653 }
654 }
655
656 if( p->n+len>=p->nAlloc ){
657 p->nAlloc = p->nAlloc*2 + len + 20;
658 p->z = realloc(p->z, p->nAlloc);
659 if( p->z==0 ){
660 memset(p, 0, sizeof(*p));
661 return;
662 }
663 }
664
665 if( quote ){
666 char *zCsr = p->z+p->n;
667 *zCsr++ = quote;
668 for(i=0; i<nAppend; i++){
669 *zCsr++ = zAppend[i];
670 if( zAppend[i]==quote ) *zCsr++ = quote;
671 }
672 *zCsr++ = quote;
673 p->n = (int)(zCsr - p->z);
674 *zCsr = '\0';
675 }else{
676 memcpy(p->z+p->n, zAppend, nAppend);
677 p->n += nAppend;
678 p->z[p->n] = '\0';
679 }
680}
681
682/*
683** Attempt to determine if identifier zName needs to be quoted, either
684** because it contains non-alphanumeric characters, or because it is an
685** SQLite keyword. Be conservative in this estimate: When in doubt assume
686** that quoting is required.
687**
688** Return '"' if quoting is required. Return 0 if no quoting is required.
689*/
690static char quoteChar(const char *zName){
691 /* All SQLite keywords, in alphabetical order */
692 static const char *azKeywords[] = {
693 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
710 "WITH", "WITHOUT",
711 };
712 int i, lwr, upr, mid, c;
713 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
714 for(i=0; zName[i]; i++){
715 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
716 }
717 lwr = 0;
718 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
719 while( lwr<=upr ){
720 mid = (lwr+upr)/2;
721 c = sqlite3_stricmp(azKeywords[mid], zName);
722 if( c==0 ) return '"';
723 if( c<0 ){
724 lwr = mid+1;
725 }else{
726 upr = mid-1;
727 }
728 }
729 return 0;
730}
drh8e7e7a22000-05-30 18:45:23 +0000731
drh09425592017-06-15 16:56:05 +0000732/*
733** SQL function: shell_add_schema(S,X)
734**
735** Add the schema name X to the CREATE statement in S and return the result.
736** Examples:
737**
738** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
739**
740** Also works on
741**
742** CREATE INDEX
743** CREATE UNIQUE INDEX
744** CREATE VIEW
745** CREATE TRIGGER
746** CREATE VIRTUAL TABLE
747**
748** This UDF is used by the .schema command to insert the schema name of
749** attached databases into the middle of the sqlite_master.sql field.
750*/
751static void shellAddSchemaName(
752 sqlite3_context *pCtx,
753 int nVal,
754 sqlite3_value **apVal
755){
756 static const char *aPrefix[] = {
757 "TABLE",
758 "INDEX",
759 "UNIQUE INDEX",
760 "VIEW",
761 "TRIGGER",
762 "VIRTUAL TABLE"
763 };
764 int i = 0;
765 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
766 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
767 assert( nVal==2 );
768 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
769 for(i=0; i<sizeof(aPrefix)/sizeof(aPrefix[0]); i++){
770 int n = strlen30(aPrefix[i]);
771 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
772 char cQuote = quoteChar(zSchema);
773 char *z;
774 if( cQuote ){
775 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
776 }else{
777 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
778 }
779 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
780 return;
781 }
782 }
783 }
784 sqlite3_result_value(pCtx, apVal[0]);
785}
786
drh1554bc82017-03-08 16:10:34 +0000787/******************************************************************************
788** SHA3 hash implementation copied from ../ext/misc/shathree.c
789*/
790typedef sqlite3_uint64 u64;
791/*
792** Macros to determine whether the machine is big or little endian,
793** and whether or not that determination is run-time or compile-time.
794**
795** For best performance, an attempt is made to guess at the byte-order
796** using C-preprocessor macros. If that is unsuccessful, or if
797** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
798** at run-time.
799*/
800#ifndef SHA3_BYTEORDER
801# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
802 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
803 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
804 defined(__arm__)
805# define SHA3_BYTEORDER 1234
806# elif defined(sparc) || defined(__ppc__)
807# define SHA3_BYTEORDER 4321
808# else
809# define SHA3_BYTEORDER 0
810# endif
811#endif
812
813
814/*
815** State structure for a SHA3 hash in progress
816*/
817typedef struct SHA3Context SHA3Context;
818struct SHA3Context {
819 union {
820 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
821 unsigned char x[1600]; /* ... or 1600 bytes */
822 } u;
823 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
824 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
825 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
826};
827
drh050b1242017-05-04 11:13:50 +0000828/* Allow the following routine to use the B0 variable, which is also
829** a macro in the termios.h header file */
830#undef B0
831
drh1554bc82017-03-08 16:10:34 +0000832/*
833** A single step of the Keccak mixing function for a 1600-bit state
834*/
835static void KeccakF1600Step(SHA3Context *p){
836 int i;
837 u64 B0, B1, B2, B3, B4;
838 u64 C0, C1, C2, C3, C4;
839 u64 D0, D1, D2, D3, D4;
840 static const u64 RC[] = {
841 0x0000000000000001ULL, 0x0000000000008082ULL,
842 0x800000000000808aULL, 0x8000000080008000ULL,
843 0x000000000000808bULL, 0x0000000080000001ULL,
844 0x8000000080008081ULL, 0x8000000000008009ULL,
845 0x000000000000008aULL, 0x0000000000000088ULL,
846 0x0000000080008009ULL, 0x000000008000000aULL,
847 0x000000008000808bULL, 0x800000000000008bULL,
848 0x8000000000008089ULL, 0x8000000000008003ULL,
849 0x8000000000008002ULL, 0x8000000000000080ULL,
850 0x000000000000800aULL, 0x800000008000000aULL,
851 0x8000000080008081ULL, 0x8000000000008080ULL,
852 0x0000000080000001ULL, 0x8000000080008008ULL
853 };
854# define A00 (p->u.s[0])
855# define A01 (p->u.s[1])
856# define A02 (p->u.s[2])
857# define A03 (p->u.s[3])
858# define A04 (p->u.s[4])
859# define A10 (p->u.s[5])
860# define A11 (p->u.s[6])
861# define A12 (p->u.s[7])
862# define A13 (p->u.s[8])
863# define A14 (p->u.s[9])
864# define A20 (p->u.s[10])
865# define A21 (p->u.s[11])
866# define A22 (p->u.s[12])
867# define A23 (p->u.s[13])
868# define A24 (p->u.s[14])
869# define A30 (p->u.s[15])
870# define A31 (p->u.s[16])
871# define A32 (p->u.s[17])
872# define A33 (p->u.s[18])
873# define A34 (p->u.s[19])
874# define A40 (p->u.s[20])
875# define A41 (p->u.s[21])
876# define A42 (p->u.s[22])
877# define A43 (p->u.s[23])
878# define A44 (p->u.s[24])
879# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
880
881 for(i=0; i<24; i+=4){
882 C0 = A00^A10^A20^A30^A40;
883 C1 = A01^A11^A21^A31^A41;
884 C2 = A02^A12^A22^A32^A42;
885 C3 = A03^A13^A23^A33^A43;
886 C4 = A04^A14^A24^A34^A44;
887 D0 = C4^ROL64(C1, 1);
888 D1 = C0^ROL64(C2, 1);
889 D2 = C1^ROL64(C3, 1);
890 D3 = C2^ROL64(C4, 1);
891 D4 = C3^ROL64(C0, 1);
892
893 B0 = (A00^D0);
894 B1 = ROL64((A11^D1), 44);
895 B2 = ROL64((A22^D2), 43);
896 B3 = ROL64((A33^D3), 21);
897 B4 = ROL64((A44^D4), 14);
898 A00 = B0 ^((~B1)& B2 );
899 A00 ^= RC[i];
900 A11 = B1 ^((~B2)& B3 );
901 A22 = B2 ^((~B3)& B4 );
902 A33 = B3 ^((~B4)& B0 );
903 A44 = B4 ^((~B0)& B1 );
904
905 B2 = ROL64((A20^D0), 3);
906 B3 = ROL64((A31^D1), 45);
907 B4 = ROL64((A42^D2), 61);
908 B0 = ROL64((A03^D3), 28);
909 B1 = ROL64((A14^D4), 20);
910 A20 = B0 ^((~B1)& B2 );
911 A31 = B1 ^((~B2)& B3 );
912 A42 = B2 ^((~B3)& B4 );
913 A03 = B3 ^((~B4)& B0 );
914 A14 = B4 ^((~B0)& B1 );
915
916 B4 = ROL64((A40^D0), 18);
917 B0 = ROL64((A01^D1), 1);
918 B1 = ROL64((A12^D2), 6);
919 B2 = ROL64((A23^D3), 25);
920 B3 = ROL64((A34^D4), 8);
921 A40 = B0 ^((~B1)& B2 );
922 A01 = B1 ^((~B2)& B3 );
923 A12 = B2 ^((~B3)& B4 );
924 A23 = B3 ^((~B4)& B0 );
925 A34 = B4 ^((~B0)& B1 );
926
927 B1 = ROL64((A10^D0), 36);
928 B2 = ROL64((A21^D1), 10);
929 B3 = ROL64((A32^D2), 15);
930 B4 = ROL64((A43^D3), 56);
931 B0 = ROL64((A04^D4), 27);
932 A10 = B0 ^((~B1)& B2 );
933 A21 = B1 ^((~B2)& B3 );
934 A32 = B2 ^((~B3)& B4 );
935 A43 = B3 ^((~B4)& B0 );
936 A04 = B4 ^((~B0)& B1 );
937
938 B3 = ROL64((A30^D0), 41);
939 B4 = ROL64((A41^D1), 2);
940 B0 = ROL64((A02^D2), 62);
941 B1 = ROL64((A13^D3), 55);
942 B2 = ROL64((A24^D4), 39);
943 A30 = B0 ^((~B1)& B2 );
944 A41 = B1 ^((~B2)& B3 );
945 A02 = B2 ^((~B3)& B4 );
946 A13 = B3 ^((~B4)& B0 );
947 A24 = B4 ^((~B0)& B1 );
948
949 C0 = A00^A20^A40^A10^A30;
950 C1 = A11^A31^A01^A21^A41;
951 C2 = A22^A42^A12^A32^A02;
952 C3 = A33^A03^A23^A43^A13;
953 C4 = A44^A14^A34^A04^A24;
954 D0 = C4^ROL64(C1, 1);
955 D1 = C0^ROL64(C2, 1);
956 D2 = C1^ROL64(C3, 1);
957 D3 = C2^ROL64(C4, 1);
958 D4 = C3^ROL64(C0, 1);
959
960 B0 = (A00^D0);
961 B1 = ROL64((A31^D1), 44);
962 B2 = ROL64((A12^D2), 43);
963 B3 = ROL64((A43^D3), 21);
964 B4 = ROL64((A24^D4), 14);
965 A00 = B0 ^((~B1)& B2 );
966 A00 ^= RC[i+1];
967 A31 = B1 ^((~B2)& B3 );
968 A12 = B2 ^((~B3)& B4 );
969 A43 = B3 ^((~B4)& B0 );
970 A24 = B4 ^((~B0)& B1 );
971
972 B2 = ROL64((A40^D0), 3);
973 B3 = ROL64((A21^D1), 45);
974 B4 = ROL64((A02^D2), 61);
975 B0 = ROL64((A33^D3), 28);
976 B1 = ROL64((A14^D4), 20);
977 A40 = B0 ^((~B1)& B2 );
978 A21 = B1 ^((~B2)& B3 );
979 A02 = B2 ^((~B3)& B4 );
980 A33 = B3 ^((~B4)& B0 );
981 A14 = B4 ^((~B0)& B1 );
982
983 B4 = ROL64((A30^D0), 18);
984 B0 = ROL64((A11^D1), 1);
985 B1 = ROL64((A42^D2), 6);
986 B2 = ROL64((A23^D3), 25);
987 B3 = ROL64((A04^D4), 8);
988 A30 = B0 ^((~B1)& B2 );
989 A11 = B1 ^((~B2)& B3 );
990 A42 = B2 ^((~B3)& B4 );
991 A23 = B3 ^((~B4)& B0 );
992 A04 = B4 ^((~B0)& B1 );
993
994 B1 = ROL64((A20^D0), 36);
995 B2 = ROL64((A01^D1), 10);
996 B3 = ROL64((A32^D2), 15);
997 B4 = ROL64((A13^D3), 56);
998 B0 = ROL64((A44^D4), 27);
999 A20 = B0 ^((~B1)& B2 );
1000 A01 = B1 ^((~B2)& B3 );
1001 A32 = B2 ^((~B3)& B4 );
1002 A13 = B3 ^((~B4)& B0 );
1003 A44 = B4 ^((~B0)& B1 );
1004
1005 B3 = ROL64((A10^D0), 41);
1006 B4 = ROL64((A41^D1), 2);
1007 B0 = ROL64((A22^D2), 62);
1008 B1 = ROL64((A03^D3), 55);
1009 B2 = ROL64((A34^D4), 39);
1010 A10 = B0 ^((~B1)& B2 );
1011 A41 = B1 ^((~B2)& B3 );
1012 A22 = B2 ^((~B3)& B4 );
1013 A03 = B3 ^((~B4)& B0 );
1014 A34 = B4 ^((~B0)& B1 );
1015
1016 C0 = A00^A40^A30^A20^A10;
1017 C1 = A31^A21^A11^A01^A41;
1018 C2 = A12^A02^A42^A32^A22;
1019 C3 = A43^A33^A23^A13^A03;
1020 C4 = A24^A14^A04^A44^A34;
1021 D0 = C4^ROL64(C1, 1);
1022 D1 = C0^ROL64(C2, 1);
1023 D2 = C1^ROL64(C3, 1);
1024 D3 = C2^ROL64(C4, 1);
1025 D4 = C3^ROL64(C0, 1);
1026
1027 B0 = (A00^D0);
1028 B1 = ROL64((A21^D1), 44);
1029 B2 = ROL64((A42^D2), 43);
1030 B3 = ROL64((A13^D3), 21);
1031 B4 = ROL64((A34^D4), 14);
1032 A00 = B0 ^((~B1)& B2 );
1033 A00 ^= RC[i+2];
1034 A21 = B1 ^((~B2)& B3 );
1035 A42 = B2 ^((~B3)& B4 );
1036 A13 = B3 ^((~B4)& B0 );
1037 A34 = B4 ^((~B0)& B1 );
1038
1039 B2 = ROL64((A30^D0), 3);
1040 B3 = ROL64((A01^D1), 45);
1041 B4 = ROL64((A22^D2), 61);
1042 B0 = ROL64((A43^D3), 28);
1043 B1 = ROL64((A14^D4), 20);
1044 A30 = B0 ^((~B1)& B2 );
1045 A01 = B1 ^((~B2)& B3 );
1046 A22 = B2 ^((~B3)& B4 );
1047 A43 = B3 ^((~B4)& B0 );
1048 A14 = B4 ^((~B0)& B1 );
1049
1050 B4 = ROL64((A10^D0), 18);
1051 B0 = ROL64((A31^D1), 1);
1052 B1 = ROL64((A02^D2), 6);
1053 B2 = ROL64((A23^D3), 25);
1054 B3 = ROL64((A44^D4), 8);
1055 A10 = B0 ^((~B1)& B2 );
1056 A31 = B1 ^((~B2)& B3 );
1057 A02 = B2 ^((~B3)& B4 );
1058 A23 = B3 ^((~B4)& B0 );
1059 A44 = B4 ^((~B0)& B1 );
1060
1061 B1 = ROL64((A40^D0), 36);
1062 B2 = ROL64((A11^D1), 10);
1063 B3 = ROL64((A32^D2), 15);
1064 B4 = ROL64((A03^D3), 56);
1065 B0 = ROL64((A24^D4), 27);
1066 A40 = B0 ^((~B1)& B2 );
1067 A11 = B1 ^((~B2)& B3 );
1068 A32 = B2 ^((~B3)& B4 );
1069 A03 = B3 ^((~B4)& B0 );
1070 A24 = B4 ^((~B0)& B1 );
1071
1072 B3 = ROL64((A20^D0), 41);
1073 B4 = ROL64((A41^D1), 2);
1074 B0 = ROL64((A12^D2), 62);
1075 B1 = ROL64((A33^D3), 55);
1076 B2 = ROL64((A04^D4), 39);
1077 A20 = B0 ^((~B1)& B2 );
1078 A41 = B1 ^((~B2)& B3 );
1079 A12 = B2 ^((~B3)& B4 );
1080 A33 = B3 ^((~B4)& B0 );
1081 A04 = B4 ^((~B0)& B1 );
1082
1083 C0 = A00^A30^A10^A40^A20;
1084 C1 = A21^A01^A31^A11^A41;
1085 C2 = A42^A22^A02^A32^A12;
1086 C3 = A13^A43^A23^A03^A33;
1087 C4 = A34^A14^A44^A24^A04;
1088 D0 = C4^ROL64(C1, 1);
1089 D1 = C0^ROL64(C2, 1);
1090 D2 = C1^ROL64(C3, 1);
1091 D3 = C2^ROL64(C4, 1);
1092 D4 = C3^ROL64(C0, 1);
1093
1094 B0 = (A00^D0);
1095 B1 = ROL64((A01^D1), 44);
1096 B2 = ROL64((A02^D2), 43);
1097 B3 = ROL64((A03^D3), 21);
1098 B4 = ROL64((A04^D4), 14);
1099 A00 = B0 ^((~B1)& B2 );
1100 A00 ^= RC[i+3];
1101 A01 = B1 ^((~B2)& B3 );
1102 A02 = B2 ^((~B3)& B4 );
1103 A03 = B3 ^((~B4)& B0 );
1104 A04 = B4 ^((~B0)& B1 );
1105
1106 B2 = ROL64((A10^D0), 3);
1107 B3 = ROL64((A11^D1), 45);
1108 B4 = ROL64((A12^D2), 61);
1109 B0 = ROL64((A13^D3), 28);
1110 B1 = ROL64((A14^D4), 20);
1111 A10 = B0 ^((~B1)& B2 );
1112 A11 = B1 ^((~B2)& B3 );
1113 A12 = B2 ^((~B3)& B4 );
1114 A13 = B3 ^((~B4)& B0 );
1115 A14 = B4 ^((~B0)& B1 );
1116
1117 B4 = ROL64((A20^D0), 18);
1118 B0 = ROL64((A21^D1), 1);
1119 B1 = ROL64((A22^D2), 6);
1120 B2 = ROL64((A23^D3), 25);
1121 B3 = ROL64((A24^D4), 8);
1122 A20 = B0 ^((~B1)& B2 );
1123 A21 = B1 ^((~B2)& B3 );
1124 A22 = B2 ^((~B3)& B4 );
1125 A23 = B3 ^((~B4)& B0 );
1126 A24 = B4 ^((~B0)& B1 );
1127
1128 B1 = ROL64((A30^D0), 36);
1129 B2 = ROL64((A31^D1), 10);
1130 B3 = ROL64((A32^D2), 15);
1131 B4 = ROL64((A33^D3), 56);
1132 B0 = ROL64((A34^D4), 27);
1133 A30 = B0 ^((~B1)& B2 );
1134 A31 = B1 ^((~B2)& B3 );
1135 A32 = B2 ^((~B3)& B4 );
1136 A33 = B3 ^((~B4)& B0 );
1137 A34 = B4 ^((~B0)& B1 );
1138
1139 B3 = ROL64((A40^D0), 41);
1140 B4 = ROL64((A41^D1), 2);
1141 B0 = ROL64((A42^D2), 62);
1142 B1 = ROL64((A43^D3), 55);
1143 B2 = ROL64((A44^D4), 39);
1144 A40 = B0 ^((~B1)& B2 );
1145 A41 = B1 ^((~B2)& B3 );
1146 A42 = B2 ^((~B3)& B4 );
1147 A43 = B3 ^((~B4)& B0 );
1148 A44 = B4 ^((~B0)& B1 );
1149 }
1150}
1151
1152/*
1153** Initialize a new hash. iSize determines the size of the hash
1154** in bits and should be one of 224, 256, 384, or 512. Or iSize
1155** can be zero to use the default hash size of 256 bits.
1156*/
1157static void SHA3Init(SHA3Context *p, int iSize){
1158 memset(p, 0, sizeof(*p));
1159 if( iSize>=128 && iSize<=512 ){
1160 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1161 }else{
1162 p->nRate = (1600 - 2*256)/8;
1163 }
1164#if SHA3_BYTEORDER==1234
1165 /* Known to be little-endian at compile-time. No-op */
1166#elif SHA3_BYTEORDER==4321
1167 p->ixMask = 7; /* Big-endian */
1168#else
1169 {
1170 static unsigned int one = 1;
1171 if( 1==*(unsigned char*)&one ){
1172 /* Little endian. No byte swapping. */
1173 p->ixMask = 0;
1174 }else{
1175 /* Big endian. Byte swap. */
1176 p->ixMask = 7;
1177 }
1178 }
1179#endif
1180}
1181
1182/*
1183** Make consecutive calls to the SHA3Update function to add new content
1184** to the hash
1185*/
1186static void SHA3Update(
1187 SHA3Context *p,
1188 const unsigned char *aData,
1189 unsigned int nData
1190){
1191 unsigned int i = 0;
1192#if SHA3_BYTEORDER==1234
1193 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1194 for(; i+7<nData; i+=8){
1195 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1196 p->nLoaded += 8;
1197 if( p->nLoaded>=p->nRate ){
1198 KeccakF1600Step(p);
1199 p->nLoaded = 0;
1200 }
1201 }
1202 }
1203#endif
1204 for(; i<nData; i++){
1205#if SHA3_BYTEORDER==1234
1206 p->u.x[p->nLoaded] ^= aData[i];
1207#elif SHA3_BYTEORDER==4321
1208 p->u.x[p->nLoaded^0x07] ^= aData[i];
1209#else
1210 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1211#endif
1212 p->nLoaded++;
1213 if( p->nLoaded==p->nRate ){
1214 KeccakF1600Step(p);
1215 p->nLoaded = 0;
1216 }
1217 }
1218}
1219
1220/*
1221** After all content has been added, invoke SHA3Final() to compute
1222** the final hash. The function returns a pointer to the binary
1223** hash value.
1224*/
1225static unsigned char *SHA3Final(SHA3Context *p){
1226 unsigned int i;
1227 if( p->nLoaded==p->nRate-1 ){
1228 const unsigned char c1 = 0x86;
1229 SHA3Update(p, &c1, 1);
1230 }else{
1231 const unsigned char c2 = 0x06;
1232 const unsigned char c3 = 0x80;
1233 SHA3Update(p, &c2, 1);
1234 p->nLoaded = p->nRate - 1;
1235 SHA3Update(p, &c3, 1);
1236 }
1237 for(i=0; i<p->nRate; i++){
1238 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1239 }
1240 return &p->u.x[p->nRate];
1241}
1242
1243/*
1244** Implementation of the sha3(X,SIZE) function.
1245**
1246** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
mistachkine16a3502017-05-29 03:48:13 +00001247** size is 256. If X is a BLOB, it is hashed as is.
drh1554bc82017-03-08 16:10:34 +00001248** For all other non-NULL types of input, X is converted into a UTF-8 string
1249** and the string is hashed without the trailing 0x00 terminator. The hash
1250** of a NULL value is NULL.
1251*/
1252static void sha3Func(
1253 sqlite3_context *context,
1254 int argc,
1255 sqlite3_value **argv
1256){
1257 SHA3Context cx;
1258 int eType = sqlite3_value_type(argv[0]);
1259 int nByte = sqlite3_value_bytes(argv[0]);
1260 int iSize;
1261 if( argc==1 ){
1262 iSize = 256;
1263 }else{
1264 iSize = sqlite3_value_int(argv[1]);
1265 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1266 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1267 "384 512", -1);
1268 return;
1269 }
1270 }
1271 if( eType==SQLITE_NULL ) return;
1272 SHA3Init(&cx, iSize);
1273 if( eType==SQLITE_BLOB ){
1274 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1275 }else{
1276 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1277 }
1278 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1279}
1280
1281/* Compute a string using sqlite3_vsnprintf() with a maximum length
1282** of 50 bytes and add it to the hash.
1283*/
1284static void hash_step_vformat(
1285 SHA3Context *p, /* Add content to this context */
1286 const char *zFormat,
1287 ...
1288){
1289 va_list ap;
1290 int n;
1291 char zBuf[50];
1292 va_start(ap, zFormat);
1293 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1294 va_end(ap);
1295 n = (int)strlen(zBuf);
1296 SHA3Update(p, (unsigned char*)zBuf, n);
1297}
1298
1299/*
1300** Implementation of the sha3_query(SQL,SIZE) function.
1301**
1302** This function compiles and runs the SQL statement(s) given in the
1303** argument. The results are hashed using a SIZE-bit SHA3. The default
1304** size is 256.
1305**
1306** The format of the byte stream that is hashed is summarized as follows:
1307**
1308** S<n>:<sql>
1309** R
1310** N
1311** I<int>
1312** F<ieee-float>
1313** B<size>:<bytes>
1314** T<size>:<text>
1315**
1316** <sql> is the original SQL text for each statement run and <n> is
1317** the size of that text. The SQL text is UTF-8. A single R character
1318** occurs before the start of each row. N means a NULL value.
1319** I mean an 8-byte little-endian integer <int>. F is a floating point
1320** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1321** B means blobs of <size> bytes. T means text rendered as <size>
1322** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1323** text integers.
1324**
1325** For each SQL statement in the X input, there is one S segment. Each
1326** S segment is followed by zero or more R segments, one for each row in the
1327** result set. After each R, there are one or more N, I, F, B, or T segments,
1328** one for each column in the result set. Segments are concatentated directly
1329** with no delimiters of any kind.
1330*/
1331static void sha3QueryFunc(
1332 sqlite3_context *context,
1333 int argc,
1334 sqlite3_value **argv
1335){
1336 sqlite3 *db = sqlite3_context_db_handle(context);
1337 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1338 sqlite3_stmt *pStmt = 0;
1339 int nCol; /* Number of columns in the result set */
1340 int i; /* Loop counter */
1341 int rc;
1342 int n;
1343 const char *z;
1344 SHA3Context cx;
1345 int iSize;
1346
1347 if( argc==1 ){
1348 iSize = 256;
1349 }else{
1350 iSize = sqlite3_value_int(argv[1]);
1351 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1352 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1353 "384 512", -1);
1354 return;
1355 }
1356 }
1357 if( zSql==0 ) return;
1358 SHA3Init(&cx, iSize);
1359 while( zSql[0] ){
1360 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1361 if( rc ){
1362 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1363 zSql, sqlite3_errmsg(db));
1364 sqlite3_finalize(pStmt);
1365 sqlite3_result_error(context, zMsg, -1);
1366 sqlite3_free(zMsg);
1367 return;
1368 }
1369 if( !sqlite3_stmt_readonly(pStmt) ){
1370 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1371 sqlite3_finalize(pStmt);
1372 sqlite3_result_error(context, zMsg, -1);
1373 sqlite3_free(zMsg);
1374 return;
1375 }
1376 nCol = sqlite3_column_count(pStmt);
1377 z = sqlite3_sql(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00001378 if( z==0 ){
1379 sqlite3_finalize(pStmt);
1380 continue;
1381 }
drh1554bc82017-03-08 16:10:34 +00001382 n = (int)strlen(z);
1383 hash_step_vformat(&cx,"S%d:",n);
1384 SHA3Update(&cx,(unsigned char*)z,n);
1385
1386 /* Compute a hash over the result of the query */
1387 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1388 SHA3Update(&cx,(const unsigned char*)"R",1);
1389 for(i=0; i<nCol; i++){
1390 switch( sqlite3_column_type(pStmt,i) ){
1391 case SQLITE_NULL: {
1392 SHA3Update(&cx, (const unsigned char*)"N",1);
1393 break;
1394 }
1395 case SQLITE_INTEGER: {
1396 sqlite3_uint64 u;
1397 int j;
1398 unsigned char x[9];
1399 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1400 memcpy(&u, &v, 8);
1401 for(j=8; j>=1; j--){
1402 x[j] = u & 0xff;
1403 u >>= 8;
1404 }
1405 x[0] = 'I';
1406 SHA3Update(&cx, x, 9);
1407 break;
1408 }
1409 case SQLITE_FLOAT: {
1410 sqlite3_uint64 u;
1411 int j;
1412 unsigned char x[9];
1413 double r = sqlite3_column_double(pStmt,i);
1414 memcpy(&u, &r, 8);
1415 for(j=8; j>=1; j--){
1416 x[j] = u & 0xff;
1417 u >>= 8;
1418 }
1419 x[0] = 'F';
1420 SHA3Update(&cx,x,9);
1421 break;
1422 }
1423 case SQLITE_TEXT: {
1424 int n2 = sqlite3_column_bytes(pStmt, i);
1425 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1426 hash_step_vformat(&cx,"T%d:",n2);
1427 SHA3Update(&cx, z2, n2);
1428 break;
1429 }
1430 case SQLITE_BLOB: {
1431 int n2 = sqlite3_column_bytes(pStmt, i);
1432 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1433 hash_step_vformat(&cx,"B%d:",n2);
1434 SHA3Update(&cx, z2, n2);
1435 break;
1436 }
1437 }
1438 }
1439 }
1440 sqlite3_finalize(pStmt);
1441 }
1442 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1443}
1444/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1445********************************************************************************/
1446
drhe6229612014-08-18 15:08:26 +00001447#if defined(SQLITE_ENABLE_SESSION)
1448/*
1449** State information for a single open session
1450*/
1451typedef struct OpenSession OpenSession;
1452struct OpenSession {
1453 char *zName; /* Symbolic name for this session */
1454 int nFilter; /* Number of xFilter rejection GLOB patterns */
1455 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1456 sqlite3_session *p; /* The open session */
1457};
1458#endif
1459
drhdcd87a92014-08-18 13:45:42 +00001460/*
mistachkin1fe36bb2016-04-04 02:16:44 +00001461** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00001462** saved so that it can be restored by ".explain off"
1463*/
1464typedef struct SavedModeInfo SavedModeInfo;
1465struct SavedModeInfo {
1466 int valid; /* Is there legit data in here? */
1467 int mode; /* Mode prior to ".explain on" */
1468 int showHeader; /* The ".header" setting prior to ".explain on" */
1469 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00001470};
drh45e29d82006-11-20 16:21:10 +00001471
drh8e7e7a22000-05-30 18:45:23 +00001472/*
drhdcd87a92014-08-18 13:45:42 +00001473** State information about the database connection is contained in an
1474** instance of the following structure.
drh75897232000-05-29 14:26:00 +00001475*/
drhdcd87a92014-08-18 13:45:42 +00001476typedef struct ShellState ShellState;
1477struct ShellState {
shane626a6e42009-10-22 17:30:15 +00001478 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00001479 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00001480 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00001481 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00001482 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00001483 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00001484 int cnt; /* Number of records displayed so far */
1485 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00001486 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00001487 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00001488 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00001489 int cMode; /* temporary output mode for the current query */
1490 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00001491 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00001492 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00001493 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00001494 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00001495 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00001496 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00001497 char colSeparator[20]; /* Column separator character for several modes */
1498 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00001499 int colWidth[100]; /* Requested width of each column when in column mode*/
1500 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00001501 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00001502 ** the database */
drh44c2eb12003-04-30 11:38:26 +00001503 char outfile[FILENAME_MAX]; /* Filename for *out */
1504 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00001505 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00001506 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00001507 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00001508 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00001509 int *aiIndent; /* Array of indents used in MODE_Explain */
1510 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00001511 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00001512#if defined(SQLITE_ENABLE_SESSION)
1513 int nSession; /* Number of active sessions */
1514 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1515#endif
drh75897232000-05-29 14:26:00 +00001516};
1517
1518/*
drh44dec872014-08-30 15:49:25 +00001519** These are the allowed shellFlgs values
1520*/
drhe6e1d122017-03-09 13:50:49 +00001521#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1522#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1523#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1524#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1525#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1526#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1527#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1528
1529/*
1530** Macros for testing and setting shellFlgs
1531*/
1532#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1533#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1534#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00001535
1536/*
drh75897232000-05-29 14:26:00 +00001537** These are the allowed modes.
1538*/
drh967e8b72000-06-21 13:59:10 +00001539#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00001540#define MODE_Column 1 /* One record per line in neat columns */
1541#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00001542#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1543#define MODE_Html 4 /* Generate an XHTML table */
1544#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00001545#define MODE_Quote 6 /* Quote values as for SQL */
1546#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1547#define MODE_Csv 8 /* Quote strings, numbers are plain */
1548#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1549#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1550#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00001551
drh66ce4d02008-02-15 17:38:06 +00001552static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00001553 "line",
1554 "column",
1555 "list",
1556 "semi",
1557 "html",
drhfeac5f82004-08-01 00:10:45 +00001558 "insert",
drh41f5f6e2016-10-21 17:39:30 +00001559 "quote",
drhfeac5f82004-08-01 00:10:45 +00001560 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00001561 "csv",
drh66ce4d02008-02-15 17:38:06 +00001562 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00001563 "ascii",
drh4926fec2016-04-13 15:33:42 +00001564 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00001565};
drh75897232000-05-29 14:26:00 +00001566
1567/*
mistachkinfad42082014-07-24 22:13:12 +00001568** These are the column/row/line separators used by the various
1569** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00001570*/
mistachkinfad42082014-07-24 22:13:12 +00001571#define SEP_Column "|"
1572#define SEP_Row "\n"
1573#define SEP_Tab "\t"
1574#define SEP_Space " "
1575#define SEP_Comma ","
1576#define SEP_CrLf "\r\n"
1577#define SEP_Unit "\x1F"
1578#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00001579
1580/*
drh75897232000-05-29 14:26:00 +00001581** Number of elements in an array
1582*/
drh902b9ee2008-12-05 17:17:07 +00001583#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00001584
1585/*
drh127f9d72010-02-23 01:47:00 +00001586** A callback for the sqlite3_log() interface.
1587*/
1588static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00001589 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00001590 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00001591 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00001592 fflush(p->pLog);
1593}
1594
1595/*
shane626a6e42009-10-22 17:30:15 +00001596** Output the given string as a hex-encoded blob (eg. X'1234' )
1597*/
1598static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1599 int i;
1600 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00001601 raw_printf(out,"X'");
1602 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1603 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00001604}
1605
1606/*
drh6193d492017-04-07 11:45:58 +00001607** Find a string that is not found anywhere in z[]. Return a pointer
1608** to that string.
1609**
1610** Try to use zA and zB first. If both of those are already found in z[]
1611** then make up some string and store it in the buffer zBuf.
1612*/
1613static const char *unused_string(
1614 const char *z, /* Result must not appear anywhere in z */
1615 const char *zA, const char *zB, /* Try these first */
1616 char *zBuf /* Space to store a generated string */
1617){
1618 unsigned i = 0;
1619 if( strstr(z, zA)==0 ) return zA;
1620 if( strstr(z, zB)==0 ) return zB;
1621 do{
1622 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1623 }while( strstr(z,zBuf)!=0 );
1624 return zBuf;
1625}
1626
1627/*
drh28bd4bc2000-06-15 15:57:22 +00001628** Output the given string as a quoted string using SQL quoting conventions.
drh708b22b2017-03-11 01:56:41 +00001629**
drh13fe1382017-04-08 13:42:55 +00001630** See also: output_quoted_escaped_string()
drh28bd4bc2000-06-15 15:57:22 +00001631*/
1632static void output_quoted_string(FILE *out, const char *z){
1633 int i;
drh708b22b2017-03-11 01:56:41 +00001634 char c;
mistachkin1fe36bb2016-04-04 02:16:44 +00001635 setBinaryMode(out, 1);
drh13fe1382017-04-08 13:42:55 +00001636 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1637 if( c==0 ){
1638 utf8_printf(out,"'%s'",z);
1639 }else{
1640 raw_printf(out, "'");
1641 while( *z ){
1642 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1643 if( c=='\'' ) i++;
1644 if( i ){
1645 utf8_printf(out, "%.*s", i, z);
1646 z += i;
1647 }
1648 if( c=='\'' ){
1649 raw_printf(out, "'");
1650 continue;
1651 }
1652 if( c==0 ){
1653 break;
1654 }
1655 z++;
1656 }
1657 raw_printf(out, "'");
1658 }
1659 setTextMode(out, 1);
1660}
1661
1662/*
1663** Output the given string as a quoted string using SQL quoting conventions.
1664** Additionallly , escape the "\n" and "\r" characters so that they do not
1665** get corrupted by end-of-line translation facilities in some operating
1666** systems.
1667**
1668** This is like output_quoted_string() but with the addition of the \r\n
1669** escape mechanism.
1670*/
1671static void output_quoted_escaped_string(FILE *out, const char *z){
1672 int i;
1673 char c;
1674 setBinaryMode(out, 1);
drh708b22b2017-03-11 01:56:41 +00001675 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1676 if( c==0 ){
drhe05461c2015-12-30 13:36:57 +00001677 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00001678 }else{
drh6193d492017-04-07 11:45:58 +00001679 const char *zNL = 0;
1680 const char *zCR = 0;
1681 int nNL = 0;
1682 int nCR = 0;
1683 char zBuf1[20], zBuf2[20];
1684 for(i=0; z[i]; i++){
1685 if( z[i]=='\n' ) nNL++;
1686 if( z[i]=='\r' ) nCR++;
1687 }
1688 if( nNL ){
1689 raw_printf(out, "replace(");
1690 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1691 }
1692 if( nCR ){
1693 raw_printf(out, "replace(");
1694 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1695 }
1696 raw_printf(out, "'");
drh28bd4bc2000-06-15 15:57:22 +00001697 while( *z ){
drh708b22b2017-03-11 01:56:41 +00001698 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1699 if( c=='\'' ) i++;
1700 if( i ){
drh708b22b2017-03-11 01:56:41 +00001701 utf8_printf(out, "%.*s", i, z);
1702 z += i;
drh708b22b2017-03-11 01:56:41 +00001703 }
1704 if( c=='\'' ){
1705 raw_printf(out, "'");
1706 continue;
1707 }
drh708b22b2017-03-11 01:56:41 +00001708 if( c==0 ){
drh28bd4bc2000-06-15 15:57:22 +00001709 break;
1710 }
drh6193d492017-04-07 11:45:58 +00001711 z++;
1712 if( c=='\n' ){
1713 raw_printf(out, "%s", zNL);
1714 continue;
drh708b22b2017-03-11 01:56:41 +00001715 }
drh6193d492017-04-07 11:45:58 +00001716 raw_printf(out, "%s", zCR);
drh28bd4bc2000-06-15 15:57:22 +00001717 }
drh6193d492017-04-07 11:45:58 +00001718 raw_printf(out, "'");
1719 if( nCR ){
1720 raw_printf(out, ",'%s',char(13))", zCR);
1721 }
1722 if( nNL ){
1723 raw_printf(out, ",'%s',char(10))", zNL);
1724 }
drh28bd4bc2000-06-15 15:57:22 +00001725 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001726 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001727}
1728
1729/*
drhfeac5f82004-08-01 00:10:45 +00001730** Output the given string as a quoted according to C or TCL quoting rules.
1731*/
1732static void output_c_string(FILE *out, const char *z){
1733 unsigned int c;
1734 fputc('"', out);
1735 while( (c = *(z++))!=0 ){
1736 if( c=='\\' ){
1737 fputc(c, out);
1738 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00001739 }else if( c=='"' ){
1740 fputc('\\', out);
1741 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00001742 }else if( c=='\t' ){
1743 fputc('\\', out);
1744 fputc('t', out);
1745 }else if( c=='\n' ){
1746 fputc('\\', out);
1747 fputc('n', out);
1748 }else if( c=='\r' ){
1749 fputc('\\', out);
1750 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00001751 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00001752 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00001753 }else{
1754 fputc(c, out);
1755 }
1756 }
1757 fputc('"', out);
1758}
1759
1760/*
drhc08a4f12000-06-15 16:49:48 +00001761** Output the given string with characters that are special to
1762** HTML escaped.
1763*/
1764static void output_html_string(FILE *out, const char *z){
1765 int i;
drhc3d6ba42014-01-13 20:38:35 +00001766 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00001767 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00001768 for(i=0; z[i]
1769 && z[i]!='<'
1770 && z[i]!='&'
1771 && z[i]!='>'
1772 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00001773 && z[i]!='\'';
1774 i++){}
drhc08a4f12000-06-15 16:49:48 +00001775 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00001776 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00001777 }
1778 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00001779 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00001780 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00001781 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00001782 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00001783 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00001784 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00001785 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00001786 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00001787 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00001788 }else{
1789 break;
1790 }
1791 z += i + 1;
1792 }
1793}
1794
1795/*
drhc49f44e2006-10-26 18:15:42 +00001796** If a field contains any character identified by a 1 in the following
1797** array, then the string must be quoted for CSV.
1798*/
1799static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00001800 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1801 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1802 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1803 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1804 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1805 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1806 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1807 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1808 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1809 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1810 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1811 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1812 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1813 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1814 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1815 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00001816};
1817
1818/*
mistachkindd11f2d2014-12-11 04:49:46 +00001819** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00001820** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00001821** the null value. Strings are quoted if necessary. The separator
1822** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00001823*/
drhdcd87a92014-08-18 13:45:42 +00001824static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00001825 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00001826 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00001827 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00001828 }else{
drhc49f44e2006-10-26 18:15:42 +00001829 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00001830 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00001831 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00001832 if( needCsvQuote[((unsigned char*)z)[i]]
1833 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00001834 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00001835 i = 0;
1836 break;
1837 }
1838 }
1839 if( i==0 ){
1840 putc('"', out);
1841 for(i=0; z[i]; i++){
1842 if( z[i]=='"' ) putc('"', out);
1843 putc(z[i], out);
1844 }
1845 putc('"', out);
1846 }else{
drhe05461c2015-12-30 13:36:57 +00001847 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00001848 }
drh8e64d1c2004-10-07 00:32:39 +00001849 }
1850 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00001851 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001852 }
1853}
1854
danielk19774af00c62005-01-23 23:43:21 +00001855#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00001856/*
drh4c504392000-10-16 22:06:40 +00001857** This routine runs when the user presses Ctrl-C
1858*/
1859static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00001860 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00001861 seenInterrupt++;
1862 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00001863 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00001864}
danielk19774af00c62005-01-23 23:43:21 +00001865#endif
drh4c504392000-10-16 22:06:40 +00001866
drha0daa752016-09-16 11:53:10 +00001867#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00001868/*
drhde613c62016-04-04 17:23:10 +00001869** When the ".auth ON" is set, the following authorizer callback is
1870** invoked. It always returns SQLITE_OK.
1871*/
1872static int shellAuth(
1873 void *pClientData,
1874 int op,
1875 const char *zA1,
1876 const char *zA2,
1877 const char *zA3,
1878 const char *zA4
1879){
1880 ShellState *p = (ShellState*)pClientData;
1881 static const char *azAction[] = { 0,
1882 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1883 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1884 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1885 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1886 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1887 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1888 "PRAGMA", "READ", "SELECT",
1889 "TRANSACTION", "UPDATE", "ATTACH",
1890 "DETACH", "ALTER_TABLE", "REINDEX",
1891 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1892 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1893 };
1894 int i;
1895 const char *az[4];
1896 az[0] = zA1;
1897 az[1] = zA2;
1898 az[2] = zA3;
1899 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00001900 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00001901 for(i=0; i<4; i++){
1902 raw_printf(p->out, " ");
1903 if( az[i] ){
1904 output_c_string(p->out, az[i]);
1905 }else{
1906 raw_printf(p->out, "NULL");
1907 }
1908 }
1909 raw_printf(p->out, "\n");
1910 return SQLITE_OK;
1911}
drha0daa752016-09-16 11:53:10 +00001912#endif
mistachkin8145fc62016-09-16 20:39:21 +00001913
drh79f20e92016-12-13 23:22:39 +00001914/*
1915** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1916**
1917** This routine converts some CREATE TABLE statements for shadow tables
1918** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1919*/
1920static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1921 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1922 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1923 }else{
1924 utf8_printf(out, "%s%s", z, zTail);
1925 }
1926}
1927static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1928 char c = z[n];
1929 z[n] = 0;
1930 printSchemaLine(out, z, zTail);
1931 z[n] = c;
1932}
drhde613c62016-04-04 17:23:10 +00001933
1934/*
shane626a6e42009-10-22 17:30:15 +00001935** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00001936** invokes for each row of a query result.
1937*/
drh4ace5362014-11-10 14:42:28 +00001938static int shell_callback(
1939 void *pArg,
1940 int nArg, /* Number of result columns */
1941 char **azArg, /* Text of each result column */
1942 char **azCol, /* Column names */
1943 int *aiType /* Column types */
1944){
drh75897232000-05-29 14:26:00 +00001945 int i;
drhdcd87a92014-08-18 13:45:42 +00001946 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00001947
drh700c2522016-02-09 18:39:25 +00001948 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00001949 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00001950 int w = 5;
drh6a535342001-10-19 16:44:56 +00001951 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00001952 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00001953 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00001954 if( len>w ) w = len;
1955 }
drhe05461c2015-12-30 13:36:57 +00001956 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001957 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001958 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00001959 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001960 }
1961 break;
1962 }
danielk19770d78bae2008-01-03 07:09:48 +00001963 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00001964 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00001965 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1966 const int *colWidth;
1967 int showHdr;
1968 char *rowSep;
1969 if( p->cMode==MODE_Column ){
1970 colWidth = p->colWidth;
1971 showHdr = p->showHeader;
1972 rowSep = p->rowSeparator;
1973 }else{
1974 colWidth = aExplainWidths;
1975 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00001976 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00001977 }
drha0c66f52000-07-29 13:20:21 +00001978 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00001979 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00001980 int w, n;
1981 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00001982 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00001983 }else{
danielk19770d78bae2008-01-03 07:09:48 +00001984 w = 0;
drh75897232000-05-29 14:26:00 +00001985 }
drh078b1fd2012-09-21 13:40:02 +00001986 if( w==0 ){
drh64bf76d2017-06-05 12:29:26 +00001987 w = strlenChar(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00001988 if( w<10 ) w = 10;
drh64bf76d2017-06-05 12:29:26 +00001989 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00001990 if( w<n ) w = n;
1991 }
1992 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00001993 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00001994 }
drh700c2522016-02-09 18:39:25 +00001995 if( showHdr ){
drh6887e8f2017-04-17 13:18:42 +00001996 utf8_width_print(p->out, w, azCol[i]);
1997 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001998 }
1999 }
drh700c2522016-02-09 18:39:25 +00002000 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00002001 for(i=0; i<nArg; i++){
2002 int w;
2003 if( i<ArraySize(p->actualWidth) ){
2004 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00002005 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00002006 }else{
2007 w = 10;
2008 }
mistachkinaae280e2015-12-31 19:06:24 +00002009 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00002010 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00002011 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00002012 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00002013 }
drh75897232000-05-29 14:26:00 +00002014 }
2015 }
drh6a535342001-10-19 16:44:56 +00002016 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002017 for(i=0; i<nArg; i++){
2018 int w;
drha0c66f52000-07-29 13:20:21 +00002019 if( i<ArraySize(p->actualWidth) ){
2020 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00002021 }else{
2022 w = 10;
2023 }
drh64bf76d2017-06-05 12:29:26 +00002024 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
2025 w = strlenChar(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00002026 }
dana98bf362013-11-13 18:35:01 +00002027 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00002028 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00002029 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00002030 }
danc4650bb2013-11-18 08:41:06 +00002031 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00002032 }
drh6887e8f2017-04-17 13:18:42 +00002033 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2034 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drh75897232000-05-29 14:26:00 +00002035 }
2036 break;
2037 }
drh4926fec2016-04-13 15:33:42 +00002038 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00002039 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00002040 break;
2041 }
2042 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2043 char *z;
drh07d683f2016-04-13 21:00:36 +00002044 int j;
drh4926fec2016-04-13 15:33:42 +00002045 int nParen = 0;
2046 char cEnd = 0;
2047 char c;
2048 int nLine = 0;
2049 assert( nArg==1 );
2050 if( azArg[0]==0 ) break;
2051 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2052 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2053 ){
2054 utf8_printf(p->out, "%s;\n", azArg[0]);
2055 break;
2056 }
2057 z = sqlite3_mprintf("%s", azArg[0]);
2058 j = 0;
2059 for(i=0; IsSpace(z[i]); i++){}
2060 for(; (c = z[i])!=0; i++){
2061 if( IsSpace(c) ){
2062 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2063 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2064 j--;
2065 }
2066 z[j++] = c;
2067 }
2068 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2069 z[j] = 0;
2070 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00002071 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00002072 if( c==cEnd ){
2073 cEnd = 0;
2074 }else if( c=='"' || c=='\'' || c=='`' ){
2075 cEnd = c;
2076 }else if( c=='[' ){
2077 cEnd = ']';
2078 }else if( c=='(' ){
2079 nParen++;
2080 }else if( c==')' ){
2081 nParen--;
2082 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00002083 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00002084 j = 0;
2085 }
2086 }
2087 z[j++] = c;
2088 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
2089 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00002090 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00002091 j = 0;
2092 nLine++;
2093 while( IsSpace(z[i+1]) ){ i++; }
2094 }
2095 }
2096 z[j] = 0;
2097 }
drh79f20e92016-12-13 23:22:39 +00002098 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00002099 sqlite3_free(z);
2100 break;
2101 }
drh75897232000-05-29 14:26:00 +00002102 case MODE_List: {
2103 if( p->cnt++==0 && p->showHeader ){
2104 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002105 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00002106 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00002107 }
2108 }
drh6a535342001-10-19 16:44:56 +00002109 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002110 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00002111 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00002112 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00002113 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00002114 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00002115 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00002116 }else{
drhe05461c2015-12-30 13:36:57 +00002117 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00002118 }
drh75897232000-05-29 14:26:00 +00002119 }
2120 break;
2121 }
drh1e5d0e92000-05-31 23:33:17 +00002122 case MODE_Html: {
2123 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00002124 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002125 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002126 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00002127 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00002128 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00002129 }
mistachkinaae280e2015-12-31 19:06:24 +00002130 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002131 }
drh6a535342001-10-19 16:44:56 +00002132 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00002133 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002134 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002135 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00002136 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00002137 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00002138 }
mistachkinaae280e2015-12-31 19:06:24 +00002139 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002140 break;
2141 }
drhfeac5f82004-08-01 00:10:45 +00002142 case MODE_Tcl: {
2143 if( p->cnt++==0 && p->showHeader ){
2144 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002145 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00002146 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002147 }
drhe05461c2015-12-30 13:36:57 +00002148 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002149 }
2150 if( azArg==0 ) break;
2151 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00002152 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00002153 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002154 }
drhe05461c2015-12-30 13:36:57 +00002155 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002156 break;
2157 }
drh8e64d1c2004-10-07 00:32:39 +00002158 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00002159 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002160 if( p->cnt++==0 && p->showHeader ){
2161 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002162 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00002163 }
drhe05461c2015-12-30 13:36:57 +00002164 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002165 }
drh40253262014-10-17 21:35:05 +00002166 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00002167 for(i=0; i<nArg; i++){
2168 output_csv(p, azArg[i], i<nArg-1);
2169 }
drhe05461c2015-12-30 13:36:57 +00002170 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002171 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002172 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002173 break;
2174 }
drh28bd4bc2000-06-15 15:57:22 +00002175 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00002176 if( azArg==0 ) break;
drh13fe1382017-04-08 13:42:55 +00002177 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2178 if( p->showHeader ){
2179 raw_printf(p->out,"(");
2180 for(i=0; i<nArg; i++){
2181 if( i>0 ) raw_printf(p->out, ",");
2182 if( quoteChar(azCol[i]) ){
2183 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2184 utf8_printf(p->out, "%s", z);
2185 sqlite3_free(z);
2186 }else{
2187 raw_printf(p->out, "%s", azCol[i]);
drh41f5f6e2016-10-21 17:39:30 +00002188 }
mistachkin151c75a2015-04-07 21:16:40 +00002189 }
drh13fe1382017-04-08 13:42:55 +00002190 raw_printf(p->out,")");
2191 }
2192 p->cnt++;
2193 for(i=0; i<nArg; i++){
2194 raw_printf(p->out, i>0 ? "," : " VALUES(");
2195 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2196 utf8_printf(p->out,"NULL");
2197 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2198 output_quoted_escaped_string(p->out, azArg[i]);
2199 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2200 utf8_printf(p->out,"%s", azArg[i]);
2201 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2202 char z[50];
2203 double r = sqlite3_column_double(p->pStmt, i);
2204 sqlite3_snprintf(50,z,"%!.20g", r);
2205 raw_printf(p->out, "%s", z);
2206 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2207 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2208 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2209 output_hex_blob(p->out, pBlob, nBlob);
2210 }else if( isNumber(azArg[i], 0) ){
2211 utf8_printf(p->out,"%s", azArg[i]);
2212 }else{
2213 output_quoted_escaped_string(p->out, azArg[i]);
2214 }
2215 }
2216 raw_printf(p->out,");\n");
2217 break;
2218 }
2219 case MODE_Quote: {
2220 if( azArg==0 ) break;
2221 if( p->cnt==0 && p->showHeader ){
drh59ce2c42016-11-03 13:12:28 +00002222 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00002223 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00002224 output_quoted_string(p->out, azCol[i]);
2225 }
mistachkin2f9a6132016-11-11 05:19:45 +00002226 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002227 }
drh59ce2c42016-11-03 13:12:28 +00002228 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002229 for(i=0; i<nArg; i++){
drh13fe1382017-04-08 13:42:55 +00002230 if( i>0 ) raw_printf(p->out, ",");
shanead6b8d02009-10-22 18:12:58 +00002231 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
drh13fe1382017-04-08 13:42:55 +00002232 utf8_printf(p->out,"NULL");
shanead6b8d02009-10-22 18:12:58 +00002233 }else if( aiType && aiType[i]==SQLITE_TEXT ){
shanead6b8d02009-10-22 18:12:58 +00002234 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002235 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drh13fe1382017-04-08 13:42:55 +00002236 utf8_printf(p->out,"%s", azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002237 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2238 char z[50];
2239 double r = sqlite3_column_double(p->pStmt, i);
2240 sqlite3_snprintf(50,z,"%!.20g", r);
drh13fe1382017-04-08 13:42:55 +00002241 raw_printf(p->out, "%s", z);
shane626a6e42009-10-22 17:30:15 +00002242 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2243 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2244 int nBlob = sqlite3_column_bytes(p->pStmt, i);
shane626a6e42009-10-22 17:30:15 +00002245 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002246 }else if( isNumber(azArg[i], 0) ){
drh13fe1382017-04-08 13:42:55 +00002247 utf8_printf(p->out,"%s", azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002248 }else{
drh28bd4bc2000-06-15 15:57:22 +00002249 output_quoted_string(p->out, azArg[i]);
2250 }
2251 }
drh13fe1382017-04-08 13:42:55 +00002252 raw_printf(p->out,"\n");
drh6a535342001-10-19 16:44:56 +00002253 break;
drh28bd4bc2000-06-15 15:57:22 +00002254 }
mistachkin636bf9f2014-07-19 20:15:16 +00002255 case MODE_Ascii: {
2256 if( p->cnt++==0 && p->showHeader ){
2257 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002258 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2259 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002260 }
drhe05461c2015-12-30 13:36:57 +00002261 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002262 }
2263 if( azArg==0 ) break;
2264 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002265 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2266 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002267 }
drhe05461c2015-12-30 13:36:57 +00002268 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002269 break;
2270 }
persicom1d0b8722002-04-18 02:53:04 +00002271 }
drh75897232000-05-29 14:26:00 +00002272 return 0;
2273}
2274
2275/*
shane626a6e42009-10-22 17:30:15 +00002276** This is the callback routine that the SQLite library
2277** invokes for each row of a query result.
2278*/
2279static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2280 /* since we don't have type info, call the shell_callback with a NULL value */
2281 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2282}
2283
drhfb546af2017-03-09 22:00:33 +00002284/*
2285** This is the callback routine from sqlite3_exec() that appends all
2286** output onto the end of a ShellText object.
2287*/
2288static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2289 ShellText *p = (ShellText*)pArg;
2290 int i;
drh2fb79e92017-03-25 12:08:11 +00002291 UNUSED_PARAMETER(az);
drhfb546af2017-03-09 22:00:33 +00002292 if( p->n ) appendText(p, "|", 0);
2293 for(i=0; i<nArg; i++){
2294 if( i ) appendText(p, ",", 0);
2295 if( azArg[i] ) appendText(p, azArg[i], 0);
2296 }
2297 return 0;
2298}
2299
2300/*
2301** Generate an appropriate SELFTEST table in the main database.
2302*/
2303static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00002304 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00002305 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00002306 "SAVEPOINT selftest_init;\n"
2307 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00002308 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2309 " op TEXT,\n" /* Operator: memo run */
2310 " cmd TEXT,\n" /* Command text */
2311 " ans TEXT\n" /* Desired answer */
2312 ");"
drhf157d102017-03-10 01:05:38 +00002313 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2314 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2315 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2316 " 'memo','Tests generated by --init');\n"
2317 "INSERT INTO [_shell$self]\n"
2318 " SELECT 'run',\n"
2319 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2320 "FROM sqlite_master ORDER BY 2'',224))',\n"
2321 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2322 "FROM sqlite_master ORDER BY 2',224));\n"
2323 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002324 " SELECT 'run',"
2325 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2326 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2327 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2328 " FROM (\n"
2329 " SELECT name FROM sqlite_master\n"
2330 " WHERE type='table'\n"
2331 " AND name<>'selftest'\n"
2332 " AND coalesce(rootpage,0)>0\n"
2333 " )\n"
2334 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00002335 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002336 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00002337 "INSERT INTO selftest(tno,op,cmd,ans)"
2338 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2339 "DROP TABLE [_shell$self];"
2340 ,0,0,&zErrMsg);
2341 if( zErrMsg ){
2342 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2343 sqlite3_free(zErrMsg);
2344 }
2345 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00002346}
2347
drhf42d3182017-03-08 12:25:18 +00002348
shane626a6e42009-10-22 17:30:15 +00002349/*
drhdcd87a92014-08-18 13:45:42 +00002350** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00002351** the name of the table given. Escape any quote characters in the
2352** table name.
2353*/
drhdcd87a92014-08-18 13:45:42 +00002354static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00002355 int i, n;
drhf42d3182017-03-08 12:25:18 +00002356 int cQuote;
drh33048c02001-10-01 14:29:22 +00002357 char *z;
2358
2359 if( p->zDestTable ){
2360 free(p->zDestTable);
2361 p->zDestTable = 0;
2362 }
2363 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00002364 cQuote = quoteChar(zName);
2365 n = strlen30(zName);
drh45e7d7d2017-06-24 13:31:40 +00002366 if( cQuote ) n += n+2;
drh33048c02001-10-01 14:29:22 +00002367 z = p->zDestTable = malloc( n+1 );
2368 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002369 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00002370 exit(1);
2371 }
2372 n = 0;
drhf42d3182017-03-08 12:25:18 +00002373 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002374 for(i=0; zName[i]; i++){
2375 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00002376 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002377 }
drhf42d3182017-03-08 12:25:18 +00002378 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002379 z[n] = 0;
2380}
2381
drhdd3d4592004-08-30 01:54:05 +00002382
2383/*
drhb21a8e42012-01-28 21:08:51 +00002384** Execute a query statement that will generate SQL output. Print
2385** the result columns, comma-separated, on a line and then add a
2386** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00002387**
drhb21a8e42012-01-28 21:08:51 +00002388** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00002389** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00002390** "--" comment occurs at the end of the statement, the comment
2391** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00002392*/
drh157e29a2009-05-21 15:15:00 +00002393static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00002394 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00002395 const char *zSelect, /* SELECT statement to extract content */
2396 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00002397){
drhdd3d4592004-08-30 01:54:05 +00002398 sqlite3_stmt *pSelect;
2399 int rc;
drhb21a8e42012-01-28 21:08:51 +00002400 int nResult;
2401 int i;
2402 const char *z;
drhc7181902014-02-27 15:04:13 +00002403 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00002404 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00002405 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2406 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002407 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00002408 return rc;
2409 }
2410 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00002411 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00002412 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00002413 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00002414 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00002415 zFirstRow = 0;
2416 }
drhb21a8e42012-01-28 21:08:51 +00002417 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00002418 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00002419 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00002420 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00002421 }
2422 if( z==0 ) z = "";
2423 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2424 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00002425 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00002426 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002427 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00002428 }
drhdd3d4592004-08-30 01:54:05 +00002429 rc = sqlite3_step(pSelect);
2430 }
drh2f464a02011-10-13 00:41:49 +00002431 rc = sqlite3_finalize(pSelect);
2432 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00002433 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2434 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002435 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00002436 }
2437 return rc;
drhdd3d4592004-08-30 01:54:05 +00002438}
2439
shane626a6e42009-10-22 17:30:15 +00002440/*
2441** Allocate space and save off current error string.
2442*/
2443static char *save_err_msg(
2444 sqlite3 *db /* Database to query */
2445){
2446 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00002447 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00002448 if( zErrMsg ){
2449 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2450 }
2451 return zErrMsg;
2452}
2453
drh34784902016-02-27 17:12:36 +00002454#ifdef __linux__
2455/*
2456** Attempt to display I/O stats on Linux using /proc/PID/io
2457*/
2458static void displayLinuxIoStats(FILE *out){
2459 FILE *in;
2460 char z[200];
2461 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2462 in = fopen(z, "rb");
2463 if( in==0 ) return;
2464 while( fgets(z, sizeof(z), in)!=0 ){
2465 static const struct {
2466 const char *zPattern;
2467 const char *zDesc;
2468 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00002469 { "rchar: ", "Bytes received by read():" },
2470 { "wchar: ", "Bytes sent to write():" },
2471 { "syscr: ", "Read() system calls:" },
2472 { "syscw: ", "Write() system calls:" },
2473 { "read_bytes: ", "Bytes read from storage:" },
2474 { "write_bytes: ", "Bytes written to storage:" },
2475 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00002476 };
2477 int i;
2478 for(i=0; i<ArraySize(aTrans); i++){
2479 int n = (int)strlen(aTrans[i].zPattern);
2480 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00002481 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00002482 break;
2483 }
2484 }
2485 }
2486 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00002487}
drh34784902016-02-27 17:12:36 +00002488#endif
2489
drha2df53b2017-03-10 14:36:10 +00002490/*
2491** Display a single line of status using 64-bit values.
2492*/
2493static void displayStatLine(
2494 ShellState *p, /* The shell context */
2495 char *zLabel, /* Label for this one line */
2496 char *zFormat, /* Format for the result */
2497 int iStatusCtrl, /* Which status to display */
2498 int bReset /* True to reset the stats */
2499){
2500 sqlite3_int64 iCur = -1;
2501 sqlite3_int64 iHiwtr = -1;
2502 int i, nPercent;
2503 char zLine[200];
2504 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2505 for(i=0, nPercent=0; zFormat[i]; i++){
2506 if( zFormat[i]=='%' ) nPercent++;
2507 }
2508 if( nPercent>1 ){
2509 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2510 }else{
2511 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2512 }
2513 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2514}
drh34784902016-02-27 17:12:36 +00002515
shane626a6e42009-10-22 17:30:15 +00002516/*
shaneh642d8b82010-07-28 16:05:34 +00002517** Display memory stats.
2518*/
2519static int display_stats(
2520 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00002521 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00002522 int bReset /* True to reset the stats */
2523){
2524 int iCur;
2525 int iHiwtr;
2526
2527 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00002528 displayStatLine(pArg, "Memory Used:",
2529 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2530 displayStatLine(pArg, "Number of Outstanding Allocations:",
2531 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00002532 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00002533 displayStatLine(pArg, "Number of Pcache Pages Used:",
2534 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002535 }
drha2df53b2017-03-10 14:36:10 +00002536 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2537 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh44dec872014-08-30 15:49:25 +00002538 if( pArg->shellFlgs & SHFLG_Scratch ){
drha2df53b2017-03-10 14:36:10 +00002539 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2540 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002541 }
drha2df53b2017-03-10 14:36:10 +00002542 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2543 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2544 displayStatLine(pArg, "Largest Allocation:",
2545 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2546 displayStatLine(pArg, "Largest Pcache Allocation:",
2547 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2548 displayStatLine(pArg, "Largest Scratch Allocation:",
2549 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002550#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00002551 displayStatLine(pArg, "Deepest Parser Stack:",
2552 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002553#endif
2554 }
2555
2556 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00002557 if( pArg->shellFlgs & SHFLG_Lookaside ){
2558 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00002559 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2560 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002561 raw_printf(pArg->out,
2562 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00002563 iCur, iHiwtr);
2564 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2565 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002566 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2567 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002568 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2569 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002570 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2571 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002572 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2573 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002574 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2575 iHiwtr);
drh44dec872014-08-30 15:49:25 +00002576 }
shaneh642d8b82010-07-28 16:05:34 +00002577 iHiwtr = iCur = -1;
2578 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002579 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2580 iCur);
drh4ace5362014-11-10 14:42:28 +00002581 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00002582 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00002583 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00002584 iHiwtr = iCur = -1;
2585 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002586 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002587 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00002588 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002589 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00002590 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00002591 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002592 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002593 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002594 iHiwtr = iCur = -1;
2595 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002596 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002597 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002598 }
2599
2600 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00002601 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2602 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002603 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002604 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002605 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00002606 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002607 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00002608 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002609 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002610 }
2611
drh34784902016-02-27 17:12:36 +00002612#ifdef __linux__
2613 displayLinuxIoStats(pArg->out);
2614#endif
2615
dan5a790282015-08-07 20:06:14 +00002616 /* Do not remove this machine readable comment: extra-stats-output-here */
2617
shaneh642d8b82010-07-28 16:05:34 +00002618 return 0;
2619}
2620
2621/*
dan8d1edb92014-11-05 09:07:28 +00002622** Display scan stats.
2623*/
2624static void display_scanstats(
2625 sqlite3 *db, /* Database to query */
2626 ShellState *pArg /* Pointer to ShellState */
2627){
drhf5ed7ad2015-06-15 14:43:25 +00002628#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2629 UNUSED_PARAMETER(db);
2630 UNUSED_PARAMETER(pArg);
2631#else
drh15f23c22014-11-06 12:46:16 +00002632 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00002633 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00002634 mx = 0;
2635 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00002636 double rEstLoop = 1.0;
2637 for(i=n=0; 1; i++){
2638 sqlite3_stmt *p = pArg->pStmt;
2639 sqlite3_int64 nLoop, nVisit;
2640 double rEst;
2641 int iSid;
2642 const char *zExplain;
2643 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2644 break;
2645 }
2646 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00002647 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00002648 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00002649 if( n==0 ){
2650 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00002651 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00002652 }
drh42f30bc2014-11-06 12:08:21 +00002653 n++;
2654 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2655 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2656 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00002657 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00002658 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00002659 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00002660 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00002661 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00002662 );
dan8d1edb92014-11-05 09:07:28 +00002663 }
dan8d1edb92014-11-05 09:07:28 +00002664 }
mistachkinaae280e2015-12-31 19:06:24 +00002665 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00002666#endif
dan8d1edb92014-11-05 09:07:28 +00002667}
2668
2669/*
dana98bf362013-11-13 18:35:01 +00002670** Parameter azArray points to a zero-terminated array of strings. zStr
2671** points to a single nul-terminated string. Return non-zero if zStr
2672** is equal, according to strcmp(), to any of the strings in the array.
2673** Otherwise, return zero.
2674*/
2675static int str_in_array(const char *zStr, const char **azArray){
2676 int i;
2677 for(i=0; azArray[i]; i++){
2678 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2679 }
2680 return 0;
2681}
2682
2683/*
2684** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00002685** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00002686** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00002687**
2688** The indenting rules are:
2689**
2690** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2691** all opcodes that occur between the p2 jump destination and the opcode
2692** itself by 2 spaces.
2693**
drh01752bc2013-11-14 23:59:33 +00002694** * For each "Goto", if the jump destination is earlier in the program
2695** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00002696** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00002697** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00002698** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00002699** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00002700*/
drhdcd87a92014-08-18 13:45:42 +00002701static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00002702 const char *zSql; /* The text of the SQL statement */
2703 const char *z; /* Used to check if this is an EXPLAIN */
2704 int *abYield = 0; /* True if op is an OP_Yield */
2705 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00002706 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00002707
drh8ad0de32014-03-20 18:45:27 +00002708 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2709 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00002710 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2711 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00002712 const char *azGoto[] = { "Goto", 0 };
2713
2714 /* Try to figure out if this is really an EXPLAIN statement. If this
2715 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00002716 if( sqlite3_column_count(pSql)!=8 ){
2717 p->cMode = p->mode;
2718 return;
2719 }
dana98bf362013-11-13 18:35:01 +00002720 zSql = sqlite3_sql(pSql);
2721 if( zSql==0 ) return;
2722 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00002723 if( sqlite3_strnicmp(z, "explain", 7) ){
2724 p->cMode = p->mode;
2725 return;
2726 }
dana98bf362013-11-13 18:35:01 +00002727
2728 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2729 int i;
danc4650bb2013-11-18 08:41:06 +00002730 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00002731 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00002732
2733 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2734 ** p2 is an instruction address, set variable p2op to the index of that
2735 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2736 ** the current instruction is part of a sub-program generated by an
2737 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00002738 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00002739 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00002740
2741 /* Grow the p->aiIndent array as required */
2742 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00002743 if( iOp==0 ){
2744 /* Do further verfication that this is explain output. Abort if
2745 ** it is not */
2746 static const char *explainCols[] = {
2747 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2748 int jj;
2749 for(jj=0; jj<ArraySize(explainCols); jj++){
2750 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2751 p->cMode = p->mode;
2752 sqlite3_reset(pSql);
2753 return;
2754 }
2755 }
2756 }
dana98bf362013-11-13 18:35:01 +00002757 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00002758 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2759 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00002760 }
2761 abYield[iOp] = str_in_array(zOp, azYield);
2762 p->aiIndent[iOp] = 0;
2763 p->nIndent = iOp+1;
2764
2765 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00002766 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002767 }
drhfe705102014-03-06 13:38:37 +00002768 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2769 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2770 ){
drheacd29d2016-04-15 15:03:27 +00002771 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002772 }
2773 }
2774
danc4650bb2013-11-18 08:41:06 +00002775 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002776 sqlite3_free(abYield);
2777 sqlite3_reset(pSql);
2778}
2779
2780/*
2781** Free the array allocated by explain_data_prepare().
2782*/
drhdcd87a92014-08-18 13:45:42 +00002783static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00002784 sqlite3_free(p->aiIndent);
2785 p->aiIndent = 0;
2786 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00002787 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002788}
2789
2790/*
drheacd29d2016-04-15 15:03:27 +00002791** Disable and restore .wheretrace and .selecttrace settings.
2792*/
2793#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2794extern int sqlite3SelectTrace;
2795static int savedSelectTrace;
2796#endif
2797#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2798extern int sqlite3WhereTrace;
2799static int savedWhereTrace;
2800#endif
2801static void disable_debug_trace_modes(void){
2802#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2803 savedSelectTrace = sqlite3SelectTrace;
2804 sqlite3SelectTrace = 0;
2805#endif
2806#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2807 savedWhereTrace = sqlite3WhereTrace;
2808 sqlite3WhereTrace = 0;
2809#endif
2810}
2811static void restore_debug_trace_modes(void){
2812#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2813 sqlite3SelectTrace = savedSelectTrace;
2814#endif
2815#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2816 sqlite3WhereTrace = savedWhereTrace;
2817#endif
2818}
2819
2820/*
2821** Run a prepared statement
2822*/
2823static void exec_prepared_stmt(
2824 ShellState *pArg, /* Pointer to ShellState */
2825 sqlite3_stmt *pStmt, /* Statment to run */
2826 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2827){
2828 int rc;
2829
2830 /* perform the first step. this will tell us if we
2831 ** have a result set or not and how wide it is.
2832 */
2833 rc = sqlite3_step(pStmt);
2834 /* if we have a result set... */
2835 if( SQLITE_ROW == rc ){
2836 /* if we have a callback... */
2837 if( xCallback ){
2838 /* allocate space for col name ptr, value ptr, and type */
2839 int nCol = sqlite3_column_count(pStmt);
2840 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2841 if( !pData ){
2842 rc = SQLITE_NOMEM;
2843 }else{
2844 char **azCols = (char **)pData; /* Names of result columns */
2845 char **azVals = &azCols[nCol]; /* Results */
2846 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2847 int i, x;
2848 assert(sizeof(int) <= sizeof(char *));
2849 /* save off ptrs to column names */
2850 for(i=0; i<nCol; i++){
2851 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2852 }
2853 do{
2854 /* extract the data and data types */
2855 for(i=0; i<nCol; i++){
2856 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2857 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2858 azVals[i] = "";
2859 }else{
2860 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2861 }
2862 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2863 rc = SQLITE_NOMEM;
2864 break; /* from for */
2865 }
2866 } /* end for */
2867
2868 /* if data and types extracted successfully... */
2869 if( SQLITE_ROW == rc ){
2870 /* call the supplied callback with the result row data */
2871 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2872 rc = SQLITE_ABORT;
2873 }else{
2874 rc = sqlite3_step(pStmt);
2875 }
2876 }
2877 } while( SQLITE_ROW == rc );
2878 sqlite3_free(pData);
2879 }
2880 }else{
2881 do{
2882 rc = sqlite3_step(pStmt);
2883 } while( rc == SQLITE_ROW );
2884 }
2885 }
2886}
2887
2888/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002889** Execute a statement or set of statements. Print
2890** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00002891** set via the supplied callback.
2892**
mistachkin1fe36bb2016-04-04 02:16:44 +00002893** This is very similar to SQLite's built-in sqlite3_exec()
2894** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00002895** and callback data argument.
2896*/
2897static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00002898 sqlite3 *db, /* An open database */
2899 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00002900 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00002901 /* (not the same as sqlite3_exec) */
2902 ShellState *pArg, /* Pointer to ShellState */
2903 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00002904){
dan4564ced2010-01-05 04:59:56 +00002905 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2906 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00002907 int rc2;
dan4564ced2010-01-05 04:59:56 +00002908 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00002909
2910 if( pzErrMsg ){
2911 *pzErrMsg = NULL;
2912 }
2913
shaneb9fc17d2009-10-22 21:23:35 +00002914 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00002915 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00002916 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2917 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00002918 if( pzErrMsg ){
2919 *pzErrMsg = save_err_msg(db);
2920 }
2921 }else{
shaneb9fc17d2009-10-22 21:23:35 +00002922 if( !pStmt ){
2923 /* this happens for a comment or white-space */
2924 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002925 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00002926 continue;
2927 }
drheacd29d2016-04-15 15:03:27 +00002928 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00002929 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00002930 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00002931
shaneh642d8b82010-07-28 16:05:34 +00002932 /* save off the prepared statment handle and reset row count */
2933 if( pArg ){
2934 pArg->pStmt = pStmt;
2935 pArg->cnt = 0;
2936 }
2937
shanehb7977c52010-01-18 18:17:10 +00002938 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00002939 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00002940 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00002941 }
shanehb7977c52010-01-18 18:17:10 +00002942
drhefbf3b12014-02-28 20:47:24 +00002943 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00002944 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00002945 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00002946 char *zEQP;
2947 disable_debug_trace_modes();
2948 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00002949 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2950 if( rc==SQLITE_OK ){
2951 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00002952 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2953 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2954 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00002955 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00002956 }
2957 }
2958 sqlite3_finalize(pExplain);
2959 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00002960 if( pArg->autoEQP>=2 ){
2961 /* Also do an EXPLAIN for ".eqp full" mode */
2962 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2963 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2964 if( rc==SQLITE_OK ){
2965 pArg->cMode = MODE_Explain;
2966 explain_data_prepare(pArg, pExplain);
2967 exec_prepared_stmt(pArg, pExplain, xCallback);
2968 explain_data_delete(pArg);
2969 }
2970 sqlite3_finalize(pExplain);
2971 sqlite3_free(zEQP);
2972 }
2973 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00002974 }
2975
drh700c2522016-02-09 18:39:25 +00002976 if( pArg ){
2977 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00002978 if( pArg->autoExplain
2979 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00002980 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00002981 ){
2982 pArg->cMode = MODE_Explain;
2983 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002984
drh700c2522016-02-09 18:39:25 +00002985 /* If the shell is currently in ".explain" mode, gather the extra
2986 ** data required to add indents to the output.*/
2987 if( pArg->cMode==MODE_Explain ){
2988 explain_data_prepare(pArg, pStmt);
2989 }
dana98bf362013-11-13 18:35:01 +00002990 }
2991
drheacd29d2016-04-15 15:03:27 +00002992 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00002993 explain_data_delete(pArg);
2994
shaneh642d8b82010-07-28 16:05:34 +00002995 /* print usage stats if stats on */
2996 if( pArg && pArg->statsOn ){
2997 display_stats(db, pArg, 0);
2998 }
2999
dan8d1edb92014-11-05 09:07:28 +00003000 /* print loop-counters if required */
3001 if( pArg && pArg->scanstatsOn ){
3002 display_scanstats(db, pArg);
3003 }
3004
mistachkin1fe36bb2016-04-04 02:16:44 +00003005 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00003006 ** copy of the error message. Otherwise, set zSql to point to the
3007 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00003008 rc2 = sqlite3_finalize(pStmt);
3009 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00003010 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00003011 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00003012 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00003013 }else if( pzErrMsg ){
3014 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00003015 }
shaneh642d8b82010-07-28 16:05:34 +00003016
3017 /* clear saved stmt handle */
3018 if( pArg ){
3019 pArg->pStmt = NULL;
3020 }
shane626a6e42009-10-22 17:30:15 +00003021 }
shaneb9fc17d2009-10-22 21:23:35 +00003022 } /* end while */
shane626a6e42009-10-22 17:30:15 +00003023
3024 return rc;
3025}
3026
drhe611f142017-03-08 11:44:00 +00003027/*
3028** Release memory previously allocated by tableColumnList().
3029*/
3030static void freeColumnList(char **azCol){
3031 int i;
3032 for(i=1; azCol[i]; i++){
3033 sqlite3_free(azCol[i]);
3034 }
3035 /* azCol[0] is a static string */
3036 sqlite3_free(azCol);
3037}
3038
3039/*
3040** Return a list of pointers to strings which are the names of all
3041** columns in table zTab. The memory to hold the names is dynamically
3042** allocated and must be released by the caller using a subsequent call
3043** to freeColumnList().
3044**
3045** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3046** value that needs to be preserved, then azCol[0] is filled in with the
3047** name of the rowid column.
3048**
3049** The first regular column in the table is azCol[1]. The list is terminated
3050** by an entry with azCol[i]==0.
3051*/
3052static char **tableColumnList(ShellState *p, const char *zTab){
3053 char **azCol = 0;
3054 sqlite3_stmt *pStmt;
3055 char *zSql;
3056 int nCol = 0;
3057 int nAlloc = 0;
3058 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3059 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00003060 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00003061 int rc;
3062
3063 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3064 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3065 sqlite3_free(zSql);
3066 if( rc ) return 0;
3067 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3068 if( nCol>=nAlloc-2 ){
3069 nAlloc = nAlloc*2 + nCol + 10;
3070 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3071 if( azCol==0 ){
3072 raw_printf(stderr, "Error: out of memory\n");
3073 exit(1);
3074 }
3075 }
3076 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3077 if( sqlite3_column_int(pStmt, 5) ){
3078 nPK++;
3079 if( nPK==1
3080 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
mistachkine16a3502017-05-29 03:48:13 +00003081 "INTEGER")==0
drhe611f142017-03-08 11:44:00 +00003082 ){
3083 isIPK = 1;
3084 }else{
3085 isIPK = 0;
3086 }
3087 }
3088 }
3089 sqlite3_finalize(pStmt);
3090 azCol[0] = 0;
3091 azCol[nCol+1] = 0;
3092
3093 /* The decision of whether or not a rowid really needs to be preserved
3094 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3095 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3096 ** rowids on tables where the rowid is inaccessible because there are other
3097 ** columns in the table named "rowid", "_rowid_", and "oid".
3098 */
3099 if( preserveRowid && isIPK ){
3100 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3101 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3102 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3103 ** ROWID aliases. To distinguish these cases, check to see if
3104 ** there is a "pk" entry in "PRAGMA index_list". There will be
3105 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3106 */
3107 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3108 " WHERE origin='pk'", zTab);
3109 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3110 sqlite3_free(zSql);
3111 if( rc ){
3112 freeColumnList(azCol);
3113 return 0;
3114 }
3115 rc = sqlite3_step(pStmt);
3116 sqlite3_finalize(pStmt);
3117 preserveRowid = rc==SQLITE_ROW;
3118 }
3119 if( preserveRowid ){
3120 /* Only preserve the rowid if we can find a name to use for the
3121 ** rowid */
3122 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3123 int i, j;
3124 for(j=0; j<3; j++){
3125 for(i=1; i<=nCol; i++){
3126 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3127 }
3128 if( i>nCol ){
3129 /* At this point, we know that azRowid[j] is not the name of any
3130 ** ordinary column in the table. Verify that azRowid[j] is a valid
3131 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3132 ** tables will fail this last check */
drhe611f142017-03-08 11:44:00 +00003133 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3134 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3135 break;
3136 }
3137 }
3138 }
3139 return azCol;
3140}
3141
drh33048c02001-10-01 14:29:22 +00003142/*
drhf8563c02017-03-09 18:13:52 +00003143** Toggle the reverse_unordered_selects setting.
3144*/
3145static void toggleSelectOrder(sqlite3 *db){
3146 sqlite3_stmt *pStmt = 0;
3147 int iSetting = 0;
3148 char zStmt[100];
3149 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3150 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3151 iSetting = sqlite3_column_int(pStmt, 0);
3152 }
3153 sqlite3_finalize(pStmt);
3154 sqlite3_snprintf(sizeof(zStmt), zStmt,
3155 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3156 sqlite3_exec(db, zStmt, 0, 0, 0);
3157}
3158
3159/*
drh4c653a02000-06-07 01:27:47 +00003160** This is a different callback routine used for dumping the database.
3161** Each row received by this callback consists of a table name,
3162** the table type ("index" or "table") and SQL to create the table.
3163** This routine should print text sufficient to recreate the table.
3164*/
drh701ff6a2017-03-22 12:51:34 +00003165static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
danielk19772a02e332004-06-05 08:04:36 +00003166 int rc;
3167 const char *zTable;
3168 const char *zType;
3169 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00003170 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00003171
drh701ff6a2017-03-22 12:51:34 +00003172 UNUSED_PARAMETER(azNotUsed);
drh4c653a02000-06-07 01:27:47 +00003173 if( nArg!=3 ) return 1;
danielk19772a02e332004-06-05 08:04:36 +00003174 zTable = azArg[0];
3175 zType = azArg[1];
3176 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00003177
drh00b950d2005-09-11 02:03:03 +00003178 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00003179 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00003180 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003181 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00003182 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3183 return 0;
drh45e29d82006-11-20 16:21:10 +00003184 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3185 char *zIns;
3186 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00003187 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00003188 p->writableSchema = 1;
3189 }
3190 zIns = sqlite3_mprintf(
3191 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3192 "VALUES('table','%q','%q',0,'%q');",
3193 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00003194 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00003195 sqlite3_free(zIns);
3196 return 0;
drh00b950d2005-09-11 02:03:03 +00003197 }else{
drh79f20e92016-12-13 23:22:39 +00003198 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00003199 }
danielk19772a02e332004-06-05 08:04:36 +00003200
3201 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00003202 ShellText sSelect;
3203 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00003204 char **azCol;
3205 int i;
3206 char *savedDestTable;
3207 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00003208
drhe611f142017-03-08 11:44:00 +00003209 azCol = tableColumnList(p, zTable);
3210 if( azCol==0 ){
3211 p->nErr++;
3212 return 0;
danielk19772a02e332004-06-05 08:04:36 +00003213 }
3214
drhbf92ec02012-03-22 12:50:34 +00003215 /* Always quote the table name, even if it appears to be pure ascii,
3216 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00003217 initText(&sTable);
3218 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003219 /* If preserving the rowid, add a column list after the table name.
3220 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3221 ** instead of the usual "INSERT INTO tab VALUES(...)".
3222 */
3223 if( azCol[0] ){
3224 appendText(&sTable, "(", 0);
3225 appendText(&sTable, azCol[0], 0);
3226 for(i=1; azCol[i]; i++){
3227 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003228 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003229 }
drhe611f142017-03-08 11:44:00 +00003230 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003231 }
danielk19772a02e332004-06-05 08:04:36 +00003232
drhe611f142017-03-08 11:44:00 +00003233 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003234 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003235 appendText(&sSelect, "SELECT ", 0);
3236 if( azCol[0] ){
3237 appendText(&sSelect, azCol[0], 0);
3238 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003239 }
drhe611f142017-03-08 11:44:00 +00003240 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003241 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003242 if( azCol[i+1] ){
3243 appendText(&sSelect, ",", 0);
3244 }
3245 }
3246 freeColumnList(azCol);
3247 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003248 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003249
3250 savedDestTable = p->zDestTable;
3251 savedMode = p->mode;
3252 p->zDestTable = sTable.z;
3253 p->mode = p->cMode = MODE_Insert;
3254 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003255 if( (rc&0xff)==SQLITE_CORRUPT ){
3256 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3257 toggleSelectOrder(p->db);
3258 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3259 toggleSelectOrder(p->db);
3260 }
drhe611f142017-03-08 11:44:00 +00003261 p->zDestTable = savedDestTable;
3262 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003263 freeText(&sTable);
3264 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003265 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003266 }
drh4c653a02000-06-07 01:27:47 +00003267 return 0;
3268}
3269
3270/*
drh45e29d82006-11-20 16:21:10 +00003271** Run zQuery. Use dump_callback() as the callback routine so that
3272** the contents of the query are output as SQL statements.
3273**
drhdd3d4592004-08-30 01:54:05 +00003274** If we get a SQLITE_CORRUPT error, rerun the query after appending
3275** "ORDER BY rowid DESC" to the end.
3276*/
3277static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003278 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003279 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003280){
3281 int rc;
drh2f464a02011-10-13 00:41:49 +00003282 char *zErr = 0;
3283 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003284 if( rc==SQLITE_CORRUPT ){
3285 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00003286 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00003287 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00003288 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00003289 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003290 sqlite3_free(zErr);
3291 zErr = 0;
3292 }
drhdd3d4592004-08-30 01:54:05 +00003293 zQ2 = malloc( len+100 );
3294 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00003295 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00003296 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3297 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003298 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003299 }else{
3300 rc = SQLITE_CORRUPT;
3301 }
3302 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00003303 free(zQ2);
3304 }
3305 return rc;
3306}
3307
3308/*
drh75897232000-05-29 14:26:00 +00003309** Text of a help message
3310*/
persicom1d0b8722002-04-18 02:53:04 +00003311static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00003312#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00003313 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00003314#endif
drh9ff849f2009-02-04 20:55:57 +00003315 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00003316 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00003317 ".binary on|off Turn binary output on or off. Default OFF\n"
drh453ca042017-05-22 18:00:34 +00003318 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
drhdf12f1c2015-12-07 21:46:19 +00003319 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00003320 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00003321 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00003322 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00003323 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00003324 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00003325 " If TABLE specified, only dump tables matching\n"
3326 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00003327 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00003328 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00003329 ".exit Exit this program\n"
drh700c2522016-02-09 18:39:25 +00003330 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
drh4926fec2016-04-13 15:33:42 +00003331 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003332 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003333 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003334 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003335#ifndef SQLITE_OMIT_TEST_CONTROL
3336 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3337#endif
drh0e55db12015-02-06 14:51:13 +00003338 ".indexes ?TABLE? Show names of all indexes\n"
3339 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003340 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003341#ifdef SQLITE_ENABLE_IOTRACE
3342 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3343#endif
drh1a513372015-05-02 17:40:23 +00003344 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003345 ".lint OPTIONS Report potential schema issues. Options:\n"
3346 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003347#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003348 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003349#endif
drh127f9d72010-02-23 01:47:00 +00003350 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003351 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003352 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003353 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003354 " column Left-aligned columns. (See .width)\n"
3355 " html HTML <table> code\n"
3356 " insert SQL insert statements for TABLE\n"
3357 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003358 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003359 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003360 " tabs Tab-separated values\n"
3361 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003362 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003363 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkine16a3502017-05-29 03:48:13 +00003364 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3365 " The --new option starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003366 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003367 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003368 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003369 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003370 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003371 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003372 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003373 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003374 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3375 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00003376 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00003377 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3378 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003379#if defined(SQLITE_ENABLE_SESSION)
3380 ".session CMD ... Create or control sessions\n"
3381#endif
drh1554bc82017-03-08 16:10:34 +00003382 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003383 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003384 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003385 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003386 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003387 ".tables ?TABLE? List names of tables\n"
3388 " If TABLE specified, only list tables matching\n"
3389 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003390 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003391 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003392 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003393 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003394 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003395 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003396 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003397 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003398 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003399;
3400
drhe6229612014-08-18 15:08:26 +00003401#if defined(SQLITE_ENABLE_SESSION)
3402/*
3403** Print help information for the ".sessions" command
3404*/
3405void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003406 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003407 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3408 "If ?NAME? is omitted, the first defined session is used.\n"
3409 "Subcommands:\n"
3410 " attach TABLE Attach TABLE\n"
3411 " changeset FILE Write a changeset into FILE\n"
3412 " close Close one session\n"
3413 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003414 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003415 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3416 " isempty Query whether the session is empty\n"
3417 " list List currently open session names\n"
3418 " open DB NAME Open a new session on DB\n"
3419 " patchset FILE Write a patchset into FILE\n"
3420 );
3421}
3422#endif
3423
3424
drhdaffd0e2001-04-11 14:28:42 +00003425/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003426static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003427
drh2db82112016-09-15 21:35:24 +00003428/*
dan11da0022016-12-17 08:18:05 +00003429** Read the content of file zName into memory obtained from sqlite3_malloc64()
mistachkine16a3502017-05-29 03:48:13 +00003430** and return a pointer to the buffer. The caller is responsible for freeing
3431** the memory.
drh2db82112016-09-15 21:35:24 +00003432**
dan11da0022016-12-17 08:18:05 +00003433** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3434** read.
3435**
3436** For convenience, a nul-terminator byte is always appended to the data read
3437** from the file before the buffer is returned. This byte is not included in
3438** the final value of (*pnByte), if applicable.
3439**
3440** NULL is returned if any error is encountered. The final value of *pnByte
3441** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003442*/
dan11da0022016-12-17 08:18:05 +00003443static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003444 FILE *in = fopen(zName, "rb");
3445 long nIn;
drhd1459152016-09-16 19:11:03 +00003446 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003447 char *pBuf;
3448 if( in==0 ) return 0;
3449 fseek(in, 0, SEEK_END);
3450 nIn = ftell(in);
3451 rewind(in);
drhd1459152016-09-16 19:11:03 +00003452 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003453 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003454 nRead = fread(pBuf, nIn, 1, in);
3455 fclose(in);
3456 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003457 sqlite3_free(pBuf);
3458 return 0;
3459 }
drhd1459152016-09-16 19:11:03 +00003460 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003461 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003462 return pBuf;
3463}
3464
drhba5b0932014-07-24 12:39:59 +00003465/*
3466** Implementation of the "readfile(X)" SQL function. The entire content
3467** of the file named X is read and returned as a BLOB. NULL is returned
3468** if the file does not exist or is unreadable.
3469*/
3470static void readfileFunc(
3471 sqlite3_context *context,
3472 int argc,
3473 sqlite3_value **argv
3474){
3475 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003476 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003477 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003478
drhf5ed7ad2015-06-15 14:43:25 +00003479 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003480 zName = (const char*)sqlite3_value_text(argv[0]);
3481 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003482 pBuf = readFile(zName, &nBuf);
3483 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003484}
3485
3486/*
3487** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3488** is written into file X. The number of bytes written is returned. Or
3489** NULL is returned if something goes wrong, such as being unable to open
3490** file X for writing.
3491*/
3492static void writefileFunc(
3493 sqlite3_context *context,
3494 int argc,
3495 sqlite3_value **argv
3496){
3497 FILE *out;
3498 const char *z;
drhba5b0932014-07-24 12:39:59 +00003499 sqlite3_int64 rc;
3500 const char *zFile;
3501
drhf5ed7ad2015-06-15 14:43:25 +00003502 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003503 zFile = (const char*)sqlite3_value_text(argv[0]);
3504 if( zFile==0 ) return;
3505 out = fopen(zFile, "wb");
3506 if( out==0 ) return;
3507 z = (const char*)sqlite3_value_blob(argv[1]);
3508 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003509 rc = 0;
3510 }else{
drh490fe862014-08-11 14:21:32 +00003511 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003512 }
3513 fclose(out);
3514 sqlite3_result_int64(context, rc);
3515}
drhdaffd0e2001-04-11 14:28:42 +00003516
drhe6229612014-08-18 15:08:26 +00003517#if defined(SQLITE_ENABLE_SESSION)
3518/*
3519** Close a single OpenSession object and release all of its associated
3520** resources.
3521*/
3522static void session_close(OpenSession *pSession){
3523 int i;
3524 sqlite3session_delete(pSession->p);
3525 sqlite3_free(pSession->zName);
3526 for(i=0; i<pSession->nFilter; i++){
3527 sqlite3_free(pSession->azFilter[i]);
3528 }
3529 sqlite3_free(pSession->azFilter);
3530 memset(pSession, 0, sizeof(OpenSession));
3531}
3532#endif
3533
3534/*
drh51b55a32016-04-04 12:38:05 +00003535** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003536*/
drhe6229612014-08-18 15:08:26 +00003537#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003538static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003539 int i;
3540 for(i=0; i<p->nSession; i++){
3541 session_close(&p->aSession[i]);
3542 }
3543 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003544}
drh51b55a32016-04-04 12:38:05 +00003545#else
3546# define session_close_all(X)
3547#endif
drhe6229612014-08-18 15:08:26 +00003548
drh75897232000-05-29 14:26:00 +00003549/*
drh03168ca2014-08-18 20:01:31 +00003550** Implementation of the xFilter function for an open session. Omit
3551** any tables named by ".session filter" but let all other table through.
3552*/
3553#if defined(SQLITE_ENABLE_SESSION)
3554static int session_filter(void *pCtx, const char *zTab){
3555 OpenSession *pSession = (OpenSession*)pCtx;
3556 int i;
3557 for(i=0; i<pSession->nFilter; i++){
3558 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3559 }
3560 return 1;
3561}
3562#endif
3563
3564/*
drh44c2eb12003-04-30 11:38:26 +00003565** Make sure the database is open. If it is not, then open it. If
3566** the database fails to open, print an error message and exit.
3567*/
drhdcd87a92014-08-18 13:45:42 +00003568static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003569 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003570 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003571 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003572 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003573 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003574 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003575 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003576 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003577 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003578 }
drhc2e87a32006-06-27 15:16:14 +00003579#ifndef SQLITE_OMIT_LOAD_EXTENSION
3580 sqlite3_enable_load_extension(p->db, 1);
3581#endif
mistachkin8e189222015-04-19 21:43:16 +00003582 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003583 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003584 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003585 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003586 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3587 sha3Func, 0, 0);
3588 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3589 sha3Func, 0, 0);
3590 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3591 sha3QueryFunc, 0, 0);
3592 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3593 sha3QueryFunc, 0, 0);
drh20c9c3f2017-06-15 12:21:09 +00003594 sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
3595 shellAddSchemaName, 0, 0);
3596
drh44c2eb12003-04-30 11:38:26 +00003597 }
3598}
3599
3600/*
drhfeac5f82004-08-01 00:10:45 +00003601** Do C-language style dequoting.
3602**
mistachkinf21979d2015-01-18 05:35:01 +00003603** \a -> alarm
3604** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003605** \t -> tab
3606** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003607** \v -> vertical tab
3608** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003609** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003610** \s -> space
drh4c56b992013-06-27 13:26:55 +00003611** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003612** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003613** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003614** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003615*/
3616static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003617 int i, j;
3618 char c;
drhc2ce0be2014-05-29 12:36:14 +00003619 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003620 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003621 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003622 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003623 if( c=='a' ){
3624 c = '\a';
3625 }else if( c=='b' ){
3626 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003627 }else if( c=='t' ){
3628 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003629 }else if( c=='n' ){
3630 c = '\n';
3631 }else if( c=='v' ){
3632 c = '\v';
3633 }else if( c=='f' ){
3634 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003635 }else if( c=='r' ){
3636 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003637 }else if( c=='"' ){
3638 c = '"';
3639 }else if( c=='\'' ){
3640 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003641 }else if( c=='\\' ){
3642 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003643 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003644 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003645 if( z[i+1]>='0' && z[i+1]<='7' ){
3646 i++;
3647 c = (c<<3) + z[i] - '0';
3648 if( z[i+1]>='0' && z[i+1]<='7' ){
3649 i++;
3650 c = (c<<3) + z[i] - '0';
3651 }
3652 }
3653 }
3654 }
3655 z[j] = c;
3656 }
drhc2ce0be2014-05-29 12:36:14 +00003657 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003658}
3659
3660/*
drh348d19c2013-06-03 12:47:43 +00003661** Return the value of a hexadecimal digit. Return -1 if the input
3662** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003663*/
drh348d19c2013-06-03 12:47:43 +00003664static int hexDigitValue(char c){
3665 if( c>='0' && c<='9' ) return c - '0';
3666 if( c>='a' && c<='f' ) return c - 'a' + 10;
3667 if( c>='A' && c<='F' ) return c - 'A' + 10;
3668 return -1;
drhc28490c2006-10-26 14:25:58 +00003669}
3670
3671/*
drh7d9f3942013-04-03 01:26:54 +00003672** Interpret zArg as an integer value, possibly with suffixes.
3673*/
3674static sqlite3_int64 integerValue(const char *zArg){
3675 sqlite3_int64 v = 0;
3676 static const struct { char *zSuffix; int iMult; } aMult[] = {
3677 { "KiB", 1024 },
3678 { "MiB", 1024*1024 },
3679 { "GiB", 1024*1024*1024 },
3680 { "KB", 1000 },
3681 { "MB", 1000000 },
3682 { "GB", 1000000000 },
3683 { "K", 1000 },
3684 { "M", 1000000 },
3685 { "G", 1000000000 },
3686 };
3687 int i;
3688 int isNeg = 0;
3689 if( zArg[0]=='-' ){
3690 isNeg = 1;
3691 zArg++;
3692 }else if( zArg[0]=='+' ){
3693 zArg++;
3694 }
drh348d19c2013-06-03 12:47:43 +00003695 if( zArg[0]=='0' && zArg[1]=='x' ){
3696 int x;
3697 zArg += 2;
3698 while( (x = hexDigitValue(zArg[0]))>=0 ){
3699 v = (v<<4) + x;
3700 zArg++;
3701 }
3702 }else{
3703 while( IsDigit(zArg[0]) ){
3704 v = v*10 + zArg[0] - '0';
3705 zArg++;
3706 }
drh7d9f3942013-04-03 01:26:54 +00003707 }
drhc2bed0a2013-05-24 11:57:50 +00003708 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003709 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3710 v *= aMult[i].iMult;
3711 break;
3712 }
3713 }
3714 return isNeg? -v : v;
3715}
3716
3717/*
drh348d19c2013-06-03 12:47:43 +00003718** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3719** for TRUE and FALSE. Return the integer value if appropriate.
3720*/
drhe6e1d122017-03-09 13:50:49 +00003721static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003722 int i;
3723 if( zArg[0]=='0' && zArg[1]=='x' ){
3724 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3725 }else{
3726 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3727 }
3728 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3729 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3730 return 1;
3731 }
3732 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3733 return 0;
3734 }
mistachkinaae280e2015-12-31 19:06:24 +00003735 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003736 zArg);
3737 return 0;
3738}
3739
3740/*
drhe6e1d122017-03-09 13:50:49 +00003741** Set or clear a shell flag according to a boolean value.
3742*/
3743static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3744 if( booleanValue(zArg) ){
3745 ShellSetFlag(p, mFlag);
3746 }else{
3747 ShellClearFlag(p, mFlag);
3748 }
3749}
3750
3751/*
drh42f64e52012-04-04 16:56:23 +00003752** Close an output file, assuming it is not stderr or stdout
3753*/
3754static void output_file_close(FILE *f){
3755 if( f && f!=stdout && f!=stderr ) fclose(f);
3756}
3757
3758/*
3759** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003760** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003761** filename is "off".
3762*/
3763static FILE *output_file_open(const char *zFile){
3764 FILE *f;
3765 if( strcmp(zFile,"stdout")==0 ){
3766 f = stdout;
3767 }else if( strcmp(zFile, "stderr")==0 ){
3768 f = stderr;
3769 }else if( strcmp(zFile, "off")==0 ){
3770 f = 0;
3771 }else{
3772 f = fopen(zFile, "wb");
3773 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003774 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003775 }
3776 }
3777 return f;
3778}
3779
drhd12602a2016-12-07 15:49:02 +00003780#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003781#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003782/*
3783** A routine for handling output from sqlite3_trace().
3784*/
drh4b363a52016-07-23 20:27:41 +00003785static int sql_trace_callback(
3786 unsigned mType,
3787 void *pArg,
3788 void *pP,
3789 void *pX
3790){
drh42f64e52012-04-04 16:56:23 +00003791 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003792 UNUSED_PARAMETER(mType);
3793 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003794 if( f ){
drh4b363a52016-07-23 20:27:41 +00003795 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003796 int i = (int)strlen(z);
3797 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003798 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003799 }
drh4b363a52016-07-23 20:27:41 +00003800 return 0;
drh42f64e52012-04-04 16:56:23 +00003801}
drhc10b9da2016-11-20 17:59:59 +00003802#endif
3803#endif
drh42f64e52012-04-04 16:56:23 +00003804
3805/*
drhd8621b92012-04-17 09:09:33 +00003806** A no-op routine that runs with the ".breakpoint" doc-command. This is
3807** a useful spot to set a debugger breakpoint.
3808*/
3809static void test_breakpoint(void){
3810 static int nCall = 0;
3811 nCall++;
3812}
3813
3814/*
mistachkin636bf9f2014-07-19 20:15:16 +00003815** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003816*/
mistachkin636bf9f2014-07-19 20:15:16 +00003817typedef struct ImportCtx ImportCtx;
3818struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003819 const char *zFile; /* Name of the input file */
3820 FILE *in; /* Read the CSV text from this input stream */
3821 char *z; /* Accumulated text for a field */
3822 int n; /* Number of bytes in z */
3823 int nAlloc; /* Space allocated for z[] */
3824 int nLine; /* Current line number */
3825 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003826 int cColSep; /* The column separator character. (Usually ",") */
3827 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003828};
3829
3830/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003831static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003832 if( p->n+1>=p->nAlloc ){
3833 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003834 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003835 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003836 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003837 exit(1);
3838 }
3839 }
3840 p->z[p->n++] = (char)c;
3841}
3842
3843/* Read a single field of CSV text. Compatible with rfc4180 and extended
3844** with the option of having a separator other than ",".
3845**
3846** + Input comes from p->in.
3847** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003848** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003849** + Use p->cSep as the column separator. The default is ",".
3850** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003851** + Keep track of the line number in p->nLine.
3852** + Store the character that terminates the field in p->cTerm. Store
3853** EOF on end-of-file.
3854** + Report syntax errors on stderr
3855*/
mistachkin44723ce2015-03-21 02:22:37 +00003856static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003857 int c;
3858 int cSep = p->cColSep;
3859 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003860 p->n = 0;
3861 c = fgetc(p->in);
3862 if( c==EOF || seenInterrupt ){
3863 p->cTerm = EOF;
3864 return 0;
3865 }
3866 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003867 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003868 int startLine = p->nLine;
3869 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003870 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003871 while( 1 ){
3872 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003873 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003874 if( c==cQuote ){
3875 if( pc==cQuote ){
3876 pc = 0;
3877 continue;
3878 }
3879 }
3880 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003881 || (c==rSep && pc==cQuote)
3882 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003883 || (c==EOF && pc==cQuote)
3884 ){
3885 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003886 p->cTerm = c;
3887 break;
3888 }
3889 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003890 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003891 p->zFile, p->nLine, cQuote);
3892 }
3893 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003894 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003895 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003896 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003897 break;
3898 }
mistachkin636bf9f2014-07-19 20:15:16 +00003899 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003900 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003901 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003902 }
drhdb95f682013-06-26 22:46:00 +00003903 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00003904 while( c!=EOF && c!=cSep && c!=rSep ){
3905 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003906 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003907 }
mistachkin636bf9f2014-07-19 20:15:16 +00003908 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003909 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003910 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003911 }
drhdb95f682013-06-26 22:46:00 +00003912 p->cTerm = c;
3913 }
drh8dd675e2013-07-12 21:09:24 +00003914 if( p->z ) p->z[p->n] = 0;
drhdb95f682013-06-26 22:46:00 +00003915 return p->z;
3916}
3917
mistachkin636bf9f2014-07-19 20:15:16 +00003918/* Read a single field of ASCII delimited text.
3919**
3920** + Input comes from p->in.
3921** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003922** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003923** + Use p->cSep as the column separator. The default is "\x1F".
3924** + Use p->rSep as the row separator. The default is "\x1E".
3925** + Keep track of the row number in p->nLine.
3926** + Store the character that terminates the field in p->cTerm. Store
3927** EOF on end-of-file.
3928** + Report syntax errors on stderr
3929*/
mistachkin44723ce2015-03-21 02:22:37 +00003930static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003931 int c;
3932 int cSep = p->cColSep;
3933 int rSep = p->cRowSep;
3934 p->n = 0;
3935 c = fgetc(p->in);
3936 if( c==EOF || seenInterrupt ){
3937 p->cTerm = EOF;
3938 return 0;
3939 }
3940 while( c!=EOF && c!=cSep && c!=rSep ){
3941 import_append_char(p, c);
3942 c = fgetc(p->in);
3943 }
3944 if( c==rSep ){
3945 p->nLine++;
3946 }
3947 p->cTerm = c;
3948 if( p->z ) p->z[p->n] = 0;
3949 return p->z;
3950}
3951
drhdb95f682013-06-26 22:46:00 +00003952/*
drh4bbcf102014-02-06 02:46:08 +00003953** Try to transfer data for table zTable. If an error is seen while
3954** moving forward, try to go backwards. The backwards movement won't
3955** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003956*/
mistachkine31ae902014-02-06 01:15:29 +00003957static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003958 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003959 sqlite3 *newDb,
3960 const char *zTable
3961){
mistachkin1fe36bb2016-04-04 02:16:44 +00003962 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003963 sqlite3_stmt *pInsert = 0;
3964 char *zQuery = 0;
3965 char *zInsert = 0;
3966 int rc;
3967 int i, j, n;
3968 int nTable = (int)strlen(zTable);
3969 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003970 int cnt = 0;
3971 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003972
3973 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3974 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3975 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003976 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003977 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3978 zQuery);
3979 goto end_data_xfer;
3980 }
3981 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00003982 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00003983 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003984 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00003985 goto end_data_xfer;
3986 }
3987 sqlite3_snprintf(200+nTable,zInsert,
3988 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3989 i = (int)strlen(zInsert);
3990 for(j=1; j<n; j++){
3991 memcpy(zInsert+i, ",?", 2);
3992 i += 2;
3993 }
3994 memcpy(zInsert+i, ");", 3);
3995 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3996 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003997 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003998 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3999 zQuery);
4000 goto end_data_xfer;
4001 }
4002 for(k=0; k<2; k++){
4003 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4004 for(i=0; i<n; i++){
4005 switch( sqlite3_column_type(pQuery, i) ){
4006 case SQLITE_NULL: {
4007 sqlite3_bind_null(pInsert, i+1);
4008 break;
4009 }
4010 case SQLITE_INTEGER: {
4011 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4012 break;
4013 }
4014 case SQLITE_FLOAT: {
4015 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4016 break;
4017 }
4018 case SQLITE_TEXT: {
4019 sqlite3_bind_text(pInsert, i+1,
4020 (const char*)sqlite3_column_text(pQuery,i),
4021 -1, SQLITE_STATIC);
4022 break;
4023 }
4024 case SQLITE_BLOB: {
4025 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4026 sqlite3_column_bytes(pQuery,i),
4027 SQLITE_STATIC);
4028 break;
4029 }
4030 }
4031 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00004032 rc = sqlite3_step(pInsert);
4033 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00004034 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00004035 sqlite3_errmsg(newDb));
4036 }
drh3350ce92014-02-06 00:49:12 +00004037 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00004038 cnt++;
4039 if( (cnt%spinRate)==0 ){
4040 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4041 fflush(stdout);
4042 }
drh3350ce92014-02-06 00:49:12 +00004043 } /* End while */
4044 if( rc==SQLITE_DONE ) break;
4045 sqlite3_finalize(pQuery);
4046 sqlite3_free(zQuery);
4047 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4048 zTable);
4049 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4050 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004051 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00004052 break;
drh3350ce92014-02-06 00:49:12 +00004053 }
4054 } /* End for(k=0...) */
4055
4056end_data_xfer:
4057 sqlite3_finalize(pQuery);
4058 sqlite3_finalize(pInsert);
4059 sqlite3_free(zQuery);
4060 sqlite3_free(zInsert);
4061}
4062
4063
4064/*
4065** Try to transfer all rows of the schema that match zWhere. For
4066** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00004067** If an error is encountered while moving forward through the
4068** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00004069*/
mistachkine31ae902014-02-06 01:15:29 +00004070static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00004071 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00004072 sqlite3 *newDb,
4073 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00004074 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00004075){
4076 sqlite3_stmt *pQuery = 0;
4077 char *zQuery = 0;
4078 int rc;
4079 const unsigned char *zName;
4080 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00004081 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00004082
4083 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4084 " WHERE %s", zWhere);
4085 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4086 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004087 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004088 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4089 zQuery);
4090 goto end_schema_xfer;
4091 }
4092 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4093 zName = sqlite3_column_text(pQuery, 0);
4094 zSql = sqlite3_column_text(pQuery, 1);
4095 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004096 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4097 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004098 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004099 sqlite3_free(zErrMsg);
4100 zErrMsg = 0;
4101 }
drh3350ce92014-02-06 00:49:12 +00004102 if( xForEach ){
4103 xForEach(p, newDb, (const char*)zName);
4104 }
4105 printf("done\n");
4106 }
4107 if( rc!=SQLITE_DONE ){
4108 sqlite3_finalize(pQuery);
4109 sqlite3_free(zQuery);
4110 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4111 " WHERE %s ORDER BY rowid DESC", zWhere);
4112 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4113 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004114 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004115 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4116 zQuery);
4117 goto end_schema_xfer;
4118 }
4119 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4120 zName = sqlite3_column_text(pQuery, 0);
4121 zSql = sqlite3_column_text(pQuery, 1);
4122 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004123 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4124 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004125 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004126 sqlite3_free(zErrMsg);
4127 zErrMsg = 0;
4128 }
drh3350ce92014-02-06 00:49:12 +00004129 if( xForEach ){
4130 xForEach(p, newDb, (const char*)zName);
4131 }
4132 printf("done\n");
4133 }
4134 }
4135end_schema_xfer:
4136 sqlite3_finalize(pQuery);
4137 sqlite3_free(zQuery);
4138}
4139
4140/*
4141** Open a new database file named "zNewDb". Try to recover as much information
4142** as possible out of the main database (which might be corrupt) and write it
4143** into zNewDb.
4144*/
drhdcd87a92014-08-18 13:45:42 +00004145static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00004146 int rc;
4147 sqlite3 *newDb = 0;
4148 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004149 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00004150 return;
4151 }
4152 rc = sqlite3_open(zNewDb, &newDb);
4153 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004154 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00004155 sqlite3_errmsg(newDb));
4156 }else{
drh54d0d2d2014-04-03 00:32:13 +00004157 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004158 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00004159 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4160 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00004161 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00004162 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004163 }
4164 sqlite3_close(newDb);
4165}
4166
4167/*
drhc2ce0be2014-05-29 12:36:14 +00004168** Change the output file back to stdout
4169*/
drhdcd87a92014-08-18 13:45:42 +00004170static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00004171 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004172#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00004173 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004174#endif
drhc2ce0be2014-05-29 12:36:14 +00004175 }else{
4176 output_file_close(p->out);
4177 }
4178 p->outfile[0] = 0;
4179 p->out = stdout;
4180}
4181
4182/*
drhf7502f02015-02-06 14:19:44 +00004183** Run an SQL command and return the single integer result.
4184*/
4185static int db_int(ShellState *p, const char *zSql){
4186 sqlite3_stmt *pStmt;
4187 int res = 0;
4188 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4189 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4190 res = sqlite3_column_int(pStmt,0);
4191 }
4192 sqlite3_finalize(pStmt);
4193 return res;
4194}
4195
4196/*
4197** Convert a 2-byte or 4-byte big-endian integer into a native integer
4198*/
drha0620ac2016-07-13 13:05:13 +00004199static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004200 return (a[0]<<8) + a[1];
4201}
drha0620ac2016-07-13 13:05:13 +00004202static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004203 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4204}
4205
4206/*
4207** Implementation of the ".info" command.
4208**
4209** Return 1 on error, 2 to exit, and 0 otherwise.
4210*/
drh0e55db12015-02-06 14:51:13 +00004211static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004212 static const struct { const char *zName; int ofst; } aField[] = {
4213 { "file change counter:", 24 },
4214 { "database page count:", 28 },
4215 { "freelist page count:", 36 },
4216 { "schema cookie:", 40 },
4217 { "schema format:", 44 },
4218 { "default cache size:", 48 },
4219 { "autovacuum top root:", 52 },
4220 { "incremental vacuum:", 64 },
4221 { "text encoding:", 56 },
4222 { "user version:", 60 },
4223 { "application id:", 68 },
4224 { "software version:", 96 },
4225 };
drh0e55db12015-02-06 14:51:13 +00004226 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4227 { "number of tables:",
4228 "SELECT count(*) FROM %s WHERE type='table'" },
4229 { "number of indexes:",
4230 "SELECT count(*) FROM %s WHERE type='index'" },
4231 { "number of triggers:",
4232 "SELECT count(*) FROM %s WHERE type='trigger'" },
4233 { "number of views:",
4234 "SELECT count(*) FROM %s WHERE type='view'" },
4235 { "schema size:",
4236 "SELECT total(length(sql)) FROM %s" },
4237 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004238 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004239 int i;
4240 char *zSchemaTab;
4241 char *zDb = nArg>=2 ? azArg[1] : "main";
4242 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004243 open_db(p, 0);
4244 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004245 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004246 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4247 return 1;
4248 }
4249 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4250 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004251 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004252 return 1;
4253 }
4254 i = get2byteInt(aHdr+16);
4255 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004256 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4257 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4258 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4259 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004260 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004261 int ofst = aField[i].ofst;
4262 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004263 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004264 switch( ofst ){
4265 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004266 if( val==1 ) raw_printf(p->out, " (utf8)");
4267 if( val==2 ) raw_printf(p->out, " (utf16le)");
4268 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004269 }
4270 }
mistachkinaae280e2015-12-31 19:06:24 +00004271 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004272 }
drh0e55db12015-02-06 14:51:13 +00004273 if( zDb==0 ){
4274 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4275 }else if( strcmp(zDb,"temp")==0 ){
4276 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4277 }else{
4278 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4279 }
drhf5ed7ad2015-06-15 14:43:25 +00004280 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004281 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4282 int val = db_int(p, zSql);
4283 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004284 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004285 }
4286 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004287 return 0;
4288}
4289
dand95bb392015-09-30 11:19:05 +00004290/*
4291** Print the current sqlite3_errmsg() value to stderr and return 1.
4292*/
4293static int shellDatabaseError(sqlite3 *db){
4294 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004295 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004296 return 1;
4297}
4298
4299/*
4300** Print an out-of-memory message to stderr and return 1.
4301*/
4302static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004303 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004304 return 1;
4305}
drhf7502f02015-02-06 14:19:44 +00004306
drh2db82112016-09-15 21:35:24 +00004307/*
4308** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4309** if they match and FALSE (0) if they do not match.
4310**
4311** Globbing rules:
4312**
4313** '*' Matches any sequence of zero or more characters.
4314**
4315** '?' Matches exactly one character.
4316**
4317** [...] Matches one character from the enclosed list of
4318** characters.
4319**
4320** [^...] Matches one character not in the enclosed list.
4321**
4322** '#' Matches any sequence of one or more digits with an
4323** optional + or - sign in front
4324**
4325** ' ' Any span of whitespace matches any other span of
4326** whitespace.
4327**
4328** Extra whitespace at the end of z[] is ignored.
4329*/
4330static int testcase_glob(const char *zGlob, const char *z){
4331 int c, c2;
4332 int invert;
4333 int seen;
4334
4335 while( (c = (*(zGlob++)))!=0 ){
4336 if( IsSpace(c) ){
4337 if( !IsSpace(*z) ) return 0;
4338 while( IsSpace(*zGlob) ) zGlob++;
4339 while( IsSpace(*z) ) z++;
4340 }else if( c=='*' ){
4341 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4342 if( c=='?' && (*(z++))==0 ) return 0;
4343 }
4344 if( c==0 ){
4345 return 1;
4346 }else if( c=='[' ){
4347 while( *z && testcase_glob(zGlob-1,z)==0 ){
4348 z++;
4349 }
4350 return (*z)!=0;
4351 }
4352 while( (c2 = (*(z++)))!=0 ){
4353 while( c2!=c ){
4354 c2 = *(z++);
4355 if( c2==0 ) return 0;
4356 }
4357 if( testcase_glob(zGlob,z) ) return 1;
4358 }
4359 return 0;
4360 }else if( c=='?' ){
4361 if( (*(z++))==0 ) return 0;
4362 }else if( c=='[' ){
4363 int prior_c = 0;
4364 seen = 0;
4365 invert = 0;
4366 c = *(z++);
4367 if( c==0 ) return 0;
4368 c2 = *(zGlob++);
4369 if( c2=='^' ){
4370 invert = 1;
4371 c2 = *(zGlob++);
4372 }
4373 if( c2==']' ){
4374 if( c==']' ) seen = 1;
4375 c2 = *(zGlob++);
4376 }
4377 while( c2 && c2!=']' ){
4378 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4379 c2 = *(zGlob++);
4380 if( c>=prior_c && c<=c2 ) seen = 1;
4381 prior_c = 0;
4382 }else{
4383 if( c==c2 ){
4384 seen = 1;
4385 }
4386 prior_c = c2;
4387 }
4388 c2 = *(zGlob++);
4389 }
4390 if( c2==0 || (seen ^ invert)==0 ) return 0;
4391 }else if( c=='#' ){
4392 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4393 if( !IsDigit(z[0]) ) return 0;
4394 z++;
4395 while( IsDigit(z[0]) ){ z++; }
4396 }else{
4397 if( c!=(*(z++)) ) return 0;
4398 }
4399 }
4400 while( IsSpace(*z) ){ z++; }
4401 return *z==0;
4402}
drh2db82112016-09-15 21:35:24 +00004403
4404
drhf7502f02015-02-06 14:19:44 +00004405/*
drh4926fec2016-04-13 15:33:42 +00004406** Compare the string as a command-line option with either one or two
4407** initial "-" characters.
4408*/
4409static int optionMatch(const char *zStr, const char *zOpt){
4410 if( zStr[0]!='-' ) return 0;
4411 zStr++;
4412 if( zStr[0]=='-' ) zStr++;
4413 return strcmp(zStr, zOpt)==0;
4414}
4415
4416/*
drhcd0509e2016-09-16 00:26:08 +00004417** Delete a file.
4418*/
4419int shellDeleteFile(const char *zFilename){
4420 int rc;
4421#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004422 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004423 rc = _wunlink(z);
4424 sqlite3_free(z);
4425#else
4426 rc = unlink(zFilename);
4427#endif
4428 return rc;
4429}
4430
dan35ac58e2016-12-14 19:28:27 +00004431
dan35ac58e2016-12-14 19:28:27 +00004432/*
dandd9e0be2016-12-16 16:44:27 +00004433** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004434** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004435** called with four arguments - the parent table name, the parent column name,
4436** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004437**
4438** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4439**
4440** If either of the named tables or columns do not exist, this function
mistachkine16a3502017-05-29 03:48:13 +00004441** returns an empty string. An empty string is also returned if both tables
dan35ac58e2016-12-14 19:28:27 +00004442** and columns exist but have the same default collation sequence. Or,
4443** if both exist but the default collation sequences are different, this
4444** function returns the string " COLLATE <parent-collation>", where
4445** <parent-collation> is the default collation sequence of the parent column.
4446*/
4447static void shellFkeyCollateClause(
mistachkine16a3502017-05-29 03:48:13 +00004448 sqlite3_context *pCtx,
4449 int nVal,
dan35ac58e2016-12-14 19:28:27 +00004450 sqlite3_value **apVal
4451){
4452 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4453 const char *zParent;
4454 const char *zParentCol;
4455 const char *zParentSeq;
4456 const char *zChild;
4457 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004458 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004459 int rc;
mistachkine16a3502017-05-29 03:48:13 +00004460
dan35ac58e2016-12-14 19:28:27 +00004461 assert( nVal==4 );
4462 zParent = (const char*)sqlite3_value_text(apVal[0]);
4463 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4464 zChild = (const char*)sqlite3_value_text(apVal[2]);
4465 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4466
4467 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4468 rc = sqlite3_table_column_metadata(
4469 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4470 );
4471 if( rc==SQLITE_OK ){
4472 rc = sqlite3_table_column_metadata(
4473 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4474 );
4475 }
4476
4477 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4478 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4479 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4480 sqlite3_free(z);
4481 }
4482}
4483
4484
4485/*
dan3c7ebeb2016-12-16 17:28:56 +00004486** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004487*/
dan3c7ebeb2016-12-16 17:28:56 +00004488static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004489 ShellState *pState, /* Current shell tool state */
4490 char **azArg, /* Array of arguments passed to dot command */
4491 int nArg /* Number of entries in azArg[] */
4492){
dandd9e0be2016-12-16 16:44:27 +00004493 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4494 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004495 int bVerbose = 0; /* If -verbose is present */
4496 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004497 int i; /* To iterate through azArg[] */
4498 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4499 int rc; /* Return code */
4500 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004501
dandd9e0be2016-12-16 16:44:27 +00004502 /*
4503 ** This SELECT statement returns one row for each foreign key constraint
4504 ** in the schema of the main database. The column values are:
4505 **
4506 ** 0. The text of an SQL statement similar to:
4507 **
4508 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4509 **
4510 ** This is the same SELECT that the foreign keys implementation needs
4511 ** to run internally on child tables. If there is an index that can
4512 ** be used to optimize this query, then it can also be used by the FK
4513 ** implementation to optimize DELETE or UPDATE statements on the parent
4514 ** table.
4515 **
4516 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4517 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4518 ** contains an index that can be used to optimize the query.
4519 **
4520 ** 2. Human readable text that describes the child table and columns. e.g.
4521 **
4522 ** "child_table(child_key1, child_key2)"
4523 **
4524 ** 3. Human readable text that describes the parent table and columns. e.g.
4525 **
4526 ** "parent_table(parent_key1, parent_key2)"
4527 **
4528 ** 4. A full CREATE INDEX statement for an index that could be used to
4529 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4530 **
4531 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4532 **
4533 ** 5. The name of the parent table.
4534 **
4535 ** These six values are used by the C logic below to generate the report.
4536 */
dan35ac58e2016-12-14 19:28:27 +00004537 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004538 "SELECT "
4539 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4540 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00004541 " || fkey_collate_clause("
4542 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004543 ", "
dandd9e0be2016-12-16 16:44:27 +00004544 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004545 " || group_concat('*=?', ' AND ') || ')'"
4546 ", "
dandd9e0be2016-12-16 16:44:27 +00004547 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004548 ", "
dan50da9382017-04-06 12:06:56 +00004549 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00004550 ", "
dandd9e0be2016-12-16 16:44:27 +00004551 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4552 " || ' ON ' || quote(s.name) || '('"
4553 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00004554 " fkey_collate_clause("
4555 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004556 " || ');'"
danf9647b62016-12-15 06:01:40 +00004557 ", "
dandd9e0be2016-12-16 16:44:27 +00004558 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00004559 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00004560 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00004561 "GROUP BY s.name, f.id "
4562 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004563 ;
dan54e2efc2017-04-06 14:56:26 +00004564 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00004565
dan3c7ebeb2016-12-16 17:28:56 +00004566 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004567 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004568 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4569 bVerbose = 1;
4570 }
4571 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4572 bGroupByParent = 1;
4573 zIndent = " ";
4574 }
4575 else{
dan3c7ebeb2016-12-16 17:28:56 +00004576 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4577 azArg[0], azArg[1]
4578 );
danf9647b62016-12-15 06:01:40 +00004579 return SQLITE_ERROR;
4580 }
dan35ac58e2016-12-14 19:28:27 +00004581 }
mistachkine16a3502017-05-29 03:48:13 +00004582
dan35ac58e2016-12-14 19:28:27 +00004583 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004584 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4585 0, shellFkeyCollateClause, 0, 0
4586 );
dan35ac58e2016-12-14 19:28:27 +00004587
4588
4589 if( rc==SQLITE_OK ){
4590 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4591 }
danf9647b62016-12-15 06:01:40 +00004592 if( rc==SQLITE_OK ){
4593 sqlite3_bind_int(pSql, 1, bGroupByParent);
4594 }
dan35ac58e2016-12-14 19:28:27 +00004595
4596 if( rc==SQLITE_OK ){
4597 int rc2;
danf9647b62016-12-15 06:01:40 +00004598 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004599 while( SQLITE_ROW==sqlite3_step(pSql) ){
4600 int res = -1;
4601 sqlite3_stmt *pExplain = 0;
4602 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4603 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4604 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4605 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4606 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004607 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004608
4609 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4610 if( rc!=SQLITE_OK ) break;
4611 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4612 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00004613 res = (
4614 0==sqlite3_strglob(zGlob, zPlan)
4615 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4616 );
dan35ac58e2016-12-14 19:28:27 +00004617 }
4618 rc = sqlite3_finalize(pExplain);
4619 if( rc!=SQLITE_OK ) break;
4620
4621 if( res<0 ){
4622 raw_printf(stderr, "Error: internal error");
4623 break;
danf9647b62016-12-15 06:01:40 +00004624 }else{
mistachkine16a3502017-05-29 03:48:13 +00004625 if( bGroupByParent
danf9647b62016-12-15 06:01:40 +00004626 && (bVerbose || res==0)
mistachkine16a3502017-05-29 03:48:13 +00004627 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
danf9647b62016-12-15 06:01:40 +00004628 ){
4629 raw_printf(out, "-- Parent table %s\n", zParent);
4630 sqlite3_free(zPrev);
4631 zPrev = sqlite3_mprintf("%s", zParent);
4632 }
4633
4634 if( res==0 ){
4635 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4636 }else if( bVerbose ){
mistachkine16a3502017-05-29 03:48:13 +00004637 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
danf9647b62016-12-15 06:01:40 +00004638 zIndent, zFrom, zTarget
4639 );
4640 }
dan35ac58e2016-12-14 19:28:27 +00004641 }
4642 }
danf9647b62016-12-15 06:01:40 +00004643 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004644
4645 if( rc!=SQLITE_OK ){
4646 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4647 }
4648
4649 rc2 = sqlite3_finalize(pSql);
4650 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4651 rc = rc2;
4652 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4653 }
4654 }else{
4655 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4656 }
4657
4658 return rc;
4659}
dan3c7ebeb2016-12-16 17:28:56 +00004660
dan35ac58e2016-12-14 19:28:27 +00004661/*
dan3c7ebeb2016-12-16 17:28:56 +00004662** Implementation of ".lint" dot command.
4663*/
4664static int lintDotCommand(
4665 ShellState *pState, /* Current shell tool state */
4666 char **azArg, /* Array of arguments passed to dot command */
4667 int nArg /* Number of entries in azArg[] */
4668){
4669 int n;
drh96ada592016-12-29 19:48:46 +00004670 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004671 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4672 return lintFkeyIndexes(pState, azArg, nArg);
4673
4674 usage:
4675 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4676 raw_printf(stderr, "Where sub-commands are:\n");
4677 raw_printf(stderr, " fkey-indexes\n");
4678 return SQLITE_ERROR;
4679}
4680
dan35ac58e2016-12-14 19:28:27 +00004681
drhcd0509e2016-09-16 00:26:08 +00004682/*
drh75897232000-05-29 14:26:00 +00004683** If an input line begins with "." then invoke this routine to
4684** process that line.
drh67505e72002-04-19 12:34:06 +00004685**
drh47ad6842006-11-08 12:25:42 +00004686** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004687*/
drhdcd87a92014-08-18 13:45:42 +00004688static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004689 int h = 1;
drh75897232000-05-29 14:26:00 +00004690 int nArg = 0;
4691 int n, c;
drh67505e72002-04-19 12:34:06 +00004692 int rc = 0;
drh75897232000-05-29 14:26:00 +00004693 char *azArg[50];
4694
4695 /* Parse the input line into tokens.
4696 */
mistachkin8e189222015-04-19 21:43:16 +00004697 while( zLine[h] && nArg<ArraySize(azArg) ){
4698 while( IsSpace(zLine[h]) ){ h++; }
4699 if( zLine[h]==0 ) break;
4700 if( zLine[h]=='\'' || zLine[h]=='"' ){
4701 int delim = zLine[h++];
4702 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004703 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004704 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004705 h++;
drh4c56b992013-06-27 13:26:55 +00004706 }
mistachkin8e189222015-04-19 21:43:16 +00004707 if( zLine[h]==delim ){
4708 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004709 }
drhfeac5f82004-08-01 00:10:45 +00004710 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004711 }else{
mistachkin8e189222015-04-19 21:43:16 +00004712 azArg[nArg++] = &zLine[h];
4713 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4714 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004715 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004716 }
4717 }
4718
4719 /* Process the input line.
4720 */
shane9bd1b442009-10-23 01:27:39 +00004721 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004722 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004723 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004724
drha0daa752016-09-16 11:53:10 +00004725#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004726 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4727 if( nArg!=2 ){
4728 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4729 rc = 1;
4730 goto meta_command_exit;
4731 }
4732 open_db(p, 0);
4733 if( booleanValue(azArg[1]) ){
4734 sqlite3_set_authorizer(p->db, shellAuth, p);
4735 }else{
4736 sqlite3_set_authorizer(p->db, 0, 0);
4737 }
4738 }else
drha0daa752016-09-16 11:53:10 +00004739#endif
drhde613c62016-04-04 17:23:10 +00004740
drh5c7976f2014-02-10 19:59:27 +00004741 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4742 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4743 ){
drhbc46f022013-01-23 18:53:23 +00004744 const char *zDestFile = 0;
4745 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004746 sqlite3 *pDest;
4747 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004748 int j;
4749 for(j=1; j<nArg; j++){
4750 const char *z = azArg[j];
4751 if( z[0]=='-' ){
4752 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004753 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004754 {
mistachkinaae280e2015-12-31 19:06:24 +00004755 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004756 return 1;
4757 }
4758 }else if( zDestFile==0 ){
4759 zDestFile = azArg[j];
4760 }else if( zDb==0 ){
4761 zDb = zDestFile;
4762 zDestFile = azArg[j];
4763 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004764 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004765 return 1;
4766 }
drh9ff849f2009-02-04 20:55:57 +00004767 }
drhbc46f022013-01-23 18:53:23 +00004768 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004769 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004770 return 1;
4771 }
4772 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004773 rc = sqlite3_open(zDestFile, &pDest);
4774 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004775 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004776 sqlite3_close(pDest);
4777 return 1;
4778 }
drh05782482013-10-24 15:20:20 +00004779 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004780 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4781 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004782 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004783 sqlite3_close(pDest);
4784 return 1;
4785 }
4786 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4787 sqlite3_backup_finish(pBackup);
4788 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004789 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004790 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004791 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004792 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004793 }
4794 sqlite3_close(pDest);
4795 }else
4796
drhc2ce0be2014-05-29 12:36:14 +00004797 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4798 if( nArg==2 ){
4799 bail_on_error = booleanValue(azArg[1]);
4800 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004801 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004802 rc = 1;
4803 }
drhc49f44e2006-10-26 18:15:42 +00004804 }else
4805
mistachkinf21979d2015-01-18 05:35:01 +00004806 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4807 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004808 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004809 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004810 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004811 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004812 }
mistachkinf21979d2015-01-18 05:35:01 +00004813 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004814 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004815 rc = 1;
4816 }
4817 }else
4818
drh453ca042017-05-22 18:00:34 +00004819 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4820 if( nArg==2 ){
4821#if defined(_WIN32) || defined(WIN32)
4822 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4823 rc = !SetCurrentDirectoryW(z);
4824 sqlite3_free(z);
4825#else
4826 rc = chdir(azArg[1]);
4827#endif
4828 if( rc ){
4829 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4830 rc = 1;
4831 }
4832 }else{
4833 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4834 rc = 1;
4835 }
4836 }else
4837
drhd8621b92012-04-17 09:09:33 +00004838 /* The undocumented ".breakpoint" command causes a call to the no-op
4839 ** routine named test_breakpoint().
4840 */
4841 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4842 test_breakpoint();
4843 }else
4844
drhdf12f1c2015-12-07 21:46:19 +00004845 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4846 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004847 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004848 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004849 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004850 rc = 1;
4851 }
4852 }else
4853
drh2db82112016-09-15 21:35:24 +00004854 /* Cancel output redirection, if it is currently set (by .testcase)
4855 ** Then read the content of the testcase-out.txt file and compare against
4856 ** azArg[1]. If there are differences, report an error and exit.
4857 */
4858 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4859 char *zRes = 0;
4860 output_reset(p);
4861 if( nArg!=2 ){
4862 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004863 rc = 2;
dan11da0022016-12-17 08:18:05 +00004864 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004865 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4866 rc = 2;
4867 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004868 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004869 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4870 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004871 rc = 2;
drh760c8162016-09-16 02:52:22 +00004872 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004873 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004874 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004875 }
4876 sqlite3_free(zRes);
4877 }else
drh2db82112016-09-15 21:35:24 +00004878
drhc2ce0be2014-05-29 12:36:14 +00004879 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4880 if( nArg==2 ){
4881 tryToClone(p, azArg[1]);
4882 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004883 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004884 rc = 1;
4885 }
mistachkine31ae902014-02-06 01:15:29 +00004886 }else
4887
drhc2ce0be2014-05-29 12:36:14 +00004888 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004889 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004890 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004891 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004892 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004893 data.showHeader = 0;
4894 data.cMode = data.mode = MODE_List;
4895 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004896 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004897 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4898 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004899 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004900 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004901 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004902 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004903 }
4904 }else
4905
drh0e55db12015-02-06 14:51:13 +00004906 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4907 rc = shell_dbinfo_command(p, nArg, azArg);
4908 }else
4909
drhc2ce0be2014-05-29 12:36:14 +00004910 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004911 const char *zLike = 0;
4912 int i;
drh72507d42017-04-08 00:55:13 +00004913 int savedShowHeader = p->showHeader;
drhe6e1d122017-03-09 13:50:49 +00004914 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004915 for(i=1; i<nArg; i++){
4916 if( azArg[i][0]=='-' ){
4917 const char *z = azArg[i]+1;
4918 if( z[0]=='-' ) z++;
4919 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00004920#ifdef SQLITE_OMIT_VIRTUALTABLE
4921 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4922 " with SQLITE_OMIT_VIRTUALTABLE\n");
4923 rc = 1;
4924 goto meta_command_exit;
4925#else
drhe6e1d122017-03-09 13:50:49 +00004926 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00004927#endif
drhe611f142017-03-08 11:44:00 +00004928 }else
4929 {
4930 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4931 rc = 1;
4932 goto meta_command_exit;
4933 }
4934 }else if( zLike ){
4935 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4936 rc = 1;
4937 goto meta_command_exit;
4938 }else{
4939 zLike = azArg[i];
4940 }
4941 }
drh05782482013-10-24 15:20:20 +00004942 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004943 /* When playing back a "dump", the content might appear in an order
4944 ** which causes immediate foreign key constraints to be violated.
4945 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004946 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4947 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004948 p->writableSchema = 0;
drh72507d42017-04-08 00:55:13 +00004949 p->showHeader = 0;
drhe611f142017-03-08 11:44:00 +00004950 /* Set writable_schema=ON since doing so forces SQLite to initialize
4951 ** as much of the schema as it can even if the sqlite_master table is
4952 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004953 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004954 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004955 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004956 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004957 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004958 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004959 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004960 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004961 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004962 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004963 );
drh2f464a02011-10-13 00:41:49 +00004964 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004965 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004966 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004967 );
drh4c653a02000-06-07 01:27:47 +00004968 }else{
drhe611f142017-03-08 11:44:00 +00004969 char *zSql;
4970 zSql = sqlite3_mprintf(
4971 "SELECT name, type, sql FROM sqlite_master "
4972 "WHERE tbl_name LIKE %Q AND type=='table'"
4973 " AND sql NOT NULL", zLike);
4974 run_schema_dump_query(p,zSql);
4975 sqlite3_free(zSql);
4976 zSql = sqlite3_mprintf(
4977 "SELECT sql FROM sqlite_master "
4978 "WHERE sql NOT NULL"
4979 " AND type IN ('index','trigger','view')"
4980 " AND tbl_name LIKE %Q", zLike);
4981 run_table_dump_query(p, zSql, 0);
4982 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00004983 }
drh45e29d82006-11-20 16:21:10 +00004984 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00004985 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00004986 p->writableSchema = 0;
4987 }
drh56197952011-10-13 16:30:13 +00004988 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4989 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00004990 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh72507d42017-04-08 00:55:13 +00004991 p->showHeader = savedShowHeader;
drh4c653a02000-06-07 01:27:47 +00004992 }else
drh75897232000-05-29 14:26:00 +00004993
drhc2ce0be2014-05-29 12:36:14 +00004994 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4995 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004996 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00004997 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004998 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004999 rc = 1;
5000 }
drhdaffd0e2001-04-11 14:28:42 +00005001 }else
5002
drhc2ce0be2014-05-29 12:36:14 +00005003 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5004 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00005005 if( strcmp(azArg[1],"full")==0 ){
5006 p->autoEQP = 2;
5007 }else{
5008 p->autoEQP = booleanValue(azArg[1]);
5009 }
drhc2ce0be2014-05-29 12:36:14 +00005010 }else{
drheacd29d2016-04-15 15:03:27 +00005011 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00005012 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00005013 }
drhefbf3b12014-02-28 20:47:24 +00005014 }else
5015
drhd3ac7d92013-01-25 18:33:43 +00005016 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00005017 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00005018 rc = 2;
drh75897232000-05-29 14:26:00 +00005019 }else
5020
drhc2ce0be2014-05-29 12:36:14 +00005021 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00005022 int val = 1;
5023 if( nArg>=2 ){
5024 if( strcmp(azArg[1],"auto")==0 ){
5025 val = 99;
5026 }else{
5027 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00005028 }
drh700c2522016-02-09 18:39:25 +00005029 }
5030 if( val==1 && p->mode!=MODE_Explain ){
5031 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00005032 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00005033 p->autoExplain = 0;
5034 }else if( val==0 ){
5035 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5036 p->autoExplain = 0;
5037 }else if( val==99 ){
5038 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5039 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005040 }
drh75897232000-05-29 14:26:00 +00005041 }else
5042
drhc1971542014-06-23 23:28:13 +00005043 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005044 ShellState data;
drhc1971542014-06-23 23:28:13 +00005045 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00005046 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00005047 memcpy(&data, p, sizeof(data));
5048 data.showHeader = 0;
5049 data.cMode = data.mode = MODE_Semi;
5050 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5051 data.cMode = data.mode = MODE_Pretty;
5052 nArg = 1;
5053 }
drhc1971542014-06-23 23:28:13 +00005054 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00005055 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00005056 rc = 1;
5057 goto meta_command_exit;
5058 }
5059 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00005060 rc = sqlite3_exec(p->db,
5061 "SELECT sql FROM"
5062 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5063 " FROM sqlite_master UNION ALL"
5064 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005065 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00005066 "ORDER BY rowid",
5067 callback, &data, &zErrMsg
5068 );
drh56f674c2014-07-18 14:43:29 +00005069 if( rc==SQLITE_OK ){
5070 sqlite3_stmt *pStmt;
5071 rc = sqlite3_prepare_v2(p->db,
5072 "SELECT rowid FROM sqlite_master"
5073 " WHERE name GLOB 'sqlite_stat[134]'",
5074 -1, &pStmt, 0);
5075 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5076 sqlite3_finalize(pStmt);
5077 }
5078 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005079 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00005080 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005081 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005082 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5083 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00005084 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00005085 data.zDestTable = "sqlite_stat1";
5086 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5087 shell_callback, &data,&zErrMsg);
5088 data.zDestTable = "sqlite_stat3";
5089 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5090 shell_callback, &data,&zErrMsg);
5091 data.zDestTable = "sqlite_stat4";
5092 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5093 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00005094 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005095 }
drhc1971542014-06-23 23:28:13 +00005096 }else
5097
drhc2ce0be2014-05-29 12:36:14 +00005098 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5099 if( nArg==2 ){
5100 p->showHeader = booleanValue(azArg[1]);
5101 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005102 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005103 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00005104 }
drh75897232000-05-29 14:26:00 +00005105 }else
5106
drhc2ce0be2014-05-29 12:36:14 +00005107 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005108 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00005109 }else
5110
5111 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00005112 char *zTable; /* Insert data into this table */
5113 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00005114 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00005115 int nCol; /* Number of columns in the table */
5116 int nByte; /* Number of bytes in an SQL string */
5117 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00005118 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00005119 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00005120 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00005121 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00005122 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5123 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00005124
drhc2ce0be2014-05-29 12:36:14 +00005125 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005126 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00005127 goto meta_command_exit;
5128 }
drh01f37542014-05-31 15:43:33 +00005129 zFile = azArg[1];
5130 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00005131 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00005132 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00005133 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005134 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00005135 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005136 raw_printf(stderr,
5137 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00005138 return 1;
drhfeac5f82004-08-01 00:10:45 +00005139 }
drhdb95f682013-06-26 22:46:00 +00005140 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005141 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00005142 " for import\n");
5143 return 1;
5144 }
mistachkin636bf9f2014-07-19 20:15:16 +00005145 nSep = strlen30(p->rowSeparator);
5146 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005147 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005148 return 1;
5149 }
mistachkine0d68852014-12-11 03:12:33 +00005150 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5151 /* When importing CSV (only), if the row separator is set to the
5152 ** default output row separator, change it to the default input
5153 ** row separator. This avoids having to maintain different input
5154 ** and output row separators. */
5155 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5156 nSep = strlen30(p->rowSeparator);
5157 }
mistachkin636bf9f2014-07-19 20:15:16 +00005158 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005159 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00005160 " for import\n");
5161 return 1;
5162 }
5163 sCtx.zFile = zFile;
5164 sCtx.nLine = 1;
5165 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005166#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005167 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005168 return 1;
5169#else
mistachkin636bf9f2014-07-19 20:15:16 +00005170 sCtx.in = popen(sCtx.zFile+1, "r");
5171 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00005172 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00005173#endif
drh5bde8162013-06-27 14:07:53 +00005174 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00005175 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00005176 xCloser = fclose;
5177 }
mistachkin636bf9f2014-07-19 20:15:16 +00005178 if( p->mode==MODE_Ascii ){
5179 xRead = ascii_read_one_field;
5180 }else{
5181 xRead = csv_read_one_field;
5182 }
5183 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005184 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00005185 return 1;
5186 }
mistachkin636bf9f2014-07-19 20:15:16 +00005187 sCtx.cColSep = p->colSeparator[0];
5188 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00005189 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00005190 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005191 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005192 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005193 return 1;
5194 }
drh4f21c4a2008-12-10 22:15:00 +00005195 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005196 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005197 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005198 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005199 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5200 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005201 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005202 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005203 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005204 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005205 }
drh5bde8162013-06-27 14:07:53 +00005206 if( cSep=='(' ){
5207 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005208 sqlite3_free(sCtx.z);
5209 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005210 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005211 return 1;
5212 }
drhdb95f682013-06-26 22:46:00 +00005213 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5214 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5215 sqlite3_free(zCreate);
5216 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005217 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005218 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005219 sqlite3_free(sCtx.z);
5220 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005221 return 1;
5222 }
drhc7181902014-02-27 15:04:13 +00005223 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005224 }
drhfeac5f82004-08-01 00:10:45 +00005225 sqlite3_free(zSql);
5226 if( rc ){
shane916f9612009-10-23 00:37:15 +00005227 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005228 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005229 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005230 return 1;
drhfeac5f82004-08-01 00:10:45 +00005231 }
shane916f9612009-10-23 00:37:15 +00005232 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005233 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005234 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005235 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005236 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005237 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005238 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005239 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005240 return 1;
5241 }
drhdb95f682013-06-26 22:46:00 +00005242 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005243 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005244 for(i=1; i<nCol; i++){
5245 zSql[j++] = ',';
5246 zSql[j++] = '?';
5247 }
5248 zSql[j++] = ')';
5249 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005250 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005251 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005252 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005253 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005254 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00005255 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00005256 return 1;
drhfeac5f82004-08-01 00:10:45 +00005257 }
mistachkin8e189222015-04-19 21:43:16 +00005258 needCommit = sqlite3_get_autocommit(p->db);
5259 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00005260 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005261 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005262 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005263 char *z = xRead(&sCtx);
5264 /*
5265 ** Did we reach end-of-file before finding any columns?
5266 ** If so, stop instead of NULL filling the remaining columns.
5267 */
drhdb95f682013-06-26 22:46:00 +00005268 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005269 /*
5270 ** Did we reach end-of-file OR end-of-line before finding any
5271 ** columns in ASCII mode? If so, stop instead of NULL filling
5272 ** the remaining columns.
5273 */
5274 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005275 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005276 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005277 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005278 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005279 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005280 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005281 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005282 }
drhfeac5f82004-08-01 00:10:45 +00005283 }
mistachkin636bf9f2014-07-19 20:15:16 +00005284 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005285 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005286 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005287 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005288 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005289 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005290 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005291 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005292 }
drhdb95f682013-06-26 22:46:00 +00005293 if( i>=nCol ){
5294 sqlite3_step(pStmt);
5295 rc = sqlite3_reset(pStmt);
5296 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005297 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5298 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005299 }
5300 }
mistachkin636bf9f2014-07-19 20:15:16 +00005301 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005302
mistachkin636bf9f2014-07-19 20:15:16 +00005303 xCloser(sCtx.in);
5304 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005305 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005306 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005307 }else
5308
drhd12602a2016-12-07 15:49:02 +00005309#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005310 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5311 char *zSql;
5312 char *zCollist = 0;
5313 sqlite3_stmt *pStmt;
5314 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005315 int i;
drh16eb5942016-11-03 13:01:38 +00005316 if( nArg!=3 ){
5317 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5318 rc = 1;
5319 goto meta_command_exit;
5320 }
5321 open_db(p, 0);
5322 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5323 " WHERE name='%q' AND type='index'", azArg[1]);
5324 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5325 sqlite3_free(zSql);
5326 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5327 tnum = sqlite3_column_int(pStmt, 0);
5328 }
5329 sqlite3_finalize(pStmt);
5330 if( tnum==0 ){
5331 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5332 rc = 1;
5333 goto meta_command_exit;
5334 }
5335 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5336 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5337 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005338 i = 0;
drh16eb5942016-11-03 13:01:38 +00005339 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005340 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005341 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005342 i++;
5343 if( zCol==0 ){
5344 if( sqlite3_column_int(pStmt,1)==-1 ){
5345 zCol = "_ROWID_";
5346 }else{
5347 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5348 zCol = zLabel;
5349 }
5350 }
drh16eb5942016-11-03 13:01:38 +00005351 if( zCollist==0 ){
5352 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5353 }else{
5354 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5355 }
5356 }
5357 sqlite3_finalize(pStmt);
5358 zSql = sqlite3_mprintf(
5359 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5360 azArg[2], zCollist, zCollist);
5361 sqlite3_free(zCollist);
5362 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5363 if( rc==SQLITE_OK ){
5364 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5365 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5366 if( rc ){
5367 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5368 }else{
5369 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005370 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005371 "WARNING: writing to an imposter table will corrupt the index!\n"
5372 );
5373 }
5374 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005375 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005376 rc = 1;
5377 }
5378 sqlite3_free(zSql);
5379 }else
5380#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5381
drhae5e4452007-05-03 17:18:36 +00005382#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005383 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005384 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005385 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5386 iotrace = 0;
5387 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005388 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005389 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005390 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005391 iotrace = stdout;
5392 }else{
5393 iotrace = fopen(azArg[1], "w");
5394 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005395 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005396 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005397 rc = 1;
drhb0603412007-02-28 04:47:26 +00005398 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005399 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005400 }
5401 }
5402 }else
drhae5e4452007-05-03 17:18:36 +00005403#endif
drh16eb5942016-11-03 13:01:38 +00005404
drh1a513372015-05-02 17:40:23 +00005405 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5406 static const struct {
5407 const char *zLimitName; /* Name of a limit */
5408 int limitCode; /* Integer code for that limit */
5409 } aLimit[] = {
5410 { "length", SQLITE_LIMIT_LENGTH },
5411 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5412 { "column", SQLITE_LIMIT_COLUMN },
5413 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5414 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5415 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5416 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5417 { "attached", SQLITE_LIMIT_ATTACHED },
5418 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5419 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5420 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5421 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5422 };
5423 int i, n2;
5424 open_db(p, 0);
5425 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005426 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005427 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005428 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5429 }
5430 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005431 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005432 rc = 1;
5433 goto meta_command_exit;
5434 }else{
5435 int iLimit = -1;
5436 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005437 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005438 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5439 if( iLimit<0 ){
5440 iLimit = i;
5441 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005442 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005443 rc = 1;
5444 goto meta_command_exit;
5445 }
5446 }
5447 }
5448 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005449 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005450 "enter \".limits\" with no arguments for a list.\n",
5451 azArg[1]);
5452 rc = 1;
5453 goto meta_command_exit;
5454 }
5455 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005456 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5457 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005458 }
5459 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5460 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5461 }
5462 }else
drhb0603412007-02-28 04:47:26 +00005463
dan3c7ebeb2016-12-16 17:28:56 +00005464 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005465 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005466 lintDotCommand(p, azArg, nArg);
5467 }else
5468
drh70df4fe2006-06-13 15:12:21 +00005469#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005470 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005471 const char *zFile, *zProc;
5472 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005473 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005474 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005475 rc = 1;
5476 goto meta_command_exit;
5477 }
drh1e397f82006-06-08 15:28:43 +00005478 zFile = azArg[1];
5479 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005480 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005481 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5482 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005483 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005484 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005485 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005486 }
5487 }else
drh70df4fe2006-06-13 15:12:21 +00005488#endif
drh1e397f82006-06-08 15:28:43 +00005489
drhc2ce0be2014-05-29 12:36:14 +00005490 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5491 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005492 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005493 rc = 1;
5494 }else{
5495 const char *zFile = azArg[1];
5496 output_file_close(p->pLog);
5497 p->pLog = output_file_open(zFile);
5498 }
drh127f9d72010-02-23 01:47:00 +00005499 }else
5500
drhc2ce0be2014-05-29 12:36:14 +00005501 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5502 const char *zMode = nArg>=2 ? azArg[1] : "";
5503 int n2 = (int)strlen(zMode);
5504 int c2 = zMode[0];
5505 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005506 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005507 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005508 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005509 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005510 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005511 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005512 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005513 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5514 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005515 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005516 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005517 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005518 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005519 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005520 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005521 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005522 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005523 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005524 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005525 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005526 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005527 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005528 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005529 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005530 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005531 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5532 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005533 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5534 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005535 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5536 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drhdaffd0e2001-04-11 14:28:42 +00005537 }else {
mistachkinaae280e2015-12-31 19:06:24 +00005538 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005539 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005540 rc = 1;
drh75897232000-05-29 14:26:00 +00005541 }
drh700c2522016-02-09 18:39:25 +00005542 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005543 }else
5544
drhc2ce0be2014-05-29 12:36:14 +00005545 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5546 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005547 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5548 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005549 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005550 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005551 rc = 1;
5552 }
5553 }else
5554
drh05782482013-10-24 15:20:20 +00005555 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005556 char *zNewFilename; /* Name of the database file to open */
5557 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005558 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005559 /* Close the existing database */
5560 session_close_all(p);
5561 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005562 p->db = 0;
dan21472212017-03-01 11:30:27 +00005563 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005564 sqlite3_free(p->zFreeOnClose);
5565 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005566 /* Check for command-line arguments */
5567 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5568 const char *z = azArg[iName];
5569 if( optionMatch(z,"new") ){
5570 newFlag = 1;
5571 }else if( z[0]=='-' ){
5572 utf8_printf(stderr, "unknown option: %s\n", z);
5573 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005574 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005575 }
drhcd0509e2016-09-16 00:26:08 +00005576 }
5577 /* If a filename is specified, try to open it first */
5578 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5579 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005580 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005581 p->zDbFilename = zNewFilename;
5582 open_db(p, 1);
5583 if( p->db==0 ){
5584 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5585 sqlite3_free(zNewFilename);
5586 }else{
5587 p->zFreeOnClose = zNewFilename;
5588 }
5589 }
5590 if( p->db==0 ){
5591 /* As a fall-back open a TEMP database */
5592 p->zDbFilename = 0;
5593 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005594 }
5595 }else
5596
drhc2ce0be2014-05-29 12:36:14 +00005597 if( c=='o'
5598 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5599 ){
5600 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5601 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005602 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005603 rc = 1;
5604 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005605 }
drhc2ce0be2014-05-29 12:36:14 +00005606 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5607 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005608 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005609 rc = 1;
5610 goto meta_command_exit;
5611 }
5612 p->outCount = 2;
5613 }else{
5614 p->outCount = 0;
5615 }
5616 output_reset(p);
5617 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005618#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005619 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005620 rc = 1;
5621 p->out = stdout;
5622#else
drhc2ce0be2014-05-29 12:36:14 +00005623 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005624 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005625 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005626 p->out = stdout;
5627 rc = 1;
5628 }else{
drhc2ce0be2014-05-29 12:36:14 +00005629 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005630 }
drh8cd5b252015-03-02 22:06:43 +00005631#endif
drh75897232000-05-29 14:26:00 +00005632 }else{
drhc2ce0be2014-05-29 12:36:14 +00005633 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005634 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005635 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005636 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005637 }
drh75897232000-05-29 14:26:00 +00005638 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005639 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005640 } else {
drhc2ce0be2014-05-29 12:36:14 +00005641 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005642 }
5643 }
5644 }else
5645
drh078b1fd2012-09-21 13:40:02 +00005646 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5647 int i;
5648 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005649 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005650 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005651 }
mistachkinaae280e2015-12-31 19:06:24 +00005652 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005653 }else
5654
drhc2ce0be2014-05-29 12:36:14 +00005655 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005656 if( nArg >= 2) {
5657 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5658 }
5659 if( nArg >= 3) {
5660 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5661 }
5662 }else
5663
drhc2ce0be2014-05-29 12:36:14 +00005664 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005665 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005666 }else
5667
drhc2ce0be2014-05-29 12:36:14 +00005668 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5669 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005670 if( nArg!=2 ){
5671 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005672 rc = 1;
5673 goto meta_command_exit;
5674 }
drh4e8142c2016-11-11 14:54:22 +00005675 alt = fopen(azArg[1], "rb");
5676 if( alt==0 ){
5677 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5678 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005679 }else{
drh4e8142c2016-11-11 14:54:22 +00005680 rc = process_input(p, alt);
5681 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005682 }
5683 }else
5684
drhc2ce0be2014-05-29 12:36:14 +00005685 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005686 const char *zSrcFile;
5687 const char *zDb;
5688 sqlite3 *pSrc;
5689 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005690 int nTimeout = 0;
5691
drh9ff849f2009-02-04 20:55:57 +00005692 if( nArg==2 ){
5693 zSrcFile = azArg[1];
5694 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005695 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005696 zSrcFile = azArg[2];
5697 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005698 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005699 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005700 rc = 1;
5701 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005702 }
5703 rc = sqlite3_open(zSrcFile, &pSrc);
5704 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005705 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005706 sqlite3_close(pSrc);
5707 return 1;
5708 }
drh05782482013-10-24 15:20:20 +00005709 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005710 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5711 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005712 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005713 sqlite3_close(pSrc);
5714 return 1;
5715 }
drhdc2c4912009-02-04 22:46:47 +00005716 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5717 || rc==SQLITE_BUSY ){
5718 if( rc==SQLITE_BUSY ){
5719 if( nTimeout++ >= 3 ) break;
5720 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005721 }
5722 }
5723 sqlite3_backup_finish(pBackup);
5724 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005725 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005726 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005727 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005728 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005729 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005730 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005731 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005732 }
5733 sqlite3_close(pSrc);
5734 }else
5735
dan8d1edb92014-11-05 09:07:28 +00005736
5737 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5738 if( nArg==2 ){
5739 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005740#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005741 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005742#endif
dan8d1edb92014-11-05 09:07:28 +00005743 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005744 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005745 rc = 1;
5746 }
5747 }else
5748
drhc2ce0be2014-05-29 12:36:14 +00005749 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drh20c9c3f2017-06-15 12:21:09 +00005750 ShellText sSelect;
drhdcd87a92014-08-18 13:45:42 +00005751 ShellState data;
drh75897232000-05-29 14:26:00 +00005752 char *zErrMsg = 0;
drh20c9c3f2017-06-15 12:21:09 +00005753 const char *zDiv = 0;
5754 int iSchema = 0;
5755
drh05782482013-10-24 15:20:20 +00005756 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005757 memcpy(&data, p, sizeof(data));
5758 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005759 data.cMode = data.mode = MODE_Semi;
drh20c9c3f2017-06-15 12:21:09 +00005760 initText(&sSelect);
drh4926fec2016-04-13 15:33:42 +00005761 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5762 data.cMode = data.mode = MODE_Pretty;
5763 nArg--;
5764 if( nArg==2 ) azArg[1] = azArg[2];
5765 }
5766 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005767 int i;
drhf0693c82011-10-11 20:41:54 +00005768 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005769 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005770 char *new_argv[2], *new_colv[2];
5771 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5772 " type text,\n"
5773 " name text,\n"
5774 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005775 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005776 " sql text\n"
5777 ")";
5778 new_argv[1] = 0;
5779 new_colv[0] = "sql";
5780 new_colv[1] = 0;
5781 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005782 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005783 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005784 char *new_argv[2], *new_colv[2];
5785 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5786 " type text,\n"
5787 " name text,\n"
5788 " tbl_name text,\n"
5789 " rootpage integer,\n"
5790 " sql text\n"
5791 ")";
5792 new_argv[1] = 0;
5793 new_colv[0] = "sql";
5794 new_colv[1] = 0;
5795 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005796 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005797 }else{
drh20c9c3f2017-06-15 12:21:09 +00005798 zDiv = "(";
drha18c5682000-10-08 22:20:57 +00005799 }
drhc2ce0be2014-05-29 12:36:14 +00005800 }else if( nArg==1 ){
drh20c9c3f2017-06-15 12:21:09 +00005801 zDiv = "(";
drhc2ce0be2014-05-29 12:36:14 +00005802 }else{
drh4926fec2016-04-13 15:33:42 +00005803 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005804 rc = 1;
5805 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005806 }
drh20c9c3f2017-06-15 12:21:09 +00005807 if( zDiv ){
5808 sqlite3_stmt *pStmt = 0;
5809 sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
5810 -1, &pStmt, 0);
5811 appendText(&sSelect, "SELECT sql FROM", 0);
5812 iSchema = 0;
5813 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5814 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
5815 char zScNum[30];
5816 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
5817 appendText(&sSelect, zDiv, 0);
5818 zDiv = " UNION ALL ";
5819 if( strcmp(zDb, "main")!=0 ){
5820 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
drh90cdec02017-06-15 13:07:56 +00005821 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00005822 appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
5823 appendText(&sSelect, zScNum, 0);
5824 appendText(&sSelect, " AS snum, ", 0);
5825 appendText(&sSelect, zDb, '\'');
5826 appendText(&sSelect, " AS sname FROM ", 0);
drh90cdec02017-06-15 13:07:56 +00005827 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00005828 appendText(&sSelect, ".sqlite_master", 0);
5829 }else{
5830 appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5831 appendText(&sSelect, zScNum, 0);
5832 appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
5833 }
5834 }
5835 sqlite3_finalize(pStmt);
5836 appendText(&sSelect, ") WHERE ", 0);
5837 if( nArg>1 ){
5838 char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
5839 if( strchr(azArg[1], '.') ){
5840 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
5841 }else{
5842 appendText(&sSelect, "lower(tbl_name)", 0);
5843 }
5844 appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
5845 appendText(&sSelect, zQarg, 0);
5846 appendText(&sSelect, " AND ", 0);
5847 sqlite3_free(zQarg);
5848 }
5849 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
5850 " ORDER BY snum, rowid", 0);
5851 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
5852 freeText(&sSelect);
5853 }
drh75897232000-05-29 14:26:00 +00005854 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005855 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005856 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005857 rc = 1;
5858 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005859 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005860 rc = 1;
5861 }else{
5862 rc = 0;
drh75897232000-05-29 14:26:00 +00005863 }
5864 }else
5865
drhabd4c722014-09-20 18:18:33 +00005866#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5867 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005868 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005869 }else
5870#endif
5871
drhe6229612014-08-18 15:08:26 +00005872#if defined(SQLITE_ENABLE_SESSION)
5873 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5874 OpenSession *pSession = &p->aSession[0];
5875 char **azCmd = &azArg[1];
5876 int iSes = 0;
5877 int nCmd = nArg - 1;
5878 int i;
5879 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005880 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005881 if( nArg>=3 ){
5882 for(iSes=0; iSes<p->nSession; iSes++){
5883 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5884 }
5885 if( iSes<p->nSession ){
5886 pSession = &p->aSession[iSes];
5887 azCmd++;
5888 nCmd--;
5889 }else{
5890 pSession = &p->aSession[0];
5891 iSes = 0;
5892 }
5893 }
5894
drh3a67b042014-08-18 17:56:31 +00005895 /* .session attach TABLE
5896 ** Invoke the sqlite3session_attach() interface to attach a particular
5897 ** table so that it is never filtered.
5898 */
5899 if( strcmp(azCmd[0],"attach")==0 ){
5900 if( nCmd!=2 ) goto session_syntax_error;
5901 if( pSession->p==0 ){
5902 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005903 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005904 }else{
5905 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5906 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005907 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005908 rc = 0;
5909 }
5910 }
5911 }else
5912
5913 /* .session changeset FILE
5914 ** .session patchset FILE
5915 ** Write a changeset or patchset into a file. The file is overwritten.
5916 */
5917 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5918 FILE *out = 0;
5919 if( nCmd!=2 ) goto session_syntax_error;
5920 if( pSession->p==0 ) goto session_not_open;
5921 out = fopen(azCmd[1], "wb");
5922 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005923 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005924 }else{
5925 int szChng;
5926 void *pChng;
5927 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005928 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005929 }else{
drh2967e0c2014-08-19 00:26:17 +00005930 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5931 }
5932 if( rc ){
5933 printf("Error: error code %d\n", rc);
5934 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005935 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005936 if( pChng
drh3a67b042014-08-18 17:56:31 +00005937 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005938 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005939 szChng);
5940 }
5941 sqlite3_free(pChng);
5942 fclose(out);
5943 }
5944 }else
5945
drhe6229612014-08-18 15:08:26 +00005946 /* .session close
5947 ** Close the identified session
5948 */
5949 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005950 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005951 if( p->nSession ){
5952 session_close(pSession);
5953 p->aSession[iSes] = p->aSession[--p->nSession];
5954 }
5955 }else
5956
drh03168ca2014-08-18 20:01:31 +00005957 /* .session enable ?BOOLEAN?
5958 ** Query or set the enable flag
5959 */
5960 if( strcmp(azCmd[0], "enable")==0 ){
5961 int ii;
5962 if( nCmd>2 ) goto session_syntax_error;
5963 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5964 if( p->nSession ){
5965 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005966 utf8_printf(p->out, "session %s enable flag = %d\n",
5967 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005968 }
5969 }else
5970
5971 /* .session filter GLOB ....
5972 ** Set a list of GLOB patterns of table names to be excluded.
5973 */
5974 if( strcmp(azCmd[0], "filter")==0 ){
5975 int ii, nByte;
5976 if( nCmd<2 ) goto session_syntax_error;
5977 if( p->nSession ){
5978 for(ii=0; ii<pSession->nFilter; ii++){
5979 sqlite3_free(pSession->azFilter[ii]);
5980 }
5981 sqlite3_free(pSession->azFilter);
5982 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5983 pSession->azFilter = sqlite3_malloc( nByte );
5984 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005985 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00005986 exit(1);
5987 }
5988 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005989 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00005990 }
5991 pSession->nFilter = ii-1;
5992 }
5993 }else
5994
5995 /* .session indirect ?BOOLEAN?
5996 ** Query or set the indirect flag
5997 */
5998 if( strcmp(azCmd[0], "indirect")==0 ){
5999 int ii;
6000 if( nCmd>2 ) goto session_syntax_error;
6001 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6002 if( p->nSession ){
6003 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00006004 utf8_printf(p->out, "session %s indirect flag = %d\n",
6005 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006006 }
6007 }else
6008
6009 /* .session isempty
6010 ** Determine if the session is empty
6011 */
6012 if( strcmp(azCmd[0], "isempty")==0 ){
6013 int ii;
6014 if( nCmd!=1 ) goto session_syntax_error;
6015 if( p->nSession ){
6016 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00006017 utf8_printf(p->out, "session %s isempty flag = %d\n",
6018 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006019 }
6020 }else
6021
drhe6229612014-08-18 15:08:26 +00006022 /* .session list
6023 ** List all currently open sessions
6024 */
6025 if( strcmp(azCmd[0],"list")==0 ){
6026 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00006027 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00006028 }
6029 }else
6030
6031 /* .session open DB NAME
6032 ** Open a new session called NAME on the attached database DB.
6033 ** DB is normally "main".
6034 */
6035 if( strcmp(azCmd[0],"open")==0 ){
6036 char *zName;
6037 if( nCmd!=3 ) goto session_syntax_error;
6038 zName = azCmd[2];
6039 if( zName[0]==0 ) goto session_syntax_error;
6040 for(i=0; i<p->nSession; i++){
6041 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006042 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00006043 goto meta_command_exit;
6044 }
6045 }
6046 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00006047 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00006048 goto meta_command_exit;
6049 }
6050 pSession = &p->aSession[p->nSession];
6051 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6052 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00006053 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00006054 rc = 0;
drhe6229612014-08-18 15:08:26 +00006055 goto meta_command_exit;
6056 }
drh03168ca2014-08-18 20:01:31 +00006057 pSession->nFilter = 0;
6058 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00006059 p->nSession++;
6060 pSession->zName = sqlite3_mprintf("%s", zName);
6061 }else
6062 /* If no command name matches, show a syntax error */
6063 session_syntax_error:
6064 session_help(p);
6065 }else
6066#endif
6067
drh340f5822013-06-27 13:01:21 +00006068#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00006069 /* Undocumented commands for internal testing. Subject to change
6070 ** without notice. */
6071 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6072 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6073 int i, v;
6074 for(i=1; i<nArg; i++){
6075 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00006076 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00006077 }
6078 }
6079 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6080 int i; sqlite3_int64 v;
6081 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00006082 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00006083 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00006084 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00006085 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00006086 }
6087 }
6088 }else
drh340f5822013-06-27 13:01:21 +00006089#endif
drh348d19c2013-06-03 12:47:43 +00006090
drhfb546af2017-03-09 22:00:33 +00006091 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6092 int bIsInit = 0; /* True to initialize the SELFTEST table */
6093 int bVerbose = 0; /* Verbose output */
6094 int bSelftestExists; /* True if SELFTEST already exists */
drhc5d353f2017-06-09 02:27:49 +00006095 int i, k; /* Loop counters */
drhfb546af2017-03-09 22:00:33 +00006096 int nTest = 0; /* Number of tests runs */
6097 int nErr = 0; /* Number of errors seen */
6098 ShellText str; /* Answer for a query */
drhc5d353f2017-06-09 02:27:49 +00006099 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
drhfb546af2017-03-09 22:00:33 +00006100
6101 open_db(p,0);
6102 for(i=1; i<nArg; i++){
6103 const char *z = azArg[i];
6104 if( z[0]=='-' && z[1]=='-' ) z++;
6105 if( strcmp(z,"-init")==0 ){
6106 bIsInit = 1;
6107 }else
6108 if( strcmp(z,"-v")==0 ){
6109 bVerbose++;
6110 }else
6111 {
6112 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6113 azArg[i], azArg[0]);
6114 raw_printf(stderr, "Should be one of: --init -v\n");
6115 rc = 1;
6116 goto meta_command_exit;
6117 }
6118 }
6119 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6120 != SQLITE_OK ){
6121 bSelftestExists = 0;
6122 }else{
6123 bSelftestExists = 1;
6124 }
6125 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006126 createSelftestTable(p);
6127 bSelftestExists = 1;
6128 }
drhc5d353f2017-06-09 02:27:49 +00006129 initText(&str);
6130 appendText(&str, "x", 0);
6131 for(k=bSelftestExists; k>=0; k--){
6132 if( k==1 ){
6133 rc = sqlite3_prepare_v2(p->db,
6134 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6135 -1, &pStmt, 0);
6136 }else{
6137 rc = sqlite3_prepare_v2(p->db,
6138 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6139 " (1,'run','PRAGMA integrity_check','ok')",
6140 -1, &pStmt, 0);
6141 }
drhfb546af2017-03-09 22:00:33 +00006142 if( rc ){
6143 raw_printf(stderr, "Error querying the selftest table\n");
6144 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006145 sqlite3_finalize(pStmt);
drhfb546af2017-03-09 22:00:33 +00006146 goto meta_command_exit;
drhfb546af2017-03-09 22:00:33 +00006147 }
drhc5d353f2017-06-09 02:27:49 +00006148 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6149 int tno = sqlite3_column_int(pStmt, 0);
6150 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6151 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6152 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
mistachkine16a3502017-05-29 03:48:13 +00006153
drhc5d353f2017-06-09 02:27:49 +00006154 k = 0;
6155 if( bVerbose>0 ){
6156 char *zQuote = sqlite3_mprintf("%q", zSql);
6157 printf("%d: %s %s\n", tno, zOp, zSql);
6158 sqlite3_free(zQuote);
drhfb546af2017-03-09 22:00:33 +00006159 }
drhc5d353f2017-06-09 02:27:49 +00006160 if( strcmp(zOp,"memo")==0 ){
6161 utf8_printf(p->out, "%s\n", zSql);
6162 }else
6163 if( strcmp(zOp,"run")==0 ){
6164 char *zErrMsg = 0;
6165 str.n = 0;
6166 str.z[0] = 0;
6167 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6168 nTest++;
6169 if( bVerbose ){
6170 utf8_printf(p->out, "Result: %s\n", str.z);
6171 }
6172 if( rc || zErrMsg ){
6173 nErr++;
6174 rc = 1;
6175 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6176 sqlite3_free(zErrMsg);
6177 }else if( strcmp(zAns,str.z)!=0 ){
6178 nErr++;
6179 rc = 1;
6180 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6181 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6182 }
6183 }else
6184 {
6185 utf8_printf(stderr,
6186 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
drhfb546af2017-03-09 22:00:33 +00006187 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006188 break;
drhfb546af2017-03-09 22:00:33 +00006189 }
drhc5d353f2017-06-09 02:27:49 +00006190 } /* End loop over rows of content from SELFTEST */
6191 sqlite3_finalize(pStmt);
6192 } /* End loop over k */
drhfb546af2017-03-09 22:00:33 +00006193 freeText(&str);
drhfb546af2017-03-09 22:00:33 +00006194 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6195 }else
6196
drhc2ce0be2014-05-29 12:36:14 +00006197 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006198 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006199 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006200 rc = 1;
6201 }
drh6976c212014-07-24 12:09:47 +00006202 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006203 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006204 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006205 }
6206 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006207 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6208 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006209 }
drh75897232000-05-29 14:26:00 +00006210 }else
6211
drh1554bc82017-03-08 16:10:34 +00006212 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6213 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6214 int i; /* Loop counter */
6215 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006216 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006217 int iSize = 224; /* Hash algorithm to use */
6218 int bDebug = 0; /* Only show the query that would have run */
6219 sqlite3_stmt *pStmt; /* For querying tables names */
6220 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006221 char *zSep; /* Separator */
6222 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006223 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006224 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006225 for(i=1; i<nArg; i++){
6226 const char *z = azArg[i];
6227 if( z[0]=='-' ){
6228 z++;
6229 if( z[0]=='-' ) z++;
6230 if( strcmp(z,"schema")==0 ){
6231 bSchema = 1;
6232 }else
mistachkine16a3502017-05-29 03:48:13 +00006233 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6234 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
drh1554bc82017-03-08 16:10:34 +00006235 ){
6236 iSize = atoi(&z[5]);
6237 }else
6238 if( strcmp(z,"debug")==0 ){
6239 bDebug = 1;
6240 }else
6241 {
6242 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006243 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006244 raw_printf(stderr, "Should be one of: --schema"
6245 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6246 rc = 1;
6247 goto meta_command_exit;
6248 }
6249 }else if( zLike ){
6250 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6251 rc = 1;
6252 goto meta_command_exit;
6253 }else{
6254 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006255 bSeparate = 1;
6256 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006257 }
6258 }
6259 if( bSchema ){
6260 zSql = "SELECT lower(name) FROM sqlite_master"
6261 " WHERE type='table' AND coalesce(rootpage,0)>1"
6262 " UNION ALL SELECT 'sqlite_master'"
6263 " ORDER BY 1 collate nocase";
6264 }else{
6265 zSql = "SELECT lower(name) FROM sqlite_master"
6266 " WHERE type='table' AND coalesce(rootpage,0)>1"
6267 " AND name NOT LIKE 'sqlite_%'"
6268 " ORDER BY 1 collate nocase";
6269 }
6270 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6271 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006272 initText(&sSql);
6273 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6274 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006275 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6276 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6277 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6278 if( strncmp(zTab, "sqlite_",7)!=0 ){
6279 appendText(&sQuery,"SELECT * FROM ", 0);
6280 appendText(&sQuery,zTab,'"');
6281 appendText(&sQuery," NOT INDEXED;", 0);
6282 }else if( strcmp(zTab, "sqlite_master")==0 ){
6283 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6284 " ORDER BY name;", 0);
6285 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6286 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6287 " ORDER BY name;", 0);
6288 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6289 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6290 " ORDER BY tbl,idx;", 0);
6291 }else if( strcmp(zTab, "sqlite_stat3")==0
6292 || strcmp(zTab, "sqlite_stat4")==0 ){
6293 appendText(&sQuery, "SELECT * FROM ", 0);
6294 appendText(&sQuery, zTab, 0);
6295 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6296 }
drh3ee83ef2017-03-08 17:56:54 +00006297 appendText(&sSql, zSep, 0);
6298 appendText(&sSql, sQuery.z, '\'');
6299 sQuery.n = 0;
6300 appendText(&sSql, ",", 0);
6301 appendText(&sSql, zTab, '\'');
6302 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006303 }
6304 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006305 if( bSeparate ){
6306 zSql = sqlite3_mprintf(
6307 "%s))"
6308 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6309 " FROM [sha3sum$query]",
6310 sSql.z, iSize);
6311 }else{
6312 zSql = sqlite3_mprintf(
6313 "%s))"
6314 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6315 " FROM [sha3sum$query]",
6316 sSql.z, iSize);
6317 }
drh1554bc82017-03-08 16:10:34 +00006318 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006319 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006320 if( bDebug ){
6321 utf8_printf(p->out, "%s\n", zSql);
6322 }else{
6323 shell_exec(p->db, zSql, shell_callback, p, 0);
6324 }
6325 sqlite3_free(zSql);
6326 }else
6327
drh62cdde52014-05-28 20:22:28 +00006328 if( c=='s'
6329 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006330 ){
6331 char *zCmd;
drh54027102014-08-06 14:36:53 +00006332 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006333 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006334 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006335 rc = 1;
6336 goto meta_command_exit;
6337 }
drhdcb3e3d2014-05-29 03:17:29 +00006338 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006339 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006340 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6341 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006342 }
drh54027102014-08-06 14:36:53 +00006343 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006344 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006345 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006346 }else
6347
drhc2ce0be2014-05-29 12:36:14 +00006348 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006349 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006350 int i;
drhc2ce0be2014-05-29 12:36:14 +00006351 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006352 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006353 rc = 1;
6354 goto meta_command_exit;
6355 }
drhe6e1d122017-03-09 13:50:49 +00006356 utf8_printf(p->out, "%12.12s: %s\n","echo",
6357 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006358 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006359 utf8_printf(p->out, "%12.12s: %s\n","explain",
6360 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006361 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006362 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6363 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006364 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006365 raw_printf(p->out, "\n");
6366 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006367 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006368 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006369 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006370 raw_printf(p->out, "\n");
6371 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006372 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006373 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006374 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006375 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006376 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006377 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006378 }
mistachkinaae280e2015-12-31 19:06:24 +00006379 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006380 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6381 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006382 }else
6383
drhc2ce0be2014-05-29 12:36:14 +00006384 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6385 if( nArg==2 ){
6386 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006387 }else if( nArg==1 ){
6388 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006389 }else{
drh34784902016-02-27 17:12:36 +00006390 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006391 rc = 1;
6392 }
shaneh642d8b82010-07-28 16:05:34 +00006393 }else
6394
drh6a5a4202016-12-24 21:32:40 +00006395 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6396 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6397 || strncmp(azArg[0], "indexes", n)==0) )
6398 ){
drh98781232012-04-23 12:38:05 +00006399 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006400 char **azResult;
drh98781232012-04-23 12:38:05 +00006401 int nRow, nAlloc;
drh98781232012-04-23 12:38:05 +00006402 int ii;
drh594ccd02017-06-15 12:50:47 +00006403 ShellText s;
6404 initText(&s);
drh05782482013-10-24 15:20:20 +00006405 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006406 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006407 if( rc ) return shellDatabaseError(p->db);
6408
drh594ccd02017-06-15 12:50:47 +00006409 if( nArg>2 && c=='i' ){
drh6a5a4202016-12-24 21:32:40 +00006410 /* It is an historical accident that the .indexes command shows an error
6411 ** when called with the wrong number of arguments whereas the .tables
6412 ** command does not. */
6413 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6414 rc = 1;
6415 goto meta_command_exit;
drh6a5a4202016-12-24 21:32:40 +00006416 }
drh594ccd02017-06-15 12:50:47 +00006417 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006418 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drh594ccd02017-06-15 12:50:47 +00006419 if( zDbName==0 ) continue;
6420 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6421 if( sqlite3_stricmp(zDbName, "main")==0 ){
6422 appendText(&s, "SELECT name FROM ", 0);
drh6a5a4202016-12-24 21:32:40 +00006423 }else{
drh594ccd02017-06-15 12:50:47 +00006424 appendText(&s, "SELECT ", 0);
6425 appendText(&s, zDbName, '\'');
6426 appendText(&s, "||'.'||name FROM ", 0);
6427 }
6428 appendText(&s, zDbName, '"');
6429 appendText(&s, ".sqlite_master ", 0);
6430 if( c=='t' ){
6431 appendText(&s," WHERE type IN ('table','view')"
6432 " AND name NOT LIKE 'sqlite_%'"
6433 " AND name LIKE ?1", 0);
6434 }else{
6435 appendText(&s," WHERE type='index'"
6436 " AND tbl_name LIKE ?1", 0);
drh98781232012-04-23 12:38:05 +00006437 }
drha50da102000-08-08 20:19:09 +00006438 }
dand95bb392015-09-30 11:19:05 +00006439 rc = sqlite3_finalize(pStmt);
drh594ccd02017-06-15 12:50:47 +00006440 appendText(&s, " ORDER BY 1", 0);
6441 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6442 freeText(&s);
dand95bb392015-09-30 11:19:05 +00006443 if( rc ) return shellDatabaseError(p->db);
6444
6445 /* Run the SQL statement prepared by the above block. Store the results
6446 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006447 nRow = nAlloc = 0;
6448 azResult = 0;
6449 if( nArg>1 ){
6450 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006451 }else{
drh98781232012-04-23 12:38:05 +00006452 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6453 }
6454 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6455 if( nRow>=nAlloc ){
6456 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006457 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006458 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006459 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006460 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006461 break;
6462 }
mistachkin8e189222015-04-19 21:43:16 +00006463 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006464 azResult = azNew;
6465 }
6466 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006467 if( 0==azResult[nRow] ){
6468 rc = shellNomemError();
6469 break;
6470 }
6471 nRow++;
drh98781232012-04-23 12:38:05 +00006472 }
dand95bb392015-09-30 11:19:05 +00006473 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6474 rc = shellDatabaseError(p->db);
6475 }
6476
6477 /* Pretty-print the contents of array azResult[] to the output */
6478 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006479 int len, maxlen = 0;
6480 int i, j;
6481 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006482 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006483 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006484 if( len>maxlen ) maxlen = len;
6485 }
6486 nPrintCol = 80/(maxlen+2);
6487 if( nPrintCol<1 ) nPrintCol = 1;
6488 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6489 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006490 for(j=i; j<nRow; j+=nPrintRow){
6491 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006492 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6493 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006494 }
mistachkinaae280e2015-12-31 19:06:24 +00006495 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006496 }
6497 }
dand95bb392015-09-30 11:19:05 +00006498
drh98781232012-04-23 12:38:05 +00006499 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6500 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006501 }else
6502
drh2db82112016-09-15 21:35:24 +00006503 /* Begin redirecting output to the file "testcase-out.txt" */
6504 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6505 output_reset(p);
6506 p->out = output_file_open("testcase-out.txt");
6507 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006508 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006509 }
drh760c8162016-09-16 02:52:22 +00006510 if( nArg>=2 ){
6511 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6512 }else{
6513 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6514 }
drh2db82112016-09-15 21:35:24 +00006515 }else
drh2db82112016-09-15 21:35:24 +00006516
drhd12602a2016-12-07 15:49:02 +00006517#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006518 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006519 static const struct {
6520 const char *zCtrlName; /* Name of a test-control option */
6521 int ctrlCode; /* Integer code for that option */
6522 } aCtrl[] = {
6523 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6524 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6525 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6526 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6527 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6528 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6529 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6530 { "assert", SQLITE_TESTCTRL_ASSERT },
6531 { "always", SQLITE_TESTCTRL_ALWAYS },
6532 { "reserve", SQLITE_TESTCTRL_RESERVE },
6533 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6534 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006535 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006536 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006537 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006538 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006539 };
shaneh96887e12011-02-10 21:08:58 +00006540 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006541 int rc2 = 0;
6542 int i, n2;
drh05782482013-10-24 15:20:20 +00006543 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006544
drhd416fe72011-03-17 16:45:50 +00006545 /* convert testctrl text option to value. allow any unique prefix
6546 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006547 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006548 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006549 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006550 if( testctrl<0 ){
6551 testctrl = aCtrl[i].ctrlCode;
6552 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006553 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006554 testctrl = -1;
6555 break;
6556 }
6557 }
6558 }
drh348d19c2013-06-03 12:47:43 +00006559 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006560 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006561 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006562 }else{
6563 switch(testctrl){
6564
6565 /* sqlite3_test_control(int, db, int) */
6566 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006567 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006568 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006569 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006570 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006571 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006572 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006573 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006574 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006575 }
6576 break;
6577
6578 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006579 case SQLITE_TESTCTRL_PRNG_SAVE:
6580 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006581 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006582 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006583 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006584 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006585 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006586 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006587 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6588 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006589 }
6590 break;
6591
6592 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006593 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006594 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006595 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006596 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006597 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006598 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006599 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006600 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006601 }
6602 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006603
shaneh96887e12011-02-10 21:08:58 +00006604 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006605 case SQLITE_TESTCTRL_ASSERT:
6606 case SQLITE_TESTCTRL_ALWAYS:
6607 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006608 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006609 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006610 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006611 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006612 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006613 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006614 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006615 }
6616 break;
6617
6618 /* sqlite3_test_control(int, char *) */
6619#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006620 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006621 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006622 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006623 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006624 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006625 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006626 utf8_printf(stderr,
6627 "Error: testctrl %s takes a single char * option\n",
6628 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006629 }
6630 break;
6631#endif
6632
drh1ffede82015-01-30 20:59:27 +00006633 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006634 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006635 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006636 azArg[2],
drh8964b342015-01-29 17:54:52 +00006637 integerValue(azArg[3]),
6638 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006639 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006640 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006641 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006642 }
6643 break;
6644
mistachkin1fe36bb2016-04-04 02:16:44 +00006645 case SQLITE_TESTCTRL_BITVEC_TEST:
6646 case SQLITE_TESTCTRL_FAULT_INSTALL:
6647 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6648 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006649 default:
mistachkinaae280e2015-12-31 19:06:24 +00006650 utf8_printf(stderr,
6651 "Error: CLI support for testctrl %s not implemented\n",
6652 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006653 break;
6654 }
6655 }
6656 }else
drhf1969722017-02-17 23:52:00 +00006657#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006658
drhc2ce0be2014-05-29 12:36:14 +00006659 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006660 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006661 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006662 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006663
drhc2ce0be2014-05-29 12:36:14 +00006664 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6665 if( nArg==2 ){
6666 enableTimer = booleanValue(azArg[1]);
6667 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006668 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006669 enableTimer = 0;
6670 }
6671 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006672 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006673 rc = 1;
6674 }
shanehe2aa9d72009-11-06 17:20:17 +00006675 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006676
drhc2ce0be2014-05-29 12:36:14 +00006677 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006678 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006679 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006680 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006681 rc = 1;
6682 goto meta_command_exit;
6683 }
drh657b4a82015-03-19 13:30:41 +00006684 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006685 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006686#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006687 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006688 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006689 }else{
drh4b363a52016-07-23 20:27:41 +00006690 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006691 }
6692#endif
6693 }else
6694
drhf442e332014-09-10 19:01:14 +00006695#if SQLITE_USER_AUTHENTICATION
6696 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6697 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006698 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006699 rc = 1;
6700 goto meta_command_exit;
6701 }
drh7883ecf2014-09-11 16:19:31 +00006702 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006703 if( strcmp(azArg[1],"login")==0 ){
6704 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006705 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006706 rc = 1;
6707 goto meta_command_exit;
6708 }
drhd39c40f2014-09-11 00:27:53 +00006709 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6710 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006711 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006712 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006713 rc = 1;
6714 }
6715 }else if( strcmp(azArg[1],"add")==0 ){
6716 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006717 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006718 rc = 1;
6719 goto meta_command_exit;
6720 }
drhd39c40f2014-09-11 00:27:53 +00006721 rc = sqlite3_user_add(p->db, azArg[2],
6722 azArg[3], (int)strlen(azArg[3]),
6723 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006724 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006725 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006726 rc = 1;
6727 }
6728 }else if( strcmp(azArg[1],"edit")==0 ){
6729 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006730 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006731 rc = 1;
6732 goto meta_command_exit;
6733 }
drhd39c40f2014-09-11 00:27:53 +00006734 rc = sqlite3_user_change(p->db, azArg[2],
6735 azArg[3], (int)strlen(azArg[3]),
6736 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006737 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006738 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006739 rc = 1;
6740 }
6741 }else if( strcmp(azArg[1],"delete")==0 ){
6742 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006743 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006744 rc = 1;
6745 goto meta_command_exit;
6746 }
6747 rc = sqlite3_user_delete(p->db, azArg[2]);
6748 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006749 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006750 rc = 1;
6751 }
6752 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006753 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006754 rc = 1;
6755 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006756 }
drhf442e332014-09-10 19:01:14 +00006757 }else
6758#endif /* SQLITE_USER_AUTHENTICATION */
6759
drh9fd301b2011-06-03 13:28:22 +00006760 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006761 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006762 sqlite3_libversion(), sqlite3_sourceid());
6763 }else
6764
drh790f2872015-11-28 18:06:36 +00006765 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6766 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006767 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006768 if( p->db ){
6769 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6770 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006771 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6772 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6773 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6774 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006775 }
6776 }
6777 }else
6778
drhb19e7352016-01-12 19:37:20 +00006779 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6780 sqlite3_vfs *pVfs;
6781 sqlite3_vfs *pCurrent = 0;
6782 if( p->db ){
6783 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6784 }
6785 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6786 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6787 pVfs==pCurrent ? " <--- CURRENT" : "");
6788 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6789 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6790 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6791 if( pVfs->pNext ){
6792 raw_printf(p->out, "-----------------------------------\n");
6793 }
6794 }
6795 }else
6796
drhde60fc22011-12-14 17:53:36 +00006797 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6798 const char *zDbName = nArg==2 ? azArg[1] : "main";
6799 char *zVfsName = 0;
6800 if( p->db ){
6801 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6802 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006803 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006804 sqlite3_free(zVfsName);
6805 }
6806 }
6807 }else
6808
drhcef4fc82012-09-21 22:50:45 +00006809#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6810 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006811 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006812 }else
6813#endif
6814
drhc2ce0be2014-05-29 12:36:14 +00006815 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006816 int j;
drh43617e92006-03-06 20:55:46 +00006817 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006818 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006819 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006820 }
6821 }else
6822
6823 {
mistachkinaae280e2015-12-31 19:06:24 +00006824 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006825 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006826 rc = 1;
drh75897232000-05-29 14:26:00 +00006827 }
drh67505e72002-04-19 12:34:06 +00006828
drhc2ce0be2014-05-29 12:36:14 +00006829meta_command_exit:
6830 if( p->outCount ){
6831 p->outCount--;
6832 if( p->outCount==0 ) output_reset(p);
6833 }
drh67505e72002-04-19 12:34:06 +00006834 return rc;
drh75897232000-05-29 14:26:00 +00006835}
6836
drh67505e72002-04-19 12:34:06 +00006837/*
drh91a66392007-09-07 01:12:32 +00006838** Return TRUE if a semicolon occurs anywhere in the first N characters
6839** of string z[].
drh324ccef2003-02-05 14:06:20 +00006840*/
drh9f099fd2013-08-06 14:01:46 +00006841static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006842 int i;
6843 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6844 return 0;
drh324ccef2003-02-05 14:06:20 +00006845}
6846
6847/*
drh70c7a4b2003-04-26 03:03:06 +00006848** Test to see if a line consists entirely of whitespace.
6849*/
6850static int _all_whitespace(const char *z){
6851 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006852 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006853 if( *z=='/' && z[1]=='*' ){
6854 z += 2;
6855 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6856 if( *z==0 ) return 0;
6857 z++;
6858 continue;
6859 }
6860 if( *z=='-' && z[1]=='-' ){
6861 z += 2;
6862 while( *z && *z!='\n' ){ z++; }
6863 if( *z==0 ) return 1;
6864 continue;
6865 }
6866 return 0;
6867 }
6868 return 1;
6869}
6870
6871/*
drha9b17162003-04-29 18:01:28 +00006872** Return TRUE if the line typed in is an SQL command terminator other
6873** than a semi-colon. The SQL Server style "go" command is understood
6874** as is the Oracle "/".
6875*/
drh9f099fd2013-08-06 14:01:46 +00006876static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006877 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006878 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6879 return 1; /* Oracle */
6880 }
drhf0693c82011-10-11 20:41:54 +00006881 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006882 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006883 return 1; /* SQL Server */
6884 }
6885 return 0;
6886}
6887
6888/*
drh233a5312008-12-18 22:25:13 +00006889** Return true if zSql is a complete SQL statement. Return false if it
6890** ends in the middle of a string literal or C-style comment.
6891*/
drh9f099fd2013-08-06 14:01:46 +00006892static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006893 int rc;
6894 if( zSql==0 ) return 1;
6895 zSql[nSql] = ';';
6896 zSql[nSql+1] = 0;
6897 rc = sqlite3_complete(zSql);
6898 zSql[nSql] = 0;
6899 return rc;
6900}
6901
6902/*
drh4e8142c2016-11-11 14:54:22 +00006903** Run a single line of SQL
6904*/
6905static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6906 int rc;
6907 char *zErrMsg = 0;
6908
6909 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006910 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006911 BEGIN_TIMER;
6912 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6913 END_TIMER;
6914 if( rc || zErrMsg ){
6915 char zPrefix[100];
6916 if( in!=0 || !stdin_is_interactive ){
6917 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6918 "Error: near line %d:", startline);
6919 }else{
6920 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6921 }
6922 if( zErrMsg!=0 ){
6923 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6924 sqlite3_free(zErrMsg);
6925 zErrMsg = 0;
6926 }else{
6927 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6928 }
6929 return 1;
drhe6e1d122017-03-09 13:50:49 +00006930 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006931 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6932 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6933 }
6934 return 0;
6935}
6936
6937
6938/*
drh67505e72002-04-19 12:34:06 +00006939** Read input from *in and process it. If *in==0 then input
6940** is interactive - the user is typing it it. Otherwise, input
6941** is coming from a file or device. A prompt is issued and history
6942** is saved only if input is interactive. An interrupt signal will
6943** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006944**
6945** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006946*/
drhdcd87a92014-08-18 13:45:42 +00006947static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006948 char *zLine = 0; /* A single input line */
6949 char *zSql = 0; /* Accumulated SQL text */
6950 int nLine; /* Length of current line */
6951 int nSql = 0; /* Bytes of zSql[] used */
6952 int nAlloc = 0; /* Allocated zSql[] space */
6953 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006954 int rc; /* Error code */
6955 int errCnt = 0; /* Number of errors seen */
6956 int lineno = 0; /* Current line number */
6957 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006958
6959 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6960 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006961 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006962 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006963 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006964 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006965 break;
drhc49f44e2006-10-26 18:15:42 +00006966 }
drh67505e72002-04-19 12:34:06 +00006967 if( seenInterrupt ){
6968 if( in!=0 ) break;
6969 seenInterrupt = 0;
6970 }
drhc28490c2006-10-26 14:25:58 +00006971 lineno++;
drh849a9d92013-12-21 15:46:06 +00006972 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006973 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006974 continue;
6975 }
drh2af0b2d2002-02-21 02:25:02 +00006976 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006977 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006978 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006979 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006980 break;
6981 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006982 errCnt++;
6983 }
drhdaffd0e2001-04-11 14:28:42 +00006984 continue;
6985 }
drh9f099fd2013-08-06 14:01:46 +00006986 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00006987 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00006988 }
drh9f099fd2013-08-06 14:01:46 +00006989 nLine = strlen30(zLine);
6990 if( nSql+nLine+2>=nAlloc ){
6991 nAlloc = nSql+nLine+100;
6992 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00006993 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006994 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00006995 exit(1);
6996 }
drhdaffd0e2001-04-11 14:28:42 +00006997 }
drh9f099fd2013-08-06 14:01:46 +00006998 nSqlPrior = nSql;
6999 if( nSql==0 ){
7000 int i;
7001 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00007002 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00007003 memcpy(zSql, zLine+i, nLine+1-i);
7004 startline = lineno;
7005 nSql = nLine-i;
7006 }else{
7007 zSql[nSql++] = '\n';
7008 memcpy(zSql+nSql, zLine, nLine+1);
7009 nSql += nLine;
7010 }
7011 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00007012 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00007013 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007014 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00007015 if( p->outCount ){
7016 output_reset(p);
7017 p->outCount = 0;
7018 }
drh9f099fd2013-08-06 14:01:46 +00007019 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00007020 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00007021 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00007022 }
7023 }
drh4e8142c2016-11-11 14:54:22 +00007024 if( nSql && !_all_whitespace(zSql) ){
7025 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007026 }
drh1f9ca2c2015-08-25 16:57:52 +00007027 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00007028 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00007029 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00007030}
7031
drh67505e72002-04-19 12:34:06 +00007032/*
7033** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00007034** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00007035*/
drhd1459152016-09-16 19:11:03 +00007036static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00007037 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00007038 if( clearFlag ){
7039 free(home_dir);
7040 home_dir = 0;
7041 return 0;
7042 }
drh85e72432012-04-11 11:38:53 +00007043 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00007044
drh4ace5362014-11-10 14:42:28 +00007045#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7046 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00007047 {
7048 struct passwd *pwent;
7049 uid_t uid = getuid();
7050 if( (pwent=getpwuid(uid)) != NULL) {
7051 home_dir = pwent->pw_dir;
7052 }
drh67505e72002-04-19 12:34:06 +00007053 }
7054#endif
7055
chw65d3c132007-11-12 21:09:10 +00007056#if defined(_WIN32_WCE)
7057 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7058 */
drh85e72432012-04-11 11:38:53 +00007059 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00007060#else
7061
drh83905c92012-06-21 13:00:37 +00007062#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00007063 if (!home_dir) {
7064 home_dir = getenv("USERPROFILE");
7065 }
7066#endif
7067
drh67505e72002-04-19 12:34:06 +00007068 if (!home_dir) {
7069 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00007070 }
7071
drh83905c92012-06-21 13:00:37 +00007072#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00007073 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00007074 char *zDrive, *zPath;
7075 int n;
7076 zDrive = getenv("HOMEDRIVE");
7077 zPath = getenv("HOMEPATH");
7078 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00007079 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00007080 home_dir = malloc( n );
7081 if( home_dir==0 ) return 0;
7082 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7083 return home_dir;
7084 }
7085 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00007086 }
7087#endif
7088
chw65d3c132007-11-12 21:09:10 +00007089#endif /* !_WIN32_WCE */
7090
drh67505e72002-04-19 12:34:06 +00007091 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00007092 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00007093 char *z = malloc( n );
7094 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00007095 home_dir = z;
7096 }
drhe98d4fa2002-04-21 19:06:22 +00007097
drh67505e72002-04-19 12:34:06 +00007098 return home_dir;
7099}
7100
7101/*
7102** Read input from the file given by sqliterc_override. Or if that
7103** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007104**
7105** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007106*/
drh534f4df2015-02-28 14:03:35 +00007107static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007108 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007109 const char *sqliterc_override /* Name of config file. NULL to use default */
7110){
persicom7e2dfdd2002-04-18 02:46:52 +00007111 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007112 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007113 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007114 FILE *in = NULL;
7115
7116 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007117 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007118 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007119 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007120 " cannot read ~/.sqliterc\n");
7121 return;
drhe98d4fa2002-04-21 19:06:22 +00007122 }
drh2f3de322012-06-27 16:41:31 +00007123 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007124 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7125 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007126 }
drha1f9b5e2004-02-14 16:31:02 +00007127 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007128 if( in ){
drhc28490c2006-10-26 14:25:58 +00007129 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007130 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007131 }
drh534f4df2015-02-28 14:03:35 +00007132 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007133 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007134 }
drh85e72432012-04-11 11:38:53 +00007135 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007136}
7137
drh67505e72002-04-19 12:34:06 +00007138/*
drhe1e38c42003-05-04 18:30:59 +00007139** Show available command line options
7140*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007141static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007142 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007143 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007144 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007145 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007146 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007147 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007148 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007149 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007150 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007151#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7152 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7153#endif
drhcc3b4f82012-02-07 14:13:50 +00007154 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007155 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007156 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007157 " -line set output mode to 'line'\n"
7158 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007159 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007160 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007161#ifdef SQLITE_ENABLE_MULTIPLEX
7162 " -multiplex enable the multiplexor VFS\n"
7163#endif
mistachkine0d68852014-12-11 03:12:33 +00007164 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007165 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007166 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7167 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00007168 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007169 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007170 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007171 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007172#ifdef SQLITE_ENABLE_VFSTRACE
7173 " -vfstrace enable tracing of all VFS calls\n"
7174#endif
drhe1e38c42003-05-04 18:30:59 +00007175;
7176static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007177 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007178 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007179 "FILENAME is the name of an SQLite database. A new database is created\n"
7180 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007181 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007182 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007183 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007184 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007185 }
7186 exit(1);
7187}
7188
7189/*
drh67505e72002-04-19 12:34:06 +00007190** Initialize the state information in data
7191*/
drhdcd87a92014-08-18 13:45:42 +00007192static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007193 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007194 data->normalMode = data->cMode = data->mode = MODE_List;
7195 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007196 memcpy(data->colSeparator,SEP_Column, 2);
7197 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007198 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007199 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007200 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007201 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007202 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007203 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7204 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007205}
7206
drh98d312f2012-10-25 15:23:14 +00007207/*
drh5c7976f2014-02-10 19:59:27 +00007208** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007209*/
7210#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007211static void printBold(const char *zText){
7212 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7213 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7214 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7215 SetConsoleTextAttribute(out,
7216 FOREGROUND_RED|FOREGROUND_INTENSITY
7217 );
7218 printf("%s", zText);
7219 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007220}
7221#else
drh5c7976f2014-02-10 19:59:27 +00007222static void printBold(const char *zText){
7223 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007224}
7225#endif
7226
7227/*
drh98d312f2012-10-25 15:23:14 +00007228** Get the argument to an --option. Throw an error and die if no argument
7229** is available.
7230*/
7231static char *cmdline_option_value(int argc, char **argv, int i){
7232 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007233 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007234 argv[0], argv[argc-1]);
7235 exit(1);
7236 }
7237 return argv[i];
7238}
7239
mistachkin1fe36bb2016-04-04 02:16:44 +00007240#ifndef SQLITE_SHELL_IS_UTF8
7241# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7242# define SQLITE_SHELL_IS_UTF8 (0)
7243# else
7244# define SQLITE_SHELL_IS_UTF8 (1)
7245# endif
7246#endif
7247
7248#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007249int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007250#else
7251int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007252 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007253#endif
drh75897232000-05-29 14:26:00 +00007254 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007255 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007256 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007257 int i;
drhc28490c2006-10-26 14:25:58 +00007258 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007259 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007260 int readStdin = 1;
7261 int nCmd = 0;
7262 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007263
mistachkin1fe36bb2016-04-04 02:16:44 +00007264 setBinaryMode(stdin, 0);
7265 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007266 stdin_is_interactive = isatty(0);
7267 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007268
drh69b30ab2014-02-27 15:11:52 +00007269#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007270 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007271 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007272 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7273 exit(1);
7274 }
drhc7181902014-02-27 15:04:13 +00007275#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007276 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007277#if !SQLITE_SHELL_IS_UTF8
7278 sqlite3_initialize();
7279 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7280 if( argv==0 ){
7281 raw_printf(stderr, "out of memory\n");
7282 exit(1);
7283 }
7284 for(i=0; i<argc; i++){
7285 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7286 if( argv[i]==0 ){
7287 raw_printf(stderr, "out of memory\n");
7288 exit(1);
7289 }
7290 }
7291#endif
mistachkin1810f222016-04-04 02:33:34 +00007292 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007293 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007294
drh44c2eb12003-04-30 11:38:26 +00007295 /* Make sure we have a valid signal handler early, before anything
7296 ** else is done.
7297 */
drh4c504392000-10-16 22:06:40 +00007298#ifdef SIGINT
7299 signal(SIGINT, interrupt_handler);
7300#endif
drh44c2eb12003-04-30 11:38:26 +00007301
drhac5649a2014-11-28 13:35:03 +00007302#ifdef SQLITE_SHELL_DBNAME_PROC
7303 {
7304 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7305 ** of a C-function that will provide the name of the database file. Use
7306 ** this compile-time option to embed this shell program in larger
7307 ** applications. */
7308 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7309 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7310 warnInmemoryDb = 0;
7311 }
7312#endif
7313
drh22fbcb82004-02-01 01:22:50 +00007314 /* Do an initial pass through the command-line argument to locate
7315 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007316 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007317 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007318 */
drh98d312f2012-10-25 15:23:14 +00007319 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007320 char *z;
drhc28490c2006-10-26 14:25:58 +00007321 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007322 if( z[0]!='-' ){
7323 if( data.zDbFilename==0 ){
7324 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007325 }else{
7326 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7327 ** mean that nothing is read from stdin */
7328 readStdin = 0;
7329 nCmd++;
7330 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7331 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007332 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007333 exit(1);
7334 }
7335 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007336 }
drh98d312f2012-10-25 15:23:14 +00007337 }
drhcc3b4f82012-02-07 14:13:50 +00007338 if( z[1]=='-' ) z++;
7339 if( strcmp(z,"-separator")==0
7340 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007341 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007342 || strcmp(z,"-cmd")==0
7343 ){
drh98d312f2012-10-25 15:23:14 +00007344 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007345 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007346 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007347 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007348 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007349 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007350 ** we do the actual processing of arguments later in a second pass.
7351 */
shanef69573d2009-10-24 02:06:14 +00007352 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007353 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007354#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007355 const char *zSize;
7356 sqlite3_int64 szHeap;
7357
drh98d312f2012-10-25 15:23:14 +00007358 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007359 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007360 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007361 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007362#else
7363 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007364#endif
drh44dec872014-08-30 15:49:25 +00007365 }else if( strcmp(z,"-scratch")==0 ){
7366 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007367 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007368 if( sz>400000 ) sz = 400000;
7369 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007370 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007371 if( n>10 ) n = 10;
7372 if( n<1 ) n = 1;
7373 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7374 data.shellFlgs |= SHFLG_Scratch;
7375 }else if( strcmp(z,"-pagecache")==0 ){
7376 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007377 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007378 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007379 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007380 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007381 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7382 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007383 data.shellFlgs |= SHFLG_Pagecache;
7384 }else if( strcmp(z,"-lookaside")==0 ){
7385 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007386 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007387 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007388 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007389 if( n<0 ) n = 0;
7390 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7391 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007392#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007393 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007394 extern int vfstrace_register(
7395 const char *zTraceName,
7396 const char *zOldVfsName,
7397 int (*xOut)(const char*,void*),
7398 void *pOutArg,
7399 int makeDefault
7400 );
drh2b625e22011-03-16 17:05:28 +00007401 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007402#endif
drh6f25e892011-07-08 17:02:57 +00007403#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007404 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007405 extern int sqlite3_multiple_initialize(const char*,int);
7406 sqlite3_multiplex_initialize(0, 1);
7407#endif
drh7d9f3942013-04-03 01:26:54 +00007408 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007409 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7410 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007411 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007412 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007413 if( pVfs ){
7414 sqlite3_vfs_register(pVfs, 1);
7415 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007416 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007417 exit(1);
7418 }
drh44c2eb12003-04-30 11:38:26 +00007419 }
7420 }
drh98d312f2012-10-25 15:23:14 +00007421 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007422#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007423 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007424 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007425#else
mistachkinaae280e2015-12-31 19:06:24 +00007426 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007427 return 1;
drh01b41712005-08-29 23:06:23 +00007428#endif
drh98d312f2012-10-25 15:23:14 +00007429 }
7430 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007431
drh44c2eb12003-04-30 11:38:26 +00007432 /* Go ahead and open the database file if it already exists. If the
7433 ** file does not exist, delay opening it. This prevents empty database
7434 ** files from being created if a user mistypes the database name argument
7435 ** to the sqlite command-line tool.
7436 */
drhc8d74412004-08-31 23:41:26 +00007437 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007438 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007439 }
7440
drh22fbcb82004-02-01 01:22:50 +00007441 /* Process the initialization file if there is one. If no -init option
7442 ** is given on the command line, look for a file named ~/.sqliterc and
7443 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007444 */
drh534f4df2015-02-28 14:03:35 +00007445 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007446
drh22fbcb82004-02-01 01:22:50 +00007447 /* Make a second pass through the command-line argument and set
7448 ** options. This second pass is delayed until after the initialization
7449 ** file is processed so that the command-line arguments will override
7450 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007451 */
drh98d312f2012-10-25 15:23:14 +00007452 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007453 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007454 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007455 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007456 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007457 i++;
7458 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007459 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007460 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007461 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007462 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007463 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007464 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007465 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007466 }else if( strcmp(z,"-csv")==0 ){
7467 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007468 memcpy(data.colSeparator,",",2);
7469 }else if( strcmp(z,"-ascii")==0 ){
7470 data.mode = MODE_Ascii;
7471 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007472 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007473 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007474 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007475 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007476 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007477 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007478 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007479 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007480 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007481 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007482 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007483 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007484 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007485 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007486 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007487 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007488 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007489 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007490 }else if( strcmp(z,"-eqp")==0 ){
7491 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007492 }else if( strcmp(z,"-eqpfull")==0 ){
7493 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007494 }else if( strcmp(z,"-stats")==0 ){
7495 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007496 }else if( strcmp(z,"-scanstats")==0 ){
7497 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007498 }else if( strcmp(z,"-backslash")==0 ){
7499 /* Undocumented command-line option: -backslash
7500 ** Causes C-style backslash escapes to be evaluated in SQL statements
7501 ** prior to sending the SQL into SQLite. Useful for injecting
7502 ** crazy bytes in the middle of SQL statements for testing and debugging.
7503 */
drhe6e1d122017-03-09 13:50:49 +00007504 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007505 }else if( strcmp(z,"-bail")==0 ){
7506 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007507 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007508 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007509 return 0;
drhc28490c2006-10-26 14:25:58 +00007510 }else if( strcmp(z,"-interactive")==0 ){
7511 stdin_is_interactive = 1;
7512 }else if( strcmp(z,"-batch")==0 ){
7513 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007514 }else if( strcmp(z,"-heap")==0 ){
7515 i++;
drh44dec872014-08-30 15:49:25 +00007516 }else if( strcmp(z,"-scratch")==0 ){
7517 i+=2;
7518 }else if( strcmp(z,"-pagecache")==0 ){
7519 i+=2;
7520 }else if( strcmp(z,"-lookaside")==0 ){
7521 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007522 }else if( strcmp(z,"-mmap")==0 ){
7523 i++;
drha7e61d82011-03-12 17:02:57 +00007524 }else if( strcmp(z,"-vfs")==0 ){
7525 i++;
drh6f25e892011-07-08 17:02:57 +00007526#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007527 }else if( strcmp(z,"-vfstrace")==0 ){
7528 i++;
drh6f25e892011-07-08 17:02:57 +00007529#endif
7530#ifdef SQLITE_ENABLE_MULTIPLEX
7531 }else if( strcmp(z,"-multiplex")==0 ){
7532 i++;
7533#endif
drhcc3b4f82012-02-07 14:13:50 +00007534 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007535 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007536 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007537 /* Run commands that follow -cmd first and separately from commands
7538 ** that simply appear on the command-line. This seems goofy. It would
7539 ** be better if all commands ran in the order that they appear. But
7540 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007541 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007542 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007543 if( z[0]=='.' ){
7544 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007545 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007546 }else{
drh05782482013-10-24 15:20:20 +00007547 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007548 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7549 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007550 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007551 if( bail_on_error ) return rc!=0 ? rc : 1;
7552 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007553 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007554 if( bail_on_error ) return rc;
7555 }
7556 }
drh1e5d0e92000-05-31 23:33:17 +00007557 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007558 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7559 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007560 return 1;
7561 }
drh700c2522016-02-09 18:39:25 +00007562 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007563 }
drh44c2eb12003-04-30 11:38:26 +00007564
drhac5649a2014-11-28 13:35:03 +00007565 if( !readStdin ){
7566 /* Run all arguments that do not begin with '-' as if they were separate
7567 ** command-line inputs, except for the argToSkip argument which contains
7568 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007569 */
drhac5649a2014-11-28 13:35:03 +00007570 for(i=0; i<nCmd; i++){
7571 if( azCmd[i][0]=='.' ){
7572 rc = do_meta_command(azCmd[i], &data);
7573 if( rc ) return rc==2 ? 0 : rc;
7574 }else{
7575 open_db(&data, 0);
7576 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7577 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007578 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007579 return rc!=0 ? rc : 1;
7580 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007581 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007582 return rc;
7583 }
drh6ff13852001-11-25 13:18:23 +00007584 }
drh75897232000-05-29 14:26:00 +00007585 }
drhac5649a2014-11-28 13:35:03 +00007586 free(azCmd);
drh75897232000-05-29 14:26:00 +00007587 }else{
drh44c2eb12003-04-30 11:38:26 +00007588 /* Run commands received from standard input
7589 */
drhc28490c2006-10-26 14:25:58 +00007590 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007591 char *zHome;
7592 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007593 int nHistory;
drh75897232000-05-29 14:26:00 +00007594 printf(
drh743e0032011-12-12 16:51:50 +00007595 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007596 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007597 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007598 );
drhb3735912014-02-10 16:13:42 +00007599 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007600 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007601 printBold("transient in-memory database");
7602 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007603 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007604 }
drhd1459152016-09-16 19:11:03 +00007605 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007606 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007607 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007608 if( (zHistory = malloc(nHistory))!=0 ){
7609 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7610 }
drh67505e72002-04-19 12:34:06 +00007611 }
drhf5ed7ad2015-06-15 14:43:25 +00007612 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007613 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007614 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007615 shell_stifle_history(100);
7616 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007617 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007618 }
drhdaffd0e2001-04-11 14:28:42 +00007619 }else{
drhc28490c2006-10-26 14:25:58 +00007620 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007621 }
7622 }
drh33048c02001-10-01 14:29:22 +00007623 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007624 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007625 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007626 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007627 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007628 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007629 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007630#if !SQLITE_SHELL_IS_UTF8
7631 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7632 sqlite3_free(argv);
7633#endif
drhc28490c2006-10-26 14:25:58 +00007634 return rc;
drh75897232000-05-29 14:26:00 +00007635}