blob: ec255a6737cfb6422c185590f560244c1609b401 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
drh75897232000-05-29 14:26:00 +000014*/
mistachkina3b2ff52011-09-16 20:16:36 +000015#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
shane18e526c2008-12-10 22:30:24 +000016/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
drh36f7dd32011-10-13 16:02:17 +000020/*
drhce13b992017-05-23 20:00:00 +000021** Warning pragmas copied from msvc.h in the core.
mistachkin2318d332015-01-12 18:02:52 +000022*/
drhce13b992017-05-23 20:00:00 +000023#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
mistachkin2318d332015-01-12 18:02:52 +000040
41/*
drh8cd5b252015-03-02 22:06:43 +000042** No support for loadable extensions in VxWorks.
43*/
drhada3f2b2015-03-23 21:32:50 +000044#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000045# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
drh36f7dd32011-10-13 16:02:17 +000049** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
drh75897232000-05-29 14:26:00 +000059#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000062#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000063#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000064#if SQLITE_USER_AUTHENTICATION
65# include "sqlite3userauth.h"
66#endif
drh75897232000-05-29 14:26:00 +000067#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000068#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000069
drh83905c92012-06-21 13:00:37 +000070#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000071# include <signal.h>
chw97185482008-11-17 08:05:31 +000072# if !defined(__RTP__) && !defined(_WRS_KERNEL)
73# include <pwd.h>
74# endif
drhdd45df82002-04-18 12:39:03 +000075# include <unistd.h>
76# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000077#endif
drh75897232000-05-29 14:26:00 +000078
drh0ede9eb2015-01-10 16:49:23 +000079#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000080# include <readline/readline.h>
81# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +000082#endif
danfd34d6d2015-02-25 10:54:53 +000083
drh0ede9eb2015-01-10 16:49:23 +000084#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +000085# include <editline/readline.h>
86#endif
danfd34d6d2015-02-25 10:54:53 +000087
88#if HAVE_EDITLINE || HAVE_READLINE
89
90# define shell_add_history(X) add_history(X)
91# define shell_read_history(X) read_history(X)
92# define shell_write_history(X) write_history(X)
93# define shell_stifle_history(X) stifle_history(X)
94# define shell_readline(X) readline(X)
95
96#elif HAVE_LINENOISE
97
98# include "linenoise.h"
99# define shell_add_history(X) linenoiseHistoryAdd(X)
100# define shell_read_history(X) linenoiseHistoryLoad(X)
101# define shell_write_history(X) linenoiseHistorySave(X)
102# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103# define shell_readline(X) linenoise(X)
104
105#else
106
mistachkin1fe36bb2016-04-04 02:16:44 +0000107# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +0000108# define shell_write_history(X)
109# define shell_stifle_history(X)
110
111# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +0000112#endif
113
danfd34d6d2015-02-25 10:54:53 +0000114
adamd2e8464a2006-09-06 21:39:40 +0000115#if defined(_WIN32) || defined(WIN32)
116# include <io.h>
drh6976c212014-07-24 12:09:47 +0000117# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000118# define isatty(h) _isatty(h)
119# ifndef access
120# define access(f,m) _access((f),(m))
121# endif
122# undef popen
123# define popen _popen
124# undef pclose
125# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000126#else
mistachkin073664d2015-06-17 18:57:37 +0000127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000129
mistachkin073664d2015-06-17 18:57:37 +0000130# if !defined(__RTP__) && !defined(_WRS_KERNEL)
131 /* popen and pclose are not C89 functions and so are
132 ** sometimes omitted from the <stdio.h> header */
133 extern FILE *popen(const char*,const char*);
134 extern int pclose(FILE*);
135# else
136# define SQLITE_OMIT_POPEN 1
137# endif
mistachkinf6418892013-08-28 01:54:12 +0000138#endif
drh53371f92013-07-25 17:07:03 +0000139
chw65d3c132007-11-12 21:09:10 +0000140#if defined(_WIN32_WCE)
141/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
144 */
145#define isatty(x) 1
146#endif
147
drhf0693c82011-10-11 20:41:54 +0000148/* ctype macros that work with signed characters */
149#define IsSpace(X) isspace((unsigned char)X)
150#define IsDigit(X) isdigit((unsigned char)X)
151#define ToLower(X) (char)tolower((unsigned char)X)
152
mistachkin1fe36bb2016-04-04 02:16:44 +0000153#if defined(_WIN32) || defined(WIN32)
154#include <windows.h>
155
156/* string conversion routines only needed on Win32 */
157extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
158extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000160extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000161#endif
162
drh047d4532015-01-18 20:30:23 +0000163/* On Windows, we normally run with output mode of TEXT so that \n characters
164** are automatically translated into \r\n. However, this behavior needs
165** to be disabled in some cases (ex: when generating CSV output and when
166** rendering quoted strings that contain \n characters). The following
167** routines take care of that.
168*/
169#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000170static void setBinaryMode(FILE *file, int isOutput){
171 if( isOutput ) fflush(file);
172 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000173}
mistachkin1fe36bb2016-04-04 02:16:44 +0000174static void setTextMode(FILE *file, int isOutput){
175 if( isOutput ) fflush(file);
176 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000177}
178#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000179# define setBinaryMode(X,Y)
180# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000181#endif
182
drh43408312013-10-30 12:43:36 +0000183
184/* True if the timer is enabled */
185static int enableTimer = 0;
186
187/* Return the current wall-clock time */
188static sqlite3_int64 timeOfDay(void){
189 static sqlite3_vfs *clockVfs = 0;
190 sqlite3_int64 t;
191 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000192 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000193 clockVfs->xCurrentTimeInt64(clockVfs, &t);
194 }else{
195 double r;
196 clockVfs->xCurrentTime(clockVfs, &r);
197 t = (sqlite3_int64)(r*86400000.0);
198 }
199 return t;
200}
201
drh91eb93c2015-03-03 19:56:20 +0000202#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000203#include <sys/time.h>
204#include <sys/resource.h>
205
drh91eb93c2015-03-03 19:56:20 +0000206/* VxWorks does not support getrusage() as far as we can determine */
207#if defined(_WRS_KERNEL) || defined(__RTP__)
208struct rusage {
209 struct timeval ru_utime; /* user CPU time used */
210 struct timeval ru_stime; /* system CPU time used */
211};
212#define getrusage(A,B) memset(B,0,sizeof(*B))
213#endif
214
drhda108222009-02-25 19:07:24 +0000215/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000216static struct rusage sBegin; /* CPU time at start */
217static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000218
drhda108222009-02-25 19:07:24 +0000219/*
220** Begin timing an operation
221*/
222static void beginTimer(void){
223 if( enableTimer ){
224 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000225 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000226 }
227}
228
229/* Return the difference of two time_structs in seconds */
230static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000231 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000232 (double)(pEnd->tv_sec - pStart->tv_sec);
233}
234
235/*
236** Print the timing results.
237*/
238static void endTimer(void){
239 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000240 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000241 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000242 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000243 printf("Run Time: real %.3f user %f sys %f\n",
244 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000245 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
246 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
247 }
248}
shaneb320ccd2009-10-21 03:42:58 +0000249
drhda108222009-02-25 19:07:24 +0000250#define BEGIN_TIMER beginTimer()
251#define END_TIMER endTimer()
252#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000253
254#elif (defined(_WIN32) || defined(WIN32))
255
shaneb320ccd2009-10-21 03:42:58 +0000256/* Saved resource information for the beginning of an operation */
257static HANDLE hProcess;
258static FILETIME ftKernelBegin;
259static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000260static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000261typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
262 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000263static GETPROCTIMES getProcessTimesAddr = NULL;
264
shaneb320ccd2009-10-21 03:42:58 +0000265/*
266** Check to see if we have timer support. Return 1 if necessary
267** support found (or found previously).
268*/
269static int hasTimer(void){
270 if( getProcessTimesAddr ){
271 return 1;
272 } else {
drh4ace5362014-11-10 14:42:28 +0000273 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274 ** versions. See if the version we are running on has it, and if it
275 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000276 */
277 hProcess = GetCurrentProcess();
278 if( hProcess ){
279 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
280 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000281 getProcessTimesAddr =
282 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000283 if( NULL != getProcessTimesAddr ){
284 return 1;
285 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000286 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000287 }
288 }
289 }
290 return 0;
291}
292
293/*
294** Begin timing an operation
295*/
296static void beginTimer(void){
297 if( enableTimer && getProcessTimesAddr ){
298 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000299 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
300 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000301 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000302 }
303}
304
305/* Return the difference of two FILETIME structs in seconds */
306static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
307 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
308 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
309 return (double) ((i64End - i64Start) / 10000000.0);
310}
311
312/*
313** Print the timing results.
314*/
315static void endTimer(void){
316 if( enableTimer && getProcessTimesAddr){
317 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000318 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000319 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000320 printf("Run Time: real %.3f user %f sys %f\n",
321 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000322 timeDiff(&ftUserBegin, &ftUserEnd),
323 timeDiff(&ftKernelBegin, &ftKernelEnd));
324 }
325}
326
327#define BEGIN_TIMER beginTimer()
328#define END_TIMER endTimer()
329#define HAS_TIMER hasTimer()
330
drhda108222009-02-25 19:07:24 +0000331#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000332#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000333#define END_TIMER
334#define HAS_TIMER 0
335#endif
336
shanec0688ea2009-03-05 03:48:06 +0000337/*
338** Used to prevent warnings about unused parameters
339*/
340#define UNUSED_PARAMETER(x) (void)(x)
341
drhe91d16b2008-12-08 18:27:31 +0000342/*
drhc49f44e2006-10-26 18:15:42 +0000343** If the following flag is set, then command execution stops
344** at an error if we are not interactive.
345*/
346static int bail_on_error = 0;
347
348/*
drhc28490c2006-10-26 14:25:58 +0000349** Threat stdin as an interactive input if the following variable
350** is true. Otherwise, assume stdin is connected to a file or pipe.
351*/
352static int stdin_is_interactive = 1;
353
354/*
drhe05461c2015-12-30 13:36:57 +0000355** On Windows systems we have to know if standard output is a console
356** in order to translate UTF-8 into MBCS. The following variable is
357** true if translation is required.
358*/
359static int stdout_is_console = 1;
360
361/*
drh4c504392000-10-16 22:06:40 +0000362** The following is the open SQLite database. We make a pointer
363** to this database a static variable so that it can be accessed
364** by the SIGINT handler to interrupt database processing.
365*/
mistachkin8e189222015-04-19 21:43:16 +0000366static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000367
368/*
drh67505e72002-04-19 12:34:06 +0000369** True if an interrupt (Control-C) has been received.
370*/
drh43617e92006-03-06 20:55:46 +0000371static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000372
373/*
persicom7e2dfdd2002-04-18 02:46:52 +0000374** This is the name of our program. It is set in main(), used
375** in a number of other places, mostly for error messages.
376*/
377static char *Argv0;
378
379/*
380** Prompt strings. Initialized in main. Settable with
381** .prompt main continue
382*/
383static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
384static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
385
drhb0603412007-02-28 04:47:26 +0000386/*
mistachkin710b33b2016-01-03 18:59:28 +0000387** Render output like fprintf(). Except, if the output is going to the
388** console and if this is running on a Windows machine, translate the
389** output from UTF-8 into MBCS.
390*/
391#if defined(_WIN32) || defined(WIN32)
392void utf8_printf(FILE *out, const char *zFormat, ...){
393 va_list ap;
394 va_start(ap, zFormat);
395 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000396 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000397 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000398 sqlite3_free(z1);
399 fputs(z2, out);
400 sqlite3_free(z2);
401 }else{
402 vfprintf(out, zFormat, ap);
403 }
404 va_end(ap);
405}
406#elif !defined(utf8_printf)
407# define utf8_printf fprintf
408#endif
409
410/*
411** Render output like fprintf(). This should not be used on anything that
412** includes string formatting (e.g. "%s").
413*/
414#if !defined(raw_printf)
415# define raw_printf fprintf
416#endif
417
418/*
drhb0603412007-02-28 04:47:26 +0000419** Write I/O traces to the following stream.
420*/
rsebe0a9092007-07-30 18:24:38 +0000421#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000422static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000423#endif
drhb0603412007-02-28 04:47:26 +0000424
425/*
426** This routine works like printf in that its first argument is a
427** format string and subsequent arguments are values to be substituted
428** in place of % fields. The result of formatting this string
429** is written to iotrace.
430*/
rsebe0a9092007-07-30 18:24:38 +0000431#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000432static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000433 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000434 char *z;
drhb0603412007-02-28 04:47:26 +0000435 if( iotrace==0 ) return;
436 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000437 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000438 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000439 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000440 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000441}
rsebe0a9092007-07-30 18:24:38 +0000442#endif
drhb0603412007-02-28 04:47:26 +0000443
drh6887e8f2017-04-17 13:18:42 +0000444/*
445** Output string zUtf to stream pOut as w characters. If w is negative,
446** then right-justify the text. W is the width in UTF-8 characters, not
447** in bytes. This is different from the %*.*s specification in printf
448** since with %*.*s the width is measured in bytes, not characters.
449*/
450static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
451 int i;
452 int n;
453 int aw = w<0 ? -w : w;
454 char zBuf[1000];
drhf8a2e8c2017-05-06 17:12:52 +0000455 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
drh6887e8f2017-04-17 13:18:42 +0000456 for(i=n=0; zUtf[i]; i++){
457 if( (zUtf[i]&0xc0)!=0x80 ){
458 n++;
459 if( n==aw ){
460 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
461 break;
462 }
463 }
464 }
465 if( n>=aw ){
466 utf8_printf(pOut, "%.*s", i, zUtf);
467 }else if( w<0 ){
468 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
469 }else{
470 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
471 }
472}
473
drh44c2eb12003-04-30 11:38:26 +0000474
persicom7e2dfdd2002-04-18 02:46:52 +0000475/*
drh83965662003-04-17 02:54:13 +0000476** Determines if a string is a number of not.
477*/
danielk19772e588c72005-12-09 14:25:08 +0000478static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000479 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000480 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000481 return 0;
482 }
483 z++;
484 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000485 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000486 if( *z=='.' ){
487 z++;
drhf0693c82011-10-11 20:41:54 +0000488 if( !IsDigit(*z) ) return 0;
489 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000490 if( realnum ) *realnum = 1;
491 }
492 if( *z=='e' || *z=='E' ){
493 z++;
494 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000495 if( !IsDigit(*z) ) return 0;
496 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000497 if( realnum ) *realnum = 1;
498 }
499 return *z==0;
500}
drh83965662003-04-17 02:54:13 +0000501
502/*
drhe05461c2015-12-30 13:36:57 +0000503** Compute a string length that is limited to what can be stored in
504** lower 30 bits of a 32-bit signed integer.
505*/
506static int strlen30(const char *z){
507 const char *z2 = z;
508 while( *z2 ){ z2++; }
509 return 0x3fffffff & (int)(z2 - z);
510}
511
512/*
drh64bf76d2017-06-05 12:29:26 +0000513** Return the length of a string in characters. Multibyte UTF8 characters
514** count as a single character.
515*/
516static int strlenChar(const char *z){
517 int n = 0;
518 while( *z ){
519 if( (0xc0&*(z++))!=0x80 ) n++;
520 }
521 return n;
522}
523
524/*
drhfeac5f82004-08-01 00:10:45 +0000525** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000526** the text in memory obtained from malloc() and returns a pointer
527** to the text. NULL is returned at end of file, or if malloc()
528** fails.
529**
drh9f099fd2013-08-06 14:01:46 +0000530** If zLine is not NULL then it is a malloced buffer returned from
531** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000532*/
drh9f099fd2013-08-06 14:01:46 +0000533static char *local_getline(char *zLine, FILE *in){
534 int nLine = zLine==0 ? 0 : 100;
535 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000536
drhb07028f2011-10-14 21:49:18 +0000537 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000538 if( n+100>nLine ){
539 nLine = nLine*2 + 100;
540 zLine = realloc(zLine, nLine);
541 if( zLine==0 ) return 0;
542 }
drhdaffd0e2001-04-11 14:28:42 +0000543 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000544 if( n==0 ){
545 free(zLine);
546 return 0;
547 }
548 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000549 break;
550 }
drh9f099fd2013-08-06 14:01:46 +0000551 while( zLine[n] ) n++;
552 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000553 n--;
shaneh13b36022009-12-17 21:07:15 +0000554 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000555 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000556 break;
drh8e7e7a22000-05-30 18:45:23 +0000557 }
558 }
drhe05461c2015-12-30 13:36:57 +0000559#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000560 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000561 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000562 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000563 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000564 if( zTrans ){
565 int nTrans = strlen30(zTrans)+1;
566 if( nTrans>nLine ){
567 zLine = realloc(zLine, nTrans);
568 if( zLine==0 ){
569 sqlite3_free(zTrans);
570 return 0;
571 }
572 }
573 memcpy(zLine, zTrans, nTrans);
574 sqlite3_free(zTrans);
575 }
576 }
577#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000578 return zLine;
579}
580
581/*
drhc28490c2006-10-26 14:25:58 +0000582** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000583**
drh9f099fd2013-08-06 14:01:46 +0000584** If in==0 then read from standard input and prompt before each line.
585** If isContinuation is true, then a continuation prompt is appropriate.
586** If isContinuation is zero, then the main prompt should be used.
587**
588** If zPrior is not NULL then it is a buffer from a prior call to this
589** routine that can be reused.
590**
591** The result is stored in space obtained from malloc() and must either
592** be freed by the caller or else passed back into this routine via the
593** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000594*/
drh9f099fd2013-08-06 14:01:46 +0000595static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000596 char *zPrompt;
597 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000598 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000599 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000600 }else{
drh9f099fd2013-08-06 14:01:46 +0000601 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000602#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000603 printf("%s", zPrompt);
604 fflush(stdout);
605 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000606#else
607 free(zPrior);
608 zResult = shell_readline(zPrompt);
609 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000610#endif
drh9f099fd2013-08-06 14:01:46 +0000611 }
drh8e7e7a22000-05-30 18:45:23 +0000612 return zResult;
613}
drhf42d3182017-03-08 12:25:18 +0000614/*
615** A variable length string to which one can append text.
616*/
617typedef struct ShellText ShellText;
618struct ShellText {
619 char *z;
620 int n;
621 int nAlloc;
622};
623
624/*
625** Initialize and destroy a ShellText object
626*/
627static void initText(ShellText *p){
628 memset(p, 0, sizeof(*p));
629}
630static void freeText(ShellText *p){
631 free(p->z);
632 initText(p);
633}
634
635/* zIn is either a pointer to a NULL-terminated string in memory obtained
636** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637** added to zIn, and the result returned in memory obtained from malloc().
638** zIn, if it was not NULL, is freed.
639**
640** If the third argument, quote, is not '\0', then it is used as a
641** quote character for zAppend.
642*/
643static void appendText(ShellText *p, char const *zAppend, char quote){
644 int len;
645 int i;
646 int nAppend = strlen30(zAppend);
647
648 len = nAppend+p->n+1;
649 if( quote ){
650 len += 2;
651 for(i=0; i<nAppend; i++){
652 if( zAppend[i]==quote ) len++;
653 }
654 }
655
656 if( p->n+len>=p->nAlloc ){
657 p->nAlloc = p->nAlloc*2 + len + 20;
658 p->z = realloc(p->z, p->nAlloc);
659 if( p->z==0 ){
660 memset(p, 0, sizeof(*p));
661 return;
662 }
663 }
664
665 if( quote ){
666 char *zCsr = p->z+p->n;
667 *zCsr++ = quote;
668 for(i=0; i<nAppend; i++){
669 *zCsr++ = zAppend[i];
670 if( zAppend[i]==quote ) *zCsr++ = quote;
671 }
672 *zCsr++ = quote;
673 p->n = (int)(zCsr - p->z);
674 *zCsr = '\0';
675 }else{
676 memcpy(p->z+p->n, zAppend, nAppend);
677 p->n += nAppend;
678 p->z[p->n] = '\0';
679 }
680}
681
682/*
683** Attempt to determine if identifier zName needs to be quoted, either
684** because it contains non-alphanumeric characters, or because it is an
685** SQLite keyword. Be conservative in this estimate: When in doubt assume
686** that quoting is required.
687**
688** Return '"' if quoting is required. Return 0 if no quoting is required.
689*/
690static char quoteChar(const char *zName){
691 /* All SQLite keywords, in alphabetical order */
692 static const char *azKeywords[] = {
693 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
710 "WITH", "WITHOUT",
711 };
712 int i, lwr, upr, mid, c;
713 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
714 for(i=0; zName[i]; i++){
715 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
716 }
717 lwr = 0;
718 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
719 while( lwr<=upr ){
720 mid = (lwr+upr)/2;
721 c = sqlite3_stricmp(azKeywords[mid], zName);
722 if( c==0 ) return '"';
723 if( c<0 ){
724 lwr = mid+1;
725 }else{
726 upr = mid-1;
727 }
728 }
729 return 0;
730}
drh8e7e7a22000-05-30 18:45:23 +0000731
drh09425592017-06-15 16:56:05 +0000732/*
733** SQL function: shell_add_schema(S,X)
734**
735** Add the schema name X to the CREATE statement in S and return the result.
736** Examples:
737**
738** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
739**
740** Also works on
741**
742** CREATE INDEX
743** CREATE UNIQUE INDEX
744** CREATE VIEW
745** CREATE TRIGGER
746** CREATE VIRTUAL TABLE
747**
748** This UDF is used by the .schema command to insert the schema name of
749** attached databases into the middle of the sqlite_master.sql field.
750*/
751static void shellAddSchemaName(
752 sqlite3_context *pCtx,
753 int nVal,
754 sqlite3_value **apVal
755){
756 static const char *aPrefix[] = {
757 "TABLE",
758 "INDEX",
759 "UNIQUE INDEX",
760 "VIEW",
761 "TRIGGER",
762 "VIRTUAL TABLE"
763 };
764 int i = 0;
765 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
766 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
767 assert( nVal==2 );
768 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
769 for(i=0; i<sizeof(aPrefix)/sizeof(aPrefix[0]); i++){
770 int n = strlen30(aPrefix[i]);
771 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
772 char cQuote = quoteChar(zSchema);
773 char *z;
774 if( cQuote ){
775 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
776 }else{
777 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
778 }
779 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
780 return;
781 }
782 }
783 }
784 sqlite3_result_value(pCtx, apVal[0]);
785}
786
drh1554bc82017-03-08 16:10:34 +0000787/******************************************************************************
788** SHA3 hash implementation copied from ../ext/misc/shathree.c
789*/
790typedef sqlite3_uint64 u64;
791/*
792** Macros to determine whether the machine is big or little endian,
793** and whether or not that determination is run-time or compile-time.
794**
795** For best performance, an attempt is made to guess at the byte-order
796** using C-preprocessor macros. If that is unsuccessful, or if
797** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
798** at run-time.
799*/
800#ifndef SHA3_BYTEORDER
801# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
802 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
803 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
804 defined(__arm__)
805# define SHA3_BYTEORDER 1234
806# elif defined(sparc) || defined(__ppc__)
807# define SHA3_BYTEORDER 4321
808# else
809# define SHA3_BYTEORDER 0
810# endif
811#endif
812
813
814/*
815** State structure for a SHA3 hash in progress
816*/
817typedef struct SHA3Context SHA3Context;
818struct SHA3Context {
819 union {
820 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
821 unsigned char x[1600]; /* ... or 1600 bytes */
822 } u;
823 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
824 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
825 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
826};
827
drh050b1242017-05-04 11:13:50 +0000828/* Allow the following routine to use the B0 variable, which is also
829** a macro in the termios.h header file */
830#undef B0
831
drh1554bc82017-03-08 16:10:34 +0000832/*
833** A single step of the Keccak mixing function for a 1600-bit state
834*/
835static void KeccakF1600Step(SHA3Context *p){
836 int i;
837 u64 B0, B1, B2, B3, B4;
838 u64 C0, C1, C2, C3, C4;
839 u64 D0, D1, D2, D3, D4;
840 static const u64 RC[] = {
841 0x0000000000000001ULL, 0x0000000000008082ULL,
842 0x800000000000808aULL, 0x8000000080008000ULL,
843 0x000000000000808bULL, 0x0000000080000001ULL,
844 0x8000000080008081ULL, 0x8000000000008009ULL,
845 0x000000000000008aULL, 0x0000000000000088ULL,
846 0x0000000080008009ULL, 0x000000008000000aULL,
847 0x000000008000808bULL, 0x800000000000008bULL,
848 0x8000000000008089ULL, 0x8000000000008003ULL,
849 0x8000000000008002ULL, 0x8000000000000080ULL,
850 0x000000000000800aULL, 0x800000008000000aULL,
851 0x8000000080008081ULL, 0x8000000000008080ULL,
852 0x0000000080000001ULL, 0x8000000080008008ULL
853 };
854# define A00 (p->u.s[0])
855# define A01 (p->u.s[1])
856# define A02 (p->u.s[2])
857# define A03 (p->u.s[3])
858# define A04 (p->u.s[4])
859# define A10 (p->u.s[5])
860# define A11 (p->u.s[6])
861# define A12 (p->u.s[7])
862# define A13 (p->u.s[8])
863# define A14 (p->u.s[9])
864# define A20 (p->u.s[10])
865# define A21 (p->u.s[11])
866# define A22 (p->u.s[12])
867# define A23 (p->u.s[13])
868# define A24 (p->u.s[14])
869# define A30 (p->u.s[15])
870# define A31 (p->u.s[16])
871# define A32 (p->u.s[17])
872# define A33 (p->u.s[18])
873# define A34 (p->u.s[19])
874# define A40 (p->u.s[20])
875# define A41 (p->u.s[21])
876# define A42 (p->u.s[22])
877# define A43 (p->u.s[23])
878# define A44 (p->u.s[24])
879# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
880
881 for(i=0; i<24; i+=4){
882 C0 = A00^A10^A20^A30^A40;
883 C1 = A01^A11^A21^A31^A41;
884 C2 = A02^A12^A22^A32^A42;
885 C3 = A03^A13^A23^A33^A43;
886 C4 = A04^A14^A24^A34^A44;
887 D0 = C4^ROL64(C1, 1);
888 D1 = C0^ROL64(C2, 1);
889 D2 = C1^ROL64(C3, 1);
890 D3 = C2^ROL64(C4, 1);
891 D4 = C3^ROL64(C0, 1);
892
893 B0 = (A00^D0);
894 B1 = ROL64((A11^D1), 44);
895 B2 = ROL64((A22^D2), 43);
896 B3 = ROL64((A33^D3), 21);
897 B4 = ROL64((A44^D4), 14);
898 A00 = B0 ^((~B1)& B2 );
899 A00 ^= RC[i];
900 A11 = B1 ^((~B2)& B3 );
901 A22 = B2 ^((~B3)& B4 );
902 A33 = B3 ^((~B4)& B0 );
903 A44 = B4 ^((~B0)& B1 );
904
905 B2 = ROL64((A20^D0), 3);
906 B3 = ROL64((A31^D1), 45);
907 B4 = ROL64((A42^D2), 61);
908 B0 = ROL64((A03^D3), 28);
909 B1 = ROL64((A14^D4), 20);
910 A20 = B0 ^((~B1)& B2 );
911 A31 = B1 ^((~B2)& B3 );
912 A42 = B2 ^((~B3)& B4 );
913 A03 = B3 ^((~B4)& B0 );
914 A14 = B4 ^((~B0)& B1 );
915
916 B4 = ROL64((A40^D0), 18);
917 B0 = ROL64((A01^D1), 1);
918 B1 = ROL64((A12^D2), 6);
919 B2 = ROL64((A23^D3), 25);
920 B3 = ROL64((A34^D4), 8);
921 A40 = B0 ^((~B1)& B2 );
922 A01 = B1 ^((~B2)& B3 );
923 A12 = B2 ^((~B3)& B4 );
924 A23 = B3 ^((~B4)& B0 );
925 A34 = B4 ^((~B0)& B1 );
926
927 B1 = ROL64((A10^D0), 36);
928 B2 = ROL64((A21^D1), 10);
929 B3 = ROL64((A32^D2), 15);
930 B4 = ROL64((A43^D3), 56);
931 B0 = ROL64((A04^D4), 27);
932 A10 = B0 ^((~B1)& B2 );
933 A21 = B1 ^((~B2)& B3 );
934 A32 = B2 ^((~B3)& B4 );
935 A43 = B3 ^((~B4)& B0 );
936 A04 = B4 ^((~B0)& B1 );
937
938 B3 = ROL64((A30^D0), 41);
939 B4 = ROL64((A41^D1), 2);
940 B0 = ROL64((A02^D2), 62);
941 B1 = ROL64((A13^D3), 55);
942 B2 = ROL64((A24^D4), 39);
943 A30 = B0 ^((~B1)& B2 );
944 A41 = B1 ^((~B2)& B3 );
945 A02 = B2 ^((~B3)& B4 );
946 A13 = B3 ^((~B4)& B0 );
947 A24 = B4 ^((~B0)& B1 );
948
949 C0 = A00^A20^A40^A10^A30;
950 C1 = A11^A31^A01^A21^A41;
951 C2 = A22^A42^A12^A32^A02;
952 C3 = A33^A03^A23^A43^A13;
953 C4 = A44^A14^A34^A04^A24;
954 D0 = C4^ROL64(C1, 1);
955 D1 = C0^ROL64(C2, 1);
956 D2 = C1^ROL64(C3, 1);
957 D3 = C2^ROL64(C4, 1);
958 D4 = C3^ROL64(C0, 1);
959
960 B0 = (A00^D0);
961 B1 = ROL64((A31^D1), 44);
962 B2 = ROL64((A12^D2), 43);
963 B3 = ROL64((A43^D3), 21);
964 B4 = ROL64((A24^D4), 14);
965 A00 = B0 ^((~B1)& B2 );
966 A00 ^= RC[i+1];
967 A31 = B1 ^((~B2)& B3 );
968 A12 = B2 ^((~B3)& B4 );
969 A43 = B3 ^((~B4)& B0 );
970 A24 = B4 ^((~B0)& B1 );
971
972 B2 = ROL64((A40^D0), 3);
973 B3 = ROL64((A21^D1), 45);
974 B4 = ROL64((A02^D2), 61);
975 B0 = ROL64((A33^D3), 28);
976 B1 = ROL64((A14^D4), 20);
977 A40 = B0 ^((~B1)& B2 );
978 A21 = B1 ^((~B2)& B3 );
979 A02 = B2 ^((~B3)& B4 );
980 A33 = B3 ^((~B4)& B0 );
981 A14 = B4 ^((~B0)& B1 );
982
983 B4 = ROL64((A30^D0), 18);
984 B0 = ROL64((A11^D1), 1);
985 B1 = ROL64((A42^D2), 6);
986 B2 = ROL64((A23^D3), 25);
987 B3 = ROL64((A04^D4), 8);
988 A30 = B0 ^((~B1)& B2 );
989 A11 = B1 ^((~B2)& B3 );
990 A42 = B2 ^((~B3)& B4 );
991 A23 = B3 ^((~B4)& B0 );
992 A04 = B4 ^((~B0)& B1 );
993
994 B1 = ROL64((A20^D0), 36);
995 B2 = ROL64((A01^D1), 10);
996 B3 = ROL64((A32^D2), 15);
997 B4 = ROL64((A13^D3), 56);
998 B0 = ROL64((A44^D4), 27);
999 A20 = B0 ^((~B1)& B2 );
1000 A01 = B1 ^((~B2)& B3 );
1001 A32 = B2 ^((~B3)& B4 );
1002 A13 = B3 ^((~B4)& B0 );
1003 A44 = B4 ^((~B0)& B1 );
1004
1005 B3 = ROL64((A10^D0), 41);
1006 B4 = ROL64((A41^D1), 2);
1007 B0 = ROL64((A22^D2), 62);
1008 B1 = ROL64((A03^D3), 55);
1009 B2 = ROL64((A34^D4), 39);
1010 A10 = B0 ^((~B1)& B2 );
1011 A41 = B1 ^((~B2)& B3 );
1012 A22 = B2 ^((~B3)& B4 );
1013 A03 = B3 ^((~B4)& B0 );
1014 A34 = B4 ^((~B0)& B1 );
1015
1016 C0 = A00^A40^A30^A20^A10;
1017 C1 = A31^A21^A11^A01^A41;
1018 C2 = A12^A02^A42^A32^A22;
1019 C3 = A43^A33^A23^A13^A03;
1020 C4 = A24^A14^A04^A44^A34;
1021 D0 = C4^ROL64(C1, 1);
1022 D1 = C0^ROL64(C2, 1);
1023 D2 = C1^ROL64(C3, 1);
1024 D3 = C2^ROL64(C4, 1);
1025 D4 = C3^ROL64(C0, 1);
1026
1027 B0 = (A00^D0);
1028 B1 = ROL64((A21^D1), 44);
1029 B2 = ROL64((A42^D2), 43);
1030 B3 = ROL64((A13^D3), 21);
1031 B4 = ROL64((A34^D4), 14);
1032 A00 = B0 ^((~B1)& B2 );
1033 A00 ^= RC[i+2];
1034 A21 = B1 ^((~B2)& B3 );
1035 A42 = B2 ^((~B3)& B4 );
1036 A13 = B3 ^((~B4)& B0 );
1037 A34 = B4 ^((~B0)& B1 );
1038
1039 B2 = ROL64((A30^D0), 3);
1040 B3 = ROL64((A01^D1), 45);
1041 B4 = ROL64((A22^D2), 61);
1042 B0 = ROL64((A43^D3), 28);
1043 B1 = ROL64((A14^D4), 20);
1044 A30 = B0 ^((~B1)& B2 );
1045 A01 = B1 ^((~B2)& B3 );
1046 A22 = B2 ^((~B3)& B4 );
1047 A43 = B3 ^((~B4)& B0 );
1048 A14 = B4 ^((~B0)& B1 );
1049
1050 B4 = ROL64((A10^D0), 18);
1051 B0 = ROL64((A31^D1), 1);
1052 B1 = ROL64((A02^D2), 6);
1053 B2 = ROL64((A23^D3), 25);
1054 B3 = ROL64((A44^D4), 8);
1055 A10 = B0 ^((~B1)& B2 );
1056 A31 = B1 ^((~B2)& B3 );
1057 A02 = B2 ^((~B3)& B4 );
1058 A23 = B3 ^((~B4)& B0 );
1059 A44 = B4 ^((~B0)& B1 );
1060
1061 B1 = ROL64((A40^D0), 36);
1062 B2 = ROL64((A11^D1), 10);
1063 B3 = ROL64((A32^D2), 15);
1064 B4 = ROL64((A03^D3), 56);
1065 B0 = ROL64((A24^D4), 27);
1066 A40 = B0 ^((~B1)& B2 );
1067 A11 = B1 ^((~B2)& B3 );
1068 A32 = B2 ^((~B3)& B4 );
1069 A03 = B3 ^((~B4)& B0 );
1070 A24 = B4 ^((~B0)& B1 );
1071
1072 B3 = ROL64((A20^D0), 41);
1073 B4 = ROL64((A41^D1), 2);
1074 B0 = ROL64((A12^D2), 62);
1075 B1 = ROL64((A33^D3), 55);
1076 B2 = ROL64((A04^D4), 39);
1077 A20 = B0 ^((~B1)& B2 );
1078 A41 = B1 ^((~B2)& B3 );
1079 A12 = B2 ^((~B3)& B4 );
1080 A33 = B3 ^((~B4)& B0 );
1081 A04 = B4 ^((~B0)& B1 );
1082
1083 C0 = A00^A30^A10^A40^A20;
1084 C1 = A21^A01^A31^A11^A41;
1085 C2 = A42^A22^A02^A32^A12;
1086 C3 = A13^A43^A23^A03^A33;
1087 C4 = A34^A14^A44^A24^A04;
1088 D0 = C4^ROL64(C1, 1);
1089 D1 = C0^ROL64(C2, 1);
1090 D2 = C1^ROL64(C3, 1);
1091 D3 = C2^ROL64(C4, 1);
1092 D4 = C3^ROL64(C0, 1);
1093
1094 B0 = (A00^D0);
1095 B1 = ROL64((A01^D1), 44);
1096 B2 = ROL64((A02^D2), 43);
1097 B3 = ROL64((A03^D3), 21);
1098 B4 = ROL64((A04^D4), 14);
1099 A00 = B0 ^((~B1)& B2 );
1100 A00 ^= RC[i+3];
1101 A01 = B1 ^((~B2)& B3 );
1102 A02 = B2 ^((~B3)& B4 );
1103 A03 = B3 ^((~B4)& B0 );
1104 A04 = B4 ^((~B0)& B1 );
1105
1106 B2 = ROL64((A10^D0), 3);
1107 B3 = ROL64((A11^D1), 45);
1108 B4 = ROL64((A12^D2), 61);
1109 B0 = ROL64((A13^D3), 28);
1110 B1 = ROL64((A14^D4), 20);
1111 A10 = B0 ^((~B1)& B2 );
1112 A11 = B1 ^((~B2)& B3 );
1113 A12 = B2 ^((~B3)& B4 );
1114 A13 = B3 ^((~B4)& B0 );
1115 A14 = B4 ^((~B0)& B1 );
1116
1117 B4 = ROL64((A20^D0), 18);
1118 B0 = ROL64((A21^D1), 1);
1119 B1 = ROL64((A22^D2), 6);
1120 B2 = ROL64((A23^D3), 25);
1121 B3 = ROL64((A24^D4), 8);
1122 A20 = B0 ^((~B1)& B2 );
1123 A21 = B1 ^((~B2)& B3 );
1124 A22 = B2 ^((~B3)& B4 );
1125 A23 = B3 ^((~B4)& B0 );
1126 A24 = B4 ^((~B0)& B1 );
1127
1128 B1 = ROL64((A30^D0), 36);
1129 B2 = ROL64((A31^D1), 10);
1130 B3 = ROL64((A32^D2), 15);
1131 B4 = ROL64((A33^D3), 56);
1132 B0 = ROL64((A34^D4), 27);
1133 A30 = B0 ^((~B1)& B2 );
1134 A31 = B1 ^((~B2)& B3 );
1135 A32 = B2 ^((~B3)& B4 );
1136 A33 = B3 ^((~B4)& B0 );
1137 A34 = B4 ^((~B0)& B1 );
1138
1139 B3 = ROL64((A40^D0), 41);
1140 B4 = ROL64((A41^D1), 2);
1141 B0 = ROL64((A42^D2), 62);
1142 B1 = ROL64((A43^D3), 55);
1143 B2 = ROL64((A44^D4), 39);
1144 A40 = B0 ^((~B1)& B2 );
1145 A41 = B1 ^((~B2)& B3 );
1146 A42 = B2 ^((~B3)& B4 );
1147 A43 = B3 ^((~B4)& B0 );
1148 A44 = B4 ^((~B0)& B1 );
1149 }
1150}
1151
1152/*
1153** Initialize a new hash. iSize determines the size of the hash
1154** in bits and should be one of 224, 256, 384, or 512. Or iSize
1155** can be zero to use the default hash size of 256 bits.
1156*/
1157static void SHA3Init(SHA3Context *p, int iSize){
1158 memset(p, 0, sizeof(*p));
1159 if( iSize>=128 && iSize<=512 ){
1160 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1161 }else{
1162 p->nRate = (1600 - 2*256)/8;
1163 }
1164#if SHA3_BYTEORDER==1234
1165 /* Known to be little-endian at compile-time. No-op */
1166#elif SHA3_BYTEORDER==4321
1167 p->ixMask = 7; /* Big-endian */
1168#else
1169 {
1170 static unsigned int one = 1;
1171 if( 1==*(unsigned char*)&one ){
1172 /* Little endian. No byte swapping. */
1173 p->ixMask = 0;
1174 }else{
1175 /* Big endian. Byte swap. */
1176 p->ixMask = 7;
1177 }
1178 }
1179#endif
1180}
1181
1182/*
1183** Make consecutive calls to the SHA3Update function to add new content
1184** to the hash
1185*/
1186static void SHA3Update(
1187 SHA3Context *p,
1188 const unsigned char *aData,
1189 unsigned int nData
1190){
1191 unsigned int i = 0;
1192#if SHA3_BYTEORDER==1234
1193 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1194 for(; i+7<nData; i+=8){
1195 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1196 p->nLoaded += 8;
1197 if( p->nLoaded>=p->nRate ){
1198 KeccakF1600Step(p);
1199 p->nLoaded = 0;
1200 }
1201 }
1202 }
1203#endif
1204 for(; i<nData; i++){
1205#if SHA3_BYTEORDER==1234
1206 p->u.x[p->nLoaded] ^= aData[i];
1207#elif SHA3_BYTEORDER==4321
1208 p->u.x[p->nLoaded^0x07] ^= aData[i];
1209#else
1210 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1211#endif
1212 p->nLoaded++;
1213 if( p->nLoaded==p->nRate ){
1214 KeccakF1600Step(p);
1215 p->nLoaded = 0;
1216 }
1217 }
1218}
1219
1220/*
1221** After all content has been added, invoke SHA3Final() to compute
1222** the final hash. The function returns a pointer to the binary
1223** hash value.
1224*/
1225static unsigned char *SHA3Final(SHA3Context *p){
1226 unsigned int i;
1227 if( p->nLoaded==p->nRate-1 ){
1228 const unsigned char c1 = 0x86;
1229 SHA3Update(p, &c1, 1);
1230 }else{
1231 const unsigned char c2 = 0x06;
1232 const unsigned char c3 = 0x80;
1233 SHA3Update(p, &c2, 1);
1234 p->nLoaded = p->nRate - 1;
1235 SHA3Update(p, &c3, 1);
1236 }
1237 for(i=0; i<p->nRate; i++){
1238 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1239 }
1240 return &p->u.x[p->nRate];
1241}
1242
1243/*
1244** Implementation of the sha3(X,SIZE) function.
1245**
1246** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
mistachkine16a3502017-05-29 03:48:13 +00001247** size is 256. If X is a BLOB, it is hashed as is.
drh1554bc82017-03-08 16:10:34 +00001248** For all other non-NULL types of input, X is converted into a UTF-8 string
1249** and the string is hashed without the trailing 0x00 terminator. The hash
1250** of a NULL value is NULL.
1251*/
1252static void sha3Func(
1253 sqlite3_context *context,
1254 int argc,
1255 sqlite3_value **argv
1256){
1257 SHA3Context cx;
1258 int eType = sqlite3_value_type(argv[0]);
1259 int nByte = sqlite3_value_bytes(argv[0]);
1260 int iSize;
1261 if( argc==1 ){
1262 iSize = 256;
1263 }else{
1264 iSize = sqlite3_value_int(argv[1]);
1265 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1266 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1267 "384 512", -1);
1268 return;
1269 }
1270 }
1271 if( eType==SQLITE_NULL ) return;
1272 SHA3Init(&cx, iSize);
1273 if( eType==SQLITE_BLOB ){
1274 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1275 }else{
1276 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1277 }
1278 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1279}
1280
1281/* Compute a string using sqlite3_vsnprintf() with a maximum length
1282** of 50 bytes and add it to the hash.
1283*/
1284static void hash_step_vformat(
1285 SHA3Context *p, /* Add content to this context */
1286 const char *zFormat,
1287 ...
1288){
1289 va_list ap;
1290 int n;
1291 char zBuf[50];
1292 va_start(ap, zFormat);
1293 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1294 va_end(ap);
1295 n = (int)strlen(zBuf);
1296 SHA3Update(p, (unsigned char*)zBuf, n);
1297}
1298
1299/*
1300** Implementation of the sha3_query(SQL,SIZE) function.
1301**
1302** This function compiles and runs the SQL statement(s) given in the
1303** argument. The results are hashed using a SIZE-bit SHA3. The default
1304** size is 256.
1305**
1306** The format of the byte stream that is hashed is summarized as follows:
1307**
1308** S<n>:<sql>
1309** R
1310** N
1311** I<int>
1312** F<ieee-float>
1313** B<size>:<bytes>
1314** T<size>:<text>
1315**
1316** <sql> is the original SQL text for each statement run and <n> is
1317** the size of that text. The SQL text is UTF-8. A single R character
1318** occurs before the start of each row. N means a NULL value.
1319** I mean an 8-byte little-endian integer <int>. F is a floating point
1320** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1321** B means blobs of <size> bytes. T means text rendered as <size>
1322** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1323** text integers.
1324**
1325** For each SQL statement in the X input, there is one S segment. Each
1326** S segment is followed by zero or more R segments, one for each row in the
1327** result set. After each R, there are one or more N, I, F, B, or T segments,
1328** one for each column in the result set. Segments are concatentated directly
1329** with no delimiters of any kind.
1330*/
1331static void sha3QueryFunc(
1332 sqlite3_context *context,
1333 int argc,
1334 sqlite3_value **argv
1335){
1336 sqlite3 *db = sqlite3_context_db_handle(context);
1337 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1338 sqlite3_stmt *pStmt = 0;
1339 int nCol; /* Number of columns in the result set */
1340 int i; /* Loop counter */
1341 int rc;
1342 int n;
1343 const char *z;
1344 SHA3Context cx;
1345 int iSize;
1346
1347 if( argc==1 ){
1348 iSize = 256;
1349 }else{
1350 iSize = sqlite3_value_int(argv[1]);
1351 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1352 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1353 "384 512", -1);
1354 return;
1355 }
1356 }
1357 if( zSql==0 ) return;
1358 SHA3Init(&cx, iSize);
1359 while( zSql[0] ){
1360 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1361 if( rc ){
1362 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1363 zSql, sqlite3_errmsg(db));
1364 sqlite3_finalize(pStmt);
1365 sqlite3_result_error(context, zMsg, -1);
1366 sqlite3_free(zMsg);
1367 return;
1368 }
1369 if( !sqlite3_stmt_readonly(pStmt) ){
1370 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1371 sqlite3_finalize(pStmt);
1372 sqlite3_result_error(context, zMsg, -1);
1373 sqlite3_free(zMsg);
1374 return;
1375 }
1376 nCol = sqlite3_column_count(pStmt);
1377 z = sqlite3_sql(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00001378 if( z==0 ){
1379 sqlite3_finalize(pStmt);
1380 continue;
1381 }
drh1554bc82017-03-08 16:10:34 +00001382 n = (int)strlen(z);
1383 hash_step_vformat(&cx,"S%d:",n);
1384 SHA3Update(&cx,(unsigned char*)z,n);
1385
1386 /* Compute a hash over the result of the query */
1387 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1388 SHA3Update(&cx,(const unsigned char*)"R",1);
1389 for(i=0; i<nCol; i++){
1390 switch( sqlite3_column_type(pStmt,i) ){
1391 case SQLITE_NULL: {
1392 SHA3Update(&cx, (const unsigned char*)"N",1);
1393 break;
1394 }
1395 case SQLITE_INTEGER: {
1396 sqlite3_uint64 u;
1397 int j;
1398 unsigned char x[9];
1399 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1400 memcpy(&u, &v, 8);
1401 for(j=8; j>=1; j--){
1402 x[j] = u & 0xff;
1403 u >>= 8;
1404 }
1405 x[0] = 'I';
1406 SHA3Update(&cx, x, 9);
1407 break;
1408 }
1409 case SQLITE_FLOAT: {
1410 sqlite3_uint64 u;
1411 int j;
1412 unsigned char x[9];
1413 double r = sqlite3_column_double(pStmt,i);
1414 memcpy(&u, &r, 8);
1415 for(j=8; j>=1; j--){
1416 x[j] = u & 0xff;
1417 u >>= 8;
1418 }
1419 x[0] = 'F';
1420 SHA3Update(&cx,x,9);
1421 break;
1422 }
1423 case SQLITE_TEXT: {
1424 int n2 = sqlite3_column_bytes(pStmt, i);
1425 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1426 hash_step_vformat(&cx,"T%d:",n2);
1427 SHA3Update(&cx, z2, n2);
1428 break;
1429 }
1430 case SQLITE_BLOB: {
1431 int n2 = sqlite3_column_bytes(pStmt, i);
1432 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1433 hash_step_vformat(&cx,"B%d:",n2);
1434 SHA3Update(&cx, z2, n2);
1435 break;
1436 }
1437 }
1438 }
1439 }
1440 sqlite3_finalize(pStmt);
1441 }
1442 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1443}
1444/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1445********************************************************************************/
1446
drhe6229612014-08-18 15:08:26 +00001447#if defined(SQLITE_ENABLE_SESSION)
1448/*
1449** State information for a single open session
1450*/
1451typedef struct OpenSession OpenSession;
1452struct OpenSession {
1453 char *zName; /* Symbolic name for this session */
1454 int nFilter; /* Number of xFilter rejection GLOB patterns */
1455 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1456 sqlite3_session *p; /* The open session */
1457};
1458#endif
1459
drhdcd87a92014-08-18 13:45:42 +00001460/*
mistachkin1fe36bb2016-04-04 02:16:44 +00001461** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00001462** saved so that it can be restored by ".explain off"
1463*/
1464typedef struct SavedModeInfo SavedModeInfo;
1465struct SavedModeInfo {
1466 int valid; /* Is there legit data in here? */
1467 int mode; /* Mode prior to ".explain on" */
1468 int showHeader; /* The ".header" setting prior to ".explain on" */
1469 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00001470};
drh45e29d82006-11-20 16:21:10 +00001471
drh8e7e7a22000-05-30 18:45:23 +00001472/*
drhdcd87a92014-08-18 13:45:42 +00001473** State information about the database connection is contained in an
1474** instance of the following structure.
drh75897232000-05-29 14:26:00 +00001475*/
drhdcd87a92014-08-18 13:45:42 +00001476typedef struct ShellState ShellState;
1477struct ShellState {
shane626a6e42009-10-22 17:30:15 +00001478 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00001479 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00001480 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00001481 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00001482 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00001483 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00001484 int cnt; /* Number of records displayed so far */
1485 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00001486 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00001487 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00001488 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00001489 int cMode; /* temporary output mode for the current query */
1490 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00001491 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00001492 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00001493 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00001494 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00001495 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00001496 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00001497 char colSeparator[20]; /* Column separator character for several modes */
1498 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00001499 int colWidth[100]; /* Requested width of each column when in column mode*/
1500 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00001501 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00001502 ** the database */
drh44c2eb12003-04-30 11:38:26 +00001503 char outfile[FILENAME_MAX]; /* Filename for *out */
1504 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00001505 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00001506 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00001507 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00001508 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00001509 int *aiIndent; /* Array of indents used in MODE_Explain */
1510 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00001511 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00001512#if defined(SQLITE_ENABLE_SESSION)
1513 int nSession; /* Number of active sessions */
1514 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1515#endif
drh75897232000-05-29 14:26:00 +00001516};
1517
1518/*
drh44dec872014-08-30 15:49:25 +00001519** These are the allowed shellFlgs values
1520*/
drhe6e1d122017-03-09 13:50:49 +00001521#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1522#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1523#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1524#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1525#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1526#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1527#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1528
1529/*
1530** Macros for testing and setting shellFlgs
1531*/
1532#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1533#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1534#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00001535
1536/*
drh75897232000-05-29 14:26:00 +00001537** These are the allowed modes.
1538*/
drh967e8b72000-06-21 13:59:10 +00001539#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00001540#define MODE_Column 1 /* One record per line in neat columns */
1541#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00001542#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1543#define MODE_Html 4 /* Generate an XHTML table */
1544#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00001545#define MODE_Quote 6 /* Quote values as for SQL */
1546#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1547#define MODE_Csv 8 /* Quote strings, numbers are plain */
1548#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1549#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1550#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00001551
drh66ce4d02008-02-15 17:38:06 +00001552static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00001553 "line",
1554 "column",
1555 "list",
1556 "semi",
1557 "html",
drhfeac5f82004-08-01 00:10:45 +00001558 "insert",
drh41f5f6e2016-10-21 17:39:30 +00001559 "quote",
drhfeac5f82004-08-01 00:10:45 +00001560 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00001561 "csv",
drh66ce4d02008-02-15 17:38:06 +00001562 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00001563 "ascii",
drh4926fec2016-04-13 15:33:42 +00001564 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00001565};
drh75897232000-05-29 14:26:00 +00001566
1567/*
mistachkinfad42082014-07-24 22:13:12 +00001568** These are the column/row/line separators used by the various
1569** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00001570*/
mistachkinfad42082014-07-24 22:13:12 +00001571#define SEP_Column "|"
1572#define SEP_Row "\n"
1573#define SEP_Tab "\t"
1574#define SEP_Space " "
1575#define SEP_Comma ","
1576#define SEP_CrLf "\r\n"
1577#define SEP_Unit "\x1F"
1578#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00001579
1580/*
drh75897232000-05-29 14:26:00 +00001581** Number of elements in an array
1582*/
drh902b9ee2008-12-05 17:17:07 +00001583#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00001584
1585/*
drh127f9d72010-02-23 01:47:00 +00001586** A callback for the sqlite3_log() interface.
1587*/
1588static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00001589 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00001590 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00001591 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00001592 fflush(p->pLog);
1593}
1594
1595/*
shane626a6e42009-10-22 17:30:15 +00001596** Output the given string as a hex-encoded blob (eg. X'1234' )
1597*/
1598static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1599 int i;
1600 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00001601 raw_printf(out,"X'");
1602 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1603 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00001604}
1605
1606/*
drh6193d492017-04-07 11:45:58 +00001607** Find a string that is not found anywhere in z[]. Return a pointer
1608** to that string.
1609**
1610** Try to use zA and zB first. If both of those are already found in z[]
1611** then make up some string and store it in the buffer zBuf.
1612*/
1613static const char *unused_string(
1614 const char *z, /* Result must not appear anywhere in z */
1615 const char *zA, const char *zB, /* Try these first */
1616 char *zBuf /* Space to store a generated string */
1617){
1618 unsigned i = 0;
1619 if( strstr(z, zA)==0 ) return zA;
1620 if( strstr(z, zB)==0 ) return zB;
1621 do{
1622 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1623 }while( strstr(z,zBuf)!=0 );
1624 return zBuf;
1625}
1626
1627/*
drh28bd4bc2000-06-15 15:57:22 +00001628** Output the given string as a quoted string using SQL quoting conventions.
drh708b22b2017-03-11 01:56:41 +00001629**
drh13fe1382017-04-08 13:42:55 +00001630** See also: output_quoted_escaped_string()
drh28bd4bc2000-06-15 15:57:22 +00001631*/
1632static void output_quoted_string(FILE *out, const char *z){
1633 int i;
drh708b22b2017-03-11 01:56:41 +00001634 char c;
mistachkin1fe36bb2016-04-04 02:16:44 +00001635 setBinaryMode(out, 1);
drh13fe1382017-04-08 13:42:55 +00001636 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1637 if( c==0 ){
1638 utf8_printf(out,"'%s'",z);
1639 }else{
1640 raw_printf(out, "'");
1641 while( *z ){
1642 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1643 if( c=='\'' ) i++;
1644 if( i ){
1645 utf8_printf(out, "%.*s", i, z);
1646 z += i;
1647 }
1648 if( c=='\'' ){
1649 raw_printf(out, "'");
1650 continue;
1651 }
1652 if( c==0 ){
1653 break;
1654 }
1655 z++;
1656 }
1657 raw_printf(out, "'");
1658 }
1659 setTextMode(out, 1);
1660}
1661
1662/*
1663** Output the given string as a quoted string using SQL quoting conventions.
1664** Additionallly , escape the "\n" and "\r" characters so that they do not
1665** get corrupted by end-of-line translation facilities in some operating
1666** systems.
1667**
1668** This is like output_quoted_string() but with the addition of the \r\n
1669** escape mechanism.
1670*/
1671static void output_quoted_escaped_string(FILE *out, const char *z){
1672 int i;
1673 char c;
1674 setBinaryMode(out, 1);
drh708b22b2017-03-11 01:56:41 +00001675 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1676 if( c==0 ){
drhe05461c2015-12-30 13:36:57 +00001677 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00001678 }else{
drh6193d492017-04-07 11:45:58 +00001679 const char *zNL = 0;
1680 const char *zCR = 0;
1681 int nNL = 0;
1682 int nCR = 0;
1683 char zBuf1[20], zBuf2[20];
1684 for(i=0; z[i]; i++){
1685 if( z[i]=='\n' ) nNL++;
1686 if( z[i]=='\r' ) nCR++;
1687 }
1688 if( nNL ){
1689 raw_printf(out, "replace(");
1690 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1691 }
1692 if( nCR ){
1693 raw_printf(out, "replace(");
1694 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1695 }
1696 raw_printf(out, "'");
drh28bd4bc2000-06-15 15:57:22 +00001697 while( *z ){
drh708b22b2017-03-11 01:56:41 +00001698 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1699 if( c=='\'' ) i++;
1700 if( i ){
drh708b22b2017-03-11 01:56:41 +00001701 utf8_printf(out, "%.*s", i, z);
1702 z += i;
drh708b22b2017-03-11 01:56:41 +00001703 }
1704 if( c=='\'' ){
1705 raw_printf(out, "'");
1706 continue;
1707 }
drh708b22b2017-03-11 01:56:41 +00001708 if( c==0 ){
drh28bd4bc2000-06-15 15:57:22 +00001709 break;
1710 }
drh6193d492017-04-07 11:45:58 +00001711 z++;
1712 if( c=='\n' ){
1713 raw_printf(out, "%s", zNL);
1714 continue;
drh708b22b2017-03-11 01:56:41 +00001715 }
drh6193d492017-04-07 11:45:58 +00001716 raw_printf(out, "%s", zCR);
drh28bd4bc2000-06-15 15:57:22 +00001717 }
drh6193d492017-04-07 11:45:58 +00001718 raw_printf(out, "'");
1719 if( nCR ){
1720 raw_printf(out, ",'%s',char(13))", zCR);
1721 }
1722 if( nNL ){
1723 raw_printf(out, ",'%s',char(10))", zNL);
1724 }
drh28bd4bc2000-06-15 15:57:22 +00001725 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001726 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001727}
1728
1729/*
drhfeac5f82004-08-01 00:10:45 +00001730** Output the given string as a quoted according to C or TCL quoting rules.
1731*/
1732static void output_c_string(FILE *out, const char *z){
1733 unsigned int c;
1734 fputc('"', out);
1735 while( (c = *(z++))!=0 ){
1736 if( c=='\\' ){
1737 fputc(c, out);
1738 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00001739 }else if( c=='"' ){
1740 fputc('\\', out);
1741 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00001742 }else if( c=='\t' ){
1743 fputc('\\', out);
1744 fputc('t', out);
1745 }else if( c=='\n' ){
1746 fputc('\\', out);
1747 fputc('n', out);
1748 }else if( c=='\r' ){
1749 fputc('\\', out);
1750 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00001751 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00001752 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00001753 }else{
1754 fputc(c, out);
1755 }
1756 }
1757 fputc('"', out);
1758}
1759
1760/*
drhc08a4f12000-06-15 16:49:48 +00001761** Output the given string with characters that are special to
1762** HTML escaped.
1763*/
1764static void output_html_string(FILE *out, const char *z){
1765 int i;
drhc3d6ba42014-01-13 20:38:35 +00001766 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00001767 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00001768 for(i=0; z[i]
1769 && z[i]!='<'
1770 && z[i]!='&'
1771 && z[i]!='>'
1772 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00001773 && z[i]!='\'';
1774 i++){}
drhc08a4f12000-06-15 16:49:48 +00001775 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00001776 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00001777 }
1778 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00001779 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00001780 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00001781 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00001782 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00001783 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00001784 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00001785 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00001786 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00001787 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00001788 }else{
1789 break;
1790 }
1791 z += i + 1;
1792 }
1793}
1794
1795/*
drhc49f44e2006-10-26 18:15:42 +00001796** If a field contains any character identified by a 1 in the following
1797** array, then the string must be quoted for CSV.
1798*/
1799static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00001800 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1801 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1802 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1803 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1804 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1805 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1806 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1807 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1808 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1809 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1810 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1811 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1812 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1813 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1814 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1815 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00001816};
1817
1818/*
mistachkindd11f2d2014-12-11 04:49:46 +00001819** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00001820** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00001821** the null value. Strings are quoted if necessary. The separator
1822** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00001823*/
drhdcd87a92014-08-18 13:45:42 +00001824static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00001825 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00001826 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00001827 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00001828 }else{
drhc49f44e2006-10-26 18:15:42 +00001829 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00001830 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00001831 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00001832 if( needCsvQuote[((unsigned char*)z)[i]]
1833 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00001834 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00001835 i = 0;
1836 break;
1837 }
1838 }
1839 if( i==0 ){
1840 putc('"', out);
1841 for(i=0; z[i]; i++){
1842 if( z[i]=='"' ) putc('"', out);
1843 putc(z[i], out);
1844 }
1845 putc('"', out);
1846 }else{
drhe05461c2015-12-30 13:36:57 +00001847 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00001848 }
drh8e64d1c2004-10-07 00:32:39 +00001849 }
1850 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00001851 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001852 }
1853}
1854
danielk19774af00c62005-01-23 23:43:21 +00001855#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00001856/*
drh4c504392000-10-16 22:06:40 +00001857** This routine runs when the user presses Ctrl-C
1858*/
1859static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00001860 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00001861 seenInterrupt++;
1862 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00001863 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00001864}
danielk19774af00c62005-01-23 23:43:21 +00001865#endif
drh4c504392000-10-16 22:06:40 +00001866
drha0daa752016-09-16 11:53:10 +00001867#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00001868/*
drhde613c62016-04-04 17:23:10 +00001869** When the ".auth ON" is set, the following authorizer callback is
1870** invoked. It always returns SQLITE_OK.
1871*/
1872static int shellAuth(
1873 void *pClientData,
1874 int op,
1875 const char *zA1,
1876 const char *zA2,
1877 const char *zA3,
1878 const char *zA4
1879){
1880 ShellState *p = (ShellState*)pClientData;
1881 static const char *azAction[] = { 0,
1882 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1883 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1884 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1885 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1886 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1887 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1888 "PRAGMA", "READ", "SELECT",
1889 "TRANSACTION", "UPDATE", "ATTACH",
1890 "DETACH", "ALTER_TABLE", "REINDEX",
1891 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1892 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1893 };
1894 int i;
1895 const char *az[4];
1896 az[0] = zA1;
1897 az[1] = zA2;
1898 az[2] = zA3;
1899 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00001900 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00001901 for(i=0; i<4; i++){
1902 raw_printf(p->out, " ");
1903 if( az[i] ){
1904 output_c_string(p->out, az[i]);
1905 }else{
1906 raw_printf(p->out, "NULL");
1907 }
1908 }
1909 raw_printf(p->out, "\n");
1910 return SQLITE_OK;
1911}
drha0daa752016-09-16 11:53:10 +00001912#endif
mistachkin8145fc62016-09-16 20:39:21 +00001913
drh79f20e92016-12-13 23:22:39 +00001914/*
1915** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1916**
1917** This routine converts some CREATE TABLE statements for shadow tables
1918** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1919*/
1920static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1921 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1922 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1923 }else{
1924 utf8_printf(out, "%s%s", z, zTail);
1925 }
1926}
1927static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1928 char c = z[n];
1929 z[n] = 0;
1930 printSchemaLine(out, z, zTail);
1931 z[n] = c;
1932}
drhde613c62016-04-04 17:23:10 +00001933
1934/*
shane626a6e42009-10-22 17:30:15 +00001935** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00001936** invokes for each row of a query result.
1937*/
drh4ace5362014-11-10 14:42:28 +00001938static int shell_callback(
1939 void *pArg,
1940 int nArg, /* Number of result columns */
1941 char **azArg, /* Text of each result column */
1942 char **azCol, /* Column names */
1943 int *aiType /* Column types */
1944){
drh75897232000-05-29 14:26:00 +00001945 int i;
drhdcd87a92014-08-18 13:45:42 +00001946 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00001947
drh700c2522016-02-09 18:39:25 +00001948 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00001949 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00001950 int w = 5;
drh6a535342001-10-19 16:44:56 +00001951 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00001952 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00001953 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00001954 if( len>w ) w = len;
1955 }
drhe05461c2015-12-30 13:36:57 +00001956 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001957 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001958 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00001959 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001960 }
1961 break;
1962 }
danielk19770d78bae2008-01-03 07:09:48 +00001963 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00001964 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00001965 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1966 const int *colWidth;
1967 int showHdr;
1968 char *rowSep;
1969 if( p->cMode==MODE_Column ){
1970 colWidth = p->colWidth;
1971 showHdr = p->showHeader;
1972 rowSep = p->rowSeparator;
1973 }else{
1974 colWidth = aExplainWidths;
1975 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00001976 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00001977 }
drha0c66f52000-07-29 13:20:21 +00001978 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00001979 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00001980 int w, n;
1981 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00001982 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00001983 }else{
danielk19770d78bae2008-01-03 07:09:48 +00001984 w = 0;
drh75897232000-05-29 14:26:00 +00001985 }
drh078b1fd2012-09-21 13:40:02 +00001986 if( w==0 ){
drh64bf76d2017-06-05 12:29:26 +00001987 w = strlenChar(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00001988 if( w<10 ) w = 10;
drh64bf76d2017-06-05 12:29:26 +00001989 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00001990 if( w<n ) w = n;
1991 }
1992 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00001993 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00001994 }
drh700c2522016-02-09 18:39:25 +00001995 if( showHdr ){
drh6887e8f2017-04-17 13:18:42 +00001996 utf8_width_print(p->out, w, azCol[i]);
1997 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001998 }
1999 }
drh700c2522016-02-09 18:39:25 +00002000 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00002001 for(i=0; i<nArg; i++){
2002 int w;
2003 if( i<ArraySize(p->actualWidth) ){
2004 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00002005 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00002006 }else{
2007 w = 10;
2008 }
mistachkinaae280e2015-12-31 19:06:24 +00002009 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00002010 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00002011 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00002012 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00002013 }
drh75897232000-05-29 14:26:00 +00002014 }
2015 }
drh6a535342001-10-19 16:44:56 +00002016 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002017 for(i=0; i<nArg; i++){
2018 int w;
drha0c66f52000-07-29 13:20:21 +00002019 if( i<ArraySize(p->actualWidth) ){
2020 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00002021 }else{
2022 w = 10;
2023 }
drh64bf76d2017-06-05 12:29:26 +00002024 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
2025 w = strlenChar(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00002026 }
dana98bf362013-11-13 18:35:01 +00002027 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00002028 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00002029 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00002030 }
danc4650bb2013-11-18 08:41:06 +00002031 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00002032 }
drh6887e8f2017-04-17 13:18:42 +00002033 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2034 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drh75897232000-05-29 14:26:00 +00002035 }
2036 break;
2037 }
drh4926fec2016-04-13 15:33:42 +00002038 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00002039 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00002040 break;
2041 }
2042 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2043 char *z;
drh07d683f2016-04-13 21:00:36 +00002044 int j;
drh4926fec2016-04-13 15:33:42 +00002045 int nParen = 0;
2046 char cEnd = 0;
2047 char c;
2048 int nLine = 0;
2049 assert( nArg==1 );
2050 if( azArg[0]==0 ) break;
2051 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2052 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2053 ){
2054 utf8_printf(p->out, "%s;\n", azArg[0]);
2055 break;
2056 }
2057 z = sqlite3_mprintf("%s", azArg[0]);
2058 j = 0;
2059 for(i=0; IsSpace(z[i]); i++){}
2060 for(; (c = z[i])!=0; i++){
2061 if( IsSpace(c) ){
2062 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2063 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2064 j--;
2065 }
2066 z[j++] = c;
2067 }
2068 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2069 z[j] = 0;
2070 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00002071 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00002072 if( c==cEnd ){
2073 cEnd = 0;
2074 }else if( c=='"' || c=='\'' || c=='`' ){
2075 cEnd = c;
2076 }else if( c=='[' ){
2077 cEnd = ']';
2078 }else if( c=='(' ){
2079 nParen++;
2080 }else if( c==')' ){
2081 nParen--;
2082 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00002083 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00002084 j = 0;
2085 }
2086 }
2087 z[j++] = c;
2088 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
2089 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00002090 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00002091 j = 0;
2092 nLine++;
2093 while( IsSpace(z[i+1]) ){ i++; }
2094 }
2095 }
2096 z[j] = 0;
2097 }
drh79f20e92016-12-13 23:22:39 +00002098 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00002099 sqlite3_free(z);
2100 break;
2101 }
drh75897232000-05-29 14:26:00 +00002102 case MODE_List: {
2103 if( p->cnt++==0 && p->showHeader ){
2104 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002105 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00002106 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00002107 }
2108 }
drh6a535342001-10-19 16:44:56 +00002109 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002110 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00002111 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00002112 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00002113 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00002114 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00002115 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00002116 }else{
drhe05461c2015-12-30 13:36:57 +00002117 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00002118 }
drh75897232000-05-29 14:26:00 +00002119 }
2120 break;
2121 }
drh1e5d0e92000-05-31 23:33:17 +00002122 case MODE_Html: {
2123 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00002124 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002125 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002126 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00002127 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00002128 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00002129 }
mistachkinaae280e2015-12-31 19:06:24 +00002130 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002131 }
drh6a535342001-10-19 16:44:56 +00002132 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00002133 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002134 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002135 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00002136 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00002137 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00002138 }
mistachkinaae280e2015-12-31 19:06:24 +00002139 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002140 break;
2141 }
drhfeac5f82004-08-01 00:10:45 +00002142 case MODE_Tcl: {
2143 if( p->cnt++==0 && p->showHeader ){
2144 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002145 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00002146 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002147 }
drhe05461c2015-12-30 13:36:57 +00002148 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002149 }
2150 if( azArg==0 ) break;
2151 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00002152 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00002153 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002154 }
drhe05461c2015-12-30 13:36:57 +00002155 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002156 break;
2157 }
drh8e64d1c2004-10-07 00:32:39 +00002158 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00002159 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002160 if( p->cnt++==0 && p->showHeader ){
2161 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002162 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00002163 }
drhe05461c2015-12-30 13:36:57 +00002164 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002165 }
drh40253262014-10-17 21:35:05 +00002166 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00002167 for(i=0; i<nArg; i++){
2168 output_csv(p, azArg[i], i<nArg-1);
2169 }
drhe05461c2015-12-30 13:36:57 +00002170 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002171 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002172 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002173 break;
2174 }
drh28bd4bc2000-06-15 15:57:22 +00002175 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00002176 if( azArg==0 ) break;
drh13fe1382017-04-08 13:42:55 +00002177 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2178 if( p->showHeader ){
2179 raw_printf(p->out,"(");
2180 for(i=0; i<nArg; i++){
2181 if( i>0 ) raw_printf(p->out, ",");
2182 if( quoteChar(azCol[i]) ){
2183 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2184 utf8_printf(p->out, "%s", z);
2185 sqlite3_free(z);
2186 }else{
2187 raw_printf(p->out, "%s", azCol[i]);
drh41f5f6e2016-10-21 17:39:30 +00002188 }
mistachkin151c75a2015-04-07 21:16:40 +00002189 }
drh13fe1382017-04-08 13:42:55 +00002190 raw_printf(p->out,")");
2191 }
2192 p->cnt++;
2193 for(i=0; i<nArg; i++){
2194 raw_printf(p->out, i>0 ? "," : " VALUES(");
2195 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2196 utf8_printf(p->out,"NULL");
2197 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2198 output_quoted_escaped_string(p->out, azArg[i]);
2199 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2200 utf8_printf(p->out,"%s", azArg[i]);
2201 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2202 char z[50];
2203 double r = sqlite3_column_double(p->pStmt, i);
2204 sqlite3_snprintf(50,z,"%!.20g", r);
2205 raw_printf(p->out, "%s", z);
2206 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2207 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2208 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2209 output_hex_blob(p->out, pBlob, nBlob);
2210 }else if( isNumber(azArg[i], 0) ){
2211 utf8_printf(p->out,"%s", azArg[i]);
2212 }else{
2213 output_quoted_escaped_string(p->out, azArg[i]);
2214 }
2215 }
2216 raw_printf(p->out,");\n");
2217 break;
2218 }
2219 case MODE_Quote: {
2220 if( azArg==0 ) break;
2221 if( p->cnt==0 && p->showHeader ){
drh59ce2c42016-11-03 13:12:28 +00002222 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00002223 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00002224 output_quoted_string(p->out, azCol[i]);
2225 }
mistachkin2f9a6132016-11-11 05:19:45 +00002226 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002227 }
drh59ce2c42016-11-03 13:12:28 +00002228 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002229 for(i=0; i<nArg; i++){
drh13fe1382017-04-08 13:42:55 +00002230 if( i>0 ) raw_printf(p->out, ",");
shanead6b8d02009-10-22 18:12:58 +00002231 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
drh13fe1382017-04-08 13:42:55 +00002232 utf8_printf(p->out,"NULL");
shanead6b8d02009-10-22 18:12:58 +00002233 }else if( aiType && aiType[i]==SQLITE_TEXT ){
shanead6b8d02009-10-22 18:12:58 +00002234 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002235 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drh13fe1382017-04-08 13:42:55 +00002236 utf8_printf(p->out,"%s", azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002237 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2238 char z[50];
2239 double r = sqlite3_column_double(p->pStmt, i);
2240 sqlite3_snprintf(50,z,"%!.20g", r);
drh13fe1382017-04-08 13:42:55 +00002241 raw_printf(p->out, "%s", z);
shane626a6e42009-10-22 17:30:15 +00002242 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2243 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2244 int nBlob = sqlite3_column_bytes(p->pStmt, i);
shane626a6e42009-10-22 17:30:15 +00002245 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002246 }else if( isNumber(azArg[i], 0) ){
drh13fe1382017-04-08 13:42:55 +00002247 utf8_printf(p->out,"%s", azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002248 }else{
drh28bd4bc2000-06-15 15:57:22 +00002249 output_quoted_string(p->out, azArg[i]);
2250 }
2251 }
drh13fe1382017-04-08 13:42:55 +00002252 raw_printf(p->out,"\n");
drh6a535342001-10-19 16:44:56 +00002253 break;
drh28bd4bc2000-06-15 15:57:22 +00002254 }
mistachkin636bf9f2014-07-19 20:15:16 +00002255 case MODE_Ascii: {
2256 if( p->cnt++==0 && p->showHeader ){
2257 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002258 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2259 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002260 }
drhe05461c2015-12-30 13:36:57 +00002261 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002262 }
2263 if( azArg==0 ) break;
2264 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002265 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2266 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002267 }
drhe05461c2015-12-30 13:36:57 +00002268 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002269 break;
2270 }
persicom1d0b8722002-04-18 02:53:04 +00002271 }
drh75897232000-05-29 14:26:00 +00002272 return 0;
2273}
2274
2275/*
shane626a6e42009-10-22 17:30:15 +00002276** This is the callback routine that the SQLite library
2277** invokes for each row of a query result.
2278*/
2279static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2280 /* since we don't have type info, call the shell_callback with a NULL value */
2281 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2282}
2283
drhfb546af2017-03-09 22:00:33 +00002284/*
2285** This is the callback routine from sqlite3_exec() that appends all
2286** output onto the end of a ShellText object.
2287*/
2288static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2289 ShellText *p = (ShellText*)pArg;
2290 int i;
drh2fb79e92017-03-25 12:08:11 +00002291 UNUSED_PARAMETER(az);
drhfb546af2017-03-09 22:00:33 +00002292 if( p->n ) appendText(p, "|", 0);
2293 for(i=0; i<nArg; i++){
2294 if( i ) appendText(p, ",", 0);
2295 if( azArg[i] ) appendText(p, azArg[i], 0);
2296 }
2297 return 0;
2298}
2299
2300/*
2301** Generate an appropriate SELFTEST table in the main database.
2302*/
2303static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00002304 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00002305 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00002306 "SAVEPOINT selftest_init;\n"
2307 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00002308 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2309 " op TEXT,\n" /* Operator: memo run */
2310 " cmd TEXT,\n" /* Command text */
2311 " ans TEXT\n" /* Desired answer */
2312 ");"
drhf157d102017-03-10 01:05:38 +00002313 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2314 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2315 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2316 " 'memo','Tests generated by --init');\n"
2317 "INSERT INTO [_shell$self]\n"
2318 " SELECT 'run',\n"
2319 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2320 "FROM sqlite_master ORDER BY 2'',224))',\n"
2321 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2322 "FROM sqlite_master ORDER BY 2',224));\n"
2323 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002324 " SELECT 'run',"
2325 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2326 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2327 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2328 " FROM (\n"
2329 " SELECT name FROM sqlite_master\n"
2330 " WHERE type='table'\n"
2331 " AND name<>'selftest'\n"
2332 " AND coalesce(rootpage,0)>0\n"
2333 " )\n"
2334 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00002335 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002336 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00002337 "INSERT INTO selftest(tno,op,cmd,ans)"
2338 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2339 "DROP TABLE [_shell$self];"
2340 ,0,0,&zErrMsg);
2341 if( zErrMsg ){
2342 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2343 sqlite3_free(zErrMsg);
2344 }
2345 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00002346}
2347
drhf42d3182017-03-08 12:25:18 +00002348
shane626a6e42009-10-22 17:30:15 +00002349/*
drhdcd87a92014-08-18 13:45:42 +00002350** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00002351** the name of the table given. Escape any quote characters in the
2352** table name.
2353*/
drhdcd87a92014-08-18 13:45:42 +00002354static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00002355 int i, n;
drhf42d3182017-03-08 12:25:18 +00002356 int cQuote;
drh33048c02001-10-01 14:29:22 +00002357 char *z;
2358
2359 if( p->zDestTable ){
2360 free(p->zDestTable);
2361 p->zDestTable = 0;
2362 }
2363 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00002364 cQuote = quoteChar(zName);
2365 n = strlen30(zName);
drh45e7d7d2017-06-24 13:31:40 +00002366 if( cQuote ) n += n+2;
drh33048c02001-10-01 14:29:22 +00002367 z = p->zDestTable = malloc( n+1 );
2368 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002369 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00002370 exit(1);
2371 }
2372 n = 0;
drhf42d3182017-03-08 12:25:18 +00002373 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002374 for(i=0; zName[i]; i++){
2375 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00002376 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002377 }
drhf42d3182017-03-08 12:25:18 +00002378 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002379 z[n] = 0;
2380}
2381
drhdd3d4592004-08-30 01:54:05 +00002382
2383/*
drhb21a8e42012-01-28 21:08:51 +00002384** Execute a query statement that will generate SQL output. Print
2385** the result columns, comma-separated, on a line and then add a
2386** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00002387**
drhb21a8e42012-01-28 21:08:51 +00002388** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00002389** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00002390** "--" comment occurs at the end of the statement, the comment
2391** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00002392*/
drh157e29a2009-05-21 15:15:00 +00002393static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00002394 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00002395 const char *zSelect, /* SELECT statement to extract content */
2396 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00002397){
drhdd3d4592004-08-30 01:54:05 +00002398 sqlite3_stmt *pSelect;
2399 int rc;
drhb21a8e42012-01-28 21:08:51 +00002400 int nResult;
2401 int i;
2402 const char *z;
drhc7181902014-02-27 15:04:13 +00002403 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00002404 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00002405 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2406 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002407 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00002408 return rc;
2409 }
2410 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00002411 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00002412 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00002413 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00002414 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00002415 zFirstRow = 0;
2416 }
drhb21a8e42012-01-28 21:08:51 +00002417 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00002418 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00002419 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00002420 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00002421 }
2422 if( z==0 ) z = "";
2423 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2424 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00002425 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00002426 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002427 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00002428 }
drhdd3d4592004-08-30 01:54:05 +00002429 rc = sqlite3_step(pSelect);
2430 }
drh2f464a02011-10-13 00:41:49 +00002431 rc = sqlite3_finalize(pSelect);
2432 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00002433 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2434 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002435 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00002436 }
2437 return rc;
drhdd3d4592004-08-30 01:54:05 +00002438}
2439
shane626a6e42009-10-22 17:30:15 +00002440/*
2441** Allocate space and save off current error string.
2442*/
2443static char *save_err_msg(
2444 sqlite3 *db /* Database to query */
2445){
2446 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00002447 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00002448 if( zErrMsg ){
2449 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2450 }
2451 return zErrMsg;
2452}
2453
drh34784902016-02-27 17:12:36 +00002454#ifdef __linux__
2455/*
2456** Attempt to display I/O stats on Linux using /proc/PID/io
2457*/
2458static void displayLinuxIoStats(FILE *out){
2459 FILE *in;
2460 char z[200];
2461 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2462 in = fopen(z, "rb");
2463 if( in==0 ) return;
2464 while( fgets(z, sizeof(z), in)!=0 ){
2465 static const struct {
2466 const char *zPattern;
2467 const char *zDesc;
2468 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00002469 { "rchar: ", "Bytes received by read():" },
2470 { "wchar: ", "Bytes sent to write():" },
2471 { "syscr: ", "Read() system calls:" },
2472 { "syscw: ", "Write() system calls:" },
2473 { "read_bytes: ", "Bytes read from storage:" },
2474 { "write_bytes: ", "Bytes written to storage:" },
2475 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00002476 };
2477 int i;
2478 for(i=0; i<ArraySize(aTrans); i++){
2479 int n = (int)strlen(aTrans[i].zPattern);
2480 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00002481 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00002482 break;
2483 }
2484 }
2485 }
2486 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00002487}
drh34784902016-02-27 17:12:36 +00002488#endif
2489
drha2df53b2017-03-10 14:36:10 +00002490/*
2491** Display a single line of status using 64-bit values.
2492*/
2493static void displayStatLine(
2494 ShellState *p, /* The shell context */
2495 char *zLabel, /* Label for this one line */
2496 char *zFormat, /* Format for the result */
2497 int iStatusCtrl, /* Which status to display */
2498 int bReset /* True to reset the stats */
2499){
2500 sqlite3_int64 iCur = -1;
2501 sqlite3_int64 iHiwtr = -1;
2502 int i, nPercent;
2503 char zLine[200];
2504 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2505 for(i=0, nPercent=0; zFormat[i]; i++){
2506 if( zFormat[i]=='%' ) nPercent++;
2507 }
2508 if( nPercent>1 ){
2509 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2510 }else{
2511 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2512 }
2513 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2514}
drh34784902016-02-27 17:12:36 +00002515
shane626a6e42009-10-22 17:30:15 +00002516/*
shaneh642d8b82010-07-28 16:05:34 +00002517** Display memory stats.
2518*/
2519static int display_stats(
2520 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00002521 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00002522 int bReset /* True to reset the stats */
2523){
2524 int iCur;
2525 int iHiwtr;
2526
2527 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00002528 displayStatLine(pArg, "Memory Used:",
2529 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2530 displayStatLine(pArg, "Number of Outstanding Allocations:",
2531 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00002532 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00002533 displayStatLine(pArg, "Number of Pcache Pages Used:",
2534 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002535 }
drha2df53b2017-03-10 14:36:10 +00002536 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2537 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh44dec872014-08-30 15:49:25 +00002538 if( pArg->shellFlgs & SHFLG_Scratch ){
drha2df53b2017-03-10 14:36:10 +00002539 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2540 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002541 }
drha2df53b2017-03-10 14:36:10 +00002542 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2543 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2544 displayStatLine(pArg, "Largest Allocation:",
2545 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2546 displayStatLine(pArg, "Largest Pcache Allocation:",
2547 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2548 displayStatLine(pArg, "Largest Scratch Allocation:",
2549 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002550#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00002551 displayStatLine(pArg, "Deepest Parser Stack:",
2552 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002553#endif
2554 }
2555
2556 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00002557 if( pArg->shellFlgs & SHFLG_Lookaside ){
2558 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00002559 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2560 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002561 raw_printf(pArg->out,
2562 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00002563 iCur, iHiwtr);
2564 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2565 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002566 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2567 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002568 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2569 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002570 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2571 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002572 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2573 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002574 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2575 iHiwtr);
drh44dec872014-08-30 15:49:25 +00002576 }
shaneh642d8b82010-07-28 16:05:34 +00002577 iHiwtr = iCur = -1;
2578 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002579 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2580 iCur);
drh4ace5362014-11-10 14:42:28 +00002581 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00002582 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00002583 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00002584 iHiwtr = iCur = -1;
2585 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002586 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002587 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00002588 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002589 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00002590 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00002591 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002592 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002593 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002594 iHiwtr = iCur = -1;
2595 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002596 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002597 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002598 }
2599
2600 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00002601 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2602 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002603 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002604 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002605 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00002606 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002607 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00002608 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002609 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002610 }
2611
drh34784902016-02-27 17:12:36 +00002612#ifdef __linux__
2613 displayLinuxIoStats(pArg->out);
2614#endif
2615
dan5a790282015-08-07 20:06:14 +00002616 /* Do not remove this machine readable comment: extra-stats-output-here */
2617
shaneh642d8b82010-07-28 16:05:34 +00002618 return 0;
2619}
2620
2621/*
dan8d1edb92014-11-05 09:07:28 +00002622** Display scan stats.
2623*/
2624static void display_scanstats(
2625 sqlite3 *db, /* Database to query */
2626 ShellState *pArg /* Pointer to ShellState */
2627){
drhf5ed7ad2015-06-15 14:43:25 +00002628#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2629 UNUSED_PARAMETER(db);
2630 UNUSED_PARAMETER(pArg);
2631#else
drh15f23c22014-11-06 12:46:16 +00002632 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00002633 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00002634 mx = 0;
2635 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00002636 double rEstLoop = 1.0;
2637 for(i=n=0; 1; i++){
2638 sqlite3_stmt *p = pArg->pStmt;
2639 sqlite3_int64 nLoop, nVisit;
2640 double rEst;
2641 int iSid;
2642 const char *zExplain;
2643 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2644 break;
2645 }
2646 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00002647 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00002648 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00002649 if( n==0 ){
2650 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00002651 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00002652 }
drh42f30bc2014-11-06 12:08:21 +00002653 n++;
2654 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2655 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2656 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00002657 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00002658 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00002659 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00002660 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00002661 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00002662 );
dan8d1edb92014-11-05 09:07:28 +00002663 }
dan8d1edb92014-11-05 09:07:28 +00002664 }
mistachkinaae280e2015-12-31 19:06:24 +00002665 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00002666#endif
dan8d1edb92014-11-05 09:07:28 +00002667}
2668
2669/*
dana98bf362013-11-13 18:35:01 +00002670** Parameter azArray points to a zero-terminated array of strings. zStr
2671** points to a single nul-terminated string. Return non-zero if zStr
2672** is equal, according to strcmp(), to any of the strings in the array.
2673** Otherwise, return zero.
2674*/
2675static int str_in_array(const char *zStr, const char **azArray){
2676 int i;
2677 for(i=0; azArray[i]; i++){
2678 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2679 }
2680 return 0;
2681}
2682
2683/*
2684** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00002685** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00002686** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00002687**
2688** The indenting rules are:
2689**
2690** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2691** all opcodes that occur between the p2 jump destination and the opcode
2692** itself by 2 spaces.
2693**
drh01752bc2013-11-14 23:59:33 +00002694** * For each "Goto", if the jump destination is earlier in the program
2695** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00002696** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00002697** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00002698** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00002699** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00002700*/
drhdcd87a92014-08-18 13:45:42 +00002701static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00002702 const char *zSql; /* The text of the SQL statement */
2703 const char *z; /* Used to check if this is an EXPLAIN */
2704 int *abYield = 0; /* True if op is an OP_Yield */
2705 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00002706 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00002707
drh8ad0de32014-03-20 18:45:27 +00002708 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2709 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00002710 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2711 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00002712 const char *azGoto[] = { "Goto", 0 };
2713
2714 /* Try to figure out if this is really an EXPLAIN statement. If this
2715 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00002716 if( sqlite3_column_count(pSql)!=8 ){
2717 p->cMode = p->mode;
2718 return;
2719 }
dana98bf362013-11-13 18:35:01 +00002720 zSql = sqlite3_sql(pSql);
2721 if( zSql==0 ) return;
2722 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00002723 if( sqlite3_strnicmp(z, "explain", 7) ){
2724 p->cMode = p->mode;
2725 return;
2726 }
dana98bf362013-11-13 18:35:01 +00002727
2728 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2729 int i;
danc4650bb2013-11-18 08:41:06 +00002730 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00002731 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00002732
2733 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2734 ** p2 is an instruction address, set variable p2op to the index of that
2735 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2736 ** the current instruction is part of a sub-program generated by an
2737 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00002738 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00002739 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00002740
2741 /* Grow the p->aiIndent array as required */
2742 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00002743 if( iOp==0 ){
2744 /* Do further verfication that this is explain output. Abort if
2745 ** it is not */
2746 static const char *explainCols[] = {
2747 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2748 int jj;
2749 for(jj=0; jj<ArraySize(explainCols); jj++){
2750 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2751 p->cMode = p->mode;
2752 sqlite3_reset(pSql);
2753 return;
2754 }
2755 }
2756 }
dana98bf362013-11-13 18:35:01 +00002757 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00002758 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2759 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00002760 }
2761 abYield[iOp] = str_in_array(zOp, azYield);
2762 p->aiIndent[iOp] = 0;
2763 p->nIndent = iOp+1;
2764
2765 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00002766 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002767 }
drhfe705102014-03-06 13:38:37 +00002768 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2769 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2770 ){
drheacd29d2016-04-15 15:03:27 +00002771 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002772 }
2773 }
2774
danc4650bb2013-11-18 08:41:06 +00002775 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002776 sqlite3_free(abYield);
2777 sqlite3_reset(pSql);
2778}
2779
2780/*
2781** Free the array allocated by explain_data_prepare().
2782*/
drhdcd87a92014-08-18 13:45:42 +00002783static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00002784 sqlite3_free(p->aiIndent);
2785 p->aiIndent = 0;
2786 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00002787 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002788}
2789
2790/*
drheacd29d2016-04-15 15:03:27 +00002791** Disable and restore .wheretrace and .selecttrace settings.
2792*/
2793#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2794extern int sqlite3SelectTrace;
2795static int savedSelectTrace;
2796#endif
2797#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2798extern int sqlite3WhereTrace;
2799static int savedWhereTrace;
2800#endif
2801static void disable_debug_trace_modes(void){
2802#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2803 savedSelectTrace = sqlite3SelectTrace;
2804 sqlite3SelectTrace = 0;
2805#endif
2806#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2807 savedWhereTrace = sqlite3WhereTrace;
2808 sqlite3WhereTrace = 0;
2809#endif
2810}
2811static void restore_debug_trace_modes(void){
2812#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2813 sqlite3SelectTrace = savedSelectTrace;
2814#endif
2815#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2816 sqlite3WhereTrace = savedWhereTrace;
2817#endif
2818}
2819
2820/*
2821** Run a prepared statement
2822*/
2823static void exec_prepared_stmt(
2824 ShellState *pArg, /* Pointer to ShellState */
2825 sqlite3_stmt *pStmt, /* Statment to run */
2826 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2827){
2828 int rc;
2829
2830 /* perform the first step. this will tell us if we
2831 ** have a result set or not and how wide it is.
2832 */
2833 rc = sqlite3_step(pStmt);
2834 /* if we have a result set... */
2835 if( SQLITE_ROW == rc ){
2836 /* if we have a callback... */
2837 if( xCallback ){
2838 /* allocate space for col name ptr, value ptr, and type */
2839 int nCol = sqlite3_column_count(pStmt);
2840 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2841 if( !pData ){
2842 rc = SQLITE_NOMEM;
2843 }else{
2844 char **azCols = (char **)pData; /* Names of result columns */
2845 char **azVals = &azCols[nCol]; /* Results */
2846 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2847 int i, x;
2848 assert(sizeof(int) <= sizeof(char *));
2849 /* save off ptrs to column names */
2850 for(i=0; i<nCol; i++){
2851 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2852 }
2853 do{
2854 /* extract the data and data types */
2855 for(i=0; i<nCol; i++){
2856 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2857 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2858 azVals[i] = "";
2859 }else{
2860 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2861 }
2862 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2863 rc = SQLITE_NOMEM;
2864 break; /* from for */
2865 }
2866 } /* end for */
2867
2868 /* if data and types extracted successfully... */
2869 if( SQLITE_ROW == rc ){
2870 /* call the supplied callback with the result row data */
2871 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2872 rc = SQLITE_ABORT;
2873 }else{
2874 rc = sqlite3_step(pStmt);
2875 }
2876 }
2877 } while( SQLITE_ROW == rc );
2878 sqlite3_free(pData);
2879 }
2880 }else{
2881 do{
2882 rc = sqlite3_step(pStmt);
2883 } while( rc == SQLITE_ROW );
2884 }
2885 }
2886}
2887
2888/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002889** Execute a statement or set of statements. Print
2890** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00002891** set via the supplied callback.
2892**
mistachkin1fe36bb2016-04-04 02:16:44 +00002893** This is very similar to SQLite's built-in sqlite3_exec()
2894** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00002895** and callback data argument.
2896*/
2897static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00002898 sqlite3 *db, /* An open database */
2899 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00002900 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00002901 /* (not the same as sqlite3_exec) */
2902 ShellState *pArg, /* Pointer to ShellState */
2903 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00002904){
dan4564ced2010-01-05 04:59:56 +00002905 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2906 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00002907 int rc2;
dan4564ced2010-01-05 04:59:56 +00002908 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00002909
2910 if( pzErrMsg ){
2911 *pzErrMsg = NULL;
2912 }
2913
shaneb9fc17d2009-10-22 21:23:35 +00002914 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00002915 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00002916 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2917 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00002918 if( pzErrMsg ){
2919 *pzErrMsg = save_err_msg(db);
2920 }
2921 }else{
shaneb9fc17d2009-10-22 21:23:35 +00002922 if( !pStmt ){
2923 /* this happens for a comment or white-space */
2924 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002925 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00002926 continue;
2927 }
drheacd29d2016-04-15 15:03:27 +00002928 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00002929 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00002930 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00002931
shaneh642d8b82010-07-28 16:05:34 +00002932 /* save off the prepared statment handle and reset row count */
2933 if( pArg ){
2934 pArg->pStmt = pStmt;
2935 pArg->cnt = 0;
2936 }
2937
shanehb7977c52010-01-18 18:17:10 +00002938 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00002939 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00002940 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00002941 }
shanehb7977c52010-01-18 18:17:10 +00002942
drhefbf3b12014-02-28 20:47:24 +00002943 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00002944 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00002945 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00002946 char *zEQP;
2947 disable_debug_trace_modes();
2948 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00002949 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2950 if( rc==SQLITE_OK ){
2951 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00002952 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2953 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2954 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00002955 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00002956 }
2957 }
2958 sqlite3_finalize(pExplain);
2959 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00002960 if( pArg->autoEQP>=2 ){
2961 /* Also do an EXPLAIN for ".eqp full" mode */
2962 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2963 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2964 if( rc==SQLITE_OK ){
2965 pArg->cMode = MODE_Explain;
2966 explain_data_prepare(pArg, pExplain);
2967 exec_prepared_stmt(pArg, pExplain, xCallback);
2968 explain_data_delete(pArg);
2969 }
2970 sqlite3_finalize(pExplain);
2971 sqlite3_free(zEQP);
2972 }
2973 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00002974 }
2975
drh700c2522016-02-09 18:39:25 +00002976 if( pArg ){
2977 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00002978 if( pArg->autoExplain
2979 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00002980 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00002981 ){
2982 pArg->cMode = MODE_Explain;
2983 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002984
drh700c2522016-02-09 18:39:25 +00002985 /* If the shell is currently in ".explain" mode, gather the extra
2986 ** data required to add indents to the output.*/
2987 if( pArg->cMode==MODE_Explain ){
2988 explain_data_prepare(pArg, pStmt);
2989 }
dana98bf362013-11-13 18:35:01 +00002990 }
2991
drheacd29d2016-04-15 15:03:27 +00002992 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00002993 explain_data_delete(pArg);
2994
shaneh642d8b82010-07-28 16:05:34 +00002995 /* print usage stats if stats on */
2996 if( pArg && pArg->statsOn ){
2997 display_stats(db, pArg, 0);
2998 }
2999
dan8d1edb92014-11-05 09:07:28 +00003000 /* print loop-counters if required */
3001 if( pArg && pArg->scanstatsOn ){
3002 display_scanstats(db, pArg);
3003 }
3004
mistachkin1fe36bb2016-04-04 02:16:44 +00003005 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00003006 ** copy of the error message. Otherwise, set zSql to point to the
3007 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00003008 rc2 = sqlite3_finalize(pStmt);
3009 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00003010 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00003011 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00003012 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00003013 }else if( pzErrMsg ){
3014 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00003015 }
shaneh642d8b82010-07-28 16:05:34 +00003016
3017 /* clear saved stmt handle */
3018 if( pArg ){
3019 pArg->pStmt = NULL;
3020 }
shane626a6e42009-10-22 17:30:15 +00003021 }
shaneb9fc17d2009-10-22 21:23:35 +00003022 } /* end while */
shane626a6e42009-10-22 17:30:15 +00003023
3024 return rc;
3025}
3026
drhe611f142017-03-08 11:44:00 +00003027/*
3028** Release memory previously allocated by tableColumnList().
3029*/
3030static void freeColumnList(char **azCol){
3031 int i;
3032 for(i=1; azCol[i]; i++){
3033 sqlite3_free(azCol[i]);
3034 }
3035 /* azCol[0] is a static string */
3036 sqlite3_free(azCol);
3037}
3038
3039/*
3040** Return a list of pointers to strings which are the names of all
3041** columns in table zTab. The memory to hold the names is dynamically
3042** allocated and must be released by the caller using a subsequent call
3043** to freeColumnList().
3044**
3045** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3046** value that needs to be preserved, then azCol[0] is filled in with the
3047** name of the rowid column.
3048**
3049** The first regular column in the table is azCol[1]. The list is terminated
3050** by an entry with azCol[i]==0.
3051*/
3052static char **tableColumnList(ShellState *p, const char *zTab){
3053 char **azCol = 0;
3054 sqlite3_stmt *pStmt;
3055 char *zSql;
3056 int nCol = 0;
3057 int nAlloc = 0;
3058 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3059 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00003060 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00003061 int rc;
3062
3063 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3064 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3065 sqlite3_free(zSql);
3066 if( rc ) return 0;
3067 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3068 if( nCol>=nAlloc-2 ){
3069 nAlloc = nAlloc*2 + nCol + 10;
3070 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3071 if( azCol==0 ){
3072 raw_printf(stderr, "Error: out of memory\n");
3073 exit(1);
3074 }
3075 }
3076 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3077 if( sqlite3_column_int(pStmt, 5) ){
3078 nPK++;
3079 if( nPK==1
3080 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
mistachkine16a3502017-05-29 03:48:13 +00003081 "INTEGER")==0
drhe611f142017-03-08 11:44:00 +00003082 ){
3083 isIPK = 1;
3084 }else{
3085 isIPK = 0;
3086 }
3087 }
3088 }
3089 sqlite3_finalize(pStmt);
3090 azCol[0] = 0;
3091 azCol[nCol+1] = 0;
3092
3093 /* The decision of whether or not a rowid really needs to be preserved
3094 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3095 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3096 ** rowids on tables where the rowid is inaccessible because there are other
3097 ** columns in the table named "rowid", "_rowid_", and "oid".
3098 */
3099 if( preserveRowid && isIPK ){
3100 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3101 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3102 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3103 ** ROWID aliases. To distinguish these cases, check to see if
3104 ** there is a "pk" entry in "PRAGMA index_list". There will be
3105 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3106 */
3107 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3108 " WHERE origin='pk'", zTab);
3109 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3110 sqlite3_free(zSql);
3111 if( rc ){
3112 freeColumnList(azCol);
3113 return 0;
3114 }
3115 rc = sqlite3_step(pStmt);
3116 sqlite3_finalize(pStmt);
3117 preserveRowid = rc==SQLITE_ROW;
3118 }
3119 if( preserveRowid ){
3120 /* Only preserve the rowid if we can find a name to use for the
3121 ** rowid */
3122 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3123 int i, j;
3124 for(j=0; j<3; j++){
3125 for(i=1; i<=nCol; i++){
3126 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3127 }
3128 if( i>nCol ){
3129 /* At this point, we know that azRowid[j] is not the name of any
3130 ** ordinary column in the table. Verify that azRowid[j] is a valid
3131 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3132 ** tables will fail this last check */
drhe611f142017-03-08 11:44:00 +00003133 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3134 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3135 break;
3136 }
3137 }
3138 }
3139 return azCol;
3140}
3141
drh33048c02001-10-01 14:29:22 +00003142/*
drhf8563c02017-03-09 18:13:52 +00003143** Toggle the reverse_unordered_selects setting.
3144*/
3145static void toggleSelectOrder(sqlite3 *db){
3146 sqlite3_stmt *pStmt = 0;
3147 int iSetting = 0;
3148 char zStmt[100];
3149 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3150 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3151 iSetting = sqlite3_column_int(pStmt, 0);
3152 }
3153 sqlite3_finalize(pStmt);
3154 sqlite3_snprintf(sizeof(zStmt), zStmt,
3155 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3156 sqlite3_exec(db, zStmt, 0, 0, 0);
3157}
3158
3159/*
drh4c653a02000-06-07 01:27:47 +00003160** This is a different callback routine used for dumping the database.
3161** Each row received by this callback consists of a table name,
3162** the table type ("index" or "table") and SQL to create the table.
3163** This routine should print text sufficient to recreate the table.
3164*/
drh701ff6a2017-03-22 12:51:34 +00003165static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
danielk19772a02e332004-06-05 08:04:36 +00003166 int rc;
3167 const char *zTable;
3168 const char *zType;
3169 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00003170 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00003171
drh701ff6a2017-03-22 12:51:34 +00003172 UNUSED_PARAMETER(azNotUsed);
drh4c653a02000-06-07 01:27:47 +00003173 if( nArg!=3 ) return 1;
danielk19772a02e332004-06-05 08:04:36 +00003174 zTable = azArg[0];
3175 zType = azArg[1];
3176 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00003177
drh00b950d2005-09-11 02:03:03 +00003178 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00003179 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00003180 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003181 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00003182 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3183 return 0;
drh45e29d82006-11-20 16:21:10 +00003184 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3185 char *zIns;
3186 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00003187 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00003188 p->writableSchema = 1;
3189 }
3190 zIns = sqlite3_mprintf(
3191 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3192 "VALUES('table','%q','%q',0,'%q');",
3193 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00003194 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00003195 sqlite3_free(zIns);
3196 return 0;
drh00b950d2005-09-11 02:03:03 +00003197 }else{
drh79f20e92016-12-13 23:22:39 +00003198 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00003199 }
danielk19772a02e332004-06-05 08:04:36 +00003200
3201 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00003202 ShellText sSelect;
3203 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00003204 char **azCol;
3205 int i;
3206 char *savedDestTable;
3207 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00003208
drhe611f142017-03-08 11:44:00 +00003209 azCol = tableColumnList(p, zTable);
3210 if( azCol==0 ){
3211 p->nErr++;
3212 return 0;
danielk19772a02e332004-06-05 08:04:36 +00003213 }
3214
drhbf92ec02012-03-22 12:50:34 +00003215 /* Always quote the table name, even if it appears to be pure ascii,
3216 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00003217 initText(&sTable);
3218 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003219 /* If preserving the rowid, add a column list after the table name.
3220 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3221 ** instead of the usual "INSERT INTO tab VALUES(...)".
3222 */
3223 if( azCol[0] ){
3224 appendText(&sTable, "(", 0);
3225 appendText(&sTable, azCol[0], 0);
3226 for(i=1; azCol[i]; i++){
3227 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003228 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003229 }
drhe611f142017-03-08 11:44:00 +00003230 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003231 }
danielk19772a02e332004-06-05 08:04:36 +00003232
drhe611f142017-03-08 11:44:00 +00003233 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003234 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003235 appendText(&sSelect, "SELECT ", 0);
3236 if( azCol[0] ){
3237 appendText(&sSelect, azCol[0], 0);
3238 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003239 }
drhe611f142017-03-08 11:44:00 +00003240 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003241 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003242 if( azCol[i+1] ){
3243 appendText(&sSelect, ",", 0);
3244 }
3245 }
3246 freeColumnList(azCol);
3247 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003248 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003249
3250 savedDestTable = p->zDestTable;
3251 savedMode = p->mode;
3252 p->zDestTable = sTable.z;
3253 p->mode = p->cMode = MODE_Insert;
3254 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003255 if( (rc&0xff)==SQLITE_CORRUPT ){
3256 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3257 toggleSelectOrder(p->db);
3258 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3259 toggleSelectOrder(p->db);
3260 }
drhe611f142017-03-08 11:44:00 +00003261 p->zDestTable = savedDestTable;
3262 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003263 freeText(&sTable);
3264 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003265 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003266 }
drh4c653a02000-06-07 01:27:47 +00003267 return 0;
3268}
3269
3270/*
drh45e29d82006-11-20 16:21:10 +00003271** Run zQuery. Use dump_callback() as the callback routine so that
3272** the contents of the query are output as SQL statements.
3273**
drhdd3d4592004-08-30 01:54:05 +00003274** If we get a SQLITE_CORRUPT error, rerun the query after appending
3275** "ORDER BY rowid DESC" to the end.
3276*/
3277static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003278 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003279 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003280){
3281 int rc;
drh2f464a02011-10-13 00:41:49 +00003282 char *zErr = 0;
3283 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003284 if( rc==SQLITE_CORRUPT ){
3285 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00003286 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00003287 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00003288 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00003289 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003290 sqlite3_free(zErr);
3291 zErr = 0;
3292 }
drhdd3d4592004-08-30 01:54:05 +00003293 zQ2 = malloc( len+100 );
3294 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00003295 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00003296 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3297 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003298 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003299 }else{
3300 rc = SQLITE_CORRUPT;
3301 }
3302 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00003303 free(zQ2);
3304 }
3305 return rc;
3306}
3307
3308/*
drh75897232000-05-29 14:26:00 +00003309** Text of a help message
3310*/
persicom1d0b8722002-04-18 02:53:04 +00003311static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00003312#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00003313 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00003314#endif
drh9ff849f2009-02-04 20:55:57 +00003315 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00003316 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00003317 ".binary on|off Turn binary output on or off. Default OFF\n"
drh453ca042017-05-22 18:00:34 +00003318 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
drhdf12f1c2015-12-07 21:46:19 +00003319 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00003320 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00003321 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00003322 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00003323 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00003324 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00003325 " If TABLE specified, only dump tables matching\n"
3326 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00003327 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00003328 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00003329 ".exit Exit this program\n"
drh700c2522016-02-09 18:39:25 +00003330 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
drh4926fec2016-04-13 15:33:42 +00003331 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003332 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003333 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003334 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003335#ifndef SQLITE_OMIT_TEST_CONTROL
3336 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3337#endif
drh0e55db12015-02-06 14:51:13 +00003338 ".indexes ?TABLE? Show names of all indexes\n"
3339 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003340 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003341#ifdef SQLITE_ENABLE_IOTRACE
3342 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3343#endif
drh1a513372015-05-02 17:40:23 +00003344 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003345 ".lint OPTIONS Report potential schema issues. Options:\n"
3346 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003347#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003348 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003349#endif
drh127f9d72010-02-23 01:47:00 +00003350 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003351 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003352 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003353 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003354 " column Left-aligned columns. (See .width)\n"
3355 " html HTML <table> code\n"
3356 " insert SQL insert statements for TABLE\n"
3357 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003358 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003359 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003360 " tabs Tab-separated values\n"
3361 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003362 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003363 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkine16a3502017-05-29 03:48:13 +00003364 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3365 " The --new option starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003366 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003367 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003368 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003369 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003370 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003371 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003372 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003373 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003374 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3375 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00003376 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00003377 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3378 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003379#if defined(SQLITE_ENABLE_SESSION)
3380 ".session CMD ... Create or control sessions\n"
3381#endif
drh1554bc82017-03-08 16:10:34 +00003382 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003383 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003384 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003385 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003386 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003387 ".tables ?TABLE? List names of tables\n"
3388 " If TABLE specified, only list tables matching\n"
3389 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003390 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003391 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003392 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003393 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003394 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003395 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003396 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003397 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003398 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003399;
3400
drhe6229612014-08-18 15:08:26 +00003401#if defined(SQLITE_ENABLE_SESSION)
3402/*
3403** Print help information for the ".sessions" command
3404*/
3405void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003406 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003407 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3408 "If ?NAME? is omitted, the first defined session is used.\n"
3409 "Subcommands:\n"
3410 " attach TABLE Attach TABLE\n"
3411 " changeset FILE Write a changeset into FILE\n"
3412 " close Close one session\n"
3413 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003414 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003415 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3416 " isempty Query whether the session is empty\n"
3417 " list List currently open session names\n"
3418 " open DB NAME Open a new session on DB\n"
3419 " patchset FILE Write a patchset into FILE\n"
3420 );
3421}
3422#endif
3423
3424
drhdaffd0e2001-04-11 14:28:42 +00003425/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003426static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003427
drh2db82112016-09-15 21:35:24 +00003428/*
dan11da0022016-12-17 08:18:05 +00003429** Read the content of file zName into memory obtained from sqlite3_malloc64()
mistachkine16a3502017-05-29 03:48:13 +00003430** and return a pointer to the buffer. The caller is responsible for freeing
3431** the memory.
drh2db82112016-09-15 21:35:24 +00003432**
dan11da0022016-12-17 08:18:05 +00003433** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3434** read.
3435**
3436** For convenience, a nul-terminator byte is always appended to the data read
3437** from the file before the buffer is returned. This byte is not included in
3438** the final value of (*pnByte), if applicable.
3439**
3440** NULL is returned if any error is encountered. The final value of *pnByte
3441** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003442*/
dan11da0022016-12-17 08:18:05 +00003443static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003444 FILE *in = fopen(zName, "rb");
3445 long nIn;
drhd1459152016-09-16 19:11:03 +00003446 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003447 char *pBuf;
3448 if( in==0 ) return 0;
3449 fseek(in, 0, SEEK_END);
3450 nIn = ftell(in);
3451 rewind(in);
drhd1459152016-09-16 19:11:03 +00003452 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003453 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003454 nRead = fread(pBuf, nIn, 1, in);
3455 fclose(in);
3456 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003457 sqlite3_free(pBuf);
3458 return 0;
3459 }
drhd1459152016-09-16 19:11:03 +00003460 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003461 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003462 return pBuf;
3463}
3464
drhba5b0932014-07-24 12:39:59 +00003465/*
3466** Implementation of the "readfile(X)" SQL function. The entire content
3467** of the file named X is read and returned as a BLOB. NULL is returned
3468** if the file does not exist or is unreadable.
3469*/
3470static void readfileFunc(
3471 sqlite3_context *context,
3472 int argc,
3473 sqlite3_value **argv
3474){
3475 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003476 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003477 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003478
drhf5ed7ad2015-06-15 14:43:25 +00003479 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003480 zName = (const char*)sqlite3_value_text(argv[0]);
3481 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003482 pBuf = readFile(zName, &nBuf);
3483 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003484}
3485
3486/*
3487** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3488** is written into file X. The number of bytes written is returned. Or
3489** NULL is returned if something goes wrong, such as being unable to open
3490** file X for writing.
3491*/
3492static void writefileFunc(
3493 sqlite3_context *context,
3494 int argc,
3495 sqlite3_value **argv
3496){
3497 FILE *out;
3498 const char *z;
drhba5b0932014-07-24 12:39:59 +00003499 sqlite3_int64 rc;
3500 const char *zFile;
3501
drhf5ed7ad2015-06-15 14:43:25 +00003502 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003503 zFile = (const char*)sqlite3_value_text(argv[0]);
3504 if( zFile==0 ) return;
3505 out = fopen(zFile, "wb");
3506 if( out==0 ) return;
3507 z = (const char*)sqlite3_value_blob(argv[1]);
3508 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003509 rc = 0;
3510 }else{
drh490fe862014-08-11 14:21:32 +00003511 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003512 }
3513 fclose(out);
3514 sqlite3_result_int64(context, rc);
3515}
drhdaffd0e2001-04-11 14:28:42 +00003516
drhe6229612014-08-18 15:08:26 +00003517#if defined(SQLITE_ENABLE_SESSION)
3518/*
3519** Close a single OpenSession object and release all of its associated
3520** resources.
3521*/
3522static void session_close(OpenSession *pSession){
3523 int i;
3524 sqlite3session_delete(pSession->p);
3525 sqlite3_free(pSession->zName);
3526 for(i=0; i<pSession->nFilter; i++){
3527 sqlite3_free(pSession->azFilter[i]);
3528 }
3529 sqlite3_free(pSession->azFilter);
3530 memset(pSession, 0, sizeof(OpenSession));
3531}
3532#endif
3533
3534/*
drh51b55a32016-04-04 12:38:05 +00003535** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003536*/
drhe6229612014-08-18 15:08:26 +00003537#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003538static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003539 int i;
3540 for(i=0; i<p->nSession; i++){
3541 session_close(&p->aSession[i]);
3542 }
3543 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003544}
drh51b55a32016-04-04 12:38:05 +00003545#else
3546# define session_close_all(X)
3547#endif
drhe6229612014-08-18 15:08:26 +00003548
drh75897232000-05-29 14:26:00 +00003549/*
drh03168ca2014-08-18 20:01:31 +00003550** Implementation of the xFilter function for an open session. Omit
3551** any tables named by ".session filter" but let all other table through.
3552*/
3553#if defined(SQLITE_ENABLE_SESSION)
3554static int session_filter(void *pCtx, const char *zTab){
3555 OpenSession *pSession = (OpenSession*)pCtx;
3556 int i;
3557 for(i=0; i<pSession->nFilter; i++){
3558 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3559 }
3560 return 1;
3561}
3562#endif
3563
3564/*
drh44c2eb12003-04-30 11:38:26 +00003565** Make sure the database is open. If it is not, then open it. If
3566** the database fails to open, print an error message and exit.
3567*/
drhdcd87a92014-08-18 13:45:42 +00003568static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003569 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003570 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003571 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003572 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003573 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003574 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003575 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003576 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003577 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003578 }
drhc2e87a32006-06-27 15:16:14 +00003579#ifndef SQLITE_OMIT_LOAD_EXTENSION
3580 sqlite3_enable_load_extension(p->db, 1);
3581#endif
mistachkin8e189222015-04-19 21:43:16 +00003582 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003583 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003584 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003585 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003586 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3587 sha3Func, 0, 0);
3588 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3589 sha3Func, 0, 0);
3590 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3591 sha3QueryFunc, 0, 0);
3592 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3593 sha3QueryFunc, 0, 0);
drh20c9c3f2017-06-15 12:21:09 +00003594 sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
3595 shellAddSchemaName, 0, 0);
3596
drh44c2eb12003-04-30 11:38:26 +00003597 }
3598}
3599
3600/*
drhfeac5f82004-08-01 00:10:45 +00003601** Do C-language style dequoting.
3602**
mistachkinf21979d2015-01-18 05:35:01 +00003603** \a -> alarm
3604** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003605** \t -> tab
3606** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003607** \v -> vertical tab
3608** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003609** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003610** \s -> space
drh4c56b992013-06-27 13:26:55 +00003611** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003612** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003613** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003614** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003615*/
3616static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003617 int i, j;
3618 char c;
drhc2ce0be2014-05-29 12:36:14 +00003619 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003620 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003621 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003622 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003623 if( c=='a' ){
3624 c = '\a';
3625 }else if( c=='b' ){
3626 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003627 }else if( c=='t' ){
3628 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003629 }else if( c=='n' ){
3630 c = '\n';
3631 }else if( c=='v' ){
3632 c = '\v';
3633 }else if( c=='f' ){
3634 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003635 }else if( c=='r' ){
3636 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003637 }else if( c=='"' ){
3638 c = '"';
3639 }else if( c=='\'' ){
3640 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003641 }else if( c=='\\' ){
3642 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003643 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003644 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003645 if( z[i+1]>='0' && z[i+1]<='7' ){
3646 i++;
3647 c = (c<<3) + z[i] - '0';
3648 if( z[i+1]>='0' && z[i+1]<='7' ){
3649 i++;
3650 c = (c<<3) + z[i] - '0';
3651 }
3652 }
3653 }
3654 }
3655 z[j] = c;
3656 }
drhc2ce0be2014-05-29 12:36:14 +00003657 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003658}
3659
3660/*
drh348d19c2013-06-03 12:47:43 +00003661** Return the value of a hexadecimal digit. Return -1 if the input
3662** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003663*/
drh348d19c2013-06-03 12:47:43 +00003664static int hexDigitValue(char c){
3665 if( c>='0' && c<='9' ) return c - '0';
3666 if( c>='a' && c<='f' ) return c - 'a' + 10;
3667 if( c>='A' && c<='F' ) return c - 'A' + 10;
3668 return -1;
drhc28490c2006-10-26 14:25:58 +00003669}
3670
3671/*
drh7d9f3942013-04-03 01:26:54 +00003672** Interpret zArg as an integer value, possibly with suffixes.
3673*/
3674static sqlite3_int64 integerValue(const char *zArg){
3675 sqlite3_int64 v = 0;
3676 static const struct { char *zSuffix; int iMult; } aMult[] = {
3677 { "KiB", 1024 },
3678 { "MiB", 1024*1024 },
3679 { "GiB", 1024*1024*1024 },
3680 { "KB", 1000 },
3681 { "MB", 1000000 },
3682 { "GB", 1000000000 },
3683 { "K", 1000 },
3684 { "M", 1000000 },
3685 { "G", 1000000000 },
3686 };
3687 int i;
3688 int isNeg = 0;
3689 if( zArg[0]=='-' ){
3690 isNeg = 1;
3691 zArg++;
3692 }else if( zArg[0]=='+' ){
3693 zArg++;
3694 }
drh348d19c2013-06-03 12:47:43 +00003695 if( zArg[0]=='0' && zArg[1]=='x' ){
3696 int x;
3697 zArg += 2;
3698 while( (x = hexDigitValue(zArg[0]))>=0 ){
3699 v = (v<<4) + x;
3700 zArg++;
3701 }
3702 }else{
3703 while( IsDigit(zArg[0]) ){
3704 v = v*10 + zArg[0] - '0';
3705 zArg++;
3706 }
drh7d9f3942013-04-03 01:26:54 +00003707 }
drhc2bed0a2013-05-24 11:57:50 +00003708 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003709 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3710 v *= aMult[i].iMult;
3711 break;
3712 }
3713 }
3714 return isNeg? -v : v;
3715}
3716
3717/*
drh348d19c2013-06-03 12:47:43 +00003718** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3719** for TRUE and FALSE. Return the integer value if appropriate.
3720*/
drhe6e1d122017-03-09 13:50:49 +00003721static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003722 int i;
3723 if( zArg[0]=='0' && zArg[1]=='x' ){
3724 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3725 }else{
3726 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3727 }
3728 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3729 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3730 return 1;
3731 }
3732 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3733 return 0;
3734 }
mistachkinaae280e2015-12-31 19:06:24 +00003735 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003736 zArg);
3737 return 0;
3738}
3739
3740/*
drhe6e1d122017-03-09 13:50:49 +00003741** Set or clear a shell flag according to a boolean value.
3742*/
3743static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3744 if( booleanValue(zArg) ){
3745 ShellSetFlag(p, mFlag);
3746 }else{
3747 ShellClearFlag(p, mFlag);
3748 }
3749}
3750
3751/*
drh42f64e52012-04-04 16:56:23 +00003752** Close an output file, assuming it is not stderr or stdout
3753*/
3754static void output_file_close(FILE *f){
3755 if( f && f!=stdout && f!=stderr ) fclose(f);
3756}
3757
3758/*
3759** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003760** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003761** filename is "off".
3762*/
3763static FILE *output_file_open(const char *zFile){
3764 FILE *f;
3765 if( strcmp(zFile,"stdout")==0 ){
3766 f = stdout;
3767 }else if( strcmp(zFile, "stderr")==0 ){
3768 f = stderr;
3769 }else if( strcmp(zFile, "off")==0 ){
3770 f = 0;
3771 }else{
3772 f = fopen(zFile, "wb");
3773 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003774 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003775 }
3776 }
3777 return f;
3778}
3779
drhd12602a2016-12-07 15:49:02 +00003780#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003781#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003782/*
3783** A routine for handling output from sqlite3_trace().
3784*/
drh4b363a52016-07-23 20:27:41 +00003785static int sql_trace_callback(
3786 unsigned mType,
3787 void *pArg,
3788 void *pP,
3789 void *pX
3790){
drh42f64e52012-04-04 16:56:23 +00003791 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003792 UNUSED_PARAMETER(mType);
3793 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003794 if( f ){
drh4b363a52016-07-23 20:27:41 +00003795 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003796 int i = (int)strlen(z);
3797 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003798 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003799 }
drh4b363a52016-07-23 20:27:41 +00003800 return 0;
drh42f64e52012-04-04 16:56:23 +00003801}
drhc10b9da2016-11-20 17:59:59 +00003802#endif
3803#endif
drh42f64e52012-04-04 16:56:23 +00003804
3805/*
drhd8621b92012-04-17 09:09:33 +00003806** A no-op routine that runs with the ".breakpoint" doc-command. This is
3807** a useful spot to set a debugger breakpoint.
3808*/
3809static void test_breakpoint(void){
3810 static int nCall = 0;
3811 nCall++;
3812}
3813
3814/*
mistachkin636bf9f2014-07-19 20:15:16 +00003815** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003816*/
mistachkin636bf9f2014-07-19 20:15:16 +00003817typedef struct ImportCtx ImportCtx;
3818struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003819 const char *zFile; /* Name of the input file */
3820 FILE *in; /* Read the CSV text from this input stream */
3821 char *z; /* Accumulated text for a field */
3822 int n; /* Number of bytes in z */
3823 int nAlloc; /* Space allocated for z[] */
3824 int nLine; /* Current line number */
drhd5fbde82017-06-26 18:42:23 +00003825 int bNotFirst; /* True if one or more bytes already read */
drhdb95f682013-06-26 22:46:00 +00003826 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003827 int cColSep; /* The column separator character. (Usually ",") */
3828 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003829};
3830
3831/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003832static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003833 if( p->n+1>=p->nAlloc ){
3834 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003835 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003836 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003837 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003838 exit(1);
3839 }
3840 }
3841 p->z[p->n++] = (char)c;
3842}
3843
3844/* Read a single field of CSV text. Compatible with rfc4180 and extended
3845** with the option of having a separator other than ",".
3846**
3847** + Input comes from p->in.
3848** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003849** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003850** + Use p->cSep as the column separator. The default is ",".
3851** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003852** + Keep track of the line number in p->nLine.
3853** + Store the character that terminates the field in p->cTerm. Store
3854** EOF on end-of-file.
3855** + Report syntax errors on stderr
3856*/
mistachkin44723ce2015-03-21 02:22:37 +00003857static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003858 int c;
3859 int cSep = p->cColSep;
3860 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003861 p->n = 0;
3862 c = fgetc(p->in);
3863 if( c==EOF || seenInterrupt ){
3864 p->cTerm = EOF;
3865 return 0;
3866 }
3867 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003868 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003869 int startLine = p->nLine;
3870 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003871 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003872 while( 1 ){
3873 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003874 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003875 if( c==cQuote ){
3876 if( pc==cQuote ){
3877 pc = 0;
3878 continue;
3879 }
3880 }
3881 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003882 || (c==rSep && pc==cQuote)
3883 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003884 || (c==EOF && pc==cQuote)
3885 ){
3886 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003887 p->cTerm = c;
3888 break;
3889 }
3890 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003891 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003892 p->zFile, p->nLine, cQuote);
3893 }
3894 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003895 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003896 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003897 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003898 break;
3899 }
mistachkin636bf9f2014-07-19 20:15:16 +00003900 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003901 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003902 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003903 }
drhdb95f682013-06-26 22:46:00 +00003904 }else{
drhd5fbde82017-06-26 18:42:23 +00003905 /* If this is the first field being parsed and it begins with the
3906 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
3907 if( (c&0xff)==0xef && p->bNotFirst==0 ){
3908 import_append_char(p, c);
3909 c = fgetc(p->in);
3910 if( (c&0xff)==0xbb ){
3911 import_append_char(p, c);
3912 c = fgetc(p->in);
3913 if( (c&0xff)==0xbf ){
3914 p->bNotFirst = 1;
3915 p->n = 0;
3916 return csv_read_one_field(p);
3917 }
3918 }
3919 }
mistachkin636bf9f2014-07-19 20:15:16 +00003920 while( c!=EOF && c!=cSep && c!=rSep ){
3921 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003922 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003923 }
mistachkin636bf9f2014-07-19 20:15:16 +00003924 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003925 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003926 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003927 }
drhdb95f682013-06-26 22:46:00 +00003928 p->cTerm = c;
3929 }
drh8dd675e2013-07-12 21:09:24 +00003930 if( p->z ) p->z[p->n] = 0;
drhd5fbde82017-06-26 18:42:23 +00003931 p->bNotFirst = 1;
drhdb95f682013-06-26 22:46:00 +00003932 return p->z;
3933}
3934
mistachkin636bf9f2014-07-19 20:15:16 +00003935/* Read a single field of ASCII delimited text.
3936**
3937** + Input comes from p->in.
3938** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003939** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003940** + Use p->cSep as the column separator. The default is "\x1F".
3941** + Use p->rSep as the row separator. The default is "\x1E".
3942** + Keep track of the row number in p->nLine.
3943** + Store the character that terminates the field in p->cTerm. Store
3944** EOF on end-of-file.
3945** + Report syntax errors on stderr
3946*/
mistachkin44723ce2015-03-21 02:22:37 +00003947static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003948 int c;
3949 int cSep = p->cColSep;
3950 int rSep = p->cRowSep;
3951 p->n = 0;
3952 c = fgetc(p->in);
3953 if( c==EOF || seenInterrupt ){
3954 p->cTerm = EOF;
3955 return 0;
3956 }
3957 while( c!=EOF && c!=cSep && c!=rSep ){
3958 import_append_char(p, c);
3959 c = fgetc(p->in);
3960 }
3961 if( c==rSep ){
3962 p->nLine++;
3963 }
3964 p->cTerm = c;
3965 if( p->z ) p->z[p->n] = 0;
3966 return p->z;
3967}
3968
drhdb95f682013-06-26 22:46:00 +00003969/*
drh4bbcf102014-02-06 02:46:08 +00003970** Try to transfer data for table zTable. If an error is seen while
3971** moving forward, try to go backwards. The backwards movement won't
3972** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003973*/
mistachkine31ae902014-02-06 01:15:29 +00003974static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003975 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003976 sqlite3 *newDb,
3977 const char *zTable
3978){
mistachkin1fe36bb2016-04-04 02:16:44 +00003979 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003980 sqlite3_stmt *pInsert = 0;
3981 char *zQuery = 0;
3982 char *zInsert = 0;
3983 int rc;
3984 int i, j, n;
3985 int nTable = (int)strlen(zTable);
3986 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003987 int cnt = 0;
3988 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003989
3990 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3991 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3992 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003993 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003994 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3995 zQuery);
3996 goto end_data_xfer;
3997 }
3998 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00003999 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00004000 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004001 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00004002 goto end_data_xfer;
4003 }
4004 sqlite3_snprintf(200+nTable,zInsert,
4005 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4006 i = (int)strlen(zInsert);
4007 for(j=1; j<n; j++){
4008 memcpy(zInsert+i, ",?", 2);
4009 i += 2;
4010 }
4011 memcpy(zInsert+i, ");", 3);
4012 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4013 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004014 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004015 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4016 zQuery);
4017 goto end_data_xfer;
4018 }
4019 for(k=0; k<2; k++){
4020 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4021 for(i=0; i<n; i++){
4022 switch( sqlite3_column_type(pQuery, i) ){
4023 case SQLITE_NULL: {
4024 sqlite3_bind_null(pInsert, i+1);
4025 break;
4026 }
4027 case SQLITE_INTEGER: {
4028 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4029 break;
4030 }
4031 case SQLITE_FLOAT: {
4032 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4033 break;
4034 }
4035 case SQLITE_TEXT: {
4036 sqlite3_bind_text(pInsert, i+1,
4037 (const char*)sqlite3_column_text(pQuery,i),
4038 -1, SQLITE_STATIC);
4039 break;
4040 }
4041 case SQLITE_BLOB: {
4042 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4043 sqlite3_column_bytes(pQuery,i),
4044 SQLITE_STATIC);
4045 break;
4046 }
4047 }
4048 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00004049 rc = sqlite3_step(pInsert);
4050 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00004051 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00004052 sqlite3_errmsg(newDb));
4053 }
drh3350ce92014-02-06 00:49:12 +00004054 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00004055 cnt++;
4056 if( (cnt%spinRate)==0 ){
4057 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4058 fflush(stdout);
4059 }
drh3350ce92014-02-06 00:49:12 +00004060 } /* End while */
4061 if( rc==SQLITE_DONE ) break;
4062 sqlite3_finalize(pQuery);
4063 sqlite3_free(zQuery);
4064 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4065 zTable);
4066 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4067 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004068 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00004069 break;
drh3350ce92014-02-06 00:49:12 +00004070 }
4071 } /* End for(k=0...) */
4072
4073end_data_xfer:
4074 sqlite3_finalize(pQuery);
4075 sqlite3_finalize(pInsert);
4076 sqlite3_free(zQuery);
4077 sqlite3_free(zInsert);
4078}
4079
4080
4081/*
4082** Try to transfer all rows of the schema that match zWhere. For
4083** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00004084** If an error is encountered while moving forward through the
4085** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00004086*/
mistachkine31ae902014-02-06 01:15:29 +00004087static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00004088 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00004089 sqlite3 *newDb,
4090 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00004091 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00004092){
4093 sqlite3_stmt *pQuery = 0;
4094 char *zQuery = 0;
4095 int rc;
4096 const unsigned char *zName;
4097 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00004098 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00004099
4100 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4101 " WHERE %s", zWhere);
4102 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4103 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004104 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004105 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4106 zQuery);
4107 goto end_schema_xfer;
4108 }
4109 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4110 zName = sqlite3_column_text(pQuery, 0);
4111 zSql = sqlite3_column_text(pQuery, 1);
4112 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004113 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4114 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004115 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004116 sqlite3_free(zErrMsg);
4117 zErrMsg = 0;
4118 }
drh3350ce92014-02-06 00:49:12 +00004119 if( xForEach ){
4120 xForEach(p, newDb, (const char*)zName);
4121 }
4122 printf("done\n");
4123 }
4124 if( rc!=SQLITE_DONE ){
4125 sqlite3_finalize(pQuery);
4126 sqlite3_free(zQuery);
4127 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4128 " WHERE %s ORDER BY rowid DESC", zWhere);
4129 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4130 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004131 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004132 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4133 zQuery);
4134 goto end_schema_xfer;
4135 }
4136 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4137 zName = sqlite3_column_text(pQuery, 0);
4138 zSql = sqlite3_column_text(pQuery, 1);
4139 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004140 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4141 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004142 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004143 sqlite3_free(zErrMsg);
4144 zErrMsg = 0;
4145 }
drh3350ce92014-02-06 00:49:12 +00004146 if( xForEach ){
4147 xForEach(p, newDb, (const char*)zName);
4148 }
4149 printf("done\n");
4150 }
4151 }
4152end_schema_xfer:
4153 sqlite3_finalize(pQuery);
4154 sqlite3_free(zQuery);
4155}
4156
4157/*
4158** Open a new database file named "zNewDb". Try to recover as much information
4159** as possible out of the main database (which might be corrupt) and write it
4160** into zNewDb.
4161*/
drhdcd87a92014-08-18 13:45:42 +00004162static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00004163 int rc;
4164 sqlite3 *newDb = 0;
4165 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004166 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00004167 return;
4168 }
4169 rc = sqlite3_open(zNewDb, &newDb);
4170 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004171 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00004172 sqlite3_errmsg(newDb));
4173 }else{
drh54d0d2d2014-04-03 00:32:13 +00004174 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004175 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00004176 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4177 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00004178 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00004179 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004180 }
4181 sqlite3_close(newDb);
4182}
4183
4184/*
drhc2ce0be2014-05-29 12:36:14 +00004185** Change the output file back to stdout
4186*/
drhdcd87a92014-08-18 13:45:42 +00004187static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00004188 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004189#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00004190 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004191#endif
drhc2ce0be2014-05-29 12:36:14 +00004192 }else{
4193 output_file_close(p->out);
4194 }
4195 p->outfile[0] = 0;
4196 p->out = stdout;
4197}
4198
4199/*
drhf7502f02015-02-06 14:19:44 +00004200** Run an SQL command and return the single integer result.
4201*/
4202static int db_int(ShellState *p, const char *zSql){
4203 sqlite3_stmt *pStmt;
4204 int res = 0;
4205 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4206 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4207 res = sqlite3_column_int(pStmt,0);
4208 }
4209 sqlite3_finalize(pStmt);
4210 return res;
4211}
4212
4213/*
4214** Convert a 2-byte or 4-byte big-endian integer into a native integer
4215*/
drha0620ac2016-07-13 13:05:13 +00004216static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004217 return (a[0]<<8) + a[1];
4218}
drha0620ac2016-07-13 13:05:13 +00004219static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004220 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4221}
4222
4223/*
4224** Implementation of the ".info" command.
4225**
4226** Return 1 on error, 2 to exit, and 0 otherwise.
4227*/
drh0e55db12015-02-06 14:51:13 +00004228static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004229 static const struct { const char *zName; int ofst; } aField[] = {
4230 { "file change counter:", 24 },
4231 { "database page count:", 28 },
4232 { "freelist page count:", 36 },
4233 { "schema cookie:", 40 },
4234 { "schema format:", 44 },
4235 { "default cache size:", 48 },
4236 { "autovacuum top root:", 52 },
4237 { "incremental vacuum:", 64 },
4238 { "text encoding:", 56 },
4239 { "user version:", 60 },
4240 { "application id:", 68 },
4241 { "software version:", 96 },
4242 };
drh0e55db12015-02-06 14:51:13 +00004243 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4244 { "number of tables:",
4245 "SELECT count(*) FROM %s WHERE type='table'" },
4246 { "number of indexes:",
4247 "SELECT count(*) FROM %s WHERE type='index'" },
4248 { "number of triggers:",
4249 "SELECT count(*) FROM %s WHERE type='trigger'" },
4250 { "number of views:",
4251 "SELECT count(*) FROM %s WHERE type='view'" },
4252 { "schema size:",
4253 "SELECT total(length(sql)) FROM %s" },
4254 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004255 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004256 int i;
4257 char *zSchemaTab;
4258 char *zDb = nArg>=2 ? azArg[1] : "main";
4259 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004260 open_db(p, 0);
4261 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004262 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004263 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4264 return 1;
4265 }
4266 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4267 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004268 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004269 return 1;
4270 }
4271 i = get2byteInt(aHdr+16);
4272 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004273 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4274 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4275 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4276 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004277 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004278 int ofst = aField[i].ofst;
4279 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004280 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004281 switch( ofst ){
4282 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004283 if( val==1 ) raw_printf(p->out, " (utf8)");
4284 if( val==2 ) raw_printf(p->out, " (utf16le)");
4285 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004286 }
4287 }
mistachkinaae280e2015-12-31 19:06:24 +00004288 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004289 }
drh0e55db12015-02-06 14:51:13 +00004290 if( zDb==0 ){
4291 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4292 }else if( strcmp(zDb,"temp")==0 ){
4293 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4294 }else{
4295 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4296 }
drhf5ed7ad2015-06-15 14:43:25 +00004297 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004298 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4299 int val = db_int(p, zSql);
4300 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004301 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004302 }
4303 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004304 return 0;
4305}
4306
dand95bb392015-09-30 11:19:05 +00004307/*
4308** Print the current sqlite3_errmsg() value to stderr and return 1.
4309*/
4310static int shellDatabaseError(sqlite3 *db){
4311 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004312 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004313 return 1;
4314}
4315
4316/*
4317** Print an out-of-memory message to stderr and return 1.
4318*/
4319static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004320 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004321 return 1;
4322}
drhf7502f02015-02-06 14:19:44 +00004323
drh2db82112016-09-15 21:35:24 +00004324/*
4325** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4326** if they match and FALSE (0) if they do not match.
4327**
4328** Globbing rules:
4329**
4330** '*' Matches any sequence of zero or more characters.
4331**
4332** '?' Matches exactly one character.
4333**
4334** [...] Matches one character from the enclosed list of
4335** characters.
4336**
4337** [^...] Matches one character not in the enclosed list.
4338**
4339** '#' Matches any sequence of one or more digits with an
4340** optional + or - sign in front
4341**
4342** ' ' Any span of whitespace matches any other span of
4343** whitespace.
4344**
4345** Extra whitespace at the end of z[] is ignored.
4346*/
4347static int testcase_glob(const char *zGlob, const char *z){
4348 int c, c2;
4349 int invert;
4350 int seen;
4351
4352 while( (c = (*(zGlob++)))!=0 ){
4353 if( IsSpace(c) ){
4354 if( !IsSpace(*z) ) return 0;
4355 while( IsSpace(*zGlob) ) zGlob++;
4356 while( IsSpace(*z) ) z++;
4357 }else if( c=='*' ){
4358 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4359 if( c=='?' && (*(z++))==0 ) return 0;
4360 }
4361 if( c==0 ){
4362 return 1;
4363 }else if( c=='[' ){
4364 while( *z && testcase_glob(zGlob-1,z)==0 ){
4365 z++;
4366 }
4367 return (*z)!=0;
4368 }
4369 while( (c2 = (*(z++)))!=0 ){
4370 while( c2!=c ){
4371 c2 = *(z++);
4372 if( c2==0 ) return 0;
4373 }
4374 if( testcase_glob(zGlob,z) ) return 1;
4375 }
4376 return 0;
4377 }else if( c=='?' ){
4378 if( (*(z++))==0 ) return 0;
4379 }else if( c=='[' ){
4380 int prior_c = 0;
4381 seen = 0;
4382 invert = 0;
4383 c = *(z++);
4384 if( c==0 ) return 0;
4385 c2 = *(zGlob++);
4386 if( c2=='^' ){
4387 invert = 1;
4388 c2 = *(zGlob++);
4389 }
4390 if( c2==']' ){
4391 if( c==']' ) seen = 1;
4392 c2 = *(zGlob++);
4393 }
4394 while( c2 && c2!=']' ){
4395 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4396 c2 = *(zGlob++);
4397 if( c>=prior_c && c<=c2 ) seen = 1;
4398 prior_c = 0;
4399 }else{
4400 if( c==c2 ){
4401 seen = 1;
4402 }
4403 prior_c = c2;
4404 }
4405 c2 = *(zGlob++);
4406 }
4407 if( c2==0 || (seen ^ invert)==0 ) return 0;
4408 }else if( c=='#' ){
4409 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4410 if( !IsDigit(z[0]) ) return 0;
4411 z++;
4412 while( IsDigit(z[0]) ){ z++; }
4413 }else{
4414 if( c!=(*(z++)) ) return 0;
4415 }
4416 }
4417 while( IsSpace(*z) ){ z++; }
4418 return *z==0;
4419}
drh2db82112016-09-15 21:35:24 +00004420
4421
drhf7502f02015-02-06 14:19:44 +00004422/*
drh4926fec2016-04-13 15:33:42 +00004423** Compare the string as a command-line option with either one or two
4424** initial "-" characters.
4425*/
4426static int optionMatch(const char *zStr, const char *zOpt){
4427 if( zStr[0]!='-' ) return 0;
4428 zStr++;
4429 if( zStr[0]=='-' ) zStr++;
4430 return strcmp(zStr, zOpt)==0;
4431}
4432
4433/*
drhcd0509e2016-09-16 00:26:08 +00004434** Delete a file.
4435*/
4436int shellDeleteFile(const char *zFilename){
4437 int rc;
4438#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004439 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004440 rc = _wunlink(z);
4441 sqlite3_free(z);
4442#else
4443 rc = unlink(zFilename);
4444#endif
4445 return rc;
4446}
4447
dan35ac58e2016-12-14 19:28:27 +00004448
dan35ac58e2016-12-14 19:28:27 +00004449/*
dandd9e0be2016-12-16 16:44:27 +00004450** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004451** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004452** called with four arguments - the parent table name, the parent column name,
4453** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004454**
4455** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4456**
4457** If either of the named tables or columns do not exist, this function
mistachkine16a3502017-05-29 03:48:13 +00004458** returns an empty string. An empty string is also returned if both tables
dan35ac58e2016-12-14 19:28:27 +00004459** and columns exist but have the same default collation sequence. Or,
4460** if both exist but the default collation sequences are different, this
4461** function returns the string " COLLATE <parent-collation>", where
4462** <parent-collation> is the default collation sequence of the parent column.
4463*/
4464static void shellFkeyCollateClause(
mistachkine16a3502017-05-29 03:48:13 +00004465 sqlite3_context *pCtx,
4466 int nVal,
dan35ac58e2016-12-14 19:28:27 +00004467 sqlite3_value **apVal
4468){
4469 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4470 const char *zParent;
4471 const char *zParentCol;
4472 const char *zParentSeq;
4473 const char *zChild;
4474 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004475 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004476 int rc;
mistachkine16a3502017-05-29 03:48:13 +00004477
dan35ac58e2016-12-14 19:28:27 +00004478 assert( nVal==4 );
4479 zParent = (const char*)sqlite3_value_text(apVal[0]);
4480 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4481 zChild = (const char*)sqlite3_value_text(apVal[2]);
4482 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4483
4484 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4485 rc = sqlite3_table_column_metadata(
4486 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4487 );
4488 if( rc==SQLITE_OK ){
4489 rc = sqlite3_table_column_metadata(
4490 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4491 );
4492 }
4493
4494 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4495 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4496 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4497 sqlite3_free(z);
4498 }
4499}
4500
4501
4502/*
dan3c7ebeb2016-12-16 17:28:56 +00004503** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004504*/
dan3c7ebeb2016-12-16 17:28:56 +00004505static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004506 ShellState *pState, /* Current shell tool state */
4507 char **azArg, /* Array of arguments passed to dot command */
4508 int nArg /* Number of entries in azArg[] */
4509){
dandd9e0be2016-12-16 16:44:27 +00004510 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4511 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004512 int bVerbose = 0; /* If -verbose is present */
4513 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004514 int i; /* To iterate through azArg[] */
4515 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4516 int rc; /* Return code */
4517 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004518
dandd9e0be2016-12-16 16:44:27 +00004519 /*
4520 ** This SELECT statement returns one row for each foreign key constraint
4521 ** in the schema of the main database. The column values are:
4522 **
4523 ** 0. The text of an SQL statement similar to:
4524 **
4525 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4526 **
4527 ** This is the same SELECT that the foreign keys implementation needs
4528 ** to run internally on child tables. If there is an index that can
4529 ** be used to optimize this query, then it can also be used by the FK
4530 ** implementation to optimize DELETE or UPDATE statements on the parent
4531 ** table.
4532 **
4533 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4534 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4535 ** contains an index that can be used to optimize the query.
4536 **
4537 ** 2. Human readable text that describes the child table and columns. e.g.
4538 **
4539 ** "child_table(child_key1, child_key2)"
4540 **
4541 ** 3. Human readable text that describes the parent table and columns. e.g.
4542 **
4543 ** "parent_table(parent_key1, parent_key2)"
4544 **
4545 ** 4. A full CREATE INDEX statement for an index that could be used to
4546 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4547 **
4548 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4549 **
4550 ** 5. The name of the parent table.
4551 **
4552 ** These six values are used by the C logic below to generate the report.
4553 */
dan35ac58e2016-12-14 19:28:27 +00004554 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004555 "SELECT "
4556 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4557 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00004558 " || fkey_collate_clause("
4559 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004560 ", "
dandd9e0be2016-12-16 16:44:27 +00004561 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004562 " || group_concat('*=?', ' AND ') || ')'"
4563 ", "
dandd9e0be2016-12-16 16:44:27 +00004564 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004565 ", "
dan50da9382017-04-06 12:06:56 +00004566 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00004567 ", "
dandd9e0be2016-12-16 16:44:27 +00004568 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4569 " || ' ON ' || quote(s.name) || '('"
4570 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00004571 " fkey_collate_clause("
4572 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004573 " || ');'"
danf9647b62016-12-15 06:01:40 +00004574 ", "
dandd9e0be2016-12-16 16:44:27 +00004575 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00004576 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00004577 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00004578 "GROUP BY s.name, f.id "
4579 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004580 ;
dan54e2efc2017-04-06 14:56:26 +00004581 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00004582
dan3c7ebeb2016-12-16 17:28:56 +00004583 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004584 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004585 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4586 bVerbose = 1;
4587 }
4588 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4589 bGroupByParent = 1;
4590 zIndent = " ";
4591 }
4592 else{
dan3c7ebeb2016-12-16 17:28:56 +00004593 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4594 azArg[0], azArg[1]
4595 );
danf9647b62016-12-15 06:01:40 +00004596 return SQLITE_ERROR;
4597 }
dan35ac58e2016-12-14 19:28:27 +00004598 }
mistachkine16a3502017-05-29 03:48:13 +00004599
dan35ac58e2016-12-14 19:28:27 +00004600 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004601 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4602 0, shellFkeyCollateClause, 0, 0
4603 );
dan35ac58e2016-12-14 19:28:27 +00004604
4605
4606 if( rc==SQLITE_OK ){
4607 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4608 }
danf9647b62016-12-15 06:01:40 +00004609 if( rc==SQLITE_OK ){
4610 sqlite3_bind_int(pSql, 1, bGroupByParent);
4611 }
dan35ac58e2016-12-14 19:28:27 +00004612
4613 if( rc==SQLITE_OK ){
4614 int rc2;
danf9647b62016-12-15 06:01:40 +00004615 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004616 while( SQLITE_ROW==sqlite3_step(pSql) ){
4617 int res = -1;
4618 sqlite3_stmt *pExplain = 0;
4619 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4620 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4621 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4622 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4623 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004624 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004625
4626 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4627 if( rc!=SQLITE_OK ) break;
4628 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4629 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00004630 res = (
4631 0==sqlite3_strglob(zGlob, zPlan)
4632 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4633 );
dan35ac58e2016-12-14 19:28:27 +00004634 }
4635 rc = sqlite3_finalize(pExplain);
4636 if( rc!=SQLITE_OK ) break;
4637
4638 if( res<0 ){
4639 raw_printf(stderr, "Error: internal error");
4640 break;
danf9647b62016-12-15 06:01:40 +00004641 }else{
mistachkine16a3502017-05-29 03:48:13 +00004642 if( bGroupByParent
danf9647b62016-12-15 06:01:40 +00004643 && (bVerbose || res==0)
mistachkine16a3502017-05-29 03:48:13 +00004644 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
danf9647b62016-12-15 06:01:40 +00004645 ){
4646 raw_printf(out, "-- Parent table %s\n", zParent);
4647 sqlite3_free(zPrev);
4648 zPrev = sqlite3_mprintf("%s", zParent);
4649 }
4650
4651 if( res==0 ){
4652 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4653 }else if( bVerbose ){
mistachkine16a3502017-05-29 03:48:13 +00004654 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
danf9647b62016-12-15 06:01:40 +00004655 zIndent, zFrom, zTarget
4656 );
4657 }
dan35ac58e2016-12-14 19:28:27 +00004658 }
4659 }
danf9647b62016-12-15 06:01:40 +00004660 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004661
4662 if( rc!=SQLITE_OK ){
4663 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4664 }
4665
4666 rc2 = sqlite3_finalize(pSql);
4667 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4668 rc = rc2;
4669 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4670 }
4671 }else{
4672 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4673 }
4674
4675 return rc;
4676}
dan3c7ebeb2016-12-16 17:28:56 +00004677
dan35ac58e2016-12-14 19:28:27 +00004678/*
dan3c7ebeb2016-12-16 17:28:56 +00004679** Implementation of ".lint" dot command.
4680*/
4681static int lintDotCommand(
4682 ShellState *pState, /* Current shell tool state */
4683 char **azArg, /* Array of arguments passed to dot command */
4684 int nArg /* Number of entries in azArg[] */
4685){
4686 int n;
drh96ada592016-12-29 19:48:46 +00004687 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004688 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4689 return lintFkeyIndexes(pState, azArg, nArg);
4690
4691 usage:
4692 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4693 raw_printf(stderr, "Where sub-commands are:\n");
4694 raw_printf(stderr, " fkey-indexes\n");
4695 return SQLITE_ERROR;
4696}
4697
dan35ac58e2016-12-14 19:28:27 +00004698
drhcd0509e2016-09-16 00:26:08 +00004699/*
drh75897232000-05-29 14:26:00 +00004700** If an input line begins with "." then invoke this routine to
4701** process that line.
drh67505e72002-04-19 12:34:06 +00004702**
drh47ad6842006-11-08 12:25:42 +00004703** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004704*/
drhdcd87a92014-08-18 13:45:42 +00004705static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004706 int h = 1;
drh75897232000-05-29 14:26:00 +00004707 int nArg = 0;
4708 int n, c;
drh67505e72002-04-19 12:34:06 +00004709 int rc = 0;
drh75897232000-05-29 14:26:00 +00004710 char *azArg[50];
4711
4712 /* Parse the input line into tokens.
4713 */
mistachkin8e189222015-04-19 21:43:16 +00004714 while( zLine[h] && nArg<ArraySize(azArg) ){
4715 while( IsSpace(zLine[h]) ){ h++; }
4716 if( zLine[h]==0 ) break;
4717 if( zLine[h]=='\'' || zLine[h]=='"' ){
4718 int delim = zLine[h++];
4719 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004720 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004721 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004722 h++;
drh4c56b992013-06-27 13:26:55 +00004723 }
mistachkin8e189222015-04-19 21:43:16 +00004724 if( zLine[h]==delim ){
4725 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004726 }
drhfeac5f82004-08-01 00:10:45 +00004727 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004728 }else{
mistachkin8e189222015-04-19 21:43:16 +00004729 azArg[nArg++] = &zLine[h];
4730 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4731 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004732 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004733 }
4734 }
4735
4736 /* Process the input line.
4737 */
shane9bd1b442009-10-23 01:27:39 +00004738 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004739 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004740 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004741
drha0daa752016-09-16 11:53:10 +00004742#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004743 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4744 if( nArg!=2 ){
4745 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4746 rc = 1;
4747 goto meta_command_exit;
4748 }
4749 open_db(p, 0);
4750 if( booleanValue(azArg[1]) ){
4751 sqlite3_set_authorizer(p->db, shellAuth, p);
4752 }else{
4753 sqlite3_set_authorizer(p->db, 0, 0);
4754 }
4755 }else
drha0daa752016-09-16 11:53:10 +00004756#endif
drhde613c62016-04-04 17:23:10 +00004757
drh5c7976f2014-02-10 19:59:27 +00004758 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4759 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4760 ){
drhbc46f022013-01-23 18:53:23 +00004761 const char *zDestFile = 0;
4762 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004763 sqlite3 *pDest;
4764 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004765 int j;
4766 for(j=1; j<nArg; j++){
4767 const char *z = azArg[j];
4768 if( z[0]=='-' ){
4769 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004770 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004771 {
mistachkinaae280e2015-12-31 19:06:24 +00004772 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004773 return 1;
4774 }
4775 }else if( zDestFile==0 ){
4776 zDestFile = azArg[j];
4777 }else if( zDb==0 ){
4778 zDb = zDestFile;
4779 zDestFile = azArg[j];
4780 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004781 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004782 return 1;
4783 }
drh9ff849f2009-02-04 20:55:57 +00004784 }
drhbc46f022013-01-23 18:53:23 +00004785 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004786 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004787 return 1;
4788 }
4789 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004790 rc = sqlite3_open(zDestFile, &pDest);
4791 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004792 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004793 sqlite3_close(pDest);
4794 return 1;
4795 }
drh05782482013-10-24 15:20:20 +00004796 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004797 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4798 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004799 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004800 sqlite3_close(pDest);
4801 return 1;
4802 }
4803 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4804 sqlite3_backup_finish(pBackup);
4805 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004806 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004807 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004808 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004809 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004810 }
4811 sqlite3_close(pDest);
4812 }else
4813
drhc2ce0be2014-05-29 12:36:14 +00004814 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4815 if( nArg==2 ){
4816 bail_on_error = booleanValue(azArg[1]);
4817 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004818 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004819 rc = 1;
4820 }
drhc49f44e2006-10-26 18:15:42 +00004821 }else
4822
mistachkinf21979d2015-01-18 05:35:01 +00004823 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4824 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004825 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004826 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004827 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004828 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004829 }
mistachkinf21979d2015-01-18 05:35:01 +00004830 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004831 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004832 rc = 1;
4833 }
4834 }else
4835
drh453ca042017-05-22 18:00:34 +00004836 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4837 if( nArg==2 ){
4838#if defined(_WIN32) || defined(WIN32)
4839 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4840 rc = !SetCurrentDirectoryW(z);
4841 sqlite3_free(z);
4842#else
4843 rc = chdir(azArg[1]);
4844#endif
4845 if( rc ){
4846 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4847 rc = 1;
4848 }
4849 }else{
4850 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4851 rc = 1;
4852 }
4853 }else
4854
drhd8621b92012-04-17 09:09:33 +00004855 /* The undocumented ".breakpoint" command causes a call to the no-op
4856 ** routine named test_breakpoint().
4857 */
4858 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4859 test_breakpoint();
4860 }else
4861
drhdf12f1c2015-12-07 21:46:19 +00004862 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4863 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004864 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004865 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004866 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004867 rc = 1;
4868 }
4869 }else
4870
drh2db82112016-09-15 21:35:24 +00004871 /* Cancel output redirection, if it is currently set (by .testcase)
4872 ** Then read the content of the testcase-out.txt file and compare against
4873 ** azArg[1]. If there are differences, report an error and exit.
4874 */
4875 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4876 char *zRes = 0;
4877 output_reset(p);
4878 if( nArg!=2 ){
4879 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004880 rc = 2;
dan11da0022016-12-17 08:18:05 +00004881 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004882 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4883 rc = 2;
4884 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004885 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004886 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4887 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004888 rc = 2;
drh760c8162016-09-16 02:52:22 +00004889 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004890 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004891 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004892 }
4893 sqlite3_free(zRes);
4894 }else
drh2db82112016-09-15 21:35:24 +00004895
drhc2ce0be2014-05-29 12:36:14 +00004896 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4897 if( nArg==2 ){
4898 tryToClone(p, azArg[1]);
4899 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004900 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004901 rc = 1;
4902 }
mistachkine31ae902014-02-06 01:15:29 +00004903 }else
4904
drhc2ce0be2014-05-29 12:36:14 +00004905 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004906 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004907 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004908 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004909 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004910 data.showHeader = 0;
4911 data.cMode = data.mode = MODE_List;
4912 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004913 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004914 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4915 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004916 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004917 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004918 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004919 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004920 }
4921 }else
4922
drh0e55db12015-02-06 14:51:13 +00004923 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4924 rc = shell_dbinfo_command(p, nArg, azArg);
4925 }else
4926
drhc2ce0be2014-05-29 12:36:14 +00004927 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004928 const char *zLike = 0;
4929 int i;
drh72507d42017-04-08 00:55:13 +00004930 int savedShowHeader = p->showHeader;
drhe6e1d122017-03-09 13:50:49 +00004931 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004932 for(i=1; i<nArg; i++){
4933 if( azArg[i][0]=='-' ){
4934 const char *z = azArg[i]+1;
4935 if( z[0]=='-' ) z++;
4936 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00004937#ifdef SQLITE_OMIT_VIRTUALTABLE
4938 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4939 " with SQLITE_OMIT_VIRTUALTABLE\n");
4940 rc = 1;
4941 goto meta_command_exit;
4942#else
drhe6e1d122017-03-09 13:50:49 +00004943 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00004944#endif
drhe611f142017-03-08 11:44:00 +00004945 }else
4946 {
4947 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4948 rc = 1;
4949 goto meta_command_exit;
4950 }
4951 }else if( zLike ){
4952 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4953 rc = 1;
4954 goto meta_command_exit;
4955 }else{
4956 zLike = azArg[i];
4957 }
4958 }
drh05782482013-10-24 15:20:20 +00004959 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004960 /* When playing back a "dump", the content might appear in an order
4961 ** which causes immediate foreign key constraints to be violated.
4962 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004963 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4964 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004965 p->writableSchema = 0;
drh72507d42017-04-08 00:55:13 +00004966 p->showHeader = 0;
drhe611f142017-03-08 11:44:00 +00004967 /* Set writable_schema=ON since doing so forces SQLite to initialize
4968 ** as much of the schema as it can even if the sqlite_master table is
4969 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004970 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004971 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004972 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004973 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004974 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004975 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004976 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004977 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004978 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004979 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004980 );
drh2f464a02011-10-13 00:41:49 +00004981 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004982 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004983 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004984 );
drh4c653a02000-06-07 01:27:47 +00004985 }else{
drhe611f142017-03-08 11:44:00 +00004986 char *zSql;
4987 zSql = sqlite3_mprintf(
4988 "SELECT name, type, sql FROM sqlite_master "
4989 "WHERE tbl_name LIKE %Q AND type=='table'"
4990 " AND sql NOT NULL", zLike);
4991 run_schema_dump_query(p,zSql);
4992 sqlite3_free(zSql);
4993 zSql = sqlite3_mprintf(
4994 "SELECT sql FROM sqlite_master "
4995 "WHERE sql NOT NULL"
4996 " AND type IN ('index','trigger','view')"
4997 " AND tbl_name LIKE %Q", zLike);
4998 run_table_dump_query(p, zSql, 0);
4999 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00005000 }
drh45e29d82006-11-20 16:21:10 +00005001 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00005002 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00005003 p->writableSchema = 0;
5004 }
drh56197952011-10-13 16:30:13 +00005005 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5006 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00005007 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh72507d42017-04-08 00:55:13 +00005008 p->showHeader = savedShowHeader;
drh4c653a02000-06-07 01:27:47 +00005009 }else
drh75897232000-05-29 14:26:00 +00005010
drhc2ce0be2014-05-29 12:36:14 +00005011 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5012 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00005013 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005014 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005015 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005016 rc = 1;
5017 }
drhdaffd0e2001-04-11 14:28:42 +00005018 }else
5019
drhc2ce0be2014-05-29 12:36:14 +00005020 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5021 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00005022 if( strcmp(azArg[1],"full")==0 ){
5023 p->autoEQP = 2;
5024 }else{
5025 p->autoEQP = booleanValue(azArg[1]);
5026 }
drhc2ce0be2014-05-29 12:36:14 +00005027 }else{
drheacd29d2016-04-15 15:03:27 +00005028 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00005029 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00005030 }
drhefbf3b12014-02-28 20:47:24 +00005031 }else
5032
drhd3ac7d92013-01-25 18:33:43 +00005033 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00005034 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00005035 rc = 2;
drh75897232000-05-29 14:26:00 +00005036 }else
5037
drhc2ce0be2014-05-29 12:36:14 +00005038 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00005039 int val = 1;
5040 if( nArg>=2 ){
5041 if( strcmp(azArg[1],"auto")==0 ){
5042 val = 99;
5043 }else{
5044 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00005045 }
drh700c2522016-02-09 18:39:25 +00005046 }
5047 if( val==1 && p->mode!=MODE_Explain ){
5048 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00005049 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00005050 p->autoExplain = 0;
5051 }else if( val==0 ){
5052 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5053 p->autoExplain = 0;
5054 }else if( val==99 ){
5055 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5056 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005057 }
drh75897232000-05-29 14:26:00 +00005058 }else
5059
drhc1971542014-06-23 23:28:13 +00005060 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005061 ShellState data;
drhc1971542014-06-23 23:28:13 +00005062 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00005063 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00005064 memcpy(&data, p, sizeof(data));
5065 data.showHeader = 0;
5066 data.cMode = data.mode = MODE_Semi;
5067 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5068 data.cMode = data.mode = MODE_Pretty;
5069 nArg = 1;
5070 }
drhc1971542014-06-23 23:28:13 +00005071 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00005072 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00005073 rc = 1;
5074 goto meta_command_exit;
5075 }
5076 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00005077 rc = sqlite3_exec(p->db,
5078 "SELECT sql FROM"
5079 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5080 " FROM sqlite_master UNION ALL"
5081 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005082 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00005083 "ORDER BY rowid",
5084 callback, &data, &zErrMsg
5085 );
drh56f674c2014-07-18 14:43:29 +00005086 if( rc==SQLITE_OK ){
5087 sqlite3_stmt *pStmt;
5088 rc = sqlite3_prepare_v2(p->db,
5089 "SELECT rowid FROM sqlite_master"
5090 " WHERE name GLOB 'sqlite_stat[134]'",
5091 -1, &pStmt, 0);
5092 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5093 sqlite3_finalize(pStmt);
5094 }
5095 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005096 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00005097 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005098 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005099 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5100 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00005101 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00005102 data.zDestTable = "sqlite_stat1";
5103 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5104 shell_callback, &data,&zErrMsg);
5105 data.zDestTable = "sqlite_stat3";
5106 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5107 shell_callback, &data,&zErrMsg);
5108 data.zDestTable = "sqlite_stat4";
5109 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5110 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00005111 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005112 }
drhc1971542014-06-23 23:28:13 +00005113 }else
5114
drhc2ce0be2014-05-29 12:36:14 +00005115 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5116 if( nArg==2 ){
5117 p->showHeader = booleanValue(azArg[1]);
5118 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005119 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005120 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00005121 }
drh75897232000-05-29 14:26:00 +00005122 }else
5123
drhc2ce0be2014-05-29 12:36:14 +00005124 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005125 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00005126 }else
5127
5128 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00005129 char *zTable; /* Insert data into this table */
5130 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00005131 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00005132 int nCol; /* Number of columns in the table */
5133 int nByte; /* Number of bytes in an SQL string */
5134 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00005135 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00005136 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00005137 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00005138 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00005139 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5140 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00005141
drhc2ce0be2014-05-29 12:36:14 +00005142 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005143 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00005144 goto meta_command_exit;
5145 }
drh01f37542014-05-31 15:43:33 +00005146 zFile = azArg[1];
5147 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00005148 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00005149 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00005150 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005151 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00005152 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005153 raw_printf(stderr,
5154 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00005155 return 1;
drhfeac5f82004-08-01 00:10:45 +00005156 }
drhdb95f682013-06-26 22:46:00 +00005157 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005158 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00005159 " for import\n");
5160 return 1;
5161 }
mistachkin636bf9f2014-07-19 20:15:16 +00005162 nSep = strlen30(p->rowSeparator);
5163 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005164 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005165 return 1;
5166 }
mistachkine0d68852014-12-11 03:12:33 +00005167 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5168 /* When importing CSV (only), if the row separator is set to the
5169 ** default output row separator, change it to the default input
5170 ** row separator. This avoids having to maintain different input
5171 ** and output row separators. */
5172 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5173 nSep = strlen30(p->rowSeparator);
5174 }
mistachkin636bf9f2014-07-19 20:15:16 +00005175 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005176 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00005177 " for import\n");
5178 return 1;
5179 }
5180 sCtx.zFile = zFile;
5181 sCtx.nLine = 1;
5182 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005183#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005184 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005185 return 1;
5186#else
mistachkin636bf9f2014-07-19 20:15:16 +00005187 sCtx.in = popen(sCtx.zFile+1, "r");
5188 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00005189 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00005190#endif
drh5bde8162013-06-27 14:07:53 +00005191 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00005192 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00005193 xCloser = fclose;
5194 }
mistachkin636bf9f2014-07-19 20:15:16 +00005195 if( p->mode==MODE_Ascii ){
5196 xRead = ascii_read_one_field;
5197 }else{
5198 xRead = csv_read_one_field;
5199 }
5200 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005201 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00005202 return 1;
5203 }
mistachkin636bf9f2014-07-19 20:15:16 +00005204 sCtx.cColSep = p->colSeparator[0];
5205 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00005206 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00005207 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005208 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005209 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005210 return 1;
5211 }
drh4f21c4a2008-12-10 22:15:00 +00005212 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005213 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005214 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005215 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005216 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5217 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005218 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005219 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005220 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005221 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005222 }
drh5bde8162013-06-27 14:07:53 +00005223 if( cSep=='(' ){
5224 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005225 sqlite3_free(sCtx.z);
5226 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005227 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005228 return 1;
5229 }
drhdb95f682013-06-26 22:46:00 +00005230 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5231 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5232 sqlite3_free(zCreate);
5233 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005234 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005235 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005236 sqlite3_free(sCtx.z);
5237 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005238 return 1;
5239 }
drhc7181902014-02-27 15:04:13 +00005240 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005241 }
drhfeac5f82004-08-01 00:10:45 +00005242 sqlite3_free(zSql);
5243 if( rc ){
shane916f9612009-10-23 00:37:15 +00005244 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005245 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005246 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005247 return 1;
drhfeac5f82004-08-01 00:10:45 +00005248 }
shane916f9612009-10-23 00:37:15 +00005249 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005250 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005251 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005252 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005253 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005254 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005255 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005256 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005257 return 1;
5258 }
drhdb95f682013-06-26 22:46:00 +00005259 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005260 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005261 for(i=1; i<nCol; i++){
5262 zSql[j++] = ',';
5263 zSql[j++] = '?';
5264 }
5265 zSql[j++] = ')';
5266 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005267 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005268 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005269 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005270 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005271 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00005272 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00005273 return 1;
drhfeac5f82004-08-01 00:10:45 +00005274 }
mistachkin8e189222015-04-19 21:43:16 +00005275 needCommit = sqlite3_get_autocommit(p->db);
5276 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00005277 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005278 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005279 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005280 char *z = xRead(&sCtx);
5281 /*
5282 ** Did we reach end-of-file before finding any columns?
5283 ** If so, stop instead of NULL filling the remaining columns.
5284 */
drhdb95f682013-06-26 22:46:00 +00005285 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005286 /*
5287 ** Did we reach end-of-file OR end-of-line before finding any
5288 ** columns in ASCII mode? If so, stop instead of NULL filling
5289 ** the remaining columns.
5290 */
5291 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005292 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005293 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005294 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005295 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005296 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005297 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005298 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005299 }
drhfeac5f82004-08-01 00:10:45 +00005300 }
mistachkin636bf9f2014-07-19 20:15:16 +00005301 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005302 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005303 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005304 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005305 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005306 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005307 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005308 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005309 }
drhdb95f682013-06-26 22:46:00 +00005310 if( i>=nCol ){
5311 sqlite3_step(pStmt);
5312 rc = sqlite3_reset(pStmt);
5313 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005314 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5315 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005316 }
5317 }
mistachkin636bf9f2014-07-19 20:15:16 +00005318 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005319
mistachkin636bf9f2014-07-19 20:15:16 +00005320 xCloser(sCtx.in);
5321 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005322 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005323 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005324 }else
5325
drhd12602a2016-12-07 15:49:02 +00005326#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005327 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5328 char *zSql;
5329 char *zCollist = 0;
5330 sqlite3_stmt *pStmt;
5331 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005332 int i;
drh16eb5942016-11-03 13:01:38 +00005333 if( nArg!=3 ){
5334 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5335 rc = 1;
5336 goto meta_command_exit;
5337 }
5338 open_db(p, 0);
5339 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5340 " WHERE name='%q' AND type='index'", azArg[1]);
5341 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5342 sqlite3_free(zSql);
5343 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5344 tnum = sqlite3_column_int(pStmt, 0);
5345 }
5346 sqlite3_finalize(pStmt);
5347 if( tnum==0 ){
5348 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5349 rc = 1;
5350 goto meta_command_exit;
5351 }
5352 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5353 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5354 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005355 i = 0;
drh16eb5942016-11-03 13:01:38 +00005356 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005357 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005358 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005359 i++;
5360 if( zCol==0 ){
5361 if( sqlite3_column_int(pStmt,1)==-1 ){
5362 zCol = "_ROWID_";
5363 }else{
5364 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5365 zCol = zLabel;
5366 }
5367 }
drh16eb5942016-11-03 13:01:38 +00005368 if( zCollist==0 ){
5369 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5370 }else{
5371 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5372 }
5373 }
5374 sqlite3_finalize(pStmt);
5375 zSql = sqlite3_mprintf(
5376 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5377 azArg[2], zCollist, zCollist);
5378 sqlite3_free(zCollist);
5379 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5380 if( rc==SQLITE_OK ){
5381 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5382 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5383 if( rc ){
5384 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5385 }else{
5386 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005387 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005388 "WARNING: writing to an imposter table will corrupt the index!\n"
5389 );
5390 }
5391 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005392 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005393 rc = 1;
5394 }
5395 sqlite3_free(zSql);
5396 }else
5397#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5398
drhae5e4452007-05-03 17:18:36 +00005399#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005400 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005401 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005402 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5403 iotrace = 0;
5404 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005405 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005406 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005407 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005408 iotrace = stdout;
5409 }else{
5410 iotrace = fopen(azArg[1], "w");
5411 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005412 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005413 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005414 rc = 1;
drhb0603412007-02-28 04:47:26 +00005415 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005416 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005417 }
5418 }
5419 }else
drhae5e4452007-05-03 17:18:36 +00005420#endif
drh16eb5942016-11-03 13:01:38 +00005421
drh1a513372015-05-02 17:40:23 +00005422 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5423 static const struct {
5424 const char *zLimitName; /* Name of a limit */
5425 int limitCode; /* Integer code for that limit */
5426 } aLimit[] = {
5427 { "length", SQLITE_LIMIT_LENGTH },
5428 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5429 { "column", SQLITE_LIMIT_COLUMN },
5430 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5431 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5432 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5433 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5434 { "attached", SQLITE_LIMIT_ATTACHED },
5435 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5436 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5437 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5438 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5439 };
5440 int i, n2;
5441 open_db(p, 0);
5442 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005443 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005444 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005445 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5446 }
5447 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005448 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005449 rc = 1;
5450 goto meta_command_exit;
5451 }else{
5452 int iLimit = -1;
5453 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005454 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005455 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5456 if( iLimit<0 ){
5457 iLimit = i;
5458 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005459 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005460 rc = 1;
5461 goto meta_command_exit;
5462 }
5463 }
5464 }
5465 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005466 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005467 "enter \".limits\" with no arguments for a list.\n",
5468 azArg[1]);
5469 rc = 1;
5470 goto meta_command_exit;
5471 }
5472 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005473 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5474 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005475 }
5476 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5477 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5478 }
5479 }else
drhb0603412007-02-28 04:47:26 +00005480
dan3c7ebeb2016-12-16 17:28:56 +00005481 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005482 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005483 lintDotCommand(p, azArg, nArg);
5484 }else
5485
drh70df4fe2006-06-13 15:12:21 +00005486#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005487 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005488 const char *zFile, *zProc;
5489 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005490 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005491 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005492 rc = 1;
5493 goto meta_command_exit;
5494 }
drh1e397f82006-06-08 15:28:43 +00005495 zFile = azArg[1];
5496 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005497 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005498 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5499 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005500 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005501 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005502 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005503 }
5504 }else
drh70df4fe2006-06-13 15:12:21 +00005505#endif
drh1e397f82006-06-08 15:28:43 +00005506
drhc2ce0be2014-05-29 12:36:14 +00005507 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5508 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005509 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005510 rc = 1;
5511 }else{
5512 const char *zFile = azArg[1];
5513 output_file_close(p->pLog);
5514 p->pLog = output_file_open(zFile);
5515 }
drh127f9d72010-02-23 01:47:00 +00005516 }else
5517
drhc2ce0be2014-05-29 12:36:14 +00005518 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5519 const char *zMode = nArg>=2 ? azArg[1] : "";
5520 int n2 = (int)strlen(zMode);
5521 int c2 = zMode[0];
5522 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005523 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005524 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005525 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005526 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005527 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005528 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005529 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005530 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5531 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005532 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005533 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005534 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005535 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005536 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005537 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005538 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005539 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005540 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005541 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005542 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005543 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005544 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005545 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005546 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005547 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005548 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5549 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005550 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5551 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005552 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5553 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drhdaffd0e2001-04-11 14:28:42 +00005554 }else {
mistachkinaae280e2015-12-31 19:06:24 +00005555 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005556 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005557 rc = 1;
drh75897232000-05-29 14:26:00 +00005558 }
drh700c2522016-02-09 18:39:25 +00005559 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005560 }else
5561
drhc2ce0be2014-05-29 12:36:14 +00005562 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5563 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005564 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5565 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005566 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005567 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005568 rc = 1;
5569 }
5570 }else
5571
drh05782482013-10-24 15:20:20 +00005572 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005573 char *zNewFilename; /* Name of the database file to open */
5574 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005575 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005576 /* Close the existing database */
5577 session_close_all(p);
5578 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005579 p->db = 0;
dan21472212017-03-01 11:30:27 +00005580 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005581 sqlite3_free(p->zFreeOnClose);
5582 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005583 /* Check for command-line arguments */
5584 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5585 const char *z = azArg[iName];
5586 if( optionMatch(z,"new") ){
5587 newFlag = 1;
5588 }else if( z[0]=='-' ){
5589 utf8_printf(stderr, "unknown option: %s\n", z);
5590 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005591 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005592 }
drhcd0509e2016-09-16 00:26:08 +00005593 }
5594 /* If a filename is specified, try to open it first */
5595 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5596 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005597 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005598 p->zDbFilename = zNewFilename;
5599 open_db(p, 1);
5600 if( p->db==0 ){
5601 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5602 sqlite3_free(zNewFilename);
5603 }else{
5604 p->zFreeOnClose = zNewFilename;
5605 }
5606 }
5607 if( p->db==0 ){
5608 /* As a fall-back open a TEMP database */
5609 p->zDbFilename = 0;
5610 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005611 }
5612 }else
5613
drhc2ce0be2014-05-29 12:36:14 +00005614 if( c=='o'
5615 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5616 ){
5617 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5618 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005619 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005620 rc = 1;
5621 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005622 }
drhc2ce0be2014-05-29 12:36:14 +00005623 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5624 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005625 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005626 rc = 1;
5627 goto meta_command_exit;
5628 }
5629 p->outCount = 2;
5630 }else{
5631 p->outCount = 0;
5632 }
5633 output_reset(p);
5634 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005635#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005636 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005637 rc = 1;
5638 p->out = stdout;
5639#else
drhc2ce0be2014-05-29 12:36:14 +00005640 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005641 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005642 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005643 p->out = stdout;
5644 rc = 1;
5645 }else{
drhc2ce0be2014-05-29 12:36:14 +00005646 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005647 }
drh8cd5b252015-03-02 22:06:43 +00005648#endif
drh75897232000-05-29 14:26:00 +00005649 }else{
drhc2ce0be2014-05-29 12:36:14 +00005650 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005651 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005652 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005653 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005654 }
drh75897232000-05-29 14:26:00 +00005655 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005656 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005657 } else {
drhc2ce0be2014-05-29 12:36:14 +00005658 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005659 }
5660 }
5661 }else
5662
drh078b1fd2012-09-21 13:40:02 +00005663 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5664 int i;
5665 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005666 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005667 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005668 }
mistachkinaae280e2015-12-31 19:06:24 +00005669 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005670 }else
5671
drhc2ce0be2014-05-29 12:36:14 +00005672 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005673 if( nArg >= 2) {
5674 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5675 }
5676 if( nArg >= 3) {
5677 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5678 }
5679 }else
5680
drhc2ce0be2014-05-29 12:36:14 +00005681 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005682 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005683 }else
5684
drhc2ce0be2014-05-29 12:36:14 +00005685 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5686 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005687 if( nArg!=2 ){
5688 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005689 rc = 1;
5690 goto meta_command_exit;
5691 }
drh4e8142c2016-11-11 14:54:22 +00005692 alt = fopen(azArg[1], "rb");
5693 if( alt==0 ){
5694 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5695 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005696 }else{
drh4e8142c2016-11-11 14:54:22 +00005697 rc = process_input(p, alt);
5698 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005699 }
5700 }else
5701
drhc2ce0be2014-05-29 12:36:14 +00005702 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005703 const char *zSrcFile;
5704 const char *zDb;
5705 sqlite3 *pSrc;
5706 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005707 int nTimeout = 0;
5708
drh9ff849f2009-02-04 20:55:57 +00005709 if( nArg==2 ){
5710 zSrcFile = azArg[1];
5711 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005712 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005713 zSrcFile = azArg[2];
5714 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005715 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005716 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005717 rc = 1;
5718 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005719 }
5720 rc = sqlite3_open(zSrcFile, &pSrc);
5721 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005722 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005723 sqlite3_close(pSrc);
5724 return 1;
5725 }
drh05782482013-10-24 15:20:20 +00005726 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005727 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5728 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005729 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005730 sqlite3_close(pSrc);
5731 return 1;
5732 }
drhdc2c4912009-02-04 22:46:47 +00005733 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5734 || rc==SQLITE_BUSY ){
5735 if( rc==SQLITE_BUSY ){
5736 if( nTimeout++ >= 3 ) break;
5737 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005738 }
5739 }
5740 sqlite3_backup_finish(pBackup);
5741 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005742 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005743 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005744 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005745 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005746 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005747 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005748 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005749 }
5750 sqlite3_close(pSrc);
5751 }else
5752
dan8d1edb92014-11-05 09:07:28 +00005753
5754 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5755 if( nArg==2 ){
5756 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005757#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005758 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005759#endif
dan8d1edb92014-11-05 09:07:28 +00005760 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005761 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005762 rc = 1;
5763 }
5764 }else
5765
drhc2ce0be2014-05-29 12:36:14 +00005766 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drh20c9c3f2017-06-15 12:21:09 +00005767 ShellText sSelect;
drhdcd87a92014-08-18 13:45:42 +00005768 ShellState data;
drh75897232000-05-29 14:26:00 +00005769 char *zErrMsg = 0;
drh20c9c3f2017-06-15 12:21:09 +00005770 const char *zDiv = 0;
5771 int iSchema = 0;
5772
drh05782482013-10-24 15:20:20 +00005773 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005774 memcpy(&data, p, sizeof(data));
5775 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005776 data.cMode = data.mode = MODE_Semi;
drh20c9c3f2017-06-15 12:21:09 +00005777 initText(&sSelect);
drh4926fec2016-04-13 15:33:42 +00005778 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5779 data.cMode = data.mode = MODE_Pretty;
5780 nArg--;
5781 if( nArg==2 ) azArg[1] = azArg[2];
5782 }
5783 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005784 int i;
drhf0693c82011-10-11 20:41:54 +00005785 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005786 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005787 char *new_argv[2], *new_colv[2];
5788 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5789 " type text,\n"
5790 " name text,\n"
5791 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005792 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005793 " sql text\n"
5794 ")";
5795 new_argv[1] = 0;
5796 new_colv[0] = "sql";
5797 new_colv[1] = 0;
5798 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005799 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005800 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005801 char *new_argv[2], *new_colv[2];
5802 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5803 " type text,\n"
5804 " name text,\n"
5805 " tbl_name text,\n"
5806 " rootpage integer,\n"
5807 " sql text\n"
5808 ")";
5809 new_argv[1] = 0;
5810 new_colv[0] = "sql";
5811 new_colv[1] = 0;
5812 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005813 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005814 }else{
drh20c9c3f2017-06-15 12:21:09 +00005815 zDiv = "(";
drha18c5682000-10-08 22:20:57 +00005816 }
drhc2ce0be2014-05-29 12:36:14 +00005817 }else if( nArg==1 ){
drh20c9c3f2017-06-15 12:21:09 +00005818 zDiv = "(";
drhc2ce0be2014-05-29 12:36:14 +00005819 }else{
drh4926fec2016-04-13 15:33:42 +00005820 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005821 rc = 1;
5822 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005823 }
drh20c9c3f2017-06-15 12:21:09 +00005824 if( zDiv ){
5825 sqlite3_stmt *pStmt = 0;
5826 sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
5827 -1, &pStmt, 0);
5828 appendText(&sSelect, "SELECT sql FROM", 0);
5829 iSchema = 0;
5830 while( sqlite3_step(pStmt)==SQLITE_ROW ){
5831 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
5832 char zScNum[30];
5833 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
5834 appendText(&sSelect, zDiv, 0);
5835 zDiv = " UNION ALL ";
5836 if( strcmp(zDb, "main")!=0 ){
5837 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
drh90cdec02017-06-15 13:07:56 +00005838 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00005839 appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
5840 appendText(&sSelect, zScNum, 0);
5841 appendText(&sSelect, " AS snum, ", 0);
5842 appendText(&sSelect, zDb, '\'');
5843 appendText(&sSelect, " AS sname FROM ", 0);
drh90cdec02017-06-15 13:07:56 +00005844 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00005845 appendText(&sSelect, ".sqlite_master", 0);
5846 }else{
5847 appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
5848 appendText(&sSelect, zScNum, 0);
5849 appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
5850 }
5851 }
5852 sqlite3_finalize(pStmt);
5853 appendText(&sSelect, ") WHERE ", 0);
5854 if( nArg>1 ){
5855 char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
5856 if( strchr(azArg[1], '.') ){
5857 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
5858 }else{
5859 appendText(&sSelect, "lower(tbl_name)", 0);
5860 }
5861 appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
5862 appendText(&sSelect, zQarg, 0);
5863 appendText(&sSelect, " AND ", 0);
5864 sqlite3_free(zQarg);
5865 }
5866 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
5867 " ORDER BY snum, rowid", 0);
5868 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
5869 freeText(&sSelect);
5870 }
drh75897232000-05-29 14:26:00 +00005871 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005872 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005873 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005874 rc = 1;
5875 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005876 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005877 rc = 1;
5878 }else{
5879 rc = 0;
drh75897232000-05-29 14:26:00 +00005880 }
5881 }else
5882
drhabd4c722014-09-20 18:18:33 +00005883#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5884 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005885 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005886 }else
5887#endif
5888
drhe6229612014-08-18 15:08:26 +00005889#if defined(SQLITE_ENABLE_SESSION)
5890 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5891 OpenSession *pSession = &p->aSession[0];
5892 char **azCmd = &azArg[1];
5893 int iSes = 0;
5894 int nCmd = nArg - 1;
5895 int i;
5896 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005897 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005898 if( nArg>=3 ){
5899 for(iSes=0; iSes<p->nSession; iSes++){
5900 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5901 }
5902 if( iSes<p->nSession ){
5903 pSession = &p->aSession[iSes];
5904 azCmd++;
5905 nCmd--;
5906 }else{
5907 pSession = &p->aSession[0];
5908 iSes = 0;
5909 }
5910 }
5911
drh3a67b042014-08-18 17:56:31 +00005912 /* .session attach TABLE
5913 ** Invoke the sqlite3session_attach() interface to attach a particular
5914 ** table so that it is never filtered.
5915 */
5916 if( strcmp(azCmd[0],"attach")==0 ){
5917 if( nCmd!=2 ) goto session_syntax_error;
5918 if( pSession->p==0 ){
5919 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005920 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005921 }else{
5922 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5923 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005924 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005925 rc = 0;
5926 }
5927 }
5928 }else
5929
5930 /* .session changeset FILE
5931 ** .session patchset FILE
5932 ** Write a changeset or patchset into a file. The file is overwritten.
5933 */
5934 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5935 FILE *out = 0;
5936 if( nCmd!=2 ) goto session_syntax_error;
5937 if( pSession->p==0 ) goto session_not_open;
5938 out = fopen(azCmd[1], "wb");
5939 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005940 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005941 }else{
5942 int szChng;
5943 void *pChng;
5944 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005945 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005946 }else{
drh2967e0c2014-08-19 00:26:17 +00005947 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5948 }
5949 if( rc ){
5950 printf("Error: error code %d\n", rc);
5951 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005952 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005953 if( pChng
drh3a67b042014-08-18 17:56:31 +00005954 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005955 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005956 szChng);
5957 }
5958 sqlite3_free(pChng);
5959 fclose(out);
5960 }
5961 }else
5962
drhe6229612014-08-18 15:08:26 +00005963 /* .session close
5964 ** Close the identified session
5965 */
5966 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005967 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005968 if( p->nSession ){
5969 session_close(pSession);
5970 p->aSession[iSes] = p->aSession[--p->nSession];
5971 }
5972 }else
5973
drh03168ca2014-08-18 20:01:31 +00005974 /* .session enable ?BOOLEAN?
5975 ** Query or set the enable flag
5976 */
5977 if( strcmp(azCmd[0], "enable")==0 ){
5978 int ii;
5979 if( nCmd>2 ) goto session_syntax_error;
5980 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5981 if( p->nSession ){
5982 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005983 utf8_printf(p->out, "session %s enable flag = %d\n",
5984 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005985 }
5986 }else
5987
5988 /* .session filter GLOB ....
5989 ** Set a list of GLOB patterns of table names to be excluded.
5990 */
5991 if( strcmp(azCmd[0], "filter")==0 ){
5992 int ii, nByte;
5993 if( nCmd<2 ) goto session_syntax_error;
5994 if( p->nSession ){
5995 for(ii=0; ii<pSession->nFilter; ii++){
5996 sqlite3_free(pSession->azFilter[ii]);
5997 }
5998 sqlite3_free(pSession->azFilter);
5999 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6000 pSession->azFilter = sqlite3_malloc( nByte );
6001 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006002 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00006003 exit(1);
6004 }
6005 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00006006 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00006007 }
6008 pSession->nFilter = ii-1;
6009 }
6010 }else
6011
6012 /* .session indirect ?BOOLEAN?
6013 ** Query or set the indirect flag
6014 */
6015 if( strcmp(azCmd[0], "indirect")==0 ){
6016 int ii;
6017 if( nCmd>2 ) goto session_syntax_error;
6018 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6019 if( p->nSession ){
6020 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00006021 utf8_printf(p->out, "session %s indirect flag = %d\n",
6022 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006023 }
6024 }else
6025
6026 /* .session isempty
6027 ** Determine if the session is empty
6028 */
6029 if( strcmp(azCmd[0], "isempty")==0 ){
6030 int ii;
6031 if( nCmd!=1 ) goto session_syntax_error;
6032 if( p->nSession ){
6033 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00006034 utf8_printf(p->out, "session %s isempty flag = %d\n",
6035 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006036 }
6037 }else
6038
drhe6229612014-08-18 15:08:26 +00006039 /* .session list
6040 ** List all currently open sessions
6041 */
6042 if( strcmp(azCmd[0],"list")==0 ){
6043 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00006044 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00006045 }
6046 }else
6047
6048 /* .session open DB NAME
6049 ** Open a new session called NAME on the attached database DB.
6050 ** DB is normally "main".
6051 */
6052 if( strcmp(azCmd[0],"open")==0 ){
6053 char *zName;
6054 if( nCmd!=3 ) goto session_syntax_error;
6055 zName = azCmd[2];
6056 if( zName[0]==0 ) goto session_syntax_error;
6057 for(i=0; i<p->nSession; i++){
6058 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006059 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00006060 goto meta_command_exit;
6061 }
6062 }
6063 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00006064 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00006065 goto meta_command_exit;
6066 }
6067 pSession = &p->aSession[p->nSession];
6068 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6069 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00006070 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00006071 rc = 0;
drhe6229612014-08-18 15:08:26 +00006072 goto meta_command_exit;
6073 }
drh03168ca2014-08-18 20:01:31 +00006074 pSession->nFilter = 0;
6075 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00006076 p->nSession++;
6077 pSession->zName = sqlite3_mprintf("%s", zName);
6078 }else
6079 /* If no command name matches, show a syntax error */
6080 session_syntax_error:
6081 session_help(p);
6082 }else
6083#endif
6084
drh340f5822013-06-27 13:01:21 +00006085#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00006086 /* Undocumented commands for internal testing. Subject to change
6087 ** without notice. */
6088 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6089 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6090 int i, v;
6091 for(i=1; i<nArg; i++){
6092 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00006093 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00006094 }
6095 }
6096 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6097 int i; sqlite3_int64 v;
6098 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00006099 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00006100 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00006101 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00006102 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00006103 }
6104 }
6105 }else
drh340f5822013-06-27 13:01:21 +00006106#endif
drh348d19c2013-06-03 12:47:43 +00006107
drhfb546af2017-03-09 22:00:33 +00006108 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6109 int bIsInit = 0; /* True to initialize the SELFTEST table */
6110 int bVerbose = 0; /* Verbose output */
6111 int bSelftestExists; /* True if SELFTEST already exists */
drhc5d353f2017-06-09 02:27:49 +00006112 int i, k; /* Loop counters */
drhfb546af2017-03-09 22:00:33 +00006113 int nTest = 0; /* Number of tests runs */
6114 int nErr = 0; /* Number of errors seen */
6115 ShellText str; /* Answer for a query */
drhc5d353f2017-06-09 02:27:49 +00006116 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
drhfb546af2017-03-09 22:00:33 +00006117
6118 open_db(p,0);
6119 for(i=1; i<nArg; i++){
6120 const char *z = azArg[i];
6121 if( z[0]=='-' && z[1]=='-' ) z++;
6122 if( strcmp(z,"-init")==0 ){
6123 bIsInit = 1;
6124 }else
6125 if( strcmp(z,"-v")==0 ){
6126 bVerbose++;
6127 }else
6128 {
6129 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6130 azArg[i], azArg[0]);
6131 raw_printf(stderr, "Should be one of: --init -v\n");
6132 rc = 1;
6133 goto meta_command_exit;
6134 }
6135 }
6136 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6137 != SQLITE_OK ){
6138 bSelftestExists = 0;
6139 }else{
6140 bSelftestExists = 1;
6141 }
6142 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006143 createSelftestTable(p);
6144 bSelftestExists = 1;
6145 }
drhc5d353f2017-06-09 02:27:49 +00006146 initText(&str);
6147 appendText(&str, "x", 0);
6148 for(k=bSelftestExists; k>=0; k--){
6149 if( k==1 ){
6150 rc = sqlite3_prepare_v2(p->db,
6151 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6152 -1, &pStmt, 0);
6153 }else{
6154 rc = sqlite3_prepare_v2(p->db,
6155 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6156 " (1,'run','PRAGMA integrity_check','ok')",
6157 -1, &pStmt, 0);
6158 }
drhfb546af2017-03-09 22:00:33 +00006159 if( rc ){
6160 raw_printf(stderr, "Error querying the selftest table\n");
6161 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006162 sqlite3_finalize(pStmt);
drhfb546af2017-03-09 22:00:33 +00006163 goto meta_command_exit;
drhfb546af2017-03-09 22:00:33 +00006164 }
drhc5d353f2017-06-09 02:27:49 +00006165 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6166 int tno = sqlite3_column_int(pStmt, 0);
6167 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6168 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6169 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
mistachkine16a3502017-05-29 03:48:13 +00006170
drhc5d353f2017-06-09 02:27:49 +00006171 k = 0;
6172 if( bVerbose>0 ){
6173 char *zQuote = sqlite3_mprintf("%q", zSql);
6174 printf("%d: %s %s\n", tno, zOp, zSql);
6175 sqlite3_free(zQuote);
drhfb546af2017-03-09 22:00:33 +00006176 }
drhc5d353f2017-06-09 02:27:49 +00006177 if( strcmp(zOp,"memo")==0 ){
6178 utf8_printf(p->out, "%s\n", zSql);
6179 }else
6180 if( strcmp(zOp,"run")==0 ){
6181 char *zErrMsg = 0;
6182 str.n = 0;
6183 str.z[0] = 0;
6184 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6185 nTest++;
6186 if( bVerbose ){
6187 utf8_printf(p->out, "Result: %s\n", str.z);
6188 }
6189 if( rc || zErrMsg ){
6190 nErr++;
6191 rc = 1;
6192 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6193 sqlite3_free(zErrMsg);
6194 }else if( strcmp(zAns,str.z)!=0 ){
6195 nErr++;
6196 rc = 1;
6197 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6198 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6199 }
6200 }else
6201 {
6202 utf8_printf(stderr,
6203 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
drhfb546af2017-03-09 22:00:33 +00006204 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006205 break;
drhfb546af2017-03-09 22:00:33 +00006206 }
drhc5d353f2017-06-09 02:27:49 +00006207 } /* End loop over rows of content from SELFTEST */
6208 sqlite3_finalize(pStmt);
6209 } /* End loop over k */
drhfb546af2017-03-09 22:00:33 +00006210 freeText(&str);
drhfb546af2017-03-09 22:00:33 +00006211 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6212 }else
6213
drhc2ce0be2014-05-29 12:36:14 +00006214 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006215 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006216 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006217 rc = 1;
6218 }
drh6976c212014-07-24 12:09:47 +00006219 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006220 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006221 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006222 }
6223 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006224 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6225 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006226 }
drh75897232000-05-29 14:26:00 +00006227 }else
6228
drh1554bc82017-03-08 16:10:34 +00006229 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6230 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6231 int i; /* Loop counter */
6232 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006233 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006234 int iSize = 224; /* Hash algorithm to use */
6235 int bDebug = 0; /* Only show the query that would have run */
6236 sqlite3_stmt *pStmt; /* For querying tables names */
6237 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006238 char *zSep; /* Separator */
6239 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006240 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006241 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006242 for(i=1; i<nArg; i++){
6243 const char *z = azArg[i];
6244 if( z[0]=='-' ){
6245 z++;
6246 if( z[0]=='-' ) z++;
6247 if( strcmp(z,"schema")==0 ){
6248 bSchema = 1;
6249 }else
mistachkine16a3502017-05-29 03:48:13 +00006250 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6251 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
drh1554bc82017-03-08 16:10:34 +00006252 ){
6253 iSize = atoi(&z[5]);
6254 }else
6255 if( strcmp(z,"debug")==0 ){
6256 bDebug = 1;
6257 }else
6258 {
6259 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006260 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006261 raw_printf(stderr, "Should be one of: --schema"
6262 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6263 rc = 1;
6264 goto meta_command_exit;
6265 }
6266 }else if( zLike ){
6267 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6268 rc = 1;
6269 goto meta_command_exit;
6270 }else{
6271 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006272 bSeparate = 1;
6273 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006274 }
6275 }
6276 if( bSchema ){
6277 zSql = "SELECT lower(name) FROM sqlite_master"
6278 " WHERE type='table' AND coalesce(rootpage,0)>1"
6279 " UNION ALL SELECT 'sqlite_master'"
6280 " ORDER BY 1 collate nocase";
6281 }else{
6282 zSql = "SELECT lower(name) FROM sqlite_master"
6283 " WHERE type='table' AND coalesce(rootpage,0)>1"
6284 " AND name NOT LIKE 'sqlite_%'"
6285 " ORDER BY 1 collate nocase";
6286 }
6287 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6288 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006289 initText(&sSql);
6290 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6291 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006292 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6293 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6294 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6295 if( strncmp(zTab, "sqlite_",7)!=0 ){
6296 appendText(&sQuery,"SELECT * FROM ", 0);
6297 appendText(&sQuery,zTab,'"');
6298 appendText(&sQuery," NOT INDEXED;", 0);
6299 }else if( strcmp(zTab, "sqlite_master")==0 ){
6300 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6301 " ORDER BY name;", 0);
6302 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6303 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6304 " ORDER BY name;", 0);
6305 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6306 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6307 " ORDER BY tbl,idx;", 0);
6308 }else if( strcmp(zTab, "sqlite_stat3")==0
6309 || strcmp(zTab, "sqlite_stat4")==0 ){
6310 appendText(&sQuery, "SELECT * FROM ", 0);
6311 appendText(&sQuery, zTab, 0);
6312 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6313 }
drh3ee83ef2017-03-08 17:56:54 +00006314 appendText(&sSql, zSep, 0);
6315 appendText(&sSql, sQuery.z, '\'');
6316 sQuery.n = 0;
6317 appendText(&sSql, ",", 0);
6318 appendText(&sSql, zTab, '\'');
6319 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006320 }
6321 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006322 if( bSeparate ){
6323 zSql = sqlite3_mprintf(
6324 "%s))"
6325 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6326 " FROM [sha3sum$query]",
6327 sSql.z, iSize);
6328 }else{
6329 zSql = sqlite3_mprintf(
6330 "%s))"
6331 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6332 " FROM [sha3sum$query]",
6333 sSql.z, iSize);
6334 }
drh1554bc82017-03-08 16:10:34 +00006335 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006336 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006337 if( bDebug ){
6338 utf8_printf(p->out, "%s\n", zSql);
6339 }else{
6340 shell_exec(p->db, zSql, shell_callback, p, 0);
6341 }
6342 sqlite3_free(zSql);
6343 }else
6344
drh62cdde52014-05-28 20:22:28 +00006345 if( c=='s'
6346 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006347 ){
6348 char *zCmd;
drh54027102014-08-06 14:36:53 +00006349 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006350 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006351 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006352 rc = 1;
6353 goto meta_command_exit;
6354 }
drhdcb3e3d2014-05-29 03:17:29 +00006355 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006356 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006357 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6358 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006359 }
drh54027102014-08-06 14:36:53 +00006360 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006361 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006362 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006363 }else
6364
drhc2ce0be2014-05-29 12:36:14 +00006365 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006366 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006367 int i;
drhc2ce0be2014-05-29 12:36:14 +00006368 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006369 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006370 rc = 1;
6371 goto meta_command_exit;
6372 }
drhe6e1d122017-03-09 13:50:49 +00006373 utf8_printf(p->out, "%12.12s: %s\n","echo",
6374 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006375 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006376 utf8_printf(p->out, "%12.12s: %s\n","explain",
6377 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006378 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006379 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6380 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006381 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006382 raw_printf(p->out, "\n");
6383 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006384 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006385 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006386 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006387 raw_printf(p->out, "\n");
6388 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006389 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006390 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006391 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006392 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006393 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006394 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006395 }
mistachkinaae280e2015-12-31 19:06:24 +00006396 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006397 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6398 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006399 }else
6400
drhc2ce0be2014-05-29 12:36:14 +00006401 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6402 if( nArg==2 ){
6403 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006404 }else if( nArg==1 ){
6405 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006406 }else{
drh34784902016-02-27 17:12:36 +00006407 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006408 rc = 1;
6409 }
shaneh642d8b82010-07-28 16:05:34 +00006410 }else
6411
drh6a5a4202016-12-24 21:32:40 +00006412 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6413 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6414 || strncmp(azArg[0], "indexes", n)==0) )
6415 ){
drh98781232012-04-23 12:38:05 +00006416 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006417 char **azResult;
drh98781232012-04-23 12:38:05 +00006418 int nRow, nAlloc;
drh98781232012-04-23 12:38:05 +00006419 int ii;
drh594ccd02017-06-15 12:50:47 +00006420 ShellText s;
6421 initText(&s);
drh05782482013-10-24 15:20:20 +00006422 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006423 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006424 if( rc ) return shellDatabaseError(p->db);
6425
drh594ccd02017-06-15 12:50:47 +00006426 if( nArg>2 && c=='i' ){
drh6a5a4202016-12-24 21:32:40 +00006427 /* It is an historical accident that the .indexes command shows an error
6428 ** when called with the wrong number of arguments whereas the .tables
6429 ** command does not. */
6430 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6431 rc = 1;
6432 goto meta_command_exit;
drh6a5a4202016-12-24 21:32:40 +00006433 }
drh594ccd02017-06-15 12:50:47 +00006434 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006435 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drh594ccd02017-06-15 12:50:47 +00006436 if( zDbName==0 ) continue;
6437 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
6438 if( sqlite3_stricmp(zDbName, "main")==0 ){
6439 appendText(&s, "SELECT name FROM ", 0);
drh6a5a4202016-12-24 21:32:40 +00006440 }else{
drh594ccd02017-06-15 12:50:47 +00006441 appendText(&s, "SELECT ", 0);
6442 appendText(&s, zDbName, '\'');
6443 appendText(&s, "||'.'||name FROM ", 0);
6444 }
6445 appendText(&s, zDbName, '"');
6446 appendText(&s, ".sqlite_master ", 0);
6447 if( c=='t' ){
6448 appendText(&s," WHERE type IN ('table','view')"
6449 " AND name NOT LIKE 'sqlite_%'"
6450 " AND name LIKE ?1", 0);
6451 }else{
6452 appendText(&s," WHERE type='index'"
6453 " AND tbl_name LIKE ?1", 0);
drh98781232012-04-23 12:38:05 +00006454 }
drha50da102000-08-08 20:19:09 +00006455 }
dand95bb392015-09-30 11:19:05 +00006456 rc = sqlite3_finalize(pStmt);
drh594ccd02017-06-15 12:50:47 +00006457 appendText(&s, " ORDER BY 1", 0);
6458 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
6459 freeText(&s);
dand95bb392015-09-30 11:19:05 +00006460 if( rc ) return shellDatabaseError(p->db);
6461
6462 /* Run the SQL statement prepared by the above block. Store the results
6463 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006464 nRow = nAlloc = 0;
6465 azResult = 0;
6466 if( nArg>1 ){
6467 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006468 }else{
drh98781232012-04-23 12:38:05 +00006469 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6470 }
6471 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6472 if( nRow>=nAlloc ){
6473 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006474 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006475 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006476 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006477 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006478 break;
6479 }
mistachkin8e189222015-04-19 21:43:16 +00006480 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006481 azResult = azNew;
6482 }
6483 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006484 if( 0==azResult[nRow] ){
6485 rc = shellNomemError();
6486 break;
6487 }
6488 nRow++;
drh98781232012-04-23 12:38:05 +00006489 }
dand95bb392015-09-30 11:19:05 +00006490 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6491 rc = shellDatabaseError(p->db);
6492 }
6493
6494 /* Pretty-print the contents of array azResult[] to the output */
6495 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006496 int len, maxlen = 0;
6497 int i, j;
6498 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006499 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006500 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006501 if( len>maxlen ) maxlen = len;
6502 }
6503 nPrintCol = 80/(maxlen+2);
6504 if( nPrintCol<1 ) nPrintCol = 1;
6505 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6506 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006507 for(j=i; j<nRow; j+=nPrintRow){
6508 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006509 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6510 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006511 }
mistachkinaae280e2015-12-31 19:06:24 +00006512 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006513 }
6514 }
dand95bb392015-09-30 11:19:05 +00006515
drh98781232012-04-23 12:38:05 +00006516 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6517 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006518 }else
6519
drh2db82112016-09-15 21:35:24 +00006520 /* Begin redirecting output to the file "testcase-out.txt" */
6521 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6522 output_reset(p);
6523 p->out = output_file_open("testcase-out.txt");
6524 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006525 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006526 }
drh760c8162016-09-16 02:52:22 +00006527 if( nArg>=2 ){
6528 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6529 }else{
6530 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6531 }
drh2db82112016-09-15 21:35:24 +00006532 }else
drh2db82112016-09-15 21:35:24 +00006533
drhd12602a2016-12-07 15:49:02 +00006534#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006535 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006536 static const struct {
6537 const char *zCtrlName; /* Name of a test-control option */
6538 int ctrlCode; /* Integer code for that option */
6539 } aCtrl[] = {
6540 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6541 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6542 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6543 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6544 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6545 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6546 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6547 { "assert", SQLITE_TESTCTRL_ASSERT },
6548 { "always", SQLITE_TESTCTRL_ALWAYS },
6549 { "reserve", SQLITE_TESTCTRL_RESERVE },
6550 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6551 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006552 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006553 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006554 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006555 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006556 };
shaneh96887e12011-02-10 21:08:58 +00006557 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006558 int rc2 = 0;
6559 int i, n2;
drh05782482013-10-24 15:20:20 +00006560 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006561
drhd416fe72011-03-17 16:45:50 +00006562 /* convert testctrl text option to value. allow any unique prefix
6563 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006564 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006565 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006566 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006567 if( testctrl<0 ){
6568 testctrl = aCtrl[i].ctrlCode;
6569 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006570 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006571 testctrl = -1;
6572 break;
6573 }
6574 }
6575 }
drh348d19c2013-06-03 12:47:43 +00006576 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006577 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006578 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006579 }else{
6580 switch(testctrl){
6581
6582 /* sqlite3_test_control(int, db, int) */
6583 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006584 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006585 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006586 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006587 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006588 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006589 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006590 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006591 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006592 }
6593 break;
6594
6595 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006596 case SQLITE_TESTCTRL_PRNG_SAVE:
6597 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006598 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006599 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006600 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006601 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006602 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006603 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006604 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6605 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006606 }
6607 break;
6608
6609 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006610 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006611 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006612 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006613 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006614 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006615 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006616 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006617 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006618 }
6619 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006620
shaneh96887e12011-02-10 21:08:58 +00006621 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006622 case SQLITE_TESTCTRL_ASSERT:
6623 case SQLITE_TESTCTRL_ALWAYS:
6624 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006625 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006626 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006627 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006628 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006629 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006630 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006631 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006632 }
6633 break;
6634
6635 /* sqlite3_test_control(int, char *) */
6636#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006637 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006638 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006639 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006640 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006641 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006642 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006643 utf8_printf(stderr,
6644 "Error: testctrl %s takes a single char * option\n",
6645 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006646 }
6647 break;
6648#endif
6649
drh1ffede82015-01-30 20:59:27 +00006650 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006651 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006652 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006653 azArg[2],
drh8964b342015-01-29 17:54:52 +00006654 integerValue(azArg[3]),
6655 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006656 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006657 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006658 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006659 }
6660 break;
6661
mistachkin1fe36bb2016-04-04 02:16:44 +00006662 case SQLITE_TESTCTRL_BITVEC_TEST:
6663 case SQLITE_TESTCTRL_FAULT_INSTALL:
6664 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6665 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006666 default:
mistachkinaae280e2015-12-31 19:06:24 +00006667 utf8_printf(stderr,
6668 "Error: CLI support for testctrl %s not implemented\n",
6669 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006670 break;
6671 }
6672 }
6673 }else
drhf1969722017-02-17 23:52:00 +00006674#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006675
drhc2ce0be2014-05-29 12:36:14 +00006676 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006677 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006678 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006679 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006680
drhc2ce0be2014-05-29 12:36:14 +00006681 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6682 if( nArg==2 ){
6683 enableTimer = booleanValue(azArg[1]);
6684 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006685 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006686 enableTimer = 0;
6687 }
6688 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006689 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006690 rc = 1;
6691 }
shanehe2aa9d72009-11-06 17:20:17 +00006692 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006693
drhc2ce0be2014-05-29 12:36:14 +00006694 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006695 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006696 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006697 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006698 rc = 1;
6699 goto meta_command_exit;
6700 }
drh657b4a82015-03-19 13:30:41 +00006701 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006702 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006703#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006704 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006705 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006706 }else{
drh4b363a52016-07-23 20:27:41 +00006707 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006708 }
6709#endif
6710 }else
6711
drhf442e332014-09-10 19:01:14 +00006712#if SQLITE_USER_AUTHENTICATION
6713 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6714 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006715 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006716 rc = 1;
6717 goto meta_command_exit;
6718 }
drh7883ecf2014-09-11 16:19:31 +00006719 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006720 if( strcmp(azArg[1],"login")==0 ){
6721 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006722 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006723 rc = 1;
6724 goto meta_command_exit;
6725 }
drhd39c40f2014-09-11 00:27:53 +00006726 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6727 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006728 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006729 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006730 rc = 1;
6731 }
6732 }else if( strcmp(azArg[1],"add")==0 ){
6733 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006734 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006735 rc = 1;
6736 goto meta_command_exit;
6737 }
drhd39c40f2014-09-11 00:27:53 +00006738 rc = sqlite3_user_add(p->db, azArg[2],
6739 azArg[3], (int)strlen(azArg[3]),
6740 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006741 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006742 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006743 rc = 1;
6744 }
6745 }else if( strcmp(azArg[1],"edit")==0 ){
6746 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006747 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006748 rc = 1;
6749 goto meta_command_exit;
6750 }
drhd39c40f2014-09-11 00:27:53 +00006751 rc = sqlite3_user_change(p->db, azArg[2],
6752 azArg[3], (int)strlen(azArg[3]),
6753 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006754 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006755 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006756 rc = 1;
6757 }
6758 }else if( strcmp(azArg[1],"delete")==0 ){
6759 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006760 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006761 rc = 1;
6762 goto meta_command_exit;
6763 }
6764 rc = sqlite3_user_delete(p->db, azArg[2]);
6765 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006766 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006767 rc = 1;
6768 }
6769 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006770 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006771 rc = 1;
6772 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006773 }
drhf442e332014-09-10 19:01:14 +00006774 }else
6775#endif /* SQLITE_USER_AUTHENTICATION */
6776
drh9fd301b2011-06-03 13:28:22 +00006777 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006778 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006779 sqlite3_libversion(), sqlite3_sourceid());
6780 }else
6781
drh790f2872015-11-28 18:06:36 +00006782 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6783 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006784 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006785 if( p->db ){
6786 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6787 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006788 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6789 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6790 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6791 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006792 }
6793 }
6794 }else
6795
drhb19e7352016-01-12 19:37:20 +00006796 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6797 sqlite3_vfs *pVfs;
6798 sqlite3_vfs *pCurrent = 0;
6799 if( p->db ){
6800 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6801 }
6802 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6803 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6804 pVfs==pCurrent ? " <--- CURRENT" : "");
6805 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6806 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6807 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6808 if( pVfs->pNext ){
6809 raw_printf(p->out, "-----------------------------------\n");
6810 }
6811 }
6812 }else
6813
drhde60fc22011-12-14 17:53:36 +00006814 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6815 const char *zDbName = nArg==2 ? azArg[1] : "main";
6816 char *zVfsName = 0;
6817 if( p->db ){
6818 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6819 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006820 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006821 sqlite3_free(zVfsName);
6822 }
6823 }
6824 }else
6825
drhcef4fc82012-09-21 22:50:45 +00006826#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6827 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006828 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006829 }else
6830#endif
6831
drhc2ce0be2014-05-29 12:36:14 +00006832 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006833 int j;
drh43617e92006-03-06 20:55:46 +00006834 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006835 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006836 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006837 }
6838 }else
6839
6840 {
mistachkinaae280e2015-12-31 19:06:24 +00006841 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006842 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006843 rc = 1;
drh75897232000-05-29 14:26:00 +00006844 }
drh67505e72002-04-19 12:34:06 +00006845
drhc2ce0be2014-05-29 12:36:14 +00006846meta_command_exit:
6847 if( p->outCount ){
6848 p->outCount--;
6849 if( p->outCount==0 ) output_reset(p);
6850 }
drh67505e72002-04-19 12:34:06 +00006851 return rc;
drh75897232000-05-29 14:26:00 +00006852}
6853
drh67505e72002-04-19 12:34:06 +00006854/*
drh91a66392007-09-07 01:12:32 +00006855** Return TRUE if a semicolon occurs anywhere in the first N characters
6856** of string z[].
drh324ccef2003-02-05 14:06:20 +00006857*/
drh9f099fd2013-08-06 14:01:46 +00006858static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006859 int i;
6860 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6861 return 0;
drh324ccef2003-02-05 14:06:20 +00006862}
6863
6864/*
drh70c7a4b2003-04-26 03:03:06 +00006865** Test to see if a line consists entirely of whitespace.
6866*/
6867static int _all_whitespace(const char *z){
6868 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006869 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006870 if( *z=='/' && z[1]=='*' ){
6871 z += 2;
6872 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6873 if( *z==0 ) return 0;
6874 z++;
6875 continue;
6876 }
6877 if( *z=='-' && z[1]=='-' ){
6878 z += 2;
6879 while( *z && *z!='\n' ){ z++; }
6880 if( *z==0 ) return 1;
6881 continue;
6882 }
6883 return 0;
6884 }
6885 return 1;
6886}
6887
6888/*
drha9b17162003-04-29 18:01:28 +00006889** Return TRUE if the line typed in is an SQL command terminator other
6890** than a semi-colon. The SQL Server style "go" command is understood
6891** as is the Oracle "/".
6892*/
drh9f099fd2013-08-06 14:01:46 +00006893static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006894 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006895 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6896 return 1; /* Oracle */
6897 }
drhf0693c82011-10-11 20:41:54 +00006898 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006899 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006900 return 1; /* SQL Server */
6901 }
6902 return 0;
6903}
6904
6905/*
drh233a5312008-12-18 22:25:13 +00006906** Return true if zSql is a complete SQL statement. Return false if it
6907** ends in the middle of a string literal or C-style comment.
6908*/
drh9f099fd2013-08-06 14:01:46 +00006909static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006910 int rc;
6911 if( zSql==0 ) return 1;
6912 zSql[nSql] = ';';
6913 zSql[nSql+1] = 0;
6914 rc = sqlite3_complete(zSql);
6915 zSql[nSql] = 0;
6916 return rc;
6917}
6918
6919/*
drh4e8142c2016-11-11 14:54:22 +00006920** Run a single line of SQL
6921*/
6922static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6923 int rc;
6924 char *zErrMsg = 0;
6925
6926 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006927 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006928 BEGIN_TIMER;
6929 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6930 END_TIMER;
6931 if( rc || zErrMsg ){
6932 char zPrefix[100];
6933 if( in!=0 || !stdin_is_interactive ){
6934 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6935 "Error: near line %d:", startline);
6936 }else{
6937 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6938 }
6939 if( zErrMsg!=0 ){
6940 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6941 sqlite3_free(zErrMsg);
6942 zErrMsg = 0;
6943 }else{
6944 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6945 }
6946 return 1;
drhe6e1d122017-03-09 13:50:49 +00006947 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006948 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6949 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6950 }
6951 return 0;
6952}
6953
6954
6955/*
drh67505e72002-04-19 12:34:06 +00006956** Read input from *in and process it. If *in==0 then input
6957** is interactive - the user is typing it it. Otherwise, input
6958** is coming from a file or device. A prompt is issued and history
6959** is saved only if input is interactive. An interrupt signal will
6960** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006961**
6962** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006963*/
drhdcd87a92014-08-18 13:45:42 +00006964static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006965 char *zLine = 0; /* A single input line */
6966 char *zSql = 0; /* Accumulated SQL text */
6967 int nLine; /* Length of current line */
6968 int nSql = 0; /* Bytes of zSql[] used */
6969 int nAlloc = 0; /* Allocated zSql[] space */
6970 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006971 int rc; /* Error code */
6972 int errCnt = 0; /* Number of errors seen */
6973 int lineno = 0; /* Current line number */
6974 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006975
6976 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6977 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006978 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006979 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006980 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006981 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006982 break;
drhc49f44e2006-10-26 18:15:42 +00006983 }
drh67505e72002-04-19 12:34:06 +00006984 if( seenInterrupt ){
6985 if( in!=0 ) break;
6986 seenInterrupt = 0;
6987 }
drhc28490c2006-10-26 14:25:58 +00006988 lineno++;
drh849a9d92013-12-21 15:46:06 +00006989 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006990 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006991 continue;
6992 }
drh2af0b2d2002-02-21 02:25:02 +00006993 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006994 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006995 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006996 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006997 break;
6998 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006999 errCnt++;
7000 }
drhdaffd0e2001-04-11 14:28:42 +00007001 continue;
7002 }
drh9f099fd2013-08-06 14:01:46 +00007003 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00007004 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00007005 }
drh9f099fd2013-08-06 14:01:46 +00007006 nLine = strlen30(zLine);
7007 if( nSql+nLine+2>=nAlloc ){
7008 nAlloc = nSql+nLine+100;
7009 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00007010 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007011 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00007012 exit(1);
7013 }
drhdaffd0e2001-04-11 14:28:42 +00007014 }
drh9f099fd2013-08-06 14:01:46 +00007015 nSqlPrior = nSql;
7016 if( nSql==0 ){
7017 int i;
7018 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00007019 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00007020 memcpy(zSql, zLine+i, nLine+1-i);
7021 startline = lineno;
7022 nSql = nLine-i;
7023 }else{
7024 zSql[nSql++] = '\n';
7025 memcpy(zSql+nSql, zLine, nLine+1);
7026 nSql += nLine;
7027 }
7028 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00007029 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00007030 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007031 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00007032 if( p->outCount ){
7033 output_reset(p);
7034 p->outCount = 0;
7035 }
drh9f099fd2013-08-06 14:01:46 +00007036 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00007037 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00007038 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00007039 }
7040 }
drh4e8142c2016-11-11 14:54:22 +00007041 if( nSql && !_all_whitespace(zSql) ){
7042 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007043 }
drh1f9ca2c2015-08-25 16:57:52 +00007044 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00007045 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00007046 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00007047}
7048
drh67505e72002-04-19 12:34:06 +00007049/*
7050** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00007051** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00007052*/
drhd1459152016-09-16 19:11:03 +00007053static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00007054 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00007055 if( clearFlag ){
7056 free(home_dir);
7057 home_dir = 0;
7058 return 0;
7059 }
drh85e72432012-04-11 11:38:53 +00007060 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00007061
drh4ace5362014-11-10 14:42:28 +00007062#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7063 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00007064 {
7065 struct passwd *pwent;
7066 uid_t uid = getuid();
7067 if( (pwent=getpwuid(uid)) != NULL) {
7068 home_dir = pwent->pw_dir;
7069 }
drh67505e72002-04-19 12:34:06 +00007070 }
7071#endif
7072
chw65d3c132007-11-12 21:09:10 +00007073#if defined(_WIN32_WCE)
7074 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7075 */
drh85e72432012-04-11 11:38:53 +00007076 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00007077#else
7078
drh83905c92012-06-21 13:00:37 +00007079#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00007080 if (!home_dir) {
7081 home_dir = getenv("USERPROFILE");
7082 }
7083#endif
7084
drh67505e72002-04-19 12:34:06 +00007085 if (!home_dir) {
7086 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00007087 }
7088
drh83905c92012-06-21 13:00:37 +00007089#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00007090 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00007091 char *zDrive, *zPath;
7092 int n;
7093 zDrive = getenv("HOMEDRIVE");
7094 zPath = getenv("HOMEPATH");
7095 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00007096 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00007097 home_dir = malloc( n );
7098 if( home_dir==0 ) return 0;
7099 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7100 return home_dir;
7101 }
7102 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00007103 }
7104#endif
7105
chw65d3c132007-11-12 21:09:10 +00007106#endif /* !_WIN32_WCE */
7107
drh67505e72002-04-19 12:34:06 +00007108 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00007109 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00007110 char *z = malloc( n );
7111 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00007112 home_dir = z;
7113 }
drhe98d4fa2002-04-21 19:06:22 +00007114
drh67505e72002-04-19 12:34:06 +00007115 return home_dir;
7116}
7117
7118/*
7119** Read input from the file given by sqliterc_override. Or if that
7120** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007121**
7122** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007123*/
drh534f4df2015-02-28 14:03:35 +00007124static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007125 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007126 const char *sqliterc_override /* Name of config file. NULL to use default */
7127){
persicom7e2dfdd2002-04-18 02:46:52 +00007128 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007129 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007130 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007131 FILE *in = NULL;
7132
7133 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007134 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007135 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007136 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007137 " cannot read ~/.sqliterc\n");
7138 return;
drhe98d4fa2002-04-21 19:06:22 +00007139 }
drh2f3de322012-06-27 16:41:31 +00007140 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007141 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7142 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007143 }
drha1f9b5e2004-02-14 16:31:02 +00007144 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007145 if( in ){
drhc28490c2006-10-26 14:25:58 +00007146 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007147 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007148 }
drh534f4df2015-02-28 14:03:35 +00007149 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007150 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007151 }
drh85e72432012-04-11 11:38:53 +00007152 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007153}
7154
drh67505e72002-04-19 12:34:06 +00007155/*
drhe1e38c42003-05-04 18:30:59 +00007156** Show available command line options
7157*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007158static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007159 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007160 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007161 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007162 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007163 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007164 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007165 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007166 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007167 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007168#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7169 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7170#endif
drhcc3b4f82012-02-07 14:13:50 +00007171 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007172 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007173 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007174 " -line set output mode to 'line'\n"
7175 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007176 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007177 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007178#ifdef SQLITE_ENABLE_MULTIPLEX
7179 " -multiplex enable the multiplexor VFS\n"
7180#endif
mistachkine0d68852014-12-11 03:12:33 +00007181 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007182 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007183 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7184 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00007185 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007186 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007187 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007188 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007189#ifdef SQLITE_ENABLE_VFSTRACE
7190 " -vfstrace enable tracing of all VFS calls\n"
7191#endif
drhe1e38c42003-05-04 18:30:59 +00007192;
7193static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007194 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007195 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007196 "FILENAME is the name of an SQLite database. A new database is created\n"
7197 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007198 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007199 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007200 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007201 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007202 }
7203 exit(1);
7204}
7205
7206/*
drh67505e72002-04-19 12:34:06 +00007207** Initialize the state information in data
7208*/
drhdcd87a92014-08-18 13:45:42 +00007209static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007210 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007211 data->normalMode = data->cMode = data->mode = MODE_List;
7212 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007213 memcpy(data->colSeparator,SEP_Column, 2);
7214 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007215 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007216 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007217 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007218 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007219 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007220 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7221 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007222}
7223
drh98d312f2012-10-25 15:23:14 +00007224/*
drh5c7976f2014-02-10 19:59:27 +00007225** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007226*/
7227#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007228static void printBold(const char *zText){
7229 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7230 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7231 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7232 SetConsoleTextAttribute(out,
7233 FOREGROUND_RED|FOREGROUND_INTENSITY
7234 );
7235 printf("%s", zText);
7236 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007237}
7238#else
drh5c7976f2014-02-10 19:59:27 +00007239static void printBold(const char *zText){
7240 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007241}
7242#endif
7243
7244/*
drh98d312f2012-10-25 15:23:14 +00007245** Get the argument to an --option. Throw an error and die if no argument
7246** is available.
7247*/
7248static char *cmdline_option_value(int argc, char **argv, int i){
7249 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007250 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007251 argv[0], argv[argc-1]);
7252 exit(1);
7253 }
7254 return argv[i];
7255}
7256
mistachkin1fe36bb2016-04-04 02:16:44 +00007257#ifndef SQLITE_SHELL_IS_UTF8
7258# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7259# define SQLITE_SHELL_IS_UTF8 (0)
7260# else
7261# define SQLITE_SHELL_IS_UTF8 (1)
7262# endif
7263#endif
7264
7265#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007266int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007267#else
7268int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007269 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007270#endif
drh75897232000-05-29 14:26:00 +00007271 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007272 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007273 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007274 int i;
drhc28490c2006-10-26 14:25:58 +00007275 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007276 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007277 int readStdin = 1;
7278 int nCmd = 0;
7279 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007280
mistachkin1fe36bb2016-04-04 02:16:44 +00007281 setBinaryMode(stdin, 0);
7282 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007283 stdin_is_interactive = isatty(0);
7284 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007285
drh69b30ab2014-02-27 15:11:52 +00007286#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007287 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007288 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007289 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7290 exit(1);
7291 }
drhc7181902014-02-27 15:04:13 +00007292#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007293 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007294#if !SQLITE_SHELL_IS_UTF8
7295 sqlite3_initialize();
7296 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7297 if( argv==0 ){
7298 raw_printf(stderr, "out of memory\n");
7299 exit(1);
7300 }
7301 for(i=0; i<argc; i++){
7302 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7303 if( argv[i]==0 ){
7304 raw_printf(stderr, "out of memory\n");
7305 exit(1);
7306 }
7307 }
7308#endif
mistachkin1810f222016-04-04 02:33:34 +00007309 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007310 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007311
drh44c2eb12003-04-30 11:38:26 +00007312 /* Make sure we have a valid signal handler early, before anything
7313 ** else is done.
7314 */
drh4c504392000-10-16 22:06:40 +00007315#ifdef SIGINT
7316 signal(SIGINT, interrupt_handler);
7317#endif
drh44c2eb12003-04-30 11:38:26 +00007318
drhac5649a2014-11-28 13:35:03 +00007319#ifdef SQLITE_SHELL_DBNAME_PROC
7320 {
7321 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7322 ** of a C-function that will provide the name of the database file. Use
7323 ** this compile-time option to embed this shell program in larger
7324 ** applications. */
7325 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7326 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7327 warnInmemoryDb = 0;
7328 }
7329#endif
7330
drh22fbcb82004-02-01 01:22:50 +00007331 /* Do an initial pass through the command-line argument to locate
7332 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007333 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007334 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007335 */
drh98d312f2012-10-25 15:23:14 +00007336 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007337 char *z;
drhc28490c2006-10-26 14:25:58 +00007338 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007339 if( z[0]!='-' ){
7340 if( data.zDbFilename==0 ){
7341 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007342 }else{
7343 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7344 ** mean that nothing is read from stdin */
7345 readStdin = 0;
7346 nCmd++;
7347 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7348 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007349 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007350 exit(1);
7351 }
7352 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007353 }
drh98d312f2012-10-25 15:23:14 +00007354 }
drhcc3b4f82012-02-07 14:13:50 +00007355 if( z[1]=='-' ) z++;
7356 if( strcmp(z,"-separator")==0
7357 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007358 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007359 || strcmp(z,"-cmd")==0
7360 ){
drh98d312f2012-10-25 15:23:14 +00007361 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007362 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007363 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007364 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007365 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007366 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007367 ** we do the actual processing of arguments later in a second pass.
7368 */
shanef69573d2009-10-24 02:06:14 +00007369 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007370 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007371#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007372 const char *zSize;
7373 sqlite3_int64 szHeap;
7374
drh98d312f2012-10-25 15:23:14 +00007375 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007376 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007377 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007378 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007379#else
7380 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007381#endif
drh44dec872014-08-30 15:49:25 +00007382 }else if( strcmp(z,"-scratch")==0 ){
7383 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007384 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007385 if( sz>400000 ) sz = 400000;
7386 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007387 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007388 if( n>10 ) n = 10;
7389 if( n<1 ) n = 1;
7390 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7391 data.shellFlgs |= SHFLG_Scratch;
7392 }else if( strcmp(z,"-pagecache")==0 ){
7393 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007394 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007395 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007396 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007397 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007398 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7399 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007400 data.shellFlgs |= SHFLG_Pagecache;
7401 }else if( strcmp(z,"-lookaside")==0 ){
7402 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007403 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007404 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007405 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007406 if( n<0 ) n = 0;
7407 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7408 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007409#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007410 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007411 extern int vfstrace_register(
7412 const char *zTraceName,
7413 const char *zOldVfsName,
7414 int (*xOut)(const char*,void*),
7415 void *pOutArg,
7416 int makeDefault
7417 );
drh2b625e22011-03-16 17:05:28 +00007418 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007419#endif
drh6f25e892011-07-08 17:02:57 +00007420#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007421 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007422 extern int sqlite3_multiple_initialize(const char*,int);
7423 sqlite3_multiplex_initialize(0, 1);
7424#endif
drh7d9f3942013-04-03 01:26:54 +00007425 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007426 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7427 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007428 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007429 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007430 if( pVfs ){
7431 sqlite3_vfs_register(pVfs, 1);
7432 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007433 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007434 exit(1);
7435 }
drh44c2eb12003-04-30 11:38:26 +00007436 }
7437 }
drh98d312f2012-10-25 15:23:14 +00007438 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007439#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007440 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007441 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007442#else
mistachkinaae280e2015-12-31 19:06:24 +00007443 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007444 return 1;
drh01b41712005-08-29 23:06:23 +00007445#endif
drh98d312f2012-10-25 15:23:14 +00007446 }
7447 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007448
drh44c2eb12003-04-30 11:38:26 +00007449 /* Go ahead and open the database file if it already exists. If the
7450 ** file does not exist, delay opening it. This prevents empty database
7451 ** files from being created if a user mistypes the database name argument
7452 ** to the sqlite command-line tool.
7453 */
drhc8d74412004-08-31 23:41:26 +00007454 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007455 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007456 }
7457
drh22fbcb82004-02-01 01:22:50 +00007458 /* Process the initialization file if there is one. If no -init option
7459 ** is given on the command line, look for a file named ~/.sqliterc and
7460 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007461 */
drh534f4df2015-02-28 14:03:35 +00007462 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007463
drh22fbcb82004-02-01 01:22:50 +00007464 /* Make a second pass through the command-line argument and set
7465 ** options. This second pass is delayed until after the initialization
7466 ** file is processed so that the command-line arguments will override
7467 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007468 */
drh98d312f2012-10-25 15:23:14 +00007469 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007470 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007471 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007472 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007473 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007474 i++;
7475 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007476 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007477 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007478 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007479 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007480 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007481 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007482 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007483 }else if( strcmp(z,"-csv")==0 ){
7484 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007485 memcpy(data.colSeparator,",",2);
7486 }else if( strcmp(z,"-ascii")==0 ){
7487 data.mode = MODE_Ascii;
7488 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007489 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007490 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007491 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007492 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007493 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007494 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007495 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007496 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007497 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007498 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007499 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007500 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007501 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007502 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007503 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007504 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007505 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007506 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007507 }else if( strcmp(z,"-eqp")==0 ){
7508 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007509 }else if( strcmp(z,"-eqpfull")==0 ){
7510 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007511 }else if( strcmp(z,"-stats")==0 ){
7512 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007513 }else if( strcmp(z,"-scanstats")==0 ){
7514 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007515 }else if( strcmp(z,"-backslash")==0 ){
7516 /* Undocumented command-line option: -backslash
7517 ** Causes C-style backslash escapes to be evaluated in SQL statements
7518 ** prior to sending the SQL into SQLite. Useful for injecting
7519 ** crazy bytes in the middle of SQL statements for testing and debugging.
7520 */
drhe6e1d122017-03-09 13:50:49 +00007521 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007522 }else if( strcmp(z,"-bail")==0 ){
7523 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007524 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007525 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007526 return 0;
drhc28490c2006-10-26 14:25:58 +00007527 }else if( strcmp(z,"-interactive")==0 ){
7528 stdin_is_interactive = 1;
7529 }else if( strcmp(z,"-batch")==0 ){
7530 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007531 }else if( strcmp(z,"-heap")==0 ){
7532 i++;
drh44dec872014-08-30 15:49:25 +00007533 }else if( strcmp(z,"-scratch")==0 ){
7534 i+=2;
7535 }else if( strcmp(z,"-pagecache")==0 ){
7536 i+=2;
7537 }else if( strcmp(z,"-lookaside")==0 ){
7538 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007539 }else if( strcmp(z,"-mmap")==0 ){
7540 i++;
drha7e61d82011-03-12 17:02:57 +00007541 }else if( strcmp(z,"-vfs")==0 ){
7542 i++;
drh6f25e892011-07-08 17:02:57 +00007543#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007544 }else if( strcmp(z,"-vfstrace")==0 ){
7545 i++;
drh6f25e892011-07-08 17:02:57 +00007546#endif
7547#ifdef SQLITE_ENABLE_MULTIPLEX
7548 }else if( strcmp(z,"-multiplex")==0 ){
7549 i++;
7550#endif
drhcc3b4f82012-02-07 14:13:50 +00007551 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007552 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007553 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007554 /* Run commands that follow -cmd first and separately from commands
7555 ** that simply appear on the command-line. This seems goofy. It would
7556 ** be better if all commands ran in the order that they appear. But
7557 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007558 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007559 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007560 if( z[0]=='.' ){
7561 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007562 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007563 }else{
drh05782482013-10-24 15:20:20 +00007564 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007565 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7566 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007567 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007568 if( bail_on_error ) return rc!=0 ? rc : 1;
7569 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007570 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007571 if( bail_on_error ) return rc;
7572 }
7573 }
drh1e5d0e92000-05-31 23:33:17 +00007574 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007575 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7576 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007577 return 1;
7578 }
drh700c2522016-02-09 18:39:25 +00007579 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007580 }
drh44c2eb12003-04-30 11:38:26 +00007581
drhac5649a2014-11-28 13:35:03 +00007582 if( !readStdin ){
7583 /* Run all arguments that do not begin with '-' as if they were separate
7584 ** command-line inputs, except for the argToSkip argument which contains
7585 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007586 */
drhac5649a2014-11-28 13:35:03 +00007587 for(i=0; i<nCmd; i++){
7588 if( azCmd[i][0]=='.' ){
7589 rc = do_meta_command(azCmd[i], &data);
7590 if( rc ) return rc==2 ? 0 : rc;
7591 }else{
7592 open_db(&data, 0);
7593 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7594 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007595 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007596 return rc!=0 ? rc : 1;
7597 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007598 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007599 return rc;
7600 }
drh6ff13852001-11-25 13:18:23 +00007601 }
drh75897232000-05-29 14:26:00 +00007602 }
drhac5649a2014-11-28 13:35:03 +00007603 free(azCmd);
drh75897232000-05-29 14:26:00 +00007604 }else{
drh44c2eb12003-04-30 11:38:26 +00007605 /* Run commands received from standard input
7606 */
drhc28490c2006-10-26 14:25:58 +00007607 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007608 char *zHome;
7609 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007610 int nHistory;
drh75897232000-05-29 14:26:00 +00007611 printf(
drh743e0032011-12-12 16:51:50 +00007612 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007613 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007614 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007615 );
drhb3735912014-02-10 16:13:42 +00007616 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007617 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007618 printBold("transient in-memory database");
7619 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007620 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007621 }
drhd1459152016-09-16 19:11:03 +00007622 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007623 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007624 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007625 if( (zHistory = malloc(nHistory))!=0 ){
7626 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7627 }
drh67505e72002-04-19 12:34:06 +00007628 }
drhf5ed7ad2015-06-15 14:43:25 +00007629 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007630 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007631 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007632 shell_stifle_history(100);
7633 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007634 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007635 }
drhdaffd0e2001-04-11 14:28:42 +00007636 }else{
drhc28490c2006-10-26 14:25:58 +00007637 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007638 }
7639 }
drh33048c02001-10-01 14:29:22 +00007640 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007641 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007642 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007643 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007644 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007645 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007646 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007647#if !SQLITE_SHELL_IS_UTF8
7648 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7649 sqlite3_free(argv);
7650#endif
drhc28490c2006-10-26 14:25:58 +00007651 return rc;
drh75897232000-05-29 14:26:00 +00007652}