blob: 468d82379ba01764dd1df1d3882a39bb82fcd7db [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
drh75897232000-05-29 14:26:00 +000014*/
mistachkina3b2ff52011-09-16 20:16:36 +000015#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
shane18e526c2008-12-10 22:30:24 +000016/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
drh36f7dd32011-10-13 16:02:17 +000020/*
mistachkin2318d332015-01-12 18:02:52 +000021** If requested, include the SQLite compiler options file for MSVC.
22*/
23#if defined(INCLUDE_MSVC_H)
24#include "msvc.h"
25#endif
26
27/*
drh8cd5b252015-03-02 22:06:43 +000028** No support for loadable extensions in VxWorks.
29*/
drhada3f2b2015-03-23 21:32:50 +000030#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000031# define SQLITE_OMIT_LOAD_EXTENSION 1
32#endif
33
34/*
drh36f7dd32011-10-13 16:02:17 +000035** Enable large-file support for fopen() and friends on unix.
36*/
37#ifndef SQLITE_DISABLE_LFS
38# define _LARGE_FILE 1
39# ifndef _FILE_OFFSET_BITS
40# define _FILE_OFFSET_BITS 64
41# endif
42# define _LARGEFILE_SOURCE 1
43#endif
44
drh75897232000-05-29 14:26:00 +000045#include <stdlib.h>
46#include <string.h>
47#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000048#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000049#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000050#if SQLITE_USER_AUTHENTICATION
51# include "sqlite3userauth.h"
52#endif
drh75897232000-05-29 14:26:00 +000053#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000054#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000055
drh83905c92012-06-21 13:00:37 +000056#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000057# include <signal.h>
chw97185482008-11-17 08:05:31 +000058# if !defined(__RTP__) && !defined(_WRS_KERNEL)
59# include <pwd.h>
60# endif
drhdd45df82002-04-18 12:39:03 +000061# include <unistd.h>
62# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000063#endif
drh75897232000-05-29 14:26:00 +000064
drh0ede9eb2015-01-10 16:49:23 +000065#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000066# include <readline/readline.h>
67# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +000068#endif
danfd34d6d2015-02-25 10:54:53 +000069
drh0ede9eb2015-01-10 16:49:23 +000070#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +000071# include <editline/readline.h>
72#endif
danfd34d6d2015-02-25 10:54:53 +000073
74#if HAVE_EDITLINE || HAVE_READLINE
75
76# define shell_add_history(X) add_history(X)
77# define shell_read_history(X) read_history(X)
78# define shell_write_history(X) write_history(X)
79# define shell_stifle_history(X) stifle_history(X)
80# define shell_readline(X) readline(X)
81
82#elif HAVE_LINENOISE
83
84# include "linenoise.h"
85# define shell_add_history(X) linenoiseHistoryAdd(X)
86# define shell_read_history(X) linenoiseHistoryLoad(X)
87# define shell_write_history(X) linenoiseHistorySave(X)
88# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89# define shell_readline(X) linenoise(X)
90
91#else
92
mistachkin1fe36bb2016-04-04 02:16:44 +000093# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +000094# define shell_write_history(X)
95# define shell_stifle_history(X)
96
97# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +000098#endif
99
danfd34d6d2015-02-25 10:54:53 +0000100
adamd2e8464a2006-09-06 21:39:40 +0000101#if defined(_WIN32) || defined(WIN32)
102# include <io.h>
drh6976c212014-07-24 12:09:47 +0000103# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000104# define isatty(h) _isatty(h)
105# ifndef access
106# define access(f,m) _access((f),(m))
107# endif
108# undef popen
109# define popen _popen
110# undef pclose
111# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000112#else
mistachkin073664d2015-06-17 18:57:37 +0000113 /* Make sure isatty() has a prototype. */
114 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000115
mistachkin073664d2015-06-17 18:57:37 +0000116# if !defined(__RTP__) && !defined(_WRS_KERNEL)
117 /* popen and pclose are not C89 functions and so are
118 ** sometimes omitted from the <stdio.h> header */
119 extern FILE *popen(const char*,const char*);
120 extern int pclose(FILE*);
121# else
122# define SQLITE_OMIT_POPEN 1
123# endif
mistachkinf6418892013-08-28 01:54:12 +0000124#endif
drh53371f92013-07-25 17:07:03 +0000125
chw65d3c132007-11-12 21:09:10 +0000126#if defined(_WIN32_WCE)
127/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128 * thus we always assume that we have a console. That can be
129 * overridden with the -batch command line option.
130 */
131#define isatty(x) 1
132#endif
133
drhf0693c82011-10-11 20:41:54 +0000134/* ctype macros that work with signed characters */
135#define IsSpace(X) isspace((unsigned char)X)
136#define IsDigit(X) isdigit((unsigned char)X)
137#define ToLower(X) (char)tolower((unsigned char)X)
138
mistachkin1fe36bb2016-04-04 02:16:44 +0000139#if defined(_WIN32) || defined(WIN32)
140#include <windows.h>
141
142/* string conversion routines only needed on Win32 */
143extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
144extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000146extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000147#endif
148
drh047d4532015-01-18 20:30:23 +0000149/* On Windows, we normally run with output mode of TEXT so that \n characters
150** are automatically translated into \r\n. However, this behavior needs
151** to be disabled in some cases (ex: when generating CSV output and when
152** rendering quoted strings that contain \n characters). The following
153** routines take care of that.
154*/
155#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000156static void setBinaryMode(FILE *file, int isOutput){
157 if( isOutput ) fflush(file);
158 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000159}
mistachkin1fe36bb2016-04-04 02:16:44 +0000160static void setTextMode(FILE *file, int isOutput){
161 if( isOutput ) fflush(file);
162 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000163}
164#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000165# define setBinaryMode(X,Y)
166# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000167#endif
168
drh43408312013-10-30 12:43:36 +0000169
170/* True if the timer is enabled */
171static int enableTimer = 0;
172
173/* Return the current wall-clock time */
174static sqlite3_int64 timeOfDay(void){
175 static sqlite3_vfs *clockVfs = 0;
176 sqlite3_int64 t;
177 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000178 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000179 clockVfs->xCurrentTimeInt64(clockVfs, &t);
180 }else{
181 double r;
182 clockVfs->xCurrentTime(clockVfs, &r);
183 t = (sqlite3_int64)(r*86400000.0);
184 }
185 return t;
186}
187
drh91eb93c2015-03-03 19:56:20 +0000188#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000189#include <sys/time.h>
190#include <sys/resource.h>
191
drh91eb93c2015-03-03 19:56:20 +0000192/* VxWorks does not support getrusage() as far as we can determine */
193#if defined(_WRS_KERNEL) || defined(__RTP__)
194struct rusage {
195 struct timeval ru_utime; /* user CPU time used */
196 struct timeval ru_stime; /* system CPU time used */
197};
198#define getrusage(A,B) memset(B,0,sizeof(*B))
199#endif
200
drhda108222009-02-25 19:07:24 +0000201/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000202static struct rusage sBegin; /* CPU time at start */
203static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000204
drhda108222009-02-25 19:07:24 +0000205/*
206** Begin timing an operation
207*/
208static void beginTimer(void){
209 if( enableTimer ){
210 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000211 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000212 }
213}
214
215/* Return the difference of two time_structs in seconds */
216static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000217 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000218 (double)(pEnd->tv_sec - pStart->tv_sec);
219}
220
221/*
222** Print the timing results.
223*/
224static void endTimer(void){
225 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000226 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000227 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000228 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000229 printf("Run Time: real %.3f user %f sys %f\n",
230 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000231 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
232 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
233 }
234}
shaneb320ccd2009-10-21 03:42:58 +0000235
drhda108222009-02-25 19:07:24 +0000236#define BEGIN_TIMER beginTimer()
237#define END_TIMER endTimer()
238#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000239
240#elif (defined(_WIN32) || defined(WIN32))
241
shaneb320ccd2009-10-21 03:42:58 +0000242/* Saved resource information for the beginning of an operation */
243static HANDLE hProcess;
244static FILETIME ftKernelBegin;
245static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000246static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000247typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
248 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000249static GETPROCTIMES getProcessTimesAddr = NULL;
250
shaneb320ccd2009-10-21 03:42:58 +0000251/*
252** Check to see if we have timer support. Return 1 if necessary
253** support found (or found previously).
254*/
255static int hasTimer(void){
256 if( getProcessTimesAddr ){
257 return 1;
258 } else {
drh4ace5362014-11-10 14:42:28 +0000259 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260 ** versions. See if the version we are running on has it, and if it
261 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000262 */
263 hProcess = GetCurrentProcess();
264 if( hProcess ){
265 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
266 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000267 getProcessTimesAddr =
268 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000269 if( NULL != getProcessTimesAddr ){
270 return 1;
271 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000272 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000273 }
274 }
275 }
276 return 0;
277}
278
279/*
280** Begin timing an operation
281*/
282static void beginTimer(void){
283 if( enableTimer && getProcessTimesAddr ){
284 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000285 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
286 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000287 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000288 }
289}
290
291/* Return the difference of two FILETIME structs in seconds */
292static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
293 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
294 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
295 return (double) ((i64End - i64Start) / 10000000.0);
296}
297
298/*
299** Print the timing results.
300*/
301static void endTimer(void){
302 if( enableTimer && getProcessTimesAddr){
303 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000304 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000305 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000306 printf("Run Time: real %.3f user %f sys %f\n",
307 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000308 timeDiff(&ftUserBegin, &ftUserEnd),
309 timeDiff(&ftKernelBegin, &ftKernelEnd));
310 }
311}
312
313#define BEGIN_TIMER beginTimer()
314#define END_TIMER endTimer()
315#define HAS_TIMER hasTimer()
316
drhda108222009-02-25 19:07:24 +0000317#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000318#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000319#define END_TIMER
320#define HAS_TIMER 0
321#endif
322
shanec0688ea2009-03-05 03:48:06 +0000323/*
324** Used to prevent warnings about unused parameters
325*/
326#define UNUSED_PARAMETER(x) (void)(x)
327
drhe91d16b2008-12-08 18:27:31 +0000328/*
drhc49f44e2006-10-26 18:15:42 +0000329** If the following flag is set, then command execution stops
330** at an error if we are not interactive.
331*/
332static int bail_on_error = 0;
333
334/*
drhc28490c2006-10-26 14:25:58 +0000335** Threat stdin as an interactive input if the following variable
336** is true. Otherwise, assume stdin is connected to a file or pipe.
337*/
338static int stdin_is_interactive = 1;
339
340/*
drhe05461c2015-12-30 13:36:57 +0000341** On Windows systems we have to know if standard output is a console
342** in order to translate UTF-8 into MBCS. The following variable is
343** true if translation is required.
344*/
345static int stdout_is_console = 1;
346
347/*
drh4c504392000-10-16 22:06:40 +0000348** The following is the open SQLite database. We make a pointer
349** to this database a static variable so that it can be accessed
350** by the SIGINT handler to interrupt database processing.
351*/
mistachkin8e189222015-04-19 21:43:16 +0000352static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000353
354/*
drh67505e72002-04-19 12:34:06 +0000355** True if an interrupt (Control-C) has been received.
356*/
drh43617e92006-03-06 20:55:46 +0000357static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000358
359/*
persicom7e2dfdd2002-04-18 02:46:52 +0000360** This is the name of our program. It is set in main(), used
361** in a number of other places, mostly for error messages.
362*/
363static char *Argv0;
364
365/*
366** Prompt strings. Initialized in main. Settable with
367** .prompt main continue
368*/
369static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
370static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
371
drhb0603412007-02-28 04:47:26 +0000372/*
mistachkin710b33b2016-01-03 18:59:28 +0000373** Render output like fprintf(). Except, if the output is going to the
374** console and if this is running on a Windows machine, translate the
375** output from UTF-8 into MBCS.
376*/
377#if defined(_WIN32) || defined(WIN32)
378void utf8_printf(FILE *out, const char *zFormat, ...){
379 va_list ap;
380 va_start(ap, zFormat);
381 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000382 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000383 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000384 sqlite3_free(z1);
385 fputs(z2, out);
386 sqlite3_free(z2);
387 }else{
388 vfprintf(out, zFormat, ap);
389 }
390 va_end(ap);
391}
392#elif !defined(utf8_printf)
393# define utf8_printf fprintf
394#endif
395
396/*
397** Render output like fprintf(). This should not be used on anything that
398** includes string formatting (e.g. "%s").
399*/
400#if !defined(raw_printf)
401# define raw_printf fprintf
402#endif
403
404/*
drhb0603412007-02-28 04:47:26 +0000405** Write I/O traces to the following stream.
406*/
rsebe0a9092007-07-30 18:24:38 +0000407#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000408static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000409#endif
drhb0603412007-02-28 04:47:26 +0000410
411/*
412** This routine works like printf in that its first argument is a
413** format string and subsequent arguments are values to be substituted
414** in place of % fields. The result of formatting this string
415** is written to iotrace.
416*/
rsebe0a9092007-07-30 18:24:38 +0000417#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000418static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000419 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000420 char *z;
drhb0603412007-02-28 04:47:26 +0000421 if( iotrace==0 ) return;
422 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000423 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000424 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000425 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000426 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000427}
rsebe0a9092007-07-30 18:24:38 +0000428#endif
drhb0603412007-02-28 04:47:26 +0000429
drh6887e8f2017-04-17 13:18:42 +0000430/*
431** Output string zUtf to stream pOut as w characters. If w is negative,
432** then right-justify the text. W is the width in UTF-8 characters, not
433** in bytes. This is different from the %*.*s specification in printf
434** since with %*.*s the width is measured in bytes, not characters.
435*/
436static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
437 int i;
438 int n;
439 int aw = w<0 ? -w : w;
440 char zBuf[1000];
drhf8a2e8c2017-05-06 17:12:52 +0000441 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
drh6887e8f2017-04-17 13:18:42 +0000442 for(i=n=0; zUtf[i]; i++){
443 if( (zUtf[i]&0xc0)!=0x80 ){
444 n++;
445 if( n==aw ){
446 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
447 break;
448 }
449 }
450 }
451 if( n>=aw ){
452 utf8_printf(pOut, "%.*s", i, zUtf);
453 }else if( w<0 ){
454 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
455 }else{
456 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
457 }
458}
459
drh44c2eb12003-04-30 11:38:26 +0000460
persicom7e2dfdd2002-04-18 02:46:52 +0000461/*
drh83965662003-04-17 02:54:13 +0000462** Determines if a string is a number of not.
463*/
danielk19772e588c72005-12-09 14:25:08 +0000464static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000465 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000466 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000467 return 0;
468 }
469 z++;
470 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000471 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000472 if( *z=='.' ){
473 z++;
drhf0693c82011-10-11 20:41:54 +0000474 if( !IsDigit(*z) ) return 0;
475 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000476 if( realnum ) *realnum = 1;
477 }
478 if( *z=='e' || *z=='E' ){
479 z++;
480 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000481 if( !IsDigit(*z) ) return 0;
482 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000483 if( realnum ) *realnum = 1;
484 }
485 return *z==0;
486}
drh83965662003-04-17 02:54:13 +0000487
488/*
drhe05461c2015-12-30 13:36:57 +0000489** Compute a string length that is limited to what can be stored in
490** lower 30 bits of a 32-bit signed integer.
491*/
492static int strlen30(const char *z){
493 const char *z2 = z;
494 while( *z2 ){ z2++; }
495 return 0x3fffffff & (int)(z2 - z);
496}
497
498/*
drhfeac5f82004-08-01 00:10:45 +0000499** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000500** the text in memory obtained from malloc() and returns a pointer
501** to the text. NULL is returned at end of file, or if malloc()
502** fails.
503**
drh9f099fd2013-08-06 14:01:46 +0000504** If zLine is not NULL then it is a malloced buffer returned from
505** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000506*/
drh9f099fd2013-08-06 14:01:46 +0000507static char *local_getline(char *zLine, FILE *in){
508 int nLine = zLine==0 ? 0 : 100;
509 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000510
drhb07028f2011-10-14 21:49:18 +0000511 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000512 if( n+100>nLine ){
513 nLine = nLine*2 + 100;
514 zLine = realloc(zLine, nLine);
515 if( zLine==0 ) return 0;
516 }
drhdaffd0e2001-04-11 14:28:42 +0000517 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000518 if( n==0 ){
519 free(zLine);
520 return 0;
521 }
522 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000523 break;
524 }
drh9f099fd2013-08-06 14:01:46 +0000525 while( zLine[n] ) n++;
526 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000527 n--;
shaneh13b36022009-12-17 21:07:15 +0000528 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000529 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000530 break;
drh8e7e7a22000-05-30 18:45:23 +0000531 }
532 }
drhe05461c2015-12-30 13:36:57 +0000533#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000534 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000535 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000536 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000537 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000538 if( zTrans ){
539 int nTrans = strlen30(zTrans)+1;
540 if( nTrans>nLine ){
541 zLine = realloc(zLine, nTrans);
542 if( zLine==0 ){
543 sqlite3_free(zTrans);
544 return 0;
545 }
546 }
547 memcpy(zLine, zTrans, nTrans);
548 sqlite3_free(zTrans);
549 }
550 }
551#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000552 return zLine;
553}
554
555/*
drhc28490c2006-10-26 14:25:58 +0000556** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000557**
drh9f099fd2013-08-06 14:01:46 +0000558** If in==0 then read from standard input and prompt before each line.
559** If isContinuation is true, then a continuation prompt is appropriate.
560** If isContinuation is zero, then the main prompt should be used.
561**
562** If zPrior is not NULL then it is a buffer from a prior call to this
563** routine that can be reused.
564**
565** The result is stored in space obtained from malloc() and must either
566** be freed by the caller or else passed back into this routine via the
567** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000568*/
drh9f099fd2013-08-06 14:01:46 +0000569static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000570 char *zPrompt;
571 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000572 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000573 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000574 }else{
drh9f099fd2013-08-06 14:01:46 +0000575 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000576#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000577 printf("%s", zPrompt);
578 fflush(stdout);
579 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000580#else
581 free(zPrior);
582 zResult = shell_readline(zPrompt);
583 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000584#endif
drh9f099fd2013-08-06 14:01:46 +0000585 }
drh8e7e7a22000-05-30 18:45:23 +0000586 return zResult;
587}
drhf42d3182017-03-08 12:25:18 +0000588/*
589** A variable length string to which one can append text.
590*/
591typedef struct ShellText ShellText;
592struct ShellText {
593 char *z;
594 int n;
595 int nAlloc;
596};
597
598/*
599** Initialize and destroy a ShellText object
600*/
601static void initText(ShellText *p){
602 memset(p, 0, sizeof(*p));
603}
604static void freeText(ShellText *p){
605 free(p->z);
606 initText(p);
607}
608
609/* zIn is either a pointer to a NULL-terminated string in memory obtained
610** from malloc(), or a NULL pointer. The string pointed to by zAppend is
611** added to zIn, and the result returned in memory obtained from malloc().
612** zIn, if it was not NULL, is freed.
613**
614** If the third argument, quote, is not '\0', then it is used as a
615** quote character for zAppend.
616*/
617static void appendText(ShellText *p, char const *zAppend, char quote){
618 int len;
619 int i;
620 int nAppend = strlen30(zAppend);
621
622 len = nAppend+p->n+1;
623 if( quote ){
624 len += 2;
625 for(i=0; i<nAppend; i++){
626 if( zAppend[i]==quote ) len++;
627 }
628 }
629
630 if( p->n+len>=p->nAlloc ){
631 p->nAlloc = p->nAlloc*2 + len + 20;
632 p->z = realloc(p->z, p->nAlloc);
633 if( p->z==0 ){
634 memset(p, 0, sizeof(*p));
635 return;
636 }
637 }
638
639 if( quote ){
640 char *zCsr = p->z+p->n;
641 *zCsr++ = quote;
642 for(i=0; i<nAppend; i++){
643 *zCsr++ = zAppend[i];
644 if( zAppend[i]==quote ) *zCsr++ = quote;
645 }
646 *zCsr++ = quote;
647 p->n = (int)(zCsr - p->z);
648 *zCsr = '\0';
649 }else{
650 memcpy(p->z+p->n, zAppend, nAppend);
651 p->n += nAppend;
652 p->z[p->n] = '\0';
653 }
654}
655
656/*
657** Attempt to determine if identifier zName needs to be quoted, either
658** because it contains non-alphanumeric characters, or because it is an
659** SQLite keyword. Be conservative in this estimate: When in doubt assume
660** that quoting is required.
661**
662** Return '"' if quoting is required. Return 0 if no quoting is required.
663*/
664static char quoteChar(const char *zName){
665 /* All SQLite keywords, in alphabetical order */
666 static const char *azKeywords[] = {
667 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
668 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
669 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
670 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
671 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
672 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
673 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
674 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
675 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
676 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
677 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
678 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
679 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
680 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
681 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
682 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
683 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
684 "WITH", "WITHOUT",
685 };
686 int i, lwr, upr, mid, c;
687 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
688 for(i=0; zName[i]; i++){
689 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
690 }
691 lwr = 0;
692 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
693 while( lwr<=upr ){
694 mid = (lwr+upr)/2;
695 c = sqlite3_stricmp(azKeywords[mid], zName);
696 if( c==0 ) return '"';
697 if( c<0 ){
698 lwr = mid+1;
699 }else{
700 upr = mid-1;
701 }
702 }
703 return 0;
704}
drh8e7e7a22000-05-30 18:45:23 +0000705
drh1554bc82017-03-08 16:10:34 +0000706/******************************************************************************
707** SHA3 hash implementation copied from ../ext/misc/shathree.c
708*/
709typedef sqlite3_uint64 u64;
710/*
711** Macros to determine whether the machine is big or little endian,
712** and whether or not that determination is run-time or compile-time.
713**
714** For best performance, an attempt is made to guess at the byte-order
715** using C-preprocessor macros. If that is unsuccessful, or if
716** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
717** at run-time.
718*/
719#ifndef SHA3_BYTEORDER
720# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
721 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
722 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
723 defined(__arm__)
724# define SHA3_BYTEORDER 1234
725# elif defined(sparc) || defined(__ppc__)
726# define SHA3_BYTEORDER 4321
727# else
728# define SHA3_BYTEORDER 0
729# endif
730#endif
731
732
733/*
734** State structure for a SHA3 hash in progress
735*/
736typedef struct SHA3Context SHA3Context;
737struct SHA3Context {
738 union {
739 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
740 unsigned char x[1600]; /* ... or 1600 bytes */
741 } u;
742 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
743 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
744 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
745};
746
drh050b1242017-05-04 11:13:50 +0000747/* Allow the following routine to use the B0 variable, which is also
748** a macro in the termios.h header file */
749#undef B0
750
drh1554bc82017-03-08 16:10:34 +0000751/*
752** A single step of the Keccak mixing function for a 1600-bit state
753*/
754static void KeccakF1600Step(SHA3Context *p){
755 int i;
756 u64 B0, B1, B2, B3, B4;
757 u64 C0, C1, C2, C3, C4;
758 u64 D0, D1, D2, D3, D4;
759 static const u64 RC[] = {
760 0x0000000000000001ULL, 0x0000000000008082ULL,
761 0x800000000000808aULL, 0x8000000080008000ULL,
762 0x000000000000808bULL, 0x0000000080000001ULL,
763 0x8000000080008081ULL, 0x8000000000008009ULL,
764 0x000000000000008aULL, 0x0000000000000088ULL,
765 0x0000000080008009ULL, 0x000000008000000aULL,
766 0x000000008000808bULL, 0x800000000000008bULL,
767 0x8000000000008089ULL, 0x8000000000008003ULL,
768 0x8000000000008002ULL, 0x8000000000000080ULL,
769 0x000000000000800aULL, 0x800000008000000aULL,
770 0x8000000080008081ULL, 0x8000000000008080ULL,
771 0x0000000080000001ULL, 0x8000000080008008ULL
772 };
773# define A00 (p->u.s[0])
774# define A01 (p->u.s[1])
775# define A02 (p->u.s[2])
776# define A03 (p->u.s[3])
777# define A04 (p->u.s[4])
778# define A10 (p->u.s[5])
779# define A11 (p->u.s[6])
780# define A12 (p->u.s[7])
781# define A13 (p->u.s[8])
782# define A14 (p->u.s[9])
783# define A20 (p->u.s[10])
784# define A21 (p->u.s[11])
785# define A22 (p->u.s[12])
786# define A23 (p->u.s[13])
787# define A24 (p->u.s[14])
788# define A30 (p->u.s[15])
789# define A31 (p->u.s[16])
790# define A32 (p->u.s[17])
791# define A33 (p->u.s[18])
792# define A34 (p->u.s[19])
793# define A40 (p->u.s[20])
794# define A41 (p->u.s[21])
795# define A42 (p->u.s[22])
796# define A43 (p->u.s[23])
797# define A44 (p->u.s[24])
798# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
799
800 for(i=0; i<24; i+=4){
801 C0 = A00^A10^A20^A30^A40;
802 C1 = A01^A11^A21^A31^A41;
803 C2 = A02^A12^A22^A32^A42;
804 C3 = A03^A13^A23^A33^A43;
805 C4 = A04^A14^A24^A34^A44;
806 D0 = C4^ROL64(C1, 1);
807 D1 = C0^ROL64(C2, 1);
808 D2 = C1^ROL64(C3, 1);
809 D3 = C2^ROL64(C4, 1);
810 D4 = C3^ROL64(C0, 1);
811
812 B0 = (A00^D0);
813 B1 = ROL64((A11^D1), 44);
814 B2 = ROL64((A22^D2), 43);
815 B3 = ROL64((A33^D3), 21);
816 B4 = ROL64((A44^D4), 14);
817 A00 = B0 ^((~B1)& B2 );
818 A00 ^= RC[i];
819 A11 = B1 ^((~B2)& B3 );
820 A22 = B2 ^((~B3)& B4 );
821 A33 = B3 ^((~B4)& B0 );
822 A44 = B4 ^((~B0)& B1 );
823
824 B2 = ROL64((A20^D0), 3);
825 B3 = ROL64((A31^D1), 45);
826 B4 = ROL64((A42^D2), 61);
827 B0 = ROL64((A03^D3), 28);
828 B1 = ROL64((A14^D4), 20);
829 A20 = B0 ^((~B1)& B2 );
830 A31 = B1 ^((~B2)& B3 );
831 A42 = B2 ^((~B3)& B4 );
832 A03 = B3 ^((~B4)& B0 );
833 A14 = B4 ^((~B0)& B1 );
834
835 B4 = ROL64((A40^D0), 18);
836 B0 = ROL64((A01^D1), 1);
837 B1 = ROL64((A12^D2), 6);
838 B2 = ROL64((A23^D3), 25);
839 B3 = ROL64((A34^D4), 8);
840 A40 = B0 ^((~B1)& B2 );
841 A01 = B1 ^((~B2)& B3 );
842 A12 = B2 ^((~B3)& B4 );
843 A23 = B3 ^((~B4)& B0 );
844 A34 = B4 ^((~B0)& B1 );
845
846 B1 = ROL64((A10^D0), 36);
847 B2 = ROL64((A21^D1), 10);
848 B3 = ROL64((A32^D2), 15);
849 B4 = ROL64((A43^D3), 56);
850 B0 = ROL64((A04^D4), 27);
851 A10 = B0 ^((~B1)& B2 );
852 A21 = B1 ^((~B2)& B3 );
853 A32 = B2 ^((~B3)& B4 );
854 A43 = B3 ^((~B4)& B0 );
855 A04 = B4 ^((~B0)& B1 );
856
857 B3 = ROL64((A30^D0), 41);
858 B4 = ROL64((A41^D1), 2);
859 B0 = ROL64((A02^D2), 62);
860 B1 = ROL64((A13^D3), 55);
861 B2 = ROL64((A24^D4), 39);
862 A30 = B0 ^((~B1)& B2 );
863 A41 = B1 ^((~B2)& B3 );
864 A02 = B2 ^((~B3)& B4 );
865 A13 = B3 ^((~B4)& B0 );
866 A24 = B4 ^((~B0)& B1 );
867
868 C0 = A00^A20^A40^A10^A30;
869 C1 = A11^A31^A01^A21^A41;
870 C2 = A22^A42^A12^A32^A02;
871 C3 = A33^A03^A23^A43^A13;
872 C4 = A44^A14^A34^A04^A24;
873 D0 = C4^ROL64(C1, 1);
874 D1 = C0^ROL64(C2, 1);
875 D2 = C1^ROL64(C3, 1);
876 D3 = C2^ROL64(C4, 1);
877 D4 = C3^ROL64(C0, 1);
878
879 B0 = (A00^D0);
880 B1 = ROL64((A31^D1), 44);
881 B2 = ROL64((A12^D2), 43);
882 B3 = ROL64((A43^D3), 21);
883 B4 = ROL64((A24^D4), 14);
884 A00 = B0 ^((~B1)& B2 );
885 A00 ^= RC[i+1];
886 A31 = B1 ^((~B2)& B3 );
887 A12 = B2 ^((~B3)& B4 );
888 A43 = B3 ^((~B4)& B0 );
889 A24 = B4 ^((~B0)& B1 );
890
891 B2 = ROL64((A40^D0), 3);
892 B3 = ROL64((A21^D1), 45);
893 B4 = ROL64((A02^D2), 61);
894 B0 = ROL64((A33^D3), 28);
895 B1 = ROL64((A14^D4), 20);
896 A40 = B0 ^((~B1)& B2 );
897 A21 = B1 ^((~B2)& B3 );
898 A02 = B2 ^((~B3)& B4 );
899 A33 = B3 ^((~B4)& B0 );
900 A14 = B4 ^((~B0)& B1 );
901
902 B4 = ROL64((A30^D0), 18);
903 B0 = ROL64((A11^D1), 1);
904 B1 = ROL64((A42^D2), 6);
905 B2 = ROL64((A23^D3), 25);
906 B3 = ROL64((A04^D4), 8);
907 A30 = B0 ^((~B1)& B2 );
908 A11 = B1 ^((~B2)& B3 );
909 A42 = B2 ^((~B3)& B4 );
910 A23 = B3 ^((~B4)& B0 );
911 A04 = B4 ^((~B0)& B1 );
912
913 B1 = ROL64((A20^D0), 36);
914 B2 = ROL64((A01^D1), 10);
915 B3 = ROL64((A32^D2), 15);
916 B4 = ROL64((A13^D3), 56);
917 B0 = ROL64((A44^D4), 27);
918 A20 = B0 ^((~B1)& B2 );
919 A01 = B1 ^((~B2)& B3 );
920 A32 = B2 ^((~B3)& B4 );
921 A13 = B3 ^((~B4)& B0 );
922 A44 = B4 ^((~B0)& B1 );
923
924 B3 = ROL64((A10^D0), 41);
925 B4 = ROL64((A41^D1), 2);
926 B0 = ROL64((A22^D2), 62);
927 B1 = ROL64((A03^D3), 55);
928 B2 = ROL64((A34^D4), 39);
929 A10 = B0 ^((~B1)& B2 );
930 A41 = B1 ^((~B2)& B3 );
931 A22 = B2 ^((~B3)& B4 );
932 A03 = B3 ^((~B4)& B0 );
933 A34 = B4 ^((~B0)& B1 );
934
935 C0 = A00^A40^A30^A20^A10;
936 C1 = A31^A21^A11^A01^A41;
937 C2 = A12^A02^A42^A32^A22;
938 C3 = A43^A33^A23^A13^A03;
939 C4 = A24^A14^A04^A44^A34;
940 D0 = C4^ROL64(C1, 1);
941 D1 = C0^ROL64(C2, 1);
942 D2 = C1^ROL64(C3, 1);
943 D3 = C2^ROL64(C4, 1);
944 D4 = C3^ROL64(C0, 1);
945
946 B0 = (A00^D0);
947 B1 = ROL64((A21^D1), 44);
948 B2 = ROL64((A42^D2), 43);
949 B3 = ROL64((A13^D3), 21);
950 B4 = ROL64((A34^D4), 14);
951 A00 = B0 ^((~B1)& B2 );
952 A00 ^= RC[i+2];
953 A21 = B1 ^((~B2)& B3 );
954 A42 = B2 ^((~B3)& B4 );
955 A13 = B3 ^((~B4)& B0 );
956 A34 = B4 ^((~B0)& B1 );
957
958 B2 = ROL64((A30^D0), 3);
959 B3 = ROL64((A01^D1), 45);
960 B4 = ROL64((A22^D2), 61);
961 B0 = ROL64((A43^D3), 28);
962 B1 = ROL64((A14^D4), 20);
963 A30 = B0 ^((~B1)& B2 );
964 A01 = B1 ^((~B2)& B3 );
965 A22 = B2 ^((~B3)& B4 );
966 A43 = B3 ^((~B4)& B0 );
967 A14 = B4 ^((~B0)& B1 );
968
969 B4 = ROL64((A10^D0), 18);
970 B0 = ROL64((A31^D1), 1);
971 B1 = ROL64((A02^D2), 6);
972 B2 = ROL64((A23^D3), 25);
973 B3 = ROL64((A44^D4), 8);
974 A10 = B0 ^((~B1)& B2 );
975 A31 = B1 ^((~B2)& B3 );
976 A02 = B2 ^((~B3)& B4 );
977 A23 = B3 ^((~B4)& B0 );
978 A44 = B4 ^((~B0)& B1 );
979
980 B1 = ROL64((A40^D0), 36);
981 B2 = ROL64((A11^D1), 10);
982 B3 = ROL64((A32^D2), 15);
983 B4 = ROL64((A03^D3), 56);
984 B0 = ROL64((A24^D4), 27);
985 A40 = B0 ^((~B1)& B2 );
986 A11 = B1 ^((~B2)& B3 );
987 A32 = B2 ^((~B3)& B4 );
988 A03 = B3 ^((~B4)& B0 );
989 A24 = B4 ^((~B0)& B1 );
990
991 B3 = ROL64((A20^D0), 41);
992 B4 = ROL64((A41^D1), 2);
993 B0 = ROL64((A12^D2), 62);
994 B1 = ROL64((A33^D3), 55);
995 B2 = ROL64((A04^D4), 39);
996 A20 = B0 ^((~B1)& B2 );
997 A41 = B1 ^((~B2)& B3 );
998 A12 = B2 ^((~B3)& B4 );
999 A33 = B3 ^((~B4)& B0 );
1000 A04 = B4 ^((~B0)& B1 );
1001
1002 C0 = A00^A30^A10^A40^A20;
1003 C1 = A21^A01^A31^A11^A41;
1004 C2 = A42^A22^A02^A32^A12;
1005 C3 = A13^A43^A23^A03^A33;
1006 C4 = A34^A14^A44^A24^A04;
1007 D0 = C4^ROL64(C1, 1);
1008 D1 = C0^ROL64(C2, 1);
1009 D2 = C1^ROL64(C3, 1);
1010 D3 = C2^ROL64(C4, 1);
1011 D4 = C3^ROL64(C0, 1);
1012
1013 B0 = (A00^D0);
1014 B1 = ROL64((A01^D1), 44);
1015 B2 = ROL64((A02^D2), 43);
1016 B3 = ROL64((A03^D3), 21);
1017 B4 = ROL64((A04^D4), 14);
1018 A00 = B0 ^((~B1)& B2 );
1019 A00 ^= RC[i+3];
1020 A01 = B1 ^((~B2)& B3 );
1021 A02 = B2 ^((~B3)& B4 );
1022 A03 = B3 ^((~B4)& B0 );
1023 A04 = B4 ^((~B0)& B1 );
1024
1025 B2 = ROL64((A10^D0), 3);
1026 B3 = ROL64((A11^D1), 45);
1027 B4 = ROL64((A12^D2), 61);
1028 B0 = ROL64((A13^D3), 28);
1029 B1 = ROL64((A14^D4), 20);
1030 A10 = B0 ^((~B1)& B2 );
1031 A11 = B1 ^((~B2)& B3 );
1032 A12 = B2 ^((~B3)& B4 );
1033 A13 = B3 ^((~B4)& B0 );
1034 A14 = B4 ^((~B0)& B1 );
1035
1036 B4 = ROL64((A20^D0), 18);
1037 B0 = ROL64((A21^D1), 1);
1038 B1 = ROL64((A22^D2), 6);
1039 B2 = ROL64((A23^D3), 25);
1040 B3 = ROL64((A24^D4), 8);
1041 A20 = B0 ^((~B1)& B2 );
1042 A21 = B1 ^((~B2)& B3 );
1043 A22 = B2 ^((~B3)& B4 );
1044 A23 = B3 ^((~B4)& B0 );
1045 A24 = B4 ^((~B0)& B1 );
1046
1047 B1 = ROL64((A30^D0), 36);
1048 B2 = ROL64((A31^D1), 10);
1049 B3 = ROL64((A32^D2), 15);
1050 B4 = ROL64((A33^D3), 56);
1051 B0 = ROL64((A34^D4), 27);
1052 A30 = B0 ^((~B1)& B2 );
1053 A31 = B1 ^((~B2)& B3 );
1054 A32 = B2 ^((~B3)& B4 );
1055 A33 = B3 ^((~B4)& B0 );
1056 A34 = B4 ^((~B0)& B1 );
1057
1058 B3 = ROL64((A40^D0), 41);
1059 B4 = ROL64((A41^D1), 2);
1060 B0 = ROL64((A42^D2), 62);
1061 B1 = ROL64((A43^D3), 55);
1062 B2 = ROL64((A44^D4), 39);
1063 A40 = B0 ^((~B1)& B2 );
1064 A41 = B1 ^((~B2)& B3 );
1065 A42 = B2 ^((~B3)& B4 );
1066 A43 = B3 ^((~B4)& B0 );
1067 A44 = B4 ^((~B0)& B1 );
1068 }
1069}
1070
1071/*
1072** Initialize a new hash. iSize determines the size of the hash
1073** in bits and should be one of 224, 256, 384, or 512. Or iSize
1074** can be zero to use the default hash size of 256 bits.
1075*/
1076static void SHA3Init(SHA3Context *p, int iSize){
1077 memset(p, 0, sizeof(*p));
1078 if( iSize>=128 && iSize<=512 ){
1079 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1080 }else{
1081 p->nRate = (1600 - 2*256)/8;
1082 }
1083#if SHA3_BYTEORDER==1234
1084 /* Known to be little-endian at compile-time. No-op */
1085#elif SHA3_BYTEORDER==4321
1086 p->ixMask = 7; /* Big-endian */
1087#else
1088 {
1089 static unsigned int one = 1;
1090 if( 1==*(unsigned char*)&one ){
1091 /* Little endian. No byte swapping. */
1092 p->ixMask = 0;
1093 }else{
1094 /* Big endian. Byte swap. */
1095 p->ixMask = 7;
1096 }
1097 }
1098#endif
1099}
1100
1101/*
1102** Make consecutive calls to the SHA3Update function to add new content
1103** to the hash
1104*/
1105static void SHA3Update(
1106 SHA3Context *p,
1107 const unsigned char *aData,
1108 unsigned int nData
1109){
1110 unsigned int i = 0;
1111#if SHA3_BYTEORDER==1234
1112 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1113 for(; i+7<nData; i+=8){
1114 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1115 p->nLoaded += 8;
1116 if( p->nLoaded>=p->nRate ){
1117 KeccakF1600Step(p);
1118 p->nLoaded = 0;
1119 }
1120 }
1121 }
1122#endif
1123 for(; i<nData; i++){
1124#if SHA3_BYTEORDER==1234
1125 p->u.x[p->nLoaded] ^= aData[i];
1126#elif SHA3_BYTEORDER==4321
1127 p->u.x[p->nLoaded^0x07] ^= aData[i];
1128#else
1129 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1130#endif
1131 p->nLoaded++;
1132 if( p->nLoaded==p->nRate ){
1133 KeccakF1600Step(p);
1134 p->nLoaded = 0;
1135 }
1136 }
1137}
1138
1139/*
1140** After all content has been added, invoke SHA3Final() to compute
1141** the final hash. The function returns a pointer to the binary
1142** hash value.
1143*/
1144static unsigned char *SHA3Final(SHA3Context *p){
1145 unsigned int i;
1146 if( p->nLoaded==p->nRate-1 ){
1147 const unsigned char c1 = 0x86;
1148 SHA3Update(p, &c1, 1);
1149 }else{
1150 const unsigned char c2 = 0x06;
1151 const unsigned char c3 = 0x80;
1152 SHA3Update(p, &c2, 1);
1153 p->nLoaded = p->nRate - 1;
1154 SHA3Update(p, &c3, 1);
1155 }
1156 for(i=0; i<p->nRate; i++){
1157 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1158 }
1159 return &p->u.x[p->nRate];
1160}
1161
1162/*
1163** Implementation of the sha3(X,SIZE) function.
1164**
1165** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
1166** size is 256. If X is a BLOB, it is hashed as is.
1167** For all other non-NULL types of input, X is converted into a UTF-8 string
1168** and the string is hashed without the trailing 0x00 terminator. The hash
1169** of a NULL value is NULL.
1170*/
1171static void sha3Func(
1172 sqlite3_context *context,
1173 int argc,
1174 sqlite3_value **argv
1175){
1176 SHA3Context cx;
1177 int eType = sqlite3_value_type(argv[0]);
1178 int nByte = sqlite3_value_bytes(argv[0]);
1179 int iSize;
1180 if( argc==1 ){
1181 iSize = 256;
1182 }else{
1183 iSize = sqlite3_value_int(argv[1]);
1184 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1185 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1186 "384 512", -1);
1187 return;
1188 }
1189 }
1190 if( eType==SQLITE_NULL ) return;
1191 SHA3Init(&cx, iSize);
1192 if( eType==SQLITE_BLOB ){
1193 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1194 }else{
1195 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1196 }
1197 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1198}
1199
1200/* Compute a string using sqlite3_vsnprintf() with a maximum length
1201** of 50 bytes and add it to the hash.
1202*/
1203static void hash_step_vformat(
1204 SHA3Context *p, /* Add content to this context */
1205 const char *zFormat,
1206 ...
1207){
1208 va_list ap;
1209 int n;
1210 char zBuf[50];
1211 va_start(ap, zFormat);
1212 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1213 va_end(ap);
1214 n = (int)strlen(zBuf);
1215 SHA3Update(p, (unsigned char*)zBuf, n);
1216}
1217
1218/*
1219** Implementation of the sha3_query(SQL,SIZE) function.
1220**
1221** This function compiles and runs the SQL statement(s) given in the
1222** argument. The results are hashed using a SIZE-bit SHA3. The default
1223** size is 256.
1224**
1225** The format of the byte stream that is hashed is summarized as follows:
1226**
1227** S<n>:<sql>
1228** R
1229** N
1230** I<int>
1231** F<ieee-float>
1232** B<size>:<bytes>
1233** T<size>:<text>
1234**
1235** <sql> is the original SQL text for each statement run and <n> is
1236** the size of that text. The SQL text is UTF-8. A single R character
1237** occurs before the start of each row. N means a NULL value.
1238** I mean an 8-byte little-endian integer <int>. F is a floating point
1239** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1240** B means blobs of <size> bytes. T means text rendered as <size>
1241** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1242** text integers.
1243**
1244** For each SQL statement in the X input, there is one S segment. Each
1245** S segment is followed by zero or more R segments, one for each row in the
1246** result set. After each R, there are one or more N, I, F, B, or T segments,
1247** one for each column in the result set. Segments are concatentated directly
1248** with no delimiters of any kind.
1249*/
1250static void sha3QueryFunc(
1251 sqlite3_context *context,
1252 int argc,
1253 sqlite3_value **argv
1254){
1255 sqlite3 *db = sqlite3_context_db_handle(context);
1256 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1257 sqlite3_stmt *pStmt = 0;
1258 int nCol; /* Number of columns in the result set */
1259 int i; /* Loop counter */
1260 int rc;
1261 int n;
1262 const char *z;
1263 SHA3Context cx;
1264 int iSize;
1265
1266 if( argc==1 ){
1267 iSize = 256;
1268 }else{
1269 iSize = sqlite3_value_int(argv[1]);
1270 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1271 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1272 "384 512", -1);
1273 return;
1274 }
1275 }
1276 if( zSql==0 ) return;
1277 SHA3Init(&cx, iSize);
1278 while( zSql[0] ){
1279 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1280 if( rc ){
1281 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1282 zSql, sqlite3_errmsg(db));
1283 sqlite3_finalize(pStmt);
1284 sqlite3_result_error(context, zMsg, -1);
1285 sqlite3_free(zMsg);
1286 return;
1287 }
1288 if( !sqlite3_stmt_readonly(pStmt) ){
1289 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1290 sqlite3_finalize(pStmt);
1291 sqlite3_result_error(context, zMsg, -1);
1292 sqlite3_free(zMsg);
1293 return;
1294 }
1295 nCol = sqlite3_column_count(pStmt);
1296 z = sqlite3_sql(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00001297 if( z==0 ){
1298 sqlite3_finalize(pStmt);
1299 continue;
1300 }
drh1554bc82017-03-08 16:10:34 +00001301 n = (int)strlen(z);
1302 hash_step_vformat(&cx,"S%d:",n);
1303 SHA3Update(&cx,(unsigned char*)z,n);
1304
1305 /* Compute a hash over the result of the query */
1306 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1307 SHA3Update(&cx,(const unsigned char*)"R",1);
1308 for(i=0; i<nCol; i++){
1309 switch( sqlite3_column_type(pStmt,i) ){
1310 case SQLITE_NULL: {
1311 SHA3Update(&cx, (const unsigned char*)"N",1);
1312 break;
1313 }
1314 case SQLITE_INTEGER: {
1315 sqlite3_uint64 u;
1316 int j;
1317 unsigned char x[9];
1318 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1319 memcpy(&u, &v, 8);
1320 for(j=8; j>=1; j--){
1321 x[j] = u & 0xff;
1322 u >>= 8;
1323 }
1324 x[0] = 'I';
1325 SHA3Update(&cx, x, 9);
1326 break;
1327 }
1328 case SQLITE_FLOAT: {
1329 sqlite3_uint64 u;
1330 int j;
1331 unsigned char x[9];
1332 double r = sqlite3_column_double(pStmt,i);
1333 memcpy(&u, &r, 8);
1334 for(j=8; j>=1; j--){
1335 x[j] = u & 0xff;
1336 u >>= 8;
1337 }
1338 x[0] = 'F';
1339 SHA3Update(&cx,x,9);
1340 break;
1341 }
1342 case SQLITE_TEXT: {
1343 int n2 = sqlite3_column_bytes(pStmt, i);
1344 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1345 hash_step_vformat(&cx,"T%d:",n2);
1346 SHA3Update(&cx, z2, n2);
1347 break;
1348 }
1349 case SQLITE_BLOB: {
1350 int n2 = sqlite3_column_bytes(pStmt, i);
1351 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1352 hash_step_vformat(&cx,"B%d:",n2);
1353 SHA3Update(&cx, z2, n2);
1354 break;
1355 }
1356 }
1357 }
1358 }
1359 sqlite3_finalize(pStmt);
1360 }
1361 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1362}
1363/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1364********************************************************************************/
1365
drhe6229612014-08-18 15:08:26 +00001366#if defined(SQLITE_ENABLE_SESSION)
1367/*
1368** State information for a single open session
1369*/
1370typedef struct OpenSession OpenSession;
1371struct OpenSession {
1372 char *zName; /* Symbolic name for this session */
1373 int nFilter; /* Number of xFilter rejection GLOB patterns */
1374 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1375 sqlite3_session *p; /* The open session */
1376};
1377#endif
1378
drhdcd87a92014-08-18 13:45:42 +00001379/*
mistachkin1fe36bb2016-04-04 02:16:44 +00001380** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00001381** saved so that it can be restored by ".explain off"
1382*/
1383typedef struct SavedModeInfo SavedModeInfo;
1384struct SavedModeInfo {
1385 int valid; /* Is there legit data in here? */
1386 int mode; /* Mode prior to ".explain on" */
1387 int showHeader; /* The ".header" setting prior to ".explain on" */
1388 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00001389};
drh45e29d82006-11-20 16:21:10 +00001390
drh8e7e7a22000-05-30 18:45:23 +00001391/*
drhdcd87a92014-08-18 13:45:42 +00001392** State information about the database connection is contained in an
1393** instance of the following structure.
drh75897232000-05-29 14:26:00 +00001394*/
drhdcd87a92014-08-18 13:45:42 +00001395typedef struct ShellState ShellState;
1396struct ShellState {
shane626a6e42009-10-22 17:30:15 +00001397 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00001398 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00001399 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00001400 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00001401 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00001402 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00001403 int cnt; /* Number of records displayed so far */
1404 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00001405 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00001406 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00001407 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00001408 int cMode; /* temporary output mode for the current query */
1409 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00001410 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00001411 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00001412 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00001413 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00001414 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00001415 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00001416 char colSeparator[20]; /* Column separator character for several modes */
1417 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00001418 int colWidth[100]; /* Requested width of each column when in column mode*/
1419 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00001420 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00001421 ** the database */
drh44c2eb12003-04-30 11:38:26 +00001422 char outfile[FILENAME_MAX]; /* Filename for *out */
1423 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00001424 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00001425 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00001426 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00001427 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00001428 int *aiIndent; /* Array of indents used in MODE_Explain */
1429 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00001430 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00001431#if defined(SQLITE_ENABLE_SESSION)
1432 int nSession; /* Number of active sessions */
1433 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1434#endif
drh75897232000-05-29 14:26:00 +00001435};
1436
1437/*
drh44dec872014-08-30 15:49:25 +00001438** These are the allowed shellFlgs values
1439*/
drhe6e1d122017-03-09 13:50:49 +00001440#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1441#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1442#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1443#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1444#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1445#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1446#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1447
1448/*
1449** Macros for testing and setting shellFlgs
1450*/
1451#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1452#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1453#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00001454
1455/*
drh75897232000-05-29 14:26:00 +00001456** These are the allowed modes.
1457*/
drh967e8b72000-06-21 13:59:10 +00001458#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00001459#define MODE_Column 1 /* One record per line in neat columns */
1460#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00001461#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1462#define MODE_Html 4 /* Generate an XHTML table */
1463#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00001464#define MODE_Quote 6 /* Quote values as for SQL */
1465#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1466#define MODE_Csv 8 /* Quote strings, numbers are plain */
1467#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1468#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1469#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00001470
drh66ce4d02008-02-15 17:38:06 +00001471static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00001472 "line",
1473 "column",
1474 "list",
1475 "semi",
1476 "html",
drhfeac5f82004-08-01 00:10:45 +00001477 "insert",
drh41f5f6e2016-10-21 17:39:30 +00001478 "quote",
drhfeac5f82004-08-01 00:10:45 +00001479 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00001480 "csv",
drh66ce4d02008-02-15 17:38:06 +00001481 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00001482 "ascii",
drh4926fec2016-04-13 15:33:42 +00001483 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00001484};
drh75897232000-05-29 14:26:00 +00001485
1486/*
mistachkinfad42082014-07-24 22:13:12 +00001487** These are the column/row/line separators used by the various
1488** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00001489*/
mistachkinfad42082014-07-24 22:13:12 +00001490#define SEP_Column "|"
1491#define SEP_Row "\n"
1492#define SEP_Tab "\t"
1493#define SEP_Space " "
1494#define SEP_Comma ","
1495#define SEP_CrLf "\r\n"
1496#define SEP_Unit "\x1F"
1497#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00001498
1499/*
drh75897232000-05-29 14:26:00 +00001500** Number of elements in an array
1501*/
drh902b9ee2008-12-05 17:17:07 +00001502#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00001503
1504/*
drh127f9d72010-02-23 01:47:00 +00001505** A callback for the sqlite3_log() interface.
1506*/
1507static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00001508 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00001509 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00001510 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00001511 fflush(p->pLog);
1512}
1513
1514/*
shane626a6e42009-10-22 17:30:15 +00001515** Output the given string as a hex-encoded blob (eg. X'1234' )
1516*/
1517static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1518 int i;
1519 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00001520 raw_printf(out,"X'");
1521 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1522 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00001523}
1524
1525/*
drh6193d492017-04-07 11:45:58 +00001526** Find a string that is not found anywhere in z[]. Return a pointer
1527** to that string.
1528**
1529** Try to use zA and zB first. If both of those are already found in z[]
1530** then make up some string and store it in the buffer zBuf.
1531*/
1532static const char *unused_string(
1533 const char *z, /* Result must not appear anywhere in z */
1534 const char *zA, const char *zB, /* Try these first */
1535 char *zBuf /* Space to store a generated string */
1536){
1537 unsigned i = 0;
1538 if( strstr(z, zA)==0 ) return zA;
1539 if( strstr(z, zB)==0 ) return zB;
1540 do{
1541 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1542 }while( strstr(z,zBuf)!=0 );
1543 return zBuf;
1544}
1545
1546/*
drh28bd4bc2000-06-15 15:57:22 +00001547** Output the given string as a quoted string using SQL quoting conventions.
drh708b22b2017-03-11 01:56:41 +00001548**
drh13fe1382017-04-08 13:42:55 +00001549** See also: output_quoted_escaped_string()
drh28bd4bc2000-06-15 15:57:22 +00001550*/
1551static void output_quoted_string(FILE *out, const char *z){
1552 int i;
drh708b22b2017-03-11 01:56:41 +00001553 char c;
mistachkin1fe36bb2016-04-04 02:16:44 +00001554 setBinaryMode(out, 1);
drh13fe1382017-04-08 13:42:55 +00001555 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1556 if( c==0 ){
1557 utf8_printf(out,"'%s'",z);
1558 }else{
1559 raw_printf(out, "'");
1560 while( *z ){
1561 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1562 if( c=='\'' ) i++;
1563 if( i ){
1564 utf8_printf(out, "%.*s", i, z);
1565 z += i;
1566 }
1567 if( c=='\'' ){
1568 raw_printf(out, "'");
1569 continue;
1570 }
1571 if( c==0 ){
1572 break;
1573 }
1574 z++;
1575 }
1576 raw_printf(out, "'");
1577 }
1578 setTextMode(out, 1);
1579}
1580
1581/*
1582** Output the given string as a quoted string using SQL quoting conventions.
1583** Additionallly , escape the "\n" and "\r" characters so that they do not
1584** get corrupted by end-of-line translation facilities in some operating
1585** systems.
1586**
1587** This is like output_quoted_string() but with the addition of the \r\n
1588** escape mechanism.
1589*/
1590static void output_quoted_escaped_string(FILE *out, const char *z){
1591 int i;
1592 char c;
1593 setBinaryMode(out, 1);
drh708b22b2017-03-11 01:56:41 +00001594 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1595 if( c==0 ){
drhe05461c2015-12-30 13:36:57 +00001596 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00001597 }else{
drh6193d492017-04-07 11:45:58 +00001598 const char *zNL = 0;
1599 const char *zCR = 0;
1600 int nNL = 0;
1601 int nCR = 0;
1602 char zBuf1[20], zBuf2[20];
1603 for(i=0; z[i]; i++){
1604 if( z[i]=='\n' ) nNL++;
1605 if( z[i]=='\r' ) nCR++;
1606 }
1607 if( nNL ){
1608 raw_printf(out, "replace(");
1609 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1610 }
1611 if( nCR ){
1612 raw_printf(out, "replace(");
1613 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1614 }
1615 raw_printf(out, "'");
drh28bd4bc2000-06-15 15:57:22 +00001616 while( *z ){
drh708b22b2017-03-11 01:56:41 +00001617 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1618 if( c=='\'' ) i++;
1619 if( i ){
drh708b22b2017-03-11 01:56:41 +00001620 utf8_printf(out, "%.*s", i, z);
1621 z += i;
drh708b22b2017-03-11 01:56:41 +00001622 }
1623 if( c=='\'' ){
1624 raw_printf(out, "'");
1625 continue;
1626 }
drh708b22b2017-03-11 01:56:41 +00001627 if( c==0 ){
drh28bd4bc2000-06-15 15:57:22 +00001628 break;
1629 }
drh6193d492017-04-07 11:45:58 +00001630 z++;
1631 if( c=='\n' ){
1632 raw_printf(out, "%s", zNL);
1633 continue;
drh708b22b2017-03-11 01:56:41 +00001634 }
drh6193d492017-04-07 11:45:58 +00001635 raw_printf(out, "%s", zCR);
drh28bd4bc2000-06-15 15:57:22 +00001636 }
drh6193d492017-04-07 11:45:58 +00001637 raw_printf(out, "'");
1638 if( nCR ){
1639 raw_printf(out, ",'%s',char(13))", zCR);
1640 }
1641 if( nNL ){
1642 raw_printf(out, ",'%s',char(10))", zNL);
1643 }
drh28bd4bc2000-06-15 15:57:22 +00001644 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001645 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001646}
1647
1648/*
drhfeac5f82004-08-01 00:10:45 +00001649** Output the given string as a quoted according to C or TCL quoting rules.
1650*/
1651static void output_c_string(FILE *out, const char *z){
1652 unsigned int c;
1653 fputc('"', out);
1654 while( (c = *(z++))!=0 ){
1655 if( c=='\\' ){
1656 fputc(c, out);
1657 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00001658 }else if( c=='"' ){
1659 fputc('\\', out);
1660 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00001661 }else if( c=='\t' ){
1662 fputc('\\', out);
1663 fputc('t', out);
1664 }else if( c=='\n' ){
1665 fputc('\\', out);
1666 fputc('n', out);
1667 }else if( c=='\r' ){
1668 fputc('\\', out);
1669 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00001670 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00001671 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00001672 }else{
1673 fputc(c, out);
1674 }
1675 }
1676 fputc('"', out);
1677}
1678
1679/*
drhc08a4f12000-06-15 16:49:48 +00001680** Output the given string with characters that are special to
1681** HTML escaped.
1682*/
1683static void output_html_string(FILE *out, const char *z){
1684 int i;
drhc3d6ba42014-01-13 20:38:35 +00001685 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00001686 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00001687 for(i=0; z[i]
1688 && z[i]!='<'
1689 && z[i]!='&'
1690 && z[i]!='>'
1691 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00001692 && z[i]!='\'';
1693 i++){}
drhc08a4f12000-06-15 16:49:48 +00001694 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00001695 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00001696 }
1697 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00001698 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00001699 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00001700 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00001701 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00001702 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00001703 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00001704 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00001705 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00001706 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00001707 }else{
1708 break;
1709 }
1710 z += i + 1;
1711 }
1712}
1713
1714/*
drhc49f44e2006-10-26 18:15:42 +00001715** If a field contains any character identified by a 1 in the following
1716** array, then the string must be quoted for CSV.
1717*/
1718static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00001719 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1720 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1721 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1722 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1723 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1724 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1725 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1726 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1727 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1728 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1729 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1730 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1731 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1732 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1733 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1734 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00001735};
1736
1737/*
mistachkindd11f2d2014-12-11 04:49:46 +00001738** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00001739** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00001740** the null value. Strings are quoted if necessary. The separator
1741** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00001742*/
drhdcd87a92014-08-18 13:45:42 +00001743static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00001744 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00001745 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00001746 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00001747 }else{
drhc49f44e2006-10-26 18:15:42 +00001748 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00001749 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00001750 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00001751 if( needCsvQuote[((unsigned char*)z)[i]]
1752 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00001753 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00001754 i = 0;
1755 break;
1756 }
1757 }
1758 if( i==0 ){
1759 putc('"', out);
1760 for(i=0; z[i]; i++){
1761 if( z[i]=='"' ) putc('"', out);
1762 putc(z[i], out);
1763 }
1764 putc('"', out);
1765 }else{
drhe05461c2015-12-30 13:36:57 +00001766 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00001767 }
drh8e64d1c2004-10-07 00:32:39 +00001768 }
1769 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00001770 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001771 }
1772}
1773
danielk19774af00c62005-01-23 23:43:21 +00001774#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00001775/*
drh4c504392000-10-16 22:06:40 +00001776** This routine runs when the user presses Ctrl-C
1777*/
1778static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00001779 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00001780 seenInterrupt++;
1781 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00001782 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00001783}
danielk19774af00c62005-01-23 23:43:21 +00001784#endif
drh4c504392000-10-16 22:06:40 +00001785
drha0daa752016-09-16 11:53:10 +00001786#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00001787/*
drhde613c62016-04-04 17:23:10 +00001788** When the ".auth ON" is set, the following authorizer callback is
1789** invoked. It always returns SQLITE_OK.
1790*/
1791static int shellAuth(
1792 void *pClientData,
1793 int op,
1794 const char *zA1,
1795 const char *zA2,
1796 const char *zA3,
1797 const char *zA4
1798){
1799 ShellState *p = (ShellState*)pClientData;
1800 static const char *azAction[] = { 0,
1801 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1802 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1803 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1804 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1805 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1806 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1807 "PRAGMA", "READ", "SELECT",
1808 "TRANSACTION", "UPDATE", "ATTACH",
1809 "DETACH", "ALTER_TABLE", "REINDEX",
1810 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1811 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1812 };
1813 int i;
1814 const char *az[4];
1815 az[0] = zA1;
1816 az[1] = zA2;
1817 az[2] = zA3;
1818 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00001819 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00001820 for(i=0; i<4; i++){
1821 raw_printf(p->out, " ");
1822 if( az[i] ){
1823 output_c_string(p->out, az[i]);
1824 }else{
1825 raw_printf(p->out, "NULL");
1826 }
1827 }
1828 raw_printf(p->out, "\n");
1829 return SQLITE_OK;
1830}
drha0daa752016-09-16 11:53:10 +00001831#endif
mistachkin8145fc62016-09-16 20:39:21 +00001832
drh79f20e92016-12-13 23:22:39 +00001833/*
1834** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1835**
1836** This routine converts some CREATE TABLE statements for shadow tables
1837** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1838*/
1839static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1840 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1841 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1842 }else{
1843 utf8_printf(out, "%s%s", z, zTail);
1844 }
1845}
1846static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1847 char c = z[n];
1848 z[n] = 0;
1849 printSchemaLine(out, z, zTail);
1850 z[n] = c;
1851}
drhde613c62016-04-04 17:23:10 +00001852
1853/*
shane626a6e42009-10-22 17:30:15 +00001854** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00001855** invokes for each row of a query result.
1856*/
drh4ace5362014-11-10 14:42:28 +00001857static int shell_callback(
1858 void *pArg,
1859 int nArg, /* Number of result columns */
1860 char **azArg, /* Text of each result column */
1861 char **azCol, /* Column names */
1862 int *aiType /* Column types */
1863){
drh75897232000-05-29 14:26:00 +00001864 int i;
drhdcd87a92014-08-18 13:45:42 +00001865 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00001866
drh700c2522016-02-09 18:39:25 +00001867 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00001868 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00001869 int w = 5;
drh6a535342001-10-19 16:44:56 +00001870 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00001871 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00001872 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00001873 if( len>w ) w = len;
1874 }
drhe05461c2015-12-30 13:36:57 +00001875 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001876 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001877 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00001878 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001879 }
1880 break;
1881 }
danielk19770d78bae2008-01-03 07:09:48 +00001882 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00001883 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00001884 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1885 const int *colWidth;
1886 int showHdr;
1887 char *rowSep;
1888 if( p->cMode==MODE_Column ){
1889 colWidth = p->colWidth;
1890 showHdr = p->showHeader;
1891 rowSep = p->rowSeparator;
1892 }else{
1893 colWidth = aExplainWidths;
1894 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00001895 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00001896 }
drha0c66f52000-07-29 13:20:21 +00001897 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00001898 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00001899 int w, n;
1900 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00001901 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00001902 }else{
danielk19770d78bae2008-01-03 07:09:48 +00001903 w = 0;
drh75897232000-05-29 14:26:00 +00001904 }
drh078b1fd2012-09-21 13:40:02 +00001905 if( w==0 ){
drh4f21c4a2008-12-10 22:15:00 +00001906 w = strlen30(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00001907 if( w<10 ) w = 10;
mistachkin44b99f72014-12-11 03:29:14 +00001908 n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00001909 if( w<n ) w = n;
1910 }
1911 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00001912 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00001913 }
drh700c2522016-02-09 18:39:25 +00001914 if( showHdr ){
drh6887e8f2017-04-17 13:18:42 +00001915 utf8_width_print(p->out, w, azCol[i]);
1916 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001917 }
1918 }
drh700c2522016-02-09 18:39:25 +00001919 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00001920 for(i=0; i<nArg; i++){
1921 int w;
1922 if( i<ArraySize(p->actualWidth) ){
1923 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00001924 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00001925 }else{
1926 w = 10;
1927 }
mistachkinaae280e2015-12-31 19:06:24 +00001928 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00001929 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00001930 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00001931 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001932 }
drh75897232000-05-29 14:26:00 +00001933 }
1934 }
drh6a535342001-10-19 16:44:56 +00001935 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00001936 for(i=0; i<nArg; i++){
1937 int w;
drha0c66f52000-07-29 13:20:21 +00001938 if( i<ArraySize(p->actualWidth) ){
1939 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00001940 }else{
1941 w = 10;
1942 }
drh700c2522016-02-09 18:39:25 +00001943 if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
drh4f21c4a2008-12-10 22:15:00 +00001944 w = strlen30(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00001945 }
dana98bf362013-11-13 18:35:01 +00001946 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00001947 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00001948 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00001949 }
danc4650bb2013-11-18 08:41:06 +00001950 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00001951 }
drh6887e8f2017-04-17 13:18:42 +00001952 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1953 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drh75897232000-05-29 14:26:00 +00001954 }
1955 break;
1956 }
drh4926fec2016-04-13 15:33:42 +00001957 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00001958 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00001959 break;
1960 }
1961 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1962 char *z;
drh07d683f2016-04-13 21:00:36 +00001963 int j;
drh4926fec2016-04-13 15:33:42 +00001964 int nParen = 0;
1965 char cEnd = 0;
1966 char c;
1967 int nLine = 0;
1968 assert( nArg==1 );
1969 if( azArg[0]==0 ) break;
1970 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1971 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1972 ){
1973 utf8_printf(p->out, "%s;\n", azArg[0]);
1974 break;
1975 }
1976 z = sqlite3_mprintf("%s", azArg[0]);
1977 j = 0;
1978 for(i=0; IsSpace(z[i]); i++){}
1979 for(; (c = z[i])!=0; i++){
1980 if( IsSpace(c) ){
1981 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1982 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1983 j--;
1984 }
1985 z[j++] = c;
1986 }
1987 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1988 z[j] = 0;
1989 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00001990 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00001991 if( c==cEnd ){
1992 cEnd = 0;
1993 }else if( c=='"' || c=='\'' || c=='`' ){
1994 cEnd = c;
1995 }else if( c=='[' ){
1996 cEnd = ']';
1997 }else if( c=='(' ){
1998 nParen++;
1999 }else if( c==')' ){
2000 nParen--;
2001 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00002002 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00002003 j = 0;
2004 }
2005 }
2006 z[j++] = c;
2007 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
2008 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00002009 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00002010 j = 0;
2011 nLine++;
2012 while( IsSpace(z[i+1]) ){ i++; }
2013 }
2014 }
2015 z[j] = 0;
2016 }
drh79f20e92016-12-13 23:22:39 +00002017 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00002018 sqlite3_free(z);
2019 break;
2020 }
drh75897232000-05-29 14:26:00 +00002021 case MODE_List: {
2022 if( p->cnt++==0 && p->showHeader ){
2023 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002024 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00002025 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00002026 }
2027 }
drh6a535342001-10-19 16:44:56 +00002028 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002029 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00002030 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00002031 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00002032 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00002033 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00002034 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00002035 }else{
drhe05461c2015-12-30 13:36:57 +00002036 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00002037 }
drh75897232000-05-29 14:26:00 +00002038 }
2039 break;
2040 }
drh1e5d0e92000-05-31 23:33:17 +00002041 case MODE_Html: {
2042 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00002043 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002044 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002045 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00002046 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00002047 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00002048 }
mistachkinaae280e2015-12-31 19:06:24 +00002049 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002050 }
drh6a535342001-10-19 16:44:56 +00002051 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00002052 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002053 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002054 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00002055 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00002056 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00002057 }
mistachkinaae280e2015-12-31 19:06:24 +00002058 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002059 break;
2060 }
drhfeac5f82004-08-01 00:10:45 +00002061 case MODE_Tcl: {
2062 if( p->cnt++==0 && p->showHeader ){
2063 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002064 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00002065 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002066 }
drhe05461c2015-12-30 13:36:57 +00002067 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002068 }
2069 if( azArg==0 ) break;
2070 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00002071 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00002072 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002073 }
drhe05461c2015-12-30 13:36:57 +00002074 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002075 break;
2076 }
drh8e64d1c2004-10-07 00:32:39 +00002077 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00002078 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002079 if( p->cnt++==0 && p->showHeader ){
2080 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002081 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00002082 }
drhe05461c2015-12-30 13:36:57 +00002083 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002084 }
drh40253262014-10-17 21:35:05 +00002085 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00002086 for(i=0; i<nArg; i++){
2087 output_csv(p, azArg[i], i<nArg-1);
2088 }
drhe05461c2015-12-30 13:36:57 +00002089 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002090 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002091 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002092 break;
2093 }
drh28bd4bc2000-06-15 15:57:22 +00002094 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00002095 if( azArg==0 ) break;
drh13fe1382017-04-08 13:42:55 +00002096 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2097 if( p->showHeader ){
2098 raw_printf(p->out,"(");
2099 for(i=0; i<nArg; i++){
2100 if( i>0 ) raw_printf(p->out, ",");
2101 if( quoteChar(azCol[i]) ){
2102 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2103 utf8_printf(p->out, "%s", z);
2104 sqlite3_free(z);
2105 }else{
2106 raw_printf(p->out, "%s", azCol[i]);
drh41f5f6e2016-10-21 17:39:30 +00002107 }
mistachkin151c75a2015-04-07 21:16:40 +00002108 }
drh13fe1382017-04-08 13:42:55 +00002109 raw_printf(p->out,")");
2110 }
2111 p->cnt++;
2112 for(i=0; i<nArg; i++){
2113 raw_printf(p->out, i>0 ? "," : " VALUES(");
2114 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2115 utf8_printf(p->out,"NULL");
2116 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2117 output_quoted_escaped_string(p->out, azArg[i]);
2118 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2119 utf8_printf(p->out,"%s", azArg[i]);
2120 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2121 char z[50];
2122 double r = sqlite3_column_double(p->pStmt, i);
2123 sqlite3_snprintf(50,z,"%!.20g", r);
2124 raw_printf(p->out, "%s", z);
2125 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2126 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2127 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2128 output_hex_blob(p->out, pBlob, nBlob);
2129 }else if( isNumber(azArg[i], 0) ){
2130 utf8_printf(p->out,"%s", azArg[i]);
2131 }else{
2132 output_quoted_escaped_string(p->out, azArg[i]);
2133 }
2134 }
2135 raw_printf(p->out,");\n");
2136 break;
2137 }
2138 case MODE_Quote: {
2139 if( azArg==0 ) break;
2140 if( p->cnt==0 && p->showHeader ){
drh59ce2c42016-11-03 13:12:28 +00002141 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00002142 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00002143 output_quoted_string(p->out, azCol[i]);
2144 }
mistachkin2f9a6132016-11-11 05:19:45 +00002145 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002146 }
drh59ce2c42016-11-03 13:12:28 +00002147 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002148 for(i=0; i<nArg; i++){
drh13fe1382017-04-08 13:42:55 +00002149 if( i>0 ) raw_printf(p->out, ",");
shanead6b8d02009-10-22 18:12:58 +00002150 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
drh13fe1382017-04-08 13:42:55 +00002151 utf8_printf(p->out,"NULL");
shanead6b8d02009-10-22 18:12:58 +00002152 }else if( aiType && aiType[i]==SQLITE_TEXT ){
shanead6b8d02009-10-22 18:12:58 +00002153 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002154 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drh13fe1382017-04-08 13:42:55 +00002155 utf8_printf(p->out,"%s", azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002156 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2157 char z[50];
2158 double r = sqlite3_column_double(p->pStmt, i);
2159 sqlite3_snprintf(50,z,"%!.20g", r);
drh13fe1382017-04-08 13:42:55 +00002160 raw_printf(p->out, "%s", z);
shane626a6e42009-10-22 17:30:15 +00002161 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2162 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2163 int nBlob = sqlite3_column_bytes(p->pStmt, i);
shane626a6e42009-10-22 17:30:15 +00002164 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002165 }else if( isNumber(azArg[i], 0) ){
drh13fe1382017-04-08 13:42:55 +00002166 utf8_printf(p->out,"%s", azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002167 }else{
drh28bd4bc2000-06-15 15:57:22 +00002168 output_quoted_string(p->out, azArg[i]);
2169 }
2170 }
drh13fe1382017-04-08 13:42:55 +00002171 raw_printf(p->out,"\n");
drh6a535342001-10-19 16:44:56 +00002172 break;
drh28bd4bc2000-06-15 15:57:22 +00002173 }
mistachkin636bf9f2014-07-19 20:15:16 +00002174 case MODE_Ascii: {
2175 if( p->cnt++==0 && p->showHeader ){
2176 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002177 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2178 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002179 }
drhe05461c2015-12-30 13:36:57 +00002180 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002181 }
2182 if( azArg==0 ) break;
2183 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002184 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2185 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002186 }
drhe05461c2015-12-30 13:36:57 +00002187 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002188 break;
2189 }
persicom1d0b8722002-04-18 02:53:04 +00002190 }
drh75897232000-05-29 14:26:00 +00002191 return 0;
2192}
2193
2194/*
shane626a6e42009-10-22 17:30:15 +00002195** This is the callback routine that the SQLite library
2196** invokes for each row of a query result.
2197*/
2198static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2199 /* since we don't have type info, call the shell_callback with a NULL value */
2200 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2201}
2202
drhfb546af2017-03-09 22:00:33 +00002203/*
2204** This is the callback routine from sqlite3_exec() that appends all
2205** output onto the end of a ShellText object.
2206*/
2207static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2208 ShellText *p = (ShellText*)pArg;
2209 int i;
drh2fb79e92017-03-25 12:08:11 +00002210 UNUSED_PARAMETER(az);
drhfb546af2017-03-09 22:00:33 +00002211 if( p->n ) appendText(p, "|", 0);
2212 for(i=0; i<nArg; i++){
2213 if( i ) appendText(p, ",", 0);
2214 if( azArg[i] ) appendText(p, azArg[i], 0);
2215 }
2216 return 0;
2217}
2218
2219/*
2220** Generate an appropriate SELFTEST table in the main database.
2221*/
2222static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00002223 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00002224 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00002225 "SAVEPOINT selftest_init;\n"
2226 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00002227 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2228 " op TEXT,\n" /* Operator: memo run */
2229 " cmd TEXT,\n" /* Command text */
2230 " ans TEXT\n" /* Desired answer */
2231 ");"
drhf157d102017-03-10 01:05:38 +00002232 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2233 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2234 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2235 " 'memo','Tests generated by --init');\n"
2236 "INSERT INTO [_shell$self]\n"
2237 " SELECT 'run',\n"
2238 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2239 "FROM sqlite_master ORDER BY 2'',224))',\n"
2240 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2241 "FROM sqlite_master ORDER BY 2',224));\n"
2242 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002243 " SELECT 'run',"
2244 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2245 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2246 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2247 " FROM (\n"
2248 " SELECT name FROM sqlite_master\n"
2249 " WHERE type='table'\n"
2250 " AND name<>'selftest'\n"
2251 " AND coalesce(rootpage,0)>0\n"
2252 " )\n"
2253 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00002254 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002255 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00002256 "INSERT INTO selftest(tno,op,cmd,ans)"
2257 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2258 "DROP TABLE [_shell$self];"
2259 ,0,0,&zErrMsg);
2260 if( zErrMsg ){
2261 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2262 sqlite3_free(zErrMsg);
2263 }
2264 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00002265}
2266
drhf42d3182017-03-08 12:25:18 +00002267
shane626a6e42009-10-22 17:30:15 +00002268/*
drhdcd87a92014-08-18 13:45:42 +00002269** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00002270** the name of the table given. Escape any quote characters in the
2271** table name.
2272*/
drhdcd87a92014-08-18 13:45:42 +00002273static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00002274 int i, n;
drhf42d3182017-03-08 12:25:18 +00002275 int cQuote;
drh33048c02001-10-01 14:29:22 +00002276 char *z;
2277
2278 if( p->zDestTable ){
2279 free(p->zDestTable);
2280 p->zDestTable = 0;
2281 }
2282 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00002283 cQuote = quoteChar(zName);
2284 n = strlen30(zName);
2285 if( cQuote ) n += 2;
drh33048c02001-10-01 14:29:22 +00002286 z = p->zDestTable = malloc( n+1 );
2287 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002288 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00002289 exit(1);
2290 }
2291 n = 0;
drhf42d3182017-03-08 12:25:18 +00002292 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002293 for(i=0; zName[i]; i++){
2294 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00002295 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002296 }
drhf42d3182017-03-08 12:25:18 +00002297 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002298 z[n] = 0;
2299}
2300
drhdd3d4592004-08-30 01:54:05 +00002301
2302/*
drhb21a8e42012-01-28 21:08:51 +00002303** Execute a query statement that will generate SQL output. Print
2304** the result columns, comma-separated, on a line and then add a
2305** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00002306**
drhb21a8e42012-01-28 21:08:51 +00002307** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00002308** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00002309** "--" comment occurs at the end of the statement, the comment
2310** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00002311*/
drh157e29a2009-05-21 15:15:00 +00002312static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00002313 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00002314 const char *zSelect, /* SELECT statement to extract content */
2315 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00002316){
drhdd3d4592004-08-30 01:54:05 +00002317 sqlite3_stmt *pSelect;
2318 int rc;
drhb21a8e42012-01-28 21:08:51 +00002319 int nResult;
2320 int i;
2321 const char *z;
drhc7181902014-02-27 15:04:13 +00002322 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00002323 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00002324 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2325 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002326 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00002327 return rc;
2328 }
2329 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00002330 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00002331 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00002332 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00002333 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00002334 zFirstRow = 0;
2335 }
drhb21a8e42012-01-28 21:08:51 +00002336 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00002337 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00002338 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00002339 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00002340 }
2341 if( z==0 ) z = "";
2342 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2343 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00002344 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00002345 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002346 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00002347 }
drhdd3d4592004-08-30 01:54:05 +00002348 rc = sqlite3_step(pSelect);
2349 }
drh2f464a02011-10-13 00:41:49 +00002350 rc = sqlite3_finalize(pSelect);
2351 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00002352 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2353 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002354 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00002355 }
2356 return rc;
drhdd3d4592004-08-30 01:54:05 +00002357}
2358
shane626a6e42009-10-22 17:30:15 +00002359/*
2360** Allocate space and save off current error string.
2361*/
2362static char *save_err_msg(
2363 sqlite3 *db /* Database to query */
2364){
2365 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00002366 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00002367 if( zErrMsg ){
2368 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2369 }
2370 return zErrMsg;
2371}
2372
drh34784902016-02-27 17:12:36 +00002373#ifdef __linux__
2374/*
2375** Attempt to display I/O stats on Linux using /proc/PID/io
2376*/
2377static void displayLinuxIoStats(FILE *out){
2378 FILE *in;
2379 char z[200];
2380 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2381 in = fopen(z, "rb");
2382 if( in==0 ) return;
2383 while( fgets(z, sizeof(z), in)!=0 ){
2384 static const struct {
2385 const char *zPattern;
2386 const char *zDesc;
2387 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00002388 { "rchar: ", "Bytes received by read():" },
2389 { "wchar: ", "Bytes sent to write():" },
2390 { "syscr: ", "Read() system calls:" },
2391 { "syscw: ", "Write() system calls:" },
2392 { "read_bytes: ", "Bytes read from storage:" },
2393 { "write_bytes: ", "Bytes written to storage:" },
2394 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00002395 };
2396 int i;
2397 for(i=0; i<ArraySize(aTrans); i++){
2398 int n = (int)strlen(aTrans[i].zPattern);
2399 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00002400 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00002401 break;
2402 }
2403 }
2404 }
2405 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00002406}
drh34784902016-02-27 17:12:36 +00002407#endif
2408
drha2df53b2017-03-10 14:36:10 +00002409/*
2410** Display a single line of status using 64-bit values.
2411*/
2412static void displayStatLine(
2413 ShellState *p, /* The shell context */
2414 char *zLabel, /* Label for this one line */
2415 char *zFormat, /* Format for the result */
2416 int iStatusCtrl, /* Which status to display */
2417 int bReset /* True to reset the stats */
2418){
2419 sqlite3_int64 iCur = -1;
2420 sqlite3_int64 iHiwtr = -1;
2421 int i, nPercent;
2422 char zLine[200];
2423 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2424 for(i=0, nPercent=0; zFormat[i]; i++){
2425 if( zFormat[i]=='%' ) nPercent++;
2426 }
2427 if( nPercent>1 ){
2428 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2429 }else{
2430 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2431 }
2432 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2433}
drh34784902016-02-27 17:12:36 +00002434
shane626a6e42009-10-22 17:30:15 +00002435/*
shaneh642d8b82010-07-28 16:05:34 +00002436** Display memory stats.
2437*/
2438static int display_stats(
2439 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00002440 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00002441 int bReset /* True to reset the stats */
2442){
2443 int iCur;
2444 int iHiwtr;
2445
2446 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00002447 displayStatLine(pArg, "Memory Used:",
2448 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2449 displayStatLine(pArg, "Number of Outstanding Allocations:",
2450 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00002451 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00002452 displayStatLine(pArg, "Number of Pcache Pages Used:",
2453 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002454 }
drha2df53b2017-03-10 14:36:10 +00002455 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2456 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh44dec872014-08-30 15:49:25 +00002457 if( pArg->shellFlgs & SHFLG_Scratch ){
drha2df53b2017-03-10 14:36:10 +00002458 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2459 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002460 }
drha2df53b2017-03-10 14:36:10 +00002461 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2462 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2463 displayStatLine(pArg, "Largest Allocation:",
2464 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2465 displayStatLine(pArg, "Largest Pcache Allocation:",
2466 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2467 displayStatLine(pArg, "Largest Scratch Allocation:",
2468 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002469#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00002470 displayStatLine(pArg, "Deepest Parser Stack:",
2471 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002472#endif
2473 }
2474
2475 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00002476 if( pArg->shellFlgs & SHFLG_Lookaside ){
2477 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00002478 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2479 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002480 raw_printf(pArg->out,
2481 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00002482 iCur, iHiwtr);
2483 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2484 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002485 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2486 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002487 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2488 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002489 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2490 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002491 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2492 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002493 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2494 iHiwtr);
drh44dec872014-08-30 15:49:25 +00002495 }
shaneh642d8b82010-07-28 16:05:34 +00002496 iHiwtr = iCur = -1;
2497 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002498 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2499 iCur);
drh4ace5362014-11-10 14:42:28 +00002500 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00002501 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00002502 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00002503 iHiwtr = iCur = -1;
2504 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002505 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002506 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00002507 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002508 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00002509 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00002510 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002511 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002512 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002513 iHiwtr = iCur = -1;
2514 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002515 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002516 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002517 }
2518
2519 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00002520 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2521 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002522 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002523 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002524 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00002525 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002526 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00002527 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002528 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002529 }
2530
drh34784902016-02-27 17:12:36 +00002531#ifdef __linux__
2532 displayLinuxIoStats(pArg->out);
2533#endif
2534
dan5a790282015-08-07 20:06:14 +00002535 /* Do not remove this machine readable comment: extra-stats-output-here */
2536
shaneh642d8b82010-07-28 16:05:34 +00002537 return 0;
2538}
2539
2540/*
dan8d1edb92014-11-05 09:07:28 +00002541** Display scan stats.
2542*/
2543static void display_scanstats(
2544 sqlite3 *db, /* Database to query */
2545 ShellState *pArg /* Pointer to ShellState */
2546){
drhf5ed7ad2015-06-15 14:43:25 +00002547#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2548 UNUSED_PARAMETER(db);
2549 UNUSED_PARAMETER(pArg);
2550#else
drh15f23c22014-11-06 12:46:16 +00002551 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00002552 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00002553 mx = 0;
2554 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00002555 double rEstLoop = 1.0;
2556 for(i=n=0; 1; i++){
2557 sqlite3_stmt *p = pArg->pStmt;
2558 sqlite3_int64 nLoop, nVisit;
2559 double rEst;
2560 int iSid;
2561 const char *zExplain;
2562 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2563 break;
2564 }
2565 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00002566 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00002567 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00002568 if( n==0 ){
2569 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00002570 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00002571 }
drh42f30bc2014-11-06 12:08:21 +00002572 n++;
2573 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2574 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2575 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00002576 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00002577 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00002578 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00002579 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00002580 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00002581 );
dan8d1edb92014-11-05 09:07:28 +00002582 }
dan8d1edb92014-11-05 09:07:28 +00002583 }
mistachkinaae280e2015-12-31 19:06:24 +00002584 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00002585#endif
dan8d1edb92014-11-05 09:07:28 +00002586}
2587
2588/*
dana98bf362013-11-13 18:35:01 +00002589** Parameter azArray points to a zero-terminated array of strings. zStr
2590** points to a single nul-terminated string. Return non-zero if zStr
2591** is equal, according to strcmp(), to any of the strings in the array.
2592** Otherwise, return zero.
2593*/
2594static int str_in_array(const char *zStr, const char **azArray){
2595 int i;
2596 for(i=0; azArray[i]; i++){
2597 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2598 }
2599 return 0;
2600}
2601
2602/*
2603** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00002604** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00002605** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00002606**
2607** The indenting rules are:
2608**
2609** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2610** all opcodes that occur between the p2 jump destination and the opcode
2611** itself by 2 spaces.
2612**
drh01752bc2013-11-14 23:59:33 +00002613** * For each "Goto", if the jump destination is earlier in the program
2614** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00002615** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00002616** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00002617** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00002618** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00002619*/
drhdcd87a92014-08-18 13:45:42 +00002620static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00002621 const char *zSql; /* The text of the SQL statement */
2622 const char *z; /* Used to check if this is an EXPLAIN */
2623 int *abYield = 0; /* True if op is an OP_Yield */
2624 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00002625 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00002626
drh8ad0de32014-03-20 18:45:27 +00002627 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2628 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00002629 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2630 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00002631 const char *azGoto[] = { "Goto", 0 };
2632
2633 /* Try to figure out if this is really an EXPLAIN statement. If this
2634 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00002635 if( sqlite3_column_count(pSql)!=8 ){
2636 p->cMode = p->mode;
2637 return;
2638 }
dana98bf362013-11-13 18:35:01 +00002639 zSql = sqlite3_sql(pSql);
2640 if( zSql==0 ) return;
2641 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00002642 if( sqlite3_strnicmp(z, "explain", 7) ){
2643 p->cMode = p->mode;
2644 return;
2645 }
dana98bf362013-11-13 18:35:01 +00002646
2647 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2648 int i;
danc4650bb2013-11-18 08:41:06 +00002649 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00002650 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00002651
2652 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2653 ** p2 is an instruction address, set variable p2op to the index of that
2654 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2655 ** the current instruction is part of a sub-program generated by an
2656 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00002657 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00002658 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00002659
2660 /* Grow the p->aiIndent array as required */
2661 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00002662 if( iOp==0 ){
2663 /* Do further verfication that this is explain output. Abort if
2664 ** it is not */
2665 static const char *explainCols[] = {
2666 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2667 int jj;
2668 for(jj=0; jj<ArraySize(explainCols); jj++){
2669 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2670 p->cMode = p->mode;
2671 sqlite3_reset(pSql);
2672 return;
2673 }
2674 }
2675 }
dana98bf362013-11-13 18:35:01 +00002676 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00002677 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2678 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00002679 }
2680 abYield[iOp] = str_in_array(zOp, azYield);
2681 p->aiIndent[iOp] = 0;
2682 p->nIndent = iOp+1;
2683
2684 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00002685 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002686 }
drhfe705102014-03-06 13:38:37 +00002687 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2688 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2689 ){
drheacd29d2016-04-15 15:03:27 +00002690 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002691 }
2692 }
2693
danc4650bb2013-11-18 08:41:06 +00002694 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002695 sqlite3_free(abYield);
2696 sqlite3_reset(pSql);
2697}
2698
2699/*
2700** Free the array allocated by explain_data_prepare().
2701*/
drhdcd87a92014-08-18 13:45:42 +00002702static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00002703 sqlite3_free(p->aiIndent);
2704 p->aiIndent = 0;
2705 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00002706 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002707}
2708
2709/*
drheacd29d2016-04-15 15:03:27 +00002710** Disable and restore .wheretrace and .selecttrace settings.
2711*/
2712#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2713extern int sqlite3SelectTrace;
2714static int savedSelectTrace;
2715#endif
2716#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2717extern int sqlite3WhereTrace;
2718static int savedWhereTrace;
2719#endif
2720static void disable_debug_trace_modes(void){
2721#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2722 savedSelectTrace = sqlite3SelectTrace;
2723 sqlite3SelectTrace = 0;
2724#endif
2725#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2726 savedWhereTrace = sqlite3WhereTrace;
2727 sqlite3WhereTrace = 0;
2728#endif
2729}
2730static void restore_debug_trace_modes(void){
2731#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2732 sqlite3SelectTrace = savedSelectTrace;
2733#endif
2734#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2735 sqlite3WhereTrace = savedWhereTrace;
2736#endif
2737}
2738
2739/*
2740** Run a prepared statement
2741*/
2742static void exec_prepared_stmt(
2743 ShellState *pArg, /* Pointer to ShellState */
2744 sqlite3_stmt *pStmt, /* Statment to run */
2745 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2746){
2747 int rc;
2748
2749 /* perform the first step. this will tell us if we
2750 ** have a result set or not and how wide it is.
2751 */
2752 rc = sqlite3_step(pStmt);
2753 /* if we have a result set... */
2754 if( SQLITE_ROW == rc ){
2755 /* if we have a callback... */
2756 if( xCallback ){
2757 /* allocate space for col name ptr, value ptr, and type */
2758 int nCol = sqlite3_column_count(pStmt);
2759 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2760 if( !pData ){
2761 rc = SQLITE_NOMEM;
2762 }else{
2763 char **azCols = (char **)pData; /* Names of result columns */
2764 char **azVals = &azCols[nCol]; /* Results */
2765 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2766 int i, x;
2767 assert(sizeof(int) <= sizeof(char *));
2768 /* save off ptrs to column names */
2769 for(i=0; i<nCol; i++){
2770 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2771 }
2772 do{
2773 /* extract the data and data types */
2774 for(i=0; i<nCol; i++){
2775 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2776 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2777 azVals[i] = "";
2778 }else{
2779 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2780 }
2781 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2782 rc = SQLITE_NOMEM;
2783 break; /* from for */
2784 }
2785 } /* end for */
2786
2787 /* if data and types extracted successfully... */
2788 if( SQLITE_ROW == rc ){
2789 /* call the supplied callback with the result row data */
2790 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2791 rc = SQLITE_ABORT;
2792 }else{
2793 rc = sqlite3_step(pStmt);
2794 }
2795 }
2796 } while( SQLITE_ROW == rc );
2797 sqlite3_free(pData);
2798 }
2799 }else{
2800 do{
2801 rc = sqlite3_step(pStmt);
2802 } while( rc == SQLITE_ROW );
2803 }
2804 }
2805}
2806
2807/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002808** Execute a statement or set of statements. Print
2809** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00002810** set via the supplied callback.
2811**
mistachkin1fe36bb2016-04-04 02:16:44 +00002812** This is very similar to SQLite's built-in sqlite3_exec()
2813** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00002814** and callback data argument.
2815*/
2816static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00002817 sqlite3 *db, /* An open database */
2818 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00002819 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00002820 /* (not the same as sqlite3_exec) */
2821 ShellState *pArg, /* Pointer to ShellState */
2822 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00002823){
dan4564ced2010-01-05 04:59:56 +00002824 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2825 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00002826 int rc2;
dan4564ced2010-01-05 04:59:56 +00002827 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00002828
2829 if( pzErrMsg ){
2830 *pzErrMsg = NULL;
2831 }
2832
shaneb9fc17d2009-10-22 21:23:35 +00002833 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00002834 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00002835 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2836 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00002837 if( pzErrMsg ){
2838 *pzErrMsg = save_err_msg(db);
2839 }
2840 }else{
shaneb9fc17d2009-10-22 21:23:35 +00002841 if( !pStmt ){
2842 /* this happens for a comment or white-space */
2843 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002844 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00002845 continue;
2846 }
drheacd29d2016-04-15 15:03:27 +00002847 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00002848 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00002849 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00002850
shaneh642d8b82010-07-28 16:05:34 +00002851 /* save off the prepared statment handle and reset row count */
2852 if( pArg ){
2853 pArg->pStmt = pStmt;
2854 pArg->cnt = 0;
2855 }
2856
shanehb7977c52010-01-18 18:17:10 +00002857 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00002858 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00002859 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00002860 }
shanehb7977c52010-01-18 18:17:10 +00002861
drhefbf3b12014-02-28 20:47:24 +00002862 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00002863 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00002864 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00002865 char *zEQP;
2866 disable_debug_trace_modes();
2867 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00002868 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2869 if( rc==SQLITE_OK ){
2870 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00002871 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2872 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2873 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00002874 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00002875 }
2876 }
2877 sqlite3_finalize(pExplain);
2878 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00002879 if( pArg->autoEQP>=2 ){
2880 /* Also do an EXPLAIN for ".eqp full" mode */
2881 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2882 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2883 if( rc==SQLITE_OK ){
2884 pArg->cMode = MODE_Explain;
2885 explain_data_prepare(pArg, pExplain);
2886 exec_prepared_stmt(pArg, pExplain, xCallback);
2887 explain_data_delete(pArg);
2888 }
2889 sqlite3_finalize(pExplain);
2890 sqlite3_free(zEQP);
2891 }
2892 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00002893 }
2894
drh700c2522016-02-09 18:39:25 +00002895 if( pArg ){
2896 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00002897 if( pArg->autoExplain
2898 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00002899 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00002900 ){
2901 pArg->cMode = MODE_Explain;
2902 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002903
drh700c2522016-02-09 18:39:25 +00002904 /* If the shell is currently in ".explain" mode, gather the extra
2905 ** data required to add indents to the output.*/
2906 if( pArg->cMode==MODE_Explain ){
2907 explain_data_prepare(pArg, pStmt);
2908 }
dana98bf362013-11-13 18:35:01 +00002909 }
2910
drheacd29d2016-04-15 15:03:27 +00002911 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00002912 explain_data_delete(pArg);
2913
shaneh642d8b82010-07-28 16:05:34 +00002914 /* print usage stats if stats on */
2915 if( pArg && pArg->statsOn ){
2916 display_stats(db, pArg, 0);
2917 }
2918
dan8d1edb92014-11-05 09:07:28 +00002919 /* print loop-counters if required */
2920 if( pArg && pArg->scanstatsOn ){
2921 display_scanstats(db, pArg);
2922 }
2923
mistachkin1fe36bb2016-04-04 02:16:44 +00002924 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00002925 ** copy of the error message. Otherwise, set zSql to point to the
2926 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00002927 rc2 = sqlite3_finalize(pStmt);
2928 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00002929 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00002930 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002931 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00002932 }else if( pzErrMsg ){
2933 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00002934 }
shaneh642d8b82010-07-28 16:05:34 +00002935
2936 /* clear saved stmt handle */
2937 if( pArg ){
2938 pArg->pStmt = NULL;
2939 }
shane626a6e42009-10-22 17:30:15 +00002940 }
shaneb9fc17d2009-10-22 21:23:35 +00002941 } /* end while */
shane626a6e42009-10-22 17:30:15 +00002942
2943 return rc;
2944}
2945
drhe611f142017-03-08 11:44:00 +00002946/*
2947** Release memory previously allocated by tableColumnList().
2948*/
2949static void freeColumnList(char **azCol){
2950 int i;
2951 for(i=1; azCol[i]; i++){
2952 sqlite3_free(azCol[i]);
2953 }
2954 /* azCol[0] is a static string */
2955 sqlite3_free(azCol);
2956}
2957
2958/*
2959** Return a list of pointers to strings which are the names of all
2960** columns in table zTab. The memory to hold the names is dynamically
2961** allocated and must be released by the caller using a subsequent call
2962** to freeColumnList().
2963**
2964** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2965** value that needs to be preserved, then azCol[0] is filled in with the
2966** name of the rowid column.
2967**
2968** The first regular column in the table is azCol[1]. The list is terminated
2969** by an entry with azCol[i]==0.
2970*/
2971static char **tableColumnList(ShellState *p, const char *zTab){
2972 char **azCol = 0;
2973 sqlite3_stmt *pStmt;
2974 char *zSql;
2975 int nCol = 0;
2976 int nAlloc = 0;
2977 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2978 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00002979 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00002980 int rc;
2981
2982 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2983 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2984 sqlite3_free(zSql);
2985 if( rc ) return 0;
2986 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2987 if( nCol>=nAlloc-2 ){
2988 nAlloc = nAlloc*2 + nCol + 10;
2989 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2990 if( azCol==0 ){
2991 raw_printf(stderr, "Error: out of memory\n");
2992 exit(1);
2993 }
2994 }
2995 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2996 if( sqlite3_column_int(pStmt, 5) ){
2997 nPK++;
2998 if( nPK==1
2999 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
3000 "INTEGER")==0
3001 ){
3002 isIPK = 1;
3003 }else{
3004 isIPK = 0;
3005 }
3006 }
3007 }
3008 sqlite3_finalize(pStmt);
3009 azCol[0] = 0;
3010 azCol[nCol+1] = 0;
3011
3012 /* The decision of whether or not a rowid really needs to be preserved
3013 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3014 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3015 ** rowids on tables where the rowid is inaccessible because there are other
3016 ** columns in the table named "rowid", "_rowid_", and "oid".
3017 */
3018 if( preserveRowid && isIPK ){
3019 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3020 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3021 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3022 ** ROWID aliases. To distinguish these cases, check to see if
3023 ** there is a "pk" entry in "PRAGMA index_list". There will be
3024 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3025 */
3026 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3027 " WHERE origin='pk'", zTab);
3028 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3029 sqlite3_free(zSql);
3030 if( rc ){
3031 freeColumnList(azCol);
3032 return 0;
3033 }
3034 rc = sqlite3_step(pStmt);
3035 sqlite3_finalize(pStmt);
3036 preserveRowid = rc==SQLITE_ROW;
3037 }
3038 if( preserveRowid ){
3039 /* Only preserve the rowid if we can find a name to use for the
3040 ** rowid */
3041 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3042 int i, j;
3043 for(j=0; j<3; j++){
3044 for(i=1; i<=nCol; i++){
3045 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3046 }
3047 if( i>nCol ){
3048 /* At this point, we know that azRowid[j] is not the name of any
3049 ** ordinary column in the table. Verify that azRowid[j] is a valid
3050 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3051 ** tables will fail this last check */
drhe611f142017-03-08 11:44:00 +00003052 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3053 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3054 break;
3055 }
3056 }
3057 }
3058 return azCol;
3059}
3060
drh33048c02001-10-01 14:29:22 +00003061/*
drhf8563c02017-03-09 18:13:52 +00003062** Toggle the reverse_unordered_selects setting.
3063*/
3064static void toggleSelectOrder(sqlite3 *db){
3065 sqlite3_stmt *pStmt = 0;
3066 int iSetting = 0;
3067 char zStmt[100];
3068 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3069 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3070 iSetting = sqlite3_column_int(pStmt, 0);
3071 }
3072 sqlite3_finalize(pStmt);
3073 sqlite3_snprintf(sizeof(zStmt), zStmt,
3074 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3075 sqlite3_exec(db, zStmt, 0, 0, 0);
3076}
3077
3078/*
drh4c653a02000-06-07 01:27:47 +00003079** This is a different callback routine used for dumping the database.
3080** Each row received by this callback consists of a table name,
3081** the table type ("index" or "table") and SQL to create the table.
3082** This routine should print text sufficient to recreate the table.
3083*/
drh701ff6a2017-03-22 12:51:34 +00003084static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
danielk19772a02e332004-06-05 08:04:36 +00003085 int rc;
3086 const char *zTable;
3087 const char *zType;
3088 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00003089 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00003090
drh701ff6a2017-03-22 12:51:34 +00003091 UNUSED_PARAMETER(azNotUsed);
drh4c653a02000-06-07 01:27:47 +00003092 if( nArg!=3 ) return 1;
danielk19772a02e332004-06-05 08:04:36 +00003093 zTable = azArg[0];
3094 zType = azArg[1];
3095 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00003096
drh00b950d2005-09-11 02:03:03 +00003097 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00003098 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00003099 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003100 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00003101 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3102 return 0;
drh45e29d82006-11-20 16:21:10 +00003103 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3104 char *zIns;
3105 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00003106 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00003107 p->writableSchema = 1;
3108 }
3109 zIns = sqlite3_mprintf(
3110 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3111 "VALUES('table','%q','%q',0,'%q');",
3112 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00003113 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00003114 sqlite3_free(zIns);
3115 return 0;
drh00b950d2005-09-11 02:03:03 +00003116 }else{
drh79f20e92016-12-13 23:22:39 +00003117 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00003118 }
danielk19772a02e332004-06-05 08:04:36 +00003119
3120 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00003121 ShellText sSelect;
3122 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00003123 char **azCol;
3124 int i;
3125 char *savedDestTable;
3126 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00003127
drhe611f142017-03-08 11:44:00 +00003128 azCol = tableColumnList(p, zTable);
3129 if( azCol==0 ){
3130 p->nErr++;
3131 return 0;
danielk19772a02e332004-06-05 08:04:36 +00003132 }
3133
drhbf92ec02012-03-22 12:50:34 +00003134 /* Always quote the table name, even if it appears to be pure ascii,
3135 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00003136 initText(&sTable);
3137 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003138 /* If preserving the rowid, add a column list after the table name.
3139 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3140 ** instead of the usual "INSERT INTO tab VALUES(...)".
3141 */
3142 if( azCol[0] ){
3143 appendText(&sTable, "(", 0);
3144 appendText(&sTable, azCol[0], 0);
3145 for(i=1; azCol[i]; i++){
3146 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003147 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003148 }
drhe611f142017-03-08 11:44:00 +00003149 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003150 }
danielk19772a02e332004-06-05 08:04:36 +00003151
drhe611f142017-03-08 11:44:00 +00003152 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003153 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003154 appendText(&sSelect, "SELECT ", 0);
3155 if( azCol[0] ){
3156 appendText(&sSelect, azCol[0], 0);
3157 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003158 }
drhe611f142017-03-08 11:44:00 +00003159 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003160 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003161 if( azCol[i+1] ){
3162 appendText(&sSelect, ",", 0);
3163 }
3164 }
3165 freeColumnList(azCol);
3166 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003167 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003168
3169 savedDestTable = p->zDestTable;
3170 savedMode = p->mode;
3171 p->zDestTable = sTable.z;
3172 p->mode = p->cMode = MODE_Insert;
3173 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003174 if( (rc&0xff)==SQLITE_CORRUPT ){
3175 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3176 toggleSelectOrder(p->db);
3177 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3178 toggleSelectOrder(p->db);
3179 }
drhe611f142017-03-08 11:44:00 +00003180 p->zDestTable = savedDestTable;
3181 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003182 freeText(&sTable);
3183 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003184 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003185 }
drh4c653a02000-06-07 01:27:47 +00003186 return 0;
3187}
3188
3189/*
drh45e29d82006-11-20 16:21:10 +00003190** Run zQuery. Use dump_callback() as the callback routine so that
3191** the contents of the query are output as SQL statements.
3192**
drhdd3d4592004-08-30 01:54:05 +00003193** If we get a SQLITE_CORRUPT error, rerun the query after appending
3194** "ORDER BY rowid DESC" to the end.
3195*/
3196static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003197 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003198 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003199){
3200 int rc;
drh2f464a02011-10-13 00:41:49 +00003201 char *zErr = 0;
3202 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003203 if( rc==SQLITE_CORRUPT ){
3204 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00003205 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00003206 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00003207 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00003208 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003209 sqlite3_free(zErr);
3210 zErr = 0;
3211 }
drhdd3d4592004-08-30 01:54:05 +00003212 zQ2 = malloc( len+100 );
3213 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00003214 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00003215 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3216 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003217 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003218 }else{
3219 rc = SQLITE_CORRUPT;
3220 }
3221 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00003222 free(zQ2);
3223 }
3224 return rc;
3225}
3226
3227/*
drh75897232000-05-29 14:26:00 +00003228** Text of a help message
3229*/
persicom1d0b8722002-04-18 02:53:04 +00003230static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00003231#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00003232 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00003233#endif
drh9ff849f2009-02-04 20:55:57 +00003234 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00003235 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00003236 ".binary on|off Turn binary output on or off. Default OFF\n"
drh453ca042017-05-22 18:00:34 +00003237 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
drhdf12f1c2015-12-07 21:46:19 +00003238 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00003239 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00003240 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00003241 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00003242 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00003243 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00003244 " If TABLE specified, only dump tables matching\n"
3245 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00003246 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00003247 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00003248 ".exit Exit this program\n"
drh700c2522016-02-09 18:39:25 +00003249 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
drh4926fec2016-04-13 15:33:42 +00003250 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003251 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003252 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003253 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003254#ifndef SQLITE_OMIT_TEST_CONTROL
3255 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3256#endif
drh0e55db12015-02-06 14:51:13 +00003257 ".indexes ?TABLE? Show names of all indexes\n"
3258 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003259 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003260#ifdef SQLITE_ENABLE_IOTRACE
3261 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3262#endif
drh1a513372015-05-02 17:40:23 +00003263 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003264 ".lint OPTIONS Report potential schema issues. Options:\n"
3265 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003266#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003267 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003268#endif
drh127f9d72010-02-23 01:47:00 +00003269 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003270 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003271 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003272 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003273 " column Left-aligned columns. (See .width)\n"
3274 " html HTML <table> code\n"
3275 " insert SQL insert statements for TABLE\n"
3276 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003277 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003278 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003279 " tabs Tab-separated values\n"
3280 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003281 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003282 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkin8145fc62016-09-16 20:39:21 +00003283 ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
drhcd0509e2016-09-16 00:26:08 +00003284 " The --new starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003285 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003286 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003287 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003288 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003289 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003290 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003291 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003292 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003293 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3294 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00003295 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00003296 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3297 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003298#if defined(SQLITE_ENABLE_SESSION)
3299 ".session CMD ... Create or control sessions\n"
3300#endif
drh1554bc82017-03-08 16:10:34 +00003301 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003302 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003303 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003304 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003305 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003306 ".tables ?TABLE? List names of tables\n"
3307 " If TABLE specified, only list tables matching\n"
3308 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003309 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003310 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003311 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003312 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003313 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003314 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003315 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003316 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003317 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003318;
3319
drhe6229612014-08-18 15:08:26 +00003320#if defined(SQLITE_ENABLE_SESSION)
3321/*
3322** Print help information for the ".sessions" command
3323*/
3324void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003325 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003326 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3327 "If ?NAME? is omitted, the first defined session is used.\n"
3328 "Subcommands:\n"
3329 " attach TABLE Attach TABLE\n"
3330 " changeset FILE Write a changeset into FILE\n"
3331 " close Close one session\n"
3332 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003333 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003334 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3335 " isempty Query whether the session is empty\n"
3336 " list List currently open session names\n"
3337 " open DB NAME Open a new session on DB\n"
3338 " patchset FILE Write a patchset into FILE\n"
3339 );
3340}
3341#endif
3342
3343
drhdaffd0e2001-04-11 14:28:42 +00003344/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003345static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003346
drh2db82112016-09-15 21:35:24 +00003347/*
dan11da0022016-12-17 08:18:05 +00003348** Read the content of file zName into memory obtained from sqlite3_malloc64()
3349** and return a pointer to the buffer. The caller is responsible for freeing
3350** the memory.
drh2db82112016-09-15 21:35:24 +00003351**
dan11da0022016-12-17 08:18:05 +00003352** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3353** read.
3354**
3355** For convenience, a nul-terminator byte is always appended to the data read
3356** from the file before the buffer is returned. This byte is not included in
3357** the final value of (*pnByte), if applicable.
3358**
3359** NULL is returned if any error is encountered. The final value of *pnByte
3360** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003361*/
dan11da0022016-12-17 08:18:05 +00003362static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003363 FILE *in = fopen(zName, "rb");
3364 long nIn;
drhd1459152016-09-16 19:11:03 +00003365 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003366 char *pBuf;
3367 if( in==0 ) return 0;
3368 fseek(in, 0, SEEK_END);
3369 nIn = ftell(in);
3370 rewind(in);
drhd1459152016-09-16 19:11:03 +00003371 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003372 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003373 nRead = fread(pBuf, nIn, 1, in);
3374 fclose(in);
3375 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003376 sqlite3_free(pBuf);
3377 return 0;
3378 }
drhd1459152016-09-16 19:11:03 +00003379 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003380 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003381 return pBuf;
3382}
3383
drhba5b0932014-07-24 12:39:59 +00003384/*
3385** Implementation of the "readfile(X)" SQL function. The entire content
3386** of the file named X is read and returned as a BLOB. NULL is returned
3387** if the file does not exist or is unreadable.
3388*/
3389static void readfileFunc(
3390 sqlite3_context *context,
3391 int argc,
3392 sqlite3_value **argv
3393){
3394 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003395 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003396 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003397
drhf5ed7ad2015-06-15 14:43:25 +00003398 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003399 zName = (const char*)sqlite3_value_text(argv[0]);
3400 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003401 pBuf = readFile(zName, &nBuf);
3402 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003403}
3404
3405/*
3406** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3407** is written into file X. The number of bytes written is returned. Or
3408** NULL is returned if something goes wrong, such as being unable to open
3409** file X for writing.
3410*/
3411static void writefileFunc(
3412 sqlite3_context *context,
3413 int argc,
3414 sqlite3_value **argv
3415){
3416 FILE *out;
3417 const char *z;
drhba5b0932014-07-24 12:39:59 +00003418 sqlite3_int64 rc;
3419 const char *zFile;
3420
drhf5ed7ad2015-06-15 14:43:25 +00003421 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003422 zFile = (const char*)sqlite3_value_text(argv[0]);
3423 if( zFile==0 ) return;
3424 out = fopen(zFile, "wb");
3425 if( out==0 ) return;
3426 z = (const char*)sqlite3_value_blob(argv[1]);
3427 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003428 rc = 0;
3429 }else{
drh490fe862014-08-11 14:21:32 +00003430 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003431 }
3432 fclose(out);
3433 sqlite3_result_int64(context, rc);
3434}
drhdaffd0e2001-04-11 14:28:42 +00003435
drhe6229612014-08-18 15:08:26 +00003436#if defined(SQLITE_ENABLE_SESSION)
3437/*
3438** Close a single OpenSession object and release all of its associated
3439** resources.
3440*/
3441static void session_close(OpenSession *pSession){
3442 int i;
3443 sqlite3session_delete(pSession->p);
3444 sqlite3_free(pSession->zName);
3445 for(i=0; i<pSession->nFilter; i++){
3446 sqlite3_free(pSession->azFilter[i]);
3447 }
3448 sqlite3_free(pSession->azFilter);
3449 memset(pSession, 0, sizeof(OpenSession));
3450}
3451#endif
3452
3453/*
drh51b55a32016-04-04 12:38:05 +00003454** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003455*/
drhe6229612014-08-18 15:08:26 +00003456#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003457static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003458 int i;
3459 for(i=0; i<p->nSession; i++){
3460 session_close(&p->aSession[i]);
3461 }
3462 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003463}
drh51b55a32016-04-04 12:38:05 +00003464#else
3465# define session_close_all(X)
3466#endif
drhe6229612014-08-18 15:08:26 +00003467
drh75897232000-05-29 14:26:00 +00003468/*
drh03168ca2014-08-18 20:01:31 +00003469** Implementation of the xFilter function for an open session. Omit
3470** any tables named by ".session filter" but let all other table through.
3471*/
3472#if defined(SQLITE_ENABLE_SESSION)
3473static int session_filter(void *pCtx, const char *zTab){
3474 OpenSession *pSession = (OpenSession*)pCtx;
3475 int i;
3476 for(i=0; i<pSession->nFilter; i++){
3477 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3478 }
3479 return 1;
3480}
3481#endif
3482
3483/*
drh44c2eb12003-04-30 11:38:26 +00003484** Make sure the database is open. If it is not, then open it. If
3485** the database fails to open, print an error message and exit.
3486*/
drhdcd87a92014-08-18 13:45:42 +00003487static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003488 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003489 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003490 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003491 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003492 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003493 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003494 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003495 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003496 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003497 }
drhc2e87a32006-06-27 15:16:14 +00003498#ifndef SQLITE_OMIT_LOAD_EXTENSION
3499 sqlite3_enable_load_extension(p->db, 1);
3500#endif
mistachkin8e189222015-04-19 21:43:16 +00003501 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003502 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003503 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003504 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003505 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3506 sha3Func, 0, 0);
3507 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3508 sha3Func, 0, 0);
3509 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3510 sha3QueryFunc, 0, 0);
3511 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3512 sha3QueryFunc, 0, 0);
drh44c2eb12003-04-30 11:38:26 +00003513 }
3514}
3515
3516/*
drhfeac5f82004-08-01 00:10:45 +00003517** Do C-language style dequoting.
3518**
mistachkinf21979d2015-01-18 05:35:01 +00003519** \a -> alarm
3520** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003521** \t -> tab
3522** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003523** \v -> vertical tab
3524** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003525** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003526** \s -> space
drh4c56b992013-06-27 13:26:55 +00003527** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003528** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003529** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003530** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003531*/
3532static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003533 int i, j;
3534 char c;
drhc2ce0be2014-05-29 12:36:14 +00003535 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003536 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003537 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003538 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003539 if( c=='a' ){
3540 c = '\a';
3541 }else if( c=='b' ){
3542 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003543 }else if( c=='t' ){
3544 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003545 }else if( c=='n' ){
3546 c = '\n';
3547 }else if( c=='v' ){
3548 c = '\v';
3549 }else if( c=='f' ){
3550 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003551 }else if( c=='r' ){
3552 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003553 }else if( c=='"' ){
3554 c = '"';
3555 }else if( c=='\'' ){
3556 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003557 }else if( c=='\\' ){
3558 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003559 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003560 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003561 if( z[i+1]>='0' && z[i+1]<='7' ){
3562 i++;
3563 c = (c<<3) + z[i] - '0';
3564 if( z[i+1]>='0' && z[i+1]<='7' ){
3565 i++;
3566 c = (c<<3) + z[i] - '0';
3567 }
3568 }
3569 }
3570 }
3571 z[j] = c;
3572 }
drhc2ce0be2014-05-29 12:36:14 +00003573 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003574}
3575
3576/*
drh348d19c2013-06-03 12:47:43 +00003577** Return the value of a hexadecimal digit. Return -1 if the input
3578** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003579*/
drh348d19c2013-06-03 12:47:43 +00003580static int hexDigitValue(char c){
3581 if( c>='0' && c<='9' ) return c - '0';
3582 if( c>='a' && c<='f' ) return c - 'a' + 10;
3583 if( c>='A' && c<='F' ) return c - 'A' + 10;
3584 return -1;
drhc28490c2006-10-26 14:25:58 +00003585}
3586
3587/*
drh7d9f3942013-04-03 01:26:54 +00003588** Interpret zArg as an integer value, possibly with suffixes.
3589*/
3590static sqlite3_int64 integerValue(const char *zArg){
3591 sqlite3_int64 v = 0;
3592 static const struct { char *zSuffix; int iMult; } aMult[] = {
3593 { "KiB", 1024 },
3594 { "MiB", 1024*1024 },
3595 { "GiB", 1024*1024*1024 },
3596 { "KB", 1000 },
3597 { "MB", 1000000 },
3598 { "GB", 1000000000 },
3599 { "K", 1000 },
3600 { "M", 1000000 },
3601 { "G", 1000000000 },
3602 };
3603 int i;
3604 int isNeg = 0;
3605 if( zArg[0]=='-' ){
3606 isNeg = 1;
3607 zArg++;
3608 }else if( zArg[0]=='+' ){
3609 zArg++;
3610 }
drh348d19c2013-06-03 12:47:43 +00003611 if( zArg[0]=='0' && zArg[1]=='x' ){
3612 int x;
3613 zArg += 2;
3614 while( (x = hexDigitValue(zArg[0]))>=0 ){
3615 v = (v<<4) + x;
3616 zArg++;
3617 }
3618 }else{
3619 while( IsDigit(zArg[0]) ){
3620 v = v*10 + zArg[0] - '0';
3621 zArg++;
3622 }
drh7d9f3942013-04-03 01:26:54 +00003623 }
drhc2bed0a2013-05-24 11:57:50 +00003624 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003625 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3626 v *= aMult[i].iMult;
3627 break;
3628 }
3629 }
3630 return isNeg? -v : v;
3631}
3632
3633/*
drh348d19c2013-06-03 12:47:43 +00003634** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3635** for TRUE and FALSE. Return the integer value if appropriate.
3636*/
drhe6e1d122017-03-09 13:50:49 +00003637static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003638 int i;
3639 if( zArg[0]=='0' && zArg[1]=='x' ){
3640 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3641 }else{
3642 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3643 }
3644 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3645 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3646 return 1;
3647 }
3648 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3649 return 0;
3650 }
mistachkinaae280e2015-12-31 19:06:24 +00003651 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003652 zArg);
3653 return 0;
3654}
3655
3656/*
drhe6e1d122017-03-09 13:50:49 +00003657** Set or clear a shell flag according to a boolean value.
3658*/
3659static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3660 if( booleanValue(zArg) ){
3661 ShellSetFlag(p, mFlag);
3662 }else{
3663 ShellClearFlag(p, mFlag);
3664 }
3665}
3666
3667/*
drh42f64e52012-04-04 16:56:23 +00003668** Close an output file, assuming it is not stderr or stdout
3669*/
3670static void output_file_close(FILE *f){
3671 if( f && f!=stdout && f!=stderr ) fclose(f);
3672}
3673
3674/*
3675** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003676** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003677** filename is "off".
3678*/
3679static FILE *output_file_open(const char *zFile){
3680 FILE *f;
3681 if( strcmp(zFile,"stdout")==0 ){
3682 f = stdout;
3683 }else if( strcmp(zFile, "stderr")==0 ){
3684 f = stderr;
3685 }else if( strcmp(zFile, "off")==0 ){
3686 f = 0;
3687 }else{
3688 f = fopen(zFile, "wb");
3689 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003690 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003691 }
3692 }
3693 return f;
3694}
3695
drhd12602a2016-12-07 15:49:02 +00003696#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003697#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003698/*
3699** A routine for handling output from sqlite3_trace().
3700*/
drh4b363a52016-07-23 20:27:41 +00003701static int sql_trace_callback(
3702 unsigned mType,
3703 void *pArg,
3704 void *pP,
3705 void *pX
3706){
drh42f64e52012-04-04 16:56:23 +00003707 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003708 UNUSED_PARAMETER(mType);
3709 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003710 if( f ){
drh4b363a52016-07-23 20:27:41 +00003711 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003712 int i = (int)strlen(z);
3713 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003714 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003715 }
drh4b363a52016-07-23 20:27:41 +00003716 return 0;
drh42f64e52012-04-04 16:56:23 +00003717}
drhc10b9da2016-11-20 17:59:59 +00003718#endif
3719#endif
drh42f64e52012-04-04 16:56:23 +00003720
3721/*
drhd8621b92012-04-17 09:09:33 +00003722** A no-op routine that runs with the ".breakpoint" doc-command. This is
3723** a useful spot to set a debugger breakpoint.
3724*/
3725static void test_breakpoint(void){
3726 static int nCall = 0;
3727 nCall++;
3728}
3729
3730/*
mistachkin636bf9f2014-07-19 20:15:16 +00003731** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003732*/
mistachkin636bf9f2014-07-19 20:15:16 +00003733typedef struct ImportCtx ImportCtx;
3734struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003735 const char *zFile; /* Name of the input file */
3736 FILE *in; /* Read the CSV text from this input stream */
3737 char *z; /* Accumulated text for a field */
3738 int n; /* Number of bytes in z */
3739 int nAlloc; /* Space allocated for z[] */
3740 int nLine; /* Current line number */
3741 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003742 int cColSep; /* The column separator character. (Usually ",") */
3743 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003744};
3745
3746/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003747static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003748 if( p->n+1>=p->nAlloc ){
3749 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003750 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003751 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003752 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003753 exit(1);
3754 }
3755 }
3756 p->z[p->n++] = (char)c;
3757}
3758
3759/* Read a single field of CSV text. Compatible with rfc4180 and extended
3760** with the option of having a separator other than ",".
3761**
3762** + Input comes from p->in.
3763** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003764** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003765** + Use p->cSep as the column separator. The default is ",".
3766** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003767** + Keep track of the line number in p->nLine.
3768** + Store the character that terminates the field in p->cTerm. Store
3769** EOF on end-of-file.
3770** + Report syntax errors on stderr
3771*/
mistachkin44723ce2015-03-21 02:22:37 +00003772static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003773 int c;
3774 int cSep = p->cColSep;
3775 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003776 p->n = 0;
3777 c = fgetc(p->in);
3778 if( c==EOF || seenInterrupt ){
3779 p->cTerm = EOF;
3780 return 0;
3781 }
3782 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003783 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003784 int startLine = p->nLine;
3785 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003786 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003787 while( 1 ){
3788 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003789 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003790 if( c==cQuote ){
3791 if( pc==cQuote ){
3792 pc = 0;
3793 continue;
3794 }
3795 }
3796 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003797 || (c==rSep && pc==cQuote)
3798 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003799 || (c==EOF && pc==cQuote)
3800 ){
3801 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003802 p->cTerm = c;
3803 break;
3804 }
3805 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003806 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003807 p->zFile, p->nLine, cQuote);
3808 }
3809 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003810 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003811 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003812 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003813 break;
3814 }
mistachkin636bf9f2014-07-19 20:15:16 +00003815 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003816 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003817 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003818 }
drhdb95f682013-06-26 22:46:00 +00003819 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00003820 while( c!=EOF && c!=cSep && c!=rSep ){
3821 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003822 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003823 }
mistachkin636bf9f2014-07-19 20:15:16 +00003824 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003825 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003826 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003827 }
drhdb95f682013-06-26 22:46:00 +00003828 p->cTerm = c;
3829 }
drh8dd675e2013-07-12 21:09:24 +00003830 if( p->z ) p->z[p->n] = 0;
drhdb95f682013-06-26 22:46:00 +00003831 return p->z;
3832}
3833
mistachkin636bf9f2014-07-19 20:15:16 +00003834/* Read a single field of ASCII delimited text.
3835**
3836** + Input comes from p->in.
3837** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003838** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003839** + Use p->cSep as the column separator. The default is "\x1F".
3840** + Use p->rSep as the row separator. The default is "\x1E".
3841** + Keep track of the row number in p->nLine.
3842** + Store the character that terminates the field in p->cTerm. Store
3843** EOF on end-of-file.
3844** + Report syntax errors on stderr
3845*/
mistachkin44723ce2015-03-21 02:22:37 +00003846static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003847 int c;
3848 int cSep = p->cColSep;
3849 int rSep = p->cRowSep;
3850 p->n = 0;
3851 c = fgetc(p->in);
3852 if( c==EOF || seenInterrupt ){
3853 p->cTerm = EOF;
3854 return 0;
3855 }
3856 while( c!=EOF && c!=cSep && c!=rSep ){
3857 import_append_char(p, c);
3858 c = fgetc(p->in);
3859 }
3860 if( c==rSep ){
3861 p->nLine++;
3862 }
3863 p->cTerm = c;
3864 if( p->z ) p->z[p->n] = 0;
3865 return p->z;
3866}
3867
drhdb95f682013-06-26 22:46:00 +00003868/*
drh4bbcf102014-02-06 02:46:08 +00003869** Try to transfer data for table zTable. If an error is seen while
3870** moving forward, try to go backwards. The backwards movement won't
3871** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003872*/
mistachkine31ae902014-02-06 01:15:29 +00003873static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003874 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003875 sqlite3 *newDb,
3876 const char *zTable
3877){
mistachkin1fe36bb2016-04-04 02:16:44 +00003878 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003879 sqlite3_stmt *pInsert = 0;
3880 char *zQuery = 0;
3881 char *zInsert = 0;
3882 int rc;
3883 int i, j, n;
3884 int nTable = (int)strlen(zTable);
3885 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003886 int cnt = 0;
3887 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003888
3889 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3890 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3891 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003892 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003893 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3894 zQuery);
3895 goto end_data_xfer;
3896 }
3897 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00003898 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00003899 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003900 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00003901 goto end_data_xfer;
3902 }
3903 sqlite3_snprintf(200+nTable,zInsert,
3904 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3905 i = (int)strlen(zInsert);
3906 for(j=1; j<n; j++){
3907 memcpy(zInsert+i, ",?", 2);
3908 i += 2;
3909 }
3910 memcpy(zInsert+i, ");", 3);
3911 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3912 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003913 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003914 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3915 zQuery);
3916 goto end_data_xfer;
3917 }
3918 for(k=0; k<2; k++){
3919 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3920 for(i=0; i<n; i++){
3921 switch( sqlite3_column_type(pQuery, i) ){
3922 case SQLITE_NULL: {
3923 sqlite3_bind_null(pInsert, i+1);
3924 break;
3925 }
3926 case SQLITE_INTEGER: {
3927 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3928 break;
3929 }
3930 case SQLITE_FLOAT: {
3931 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3932 break;
3933 }
3934 case SQLITE_TEXT: {
3935 sqlite3_bind_text(pInsert, i+1,
3936 (const char*)sqlite3_column_text(pQuery,i),
3937 -1, SQLITE_STATIC);
3938 break;
3939 }
3940 case SQLITE_BLOB: {
3941 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3942 sqlite3_column_bytes(pQuery,i),
3943 SQLITE_STATIC);
3944 break;
3945 }
3946 }
3947 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00003948 rc = sqlite3_step(pInsert);
3949 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00003950 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00003951 sqlite3_errmsg(newDb));
3952 }
drh3350ce92014-02-06 00:49:12 +00003953 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00003954 cnt++;
3955 if( (cnt%spinRate)==0 ){
3956 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3957 fflush(stdout);
3958 }
drh3350ce92014-02-06 00:49:12 +00003959 } /* End while */
3960 if( rc==SQLITE_DONE ) break;
3961 sqlite3_finalize(pQuery);
3962 sqlite3_free(zQuery);
3963 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3964 zTable);
3965 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3966 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003967 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00003968 break;
drh3350ce92014-02-06 00:49:12 +00003969 }
3970 } /* End for(k=0...) */
3971
3972end_data_xfer:
3973 sqlite3_finalize(pQuery);
3974 sqlite3_finalize(pInsert);
3975 sqlite3_free(zQuery);
3976 sqlite3_free(zInsert);
3977}
3978
3979
3980/*
3981** Try to transfer all rows of the schema that match zWhere. For
3982** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00003983** If an error is encountered while moving forward through the
3984** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00003985*/
mistachkine31ae902014-02-06 01:15:29 +00003986static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00003987 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003988 sqlite3 *newDb,
3989 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00003990 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00003991){
3992 sqlite3_stmt *pQuery = 0;
3993 char *zQuery = 0;
3994 int rc;
3995 const unsigned char *zName;
3996 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00003997 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00003998
3999 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4000 " WHERE %s", zWhere);
4001 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4002 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004003 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004004 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4005 zQuery);
4006 goto end_schema_xfer;
4007 }
4008 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4009 zName = sqlite3_column_text(pQuery, 0);
4010 zSql = sqlite3_column_text(pQuery, 1);
4011 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004012 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4013 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004014 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004015 sqlite3_free(zErrMsg);
4016 zErrMsg = 0;
4017 }
drh3350ce92014-02-06 00:49:12 +00004018 if( xForEach ){
4019 xForEach(p, newDb, (const char*)zName);
4020 }
4021 printf("done\n");
4022 }
4023 if( rc!=SQLITE_DONE ){
4024 sqlite3_finalize(pQuery);
4025 sqlite3_free(zQuery);
4026 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4027 " WHERE %s ORDER BY rowid DESC", zWhere);
4028 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4029 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004030 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004031 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4032 zQuery);
4033 goto end_schema_xfer;
4034 }
4035 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4036 zName = sqlite3_column_text(pQuery, 0);
4037 zSql = sqlite3_column_text(pQuery, 1);
4038 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004039 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4040 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004041 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004042 sqlite3_free(zErrMsg);
4043 zErrMsg = 0;
4044 }
drh3350ce92014-02-06 00:49:12 +00004045 if( xForEach ){
4046 xForEach(p, newDb, (const char*)zName);
4047 }
4048 printf("done\n");
4049 }
4050 }
4051end_schema_xfer:
4052 sqlite3_finalize(pQuery);
4053 sqlite3_free(zQuery);
4054}
4055
4056/*
4057** Open a new database file named "zNewDb". Try to recover as much information
4058** as possible out of the main database (which might be corrupt) and write it
4059** into zNewDb.
4060*/
drhdcd87a92014-08-18 13:45:42 +00004061static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00004062 int rc;
4063 sqlite3 *newDb = 0;
4064 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004065 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00004066 return;
4067 }
4068 rc = sqlite3_open(zNewDb, &newDb);
4069 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004070 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00004071 sqlite3_errmsg(newDb));
4072 }else{
drh54d0d2d2014-04-03 00:32:13 +00004073 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004074 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00004075 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4076 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00004077 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00004078 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004079 }
4080 sqlite3_close(newDb);
4081}
4082
4083/*
drhc2ce0be2014-05-29 12:36:14 +00004084** Change the output file back to stdout
4085*/
drhdcd87a92014-08-18 13:45:42 +00004086static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00004087 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004088#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00004089 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004090#endif
drhc2ce0be2014-05-29 12:36:14 +00004091 }else{
4092 output_file_close(p->out);
4093 }
4094 p->outfile[0] = 0;
4095 p->out = stdout;
4096}
4097
4098/*
drhf7502f02015-02-06 14:19:44 +00004099** Run an SQL command and return the single integer result.
4100*/
4101static int db_int(ShellState *p, const char *zSql){
4102 sqlite3_stmt *pStmt;
4103 int res = 0;
4104 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4105 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4106 res = sqlite3_column_int(pStmt,0);
4107 }
4108 sqlite3_finalize(pStmt);
4109 return res;
4110}
4111
4112/*
4113** Convert a 2-byte or 4-byte big-endian integer into a native integer
4114*/
drha0620ac2016-07-13 13:05:13 +00004115static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004116 return (a[0]<<8) + a[1];
4117}
drha0620ac2016-07-13 13:05:13 +00004118static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004119 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4120}
4121
4122/*
4123** Implementation of the ".info" command.
4124**
4125** Return 1 on error, 2 to exit, and 0 otherwise.
4126*/
drh0e55db12015-02-06 14:51:13 +00004127static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004128 static const struct { const char *zName; int ofst; } aField[] = {
4129 { "file change counter:", 24 },
4130 { "database page count:", 28 },
4131 { "freelist page count:", 36 },
4132 { "schema cookie:", 40 },
4133 { "schema format:", 44 },
4134 { "default cache size:", 48 },
4135 { "autovacuum top root:", 52 },
4136 { "incremental vacuum:", 64 },
4137 { "text encoding:", 56 },
4138 { "user version:", 60 },
4139 { "application id:", 68 },
4140 { "software version:", 96 },
4141 };
drh0e55db12015-02-06 14:51:13 +00004142 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4143 { "number of tables:",
4144 "SELECT count(*) FROM %s WHERE type='table'" },
4145 { "number of indexes:",
4146 "SELECT count(*) FROM %s WHERE type='index'" },
4147 { "number of triggers:",
4148 "SELECT count(*) FROM %s WHERE type='trigger'" },
4149 { "number of views:",
4150 "SELECT count(*) FROM %s WHERE type='view'" },
4151 { "schema size:",
4152 "SELECT total(length(sql)) FROM %s" },
4153 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004154 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004155 int i;
4156 char *zSchemaTab;
4157 char *zDb = nArg>=2 ? azArg[1] : "main";
4158 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004159 open_db(p, 0);
4160 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004161 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004162 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4163 return 1;
4164 }
4165 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4166 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004167 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004168 return 1;
4169 }
4170 i = get2byteInt(aHdr+16);
4171 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004172 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4173 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4174 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4175 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004176 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004177 int ofst = aField[i].ofst;
4178 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004179 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004180 switch( ofst ){
4181 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004182 if( val==1 ) raw_printf(p->out, " (utf8)");
4183 if( val==2 ) raw_printf(p->out, " (utf16le)");
4184 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004185 }
4186 }
mistachkinaae280e2015-12-31 19:06:24 +00004187 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004188 }
drh0e55db12015-02-06 14:51:13 +00004189 if( zDb==0 ){
4190 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4191 }else if( strcmp(zDb,"temp")==0 ){
4192 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4193 }else{
4194 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4195 }
drhf5ed7ad2015-06-15 14:43:25 +00004196 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004197 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4198 int val = db_int(p, zSql);
4199 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004200 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004201 }
4202 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004203 return 0;
4204}
4205
dand95bb392015-09-30 11:19:05 +00004206/*
4207** Print the current sqlite3_errmsg() value to stderr and return 1.
4208*/
4209static int shellDatabaseError(sqlite3 *db){
4210 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004211 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004212 return 1;
4213}
4214
4215/*
4216** Print an out-of-memory message to stderr and return 1.
4217*/
4218static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004219 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004220 return 1;
4221}
drhf7502f02015-02-06 14:19:44 +00004222
drh2db82112016-09-15 21:35:24 +00004223/*
4224** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4225** if they match and FALSE (0) if they do not match.
4226**
4227** Globbing rules:
4228**
4229** '*' Matches any sequence of zero or more characters.
4230**
4231** '?' Matches exactly one character.
4232**
4233** [...] Matches one character from the enclosed list of
4234** characters.
4235**
4236** [^...] Matches one character not in the enclosed list.
4237**
4238** '#' Matches any sequence of one or more digits with an
4239** optional + or - sign in front
4240**
4241** ' ' Any span of whitespace matches any other span of
4242** whitespace.
4243**
4244** Extra whitespace at the end of z[] is ignored.
4245*/
4246static int testcase_glob(const char *zGlob, const char *z){
4247 int c, c2;
4248 int invert;
4249 int seen;
4250
4251 while( (c = (*(zGlob++)))!=0 ){
4252 if( IsSpace(c) ){
4253 if( !IsSpace(*z) ) return 0;
4254 while( IsSpace(*zGlob) ) zGlob++;
4255 while( IsSpace(*z) ) z++;
4256 }else if( c=='*' ){
4257 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4258 if( c=='?' && (*(z++))==0 ) return 0;
4259 }
4260 if( c==0 ){
4261 return 1;
4262 }else if( c=='[' ){
4263 while( *z && testcase_glob(zGlob-1,z)==0 ){
4264 z++;
4265 }
4266 return (*z)!=0;
4267 }
4268 while( (c2 = (*(z++)))!=0 ){
4269 while( c2!=c ){
4270 c2 = *(z++);
4271 if( c2==0 ) return 0;
4272 }
4273 if( testcase_glob(zGlob,z) ) return 1;
4274 }
4275 return 0;
4276 }else if( c=='?' ){
4277 if( (*(z++))==0 ) return 0;
4278 }else if( c=='[' ){
4279 int prior_c = 0;
4280 seen = 0;
4281 invert = 0;
4282 c = *(z++);
4283 if( c==0 ) return 0;
4284 c2 = *(zGlob++);
4285 if( c2=='^' ){
4286 invert = 1;
4287 c2 = *(zGlob++);
4288 }
4289 if( c2==']' ){
4290 if( c==']' ) seen = 1;
4291 c2 = *(zGlob++);
4292 }
4293 while( c2 && c2!=']' ){
4294 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4295 c2 = *(zGlob++);
4296 if( c>=prior_c && c<=c2 ) seen = 1;
4297 prior_c = 0;
4298 }else{
4299 if( c==c2 ){
4300 seen = 1;
4301 }
4302 prior_c = c2;
4303 }
4304 c2 = *(zGlob++);
4305 }
4306 if( c2==0 || (seen ^ invert)==0 ) return 0;
4307 }else if( c=='#' ){
4308 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4309 if( !IsDigit(z[0]) ) return 0;
4310 z++;
4311 while( IsDigit(z[0]) ){ z++; }
4312 }else{
4313 if( c!=(*(z++)) ) return 0;
4314 }
4315 }
4316 while( IsSpace(*z) ){ z++; }
4317 return *z==0;
4318}
drh2db82112016-09-15 21:35:24 +00004319
4320
drhf7502f02015-02-06 14:19:44 +00004321/*
drh4926fec2016-04-13 15:33:42 +00004322** Compare the string as a command-line option with either one or two
4323** initial "-" characters.
4324*/
4325static int optionMatch(const char *zStr, const char *zOpt){
4326 if( zStr[0]!='-' ) return 0;
4327 zStr++;
4328 if( zStr[0]=='-' ) zStr++;
4329 return strcmp(zStr, zOpt)==0;
4330}
4331
4332/*
drhcd0509e2016-09-16 00:26:08 +00004333** Delete a file.
4334*/
4335int shellDeleteFile(const char *zFilename){
4336 int rc;
4337#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004338 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004339 rc = _wunlink(z);
4340 sqlite3_free(z);
4341#else
4342 rc = unlink(zFilename);
4343#endif
4344 return rc;
4345}
4346
dan35ac58e2016-12-14 19:28:27 +00004347
dan35ac58e2016-12-14 19:28:27 +00004348/*
dandd9e0be2016-12-16 16:44:27 +00004349** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004350** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004351** called with four arguments - the parent table name, the parent column name,
4352** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004353**
4354** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4355**
4356** If either of the named tables or columns do not exist, this function
4357** returns an empty string. An empty string is also returned if both tables
4358** and columns exist but have the same default collation sequence. Or,
4359** if both exist but the default collation sequences are different, this
4360** function returns the string " COLLATE <parent-collation>", where
4361** <parent-collation> is the default collation sequence of the parent column.
4362*/
4363static void shellFkeyCollateClause(
4364 sqlite3_context *pCtx,
4365 int nVal,
4366 sqlite3_value **apVal
4367){
4368 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4369 const char *zParent;
4370 const char *zParentCol;
4371 const char *zParentSeq;
4372 const char *zChild;
4373 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004374 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004375 int rc;
4376
4377 assert( nVal==4 );
4378 zParent = (const char*)sqlite3_value_text(apVal[0]);
4379 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4380 zChild = (const char*)sqlite3_value_text(apVal[2]);
4381 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4382
4383 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4384 rc = sqlite3_table_column_metadata(
4385 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4386 );
4387 if( rc==SQLITE_OK ){
4388 rc = sqlite3_table_column_metadata(
4389 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4390 );
4391 }
4392
4393 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4394 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4395 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4396 sqlite3_free(z);
4397 }
4398}
4399
4400
4401/*
dan3c7ebeb2016-12-16 17:28:56 +00004402** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004403*/
dan3c7ebeb2016-12-16 17:28:56 +00004404static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004405 ShellState *pState, /* Current shell tool state */
4406 char **azArg, /* Array of arguments passed to dot command */
4407 int nArg /* Number of entries in azArg[] */
4408){
dandd9e0be2016-12-16 16:44:27 +00004409 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4410 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004411 int bVerbose = 0; /* If -verbose is present */
4412 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004413 int i; /* To iterate through azArg[] */
4414 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4415 int rc; /* Return code */
4416 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004417
dandd9e0be2016-12-16 16:44:27 +00004418 /*
4419 ** This SELECT statement returns one row for each foreign key constraint
4420 ** in the schema of the main database. The column values are:
4421 **
4422 ** 0. The text of an SQL statement similar to:
4423 **
4424 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4425 **
4426 ** This is the same SELECT that the foreign keys implementation needs
4427 ** to run internally on child tables. If there is an index that can
4428 ** be used to optimize this query, then it can also be used by the FK
4429 ** implementation to optimize DELETE or UPDATE statements on the parent
4430 ** table.
4431 **
4432 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4433 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4434 ** contains an index that can be used to optimize the query.
4435 **
4436 ** 2. Human readable text that describes the child table and columns. e.g.
4437 **
4438 ** "child_table(child_key1, child_key2)"
4439 **
4440 ** 3. Human readable text that describes the parent table and columns. e.g.
4441 **
4442 ** "parent_table(parent_key1, parent_key2)"
4443 **
4444 ** 4. A full CREATE INDEX statement for an index that could be used to
4445 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4446 **
4447 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4448 **
4449 ** 5. The name of the parent table.
4450 **
4451 ** These six values are used by the C logic below to generate the report.
4452 */
dan35ac58e2016-12-14 19:28:27 +00004453 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004454 "SELECT "
4455 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4456 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00004457 " || fkey_collate_clause("
4458 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004459 ", "
dandd9e0be2016-12-16 16:44:27 +00004460 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004461 " || group_concat('*=?', ' AND ') || ')'"
4462 ", "
dandd9e0be2016-12-16 16:44:27 +00004463 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004464 ", "
dan50da9382017-04-06 12:06:56 +00004465 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00004466 ", "
dandd9e0be2016-12-16 16:44:27 +00004467 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4468 " || ' ON ' || quote(s.name) || '('"
4469 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00004470 " fkey_collate_clause("
4471 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004472 " || ');'"
danf9647b62016-12-15 06:01:40 +00004473 ", "
dandd9e0be2016-12-16 16:44:27 +00004474 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00004475 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00004476 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00004477 "GROUP BY s.name, f.id "
4478 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004479 ;
dan54e2efc2017-04-06 14:56:26 +00004480 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00004481
dan3c7ebeb2016-12-16 17:28:56 +00004482 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004483 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004484 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4485 bVerbose = 1;
4486 }
4487 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4488 bGroupByParent = 1;
4489 zIndent = " ";
4490 }
4491 else{
dan3c7ebeb2016-12-16 17:28:56 +00004492 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4493 azArg[0], azArg[1]
4494 );
danf9647b62016-12-15 06:01:40 +00004495 return SQLITE_ERROR;
4496 }
dan35ac58e2016-12-14 19:28:27 +00004497 }
dan35ac58e2016-12-14 19:28:27 +00004498
4499 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004500 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4501 0, shellFkeyCollateClause, 0, 0
4502 );
dan35ac58e2016-12-14 19:28:27 +00004503
4504
4505 if( rc==SQLITE_OK ){
4506 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4507 }
danf9647b62016-12-15 06:01:40 +00004508 if( rc==SQLITE_OK ){
4509 sqlite3_bind_int(pSql, 1, bGroupByParent);
4510 }
dan35ac58e2016-12-14 19:28:27 +00004511
4512 if( rc==SQLITE_OK ){
4513 int rc2;
danf9647b62016-12-15 06:01:40 +00004514 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004515 while( SQLITE_ROW==sqlite3_step(pSql) ){
4516 int res = -1;
4517 sqlite3_stmt *pExplain = 0;
4518 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4519 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4520 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4521 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4522 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004523 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004524
4525 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4526 if( rc!=SQLITE_OK ) break;
4527 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4528 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00004529 res = (
4530 0==sqlite3_strglob(zGlob, zPlan)
4531 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4532 );
dan35ac58e2016-12-14 19:28:27 +00004533 }
4534 rc = sqlite3_finalize(pExplain);
4535 if( rc!=SQLITE_OK ) break;
4536
4537 if( res<0 ){
4538 raw_printf(stderr, "Error: internal error");
4539 break;
danf9647b62016-12-15 06:01:40 +00004540 }else{
4541 if( bGroupByParent
4542 && (bVerbose || res==0)
4543 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4544 ){
4545 raw_printf(out, "-- Parent table %s\n", zParent);
4546 sqlite3_free(zPrev);
4547 zPrev = sqlite3_mprintf("%s", zParent);
4548 }
4549
4550 if( res==0 ){
4551 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4552 }else if( bVerbose ){
4553 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4554 zIndent, zFrom, zTarget
4555 );
4556 }
dan35ac58e2016-12-14 19:28:27 +00004557 }
4558 }
danf9647b62016-12-15 06:01:40 +00004559 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004560
4561 if( rc!=SQLITE_OK ){
4562 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4563 }
4564
4565 rc2 = sqlite3_finalize(pSql);
4566 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4567 rc = rc2;
4568 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4569 }
4570 }else{
4571 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4572 }
4573
4574 return rc;
4575}
dan3c7ebeb2016-12-16 17:28:56 +00004576
dan35ac58e2016-12-14 19:28:27 +00004577/*
dan3c7ebeb2016-12-16 17:28:56 +00004578** Implementation of ".lint" dot command.
4579*/
4580static int lintDotCommand(
4581 ShellState *pState, /* Current shell tool state */
4582 char **azArg, /* Array of arguments passed to dot command */
4583 int nArg /* Number of entries in azArg[] */
4584){
4585 int n;
drh96ada592016-12-29 19:48:46 +00004586 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004587 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4588 return lintFkeyIndexes(pState, azArg, nArg);
4589
4590 usage:
4591 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4592 raw_printf(stderr, "Where sub-commands are:\n");
4593 raw_printf(stderr, " fkey-indexes\n");
4594 return SQLITE_ERROR;
4595}
4596
dan35ac58e2016-12-14 19:28:27 +00004597
drhcd0509e2016-09-16 00:26:08 +00004598/*
drh75897232000-05-29 14:26:00 +00004599** If an input line begins with "." then invoke this routine to
4600** process that line.
drh67505e72002-04-19 12:34:06 +00004601**
drh47ad6842006-11-08 12:25:42 +00004602** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004603*/
drhdcd87a92014-08-18 13:45:42 +00004604static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004605 int h = 1;
drh75897232000-05-29 14:26:00 +00004606 int nArg = 0;
4607 int n, c;
drh67505e72002-04-19 12:34:06 +00004608 int rc = 0;
drh75897232000-05-29 14:26:00 +00004609 char *azArg[50];
4610
4611 /* Parse the input line into tokens.
4612 */
mistachkin8e189222015-04-19 21:43:16 +00004613 while( zLine[h] && nArg<ArraySize(azArg) ){
4614 while( IsSpace(zLine[h]) ){ h++; }
4615 if( zLine[h]==0 ) break;
4616 if( zLine[h]=='\'' || zLine[h]=='"' ){
4617 int delim = zLine[h++];
4618 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004619 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004620 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004621 h++;
drh4c56b992013-06-27 13:26:55 +00004622 }
mistachkin8e189222015-04-19 21:43:16 +00004623 if( zLine[h]==delim ){
4624 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004625 }
drhfeac5f82004-08-01 00:10:45 +00004626 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004627 }else{
mistachkin8e189222015-04-19 21:43:16 +00004628 azArg[nArg++] = &zLine[h];
4629 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4630 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004631 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004632 }
4633 }
4634
4635 /* Process the input line.
4636 */
shane9bd1b442009-10-23 01:27:39 +00004637 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004638 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004639 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004640
drha0daa752016-09-16 11:53:10 +00004641#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004642 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4643 if( nArg!=2 ){
4644 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4645 rc = 1;
4646 goto meta_command_exit;
4647 }
4648 open_db(p, 0);
4649 if( booleanValue(azArg[1]) ){
4650 sqlite3_set_authorizer(p->db, shellAuth, p);
4651 }else{
4652 sqlite3_set_authorizer(p->db, 0, 0);
4653 }
4654 }else
drha0daa752016-09-16 11:53:10 +00004655#endif
drhde613c62016-04-04 17:23:10 +00004656
drh5c7976f2014-02-10 19:59:27 +00004657 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4658 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4659 ){
drhbc46f022013-01-23 18:53:23 +00004660 const char *zDestFile = 0;
4661 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004662 sqlite3 *pDest;
4663 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004664 int j;
4665 for(j=1; j<nArg; j++){
4666 const char *z = azArg[j];
4667 if( z[0]=='-' ){
4668 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004669 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004670 {
mistachkinaae280e2015-12-31 19:06:24 +00004671 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004672 return 1;
4673 }
4674 }else if( zDestFile==0 ){
4675 zDestFile = azArg[j];
4676 }else if( zDb==0 ){
4677 zDb = zDestFile;
4678 zDestFile = azArg[j];
4679 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004680 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004681 return 1;
4682 }
drh9ff849f2009-02-04 20:55:57 +00004683 }
drhbc46f022013-01-23 18:53:23 +00004684 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004685 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004686 return 1;
4687 }
4688 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004689 rc = sqlite3_open(zDestFile, &pDest);
4690 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004691 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004692 sqlite3_close(pDest);
4693 return 1;
4694 }
drh05782482013-10-24 15:20:20 +00004695 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004696 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4697 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004698 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004699 sqlite3_close(pDest);
4700 return 1;
4701 }
4702 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4703 sqlite3_backup_finish(pBackup);
4704 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004705 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004706 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004707 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004708 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004709 }
4710 sqlite3_close(pDest);
4711 }else
4712
drhc2ce0be2014-05-29 12:36:14 +00004713 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4714 if( nArg==2 ){
4715 bail_on_error = booleanValue(azArg[1]);
4716 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004717 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004718 rc = 1;
4719 }
drhc49f44e2006-10-26 18:15:42 +00004720 }else
4721
mistachkinf21979d2015-01-18 05:35:01 +00004722 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4723 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004724 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004725 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004726 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004727 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004728 }
mistachkinf21979d2015-01-18 05:35:01 +00004729 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004730 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004731 rc = 1;
4732 }
4733 }else
4734
drh453ca042017-05-22 18:00:34 +00004735 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4736 if( nArg==2 ){
4737#if defined(_WIN32) || defined(WIN32)
4738 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4739 rc = !SetCurrentDirectoryW(z);
4740 sqlite3_free(z);
4741#else
4742 rc = chdir(azArg[1]);
4743#endif
4744 if( rc ){
4745 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4746 rc = 1;
4747 }
4748 }else{
4749 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4750 rc = 1;
4751 }
4752 }else
4753
drhd8621b92012-04-17 09:09:33 +00004754 /* The undocumented ".breakpoint" command causes a call to the no-op
4755 ** routine named test_breakpoint().
4756 */
4757 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4758 test_breakpoint();
4759 }else
4760
drhdf12f1c2015-12-07 21:46:19 +00004761 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4762 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004763 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004764 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004765 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004766 rc = 1;
4767 }
4768 }else
4769
drh2db82112016-09-15 21:35:24 +00004770 /* Cancel output redirection, if it is currently set (by .testcase)
4771 ** Then read the content of the testcase-out.txt file and compare against
4772 ** azArg[1]. If there are differences, report an error and exit.
4773 */
4774 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4775 char *zRes = 0;
4776 output_reset(p);
4777 if( nArg!=2 ){
4778 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004779 rc = 2;
dan11da0022016-12-17 08:18:05 +00004780 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004781 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4782 rc = 2;
4783 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004784 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004785 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4786 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004787 rc = 2;
drh760c8162016-09-16 02:52:22 +00004788 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004789 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004790 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004791 }
4792 sqlite3_free(zRes);
4793 }else
drh2db82112016-09-15 21:35:24 +00004794
drhc2ce0be2014-05-29 12:36:14 +00004795 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4796 if( nArg==2 ){
4797 tryToClone(p, azArg[1]);
4798 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004799 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004800 rc = 1;
4801 }
mistachkine31ae902014-02-06 01:15:29 +00004802 }else
4803
drhc2ce0be2014-05-29 12:36:14 +00004804 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004805 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004806 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004807 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004808 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004809 data.showHeader = 0;
4810 data.cMode = data.mode = MODE_List;
4811 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004812 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004813 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4814 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004815 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004816 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004817 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004818 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004819 }
4820 }else
4821
drh0e55db12015-02-06 14:51:13 +00004822 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4823 rc = shell_dbinfo_command(p, nArg, azArg);
4824 }else
4825
drhc2ce0be2014-05-29 12:36:14 +00004826 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004827 const char *zLike = 0;
4828 int i;
drh72507d42017-04-08 00:55:13 +00004829 int savedShowHeader = p->showHeader;
drhe6e1d122017-03-09 13:50:49 +00004830 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004831 for(i=1; i<nArg; i++){
4832 if( azArg[i][0]=='-' ){
4833 const char *z = azArg[i]+1;
4834 if( z[0]=='-' ) z++;
4835 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00004836#ifdef SQLITE_OMIT_VIRTUALTABLE
4837 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4838 " with SQLITE_OMIT_VIRTUALTABLE\n");
4839 rc = 1;
4840 goto meta_command_exit;
4841#else
drhe6e1d122017-03-09 13:50:49 +00004842 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00004843#endif
drhe611f142017-03-08 11:44:00 +00004844 }else
4845 {
4846 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4847 rc = 1;
4848 goto meta_command_exit;
4849 }
4850 }else if( zLike ){
4851 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4852 rc = 1;
4853 goto meta_command_exit;
4854 }else{
4855 zLike = azArg[i];
4856 }
4857 }
drh05782482013-10-24 15:20:20 +00004858 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004859 /* When playing back a "dump", the content might appear in an order
4860 ** which causes immediate foreign key constraints to be violated.
4861 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004862 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4863 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004864 p->writableSchema = 0;
drh72507d42017-04-08 00:55:13 +00004865 p->showHeader = 0;
drhe611f142017-03-08 11:44:00 +00004866 /* Set writable_schema=ON since doing so forces SQLite to initialize
4867 ** as much of the schema as it can even if the sqlite_master table is
4868 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004869 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004870 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004871 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004872 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004873 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004874 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004875 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004876 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004877 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004878 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004879 );
drh2f464a02011-10-13 00:41:49 +00004880 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004881 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004882 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004883 );
drh4c653a02000-06-07 01:27:47 +00004884 }else{
drhe611f142017-03-08 11:44:00 +00004885 char *zSql;
4886 zSql = sqlite3_mprintf(
4887 "SELECT name, type, sql FROM sqlite_master "
4888 "WHERE tbl_name LIKE %Q AND type=='table'"
4889 " AND sql NOT NULL", zLike);
4890 run_schema_dump_query(p,zSql);
4891 sqlite3_free(zSql);
4892 zSql = sqlite3_mprintf(
4893 "SELECT sql FROM sqlite_master "
4894 "WHERE sql NOT NULL"
4895 " AND type IN ('index','trigger','view')"
4896 " AND tbl_name LIKE %Q", zLike);
4897 run_table_dump_query(p, zSql, 0);
4898 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00004899 }
drh45e29d82006-11-20 16:21:10 +00004900 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00004901 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00004902 p->writableSchema = 0;
4903 }
drh56197952011-10-13 16:30:13 +00004904 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4905 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00004906 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh72507d42017-04-08 00:55:13 +00004907 p->showHeader = savedShowHeader;
drh4c653a02000-06-07 01:27:47 +00004908 }else
drh75897232000-05-29 14:26:00 +00004909
drhc2ce0be2014-05-29 12:36:14 +00004910 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4911 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004912 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00004913 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004914 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004915 rc = 1;
4916 }
drhdaffd0e2001-04-11 14:28:42 +00004917 }else
4918
drhc2ce0be2014-05-29 12:36:14 +00004919 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4920 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00004921 if( strcmp(azArg[1],"full")==0 ){
4922 p->autoEQP = 2;
4923 }else{
4924 p->autoEQP = booleanValue(azArg[1]);
4925 }
drhc2ce0be2014-05-29 12:36:14 +00004926 }else{
drheacd29d2016-04-15 15:03:27 +00004927 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00004928 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00004929 }
drhefbf3b12014-02-28 20:47:24 +00004930 }else
4931
drhd3ac7d92013-01-25 18:33:43 +00004932 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00004933 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00004934 rc = 2;
drh75897232000-05-29 14:26:00 +00004935 }else
4936
drhc2ce0be2014-05-29 12:36:14 +00004937 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00004938 int val = 1;
4939 if( nArg>=2 ){
4940 if( strcmp(azArg[1],"auto")==0 ){
4941 val = 99;
4942 }else{
4943 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00004944 }
drh700c2522016-02-09 18:39:25 +00004945 }
4946 if( val==1 && p->mode!=MODE_Explain ){
4947 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00004948 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00004949 p->autoExplain = 0;
4950 }else if( val==0 ){
4951 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4952 p->autoExplain = 0;
4953 }else if( val==99 ){
4954 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4955 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00004956 }
drh75897232000-05-29 14:26:00 +00004957 }else
4958
drhc1971542014-06-23 23:28:13 +00004959 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004960 ShellState data;
drhc1971542014-06-23 23:28:13 +00004961 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00004962 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00004963 memcpy(&data, p, sizeof(data));
4964 data.showHeader = 0;
4965 data.cMode = data.mode = MODE_Semi;
4966 if( nArg==2 && optionMatch(azArg[1], "indent") ){
4967 data.cMode = data.mode = MODE_Pretty;
4968 nArg = 1;
4969 }
drhc1971542014-06-23 23:28:13 +00004970 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00004971 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00004972 rc = 1;
4973 goto meta_command_exit;
4974 }
4975 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00004976 rc = sqlite3_exec(p->db,
4977 "SELECT sql FROM"
4978 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4979 " FROM sqlite_master UNION ALL"
4980 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00004981 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00004982 "ORDER BY rowid",
4983 callback, &data, &zErrMsg
4984 );
drh56f674c2014-07-18 14:43:29 +00004985 if( rc==SQLITE_OK ){
4986 sqlite3_stmt *pStmt;
4987 rc = sqlite3_prepare_v2(p->db,
4988 "SELECT rowid FROM sqlite_master"
4989 " WHERE name GLOB 'sqlite_stat[134]'",
4990 -1, &pStmt, 0);
4991 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4992 sqlite3_finalize(pStmt);
4993 }
4994 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004995 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00004996 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004997 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00004998 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4999 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00005000 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00005001 data.zDestTable = "sqlite_stat1";
5002 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5003 shell_callback, &data,&zErrMsg);
5004 data.zDestTable = "sqlite_stat3";
5005 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5006 shell_callback, &data,&zErrMsg);
5007 data.zDestTable = "sqlite_stat4";
5008 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5009 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00005010 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005011 }
drhc1971542014-06-23 23:28:13 +00005012 }else
5013
drhc2ce0be2014-05-29 12:36:14 +00005014 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5015 if( nArg==2 ){
5016 p->showHeader = booleanValue(azArg[1]);
5017 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005018 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005019 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00005020 }
drh75897232000-05-29 14:26:00 +00005021 }else
5022
drhc2ce0be2014-05-29 12:36:14 +00005023 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005024 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00005025 }else
5026
5027 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00005028 char *zTable; /* Insert data into this table */
5029 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00005030 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00005031 int nCol; /* Number of columns in the table */
5032 int nByte; /* Number of bytes in an SQL string */
5033 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00005034 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00005035 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00005036 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00005037 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00005038 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5039 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00005040
drhc2ce0be2014-05-29 12:36:14 +00005041 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005042 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00005043 goto meta_command_exit;
5044 }
drh01f37542014-05-31 15:43:33 +00005045 zFile = azArg[1];
5046 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00005047 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00005048 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00005049 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005050 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00005051 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005052 raw_printf(stderr,
5053 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00005054 return 1;
drhfeac5f82004-08-01 00:10:45 +00005055 }
drhdb95f682013-06-26 22:46:00 +00005056 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005057 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00005058 " for import\n");
5059 return 1;
5060 }
mistachkin636bf9f2014-07-19 20:15:16 +00005061 nSep = strlen30(p->rowSeparator);
5062 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005063 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005064 return 1;
5065 }
mistachkine0d68852014-12-11 03:12:33 +00005066 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5067 /* When importing CSV (only), if the row separator is set to the
5068 ** default output row separator, change it to the default input
5069 ** row separator. This avoids having to maintain different input
5070 ** and output row separators. */
5071 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5072 nSep = strlen30(p->rowSeparator);
5073 }
mistachkin636bf9f2014-07-19 20:15:16 +00005074 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005075 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00005076 " for import\n");
5077 return 1;
5078 }
5079 sCtx.zFile = zFile;
5080 sCtx.nLine = 1;
5081 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005082#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005083 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005084 return 1;
5085#else
mistachkin636bf9f2014-07-19 20:15:16 +00005086 sCtx.in = popen(sCtx.zFile+1, "r");
5087 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00005088 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00005089#endif
drh5bde8162013-06-27 14:07:53 +00005090 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00005091 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00005092 xCloser = fclose;
5093 }
mistachkin636bf9f2014-07-19 20:15:16 +00005094 if( p->mode==MODE_Ascii ){
5095 xRead = ascii_read_one_field;
5096 }else{
5097 xRead = csv_read_one_field;
5098 }
5099 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005100 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00005101 return 1;
5102 }
mistachkin636bf9f2014-07-19 20:15:16 +00005103 sCtx.cColSep = p->colSeparator[0];
5104 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00005105 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00005106 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005107 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005108 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005109 return 1;
5110 }
drh4f21c4a2008-12-10 22:15:00 +00005111 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005112 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005113 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005114 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005115 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5116 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005117 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005118 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005119 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005120 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005121 }
drh5bde8162013-06-27 14:07:53 +00005122 if( cSep=='(' ){
5123 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005124 sqlite3_free(sCtx.z);
5125 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005126 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005127 return 1;
5128 }
drhdb95f682013-06-26 22:46:00 +00005129 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5130 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5131 sqlite3_free(zCreate);
5132 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005133 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005134 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005135 sqlite3_free(sCtx.z);
5136 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005137 return 1;
5138 }
drhc7181902014-02-27 15:04:13 +00005139 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005140 }
drhfeac5f82004-08-01 00:10:45 +00005141 sqlite3_free(zSql);
5142 if( rc ){
shane916f9612009-10-23 00:37:15 +00005143 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005144 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005145 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005146 return 1;
drhfeac5f82004-08-01 00:10:45 +00005147 }
shane916f9612009-10-23 00:37:15 +00005148 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005149 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005150 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005151 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005152 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005153 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005154 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005155 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005156 return 1;
5157 }
drhdb95f682013-06-26 22:46:00 +00005158 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005159 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005160 for(i=1; i<nCol; i++){
5161 zSql[j++] = ',';
5162 zSql[j++] = '?';
5163 }
5164 zSql[j++] = ')';
5165 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005166 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005167 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005168 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005169 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005170 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00005171 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00005172 return 1;
drhfeac5f82004-08-01 00:10:45 +00005173 }
mistachkin8e189222015-04-19 21:43:16 +00005174 needCommit = sqlite3_get_autocommit(p->db);
5175 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00005176 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005177 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005178 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005179 char *z = xRead(&sCtx);
5180 /*
5181 ** Did we reach end-of-file before finding any columns?
5182 ** If so, stop instead of NULL filling the remaining columns.
5183 */
drhdb95f682013-06-26 22:46:00 +00005184 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005185 /*
5186 ** Did we reach end-of-file OR end-of-line before finding any
5187 ** columns in ASCII mode? If so, stop instead of NULL filling
5188 ** the remaining columns.
5189 */
5190 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005191 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005192 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005193 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005194 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005195 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005196 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005197 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005198 }
drhfeac5f82004-08-01 00:10:45 +00005199 }
mistachkin636bf9f2014-07-19 20:15:16 +00005200 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005201 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005202 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005203 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005204 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005205 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005206 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005207 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005208 }
drhdb95f682013-06-26 22:46:00 +00005209 if( i>=nCol ){
5210 sqlite3_step(pStmt);
5211 rc = sqlite3_reset(pStmt);
5212 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005213 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5214 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005215 }
5216 }
mistachkin636bf9f2014-07-19 20:15:16 +00005217 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005218
mistachkin636bf9f2014-07-19 20:15:16 +00005219 xCloser(sCtx.in);
5220 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005221 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005222 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005223 }else
5224
drhd12602a2016-12-07 15:49:02 +00005225#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005226 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5227 char *zSql;
5228 char *zCollist = 0;
5229 sqlite3_stmt *pStmt;
5230 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005231 int i;
drh16eb5942016-11-03 13:01:38 +00005232 if( nArg!=3 ){
5233 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5234 rc = 1;
5235 goto meta_command_exit;
5236 }
5237 open_db(p, 0);
5238 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5239 " WHERE name='%q' AND type='index'", azArg[1]);
5240 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5241 sqlite3_free(zSql);
5242 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5243 tnum = sqlite3_column_int(pStmt, 0);
5244 }
5245 sqlite3_finalize(pStmt);
5246 if( tnum==0 ){
5247 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5248 rc = 1;
5249 goto meta_command_exit;
5250 }
5251 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5252 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5253 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005254 i = 0;
drh16eb5942016-11-03 13:01:38 +00005255 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005256 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005257 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005258 i++;
5259 if( zCol==0 ){
5260 if( sqlite3_column_int(pStmt,1)==-1 ){
5261 zCol = "_ROWID_";
5262 }else{
5263 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5264 zCol = zLabel;
5265 }
5266 }
drh16eb5942016-11-03 13:01:38 +00005267 if( zCollist==0 ){
5268 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5269 }else{
5270 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5271 }
5272 }
5273 sqlite3_finalize(pStmt);
5274 zSql = sqlite3_mprintf(
5275 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5276 azArg[2], zCollist, zCollist);
5277 sqlite3_free(zCollist);
5278 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5279 if( rc==SQLITE_OK ){
5280 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5281 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5282 if( rc ){
5283 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5284 }else{
5285 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005286 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005287 "WARNING: writing to an imposter table will corrupt the index!\n"
5288 );
5289 }
5290 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005291 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005292 rc = 1;
5293 }
5294 sqlite3_free(zSql);
5295 }else
5296#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5297
drhae5e4452007-05-03 17:18:36 +00005298#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005299 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005300 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005301 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5302 iotrace = 0;
5303 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005304 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005305 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005306 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005307 iotrace = stdout;
5308 }else{
5309 iotrace = fopen(azArg[1], "w");
5310 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005311 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005312 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005313 rc = 1;
drhb0603412007-02-28 04:47:26 +00005314 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005315 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005316 }
5317 }
5318 }else
drhae5e4452007-05-03 17:18:36 +00005319#endif
drh16eb5942016-11-03 13:01:38 +00005320
drh1a513372015-05-02 17:40:23 +00005321 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5322 static const struct {
5323 const char *zLimitName; /* Name of a limit */
5324 int limitCode; /* Integer code for that limit */
5325 } aLimit[] = {
5326 { "length", SQLITE_LIMIT_LENGTH },
5327 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5328 { "column", SQLITE_LIMIT_COLUMN },
5329 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5330 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5331 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5332 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5333 { "attached", SQLITE_LIMIT_ATTACHED },
5334 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5335 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5336 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5337 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5338 };
5339 int i, n2;
5340 open_db(p, 0);
5341 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005342 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005343 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005344 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5345 }
5346 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005347 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005348 rc = 1;
5349 goto meta_command_exit;
5350 }else{
5351 int iLimit = -1;
5352 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005353 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005354 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5355 if( iLimit<0 ){
5356 iLimit = i;
5357 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005358 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005359 rc = 1;
5360 goto meta_command_exit;
5361 }
5362 }
5363 }
5364 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005365 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005366 "enter \".limits\" with no arguments for a list.\n",
5367 azArg[1]);
5368 rc = 1;
5369 goto meta_command_exit;
5370 }
5371 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005372 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5373 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005374 }
5375 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5376 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5377 }
5378 }else
drhb0603412007-02-28 04:47:26 +00005379
dan3c7ebeb2016-12-16 17:28:56 +00005380 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005381 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005382 lintDotCommand(p, azArg, nArg);
5383 }else
5384
drh70df4fe2006-06-13 15:12:21 +00005385#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005386 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005387 const char *zFile, *zProc;
5388 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005389 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005390 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005391 rc = 1;
5392 goto meta_command_exit;
5393 }
drh1e397f82006-06-08 15:28:43 +00005394 zFile = azArg[1];
5395 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005396 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005397 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5398 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005399 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005400 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005401 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005402 }
5403 }else
drh70df4fe2006-06-13 15:12:21 +00005404#endif
drh1e397f82006-06-08 15:28:43 +00005405
drhc2ce0be2014-05-29 12:36:14 +00005406 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5407 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005408 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005409 rc = 1;
5410 }else{
5411 const char *zFile = azArg[1];
5412 output_file_close(p->pLog);
5413 p->pLog = output_file_open(zFile);
5414 }
drh127f9d72010-02-23 01:47:00 +00005415 }else
5416
drhc2ce0be2014-05-29 12:36:14 +00005417 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5418 const char *zMode = nArg>=2 ? azArg[1] : "";
5419 int n2 = (int)strlen(zMode);
5420 int c2 = zMode[0];
5421 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005422 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005423 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005424 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005425 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005426 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005427 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005428 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005429 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5430 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005431 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005432 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005433 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005434 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005435 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005436 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005437 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005438 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005439 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005440 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005441 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005442 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005443 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005444 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005445 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005446 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005447 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5448 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005449 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5450 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005451 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5452 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drhdaffd0e2001-04-11 14:28:42 +00005453 }else {
mistachkinaae280e2015-12-31 19:06:24 +00005454 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005455 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005456 rc = 1;
drh75897232000-05-29 14:26:00 +00005457 }
drh700c2522016-02-09 18:39:25 +00005458 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005459 }else
5460
drhc2ce0be2014-05-29 12:36:14 +00005461 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5462 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005463 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5464 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005465 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005466 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005467 rc = 1;
5468 }
5469 }else
5470
drh05782482013-10-24 15:20:20 +00005471 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005472 char *zNewFilename; /* Name of the database file to open */
5473 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005474 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005475 /* Close the existing database */
5476 session_close_all(p);
5477 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005478 p->db = 0;
dan21472212017-03-01 11:30:27 +00005479 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005480 sqlite3_free(p->zFreeOnClose);
5481 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005482 /* Check for command-line arguments */
5483 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5484 const char *z = azArg[iName];
5485 if( optionMatch(z,"new") ){
5486 newFlag = 1;
5487 }else if( z[0]=='-' ){
5488 utf8_printf(stderr, "unknown option: %s\n", z);
5489 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005490 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005491 }
drhcd0509e2016-09-16 00:26:08 +00005492 }
5493 /* If a filename is specified, try to open it first */
5494 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5495 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005496 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005497 p->zDbFilename = zNewFilename;
5498 open_db(p, 1);
5499 if( p->db==0 ){
5500 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5501 sqlite3_free(zNewFilename);
5502 }else{
5503 p->zFreeOnClose = zNewFilename;
5504 }
5505 }
5506 if( p->db==0 ){
5507 /* As a fall-back open a TEMP database */
5508 p->zDbFilename = 0;
5509 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005510 }
5511 }else
5512
drhc2ce0be2014-05-29 12:36:14 +00005513 if( c=='o'
5514 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5515 ){
5516 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5517 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005518 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005519 rc = 1;
5520 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005521 }
drhc2ce0be2014-05-29 12:36:14 +00005522 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5523 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005524 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005525 rc = 1;
5526 goto meta_command_exit;
5527 }
5528 p->outCount = 2;
5529 }else{
5530 p->outCount = 0;
5531 }
5532 output_reset(p);
5533 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005534#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005535 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005536 rc = 1;
5537 p->out = stdout;
5538#else
drhc2ce0be2014-05-29 12:36:14 +00005539 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005540 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005541 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005542 p->out = stdout;
5543 rc = 1;
5544 }else{
drhc2ce0be2014-05-29 12:36:14 +00005545 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005546 }
drh8cd5b252015-03-02 22:06:43 +00005547#endif
drh75897232000-05-29 14:26:00 +00005548 }else{
drhc2ce0be2014-05-29 12:36:14 +00005549 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005550 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005551 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005552 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005553 }
drh75897232000-05-29 14:26:00 +00005554 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005555 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005556 } else {
drhc2ce0be2014-05-29 12:36:14 +00005557 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005558 }
5559 }
5560 }else
5561
drh078b1fd2012-09-21 13:40:02 +00005562 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5563 int i;
5564 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005565 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005566 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005567 }
mistachkinaae280e2015-12-31 19:06:24 +00005568 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005569 }else
5570
drhc2ce0be2014-05-29 12:36:14 +00005571 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005572 if( nArg >= 2) {
5573 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5574 }
5575 if( nArg >= 3) {
5576 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5577 }
5578 }else
5579
drhc2ce0be2014-05-29 12:36:14 +00005580 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005581 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005582 }else
5583
drhc2ce0be2014-05-29 12:36:14 +00005584 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5585 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005586 if( nArg!=2 ){
5587 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005588 rc = 1;
5589 goto meta_command_exit;
5590 }
drh4e8142c2016-11-11 14:54:22 +00005591 alt = fopen(azArg[1], "rb");
5592 if( alt==0 ){
5593 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5594 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005595 }else{
drh4e8142c2016-11-11 14:54:22 +00005596 rc = process_input(p, alt);
5597 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005598 }
5599 }else
5600
drhc2ce0be2014-05-29 12:36:14 +00005601 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005602 const char *zSrcFile;
5603 const char *zDb;
5604 sqlite3 *pSrc;
5605 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005606 int nTimeout = 0;
5607
drh9ff849f2009-02-04 20:55:57 +00005608 if( nArg==2 ){
5609 zSrcFile = azArg[1];
5610 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005611 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005612 zSrcFile = azArg[2];
5613 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005614 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005615 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005616 rc = 1;
5617 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005618 }
5619 rc = sqlite3_open(zSrcFile, &pSrc);
5620 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005621 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005622 sqlite3_close(pSrc);
5623 return 1;
5624 }
drh05782482013-10-24 15:20:20 +00005625 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005626 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5627 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005628 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005629 sqlite3_close(pSrc);
5630 return 1;
5631 }
drhdc2c4912009-02-04 22:46:47 +00005632 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5633 || rc==SQLITE_BUSY ){
5634 if( rc==SQLITE_BUSY ){
5635 if( nTimeout++ >= 3 ) break;
5636 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005637 }
5638 }
5639 sqlite3_backup_finish(pBackup);
5640 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005641 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005642 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005643 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005644 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005645 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005646 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005647 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005648 }
5649 sqlite3_close(pSrc);
5650 }else
5651
dan8d1edb92014-11-05 09:07:28 +00005652
5653 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5654 if( nArg==2 ){
5655 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005656#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005657 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005658#endif
dan8d1edb92014-11-05 09:07:28 +00005659 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005660 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005661 rc = 1;
5662 }
5663 }else
5664
drhc2ce0be2014-05-29 12:36:14 +00005665 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005666 ShellState data;
drh75897232000-05-29 14:26:00 +00005667 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00005668 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005669 memcpy(&data, p, sizeof(data));
5670 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005671 data.cMode = data.mode = MODE_Semi;
drh4926fec2016-04-13 15:33:42 +00005672 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5673 data.cMode = data.mode = MODE_Pretty;
5674 nArg--;
5675 if( nArg==2 ) azArg[1] = azArg[2];
5676 }
5677 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005678 int i;
drhf0693c82011-10-11 20:41:54 +00005679 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005680 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005681 char *new_argv[2], *new_colv[2];
5682 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5683 " type text,\n"
5684 " name text,\n"
5685 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005686 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005687 " sql text\n"
5688 ")";
5689 new_argv[1] = 0;
5690 new_colv[0] = "sql";
5691 new_colv[1] = 0;
5692 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005693 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005694 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005695 char *new_argv[2], *new_colv[2];
5696 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5697 " type text,\n"
5698 " name text,\n"
5699 " tbl_name text,\n"
5700 " rootpage integer,\n"
5701 " sql text\n"
5702 ")";
5703 new_argv[1] = 0;
5704 new_colv[0] = "sql";
5705 new_colv[1] = 0;
5706 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005707 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005708 }else{
drhe611f142017-03-08 11:44:00 +00005709 char *zSql;
5710 zSql = sqlite3_mprintf(
drhe0bc4042002-06-25 01:09:11 +00005711 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005712 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005713 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005714 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drhe611f142017-03-08 11:44:00 +00005715 "WHERE lower(tbl_name) LIKE %Q"
drh6ac7a582011-11-04 00:35:56 +00005716 " AND type!='meta' AND sql NOTNULL "
drhe611f142017-03-08 11:44:00 +00005717 "ORDER BY rowid", azArg[1]);
5718 rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
5719 sqlite3_free(zSql);
drha18c5682000-10-08 22:20:57 +00005720 }
drhc2ce0be2014-05-29 12:36:14 +00005721 }else if( nArg==1 ){
shane9bd1b442009-10-23 01:27:39 +00005722 rc = sqlite3_exec(p->db,
drhe0bc4042002-06-25 01:09:11 +00005723 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005724 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005725 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005726 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005727 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drh1ba00292013-05-06 21:01:06 +00005728 "ORDER BY rowid",
drha18c5682000-10-08 22:20:57 +00005729 callback, &data, &zErrMsg
5730 );
drhc2ce0be2014-05-29 12:36:14 +00005731 }else{
drh4926fec2016-04-13 15:33:42 +00005732 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005733 rc = 1;
5734 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005735 }
drh75897232000-05-29 14:26:00 +00005736 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005737 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005738 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005739 rc = 1;
5740 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005741 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005742 rc = 1;
5743 }else{
5744 rc = 0;
drh75897232000-05-29 14:26:00 +00005745 }
5746 }else
5747
drhabd4c722014-09-20 18:18:33 +00005748#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5749 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005750 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005751 }else
5752#endif
5753
drhe6229612014-08-18 15:08:26 +00005754#if defined(SQLITE_ENABLE_SESSION)
5755 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5756 OpenSession *pSession = &p->aSession[0];
5757 char **azCmd = &azArg[1];
5758 int iSes = 0;
5759 int nCmd = nArg - 1;
5760 int i;
5761 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005762 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005763 if( nArg>=3 ){
5764 for(iSes=0; iSes<p->nSession; iSes++){
5765 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5766 }
5767 if( iSes<p->nSession ){
5768 pSession = &p->aSession[iSes];
5769 azCmd++;
5770 nCmd--;
5771 }else{
5772 pSession = &p->aSession[0];
5773 iSes = 0;
5774 }
5775 }
5776
drh3a67b042014-08-18 17:56:31 +00005777 /* .session attach TABLE
5778 ** Invoke the sqlite3session_attach() interface to attach a particular
5779 ** table so that it is never filtered.
5780 */
5781 if( strcmp(azCmd[0],"attach")==0 ){
5782 if( nCmd!=2 ) goto session_syntax_error;
5783 if( pSession->p==0 ){
5784 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005785 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005786 }else{
5787 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5788 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005789 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005790 rc = 0;
5791 }
5792 }
5793 }else
5794
5795 /* .session changeset FILE
5796 ** .session patchset FILE
5797 ** Write a changeset or patchset into a file. The file is overwritten.
5798 */
5799 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5800 FILE *out = 0;
5801 if( nCmd!=2 ) goto session_syntax_error;
5802 if( pSession->p==0 ) goto session_not_open;
5803 out = fopen(azCmd[1], "wb");
5804 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005805 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005806 }else{
5807 int szChng;
5808 void *pChng;
5809 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005810 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005811 }else{
drh2967e0c2014-08-19 00:26:17 +00005812 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5813 }
5814 if( rc ){
5815 printf("Error: error code %d\n", rc);
5816 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005817 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005818 if( pChng
drh3a67b042014-08-18 17:56:31 +00005819 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005820 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005821 szChng);
5822 }
5823 sqlite3_free(pChng);
5824 fclose(out);
5825 }
5826 }else
5827
drhe6229612014-08-18 15:08:26 +00005828 /* .session close
5829 ** Close the identified session
5830 */
5831 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005832 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005833 if( p->nSession ){
5834 session_close(pSession);
5835 p->aSession[iSes] = p->aSession[--p->nSession];
5836 }
5837 }else
5838
drh03168ca2014-08-18 20:01:31 +00005839 /* .session enable ?BOOLEAN?
5840 ** Query or set the enable flag
5841 */
5842 if( strcmp(azCmd[0], "enable")==0 ){
5843 int ii;
5844 if( nCmd>2 ) goto session_syntax_error;
5845 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5846 if( p->nSession ){
5847 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005848 utf8_printf(p->out, "session %s enable flag = %d\n",
5849 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005850 }
5851 }else
5852
5853 /* .session filter GLOB ....
5854 ** Set a list of GLOB patterns of table names to be excluded.
5855 */
5856 if( strcmp(azCmd[0], "filter")==0 ){
5857 int ii, nByte;
5858 if( nCmd<2 ) goto session_syntax_error;
5859 if( p->nSession ){
5860 for(ii=0; ii<pSession->nFilter; ii++){
5861 sqlite3_free(pSession->azFilter[ii]);
5862 }
5863 sqlite3_free(pSession->azFilter);
5864 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5865 pSession->azFilter = sqlite3_malloc( nByte );
5866 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005867 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00005868 exit(1);
5869 }
5870 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005871 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00005872 }
5873 pSession->nFilter = ii-1;
5874 }
5875 }else
5876
5877 /* .session indirect ?BOOLEAN?
5878 ** Query or set the indirect flag
5879 */
5880 if( strcmp(azCmd[0], "indirect")==0 ){
5881 int ii;
5882 if( nCmd>2 ) goto session_syntax_error;
5883 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5884 if( p->nSession ){
5885 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005886 utf8_printf(p->out, "session %s indirect flag = %d\n",
5887 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005888 }
5889 }else
5890
5891 /* .session isempty
5892 ** Determine if the session is empty
5893 */
5894 if( strcmp(azCmd[0], "isempty")==0 ){
5895 int ii;
5896 if( nCmd!=1 ) goto session_syntax_error;
5897 if( p->nSession ){
5898 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00005899 utf8_printf(p->out, "session %s isempty flag = %d\n",
5900 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005901 }
5902 }else
5903
drhe6229612014-08-18 15:08:26 +00005904 /* .session list
5905 ** List all currently open sessions
5906 */
5907 if( strcmp(azCmd[0],"list")==0 ){
5908 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00005909 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00005910 }
5911 }else
5912
5913 /* .session open DB NAME
5914 ** Open a new session called NAME on the attached database DB.
5915 ** DB is normally "main".
5916 */
5917 if( strcmp(azCmd[0],"open")==0 ){
5918 char *zName;
5919 if( nCmd!=3 ) goto session_syntax_error;
5920 zName = azCmd[2];
5921 if( zName[0]==0 ) goto session_syntax_error;
5922 for(i=0; i<p->nSession; i++){
5923 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005924 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00005925 goto meta_command_exit;
5926 }
5927 }
5928 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00005929 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00005930 goto meta_command_exit;
5931 }
5932 pSession = &p->aSession[p->nSession];
5933 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5934 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005935 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005936 rc = 0;
drhe6229612014-08-18 15:08:26 +00005937 goto meta_command_exit;
5938 }
drh03168ca2014-08-18 20:01:31 +00005939 pSession->nFilter = 0;
5940 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00005941 p->nSession++;
5942 pSession->zName = sqlite3_mprintf("%s", zName);
5943 }else
5944 /* If no command name matches, show a syntax error */
5945 session_syntax_error:
5946 session_help(p);
5947 }else
5948#endif
5949
drh340f5822013-06-27 13:01:21 +00005950#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00005951 /* Undocumented commands for internal testing. Subject to change
5952 ** without notice. */
5953 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5954 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5955 int i, v;
5956 for(i=1; i<nArg; i++){
5957 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00005958 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00005959 }
5960 }
5961 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5962 int i; sqlite3_int64 v;
5963 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00005964 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00005965 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00005966 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00005967 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00005968 }
5969 }
5970 }else
drh340f5822013-06-27 13:01:21 +00005971#endif
drh348d19c2013-06-03 12:47:43 +00005972
drhfb546af2017-03-09 22:00:33 +00005973 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5974 int bIsInit = 0; /* True to initialize the SELFTEST table */
5975 int bVerbose = 0; /* Verbose output */
5976 int bSelftestExists; /* True if SELFTEST already exists */
5977 char **azTest = 0; /* Content of the SELFTEST table */
5978 int nRow = 0; /* Number of rows in the SELFTEST table */
5979 int nCol = 4; /* Number of columns in the SELFTEST table */
5980 int i; /* Loop counter */
5981 int nTest = 0; /* Number of tests runs */
5982 int nErr = 0; /* Number of errors seen */
5983 ShellText str; /* Answer for a query */
5984 static char *azDefaultTest[] = {
5985 0, 0, 0, 0,
5986 "0", "memo", "Missing SELFTEST table - default checks only", "",
5987 "1", "run", "PRAGMA integrity_check", "ok"
5988 };
5989 static const int nDefaultRow = 2;
5990
5991 open_db(p,0);
5992 for(i=1; i<nArg; i++){
5993 const char *z = azArg[i];
5994 if( z[0]=='-' && z[1]=='-' ) z++;
5995 if( strcmp(z,"-init")==0 ){
5996 bIsInit = 1;
5997 }else
5998 if( strcmp(z,"-v")==0 ){
5999 bVerbose++;
6000 }else
6001 {
6002 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6003 azArg[i], azArg[0]);
6004 raw_printf(stderr, "Should be one of: --init -v\n");
6005 rc = 1;
6006 goto meta_command_exit;
6007 }
6008 }
6009 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6010 != SQLITE_OK ){
6011 bSelftestExists = 0;
6012 }else{
6013 bSelftestExists = 1;
6014 }
6015 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006016 createSelftestTable(p);
6017 bSelftestExists = 1;
6018 }
6019 if( bSelftestExists ){
6020 rc = sqlite3_get_table(p->db,
6021 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6022 &azTest, &nRow, &nCol, 0);
6023 if( rc ){
6024 raw_printf(stderr, "Error querying the selftest table\n");
6025 rc = 1;
6026 sqlite3_free_table(azTest);
6027 goto meta_command_exit;
6028 }else if( nRow==0 ){
6029 sqlite3_free_table(azTest);
6030 azTest = azDefaultTest;
6031 nRow = nDefaultRow;
6032 }
6033 }else{
6034 azTest = azDefaultTest;
6035 nRow = nDefaultRow;
6036 }
6037 initText(&str);
6038 appendText(&str, "x", 0);
6039 for(i=1; i<=nRow; i++){
6040 int tno = atoi(azTest[i*nCol]);
6041 const char *zOp = azTest[i*nCol+1];
6042 const char *zSql = azTest[i*nCol+2];
6043 const char *zAns = azTest[i*nCol+3];
6044
6045 if( bVerbose>0 ){
6046 char *zQuote = sqlite3_mprintf("%q", zSql);
6047 printf("%d: %s %s\n", tno, zOp, zSql);
6048 sqlite3_free(zQuote);
6049 }
6050 if( strcmp(zOp,"memo")==0 ){
6051 utf8_printf(p->out, "%s\n", zSql);
6052 }else
6053 if( strcmp(zOp,"run")==0 ){
6054 char *zErrMsg = 0;
6055 str.n = 0;
6056 str.z[0] = 0;
6057 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6058 nTest++;
6059 if( bVerbose ){
6060 utf8_printf(p->out, "Result: %s\n", str.z);
6061 }
6062 if( rc || zErrMsg ){
6063 nErr++;
6064 rc = 1;
6065 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6066 sqlite3_free(zErrMsg);
6067 }else if( strcmp(zAns,str.z)!=0 ){
6068 nErr++;
6069 rc = 1;
6070 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6071 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6072 }
6073 }else
6074 {
6075 utf8_printf(stderr,
6076 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6077 rc = 1;
6078 break;
6079 }
6080 }
6081 freeText(&str);
6082 if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
6083 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6084 }else
6085
drhc2ce0be2014-05-29 12:36:14 +00006086 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006087 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006088 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006089 rc = 1;
6090 }
drh6976c212014-07-24 12:09:47 +00006091 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006092 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006093 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006094 }
6095 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006096 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6097 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006098 }
drh75897232000-05-29 14:26:00 +00006099 }else
6100
drh1554bc82017-03-08 16:10:34 +00006101 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6102 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6103 int i; /* Loop counter */
6104 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006105 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006106 int iSize = 224; /* Hash algorithm to use */
6107 int bDebug = 0; /* Only show the query that would have run */
6108 sqlite3_stmt *pStmt; /* For querying tables names */
6109 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006110 char *zSep; /* Separator */
6111 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006112 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006113 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006114 for(i=1; i<nArg; i++){
6115 const char *z = azArg[i];
6116 if( z[0]=='-' ){
6117 z++;
6118 if( z[0]=='-' ) z++;
6119 if( strcmp(z,"schema")==0 ){
6120 bSchema = 1;
6121 }else
6122 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6123 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6124 ){
6125 iSize = atoi(&z[5]);
6126 }else
6127 if( strcmp(z,"debug")==0 ){
6128 bDebug = 1;
6129 }else
6130 {
6131 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006132 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006133 raw_printf(stderr, "Should be one of: --schema"
6134 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6135 rc = 1;
6136 goto meta_command_exit;
6137 }
6138 }else if( zLike ){
6139 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6140 rc = 1;
6141 goto meta_command_exit;
6142 }else{
6143 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006144 bSeparate = 1;
6145 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006146 }
6147 }
6148 if( bSchema ){
6149 zSql = "SELECT lower(name) FROM sqlite_master"
6150 " WHERE type='table' AND coalesce(rootpage,0)>1"
6151 " UNION ALL SELECT 'sqlite_master'"
6152 " ORDER BY 1 collate nocase";
6153 }else{
6154 zSql = "SELECT lower(name) FROM sqlite_master"
6155 " WHERE type='table' AND coalesce(rootpage,0)>1"
6156 " AND name NOT LIKE 'sqlite_%'"
6157 " ORDER BY 1 collate nocase";
6158 }
6159 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6160 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006161 initText(&sSql);
6162 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6163 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006164 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6165 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6166 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6167 if( strncmp(zTab, "sqlite_",7)!=0 ){
6168 appendText(&sQuery,"SELECT * FROM ", 0);
6169 appendText(&sQuery,zTab,'"');
6170 appendText(&sQuery," NOT INDEXED;", 0);
6171 }else if( strcmp(zTab, "sqlite_master")==0 ){
6172 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6173 " ORDER BY name;", 0);
6174 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6175 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6176 " ORDER BY name;", 0);
6177 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6178 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6179 " ORDER BY tbl,idx;", 0);
6180 }else if( strcmp(zTab, "sqlite_stat3")==0
6181 || strcmp(zTab, "sqlite_stat4")==0 ){
6182 appendText(&sQuery, "SELECT * FROM ", 0);
6183 appendText(&sQuery, zTab, 0);
6184 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6185 }
drh3ee83ef2017-03-08 17:56:54 +00006186 appendText(&sSql, zSep, 0);
6187 appendText(&sSql, sQuery.z, '\'');
6188 sQuery.n = 0;
6189 appendText(&sSql, ",", 0);
6190 appendText(&sSql, zTab, '\'');
6191 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006192 }
6193 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006194 if( bSeparate ){
6195 zSql = sqlite3_mprintf(
6196 "%s))"
6197 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6198 " FROM [sha3sum$query]",
6199 sSql.z, iSize);
6200 }else{
6201 zSql = sqlite3_mprintf(
6202 "%s))"
6203 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6204 " FROM [sha3sum$query]",
6205 sSql.z, iSize);
6206 }
drh1554bc82017-03-08 16:10:34 +00006207 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006208 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006209 if( bDebug ){
6210 utf8_printf(p->out, "%s\n", zSql);
6211 }else{
6212 shell_exec(p->db, zSql, shell_callback, p, 0);
6213 }
6214 sqlite3_free(zSql);
6215 }else
6216
drh62cdde52014-05-28 20:22:28 +00006217 if( c=='s'
6218 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006219 ){
6220 char *zCmd;
drh54027102014-08-06 14:36:53 +00006221 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006222 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006223 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006224 rc = 1;
6225 goto meta_command_exit;
6226 }
drhdcb3e3d2014-05-29 03:17:29 +00006227 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006228 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006229 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6230 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006231 }
drh54027102014-08-06 14:36:53 +00006232 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006233 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006234 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006235 }else
6236
drhc2ce0be2014-05-29 12:36:14 +00006237 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006238 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006239 int i;
drhc2ce0be2014-05-29 12:36:14 +00006240 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006241 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006242 rc = 1;
6243 goto meta_command_exit;
6244 }
drhe6e1d122017-03-09 13:50:49 +00006245 utf8_printf(p->out, "%12.12s: %s\n","echo",
6246 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006247 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006248 utf8_printf(p->out, "%12.12s: %s\n","explain",
6249 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006250 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006251 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6252 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006253 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006254 raw_printf(p->out, "\n");
6255 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006256 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006257 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006258 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006259 raw_printf(p->out, "\n");
6260 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006261 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006262 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006263 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006264 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006265 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006266 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006267 }
mistachkinaae280e2015-12-31 19:06:24 +00006268 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006269 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6270 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006271 }else
6272
drhc2ce0be2014-05-29 12:36:14 +00006273 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6274 if( nArg==2 ){
6275 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006276 }else if( nArg==1 ){
6277 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006278 }else{
drh34784902016-02-27 17:12:36 +00006279 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006280 rc = 1;
6281 }
shaneh642d8b82010-07-28 16:05:34 +00006282 }else
6283
drh6a5a4202016-12-24 21:32:40 +00006284 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6285 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6286 || strncmp(azArg[0], "indexes", n)==0) )
6287 ){
drh98781232012-04-23 12:38:05 +00006288 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006289 char **azResult;
drh98781232012-04-23 12:38:05 +00006290 int nRow, nAlloc;
6291 char *zSql = 0;
6292 int ii;
drh05782482013-10-24 15:20:20 +00006293 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006294 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006295 if( rc ) return shellDatabaseError(p->db);
6296
6297 /* Create an SQL statement to query for the list of tables in the
6298 ** main and all attached databases where the table name matches the
6299 ** LIKE pattern bound to variable "?1". */
drh6a5a4202016-12-24 21:32:40 +00006300 if( c=='t' ){
6301 zSql = sqlite3_mprintf(
6302 "SELECT name FROM sqlite_master"
6303 " WHERE type IN ('table','view')"
6304 " AND name NOT LIKE 'sqlite_%%'"
6305 " AND name LIKE ?1");
6306 }else if( nArg>2 ){
6307 /* It is an historical accident that the .indexes command shows an error
6308 ** when called with the wrong number of arguments whereas the .tables
6309 ** command does not. */
6310 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6311 rc = 1;
6312 goto meta_command_exit;
6313 }else{
6314 zSql = sqlite3_mprintf(
6315 "SELECT name FROM sqlite_master"
6316 " WHERE type='index'"
6317 " AND tbl_name LIKE ?1");
6318 }
drha4b81d22016-12-24 18:04:28 +00006319 for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006320 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drha4b81d22016-12-24 18:04:28 +00006321 if( zDbName==0 || ii==0 ) continue;
drh6a5a4202016-12-24 21:32:40 +00006322 if( c=='t' ){
drh98781232012-04-23 12:38:05 +00006323 zSql = sqlite3_mprintf(
6324 "%z UNION ALL "
6325 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6326 " WHERE type IN ('table','view')"
6327 " AND name NOT LIKE 'sqlite_%%'"
6328 " AND name LIKE ?1", zSql, zDbName, zDbName);
drh6a5a4202016-12-24 21:32:40 +00006329 }else{
6330 zSql = sqlite3_mprintf(
6331 "%z UNION ALL "
6332 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6333 " WHERE type='index'"
6334 " AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
drh98781232012-04-23 12:38:05 +00006335 }
drha50da102000-08-08 20:19:09 +00006336 }
dand95bb392015-09-30 11:19:05 +00006337 rc = sqlite3_finalize(pStmt);
6338 if( zSql && rc==SQLITE_OK ){
6339 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6340 if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6341 }
drh98781232012-04-23 12:38:05 +00006342 sqlite3_free(zSql);
dand95bb392015-09-30 11:19:05 +00006343 if( !zSql ) return shellNomemError();
6344 if( rc ) return shellDatabaseError(p->db);
6345
6346 /* Run the SQL statement prepared by the above block. Store the results
6347 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006348 nRow = nAlloc = 0;
6349 azResult = 0;
6350 if( nArg>1 ){
6351 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006352 }else{
drh98781232012-04-23 12:38:05 +00006353 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6354 }
6355 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6356 if( nRow>=nAlloc ){
6357 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006358 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006359 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006360 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006361 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006362 break;
6363 }
mistachkin8e189222015-04-19 21:43:16 +00006364 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006365 azResult = azNew;
6366 }
6367 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006368 if( 0==azResult[nRow] ){
6369 rc = shellNomemError();
6370 break;
6371 }
6372 nRow++;
drh98781232012-04-23 12:38:05 +00006373 }
dand95bb392015-09-30 11:19:05 +00006374 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6375 rc = shellDatabaseError(p->db);
6376 }
6377
6378 /* Pretty-print the contents of array azResult[] to the output */
6379 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006380 int len, maxlen = 0;
6381 int i, j;
6382 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006383 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006384 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006385 if( len>maxlen ) maxlen = len;
6386 }
6387 nPrintCol = 80/(maxlen+2);
6388 if( nPrintCol<1 ) nPrintCol = 1;
6389 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6390 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006391 for(j=i; j<nRow; j+=nPrintRow){
6392 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006393 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6394 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006395 }
mistachkinaae280e2015-12-31 19:06:24 +00006396 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006397 }
6398 }
dand95bb392015-09-30 11:19:05 +00006399
drh98781232012-04-23 12:38:05 +00006400 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6401 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006402 }else
6403
drh2db82112016-09-15 21:35:24 +00006404 /* Begin redirecting output to the file "testcase-out.txt" */
6405 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6406 output_reset(p);
6407 p->out = output_file_open("testcase-out.txt");
6408 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006409 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006410 }
drh760c8162016-09-16 02:52:22 +00006411 if( nArg>=2 ){
6412 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6413 }else{
6414 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6415 }
drh2db82112016-09-15 21:35:24 +00006416 }else
drh2db82112016-09-15 21:35:24 +00006417
drhd12602a2016-12-07 15:49:02 +00006418#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006419 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006420 static const struct {
6421 const char *zCtrlName; /* Name of a test-control option */
6422 int ctrlCode; /* Integer code for that option */
6423 } aCtrl[] = {
6424 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6425 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6426 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6427 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6428 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6429 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6430 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6431 { "assert", SQLITE_TESTCTRL_ASSERT },
6432 { "always", SQLITE_TESTCTRL_ALWAYS },
6433 { "reserve", SQLITE_TESTCTRL_RESERVE },
6434 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6435 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006436 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006437 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006438 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006439 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006440 };
shaneh96887e12011-02-10 21:08:58 +00006441 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006442 int rc2 = 0;
6443 int i, n2;
drh05782482013-10-24 15:20:20 +00006444 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006445
drhd416fe72011-03-17 16:45:50 +00006446 /* convert testctrl text option to value. allow any unique prefix
6447 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006448 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006449 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006450 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006451 if( testctrl<0 ){
6452 testctrl = aCtrl[i].ctrlCode;
6453 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006454 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006455 testctrl = -1;
6456 break;
6457 }
6458 }
6459 }
drh348d19c2013-06-03 12:47:43 +00006460 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006461 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006462 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006463 }else{
6464 switch(testctrl){
6465
6466 /* sqlite3_test_control(int, db, int) */
6467 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006468 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006469 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006470 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006471 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006472 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006473 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006474 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006475 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006476 }
6477 break;
6478
6479 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006480 case SQLITE_TESTCTRL_PRNG_SAVE:
6481 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006482 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006483 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006484 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006485 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006486 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006487 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006488 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6489 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006490 }
6491 break;
6492
6493 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006494 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006495 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006496 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006497 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006498 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006499 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006500 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006501 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006502 }
6503 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006504
shaneh96887e12011-02-10 21:08:58 +00006505 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006506 case SQLITE_TESTCTRL_ASSERT:
6507 case SQLITE_TESTCTRL_ALWAYS:
6508 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006509 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006510 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006511 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006512 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006513 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006514 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006515 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006516 }
6517 break;
6518
6519 /* sqlite3_test_control(int, char *) */
6520#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006521 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006522 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006523 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006524 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006525 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006526 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006527 utf8_printf(stderr,
6528 "Error: testctrl %s takes a single char * option\n",
6529 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006530 }
6531 break;
6532#endif
6533
drh1ffede82015-01-30 20:59:27 +00006534 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006535 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006536 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006537 azArg[2],
drh8964b342015-01-29 17:54:52 +00006538 integerValue(azArg[3]),
6539 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006540 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006541 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006542 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006543 }
6544 break;
6545
mistachkin1fe36bb2016-04-04 02:16:44 +00006546 case SQLITE_TESTCTRL_BITVEC_TEST:
6547 case SQLITE_TESTCTRL_FAULT_INSTALL:
6548 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6549 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006550 default:
mistachkinaae280e2015-12-31 19:06:24 +00006551 utf8_printf(stderr,
6552 "Error: CLI support for testctrl %s not implemented\n",
6553 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006554 break;
6555 }
6556 }
6557 }else
drhf1969722017-02-17 23:52:00 +00006558#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006559
drhc2ce0be2014-05-29 12:36:14 +00006560 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006561 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006562 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006563 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006564
drhc2ce0be2014-05-29 12:36:14 +00006565 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6566 if( nArg==2 ){
6567 enableTimer = booleanValue(azArg[1]);
6568 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006569 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006570 enableTimer = 0;
6571 }
6572 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006573 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006574 rc = 1;
6575 }
shanehe2aa9d72009-11-06 17:20:17 +00006576 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006577
drhc2ce0be2014-05-29 12:36:14 +00006578 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006579 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006580 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006581 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006582 rc = 1;
6583 goto meta_command_exit;
6584 }
drh657b4a82015-03-19 13:30:41 +00006585 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006586 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006587#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006588 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006589 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006590 }else{
drh4b363a52016-07-23 20:27:41 +00006591 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006592 }
6593#endif
6594 }else
6595
drhf442e332014-09-10 19:01:14 +00006596#if SQLITE_USER_AUTHENTICATION
6597 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6598 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006599 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006600 rc = 1;
6601 goto meta_command_exit;
6602 }
drh7883ecf2014-09-11 16:19:31 +00006603 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006604 if( strcmp(azArg[1],"login")==0 ){
6605 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006606 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006607 rc = 1;
6608 goto meta_command_exit;
6609 }
drhd39c40f2014-09-11 00:27:53 +00006610 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6611 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006612 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006613 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006614 rc = 1;
6615 }
6616 }else if( strcmp(azArg[1],"add")==0 ){
6617 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006618 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006619 rc = 1;
6620 goto meta_command_exit;
6621 }
drhd39c40f2014-09-11 00:27:53 +00006622 rc = sqlite3_user_add(p->db, azArg[2],
6623 azArg[3], (int)strlen(azArg[3]),
6624 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006625 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006626 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006627 rc = 1;
6628 }
6629 }else if( strcmp(azArg[1],"edit")==0 ){
6630 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006631 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006632 rc = 1;
6633 goto meta_command_exit;
6634 }
drhd39c40f2014-09-11 00:27:53 +00006635 rc = sqlite3_user_change(p->db, azArg[2],
6636 azArg[3], (int)strlen(azArg[3]),
6637 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006638 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006639 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006640 rc = 1;
6641 }
6642 }else if( strcmp(azArg[1],"delete")==0 ){
6643 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006644 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006645 rc = 1;
6646 goto meta_command_exit;
6647 }
6648 rc = sqlite3_user_delete(p->db, azArg[2]);
6649 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006650 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006651 rc = 1;
6652 }
6653 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006654 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006655 rc = 1;
6656 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006657 }
drhf442e332014-09-10 19:01:14 +00006658 }else
6659#endif /* SQLITE_USER_AUTHENTICATION */
6660
drh9fd301b2011-06-03 13:28:22 +00006661 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006662 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006663 sqlite3_libversion(), sqlite3_sourceid());
6664 }else
6665
drh790f2872015-11-28 18:06:36 +00006666 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6667 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006668 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006669 if( p->db ){
6670 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6671 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006672 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6673 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6674 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6675 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006676 }
6677 }
6678 }else
6679
drhb19e7352016-01-12 19:37:20 +00006680 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6681 sqlite3_vfs *pVfs;
6682 sqlite3_vfs *pCurrent = 0;
6683 if( p->db ){
6684 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6685 }
6686 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6687 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6688 pVfs==pCurrent ? " <--- CURRENT" : "");
6689 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6690 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6691 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6692 if( pVfs->pNext ){
6693 raw_printf(p->out, "-----------------------------------\n");
6694 }
6695 }
6696 }else
6697
drhde60fc22011-12-14 17:53:36 +00006698 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6699 const char *zDbName = nArg==2 ? azArg[1] : "main";
6700 char *zVfsName = 0;
6701 if( p->db ){
6702 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6703 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006704 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006705 sqlite3_free(zVfsName);
6706 }
6707 }
6708 }else
6709
drhcef4fc82012-09-21 22:50:45 +00006710#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6711 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006712 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006713 }else
6714#endif
6715
drhc2ce0be2014-05-29 12:36:14 +00006716 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006717 int j;
drh43617e92006-03-06 20:55:46 +00006718 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006719 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006720 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006721 }
6722 }else
6723
6724 {
mistachkinaae280e2015-12-31 19:06:24 +00006725 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006726 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006727 rc = 1;
drh75897232000-05-29 14:26:00 +00006728 }
drh67505e72002-04-19 12:34:06 +00006729
drhc2ce0be2014-05-29 12:36:14 +00006730meta_command_exit:
6731 if( p->outCount ){
6732 p->outCount--;
6733 if( p->outCount==0 ) output_reset(p);
6734 }
drh67505e72002-04-19 12:34:06 +00006735 return rc;
drh75897232000-05-29 14:26:00 +00006736}
6737
drh67505e72002-04-19 12:34:06 +00006738/*
drh91a66392007-09-07 01:12:32 +00006739** Return TRUE if a semicolon occurs anywhere in the first N characters
6740** of string z[].
drh324ccef2003-02-05 14:06:20 +00006741*/
drh9f099fd2013-08-06 14:01:46 +00006742static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006743 int i;
6744 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6745 return 0;
drh324ccef2003-02-05 14:06:20 +00006746}
6747
6748/*
drh70c7a4b2003-04-26 03:03:06 +00006749** Test to see if a line consists entirely of whitespace.
6750*/
6751static int _all_whitespace(const char *z){
6752 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006753 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006754 if( *z=='/' && z[1]=='*' ){
6755 z += 2;
6756 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6757 if( *z==0 ) return 0;
6758 z++;
6759 continue;
6760 }
6761 if( *z=='-' && z[1]=='-' ){
6762 z += 2;
6763 while( *z && *z!='\n' ){ z++; }
6764 if( *z==0 ) return 1;
6765 continue;
6766 }
6767 return 0;
6768 }
6769 return 1;
6770}
6771
6772/*
drha9b17162003-04-29 18:01:28 +00006773** Return TRUE if the line typed in is an SQL command terminator other
6774** than a semi-colon. The SQL Server style "go" command is understood
6775** as is the Oracle "/".
6776*/
drh9f099fd2013-08-06 14:01:46 +00006777static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006778 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006779 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6780 return 1; /* Oracle */
6781 }
drhf0693c82011-10-11 20:41:54 +00006782 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006783 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006784 return 1; /* SQL Server */
6785 }
6786 return 0;
6787}
6788
6789/*
drh233a5312008-12-18 22:25:13 +00006790** Return true if zSql is a complete SQL statement. Return false if it
6791** ends in the middle of a string literal or C-style comment.
6792*/
drh9f099fd2013-08-06 14:01:46 +00006793static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006794 int rc;
6795 if( zSql==0 ) return 1;
6796 zSql[nSql] = ';';
6797 zSql[nSql+1] = 0;
6798 rc = sqlite3_complete(zSql);
6799 zSql[nSql] = 0;
6800 return rc;
6801}
6802
6803/*
drh4e8142c2016-11-11 14:54:22 +00006804** Run a single line of SQL
6805*/
6806static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6807 int rc;
6808 char *zErrMsg = 0;
6809
6810 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006811 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006812 BEGIN_TIMER;
6813 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6814 END_TIMER;
6815 if( rc || zErrMsg ){
6816 char zPrefix[100];
6817 if( in!=0 || !stdin_is_interactive ){
6818 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6819 "Error: near line %d:", startline);
6820 }else{
6821 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6822 }
6823 if( zErrMsg!=0 ){
6824 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6825 sqlite3_free(zErrMsg);
6826 zErrMsg = 0;
6827 }else{
6828 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6829 }
6830 return 1;
drhe6e1d122017-03-09 13:50:49 +00006831 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006832 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6833 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6834 }
6835 return 0;
6836}
6837
6838
6839/*
drh67505e72002-04-19 12:34:06 +00006840** Read input from *in and process it. If *in==0 then input
6841** is interactive - the user is typing it it. Otherwise, input
6842** is coming from a file or device. A prompt is issued and history
6843** is saved only if input is interactive. An interrupt signal will
6844** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006845**
6846** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006847*/
drhdcd87a92014-08-18 13:45:42 +00006848static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006849 char *zLine = 0; /* A single input line */
6850 char *zSql = 0; /* Accumulated SQL text */
6851 int nLine; /* Length of current line */
6852 int nSql = 0; /* Bytes of zSql[] used */
6853 int nAlloc = 0; /* Allocated zSql[] space */
6854 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006855 int rc; /* Error code */
6856 int errCnt = 0; /* Number of errors seen */
6857 int lineno = 0; /* Current line number */
6858 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006859
6860 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6861 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006862 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006863 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006864 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006865 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006866 break;
drhc49f44e2006-10-26 18:15:42 +00006867 }
drh67505e72002-04-19 12:34:06 +00006868 if( seenInterrupt ){
6869 if( in!=0 ) break;
6870 seenInterrupt = 0;
6871 }
drhc28490c2006-10-26 14:25:58 +00006872 lineno++;
drh849a9d92013-12-21 15:46:06 +00006873 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006874 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006875 continue;
6876 }
drh2af0b2d2002-02-21 02:25:02 +00006877 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006878 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006879 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006880 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006881 break;
6882 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006883 errCnt++;
6884 }
drhdaffd0e2001-04-11 14:28:42 +00006885 continue;
6886 }
drh9f099fd2013-08-06 14:01:46 +00006887 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00006888 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00006889 }
drh9f099fd2013-08-06 14:01:46 +00006890 nLine = strlen30(zLine);
6891 if( nSql+nLine+2>=nAlloc ){
6892 nAlloc = nSql+nLine+100;
6893 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00006894 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006895 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00006896 exit(1);
6897 }
drhdaffd0e2001-04-11 14:28:42 +00006898 }
drh9f099fd2013-08-06 14:01:46 +00006899 nSqlPrior = nSql;
6900 if( nSql==0 ){
6901 int i;
6902 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00006903 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00006904 memcpy(zSql, zLine+i, nLine+1-i);
6905 startline = lineno;
6906 nSql = nLine-i;
6907 }else{
6908 zSql[nSql++] = '\n';
6909 memcpy(zSql+nSql, zLine, nLine+1);
6910 nSql += nLine;
6911 }
6912 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00006913 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00006914 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006915 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00006916 if( p->outCount ){
6917 output_reset(p);
6918 p->outCount = 0;
6919 }
drh9f099fd2013-08-06 14:01:46 +00006920 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00006921 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00006922 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00006923 }
6924 }
drh4e8142c2016-11-11 14:54:22 +00006925 if( nSql && !_all_whitespace(zSql) ){
6926 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006927 }
drh1f9ca2c2015-08-25 16:57:52 +00006928 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00006929 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00006930 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00006931}
6932
drh67505e72002-04-19 12:34:06 +00006933/*
6934** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00006935** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00006936*/
drhd1459152016-09-16 19:11:03 +00006937static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00006938 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00006939 if( clearFlag ){
6940 free(home_dir);
6941 home_dir = 0;
6942 return 0;
6943 }
drh85e72432012-04-11 11:38:53 +00006944 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00006945
drh4ace5362014-11-10 14:42:28 +00006946#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6947 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00006948 {
6949 struct passwd *pwent;
6950 uid_t uid = getuid();
6951 if( (pwent=getpwuid(uid)) != NULL) {
6952 home_dir = pwent->pw_dir;
6953 }
drh67505e72002-04-19 12:34:06 +00006954 }
6955#endif
6956
chw65d3c132007-11-12 21:09:10 +00006957#if defined(_WIN32_WCE)
6958 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6959 */
drh85e72432012-04-11 11:38:53 +00006960 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00006961#else
6962
drh83905c92012-06-21 13:00:37 +00006963#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00006964 if (!home_dir) {
6965 home_dir = getenv("USERPROFILE");
6966 }
6967#endif
6968
drh67505e72002-04-19 12:34:06 +00006969 if (!home_dir) {
6970 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00006971 }
6972
drh83905c92012-06-21 13:00:37 +00006973#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00006974 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00006975 char *zDrive, *zPath;
6976 int n;
6977 zDrive = getenv("HOMEDRIVE");
6978 zPath = getenv("HOMEPATH");
6979 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00006980 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00006981 home_dir = malloc( n );
6982 if( home_dir==0 ) return 0;
6983 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6984 return home_dir;
6985 }
6986 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00006987 }
6988#endif
6989
chw65d3c132007-11-12 21:09:10 +00006990#endif /* !_WIN32_WCE */
6991
drh67505e72002-04-19 12:34:06 +00006992 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00006993 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00006994 char *z = malloc( n );
6995 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00006996 home_dir = z;
6997 }
drhe98d4fa2002-04-21 19:06:22 +00006998
drh67505e72002-04-19 12:34:06 +00006999 return home_dir;
7000}
7001
7002/*
7003** Read input from the file given by sqliterc_override. Or if that
7004** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007005**
7006** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007007*/
drh534f4df2015-02-28 14:03:35 +00007008static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007009 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007010 const char *sqliterc_override /* Name of config file. NULL to use default */
7011){
persicom7e2dfdd2002-04-18 02:46:52 +00007012 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007013 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007014 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007015 FILE *in = NULL;
7016
7017 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007018 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007019 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007020 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007021 " cannot read ~/.sqliterc\n");
7022 return;
drhe98d4fa2002-04-21 19:06:22 +00007023 }
drh2f3de322012-06-27 16:41:31 +00007024 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007025 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7026 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007027 }
drha1f9b5e2004-02-14 16:31:02 +00007028 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007029 if( in ){
drhc28490c2006-10-26 14:25:58 +00007030 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007031 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007032 }
drh534f4df2015-02-28 14:03:35 +00007033 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007034 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007035 }
drh85e72432012-04-11 11:38:53 +00007036 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007037}
7038
drh67505e72002-04-19 12:34:06 +00007039/*
drhe1e38c42003-05-04 18:30:59 +00007040** Show available command line options
7041*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007042static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007043 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007044 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007045 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007046 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007047 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007048 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007049 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007050 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007051 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007052#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7053 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7054#endif
drhcc3b4f82012-02-07 14:13:50 +00007055 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007056 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007057 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007058 " -line set output mode to 'line'\n"
7059 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007060 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007061 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007062#ifdef SQLITE_ENABLE_MULTIPLEX
7063 " -multiplex enable the multiplexor VFS\n"
7064#endif
mistachkine0d68852014-12-11 03:12:33 +00007065 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007066 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007067 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7068 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00007069 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007070 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007071 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007072 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007073#ifdef SQLITE_ENABLE_VFSTRACE
7074 " -vfstrace enable tracing of all VFS calls\n"
7075#endif
drhe1e38c42003-05-04 18:30:59 +00007076;
7077static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007078 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007079 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007080 "FILENAME is the name of an SQLite database. A new database is created\n"
7081 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007082 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007083 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007084 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007085 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007086 }
7087 exit(1);
7088}
7089
7090/*
drh67505e72002-04-19 12:34:06 +00007091** Initialize the state information in data
7092*/
drhdcd87a92014-08-18 13:45:42 +00007093static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007094 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007095 data->normalMode = data->cMode = data->mode = MODE_List;
7096 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007097 memcpy(data->colSeparator,SEP_Column, 2);
7098 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007099 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007100 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007101 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007102 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007103 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007104 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7105 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007106}
7107
drh98d312f2012-10-25 15:23:14 +00007108/*
drh5c7976f2014-02-10 19:59:27 +00007109** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007110*/
7111#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007112static void printBold(const char *zText){
7113 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7114 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7115 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7116 SetConsoleTextAttribute(out,
7117 FOREGROUND_RED|FOREGROUND_INTENSITY
7118 );
7119 printf("%s", zText);
7120 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007121}
7122#else
drh5c7976f2014-02-10 19:59:27 +00007123static void printBold(const char *zText){
7124 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007125}
7126#endif
7127
7128/*
drh98d312f2012-10-25 15:23:14 +00007129** Get the argument to an --option. Throw an error and die if no argument
7130** is available.
7131*/
7132static char *cmdline_option_value(int argc, char **argv, int i){
7133 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007134 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007135 argv[0], argv[argc-1]);
7136 exit(1);
7137 }
7138 return argv[i];
7139}
7140
mistachkin1fe36bb2016-04-04 02:16:44 +00007141#ifndef SQLITE_SHELL_IS_UTF8
7142# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7143# define SQLITE_SHELL_IS_UTF8 (0)
7144# else
7145# define SQLITE_SHELL_IS_UTF8 (1)
7146# endif
7147#endif
7148
7149#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007150int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007151#else
7152int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007153 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007154#endif
drh75897232000-05-29 14:26:00 +00007155 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007156 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007157 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007158 int i;
drhc28490c2006-10-26 14:25:58 +00007159 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007160 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007161 int readStdin = 1;
7162 int nCmd = 0;
7163 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007164
mistachkin1fe36bb2016-04-04 02:16:44 +00007165 setBinaryMode(stdin, 0);
7166 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007167 stdin_is_interactive = isatty(0);
7168 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007169
drh69b30ab2014-02-27 15:11:52 +00007170#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007171 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007172 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007173 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7174 exit(1);
7175 }
drhc7181902014-02-27 15:04:13 +00007176#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007177 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007178#if !SQLITE_SHELL_IS_UTF8
7179 sqlite3_initialize();
7180 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7181 if( argv==0 ){
7182 raw_printf(stderr, "out of memory\n");
7183 exit(1);
7184 }
7185 for(i=0; i<argc; i++){
7186 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7187 if( argv[i]==0 ){
7188 raw_printf(stderr, "out of memory\n");
7189 exit(1);
7190 }
7191 }
7192#endif
mistachkin1810f222016-04-04 02:33:34 +00007193 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007194 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007195
drh44c2eb12003-04-30 11:38:26 +00007196 /* Make sure we have a valid signal handler early, before anything
7197 ** else is done.
7198 */
drh4c504392000-10-16 22:06:40 +00007199#ifdef SIGINT
7200 signal(SIGINT, interrupt_handler);
7201#endif
drh44c2eb12003-04-30 11:38:26 +00007202
drhac5649a2014-11-28 13:35:03 +00007203#ifdef SQLITE_SHELL_DBNAME_PROC
7204 {
7205 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7206 ** of a C-function that will provide the name of the database file. Use
7207 ** this compile-time option to embed this shell program in larger
7208 ** applications. */
7209 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7210 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7211 warnInmemoryDb = 0;
7212 }
7213#endif
7214
drh22fbcb82004-02-01 01:22:50 +00007215 /* Do an initial pass through the command-line argument to locate
7216 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007217 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007218 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007219 */
drh98d312f2012-10-25 15:23:14 +00007220 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007221 char *z;
drhc28490c2006-10-26 14:25:58 +00007222 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007223 if( z[0]!='-' ){
7224 if( data.zDbFilename==0 ){
7225 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007226 }else{
7227 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7228 ** mean that nothing is read from stdin */
7229 readStdin = 0;
7230 nCmd++;
7231 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7232 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007233 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007234 exit(1);
7235 }
7236 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007237 }
drh98d312f2012-10-25 15:23:14 +00007238 }
drhcc3b4f82012-02-07 14:13:50 +00007239 if( z[1]=='-' ) z++;
7240 if( strcmp(z,"-separator")==0
7241 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007242 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007243 || strcmp(z,"-cmd")==0
7244 ){
drh98d312f2012-10-25 15:23:14 +00007245 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007246 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007247 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007248 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007249 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007250 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007251 ** we do the actual processing of arguments later in a second pass.
7252 */
shanef69573d2009-10-24 02:06:14 +00007253 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007254 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007255#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007256 const char *zSize;
7257 sqlite3_int64 szHeap;
7258
drh98d312f2012-10-25 15:23:14 +00007259 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007260 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007261 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007262 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007263#else
7264 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007265#endif
drh44dec872014-08-30 15:49:25 +00007266 }else if( strcmp(z,"-scratch")==0 ){
7267 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007268 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007269 if( sz>400000 ) sz = 400000;
7270 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007271 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007272 if( n>10 ) n = 10;
7273 if( n<1 ) n = 1;
7274 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7275 data.shellFlgs |= SHFLG_Scratch;
7276 }else if( strcmp(z,"-pagecache")==0 ){
7277 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007278 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007279 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007280 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007281 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007282 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7283 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007284 data.shellFlgs |= SHFLG_Pagecache;
7285 }else if( strcmp(z,"-lookaside")==0 ){
7286 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007287 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007288 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007289 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007290 if( n<0 ) n = 0;
7291 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7292 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007293#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007294 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007295 extern int vfstrace_register(
7296 const char *zTraceName,
7297 const char *zOldVfsName,
7298 int (*xOut)(const char*,void*),
7299 void *pOutArg,
7300 int makeDefault
7301 );
drh2b625e22011-03-16 17:05:28 +00007302 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007303#endif
drh6f25e892011-07-08 17:02:57 +00007304#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007305 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007306 extern int sqlite3_multiple_initialize(const char*,int);
7307 sqlite3_multiplex_initialize(0, 1);
7308#endif
drh7d9f3942013-04-03 01:26:54 +00007309 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007310 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7311 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007312 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007313 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007314 if( pVfs ){
7315 sqlite3_vfs_register(pVfs, 1);
7316 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007317 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007318 exit(1);
7319 }
drh44c2eb12003-04-30 11:38:26 +00007320 }
7321 }
drh98d312f2012-10-25 15:23:14 +00007322 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007323#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007324 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007325 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007326#else
mistachkinaae280e2015-12-31 19:06:24 +00007327 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007328 return 1;
drh01b41712005-08-29 23:06:23 +00007329#endif
drh98d312f2012-10-25 15:23:14 +00007330 }
7331 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007332
drh44c2eb12003-04-30 11:38:26 +00007333 /* Go ahead and open the database file if it already exists. If the
7334 ** file does not exist, delay opening it. This prevents empty database
7335 ** files from being created if a user mistypes the database name argument
7336 ** to the sqlite command-line tool.
7337 */
drhc8d74412004-08-31 23:41:26 +00007338 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007339 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007340 }
7341
drh22fbcb82004-02-01 01:22:50 +00007342 /* Process the initialization file if there is one. If no -init option
7343 ** is given on the command line, look for a file named ~/.sqliterc and
7344 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007345 */
drh534f4df2015-02-28 14:03:35 +00007346 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007347
drh22fbcb82004-02-01 01:22:50 +00007348 /* Make a second pass through the command-line argument and set
7349 ** options. This second pass is delayed until after the initialization
7350 ** file is processed so that the command-line arguments will override
7351 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007352 */
drh98d312f2012-10-25 15:23:14 +00007353 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007354 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007355 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007356 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007357 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007358 i++;
7359 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007360 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007361 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007362 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007363 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007364 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007365 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007366 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007367 }else if( strcmp(z,"-csv")==0 ){
7368 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007369 memcpy(data.colSeparator,",",2);
7370 }else if( strcmp(z,"-ascii")==0 ){
7371 data.mode = MODE_Ascii;
7372 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007373 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007374 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007375 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007376 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007377 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007378 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007379 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007380 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007381 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007382 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007383 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007384 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007385 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007386 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007387 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007388 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007389 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007390 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007391 }else if( strcmp(z,"-eqp")==0 ){
7392 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007393 }else if( strcmp(z,"-eqpfull")==0 ){
7394 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007395 }else if( strcmp(z,"-stats")==0 ){
7396 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007397 }else if( strcmp(z,"-scanstats")==0 ){
7398 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007399 }else if( strcmp(z,"-backslash")==0 ){
7400 /* Undocumented command-line option: -backslash
7401 ** Causes C-style backslash escapes to be evaluated in SQL statements
7402 ** prior to sending the SQL into SQLite. Useful for injecting
7403 ** crazy bytes in the middle of SQL statements for testing and debugging.
7404 */
drhe6e1d122017-03-09 13:50:49 +00007405 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007406 }else if( strcmp(z,"-bail")==0 ){
7407 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007408 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007409 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007410 return 0;
drhc28490c2006-10-26 14:25:58 +00007411 }else if( strcmp(z,"-interactive")==0 ){
7412 stdin_is_interactive = 1;
7413 }else if( strcmp(z,"-batch")==0 ){
7414 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007415 }else if( strcmp(z,"-heap")==0 ){
7416 i++;
drh44dec872014-08-30 15:49:25 +00007417 }else if( strcmp(z,"-scratch")==0 ){
7418 i+=2;
7419 }else if( strcmp(z,"-pagecache")==0 ){
7420 i+=2;
7421 }else if( strcmp(z,"-lookaside")==0 ){
7422 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007423 }else if( strcmp(z,"-mmap")==0 ){
7424 i++;
drha7e61d82011-03-12 17:02:57 +00007425 }else if( strcmp(z,"-vfs")==0 ){
7426 i++;
drh6f25e892011-07-08 17:02:57 +00007427#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007428 }else if( strcmp(z,"-vfstrace")==0 ){
7429 i++;
drh6f25e892011-07-08 17:02:57 +00007430#endif
7431#ifdef SQLITE_ENABLE_MULTIPLEX
7432 }else if( strcmp(z,"-multiplex")==0 ){
7433 i++;
7434#endif
drhcc3b4f82012-02-07 14:13:50 +00007435 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007436 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007437 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007438 /* Run commands that follow -cmd first and separately from commands
7439 ** that simply appear on the command-line. This seems goofy. It would
7440 ** be better if all commands ran in the order that they appear. But
7441 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007442 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007443 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007444 if( z[0]=='.' ){
7445 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007446 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007447 }else{
drh05782482013-10-24 15:20:20 +00007448 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007449 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7450 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007451 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007452 if( bail_on_error ) return rc!=0 ? rc : 1;
7453 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007454 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007455 if( bail_on_error ) return rc;
7456 }
7457 }
drh1e5d0e92000-05-31 23:33:17 +00007458 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007459 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7460 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007461 return 1;
7462 }
drh700c2522016-02-09 18:39:25 +00007463 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007464 }
drh44c2eb12003-04-30 11:38:26 +00007465
drhac5649a2014-11-28 13:35:03 +00007466 if( !readStdin ){
7467 /* Run all arguments that do not begin with '-' as if they were separate
7468 ** command-line inputs, except for the argToSkip argument which contains
7469 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007470 */
drhac5649a2014-11-28 13:35:03 +00007471 for(i=0; i<nCmd; i++){
7472 if( azCmd[i][0]=='.' ){
7473 rc = do_meta_command(azCmd[i], &data);
7474 if( rc ) return rc==2 ? 0 : rc;
7475 }else{
7476 open_db(&data, 0);
7477 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7478 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007479 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007480 return rc!=0 ? rc : 1;
7481 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007482 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007483 return rc;
7484 }
drh6ff13852001-11-25 13:18:23 +00007485 }
drh75897232000-05-29 14:26:00 +00007486 }
drhac5649a2014-11-28 13:35:03 +00007487 free(azCmd);
drh75897232000-05-29 14:26:00 +00007488 }else{
drh44c2eb12003-04-30 11:38:26 +00007489 /* Run commands received from standard input
7490 */
drhc28490c2006-10-26 14:25:58 +00007491 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007492 char *zHome;
7493 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007494 int nHistory;
drh75897232000-05-29 14:26:00 +00007495 printf(
drh743e0032011-12-12 16:51:50 +00007496 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007497 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007498 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007499 );
drhb3735912014-02-10 16:13:42 +00007500 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007501 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007502 printBold("transient in-memory database");
7503 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007504 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007505 }
drhd1459152016-09-16 19:11:03 +00007506 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007507 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007508 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007509 if( (zHistory = malloc(nHistory))!=0 ){
7510 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7511 }
drh67505e72002-04-19 12:34:06 +00007512 }
drhf5ed7ad2015-06-15 14:43:25 +00007513 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007514 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007515 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007516 shell_stifle_history(100);
7517 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007518 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007519 }
drhdaffd0e2001-04-11 14:28:42 +00007520 }else{
drhc28490c2006-10-26 14:25:58 +00007521 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007522 }
7523 }
drh33048c02001-10-01 14:29:22 +00007524 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007525 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007526 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007527 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007528 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007529 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007530 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007531#if !SQLITE_SHELL_IS_UTF8
7532 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7533 sqlite3_free(argv);
7534#endif
drhc28490c2006-10-26 14:25:58 +00007535 return rc;
drh75897232000-05-29 14:26:00 +00007536}