blob: 9ea603bab202ce67ff56cb2c9bcfdfbaa328b269 [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"
drhc31b79d2017-06-29 21:11:27 +00003330/* Because explain mode comes on automatically now, the ".explain" mode
3331** is removed from the help screen. It is still supported for legacy, however */
3332/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
drh4926fec2016-04-13 15:33:42 +00003333 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003334 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003335 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003336 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003337#ifndef SQLITE_OMIT_TEST_CONTROL
3338 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3339#endif
drh0e55db12015-02-06 14:51:13 +00003340 ".indexes ?TABLE? Show names of all indexes\n"
3341 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003342 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003343#ifdef SQLITE_ENABLE_IOTRACE
3344 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3345#endif
drh1a513372015-05-02 17:40:23 +00003346 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003347 ".lint OPTIONS Report potential schema issues. Options:\n"
3348 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003349#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003350 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003351#endif
drh127f9d72010-02-23 01:47:00 +00003352 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003353 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003354 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003355 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003356 " column Left-aligned columns. (See .width)\n"
3357 " html HTML <table> code\n"
3358 " insert SQL insert statements for TABLE\n"
3359 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003360 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003361 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003362 " tabs Tab-separated values\n"
3363 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003364 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003365 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkine16a3502017-05-29 03:48:13 +00003366 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3367 " The --new option starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003368 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003369 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003370 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003371 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003372 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003373 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003374 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003375 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003376 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3377 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00003378 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00003379 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3380 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003381#if defined(SQLITE_ENABLE_SESSION)
3382 ".session CMD ... Create or control sessions\n"
3383#endif
drh1554bc82017-03-08 16:10:34 +00003384 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003385 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003386 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003387 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003388 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003389 ".tables ?TABLE? List names of tables\n"
3390 " If TABLE specified, only list tables matching\n"
3391 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003392 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003393 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003394 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003395 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003396 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003397 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003398 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003399 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003400 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003401;
3402
drhe6229612014-08-18 15:08:26 +00003403#if defined(SQLITE_ENABLE_SESSION)
3404/*
3405** Print help information for the ".sessions" command
3406*/
3407void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003408 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003409 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3410 "If ?NAME? is omitted, the first defined session is used.\n"
3411 "Subcommands:\n"
3412 " attach TABLE Attach TABLE\n"
3413 " changeset FILE Write a changeset into FILE\n"
3414 " close Close one session\n"
3415 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003416 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003417 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3418 " isempty Query whether the session is empty\n"
3419 " list List currently open session names\n"
3420 " open DB NAME Open a new session on DB\n"
3421 " patchset FILE Write a patchset into FILE\n"
3422 );
3423}
3424#endif
3425
3426
drhdaffd0e2001-04-11 14:28:42 +00003427/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003428static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003429
drh2db82112016-09-15 21:35:24 +00003430/*
dan11da0022016-12-17 08:18:05 +00003431** Read the content of file zName into memory obtained from sqlite3_malloc64()
mistachkine16a3502017-05-29 03:48:13 +00003432** and return a pointer to the buffer. The caller is responsible for freeing
3433** the memory.
drh2db82112016-09-15 21:35:24 +00003434**
dan11da0022016-12-17 08:18:05 +00003435** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3436** read.
3437**
3438** For convenience, a nul-terminator byte is always appended to the data read
3439** from the file before the buffer is returned. This byte is not included in
3440** the final value of (*pnByte), if applicable.
3441**
3442** NULL is returned if any error is encountered. The final value of *pnByte
3443** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003444*/
dan11da0022016-12-17 08:18:05 +00003445static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003446 FILE *in = fopen(zName, "rb");
3447 long nIn;
drhd1459152016-09-16 19:11:03 +00003448 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003449 char *pBuf;
3450 if( in==0 ) return 0;
3451 fseek(in, 0, SEEK_END);
3452 nIn = ftell(in);
3453 rewind(in);
drhd1459152016-09-16 19:11:03 +00003454 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003455 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003456 nRead = fread(pBuf, nIn, 1, in);
3457 fclose(in);
3458 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003459 sqlite3_free(pBuf);
3460 return 0;
3461 }
drhd1459152016-09-16 19:11:03 +00003462 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003463 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003464 return pBuf;
3465}
3466
drhba5b0932014-07-24 12:39:59 +00003467/*
3468** Implementation of the "readfile(X)" SQL function. The entire content
3469** of the file named X is read and returned as a BLOB. NULL is returned
3470** if the file does not exist or is unreadable.
3471*/
3472static void readfileFunc(
3473 sqlite3_context *context,
3474 int argc,
3475 sqlite3_value **argv
3476){
3477 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003478 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003479 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003480
drhf5ed7ad2015-06-15 14:43:25 +00003481 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003482 zName = (const char*)sqlite3_value_text(argv[0]);
3483 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003484 pBuf = readFile(zName, &nBuf);
3485 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003486}
3487
3488/*
3489** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3490** is written into file X. The number of bytes written is returned. Or
3491** NULL is returned if something goes wrong, such as being unable to open
3492** file X for writing.
3493*/
3494static void writefileFunc(
3495 sqlite3_context *context,
3496 int argc,
3497 sqlite3_value **argv
3498){
3499 FILE *out;
3500 const char *z;
drhba5b0932014-07-24 12:39:59 +00003501 sqlite3_int64 rc;
3502 const char *zFile;
3503
drhf5ed7ad2015-06-15 14:43:25 +00003504 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003505 zFile = (const char*)sqlite3_value_text(argv[0]);
3506 if( zFile==0 ) return;
3507 out = fopen(zFile, "wb");
3508 if( out==0 ) return;
3509 z = (const char*)sqlite3_value_blob(argv[1]);
3510 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003511 rc = 0;
3512 }else{
drh490fe862014-08-11 14:21:32 +00003513 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003514 }
3515 fclose(out);
3516 sqlite3_result_int64(context, rc);
3517}
drhdaffd0e2001-04-11 14:28:42 +00003518
drhe6229612014-08-18 15:08:26 +00003519#if defined(SQLITE_ENABLE_SESSION)
3520/*
3521** Close a single OpenSession object and release all of its associated
3522** resources.
3523*/
3524static void session_close(OpenSession *pSession){
3525 int i;
3526 sqlite3session_delete(pSession->p);
3527 sqlite3_free(pSession->zName);
3528 for(i=0; i<pSession->nFilter; i++){
3529 sqlite3_free(pSession->azFilter[i]);
3530 }
3531 sqlite3_free(pSession->azFilter);
3532 memset(pSession, 0, sizeof(OpenSession));
3533}
3534#endif
3535
3536/*
drh51b55a32016-04-04 12:38:05 +00003537** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003538*/
drhe6229612014-08-18 15:08:26 +00003539#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003540static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003541 int i;
3542 for(i=0; i<p->nSession; i++){
3543 session_close(&p->aSession[i]);
3544 }
3545 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003546}
drh51b55a32016-04-04 12:38:05 +00003547#else
3548# define session_close_all(X)
3549#endif
drhe6229612014-08-18 15:08:26 +00003550
drh75897232000-05-29 14:26:00 +00003551/*
drh03168ca2014-08-18 20:01:31 +00003552** Implementation of the xFilter function for an open session. Omit
3553** any tables named by ".session filter" but let all other table through.
3554*/
3555#if defined(SQLITE_ENABLE_SESSION)
3556static int session_filter(void *pCtx, const char *zTab){
3557 OpenSession *pSession = (OpenSession*)pCtx;
3558 int i;
3559 for(i=0; i<pSession->nFilter; i++){
3560 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3561 }
3562 return 1;
3563}
3564#endif
3565
3566/*
drh44c2eb12003-04-30 11:38:26 +00003567** Make sure the database is open. If it is not, then open it. If
3568** the database fails to open, print an error message and exit.
3569*/
drhdcd87a92014-08-18 13:45:42 +00003570static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003571 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003572 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003573 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003574 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003575 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003576 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003577 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003578 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003579 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003580 }
drhc2e87a32006-06-27 15:16:14 +00003581#ifndef SQLITE_OMIT_LOAD_EXTENSION
3582 sqlite3_enable_load_extension(p->db, 1);
3583#endif
mistachkin8e189222015-04-19 21:43:16 +00003584 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003585 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003586 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003587 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003588 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3589 sha3Func, 0, 0);
3590 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3591 sha3Func, 0, 0);
3592 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3593 sha3QueryFunc, 0, 0);
3594 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3595 sha3QueryFunc, 0, 0);
drh20c9c3f2017-06-15 12:21:09 +00003596 sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
3597 shellAddSchemaName, 0, 0);
3598
drh44c2eb12003-04-30 11:38:26 +00003599 }
3600}
3601
3602/*
drhfeac5f82004-08-01 00:10:45 +00003603** Do C-language style dequoting.
3604**
mistachkinf21979d2015-01-18 05:35:01 +00003605** \a -> alarm
3606** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003607** \t -> tab
3608** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003609** \v -> vertical tab
3610** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003611** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003612** \s -> space
drh4c56b992013-06-27 13:26:55 +00003613** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003614** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003615** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003616** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003617*/
3618static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003619 int i, j;
3620 char c;
drhc2ce0be2014-05-29 12:36:14 +00003621 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003622 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003623 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003624 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003625 if( c=='a' ){
3626 c = '\a';
3627 }else if( c=='b' ){
3628 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003629 }else if( c=='t' ){
3630 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003631 }else if( c=='n' ){
3632 c = '\n';
3633 }else if( c=='v' ){
3634 c = '\v';
3635 }else if( c=='f' ){
3636 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003637 }else if( c=='r' ){
3638 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003639 }else if( c=='"' ){
3640 c = '"';
3641 }else if( c=='\'' ){
3642 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003643 }else if( c=='\\' ){
3644 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003645 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003646 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003647 if( z[i+1]>='0' && z[i+1]<='7' ){
3648 i++;
3649 c = (c<<3) + z[i] - '0';
3650 if( z[i+1]>='0' && z[i+1]<='7' ){
3651 i++;
3652 c = (c<<3) + z[i] - '0';
3653 }
3654 }
3655 }
3656 }
3657 z[j] = c;
3658 }
drhc2ce0be2014-05-29 12:36:14 +00003659 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003660}
3661
3662/*
drh348d19c2013-06-03 12:47:43 +00003663** Return the value of a hexadecimal digit. Return -1 if the input
3664** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003665*/
drh348d19c2013-06-03 12:47:43 +00003666static int hexDigitValue(char c){
3667 if( c>='0' && c<='9' ) return c - '0';
3668 if( c>='a' && c<='f' ) return c - 'a' + 10;
3669 if( c>='A' && c<='F' ) return c - 'A' + 10;
3670 return -1;
drhc28490c2006-10-26 14:25:58 +00003671}
3672
3673/*
drh7d9f3942013-04-03 01:26:54 +00003674** Interpret zArg as an integer value, possibly with suffixes.
3675*/
3676static sqlite3_int64 integerValue(const char *zArg){
3677 sqlite3_int64 v = 0;
3678 static const struct { char *zSuffix; int iMult; } aMult[] = {
3679 { "KiB", 1024 },
3680 { "MiB", 1024*1024 },
3681 { "GiB", 1024*1024*1024 },
3682 { "KB", 1000 },
3683 { "MB", 1000000 },
3684 { "GB", 1000000000 },
3685 { "K", 1000 },
3686 { "M", 1000000 },
3687 { "G", 1000000000 },
3688 };
3689 int i;
3690 int isNeg = 0;
3691 if( zArg[0]=='-' ){
3692 isNeg = 1;
3693 zArg++;
3694 }else if( zArg[0]=='+' ){
3695 zArg++;
3696 }
drh348d19c2013-06-03 12:47:43 +00003697 if( zArg[0]=='0' && zArg[1]=='x' ){
3698 int x;
3699 zArg += 2;
3700 while( (x = hexDigitValue(zArg[0]))>=0 ){
3701 v = (v<<4) + x;
3702 zArg++;
3703 }
3704 }else{
3705 while( IsDigit(zArg[0]) ){
3706 v = v*10 + zArg[0] - '0';
3707 zArg++;
3708 }
drh7d9f3942013-04-03 01:26:54 +00003709 }
drhc2bed0a2013-05-24 11:57:50 +00003710 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003711 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3712 v *= aMult[i].iMult;
3713 break;
3714 }
3715 }
3716 return isNeg? -v : v;
3717}
3718
3719/*
drh348d19c2013-06-03 12:47:43 +00003720** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3721** for TRUE and FALSE. Return the integer value if appropriate.
3722*/
drhe6e1d122017-03-09 13:50:49 +00003723static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003724 int i;
3725 if( zArg[0]=='0' && zArg[1]=='x' ){
3726 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3727 }else{
3728 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3729 }
3730 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3731 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3732 return 1;
3733 }
3734 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3735 return 0;
3736 }
mistachkinaae280e2015-12-31 19:06:24 +00003737 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003738 zArg);
3739 return 0;
3740}
3741
3742/*
drhe6e1d122017-03-09 13:50:49 +00003743** Set or clear a shell flag according to a boolean value.
3744*/
3745static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3746 if( booleanValue(zArg) ){
3747 ShellSetFlag(p, mFlag);
3748 }else{
3749 ShellClearFlag(p, mFlag);
3750 }
3751}
3752
3753/*
drh42f64e52012-04-04 16:56:23 +00003754** Close an output file, assuming it is not stderr or stdout
3755*/
3756static void output_file_close(FILE *f){
3757 if( f && f!=stdout && f!=stderr ) fclose(f);
3758}
3759
3760/*
3761** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003762** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003763** filename is "off".
3764*/
3765static FILE *output_file_open(const char *zFile){
3766 FILE *f;
3767 if( strcmp(zFile,"stdout")==0 ){
3768 f = stdout;
3769 }else if( strcmp(zFile, "stderr")==0 ){
3770 f = stderr;
3771 }else if( strcmp(zFile, "off")==0 ){
3772 f = 0;
3773 }else{
3774 f = fopen(zFile, "wb");
3775 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003776 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003777 }
3778 }
3779 return f;
3780}
3781
drhd12602a2016-12-07 15:49:02 +00003782#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003783#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003784/*
3785** A routine for handling output from sqlite3_trace().
3786*/
drh4b363a52016-07-23 20:27:41 +00003787static int sql_trace_callback(
3788 unsigned mType,
3789 void *pArg,
3790 void *pP,
3791 void *pX
3792){
drh42f64e52012-04-04 16:56:23 +00003793 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003794 UNUSED_PARAMETER(mType);
3795 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003796 if( f ){
drh4b363a52016-07-23 20:27:41 +00003797 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003798 int i = (int)strlen(z);
3799 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003800 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003801 }
drh4b363a52016-07-23 20:27:41 +00003802 return 0;
drh42f64e52012-04-04 16:56:23 +00003803}
drhc10b9da2016-11-20 17:59:59 +00003804#endif
3805#endif
drh42f64e52012-04-04 16:56:23 +00003806
3807/*
drhd8621b92012-04-17 09:09:33 +00003808** A no-op routine that runs with the ".breakpoint" doc-command. This is
3809** a useful spot to set a debugger breakpoint.
3810*/
3811static void test_breakpoint(void){
3812 static int nCall = 0;
3813 nCall++;
3814}
3815
3816/*
mistachkin636bf9f2014-07-19 20:15:16 +00003817** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003818*/
mistachkin636bf9f2014-07-19 20:15:16 +00003819typedef struct ImportCtx ImportCtx;
3820struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003821 const char *zFile; /* Name of the input file */
3822 FILE *in; /* Read the CSV text from this input stream */
3823 char *z; /* Accumulated text for a field */
3824 int n; /* Number of bytes in z */
3825 int nAlloc; /* Space allocated for z[] */
3826 int nLine; /* Current line number */
drhd5fbde82017-06-26 18:42:23 +00003827 int bNotFirst; /* True if one or more bytes already read */
drhdb95f682013-06-26 22:46:00 +00003828 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003829 int cColSep; /* The column separator character. (Usually ",") */
3830 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003831};
3832
3833/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003834static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003835 if( p->n+1>=p->nAlloc ){
3836 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003837 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003838 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003839 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003840 exit(1);
3841 }
3842 }
3843 p->z[p->n++] = (char)c;
3844}
3845
3846/* Read a single field of CSV text. Compatible with rfc4180 and extended
3847** with the option of having a separator other than ",".
3848**
3849** + Input comes from p->in.
3850** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003851** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003852** + Use p->cSep as the column separator. The default is ",".
3853** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003854** + Keep track of the line number in p->nLine.
3855** + Store the character that terminates the field in p->cTerm. Store
3856** EOF on end-of-file.
3857** + Report syntax errors on stderr
3858*/
mistachkin44723ce2015-03-21 02:22:37 +00003859static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003860 int c;
3861 int cSep = p->cColSep;
3862 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003863 p->n = 0;
3864 c = fgetc(p->in);
3865 if( c==EOF || seenInterrupt ){
3866 p->cTerm = EOF;
3867 return 0;
3868 }
3869 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003870 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003871 int startLine = p->nLine;
3872 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003873 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003874 while( 1 ){
3875 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003876 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003877 if( c==cQuote ){
3878 if( pc==cQuote ){
3879 pc = 0;
3880 continue;
3881 }
3882 }
3883 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003884 || (c==rSep && pc==cQuote)
3885 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003886 || (c==EOF && pc==cQuote)
3887 ){
3888 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003889 p->cTerm = c;
3890 break;
3891 }
3892 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003893 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003894 p->zFile, p->nLine, cQuote);
3895 }
3896 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003897 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003898 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003899 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003900 break;
3901 }
mistachkin636bf9f2014-07-19 20:15:16 +00003902 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003903 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003904 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003905 }
drhdb95f682013-06-26 22:46:00 +00003906 }else{
drhd5fbde82017-06-26 18:42:23 +00003907 /* If this is the first field being parsed and it begins with the
3908 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3909 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3910 import_append_char(p, c);
3911 c = fgetc(p->in);
3912 if( (c&0xff)==0xbb ){
3913 import_append_char(p, c);
3914 c = fgetc(p->in);
3915 if( (c&0xff)==0xbf ){
3916 p->bNotFirst = 1;
3917 p->n = 0;
3918 return csv_read_one_field(p);
3919 }
3920 }
3921 }
mistachkin636bf9f2014-07-19 20:15:16 +00003922 while( c!=EOF && c!=cSep && c!=rSep ){
3923 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003924 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003925 }
mistachkin636bf9f2014-07-19 20:15:16 +00003926 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003927 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003928 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003929 }
drhdb95f682013-06-26 22:46:00 +00003930 p->cTerm = c;
3931 }
drh8dd675e2013-07-12 21:09:24 +00003932 if( p->z ) p->z[p->n] = 0;
drhd5fbde82017-06-26 18:42:23 +00003933 p->bNotFirst = 1;
drhdb95f682013-06-26 22:46:00 +00003934 return p->z;
3935}
3936
mistachkin636bf9f2014-07-19 20:15:16 +00003937/* Read a single field of ASCII delimited text.
3938**
3939** + Input comes from p->in.
3940** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003941** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003942** + Use p->cSep as the column separator. The default is "\x1F".
3943** + Use p->rSep as the row separator. The default is "\x1E".
3944** + Keep track of the row number in p->nLine.
3945** + Store the character that terminates the field in p->cTerm. Store
3946** EOF on end-of-file.
3947** + Report syntax errors on stderr
3948*/
mistachkin44723ce2015-03-21 02:22:37 +00003949static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003950 int c;
3951 int cSep = p->cColSep;
3952 int rSep = p->cRowSep;
3953 p->n = 0;
3954 c = fgetc(p->in);
3955 if( c==EOF || seenInterrupt ){
3956 p->cTerm = EOF;
3957 return 0;
3958 }
3959 while( c!=EOF && c!=cSep && c!=rSep ){
3960 import_append_char(p, c);
3961 c = fgetc(p->in);
3962 }
3963 if( c==rSep ){
3964 p->nLine++;
3965 }
3966 p->cTerm = c;
3967 if( p->z ) p->z[p->n] = 0;
3968 return p->z;
3969}
3970
drhdb95f682013-06-26 22:46:00 +00003971/*
drh4bbcf102014-02-06 02:46:08 +00003972** Try to transfer data for table zTable. If an error is seen while
3973** moving forward, try to go backwards. The backwards movement won't
3974** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003975*/
mistachkine31ae902014-02-06 01:15:29 +00003976static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003977 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003978 sqlite3 *newDb,
3979 const char *zTable
3980){
mistachkin1fe36bb2016-04-04 02:16:44 +00003981 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003982 sqlite3_stmt *pInsert = 0;
3983 char *zQuery = 0;
3984 char *zInsert = 0;
3985 int rc;
3986 int i, j, n;
3987 int nTable = (int)strlen(zTable);
3988 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003989 int cnt = 0;
3990 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003991
3992 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3993 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3994 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003995 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003996 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3997 zQuery);
3998 goto end_data_xfer;
3999 }
4000 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00004001 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00004002 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004003 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00004004 goto end_data_xfer;
4005 }
4006 sqlite3_snprintf(200+nTable,zInsert,
4007 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4008 i = (int)strlen(zInsert);
4009 for(j=1; j<n; j++){
4010 memcpy(zInsert+i, ",?", 2);
4011 i += 2;
4012 }
4013 memcpy(zInsert+i, ");", 3);
4014 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4015 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004016 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004017 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4018 zQuery);
4019 goto end_data_xfer;
4020 }
4021 for(k=0; k<2; k++){
4022 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4023 for(i=0; i<n; i++){
4024 switch( sqlite3_column_type(pQuery, i) ){
4025 case SQLITE_NULL: {
4026 sqlite3_bind_null(pInsert, i+1);
4027 break;
4028 }
4029 case SQLITE_INTEGER: {
4030 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4031 break;
4032 }
4033 case SQLITE_FLOAT: {
4034 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4035 break;
4036 }
4037 case SQLITE_TEXT: {
4038 sqlite3_bind_text(pInsert, i+1,
4039 (const char*)sqlite3_column_text(pQuery,i),
4040 -1, SQLITE_STATIC);
4041 break;
4042 }
4043 case SQLITE_BLOB: {
4044 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4045 sqlite3_column_bytes(pQuery,i),
4046 SQLITE_STATIC);
4047 break;
4048 }
4049 }
4050 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00004051 rc = sqlite3_step(pInsert);
4052 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00004053 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00004054 sqlite3_errmsg(newDb));
4055 }
drh3350ce92014-02-06 00:49:12 +00004056 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00004057 cnt++;
4058 if( (cnt%spinRate)==0 ){
4059 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4060 fflush(stdout);
4061 }
drh3350ce92014-02-06 00:49:12 +00004062 } /* End while */
4063 if( rc==SQLITE_DONE ) break;
4064 sqlite3_finalize(pQuery);
4065 sqlite3_free(zQuery);
4066 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4067 zTable);
4068 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4069 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004070 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00004071 break;
drh3350ce92014-02-06 00:49:12 +00004072 }
4073 } /* End for(k=0...) */
4074
4075end_data_xfer:
4076 sqlite3_finalize(pQuery);
4077 sqlite3_finalize(pInsert);
4078 sqlite3_free(zQuery);
4079 sqlite3_free(zInsert);
4080}
4081
4082
4083/*
4084** Try to transfer all rows of the schema that match zWhere. For
4085** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00004086** If an error is encountered while moving forward through the
4087** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00004088*/
mistachkine31ae902014-02-06 01:15:29 +00004089static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00004090 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00004091 sqlite3 *newDb,
4092 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00004093 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00004094){
4095 sqlite3_stmt *pQuery = 0;
4096 char *zQuery = 0;
4097 int rc;
4098 const unsigned char *zName;
4099 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00004100 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00004101
4102 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4103 " WHERE %s", zWhere);
4104 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4105 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004106 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004107 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4108 zQuery);
4109 goto end_schema_xfer;
4110 }
4111 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4112 zName = sqlite3_column_text(pQuery, 0);
4113 zSql = sqlite3_column_text(pQuery, 1);
4114 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004115 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4116 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004117 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004118 sqlite3_free(zErrMsg);
4119 zErrMsg = 0;
4120 }
drh3350ce92014-02-06 00:49:12 +00004121 if( xForEach ){
4122 xForEach(p, newDb, (const char*)zName);
4123 }
4124 printf("done\n");
4125 }
4126 if( rc!=SQLITE_DONE ){
4127 sqlite3_finalize(pQuery);
4128 sqlite3_free(zQuery);
4129 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4130 " WHERE %s ORDER BY rowid DESC", zWhere);
4131 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4132 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004133 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004134 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4135 zQuery);
4136 goto end_schema_xfer;
4137 }
4138 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4139 zName = sqlite3_column_text(pQuery, 0);
4140 zSql = sqlite3_column_text(pQuery, 1);
4141 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004142 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4143 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004144 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004145 sqlite3_free(zErrMsg);
4146 zErrMsg = 0;
4147 }
drh3350ce92014-02-06 00:49:12 +00004148 if( xForEach ){
4149 xForEach(p, newDb, (const char*)zName);
4150 }
4151 printf("done\n");
4152 }
4153 }
4154end_schema_xfer:
4155 sqlite3_finalize(pQuery);
4156 sqlite3_free(zQuery);
4157}
4158
4159/*
4160** Open a new database file named "zNewDb". Try to recover as much information
4161** as possible out of the main database (which might be corrupt) and write it
4162** into zNewDb.
4163*/
drhdcd87a92014-08-18 13:45:42 +00004164static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00004165 int rc;
4166 sqlite3 *newDb = 0;
4167 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004168 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00004169 return;
4170 }
4171 rc = sqlite3_open(zNewDb, &newDb);
4172 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004173 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00004174 sqlite3_errmsg(newDb));
4175 }else{
drh54d0d2d2014-04-03 00:32:13 +00004176 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004177 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00004178 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4179 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00004180 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00004181 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004182 }
4183 sqlite3_close(newDb);
4184}
4185
4186/*
drhc2ce0be2014-05-29 12:36:14 +00004187** Change the output file back to stdout
4188*/
drhdcd87a92014-08-18 13:45:42 +00004189static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00004190 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004191#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00004192 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004193#endif
drhc2ce0be2014-05-29 12:36:14 +00004194 }else{
4195 output_file_close(p->out);
4196 }
4197 p->outfile[0] = 0;
4198 p->out = stdout;
4199}
4200
4201/*
drhf7502f02015-02-06 14:19:44 +00004202** Run an SQL command and return the single integer result.
4203*/
4204static int db_int(ShellState *p, const char *zSql){
4205 sqlite3_stmt *pStmt;
4206 int res = 0;
4207 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4208 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4209 res = sqlite3_column_int(pStmt,0);
4210 }
4211 sqlite3_finalize(pStmt);
4212 return res;
4213}
4214
4215/*
4216** Convert a 2-byte or 4-byte big-endian integer into a native integer
4217*/
drha0620ac2016-07-13 13:05:13 +00004218static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004219 return (a[0]<<8) + a[1];
4220}
drha0620ac2016-07-13 13:05:13 +00004221static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004222 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4223}
4224
4225/*
4226** Implementation of the ".info" command.
4227**
4228** Return 1 on error, 2 to exit, and 0 otherwise.
4229*/
drh0e55db12015-02-06 14:51:13 +00004230static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004231 static const struct { const char *zName; int ofst; } aField[] = {
4232 { "file change counter:", 24 },
4233 { "database page count:", 28 },
4234 { "freelist page count:", 36 },
4235 { "schema cookie:", 40 },
4236 { "schema format:", 44 },
4237 { "default cache size:", 48 },
4238 { "autovacuum top root:", 52 },
4239 { "incremental vacuum:", 64 },
4240 { "text encoding:", 56 },
4241 { "user version:", 60 },
4242 { "application id:", 68 },
4243 { "software version:", 96 },
4244 };
drh0e55db12015-02-06 14:51:13 +00004245 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4246 { "number of tables:",
4247 "SELECT count(*) FROM %s WHERE type='table'" },
4248 { "number of indexes:",
4249 "SELECT count(*) FROM %s WHERE type='index'" },
4250 { "number of triggers:",
4251 "SELECT count(*) FROM %s WHERE type='trigger'" },
4252 { "number of views:",
4253 "SELECT count(*) FROM %s WHERE type='view'" },
4254 { "schema size:",
4255 "SELECT total(length(sql)) FROM %s" },
4256 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004257 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004258 int i;
4259 char *zSchemaTab;
4260 char *zDb = nArg>=2 ? azArg[1] : "main";
4261 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004262 open_db(p, 0);
4263 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004264 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004265 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4266 return 1;
4267 }
4268 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4269 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004270 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004271 return 1;
4272 }
4273 i = get2byteInt(aHdr+16);
4274 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004275 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4276 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4277 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4278 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004279 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004280 int ofst = aField[i].ofst;
4281 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004282 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004283 switch( ofst ){
4284 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004285 if( val==1 ) raw_printf(p->out, " (utf8)");
4286 if( val==2 ) raw_printf(p->out, " (utf16le)");
4287 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004288 }
4289 }
mistachkinaae280e2015-12-31 19:06:24 +00004290 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004291 }
drh0e55db12015-02-06 14:51:13 +00004292 if( zDb==0 ){
4293 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4294 }else if( strcmp(zDb,"temp")==0 ){
4295 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4296 }else{
4297 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4298 }
drhf5ed7ad2015-06-15 14:43:25 +00004299 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004300 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4301 int val = db_int(p, zSql);
4302 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004303 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004304 }
4305 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004306 return 0;
4307}
4308
dand95bb392015-09-30 11:19:05 +00004309/*
4310** Print the current sqlite3_errmsg() value to stderr and return 1.
4311*/
4312static int shellDatabaseError(sqlite3 *db){
4313 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004314 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004315 return 1;
4316}
4317
4318/*
4319** Print an out-of-memory message to stderr and return 1.
4320*/
4321static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004322 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004323 return 1;
4324}
drhf7502f02015-02-06 14:19:44 +00004325
drh2db82112016-09-15 21:35:24 +00004326/*
4327** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4328** if they match and FALSE (0) if they do not match.
4329**
4330** Globbing rules:
4331**
4332** '*' Matches any sequence of zero or more characters.
4333**
4334** '?' Matches exactly one character.
4335**
4336** [...] Matches one character from the enclosed list of
4337** characters.
4338**
4339** [^...] Matches one character not in the enclosed list.
4340**
4341** '#' Matches any sequence of one or more digits with an
4342** optional + or - sign in front
4343**
4344** ' ' Any span of whitespace matches any other span of
4345** whitespace.
4346**
4347** Extra whitespace at the end of z[] is ignored.
4348*/
4349static int testcase_glob(const char *zGlob, const char *z){
4350 int c, c2;
4351 int invert;
4352 int seen;
4353
4354 while( (c = (*(zGlob++)))!=0 ){
4355 if( IsSpace(c) ){
4356 if( !IsSpace(*z) ) return 0;
4357 while( IsSpace(*zGlob) ) zGlob++;
4358 while( IsSpace(*z) ) z++;
4359 }else if( c=='*' ){
4360 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4361 if( c=='?' && (*(z++))==0 ) return 0;
4362 }
4363 if( c==0 ){
4364 return 1;
4365 }else if( c=='[' ){
4366 while( *z && testcase_glob(zGlob-1,z)==0 ){
4367 z++;
4368 }
4369 return (*z)!=0;
4370 }
4371 while( (c2 = (*(z++)))!=0 ){
4372 while( c2!=c ){
4373 c2 = *(z++);
4374 if( c2==0 ) return 0;
4375 }
4376 if( testcase_glob(zGlob,z) ) return 1;
4377 }
4378 return 0;
4379 }else if( c=='?' ){
4380 if( (*(z++))==0 ) return 0;
4381 }else if( c=='[' ){
4382 int prior_c = 0;
4383 seen = 0;
4384 invert = 0;
4385 c = *(z++);
4386 if( c==0 ) return 0;
4387 c2 = *(zGlob++);
4388 if( c2=='^' ){
4389 invert = 1;
4390 c2 = *(zGlob++);
4391 }
4392 if( c2==']' ){
4393 if( c==']' ) seen = 1;
4394 c2 = *(zGlob++);
4395 }
4396 while( c2 && c2!=']' ){
4397 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4398 c2 = *(zGlob++);
4399 if( c>=prior_c && c<=c2 ) seen = 1;
4400 prior_c = 0;
4401 }else{
4402 if( c==c2 ){
4403 seen = 1;
4404 }
4405 prior_c = c2;
4406 }
4407 c2 = *(zGlob++);
4408 }
4409 if( c2==0 || (seen ^ invert)==0 ) return 0;
4410 }else if( c=='#' ){
4411 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4412 if( !IsDigit(z[0]) ) return 0;
4413 z++;
4414 while( IsDigit(z[0]) ){ z++; }
4415 }else{
4416 if( c!=(*(z++)) ) return 0;
4417 }
4418 }
4419 while( IsSpace(*z) ){ z++; }
4420 return *z==0;
4421}
drh2db82112016-09-15 21:35:24 +00004422
4423
drhf7502f02015-02-06 14:19:44 +00004424/*
drh4926fec2016-04-13 15:33:42 +00004425** Compare the string as a command-line option with either one or two
4426** initial "-" characters.
4427*/
4428static int optionMatch(const char *zStr, const char *zOpt){
4429 if( zStr[0]!='-' ) return 0;
4430 zStr++;
4431 if( zStr[0]=='-' ) zStr++;
4432 return strcmp(zStr, zOpt)==0;
4433}
4434
4435/*
drhcd0509e2016-09-16 00:26:08 +00004436** Delete a file.
4437*/
4438int shellDeleteFile(const char *zFilename){
4439 int rc;
4440#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004441 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004442 rc = _wunlink(z);
4443 sqlite3_free(z);
4444#else
4445 rc = unlink(zFilename);
4446#endif
4447 return rc;
4448}
4449
dan35ac58e2016-12-14 19:28:27 +00004450
dan35ac58e2016-12-14 19:28:27 +00004451/*
dandd9e0be2016-12-16 16:44:27 +00004452** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004453** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004454** called with four arguments - the parent table name, the parent column name,
4455** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004456**
4457** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4458**
4459** If either of the named tables or columns do not exist, this function
mistachkine16a3502017-05-29 03:48:13 +00004460** returns an empty string. An empty string is also returned if both tables
dan35ac58e2016-12-14 19:28:27 +00004461** and columns exist but have the same default collation sequence. Or,
4462** if both exist but the default collation sequences are different, this
4463** function returns the string " COLLATE <parent-collation>", where
4464** <parent-collation> is the default collation sequence of the parent column.
4465*/
4466static void shellFkeyCollateClause(
mistachkine16a3502017-05-29 03:48:13 +00004467 sqlite3_context *pCtx,
4468 int nVal,
dan35ac58e2016-12-14 19:28:27 +00004469 sqlite3_value **apVal
4470){
4471 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4472 const char *zParent;
4473 const char *zParentCol;
4474 const char *zParentSeq;
4475 const char *zChild;
4476 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004477 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004478 int rc;
mistachkine16a3502017-05-29 03:48:13 +00004479
dan35ac58e2016-12-14 19:28:27 +00004480 assert( nVal==4 );
4481 zParent = (const char*)sqlite3_value_text(apVal[0]);
4482 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4483 zChild = (const char*)sqlite3_value_text(apVal[2]);
4484 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4485
4486 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4487 rc = sqlite3_table_column_metadata(
4488 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4489 );
4490 if( rc==SQLITE_OK ){
4491 rc = sqlite3_table_column_metadata(
4492 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4493 );
4494 }
4495
4496 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4497 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4498 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4499 sqlite3_free(z);
4500 }
4501}
4502
4503
4504/*
dan3c7ebeb2016-12-16 17:28:56 +00004505** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004506*/
dan3c7ebeb2016-12-16 17:28:56 +00004507static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004508 ShellState *pState, /* Current shell tool state */
4509 char **azArg, /* Array of arguments passed to dot command */
4510 int nArg /* Number of entries in azArg[] */
4511){
dandd9e0be2016-12-16 16:44:27 +00004512 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4513 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004514 int bVerbose = 0; /* If -verbose is present */
4515 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004516 int i; /* To iterate through azArg[] */
4517 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4518 int rc; /* Return code */
4519 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004520
dandd9e0be2016-12-16 16:44:27 +00004521 /*
4522 ** This SELECT statement returns one row for each foreign key constraint
4523 ** in the schema of the main database. The column values are:
4524 **
4525 ** 0. The text of an SQL statement similar to:
4526 **
4527 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4528 **
4529 ** This is the same SELECT that the foreign keys implementation needs
4530 ** to run internally on child tables. If there is an index that can
4531 ** be used to optimize this query, then it can also be used by the FK
4532 ** implementation to optimize DELETE or UPDATE statements on the parent
4533 ** table.
4534 **
4535 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4536 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4537 ** contains an index that can be used to optimize the query.
4538 **
4539 ** 2. Human readable text that describes the child table and columns. e.g.
4540 **
4541 ** "child_table(child_key1, child_key2)"
4542 **
4543 ** 3. Human readable text that describes the parent table and columns. e.g.
4544 **
4545 ** "parent_table(parent_key1, parent_key2)"
4546 **
4547 ** 4. A full CREATE INDEX statement for an index that could be used to
4548 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4549 **
4550 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4551 **
4552 ** 5. The name of the parent table.
4553 **
4554 ** These six values are used by the C logic below to generate the report.
4555 */
dan35ac58e2016-12-14 19:28:27 +00004556 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004557 "SELECT "
4558 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4559 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00004560 " || fkey_collate_clause("
4561 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004562 ", "
dandd9e0be2016-12-16 16:44:27 +00004563 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004564 " || group_concat('*=?', ' AND ') || ')'"
4565 ", "
dandd9e0be2016-12-16 16:44:27 +00004566 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004567 ", "
dan50da9382017-04-06 12:06:56 +00004568 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00004569 ", "
dandd9e0be2016-12-16 16:44:27 +00004570 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4571 " || ' ON ' || quote(s.name) || '('"
4572 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00004573 " fkey_collate_clause("
4574 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004575 " || ');'"
danf9647b62016-12-15 06:01:40 +00004576 ", "
dandd9e0be2016-12-16 16:44:27 +00004577 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00004578 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00004579 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00004580 "GROUP BY s.name, f.id "
4581 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004582 ;
dan54e2efc2017-04-06 14:56:26 +00004583 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00004584
dan3c7ebeb2016-12-16 17:28:56 +00004585 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004586 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004587 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4588 bVerbose = 1;
4589 }
4590 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4591 bGroupByParent = 1;
4592 zIndent = " ";
4593 }
4594 else{
dan3c7ebeb2016-12-16 17:28:56 +00004595 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4596 azArg[0], azArg[1]
4597 );
danf9647b62016-12-15 06:01:40 +00004598 return SQLITE_ERROR;
4599 }
dan35ac58e2016-12-14 19:28:27 +00004600 }
mistachkine16a3502017-05-29 03:48:13 +00004601
dan35ac58e2016-12-14 19:28:27 +00004602 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004603 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4604 0, shellFkeyCollateClause, 0, 0
4605 );
dan35ac58e2016-12-14 19:28:27 +00004606
4607
4608 if( rc==SQLITE_OK ){
4609 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4610 }
danf9647b62016-12-15 06:01:40 +00004611 if( rc==SQLITE_OK ){
4612 sqlite3_bind_int(pSql, 1, bGroupByParent);
4613 }
dan35ac58e2016-12-14 19:28:27 +00004614
4615 if( rc==SQLITE_OK ){
4616 int rc2;
danf9647b62016-12-15 06:01:40 +00004617 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004618 while( SQLITE_ROW==sqlite3_step(pSql) ){
4619 int res = -1;
4620 sqlite3_stmt *pExplain = 0;
4621 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4622 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4623 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4624 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4625 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004626 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004627
4628 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4629 if( rc!=SQLITE_OK ) break;
4630 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4631 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00004632 res = (
4633 0==sqlite3_strglob(zGlob, zPlan)
4634 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4635 );
dan35ac58e2016-12-14 19:28:27 +00004636 }
4637 rc = sqlite3_finalize(pExplain);
4638 if( rc!=SQLITE_OK ) break;
4639
4640 if( res<0 ){
4641 raw_printf(stderr, "Error: internal error");
4642 break;
danf9647b62016-12-15 06:01:40 +00004643 }else{
mistachkine16a3502017-05-29 03:48:13 +00004644 if( bGroupByParent
danf9647b62016-12-15 06:01:40 +00004645 && (bVerbose || res==0)
mistachkine16a3502017-05-29 03:48:13 +00004646 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
danf9647b62016-12-15 06:01:40 +00004647 ){
4648 raw_printf(out, "-- Parent table %s\n", zParent);
4649 sqlite3_free(zPrev);
4650 zPrev = sqlite3_mprintf("%s", zParent);
4651 }
4652
4653 if( res==0 ){
4654 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4655 }else if( bVerbose ){
mistachkine16a3502017-05-29 03:48:13 +00004656 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
danf9647b62016-12-15 06:01:40 +00004657 zIndent, zFrom, zTarget
4658 );
4659 }
dan35ac58e2016-12-14 19:28:27 +00004660 }
4661 }
danf9647b62016-12-15 06:01:40 +00004662 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004663
4664 if( rc!=SQLITE_OK ){
4665 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4666 }
4667
4668 rc2 = sqlite3_finalize(pSql);
4669 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4670 rc = rc2;
4671 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4672 }
4673 }else{
4674 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4675 }
4676
4677 return rc;
4678}
dan3c7ebeb2016-12-16 17:28:56 +00004679
dan35ac58e2016-12-14 19:28:27 +00004680/*
dan3c7ebeb2016-12-16 17:28:56 +00004681** Implementation of ".lint" dot command.
4682*/
4683static int lintDotCommand(
4684 ShellState *pState, /* Current shell tool state */
4685 char **azArg, /* Array of arguments passed to dot command */
4686 int nArg /* Number of entries in azArg[] */
4687){
4688 int n;
drh96ada592016-12-29 19:48:46 +00004689 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004690 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4691 return lintFkeyIndexes(pState, azArg, nArg);
4692
4693 usage:
4694 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4695 raw_printf(stderr, "Where sub-commands are:\n");
4696 raw_printf(stderr, " fkey-indexes\n");
4697 return SQLITE_ERROR;
4698}
4699
dan35ac58e2016-12-14 19:28:27 +00004700
drhcd0509e2016-09-16 00:26:08 +00004701/*
drh75897232000-05-29 14:26:00 +00004702** If an input line begins with "." then invoke this routine to
4703** process that line.
drh67505e72002-04-19 12:34:06 +00004704**
drh47ad6842006-11-08 12:25:42 +00004705** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004706*/
drhdcd87a92014-08-18 13:45:42 +00004707static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004708 int h = 1;
drh75897232000-05-29 14:26:00 +00004709 int nArg = 0;
4710 int n, c;
drh67505e72002-04-19 12:34:06 +00004711 int rc = 0;
drh75897232000-05-29 14:26:00 +00004712 char *azArg[50];
4713
4714 /* Parse the input line into tokens.
4715 */
mistachkin8e189222015-04-19 21:43:16 +00004716 while( zLine[h] && nArg<ArraySize(azArg) ){
4717 while( IsSpace(zLine[h]) ){ h++; }
4718 if( zLine[h]==0 ) break;
4719 if( zLine[h]=='\'' || zLine[h]=='"' ){
4720 int delim = zLine[h++];
4721 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004722 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004723 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004724 h++;
drh4c56b992013-06-27 13:26:55 +00004725 }
mistachkin8e189222015-04-19 21:43:16 +00004726 if( zLine[h]==delim ){
4727 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004728 }
drhfeac5f82004-08-01 00:10:45 +00004729 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004730 }else{
mistachkin8e189222015-04-19 21:43:16 +00004731 azArg[nArg++] = &zLine[h];
4732 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4733 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004734 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004735 }
4736 }
4737
4738 /* Process the input line.
4739 */
shane9bd1b442009-10-23 01:27:39 +00004740 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004741 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004742 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004743
drha0daa752016-09-16 11:53:10 +00004744#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004745 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4746 if( nArg!=2 ){
4747 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4748 rc = 1;
4749 goto meta_command_exit;
4750 }
4751 open_db(p, 0);
4752 if( booleanValue(azArg[1]) ){
4753 sqlite3_set_authorizer(p->db, shellAuth, p);
4754 }else{
4755 sqlite3_set_authorizer(p->db, 0, 0);
4756 }
4757 }else
drha0daa752016-09-16 11:53:10 +00004758#endif
drhde613c62016-04-04 17:23:10 +00004759
drh5c7976f2014-02-10 19:59:27 +00004760 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4761 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4762 ){
drhbc46f022013-01-23 18:53:23 +00004763 const char *zDestFile = 0;
4764 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004765 sqlite3 *pDest;
4766 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004767 int j;
4768 for(j=1; j<nArg; j++){
4769 const char *z = azArg[j];
4770 if( z[0]=='-' ){
4771 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004772 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004773 {
mistachkinaae280e2015-12-31 19:06:24 +00004774 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004775 return 1;
4776 }
4777 }else if( zDestFile==0 ){
4778 zDestFile = azArg[j];
4779 }else if( zDb==0 ){
4780 zDb = zDestFile;
4781 zDestFile = azArg[j];
4782 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004783 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004784 return 1;
4785 }
drh9ff849f2009-02-04 20:55:57 +00004786 }
drhbc46f022013-01-23 18:53:23 +00004787 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004788 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004789 return 1;
4790 }
4791 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004792 rc = sqlite3_open(zDestFile, &pDest);
4793 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004794 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004795 sqlite3_close(pDest);
4796 return 1;
4797 }
drh05782482013-10-24 15:20:20 +00004798 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004799 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4800 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004801 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004802 sqlite3_close(pDest);
4803 return 1;
4804 }
4805 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4806 sqlite3_backup_finish(pBackup);
4807 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004808 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004809 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004810 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004811 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004812 }
4813 sqlite3_close(pDest);
4814 }else
4815
drhc2ce0be2014-05-29 12:36:14 +00004816 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4817 if( nArg==2 ){
4818 bail_on_error = booleanValue(azArg[1]);
4819 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004820 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004821 rc = 1;
4822 }
drhc49f44e2006-10-26 18:15:42 +00004823 }else
4824
mistachkinf21979d2015-01-18 05:35:01 +00004825 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4826 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004827 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004828 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004829 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004830 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004831 }
mistachkinf21979d2015-01-18 05:35:01 +00004832 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004833 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004834 rc = 1;
4835 }
4836 }else
4837
drh453ca042017-05-22 18:00:34 +00004838 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4839 if( nArg==2 ){
4840#if defined(_WIN32) || defined(WIN32)
4841 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4842 rc = !SetCurrentDirectoryW(z);
4843 sqlite3_free(z);
4844#else
4845 rc = chdir(azArg[1]);
4846#endif
4847 if( rc ){
4848 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4849 rc = 1;
4850 }
4851 }else{
4852 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4853 rc = 1;
4854 }
4855 }else
4856
drhd8621b92012-04-17 09:09:33 +00004857 /* The undocumented ".breakpoint" command causes a call to the no-op
4858 ** routine named test_breakpoint().
4859 */
4860 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4861 test_breakpoint();
4862 }else
4863
drhdf12f1c2015-12-07 21:46:19 +00004864 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4865 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004866 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004867 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004868 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004869 rc = 1;
4870 }
4871 }else
4872
drh2db82112016-09-15 21:35:24 +00004873 /* Cancel output redirection, if it is currently set (by .testcase)
4874 ** Then read the content of the testcase-out.txt file and compare against
4875 ** azArg[1]. If there are differences, report an error and exit.
4876 */
4877 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4878 char *zRes = 0;
4879 output_reset(p);
4880 if( nArg!=2 ){
4881 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004882 rc = 2;
dan11da0022016-12-17 08:18:05 +00004883 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004884 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4885 rc = 2;
4886 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004887 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004888 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4889 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004890 rc = 2;
drh760c8162016-09-16 02:52:22 +00004891 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004892 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004893 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004894 }
4895 sqlite3_free(zRes);
4896 }else
drh2db82112016-09-15 21:35:24 +00004897
drhc2ce0be2014-05-29 12:36:14 +00004898 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4899 if( nArg==2 ){
4900 tryToClone(p, azArg[1]);
4901 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004902 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004903 rc = 1;
4904 }
mistachkine31ae902014-02-06 01:15:29 +00004905 }else
4906
drhc2ce0be2014-05-29 12:36:14 +00004907 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004908 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004909 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004910 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004911 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004912 data.showHeader = 0;
4913 data.cMode = data.mode = MODE_List;
4914 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004915 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004916 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4917 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004918 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004919 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004920 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004921 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004922 }
4923 }else
4924
drh0e55db12015-02-06 14:51:13 +00004925 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4926 rc = shell_dbinfo_command(p, nArg, azArg);
4927 }else
4928
drhc2ce0be2014-05-29 12:36:14 +00004929 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004930 const char *zLike = 0;
4931 int i;
drh72507d42017-04-08 00:55:13 +00004932 int savedShowHeader = p->showHeader;
drhe6e1d122017-03-09 13:50:49 +00004933 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004934 for(i=1; i<nArg; i++){
4935 if( azArg[i][0]=='-' ){
4936 const char *z = azArg[i]+1;
4937 if( z[0]=='-' ) z++;
4938 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00004939#ifdef SQLITE_OMIT_VIRTUALTABLE
4940 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4941 " with SQLITE_OMIT_VIRTUALTABLE\n");
4942 rc = 1;
4943 goto meta_command_exit;
4944#else
drhe6e1d122017-03-09 13:50:49 +00004945 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00004946#endif
drhe611f142017-03-08 11:44:00 +00004947 }else
4948 {
4949 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4950 rc = 1;
4951 goto meta_command_exit;
4952 }
4953 }else if( zLike ){
4954 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4955 rc = 1;
4956 goto meta_command_exit;
4957 }else{
4958 zLike = azArg[i];
4959 }
4960 }
drh05782482013-10-24 15:20:20 +00004961 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004962 /* When playing back a "dump", the content might appear in an order
4963 ** which causes immediate foreign key constraints to be violated.
4964 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004965 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4966 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004967 p->writableSchema = 0;
drh72507d42017-04-08 00:55:13 +00004968 p->showHeader = 0;
drhe611f142017-03-08 11:44:00 +00004969 /* Set writable_schema=ON since doing so forces SQLite to initialize
4970 ** as much of the schema as it can even if the sqlite_master table is
4971 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004972 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004973 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004974 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004975 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004976 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004977 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004978 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004979 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004980 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004981 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004982 );
drh2f464a02011-10-13 00:41:49 +00004983 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004984 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004985 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004986 );
drh4c653a02000-06-07 01:27:47 +00004987 }else{
drhe611f142017-03-08 11:44:00 +00004988 char *zSql;
4989 zSql = sqlite3_mprintf(
4990 "SELECT name, type, sql FROM sqlite_master "
4991 "WHERE tbl_name LIKE %Q AND type=='table'"
4992 " AND sql NOT NULL", zLike);
4993 run_schema_dump_query(p,zSql);
4994 sqlite3_free(zSql);
4995 zSql = sqlite3_mprintf(
4996 "SELECT sql FROM sqlite_master "
4997 "WHERE sql NOT NULL"
4998 " AND type IN ('index','trigger','view')"
4999 " AND tbl_name LIKE %Q", zLike);
5000 run_table_dump_query(p, zSql, 0);
5001 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00005002 }
drh45e29d82006-11-20 16:21:10 +00005003 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00005004 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00005005 p->writableSchema = 0;
5006 }
drh56197952011-10-13 16:30:13 +00005007 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5008 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00005009 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh72507d42017-04-08 00:55:13 +00005010 p->showHeader = savedShowHeader;
drh4c653a02000-06-07 01:27:47 +00005011 }else
drh75897232000-05-29 14:26:00 +00005012
drhc2ce0be2014-05-29 12:36:14 +00005013 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5014 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00005015 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005016 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005017 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005018 rc = 1;
5019 }
drhdaffd0e2001-04-11 14:28:42 +00005020 }else
5021
drhc2ce0be2014-05-29 12:36:14 +00005022 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5023 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00005024 if( strcmp(azArg[1],"full")==0 ){
5025 p->autoEQP = 2;
5026 }else{
5027 p->autoEQP = booleanValue(azArg[1]);
5028 }
drhc2ce0be2014-05-29 12:36:14 +00005029 }else{
drheacd29d2016-04-15 15:03:27 +00005030 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00005031 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00005032 }
drhefbf3b12014-02-28 20:47:24 +00005033 }else
5034
drhd3ac7d92013-01-25 18:33:43 +00005035 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00005036 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00005037 rc = 2;
drh75897232000-05-29 14:26:00 +00005038 }else
5039
drhc31b79d2017-06-29 21:11:27 +00005040 /* The ".explain" command is automatic now. It is largely pointless. It
5041 ** retained purely for backwards compatibility */
drhc2ce0be2014-05-29 12:36:14 +00005042 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00005043 int val = 1;
5044 if( nArg>=2 ){
5045 if( strcmp(azArg[1],"auto")==0 ){
5046 val = 99;
5047 }else{
5048 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00005049 }
drh700c2522016-02-09 18:39:25 +00005050 }
5051 if( val==1 && p->mode!=MODE_Explain ){
5052 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00005053 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00005054 p->autoExplain = 0;
5055 }else if( val==0 ){
5056 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5057 p->autoExplain = 0;
5058 }else if( val==99 ){
5059 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5060 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005061 }
drh75897232000-05-29 14:26:00 +00005062 }else
5063
drhc1971542014-06-23 23:28:13 +00005064 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005065 ShellState data;
drhc1971542014-06-23 23:28:13 +00005066 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00005067 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00005068 memcpy(&data, p, sizeof(data));
5069 data.showHeader = 0;
5070 data.cMode = data.mode = MODE_Semi;
5071 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5072 data.cMode = data.mode = MODE_Pretty;
5073 nArg = 1;
5074 }
drhc1971542014-06-23 23:28:13 +00005075 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00005076 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00005077 rc = 1;
5078 goto meta_command_exit;
5079 }
5080 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00005081 rc = sqlite3_exec(p->db,
5082 "SELECT sql FROM"
5083 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5084 " FROM sqlite_master UNION ALL"
5085 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005086 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00005087 "ORDER BY rowid",
5088 callback, &data, &zErrMsg
5089 );
drh56f674c2014-07-18 14:43:29 +00005090 if( rc==SQLITE_OK ){
5091 sqlite3_stmt *pStmt;
5092 rc = sqlite3_prepare_v2(p->db,
5093 "SELECT rowid FROM sqlite_master"
5094 " WHERE name GLOB 'sqlite_stat[134]'",
5095 -1, &pStmt, 0);
5096 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5097 sqlite3_finalize(pStmt);
5098 }
5099 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005100 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00005101 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005102 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005103 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5104 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00005105 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00005106 data.zDestTable = "sqlite_stat1";
5107 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5108 shell_callback, &data,&zErrMsg);
5109 data.zDestTable = "sqlite_stat3";
5110 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5111 shell_callback, &data,&zErrMsg);
5112 data.zDestTable = "sqlite_stat4";
5113 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5114 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00005115 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005116 }
drhc1971542014-06-23 23:28:13 +00005117 }else
5118
drhc2ce0be2014-05-29 12:36:14 +00005119 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5120 if( nArg==2 ){
5121 p->showHeader = booleanValue(azArg[1]);
5122 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005123 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005124 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00005125 }
drh75897232000-05-29 14:26:00 +00005126 }else
5127
drhc2ce0be2014-05-29 12:36:14 +00005128 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005129 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00005130 }else
5131
5132 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00005133 char *zTable; /* Insert data into this table */
5134 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00005135 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00005136 int nCol; /* Number of columns in the table */
5137 int nByte; /* Number of bytes in an SQL string */
5138 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00005139 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00005140 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00005141 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00005142 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00005143 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5144 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00005145
drhc2ce0be2014-05-29 12:36:14 +00005146 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005147 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00005148 goto meta_command_exit;
5149 }
drh01f37542014-05-31 15:43:33 +00005150 zFile = azArg[1];
5151 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00005152 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00005153 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00005154 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005155 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00005156 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005157 raw_printf(stderr,
5158 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00005159 return 1;
drhfeac5f82004-08-01 00:10:45 +00005160 }
drhdb95f682013-06-26 22:46:00 +00005161 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005162 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00005163 " for import\n");
5164 return 1;
5165 }
mistachkin636bf9f2014-07-19 20:15:16 +00005166 nSep = strlen30(p->rowSeparator);
5167 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005168 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005169 return 1;
5170 }
mistachkine0d68852014-12-11 03:12:33 +00005171 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5172 /* When importing CSV (only), if the row separator is set to the
5173 ** default output row separator, change it to the default input
5174 ** row separator. This avoids having to maintain different input
5175 ** and output row separators. */
5176 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5177 nSep = strlen30(p->rowSeparator);
5178 }
mistachkin636bf9f2014-07-19 20:15:16 +00005179 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005180 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00005181 " for import\n");
5182 return 1;
5183 }
5184 sCtx.zFile = zFile;
5185 sCtx.nLine = 1;
5186 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005187#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005188 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005189 return 1;
5190#else
mistachkin636bf9f2014-07-19 20:15:16 +00005191 sCtx.in = popen(sCtx.zFile+1, "r");
5192 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00005193 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00005194#endif
drh5bde8162013-06-27 14:07:53 +00005195 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00005196 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00005197 xCloser = fclose;
5198 }
mistachkin636bf9f2014-07-19 20:15:16 +00005199 if( p->mode==MODE_Ascii ){
5200 xRead = ascii_read_one_field;
5201 }else{
5202 xRead = csv_read_one_field;
5203 }
5204 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005205 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00005206 return 1;
5207 }
mistachkin636bf9f2014-07-19 20:15:16 +00005208 sCtx.cColSep = p->colSeparator[0];
5209 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00005210 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00005211 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005212 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005213 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005214 return 1;
5215 }
drh4f21c4a2008-12-10 22:15:00 +00005216 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005217 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005218 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005219 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005220 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5221 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005222 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005223 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005224 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005225 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005226 }
drh5bde8162013-06-27 14:07:53 +00005227 if( cSep=='(' ){
5228 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005229 sqlite3_free(sCtx.z);
5230 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005231 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005232 return 1;
5233 }
drhdb95f682013-06-26 22:46:00 +00005234 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5235 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5236 sqlite3_free(zCreate);
5237 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005238 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005239 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005240 sqlite3_free(sCtx.z);
5241 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005242 return 1;
5243 }
drhc7181902014-02-27 15:04:13 +00005244 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005245 }
drhfeac5f82004-08-01 00:10:45 +00005246 sqlite3_free(zSql);
5247 if( rc ){
shane916f9612009-10-23 00:37:15 +00005248 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005249 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005250 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005251 return 1;
drhfeac5f82004-08-01 00:10:45 +00005252 }
shane916f9612009-10-23 00:37:15 +00005253 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005254 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005255 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005256 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005257 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005258 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005259 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005260 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005261 return 1;
5262 }
drhdb95f682013-06-26 22:46:00 +00005263 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005264 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005265 for(i=1; i<nCol; i++){
5266 zSql[j++] = ',';
5267 zSql[j++] = '?';
5268 }
5269 zSql[j++] = ')';
5270 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005271 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005272 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005273 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005274 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005275 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00005276 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00005277 return 1;
drhfeac5f82004-08-01 00:10:45 +00005278 }
mistachkin8e189222015-04-19 21:43:16 +00005279 needCommit = sqlite3_get_autocommit(p->db);
5280 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00005281 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005282 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005283 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005284 char *z = xRead(&sCtx);
5285 /*
5286 ** Did we reach end-of-file before finding any columns?
5287 ** If so, stop instead of NULL filling the remaining columns.
5288 */
drhdb95f682013-06-26 22:46:00 +00005289 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005290 /*
5291 ** Did we reach end-of-file OR end-of-line before finding any
5292 ** columns in ASCII mode? If so, stop instead of NULL filling
5293 ** the remaining columns.
5294 */
5295 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005296 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005297 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005298 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005299 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005300 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005301 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005302 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005303 }
drhfeac5f82004-08-01 00:10:45 +00005304 }
mistachkin636bf9f2014-07-19 20:15:16 +00005305 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005306 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005307 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005308 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005309 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005310 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005311 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005312 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005313 }
drhdb95f682013-06-26 22:46:00 +00005314 if( i>=nCol ){
5315 sqlite3_step(pStmt);
5316 rc = sqlite3_reset(pStmt);
5317 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005318 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5319 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005320 }
5321 }
mistachkin636bf9f2014-07-19 20:15:16 +00005322 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005323
mistachkin636bf9f2014-07-19 20:15:16 +00005324 xCloser(sCtx.in);
5325 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005326 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005327 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005328 }else
5329
drhd12602a2016-12-07 15:49:02 +00005330#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005331 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5332 char *zSql;
5333 char *zCollist = 0;
5334 sqlite3_stmt *pStmt;
5335 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005336 int i;
drh16eb5942016-11-03 13:01:38 +00005337 if( nArg!=3 ){
5338 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5339 rc = 1;
5340 goto meta_command_exit;
5341 }
5342 open_db(p, 0);
5343 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5344 " WHERE name='%q' AND type='index'", azArg[1]);
5345 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5346 sqlite3_free(zSql);
5347 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5348 tnum = sqlite3_column_int(pStmt, 0);
5349 }
5350 sqlite3_finalize(pStmt);
5351 if( tnum==0 ){
5352 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5353 rc = 1;
5354 goto meta_command_exit;
5355 }
5356 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5357 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5358 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005359 i = 0;
drh16eb5942016-11-03 13:01:38 +00005360 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005361 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005362 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005363 i++;
5364 if( zCol==0 ){
5365 if( sqlite3_column_int(pStmt,1)==-1 ){
5366 zCol = "_ROWID_";
5367 }else{
5368 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5369 zCol = zLabel;
5370 }
5371 }
drh16eb5942016-11-03 13:01:38 +00005372 if( zCollist==0 ){
5373 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5374 }else{
5375 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5376 }
5377 }
5378 sqlite3_finalize(pStmt);
5379 zSql = sqlite3_mprintf(
5380 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5381 azArg[2], zCollist, zCollist);
5382 sqlite3_free(zCollist);
5383 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5384 if( rc==SQLITE_OK ){
5385 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5386 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5387 if( rc ){
5388 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5389 }else{
5390 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005391 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005392 "WARNING: writing to an imposter table will corrupt the index!\n"
5393 );
5394 }
5395 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005396 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005397 rc = 1;
5398 }
5399 sqlite3_free(zSql);
5400 }else
5401#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5402
drhae5e4452007-05-03 17:18:36 +00005403#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005404 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005405 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005406 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5407 iotrace = 0;
5408 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005409 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005410 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005411 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005412 iotrace = stdout;
5413 }else{
5414 iotrace = fopen(azArg[1], "w");
5415 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005416 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005417 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005418 rc = 1;
drhb0603412007-02-28 04:47:26 +00005419 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005420 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005421 }
5422 }
5423 }else
drhae5e4452007-05-03 17:18:36 +00005424#endif
drh16eb5942016-11-03 13:01:38 +00005425
drh1a513372015-05-02 17:40:23 +00005426 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5427 static const struct {
5428 const char *zLimitName; /* Name of a limit */
5429 int limitCode; /* Integer code for that limit */
5430 } aLimit[] = {
5431 { "length", SQLITE_LIMIT_LENGTH },
5432 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5433 { "column", SQLITE_LIMIT_COLUMN },
5434 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5435 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5436 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5437 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5438 { "attached", SQLITE_LIMIT_ATTACHED },
5439 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5440 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5441 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5442 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5443 };
5444 int i, n2;
5445 open_db(p, 0);
5446 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005447 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005448 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005449 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5450 }
5451 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005452 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005453 rc = 1;
5454 goto meta_command_exit;
5455 }else{
5456 int iLimit = -1;
5457 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005458 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005459 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5460 if( iLimit<0 ){
5461 iLimit = i;
5462 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005463 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005464 rc = 1;
5465 goto meta_command_exit;
5466 }
5467 }
5468 }
5469 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005470 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005471 "enter \".limits\" with no arguments for a list.\n",
5472 azArg[1]);
5473 rc = 1;
5474 goto meta_command_exit;
5475 }
5476 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005477 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5478 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005479 }
5480 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5481 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5482 }
5483 }else
drhb0603412007-02-28 04:47:26 +00005484
dan3c7ebeb2016-12-16 17:28:56 +00005485 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005486 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005487 lintDotCommand(p, azArg, nArg);
5488 }else
5489
drh70df4fe2006-06-13 15:12:21 +00005490#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005491 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005492 const char *zFile, *zProc;
5493 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005494 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005495 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005496 rc = 1;
5497 goto meta_command_exit;
5498 }
drh1e397f82006-06-08 15:28:43 +00005499 zFile = azArg[1];
5500 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005501 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005502 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5503 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005504 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005505 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005506 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005507 }
5508 }else
drh70df4fe2006-06-13 15:12:21 +00005509#endif
drh1e397f82006-06-08 15:28:43 +00005510
drhc2ce0be2014-05-29 12:36:14 +00005511 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5512 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005513 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005514 rc = 1;
5515 }else{
5516 const char *zFile = azArg[1];
5517 output_file_close(p->pLog);
5518 p->pLog = output_file_open(zFile);
5519 }
drh127f9d72010-02-23 01:47:00 +00005520 }else
5521
drhc2ce0be2014-05-29 12:36:14 +00005522 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5523 const char *zMode = nArg>=2 ? azArg[1] : "";
5524 int n2 = (int)strlen(zMode);
5525 int c2 = zMode[0];
5526 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005527 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005528 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005529 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005530 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005531 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005532 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005533 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005534 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5535 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005536 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005537 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005538 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005539 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005540 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005541 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005542 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005543 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005544 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005545 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005546 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005547 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005548 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005549 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005550 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005551 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005552 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5553 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005554 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5555 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005556 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5557 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drha501f7d2017-06-29 21:33:25 +00005558 }else if( nArg==1 ){
5559 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
5560 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005561 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005562 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005563 rc = 1;
drh75897232000-05-29 14:26:00 +00005564 }
drh700c2522016-02-09 18:39:25 +00005565 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005566 }else
5567
drhc2ce0be2014-05-29 12:36:14 +00005568 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5569 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005570 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5571 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005572 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005573 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005574 rc = 1;
5575 }
5576 }else
5577
drh05782482013-10-24 15:20:20 +00005578 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005579 char *zNewFilename; /* Name of the database file to open */
5580 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005581 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005582 /* Close the existing database */
5583 session_close_all(p);
5584 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005585 p->db = 0;
dan21472212017-03-01 11:30:27 +00005586 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005587 sqlite3_free(p->zFreeOnClose);
5588 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005589 /* Check for command-line arguments */
5590 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5591 const char *z = azArg[iName];
5592 if( optionMatch(z,"new") ){
5593 newFlag = 1;
5594 }else if( z[0]=='-' ){
5595 utf8_printf(stderr, "unknown option: %s\n", z);
5596 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005597 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005598 }
drhcd0509e2016-09-16 00:26:08 +00005599 }
5600 /* If a filename is specified, try to open it first */
5601 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5602 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005603 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005604 p->zDbFilename = zNewFilename;
5605 open_db(p, 1);
5606 if( p->db==0 ){
5607 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5608 sqlite3_free(zNewFilename);
5609 }else{
5610 p->zFreeOnClose = zNewFilename;
5611 }
5612 }
5613 if( p->db==0 ){
5614 /* As a fall-back open a TEMP database */
5615 p->zDbFilename = 0;
5616 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005617 }
5618 }else
5619
drhc2ce0be2014-05-29 12:36:14 +00005620 if( c=='o'
5621 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5622 ){
5623 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5624 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005625 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005626 rc = 1;
5627 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005628 }
drhc2ce0be2014-05-29 12:36:14 +00005629 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5630 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005631 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005632 rc = 1;
5633 goto meta_command_exit;
5634 }
5635 p->outCount = 2;
5636 }else{
5637 p->outCount = 0;
5638 }
5639 output_reset(p);
5640 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005641#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005642 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005643 rc = 1;
5644 p->out = stdout;
5645#else
drhc2ce0be2014-05-29 12:36:14 +00005646 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005647 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005648 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005649 p->out = stdout;
5650 rc = 1;
5651 }else{
drhc2ce0be2014-05-29 12:36:14 +00005652 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005653 }
drh8cd5b252015-03-02 22:06:43 +00005654#endif
drh75897232000-05-29 14:26:00 +00005655 }else{
drhc2ce0be2014-05-29 12:36:14 +00005656 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005657 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005658 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005659 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005660 }
drh75897232000-05-29 14:26:00 +00005661 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005662 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005663 } else {
drhc2ce0be2014-05-29 12:36:14 +00005664 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005665 }
5666 }
5667 }else
5668
drh078b1fd2012-09-21 13:40:02 +00005669 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5670 int i;
5671 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005672 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005673 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005674 }
mistachkinaae280e2015-12-31 19:06:24 +00005675 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005676 }else
5677
drhc2ce0be2014-05-29 12:36:14 +00005678 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005679 if( nArg >= 2) {
5680 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5681 }
5682 if( nArg >= 3) {
5683 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5684 }
5685 }else
5686
drhc2ce0be2014-05-29 12:36:14 +00005687 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005688 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005689 }else
5690
drhc2ce0be2014-05-29 12:36:14 +00005691 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5692 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005693 if( nArg!=2 ){
5694 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005695 rc = 1;
5696 goto meta_command_exit;
5697 }
drh4e8142c2016-11-11 14:54:22 +00005698 alt = fopen(azArg[1], "rb");
5699 if( alt==0 ){
5700 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5701 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005702 }else{
drh4e8142c2016-11-11 14:54:22 +00005703 rc = process_input(p, alt);
5704 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005705 }
5706 }else
5707
drhc2ce0be2014-05-29 12:36:14 +00005708 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005709 const char *zSrcFile;
5710 const char *zDb;
5711 sqlite3 *pSrc;
5712 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005713 int nTimeout = 0;
5714
drh9ff849f2009-02-04 20:55:57 +00005715 if( nArg==2 ){
5716 zSrcFile = azArg[1];
5717 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005718 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005719 zSrcFile = azArg[2];
5720 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005721 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005722 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005723 rc = 1;
5724 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005725 }
5726 rc = sqlite3_open(zSrcFile, &pSrc);
5727 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005728 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005729 sqlite3_close(pSrc);
5730 return 1;
5731 }
drh05782482013-10-24 15:20:20 +00005732 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005733 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5734 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005735 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005736 sqlite3_close(pSrc);
5737 return 1;
5738 }
drhdc2c4912009-02-04 22:46:47 +00005739 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5740 || rc==SQLITE_BUSY ){
5741 if( rc==SQLITE_BUSY ){
5742 if( nTimeout++ >= 3 ) break;
5743 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005744 }
5745 }
5746 sqlite3_backup_finish(pBackup);
5747 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005748 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005749 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005750 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005751 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005752 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005753 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005754 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005755 }
5756 sqlite3_close(pSrc);
5757 }else
5758
dan8d1edb92014-11-05 09:07:28 +00005759
5760 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5761 if( nArg==2 ){
5762 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005763#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005764 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005765#endif
dan8d1edb92014-11-05 09:07:28 +00005766 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005767 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005768 rc = 1;
5769 }
5770 }else
5771
drhc2ce0be2014-05-29 12:36:14 +00005772 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drh20c9c3f2017-06-15 12:21:09 +00005773 ShellText sSelect;
drhdcd87a92014-08-18 13:45:42 +00005774 ShellState data;
drh75897232000-05-29 14:26:00 +00005775 char *zErrMsg = 0;
drh20c9c3f2017-06-15 12:21:09 +00005776 const char *zDiv = 0;
5777 int iSchema = 0;
5778
drh05782482013-10-24 15:20:20 +00005779 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005780 memcpy(&data, p, sizeof(data));
5781 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005782 data.cMode = data.mode = MODE_Semi;
drh20c9c3f2017-06-15 12:21:09 +00005783 initText(&sSelect);
drh4926fec2016-04-13 15:33:42 +00005784 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5785 data.cMode = data.mode = MODE_Pretty;
5786 nArg--;
5787 if( nArg==2 ) azArg[1] = azArg[2];
5788 }
5789 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005790 int i;
drhf0693c82011-10-11 20:41:54 +00005791 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005792 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005793 char *new_argv[2], *new_colv[2];
5794 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5795 " type text,\n"
5796 " name text,\n"
5797 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005798 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005799 " sql text\n"
5800 ")";
5801 new_argv[1] = 0;
5802 new_colv[0] = "sql";
5803 new_colv[1] = 0;
5804 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005805 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005806 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005807 char *new_argv[2], *new_colv[2];
5808 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5809 " type text,\n"
5810 " name text,\n"
5811 " tbl_name text,\n"
5812 " rootpage integer,\n"
5813 " sql text\n"
5814 ")";
5815 new_argv[1] = 0;
5816 new_colv[0] = "sql";
5817 new_colv[1] = 0;
5818 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005819 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005820 }else{
drh20c9c3f2017-06-15 12:21:09 +00005821 zDiv = "(";
drha18c5682000-10-08 22:20:57 +00005822 }
drhc2ce0be2014-05-29 12:36:14 +00005823 }else if( nArg==1 ){
drh20c9c3f2017-06-15 12:21:09 +00005824 zDiv = "(";
drhc2ce0be2014-05-29 12:36:14 +00005825 }else{
drh4926fec2016-04-13 15:33:42 +00005826 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005827 rc = 1;
5828 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005829 }
drh20c9c3f2017-06-15 12:21:09 +00005830 if( zDiv ){
5831 sqlite3_stmt *pStmt = 0;
5832 sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
5833 -1, &pStmt, 0);
5834 appendText(&sSelect, "SELECT sql FROM", 0);
5835 iSchema = 0;
5836 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5837 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
5838 char zScNum[30];
5839 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
5840 appendText(&sSelect, zDiv, 0);
5841 zDiv = " UNION ALL ";
5842 if( strcmp(zDb, "main")!=0 ){
5843 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
drh90cdec02017-06-15 13:07:56 +00005844 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00005845 appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
5846 appendText(&sSelect, zScNum, 0);
5847 appendText(&sSelect, " AS snum, ", 0);
5848 appendText(&sSelect, zDb, '\'');
5849 appendText(&sSelect, " AS sname FROM ", 0);
drh90cdec02017-06-15 13:07:56 +00005850 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00005851 appendText(&sSelect, ".sqlite_master", 0);
5852 }else{
5853 appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5854 appendText(&sSelect, zScNum, 0);
5855 appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
5856 }
5857 }
5858 sqlite3_finalize(pStmt);
5859 appendText(&sSelect, ") WHERE ", 0);
5860 if( nArg>1 ){
5861 char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
5862 if( strchr(azArg[1], '.') ){
5863 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
5864 }else{
5865 appendText(&sSelect, "lower(tbl_name)", 0);
5866 }
5867 appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
5868 appendText(&sSelect, zQarg, 0);
5869 appendText(&sSelect, " AND ", 0);
5870 sqlite3_free(zQarg);
5871 }
5872 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
5873 " ORDER BY snum, rowid", 0);
5874 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
5875 freeText(&sSelect);
5876 }
drh75897232000-05-29 14:26:00 +00005877 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005878 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005879 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005880 rc = 1;
5881 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005882 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005883 rc = 1;
5884 }else{
5885 rc = 0;
drh75897232000-05-29 14:26:00 +00005886 }
5887 }else
5888
drhabd4c722014-09-20 18:18:33 +00005889#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5890 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005891 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005892 }else
5893#endif
5894
drhe6229612014-08-18 15:08:26 +00005895#if defined(SQLITE_ENABLE_SESSION)
5896 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5897 OpenSession *pSession = &p->aSession[0];
5898 char **azCmd = &azArg[1];
5899 int iSes = 0;
5900 int nCmd = nArg - 1;
5901 int i;
5902 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005903 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005904 if( nArg>=3 ){
5905 for(iSes=0; iSes<p->nSession; iSes++){
5906 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5907 }
5908 if( iSes<p->nSession ){
5909 pSession = &p->aSession[iSes];
5910 azCmd++;
5911 nCmd--;
5912 }else{
5913 pSession = &p->aSession[0];
5914 iSes = 0;
5915 }
5916 }
5917
drh3a67b042014-08-18 17:56:31 +00005918 /* .session attach TABLE
5919 ** Invoke the sqlite3session_attach() interface to attach a particular
5920 ** table so that it is never filtered.
5921 */
5922 if( strcmp(azCmd[0],"attach")==0 ){
5923 if( nCmd!=2 ) goto session_syntax_error;
5924 if( pSession->p==0 ){
5925 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005926 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005927 }else{
5928 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5929 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005930 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005931 rc = 0;
5932 }
5933 }
5934 }else
5935
5936 /* .session changeset FILE
5937 ** .session patchset FILE
5938 ** Write a changeset or patchset into a file. The file is overwritten.
5939 */
5940 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5941 FILE *out = 0;
5942 if( nCmd!=2 ) goto session_syntax_error;
5943 if( pSession->p==0 ) goto session_not_open;
5944 out = fopen(azCmd[1], "wb");
5945 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005946 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005947 }else{
5948 int szChng;
5949 void *pChng;
5950 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005951 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005952 }else{
drh2967e0c2014-08-19 00:26:17 +00005953 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5954 }
5955 if( rc ){
5956 printf("Error: error code %d\n", rc);
5957 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005958 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005959 if( pChng
drh3a67b042014-08-18 17:56:31 +00005960 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005961 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005962 szChng);
5963 }
5964 sqlite3_free(pChng);
5965 fclose(out);
5966 }
5967 }else
5968
drhe6229612014-08-18 15:08:26 +00005969 /* .session close
5970 ** Close the identified session
5971 */
5972 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005973 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005974 if( p->nSession ){
5975 session_close(pSession);
5976 p->aSession[iSes] = p->aSession[--p->nSession];
5977 }
5978 }else
5979
drh03168ca2014-08-18 20:01:31 +00005980 /* .session enable ?BOOLEAN?
5981 ** Query or set the enable flag
5982 */
5983 if( strcmp(azCmd[0], "enable")==0 ){
5984 int ii;
5985 if( nCmd>2 ) goto session_syntax_error;
5986 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5987 if( p->nSession ){
5988 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005989 utf8_printf(p->out, "session %s enable flag = %d\n",
5990 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005991 }
5992 }else
5993
5994 /* .session filter GLOB ....
5995 ** Set a list of GLOB patterns of table names to be excluded.
5996 */
5997 if( strcmp(azCmd[0], "filter")==0 ){
5998 int ii, nByte;
5999 if( nCmd<2 ) goto session_syntax_error;
6000 if( p->nSession ){
6001 for(ii=0; ii<pSession->nFilter; ii++){
6002 sqlite3_free(pSession->azFilter[ii]);
6003 }
6004 sqlite3_free(pSession->azFilter);
6005 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6006 pSession->azFilter = sqlite3_malloc( nByte );
6007 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006008 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00006009 exit(1);
6010 }
6011 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00006012 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00006013 }
6014 pSession->nFilter = ii-1;
6015 }
6016 }else
6017
6018 /* .session indirect ?BOOLEAN?
6019 ** Query or set the indirect flag
6020 */
6021 if( strcmp(azCmd[0], "indirect")==0 ){
6022 int ii;
6023 if( nCmd>2 ) goto session_syntax_error;
6024 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6025 if( p->nSession ){
6026 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00006027 utf8_printf(p->out, "session %s indirect flag = %d\n",
6028 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006029 }
6030 }else
6031
6032 /* .session isempty
6033 ** Determine if the session is empty
6034 */
6035 if( strcmp(azCmd[0], "isempty")==0 ){
6036 int ii;
6037 if( nCmd!=1 ) goto session_syntax_error;
6038 if( p->nSession ){
6039 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00006040 utf8_printf(p->out, "session %s isempty flag = %d\n",
6041 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006042 }
6043 }else
6044
drhe6229612014-08-18 15:08:26 +00006045 /* .session list
6046 ** List all currently open sessions
6047 */
6048 if( strcmp(azCmd[0],"list")==0 ){
6049 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00006050 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00006051 }
6052 }else
6053
6054 /* .session open DB NAME
6055 ** Open a new session called NAME on the attached database DB.
6056 ** DB is normally "main".
6057 */
6058 if( strcmp(azCmd[0],"open")==0 ){
6059 char *zName;
6060 if( nCmd!=3 ) goto session_syntax_error;
6061 zName = azCmd[2];
6062 if( zName[0]==0 ) goto session_syntax_error;
6063 for(i=0; i<p->nSession; i++){
6064 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006065 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00006066 goto meta_command_exit;
6067 }
6068 }
6069 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00006070 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00006071 goto meta_command_exit;
6072 }
6073 pSession = &p->aSession[p->nSession];
6074 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6075 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00006076 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00006077 rc = 0;
drhe6229612014-08-18 15:08:26 +00006078 goto meta_command_exit;
6079 }
drh03168ca2014-08-18 20:01:31 +00006080 pSession->nFilter = 0;
6081 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00006082 p->nSession++;
6083 pSession->zName = sqlite3_mprintf("%s", zName);
6084 }else
6085 /* If no command name matches, show a syntax error */
6086 session_syntax_error:
6087 session_help(p);
6088 }else
6089#endif
6090
drh340f5822013-06-27 13:01:21 +00006091#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00006092 /* Undocumented commands for internal testing. Subject to change
6093 ** without notice. */
6094 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6095 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6096 int i, v;
6097 for(i=1; i<nArg; i++){
6098 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00006099 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00006100 }
6101 }
6102 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6103 int i; sqlite3_int64 v;
6104 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00006105 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00006106 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00006107 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00006108 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00006109 }
6110 }
6111 }else
drh340f5822013-06-27 13:01:21 +00006112#endif
drh348d19c2013-06-03 12:47:43 +00006113
drhfb546af2017-03-09 22:00:33 +00006114 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6115 int bIsInit = 0; /* True to initialize the SELFTEST table */
6116 int bVerbose = 0; /* Verbose output */
6117 int bSelftestExists; /* True if SELFTEST already exists */
drhc5d353f2017-06-09 02:27:49 +00006118 int i, k; /* Loop counters */
drhfb546af2017-03-09 22:00:33 +00006119 int nTest = 0; /* Number of tests runs */
6120 int nErr = 0; /* Number of errors seen */
6121 ShellText str; /* Answer for a query */
drhc5d353f2017-06-09 02:27:49 +00006122 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
drhfb546af2017-03-09 22:00:33 +00006123
6124 open_db(p,0);
6125 for(i=1; i<nArg; i++){
6126 const char *z = azArg[i];
6127 if( z[0]=='-' && z[1]=='-' ) z++;
6128 if( strcmp(z,"-init")==0 ){
6129 bIsInit = 1;
6130 }else
6131 if( strcmp(z,"-v")==0 ){
6132 bVerbose++;
6133 }else
6134 {
6135 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6136 azArg[i], azArg[0]);
6137 raw_printf(stderr, "Should be one of: --init -v\n");
6138 rc = 1;
6139 goto meta_command_exit;
6140 }
6141 }
6142 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6143 != SQLITE_OK ){
6144 bSelftestExists = 0;
6145 }else{
6146 bSelftestExists = 1;
6147 }
6148 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006149 createSelftestTable(p);
6150 bSelftestExists = 1;
6151 }
drhc5d353f2017-06-09 02:27:49 +00006152 initText(&str);
6153 appendText(&str, "x", 0);
6154 for(k=bSelftestExists; k>=0; k--){
6155 if( k==1 ){
6156 rc = sqlite3_prepare_v2(p->db,
6157 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6158 -1, &pStmt, 0);
6159 }else{
6160 rc = sqlite3_prepare_v2(p->db,
6161 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6162 " (1,'run','PRAGMA integrity_check','ok')",
6163 -1, &pStmt, 0);
6164 }
drhfb546af2017-03-09 22:00:33 +00006165 if( rc ){
6166 raw_printf(stderr, "Error querying the selftest table\n");
6167 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006168 sqlite3_finalize(pStmt);
drhfb546af2017-03-09 22:00:33 +00006169 goto meta_command_exit;
drhfb546af2017-03-09 22:00:33 +00006170 }
drhc5d353f2017-06-09 02:27:49 +00006171 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6172 int tno = sqlite3_column_int(pStmt, 0);
6173 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6174 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6175 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
mistachkine16a3502017-05-29 03:48:13 +00006176
drhc5d353f2017-06-09 02:27:49 +00006177 k = 0;
6178 if( bVerbose>0 ){
6179 char *zQuote = sqlite3_mprintf("%q", zSql);
6180 printf("%d: %s %s\n", tno, zOp, zSql);
6181 sqlite3_free(zQuote);
drhfb546af2017-03-09 22:00:33 +00006182 }
drhc5d353f2017-06-09 02:27:49 +00006183 if( strcmp(zOp,"memo")==0 ){
6184 utf8_printf(p->out, "%s\n", zSql);
6185 }else
6186 if( strcmp(zOp,"run")==0 ){
6187 char *zErrMsg = 0;
6188 str.n = 0;
6189 str.z[0] = 0;
6190 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6191 nTest++;
6192 if( bVerbose ){
6193 utf8_printf(p->out, "Result: %s\n", str.z);
6194 }
6195 if( rc || zErrMsg ){
6196 nErr++;
6197 rc = 1;
6198 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6199 sqlite3_free(zErrMsg);
6200 }else if( strcmp(zAns,str.z)!=0 ){
6201 nErr++;
6202 rc = 1;
6203 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6204 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6205 }
6206 }else
6207 {
6208 utf8_printf(stderr,
6209 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
drhfb546af2017-03-09 22:00:33 +00006210 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006211 break;
drhfb546af2017-03-09 22:00:33 +00006212 }
drhc5d353f2017-06-09 02:27:49 +00006213 } /* End loop over rows of content from SELFTEST */
6214 sqlite3_finalize(pStmt);
6215 } /* End loop over k */
drhfb546af2017-03-09 22:00:33 +00006216 freeText(&str);
drhfb546af2017-03-09 22:00:33 +00006217 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6218 }else
6219
drhc2ce0be2014-05-29 12:36:14 +00006220 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006221 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006222 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006223 rc = 1;
6224 }
drh6976c212014-07-24 12:09:47 +00006225 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006226 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006227 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006228 }
6229 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006230 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6231 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006232 }
drh75897232000-05-29 14:26:00 +00006233 }else
6234
drh1554bc82017-03-08 16:10:34 +00006235 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6236 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6237 int i; /* Loop counter */
6238 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006239 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006240 int iSize = 224; /* Hash algorithm to use */
6241 int bDebug = 0; /* Only show the query that would have run */
6242 sqlite3_stmt *pStmt; /* For querying tables names */
6243 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006244 char *zSep; /* Separator */
6245 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006246 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006247 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006248 for(i=1; i<nArg; i++){
6249 const char *z = azArg[i];
6250 if( z[0]=='-' ){
6251 z++;
6252 if( z[0]=='-' ) z++;
6253 if( strcmp(z,"schema")==0 ){
6254 bSchema = 1;
6255 }else
mistachkine16a3502017-05-29 03:48:13 +00006256 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6257 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
drh1554bc82017-03-08 16:10:34 +00006258 ){
6259 iSize = atoi(&z[5]);
6260 }else
6261 if( strcmp(z,"debug")==0 ){
6262 bDebug = 1;
6263 }else
6264 {
6265 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006266 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006267 raw_printf(stderr, "Should be one of: --schema"
6268 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6269 rc = 1;
6270 goto meta_command_exit;
6271 }
6272 }else if( zLike ){
6273 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6274 rc = 1;
6275 goto meta_command_exit;
6276 }else{
6277 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006278 bSeparate = 1;
6279 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006280 }
6281 }
6282 if( bSchema ){
6283 zSql = "SELECT lower(name) FROM sqlite_master"
6284 " WHERE type='table' AND coalesce(rootpage,0)>1"
6285 " UNION ALL SELECT 'sqlite_master'"
6286 " ORDER BY 1 collate nocase";
6287 }else{
6288 zSql = "SELECT lower(name) FROM sqlite_master"
6289 " WHERE type='table' AND coalesce(rootpage,0)>1"
6290 " AND name NOT LIKE 'sqlite_%'"
6291 " ORDER BY 1 collate nocase";
6292 }
6293 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6294 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006295 initText(&sSql);
6296 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6297 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006298 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6299 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6300 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6301 if( strncmp(zTab, "sqlite_",7)!=0 ){
6302 appendText(&sQuery,"SELECT * FROM ", 0);
6303 appendText(&sQuery,zTab,'"');
6304 appendText(&sQuery," NOT INDEXED;", 0);
6305 }else if( strcmp(zTab, "sqlite_master")==0 ){
6306 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6307 " ORDER BY name;", 0);
6308 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6309 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6310 " ORDER BY name;", 0);
6311 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6312 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6313 " ORDER BY tbl,idx;", 0);
6314 }else if( strcmp(zTab, "sqlite_stat3")==0
6315 || strcmp(zTab, "sqlite_stat4")==0 ){
6316 appendText(&sQuery, "SELECT * FROM ", 0);
6317 appendText(&sQuery, zTab, 0);
6318 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6319 }
drh3ee83ef2017-03-08 17:56:54 +00006320 appendText(&sSql, zSep, 0);
6321 appendText(&sSql, sQuery.z, '\'');
6322 sQuery.n = 0;
6323 appendText(&sSql, ",", 0);
6324 appendText(&sSql, zTab, '\'');
6325 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006326 }
6327 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006328 if( bSeparate ){
6329 zSql = sqlite3_mprintf(
6330 "%s))"
6331 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6332 " FROM [sha3sum$query]",
6333 sSql.z, iSize);
6334 }else{
6335 zSql = sqlite3_mprintf(
6336 "%s))"
6337 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6338 " FROM [sha3sum$query]",
6339 sSql.z, iSize);
6340 }
drh1554bc82017-03-08 16:10:34 +00006341 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006342 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006343 if( bDebug ){
6344 utf8_printf(p->out, "%s\n", zSql);
6345 }else{
6346 shell_exec(p->db, zSql, shell_callback, p, 0);
6347 }
6348 sqlite3_free(zSql);
6349 }else
6350
drh62cdde52014-05-28 20:22:28 +00006351 if( c=='s'
6352 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006353 ){
6354 char *zCmd;
drh54027102014-08-06 14:36:53 +00006355 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006356 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006357 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006358 rc = 1;
6359 goto meta_command_exit;
6360 }
drhdcb3e3d2014-05-29 03:17:29 +00006361 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006362 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006363 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6364 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006365 }
drh54027102014-08-06 14:36:53 +00006366 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006367 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006368 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006369 }else
6370
drhc2ce0be2014-05-29 12:36:14 +00006371 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006372 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006373 int i;
drhc2ce0be2014-05-29 12:36:14 +00006374 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006375 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006376 rc = 1;
6377 goto meta_command_exit;
6378 }
drhe6e1d122017-03-09 13:50:49 +00006379 utf8_printf(p->out, "%12.12s: %s\n","echo",
6380 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006381 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006382 utf8_printf(p->out, "%12.12s: %s\n","explain",
6383 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006384 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006385 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6386 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006387 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006388 raw_printf(p->out, "\n");
6389 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006390 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006391 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006392 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006393 raw_printf(p->out, "\n");
6394 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006395 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006396 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006397 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006398 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006399 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006400 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006401 }
mistachkinaae280e2015-12-31 19:06:24 +00006402 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006403 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6404 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006405 }else
6406
drhc2ce0be2014-05-29 12:36:14 +00006407 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6408 if( nArg==2 ){
6409 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006410 }else if( nArg==1 ){
6411 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006412 }else{
drh34784902016-02-27 17:12:36 +00006413 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006414 rc = 1;
6415 }
shaneh642d8b82010-07-28 16:05:34 +00006416 }else
6417
drh6a5a4202016-12-24 21:32:40 +00006418 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6419 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6420 || strncmp(azArg[0], "indexes", n)==0) )
6421 ){
drh98781232012-04-23 12:38:05 +00006422 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006423 char **azResult;
drh98781232012-04-23 12:38:05 +00006424 int nRow, nAlloc;
drh98781232012-04-23 12:38:05 +00006425 int ii;
drh594ccd02017-06-15 12:50:47 +00006426 ShellText s;
6427 initText(&s);
drh05782482013-10-24 15:20:20 +00006428 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006429 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006430 if( rc ) return shellDatabaseError(p->db);
6431
drh594ccd02017-06-15 12:50:47 +00006432 if( nArg>2 && c=='i' ){
drh6a5a4202016-12-24 21:32:40 +00006433 /* It is an historical accident that the .indexes command shows an error
6434 ** when called with the wrong number of arguments whereas the .tables
6435 ** command does not. */
6436 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6437 rc = 1;
6438 goto meta_command_exit;
drh6a5a4202016-12-24 21:32:40 +00006439 }
drh594ccd02017-06-15 12:50:47 +00006440 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006441 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drh594ccd02017-06-15 12:50:47 +00006442 if( zDbName==0 ) continue;
6443 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6444 if( sqlite3_stricmp(zDbName, "main")==0 ){
6445 appendText(&s, "SELECT name FROM ", 0);
drh6a5a4202016-12-24 21:32:40 +00006446 }else{
drh594ccd02017-06-15 12:50:47 +00006447 appendText(&s, "SELECT ", 0);
6448 appendText(&s, zDbName, '\'');
6449 appendText(&s, "||'.'||name FROM ", 0);
6450 }
6451 appendText(&s, zDbName, '"');
6452 appendText(&s, ".sqlite_master ", 0);
6453 if( c=='t' ){
6454 appendText(&s," WHERE type IN ('table','view')"
6455 " AND name NOT LIKE 'sqlite_%'"
6456 " AND name LIKE ?1", 0);
6457 }else{
6458 appendText(&s," WHERE type='index'"
6459 " AND tbl_name LIKE ?1", 0);
drh98781232012-04-23 12:38:05 +00006460 }
drha50da102000-08-08 20:19:09 +00006461 }
dand95bb392015-09-30 11:19:05 +00006462 rc = sqlite3_finalize(pStmt);
drh594ccd02017-06-15 12:50:47 +00006463 appendText(&s, " ORDER BY 1", 0);
6464 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6465 freeText(&s);
dand95bb392015-09-30 11:19:05 +00006466 if( rc ) return shellDatabaseError(p->db);
6467
6468 /* Run the SQL statement prepared by the above block. Store the results
6469 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006470 nRow = nAlloc = 0;
6471 azResult = 0;
6472 if( nArg>1 ){
6473 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006474 }else{
drh98781232012-04-23 12:38:05 +00006475 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6476 }
6477 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6478 if( nRow>=nAlloc ){
6479 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006480 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006481 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006482 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006483 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006484 break;
6485 }
mistachkin8e189222015-04-19 21:43:16 +00006486 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006487 azResult = azNew;
6488 }
6489 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006490 if( 0==azResult[nRow] ){
6491 rc = shellNomemError();
6492 break;
6493 }
6494 nRow++;
drh98781232012-04-23 12:38:05 +00006495 }
dand95bb392015-09-30 11:19:05 +00006496 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6497 rc = shellDatabaseError(p->db);
6498 }
6499
6500 /* Pretty-print the contents of array azResult[] to the output */
6501 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006502 int len, maxlen = 0;
6503 int i, j;
6504 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006505 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006506 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006507 if( len>maxlen ) maxlen = len;
6508 }
6509 nPrintCol = 80/(maxlen+2);
6510 if( nPrintCol<1 ) nPrintCol = 1;
6511 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6512 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006513 for(j=i; j<nRow; j+=nPrintRow){
6514 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006515 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6516 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006517 }
mistachkinaae280e2015-12-31 19:06:24 +00006518 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006519 }
6520 }
dand95bb392015-09-30 11:19:05 +00006521
drh98781232012-04-23 12:38:05 +00006522 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6523 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006524 }else
6525
drh2db82112016-09-15 21:35:24 +00006526 /* Begin redirecting output to the file "testcase-out.txt" */
6527 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6528 output_reset(p);
6529 p->out = output_file_open("testcase-out.txt");
6530 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006531 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006532 }
drh760c8162016-09-16 02:52:22 +00006533 if( nArg>=2 ){
6534 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6535 }else{
6536 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6537 }
drh2db82112016-09-15 21:35:24 +00006538 }else
drh2db82112016-09-15 21:35:24 +00006539
drhd12602a2016-12-07 15:49:02 +00006540#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006541 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006542 static const struct {
6543 const char *zCtrlName; /* Name of a test-control option */
6544 int ctrlCode; /* Integer code for that option */
6545 } aCtrl[] = {
6546 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6547 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6548 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6549 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6550 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6551 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6552 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6553 { "assert", SQLITE_TESTCTRL_ASSERT },
6554 { "always", SQLITE_TESTCTRL_ALWAYS },
6555 { "reserve", SQLITE_TESTCTRL_RESERVE },
6556 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6557 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006558 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006559 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006560 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006561 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006562 };
shaneh96887e12011-02-10 21:08:58 +00006563 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006564 int rc2 = 0;
6565 int i, n2;
drh05782482013-10-24 15:20:20 +00006566 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006567
drhd416fe72011-03-17 16:45:50 +00006568 /* convert testctrl text option to value. allow any unique prefix
6569 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006570 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006571 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006572 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006573 if( testctrl<0 ){
6574 testctrl = aCtrl[i].ctrlCode;
6575 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006576 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006577 testctrl = -1;
6578 break;
6579 }
6580 }
6581 }
drh348d19c2013-06-03 12:47:43 +00006582 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006583 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006584 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006585 }else{
6586 switch(testctrl){
6587
6588 /* sqlite3_test_control(int, db, int) */
6589 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006590 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006591 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006592 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006593 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006594 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006595 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006596 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006597 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006598 }
6599 break;
6600
6601 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006602 case SQLITE_TESTCTRL_PRNG_SAVE:
6603 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006604 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006605 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006606 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006607 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006608 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006609 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006610 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6611 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006612 }
6613 break;
6614
6615 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006616 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006617 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006618 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006619 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006620 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006621 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006622 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006623 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006624 }
6625 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006626
shaneh96887e12011-02-10 21:08:58 +00006627 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006628 case SQLITE_TESTCTRL_ASSERT:
6629 case SQLITE_TESTCTRL_ALWAYS:
6630 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006631 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006632 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006633 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006634 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006635 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006636 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006637 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006638 }
6639 break;
6640
6641 /* sqlite3_test_control(int, char *) */
6642#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006643 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006644 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006645 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006646 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006647 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006648 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006649 utf8_printf(stderr,
6650 "Error: testctrl %s takes a single char * option\n",
6651 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006652 }
6653 break;
6654#endif
6655
drh1ffede82015-01-30 20:59:27 +00006656 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006657 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006658 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006659 azArg[2],
drh8964b342015-01-29 17:54:52 +00006660 integerValue(azArg[3]),
6661 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006662 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006663 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006664 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006665 }
6666 break;
6667
mistachkin1fe36bb2016-04-04 02:16:44 +00006668 case SQLITE_TESTCTRL_BITVEC_TEST:
6669 case SQLITE_TESTCTRL_FAULT_INSTALL:
6670 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6671 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006672 default:
mistachkinaae280e2015-12-31 19:06:24 +00006673 utf8_printf(stderr,
6674 "Error: CLI support for testctrl %s not implemented\n",
6675 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006676 break;
6677 }
6678 }
6679 }else
drhf1969722017-02-17 23:52:00 +00006680#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006681
drhc2ce0be2014-05-29 12:36:14 +00006682 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006683 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006684 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006685 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006686
drhc2ce0be2014-05-29 12:36:14 +00006687 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6688 if( nArg==2 ){
6689 enableTimer = booleanValue(azArg[1]);
6690 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006691 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006692 enableTimer = 0;
6693 }
6694 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006695 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006696 rc = 1;
6697 }
shanehe2aa9d72009-11-06 17:20:17 +00006698 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006699
drhc2ce0be2014-05-29 12:36:14 +00006700 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006701 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006702 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006703 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006704 rc = 1;
6705 goto meta_command_exit;
6706 }
drh657b4a82015-03-19 13:30:41 +00006707 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006708 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006709#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006710 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006711 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006712 }else{
drh4b363a52016-07-23 20:27:41 +00006713 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006714 }
6715#endif
6716 }else
6717
drhf442e332014-09-10 19:01:14 +00006718#if SQLITE_USER_AUTHENTICATION
6719 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6720 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006721 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006722 rc = 1;
6723 goto meta_command_exit;
6724 }
drh7883ecf2014-09-11 16:19:31 +00006725 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006726 if( strcmp(azArg[1],"login")==0 ){
6727 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006728 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006729 rc = 1;
6730 goto meta_command_exit;
6731 }
drhd39c40f2014-09-11 00:27:53 +00006732 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6733 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006734 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006735 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006736 rc = 1;
6737 }
6738 }else if( strcmp(azArg[1],"add")==0 ){
6739 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006740 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006741 rc = 1;
6742 goto meta_command_exit;
6743 }
drhd39c40f2014-09-11 00:27:53 +00006744 rc = sqlite3_user_add(p->db, azArg[2],
6745 azArg[3], (int)strlen(azArg[3]),
6746 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006747 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006748 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006749 rc = 1;
6750 }
6751 }else if( strcmp(azArg[1],"edit")==0 ){
6752 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006753 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006754 rc = 1;
6755 goto meta_command_exit;
6756 }
drhd39c40f2014-09-11 00:27:53 +00006757 rc = sqlite3_user_change(p->db, azArg[2],
6758 azArg[3], (int)strlen(azArg[3]),
6759 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006760 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006761 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006762 rc = 1;
6763 }
6764 }else if( strcmp(azArg[1],"delete")==0 ){
6765 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006766 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006767 rc = 1;
6768 goto meta_command_exit;
6769 }
6770 rc = sqlite3_user_delete(p->db, azArg[2]);
6771 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006772 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006773 rc = 1;
6774 }
6775 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006776 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006777 rc = 1;
6778 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006779 }
drhf442e332014-09-10 19:01:14 +00006780 }else
6781#endif /* SQLITE_USER_AUTHENTICATION */
6782
drh9fd301b2011-06-03 13:28:22 +00006783 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006784 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006785 sqlite3_libversion(), sqlite3_sourceid());
6786 }else
6787
drh790f2872015-11-28 18:06:36 +00006788 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6789 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006790 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006791 if( p->db ){
6792 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6793 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006794 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6795 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6796 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6797 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006798 }
6799 }
6800 }else
6801
drhb19e7352016-01-12 19:37:20 +00006802 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6803 sqlite3_vfs *pVfs;
6804 sqlite3_vfs *pCurrent = 0;
6805 if( p->db ){
6806 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6807 }
6808 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6809 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6810 pVfs==pCurrent ? " <--- CURRENT" : "");
6811 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6812 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6813 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6814 if( pVfs->pNext ){
6815 raw_printf(p->out, "-----------------------------------\n");
6816 }
6817 }
6818 }else
6819
drhde60fc22011-12-14 17:53:36 +00006820 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6821 const char *zDbName = nArg==2 ? azArg[1] : "main";
6822 char *zVfsName = 0;
6823 if( p->db ){
6824 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6825 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006826 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006827 sqlite3_free(zVfsName);
6828 }
6829 }
6830 }else
6831
drhcef4fc82012-09-21 22:50:45 +00006832#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6833 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006834 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006835 }else
6836#endif
6837
drhc2ce0be2014-05-29 12:36:14 +00006838 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006839 int j;
drh43617e92006-03-06 20:55:46 +00006840 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006841 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006842 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006843 }
6844 }else
6845
6846 {
mistachkinaae280e2015-12-31 19:06:24 +00006847 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006848 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006849 rc = 1;
drh75897232000-05-29 14:26:00 +00006850 }
drh67505e72002-04-19 12:34:06 +00006851
drhc2ce0be2014-05-29 12:36:14 +00006852meta_command_exit:
6853 if( p->outCount ){
6854 p->outCount--;
6855 if( p->outCount==0 ) output_reset(p);
6856 }
drh67505e72002-04-19 12:34:06 +00006857 return rc;
drh75897232000-05-29 14:26:00 +00006858}
6859
drh67505e72002-04-19 12:34:06 +00006860/*
drh91a66392007-09-07 01:12:32 +00006861** Return TRUE if a semicolon occurs anywhere in the first N characters
6862** of string z[].
drh324ccef2003-02-05 14:06:20 +00006863*/
drh9f099fd2013-08-06 14:01:46 +00006864static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006865 int i;
6866 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6867 return 0;
drh324ccef2003-02-05 14:06:20 +00006868}
6869
6870/*
drh70c7a4b2003-04-26 03:03:06 +00006871** Test to see if a line consists entirely of whitespace.
6872*/
6873static int _all_whitespace(const char *z){
6874 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006875 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006876 if( *z=='/' && z[1]=='*' ){
6877 z += 2;
6878 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6879 if( *z==0 ) return 0;
6880 z++;
6881 continue;
6882 }
6883 if( *z=='-' && z[1]=='-' ){
6884 z += 2;
6885 while( *z && *z!='\n' ){ z++; }
6886 if( *z==0 ) return 1;
6887 continue;
6888 }
6889 return 0;
6890 }
6891 return 1;
6892}
6893
6894/*
drha9b17162003-04-29 18:01:28 +00006895** Return TRUE if the line typed in is an SQL command terminator other
6896** than a semi-colon. The SQL Server style "go" command is understood
6897** as is the Oracle "/".
6898*/
drh9f099fd2013-08-06 14:01:46 +00006899static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006900 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006901 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6902 return 1; /* Oracle */
6903 }
drhf0693c82011-10-11 20:41:54 +00006904 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006905 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006906 return 1; /* SQL Server */
6907 }
6908 return 0;
6909}
6910
6911/*
drh233a5312008-12-18 22:25:13 +00006912** Return true if zSql is a complete SQL statement. Return false if it
6913** ends in the middle of a string literal or C-style comment.
6914*/
drh9f099fd2013-08-06 14:01:46 +00006915static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006916 int rc;
6917 if( zSql==0 ) return 1;
6918 zSql[nSql] = ';';
6919 zSql[nSql+1] = 0;
6920 rc = sqlite3_complete(zSql);
6921 zSql[nSql] = 0;
6922 return rc;
6923}
6924
6925/*
drh4e8142c2016-11-11 14:54:22 +00006926** Run a single line of SQL
6927*/
6928static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6929 int rc;
6930 char *zErrMsg = 0;
6931
6932 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006933 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006934 BEGIN_TIMER;
6935 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6936 END_TIMER;
6937 if( rc || zErrMsg ){
6938 char zPrefix[100];
6939 if( in!=0 || !stdin_is_interactive ){
6940 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6941 "Error: near line %d:", startline);
6942 }else{
6943 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6944 }
6945 if( zErrMsg!=0 ){
6946 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6947 sqlite3_free(zErrMsg);
6948 zErrMsg = 0;
6949 }else{
6950 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6951 }
6952 return 1;
drhe6e1d122017-03-09 13:50:49 +00006953 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006954 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6955 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6956 }
6957 return 0;
6958}
6959
6960
6961/*
drh67505e72002-04-19 12:34:06 +00006962** Read input from *in and process it. If *in==0 then input
6963** is interactive - the user is typing it it. Otherwise, input
6964** is coming from a file or device. A prompt is issued and history
6965** is saved only if input is interactive. An interrupt signal will
6966** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006967**
6968** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006969*/
drhdcd87a92014-08-18 13:45:42 +00006970static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006971 char *zLine = 0; /* A single input line */
6972 char *zSql = 0; /* Accumulated SQL text */
6973 int nLine; /* Length of current line */
6974 int nSql = 0; /* Bytes of zSql[] used */
6975 int nAlloc = 0; /* Allocated zSql[] space */
6976 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006977 int rc; /* Error code */
6978 int errCnt = 0; /* Number of errors seen */
6979 int lineno = 0; /* Current line number */
6980 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006981
6982 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6983 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006984 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006985 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006986 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006987 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006988 break;
drhc49f44e2006-10-26 18:15:42 +00006989 }
drh67505e72002-04-19 12:34:06 +00006990 if( seenInterrupt ){
6991 if( in!=0 ) break;
6992 seenInterrupt = 0;
6993 }
drhc28490c2006-10-26 14:25:58 +00006994 lineno++;
drh849a9d92013-12-21 15:46:06 +00006995 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006996 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006997 continue;
6998 }
drh2af0b2d2002-02-21 02:25:02 +00006999 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00007000 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00007001 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00007002 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00007003 break;
7004 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00007005 errCnt++;
7006 }
drhdaffd0e2001-04-11 14:28:42 +00007007 continue;
7008 }
drh9f099fd2013-08-06 14:01:46 +00007009 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00007010 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00007011 }
drh9f099fd2013-08-06 14:01:46 +00007012 nLine = strlen30(zLine);
7013 if( nSql+nLine+2>=nAlloc ){
7014 nAlloc = nSql+nLine+100;
7015 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00007016 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007017 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00007018 exit(1);
7019 }
drhdaffd0e2001-04-11 14:28:42 +00007020 }
drh9f099fd2013-08-06 14:01:46 +00007021 nSqlPrior = nSql;
7022 if( nSql==0 ){
7023 int i;
7024 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00007025 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00007026 memcpy(zSql, zLine+i, nLine+1-i);
7027 startline = lineno;
7028 nSql = nLine-i;
7029 }else{
7030 zSql[nSql++] = '\n';
7031 memcpy(zSql+nSql, zLine, nLine+1);
7032 nSql += nLine;
7033 }
7034 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00007035 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00007036 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007037 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00007038 if( p->outCount ){
7039 output_reset(p);
7040 p->outCount = 0;
7041 }
drh9f099fd2013-08-06 14:01:46 +00007042 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00007043 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00007044 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00007045 }
7046 }
drh4e8142c2016-11-11 14:54:22 +00007047 if( nSql && !_all_whitespace(zSql) ){
7048 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007049 }
drh1f9ca2c2015-08-25 16:57:52 +00007050 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00007051 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00007052 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00007053}
7054
drh67505e72002-04-19 12:34:06 +00007055/*
7056** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00007057** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00007058*/
drhd1459152016-09-16 19:11:03 +00007059static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00007060 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00007061 if( clearFlag ){
7062 free(home_dir);
7063 home_dir = 0;
7064 return 0;
7065 }
drh85e72432012-04-11 11:38:53 +00007066 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00007067
drh4ace5362014-11-10 14:42:28 +00007068#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7069 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00007070 {
7071 struct passwd *pwent;
7072 uid_t uid = getuid();
7073 if( (pwent=getpwuid(uid)) != NULL) {
7074 home_dir = pwent->pw_dir;
7075 }
drh67505e72002-04-19 12:34:06 +00007076 }
7077#endif
7078
chw65d3c132007-11-12 21:09:10 +00007079#if defined(_WIN32_WCE)
7080 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7081 */
drh85e72432012-04-11 11:38:53 +00007082 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00007083#else
7084
drh83905c92012-06-21 13:00:37 +00007085#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00007086 if (!home_dir) {
7087 home_dir = getenv("USERPROFILE");
7088 }
7089#endif
7090
drh67505e72002-04-19 12:34:06 +00007091 if (!home_dir) {
7092 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00007093 }
7094
drh83905c92012-06-21 13:00:37 +00007095#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00007096 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00007097 char *zDrive, *zPath;
7098 int n;
7099 zDrive = getenv("HOMEDRIVE");
7100 zPath = getenv("HOMEPATH");
7101 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00007102 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00007103 home_dir = malloc( n );
7104 if( home_dir==0 ) return 0;
7105 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7106 return home_dir;
7107 }
7108 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00007109 }
7110#endif
7111
chw65d3c132007-11-12 21:09:10 +00007112#endif /* !_WIN32_WCE */
7113
drh67505e72002-04-19 12:34:06 +00007114 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00007115 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00007116 char *z = malloc( n );
7117 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00007118 home_dir = z;
7119 }
drhe98d4fa2002-04-21 19:06:22 +00007120
drh67505e72002-04-19 12:34:06 +00007121 return home_dir;
7122}
7123
7124/*
7125** Read input from the file given by sqliterc_override. Or if that
7126** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007127**
7128** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007129*/
drh534f4df2015-02-28 14:03:35 +00007130static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007131 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007132 const char *sqliterc_override /* Name of config file. NULL to use default */
7133){
persicom7e2dfdd2002-04-18 02:46:52 +00007134 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007135 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007136 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007137 FILE *in = NULL;
7138
7139 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007140 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007141 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007142 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007143 " cannot read ~/.sqliterc\n");
7144 return;
drhe98d4fa2002-04-21 19:06:22 +00007145 }
drh2f3de322012-06-27 16:41:31 +00007146 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007147 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7148 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007149 }
drha1f9b5e2004-02-14 16:31:02 +00007150 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007151 if( in ){
drhc28490c2006-10-26 14:25:58 +00007152 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007153 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007154 }
drh534f4df2015-02-28 14:03:35 +00007155 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007156 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007157 }
drh85e72432012-04-11 11:38:53 +00007158 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007159}
7160
drh67505e72002-04-19 12:34:06 +00007161/*
drhe1e38c42003-05-04 18:30:59 +00007162** Show available command line options
7163*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007164static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007165 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007166 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007167 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007168 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007169 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007170 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007171 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007172 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007173 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007174#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7175 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7176#endif
drhcc3b4f82012-02-07 14:13:50 +00007177 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007178 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007179 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007180 " -line set output mode to 'line'\n"
7181 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007182 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007183 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007184#ifdef SQLITE_ENABLE_MULTIPLEX
7185 " -multiplex enable the multiplexor VFS\n"
7186#endif
mistachkine0d68852014-12-11 03:12:33 +00007187 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007188 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007189 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
drha501f7d2017-06-29 21:33:25 +00007190 " -quote set output mode to 'quote'\n"
drh44dec872014-08-30 15:49:25 +00007191 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00007192 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007193 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007194 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007195 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007196#ifdef SQLITE_ENABLE_VFSTRACE
7197 " -vfstrace enable tracing of all VFS calls\n"
7198#endif
drhe1e38c42003-05-04 18:30:59 +00007199;
7200static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007201 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007202 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007203 "FILENAME is the name of an SQLite database. A new database is created\n"
7204 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007205 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007206 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007207 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007208 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007209 }
7210 exit(1);
7211}
7212
7213/*
drh67505e72002-04-19 12:34:06 +00007214** Initialize the state information in data
7215*/
drhdcd87a92014-08-18 13:45:42 +00007216static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007217 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007218 data->normalMode = data->cMode = data->mode = MODE_List;
7219 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007220 memcpy(data->colSeparator,SEP_Column, 2);
7221 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007222 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007223 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007224 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007225 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007226 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007227 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7228 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007229}
7230
drh98d312f2012-10-25 15:23:14 +00007231/*
drh5c7976f2014-02-10 19:59:27 +00007232** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007233*/
7234#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007235static void printBold(const char *zText){
7236 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7237 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7238 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7239 SetConsoleTextAttribute(out,
7240 FOREGROUND_RED|FOREGROUND_INTENSITY
7241 );
7242 printf("%s", zText);
7243 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007244}
7245#else
drh5c7976f2014-02-10 19:59:27 +00007246static void printBold(const char *zText){
7247 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007248}
7249#endif
7250
7251/*
drh98d312f2012-10-25 15:23:14 +00007252** Get the argument to an --option. Throw an error and die if no argument
7253** is available.
7254*/
7255static char *cmdline_option_value(int argc, char **argv, int i){
7256 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007257 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007258 argv[0], argv[argc-1]);
7259 exit(1);
7260 }
7261 return argv[i];
7262}
7263
mistachkin1fe36bb2016-04-04 02:16:44 +00007264#ifndef SQLITE_SHELL_IS_UTF8
7265# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7266# define SQLITE_SHELL_IS_UTF8 (0)
7267# else
7268# define SQLITE_SHELL_IS_UTF8 (1)
7269# endif
7270#endif
7271
7272#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007273int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007274#else
7275int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007276 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007277#endif
drh75897232000-05-29 14:26:00 +00007278 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007279 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007280 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007281 int i;
drhc28490c2006-10-26 14:25:58 +00007282 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007283 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007284 int readStdin = 1;
7285 int nCmd = 0;
7286 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007287
mistachkin1fe36bb2016-04-04 02:16:44 +00007288 setBinaryMode(stdin, 0);
7289 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007290 stdin_is_interactive = isatty(0);
7291 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007292
drh69b30ab2014-02-27 15:11:52 +00007293#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007294 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007295 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007296 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7297 exit(1);
7298 }
drhc7181902014-02-27 15:04:13 +00007299#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007300 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007301#if !SQLITE_SHELL_IS_UTF8
7302 sqlite3_initialize();
7303 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7304 if( argv==0 ){
7305 raw_printf(stderr, "out of memory\n");
7306 exit(1);
7307 }
7308 for(i=0; i<argc; i++){
7309 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7310 if( argv[i]==0 ){
7311 raw_printf(stderr, "out of memory\n");
7312 exit(1);
7313 }
7314 }
7315#endif
mistachkin1810f222016-04-04 02:33:34 +00007316 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007317 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007318
drh44c2eb12003-04-30 11:38:26 +00007319 /* Make sure we have a valid signal handler early, before anything
7320 ** else is done.
7321 */
drh4c504392000-10-16 22:06:40 +00007322#ifdef SIGINT
7323 signal(SIGINT, interrupt_handler);
7324#endif
drh44c2eb12003-04-30 11:38:26 +00007325
drhac5649a2014-11-28 13:35:03 +00007326#ifdef SQLITE_SHELL_DBNAME_PROC
7327 {
7328 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7329 ** of a C-function that will provide the name of the database file. Use
7330 ** this compile-time option to embed this shell program in larger
7331 ** applications. */
7332 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7333 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7334 warnInmemoryDb = 0;
7335 }
7336#endif
7337
drh22fbcb82004-02-01 01:22:50 +00007338 /* Do an initial pass through the command-line argument to locate
7339 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007340 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007341 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007342 */
drh98d312f2012-10-25 15:23:14 +00007343 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007344 char *z;
drhc28490c2006-10-26 14:25:58 +00007345 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007346 if( z[0]!='-' ){
7347 if( data.zDbFilename==0 ){
7348 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007349 }else{
7350 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7351 ** mean that nothing is read from stdin */
7352 readStdin = 0;
7353 nCmd++;
7354 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7355 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007356 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007357 exit(1);
7358 }
7359 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007360 }
drh98d312f2012-10-25 15:23:14 +00007361 }
drhcc3b4f82012-02-07 14:13:50 +00007362 if( z[1]=='-' ) z++;
7363 if( strcmp(z,"-separator")==0
7364 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007365 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007366 || strcmp(z,"-cmd")==0
7367 ){
drh98d312f2012-10-25 15:23:14 +00007368 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007369 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007370 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007371 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007372 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007373 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007374 ** we do the actual processing of arguments later in a second pass.
7375 */
shanef69573d2009-10-24 02:06:14 +00007376 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007377 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007378#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007379 const char *zSize;
7380 sqlite3_int64 szHeap;
7381
drh98d312f2012-10-25 15:23:14 +00007382 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007383 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007384 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007385 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007386#else
7387 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007388#endif
drh44dec872014-08-30 15:49:25 +00007389 }else if( strcmp(z,"-scratch")==0 ){
7390 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007391 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007392 if( sz>400000 ) sz = 400000;
7393 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007394 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007395 if( n>10 ) n = 10;
7396 if( n<1 ) n = 1;
7397 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7398 data.shellFlgs |= SHFLG_Scratch;
7399 }else if( strcmp(z,"-pagecache")==0 ){
7400 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007401 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007402 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007403 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007404 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007405 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7406 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007407 data.shellFlgs |= SHFLG_Pagecache;
7408 }else if( strcmp(z,"-lookaside")==0 ){
7409 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007410 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007411 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007412 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007413 if( n<0 ) n = 0;
7414 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7415 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007416#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007417 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007418 extern int vfstrace_register(
7419 const char *zTraceName,
7420 const char *zOldVfsName,
7421 int (*xOut)(const char*,void*),
7422 void *pOutArg,
7423 int makeDefault
7424 );
drh2b625e22011-03-16 17:05:28 +00007425 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007426#endif
drh6f25e892011-07-08 17:02:57 +00007427#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007428 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007429 extern int sqlite3_multiple_initialize(const char*,int);
7430 sqlite3_multiplex_initialize(0, 1);
7431#endif
drh7d9f3942013-04-03 01:26:54 +00007432 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007433 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7434 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007435 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007436 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007437 if( pVfs ){
7438 sqlite3_vfs_register(pVfs, 1);
7439 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007440 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007441 exit(1);
7442 }
drh44c2eb12003-04-30 11:38:26 +00007443 }
7444 }
drh98d312f2012-10-25 15:23:14 +00007445 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007446#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007447 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007448 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007449#else
mistachkinaae280e2015-12-31 19:06:24 +00007450 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007451 return 1;
drh01b41712005-08-29 23:06:23 +00007452#endif
drh98d312f2012-10-25 15:23:14 +00007453 }
7454 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007455
drh44c2eb12003-04-30 11:38:26 +00007456 /* Go ahead and open the database file if it already exists. If the
7457 ** file does not exist, delay opening it. This prevents empty database
7458 ** files from being created if a user mistypes the database name argument
7459 ** to the sqlite command-line tool.
7460 */
drhc8d74412004-08-31 23:41:26 +00007461 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007462 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007463 }
7464
drh22fbcb82004-02-01 01:22:50 +00007465 /* Process the initialization file if there is one. If no -init option
7466 ** is given on the command line, look for a file named ~/.sqliterc and
7467 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007468 */
drh534f4df2015-02-28 14:03:35 +00007469 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007470
drh22fbcb82004-02-01 01:22:50 +00007471 /* Make a second pass through the command-line argument and set
7472 ** options. This second pass is delayed until after the initialization
7473 ** file is processed so that the command-line arguments will override
7474 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007475 */
drh98d312f2012-10-25 15:23:14 +00007476 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007477 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007478 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007479 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007480 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007481 i++;
7482 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007483 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007484 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007485 data.mode = MODE_List;
drha501f7d2017-06-29 21:33:25 +00007486 }else if( strcmp(z,"-quote")==0 ){
7487 data.mode = MODE_Quote;
drh22fbcb82004-02-01 01:22:50 +00007488 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007489 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007490 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007491 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007492 }else if( strcmp(z,"-csv")==0 ){
7493 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007494 memcpy(data.colSeparator,",",2);
7495 }else if( strcmp(z,"-ascii")==0 ){
7496 data.mode = MODE_Ascii;
7497 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007498 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007499 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007500 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007501 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007502 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007503 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007504 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007505 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007506 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007507 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007508 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007509 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007510 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007511 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007512 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007513 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007514 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007515 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007516 }else if( strcmp(z,"-eqp")==0 ){
7517 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007518 }else if( strcmp(z,"-eqpfull")==0 ){
7519 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007520 }else if( strcmp(z,"-stats")==0 ){
7521 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007522 }else if( strcmp(z,"-scanstats")==0 ){
7523 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007524 }else if( strcmp(z,"-backslash")==0 ){
7525 /* Undocumented command-line option: -backslash
7526 ** Causes C-style backslash escapes to be evaluated in SQL statements
7527 ** prior to sending the SQL into SQLite. Useful for injecting
7528 ** crazy bytes in the middle of SQL statements for testing and debugging.
7529 */
drhe6e1d122017-03-09 13:50:49 +00007530 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007531 }else if( strcmp(z,"-bail")==0 ){
7532 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007533 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007534 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007535 return 0;
drhc28490c2006-10-26 14:25:58 +00007536 }else if( strcmp(z,"-interactive")==0 ){
7537 stdin_is_interactive = 1;
7538 }else if( strcmp(z,"-batch")==0 ){
7539 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007540 }else if( strcmp(z,"-heap")==0 ){
7541 i++;
drh44dec872014-08-30 15:49:25 +00007542 }else if( strcmp(z,"-scratch")==0 ){
7543 i+=2;
7544 }else if( strcmp(z,"-pagecache")==0 ){
7545 i+=2;
7546 }else if( strcmp(z,"-lookaside")==0 ){
7547 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007548 }else if( strcmp(z,"-mmap")==0 ){
7549 i++;
drha7e61d82011-03-12 17:02:57 +00007550 }else if( strcmp(z,"-vfs")==0 ){
7551 i++;
drh6f25e892011-07-08 17:02:57 +00007552#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007553 }else if( strcmp(z,"-vfstrace")==0 ){
7554 i++;
drh6f25e892011-07-08 17:02:57 +00007555#endif
7556#ifdef SQLITE_ENABLE_MULTIPLEX
7557 }else if( strcmp(z,"-multiplex")==0 ){
7558 i++;
7559#endif
drhcc3b4f82012-02-07 14:13:50 +00007560 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007561 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007562 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007563 /* Run commands that follow -cmd first and separately from commands
7564 ** that simply appear on the command-line. This seems goofy. It would
7565 ** be better if all commands ran in the order that they appear. But
7566 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007567 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007568 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007569 if( z[0]=='.' ){
7570 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007571 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007572 }else{
drh05782482013-10-24 15:20:20 +00007573 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007574 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7575 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007576 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007577 if( bail_on_error ) return rc!=0 ? rc : 1;
7578 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007579 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007580 if( bail_on_error ) return rc;
7581 }
7582 }
drh1e5d0e92000-05-31 23:33:17 +00007583 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007584 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7585 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007586 return 1;
7587 }
drh700c2522016-02-09 18:39:25 +00007588 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007589 }
drh44c2eb12003-04-30 11:38:26 +00007590
drhac5649a2014-11-28 13:35:03 +00007591 if( !readStdin ){
7592 /* Run all arguments that do not begin with '-' as if they were separate
7593 ** command-line inputs, except for the argToSkip argument which contains
7594 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007595 */
drhac5649a2014-11-28 13:35:03 +00007596 for(i=0; i<nCmd; i++){
7597 if( azCmd[i][0]=='.' ){
7598 rc = do_meta_command(azCmd[i], &data);
7599 if( rc ) return rc==2 ? 0 : rc;
7600 }else{
7601 open_db(&data, 0);
7602 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7603 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007604 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007605 return rc!=0 ? rc : 1;
7606 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007607 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007608 return rc;
7609 }
drh6ff13852001-11-25 13:18:23 +00007610 }
drh75897232000-05-29 14:26:00 +00007611 }
drhac5649a2014-11-28 13:35:03 +00007612 free(azCmd);
drh75897232000-05-29 14:26:00 +00007613 }else{
drh44c2eb12003-04-30 11:38:26 +00007614 /* Run commands received from standard input
7615 */
drhc28490c2006-10-26 14:25:58 +00007616 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007617 char *zHome;
7618 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007619 int nHistory;
drh75897232000-05-29 14:26:00 +00007620 printf(
drh743e0032011-12-12 16:51:50 +00007621 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007622 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007623 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007624 );
drhb3735912014-02-10 16:13:42 +00007625 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007626 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007627 printBold("transient in-memory database");
7628 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007629 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007630 }
drhd1459152016-09-16 19:11:03 +00007631 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007632 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007633 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007634 if( (zHistory = malloc(nHistory))!=0 ){
7635 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7636 }
drh67505e72002-04-19 12:34:06 +00007637 }
drhf5ed7ad2015-06-15 14:43:25 +00007638 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007639 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007640 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007641 shell_stifle_history(100);
7642 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007643 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007644 }
drhdaffd0e2001-04-11 14:28:42 +00007645 }else{
drhc28490c2006-10-26 14:25:58 +00007646 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007647 }
7648 }
drh33048c02001-10-01 14:29:22 +00007649 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007650 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007651 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007652 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007653 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007654 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007655 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007656#if !SQLITE_SHELL_IS_UTF8
7657 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7658 sqlite3_free(argv);
7659#endif
drhc28490c2006-10-26 14:25:58 +00007660 return rc;
drh75897232000-05-29 14:26:00 +00007661}