blob: 36f6970d1f14451f8284a1e249839c32da6563e8 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
drh75897232000-05-29 14:26:00 +000014*/
mistachkina3b2ff52011-09-16 20:16:36 +000015#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
shane18e526c2008-12-10 22:30:24 +000016/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
drh36f7dd32011-10-13 16:02:17 +000020/*
drhce13b992017-05-23 20:00:00 +000021** Warning pragmas copied from msvc.h in the core.
mistachkin2318d332015-01-12 18:02:52 +000022*/
drhce13b992017-05-23 20:00:00 +000023#if defined(_MSC_VER)
24#pragma warning(disable : 4054)
25#pragma warning(disable : 4055)
26#pragma warning(disable : 4100)
27#pragma warning(disable : 4127)
28#pragma warning(disable : 4130)
29#pragma warning(disable : 4152)
30#pragma warning(disable : 4189)
31#pragma warning(disable : 4206)
32#pragma warning(disable : 4210)
33#pragma warning(disable : 4232)
34#pragma warning(disable : 4244)
35#pragma warning(disable : 4305)
36#pragma warning(disable : 4306)
37#pragma warning(disable : 4702)
38#pragma warning(disable : 4706)
39#endif /* defined(_MSC_VER) */
mistachkin2318d332015-01-12 18:02:52 +000040
41/*
drh8cd5b252015-03-02 22:06:43 +000042** No support for loadable extensions in VxWorks.
43*/
drhada3f2b2015-03-23 21:32:50 +000044#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000045# define SQLITE_OMIT_LOAD_EXTENSION 1
46#endif
47
48/*
drh36f7dd32011-10-13 16:02:17 +000049** Enable large-file support for fopen() and friends on unix.
50*/
51#ifndef SQLITE_DISABLE_LFS
52# define _LARGE_FILE 1
53# ifndef _FILE_OFFSET_BITS
54# define _FILE_OFFSET_BITS 64
55# endif
56# define _LARGEFILE_SOURCE 1
57#endif
58
drh75897232000-05-29 14:26:00 +000059#include <stdlib.h>
60#include <string.h>
61#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000062#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000063#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000064#if SQLITE_USER_AUTHENTICATION
65# include "sqlite3userauth.h"
66#endif
drh75897232000-05-29 14:26:00 +000067#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000068#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000069
drh83905c92012-06-21 13:00:37 +000070#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000071# include <signal.h>
chw97185482008-11-17 08:05:31 +000072# if !defined(__RTP__) && !defined(_WRS_KERNEL)
73# include <pwd.h>
74# endif
drhdd45df82002-04-18 12:39:03 +000075# include <unistd.h>
76# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000077#endif
drh75897232000-05-29 14:26:00 +000078
drh0ede9eb2015-01-10 16:49:23 +000079#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000080# include <readline/readline.h>
81# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +000082#endif
danfd34d6d2015-02-25 10:54:53 +000083
drh0ede9eb2015-01-10 16:49:23 +000084#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +000085# include <editline/readline.h>
86#endif
danfd34d6d2015-02-25 10:54:53 +000087
88#if HAVE_EDITLINE || HAVE_READLINE
89
90# define shell_add_history(X) add_history(X)
91# define shell_read_history(X) read_history(X)
92# define shell_write_history(X) write_history(X)
93# define shell_stifle_history(X) stifle_history(X)
94# define shell_readline(X) readline(X)
95
96#elif HAVE_LINENOISE
97
98# include "linenoise.h"
99# define shell_add_history(X) linenoiseHistoryAdd(X)
100# define shell_read_history(X) linenoiseHistoryLoad(X)
101# define shell_write_history(X) linenoiseHistorySave(X)
102# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
103# define shell_readline(X) linenoise(X)
104
105#else
106
mistachkin1fe36bb2016-04-04 02:16:44 +0000107# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +0000108# define shell_write_history(X)
109# define shell_stifle_history(X)
110
111# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +0000112#endif
113
danfd34d6d2015-02-25 10:54:53 +0000114
adamd2e8464a2006-09-06 21:39:40 +0000115#if defined(_WIN32) || defined(WIN32)
116# include <io.h>
drh6976c212014-07-24 12:09:47 +0000117# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000118# define isatty(h) _isatty(h)
119# ifndef access
120# define access(f,m) _access((f),(m))
121# endif
122# undef popen
123# define popen _popen
124# undef pclose
125# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000126#else
mistachkin073664d2015-06-17 18:57:37 +0000127 /* Make sure isatty() has a prototype. */
128 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000129
mistachkin073664d2015-06-17 18:57:37 +0000130# if !defined(__RTP__) && !defined(_WRS_KERNEL)
131 /* popen and pclose are not C89 functions and so are
132 ** sometimes omitted from the <stdio.h> header */
133 extern FILE *popen(const char*,const char*);
134 extern int pclose(FILE*);
135# else
136# define SQLITE_OMIT_POPEN 1
137# endif
mistachkinf6418892013-08-28 01:54:12 +0000138#endif
drh53371f92013-07-25 17:07:03 +0000139
chw65d3c132007-11-12 21:09:10 +0000140#if defined(_WIN32_WCE)
141/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
142 * thus we always assume that we have a console. That can be
143 * overridden with the -batch command line option.
144 */
145#define isatty(x) 1
146#endif
147
drhf0693c82011-10-11 20:41:54 +0000148/* ctype macros that work with signed characters */
149#define IsSpace(X) isspace((unsigned char)X)
150#define IsDigit(X) isdigit((unsigned char)X)
151#define ToLower(X) (char)tolower((unsigned char)X)
152
mistachkin1fe36bb2016-04-04 02:16:44 +0000153#if defined(_WIN32) || defined(WIN32)
154#include <windows.h>
155
156/* string conversion routines only needed on Win32 */
157extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
158extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
159extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000160extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000161#endif
162
drh047d4532015-01-18 20:30:23 +0000163/* On Windows, we normally run with output mode of TEXT so that \n characters
164** are automatically translated into \r\n. However, this behavior needs
165** to be disabled in some cases (ex: when generating CSV output and when
166** rendering quoted strings that contain \n characters). The following
167** routines take care of that.
168*/
169#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000170static void setBinaryMode(FILE *file, int isOutput){
171 if( isOutput ) fflush(file);
172 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000173}
mistachkin1fe36bb2016-04-04 02:16:44 +0000174static void setTextMode(FILE *file, int isOutput){
175 if( isOutput ) fflush(file);
176 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000177}
178#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000179# define setBinaryMode(X,Y)
180# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000181#endif
182
drh43408312013-10-30 12:43:36 +0000183
184/* True if the timer is enabled */
185static int enableTimer = 0;
186
187/* Return the current wall-clock time */
188static sqlite3_int64 timeOfDay(void){
189 static sqlite3_vfs *clockVfs = 0;
190 sqlite3_int64 t;
191 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000192 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000193 clockVfs->xCurrentTimeInt64(clockVfs, &t);
194 }else{
195 double r;
196 clockVfs->xCurrentTime(clockVfs, &r);
197 t = (sqlite3_int64)(r*86400000.0);
198 }
199 return t;
200}
201
drh91eb93c2015-03-03 19:56:20 +0000202#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000203#include <sys/time.h>
204#include <sys/resource.h>
205
drh91eb93c2015-03-03 19:56:20 +0000206/* VxWorks does not support getrusage() as far as we can determine */
207#if defined(_WRS_KERNEL) || defined(__RTP__)
208struct rusage {
209 struct timeval ru_utime; /* user CPU time used */
210 struct timeval ru_stime; /* system CPU time used */
211};
212#define getrusage(A,B) memset(B,0,sizeof(*B))
213#endif
214
drhda108222009-02-25 19:07:24 +0000215/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000216static struct rusage sBegin; /* CPU time at start */
217static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000218
drhda108222009-02-25 19:07:24 +0000219/*
220** Begin timing an operation
221*/
222static void beginTimer(void){
223 if( enableTimer ){
224 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000225 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000226 }
227}
228
229/* Return the difference of two time_structs in seconds */
230static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000231 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000232 (double)(pEnd->tv_sec - pStart->tv_sec);
233}
234
235/*
236** Print the timing results.
237*/
238static void endTimer(void){
239 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000240 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000241 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000242 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000243 printf("Run Time: real %.3f user %f sys %f\n",
244 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000245 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
246 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
247 }
248}
shaneb320ccd2009-10-21 03:42:58 +0000249
drhda108222009-02-25 19:07:24 +0000250#define BEGIN_TIMER beginTimer()
251#define END_TIMER endTimer()
252#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000253
254#elif (defined(_WIN32) || defined(WIN32))
255
shaneb320ccd2009-10-21 03:42:58 +0000256/* Saved resource information for the beginning of an operation */
257static HANDLE hProcess;
258static FILETIME ftKernelBegin;
259static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000260static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000261typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
262 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000263static GETPROCTIMES getProcessTimesAddr = NULL;
264
shaneb320ccd2009-10-21 03:42:58 +0000265/*
266** Check to see if we have timer support. Return 1 if necessary
267** support found (or found previously).
268*/
269static int hasTimer(void){
270 if( getProcessTimesAddr ){
271 return 1;
272 } else {
drh4ace5362014-11-10 14:42:28 +0000273 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
274 ** versions. See if the version we are running on has it, and if it
275 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000276 */
277 hProcess = GetCurrentProcess();
278 if( hProcess ){
279 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
280 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000281 getProcessTimesAddr =
282 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000283 if( NULL != getProcessTimesAddr ){
284 return 1;
285 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000286 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000287 }
288 }
289 }
290 return 0;
291}
292
293/*
294** Begin timing an operation
295*/
296static void beginTimer(void){
297 if( enableTimer && getProcessTimesAddr ){
298 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000299 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
300 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000301 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000302 }
303}
304
305/* Return the difference of two FILETIME structs in seconds */
306static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
307 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
308 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
309 return (double) ((i64End - i64Start) / 10000000.0);
310}
311
312/*
313** Print the timing results.
314*/
315static void endTimer(void){
316 if( enableTimer && getProcessTimesAddr){
317 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000318 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000319 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000320 printf("Run Time: real %.3f user %f sys %f\n",
321 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000322 timeDiff(&ftUserBegin, &ftUserEnd),
323 timeDiff(&ftKernelBegin, &ftKernelEnd));
324 }
325}
326
327#define BEGIN_TIMER beginTimer()
328#define END_TIMER endTimer()
329#define HAS_TIMER hasTimer()
330
drhda108222009-02-25 19:07:24 +0000331#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000332#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000333#define END_TIMER
334#define HAS_TIMER 0
335#endif
336
shanec0688ea2009-03-05 03:48:06 +0000337/*
338** Used to prevent warnings about unused parameters
339*/
340#define UNUSED_PARAMETER(x) (void)(x)
341
drhe91d16b2008-12-08 18:27:31 +0000342/*
drhc49f44e2006-10-26 18:15:42 +0000343** If the following flag is set, then command execution stops
344** at an error if we are not interactive.
345*/
346static int bail_on_error = 0;
347
348/*
drhc28490c2006-10-26 14:25:58 +0000349** Threat stdin as an interactive input if the following variable
350** is true. Otherwise, assume stdin is connected to a file or pipe.
351*/
352static int stdin_is_interactive = 1;
353
354/*
drhe05461c2015-12-30 13:36:57 +0000355** On Windows systems we have to know if standard output is a console
356** in order to translate UTF-8 into MBCS. The following variable is
357** true if translation is required.
358*/
359static int stdout_is_console = 1;
360
361/*
drh4c504392000-10-16 22:06:40 +0000362** The following is the open SQLite database. We make a pointer
363** to this database a static variable so that it can be accessed
364** by the SIGINT handler to interrupt database processing.
365*/
mistachkin8e189222015-04-19 21:43:16 +0000366static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000367
368/*
drh67505e72002-04-19 12:34:06 +0000369** True if an interrupt (Control-C) has been received.
370*/
drh43617e92006-03-06 20:55:46 +0000371static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000372
373/*
persicom7e2dfdd2002-04-18 02:46:52 +0000374** This is the name of our program. It is set in main(), used
375** in a number of other places, mostly for error messages.
376*/
377static char *Argv0;
378
379/*
380** Prompt strings. Initialized in main. Settable with
381** .prompt main continue
382*/
383static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
384static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
385
drhb0603412007-02-28 04:47:26 +0000386/*
mistachkin710b33b2016-01-03 18:59:28 +0000387** Render output like fprintf(). Except, if the output is going to the
388** console and if this is running on a Windows machine, translate the
389** output from UTF-8 into MBCS.
390*/
391#if defined(_WIN32) || defined(WIN32)
392void utf8_printf(FILE *out, const char *zFormat, ...){
393 va_list ap;
394 va_start(ap, zFormat);
395 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000396 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000397 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000398 sqlite3_free(z1);
399 fputs(z2, out);
400 sqlite3_free(z2);
401 }else{
402 vfprintf(out, zFormat, ap);
403 }
404 va_end(ap);
405}
406#elif !defined(utf8_printf)
407# define utf8_printf fprintf
408#endif
409
410/*
411** Render output like fprintf(). This should not be used on anything that
412** includes string formatting (e.g. "%s").
413*/
414#if !defined(raw_printf)
415# define raw_printf fprintf
416#endif
417
418/*
drhb0603412007-02-28 04:47:26 +0000419** Write I/O traces to the following stream.
420*/
rsebe0a9092007-07-30 18:24:38 +0000421#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000422static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000423#endif
drhb0603412007-02-28 04:47:26 +0000424
425/*
426** This routine works like printf in that its first argument is a
427** format string and subsequent arguments are values to be substituted
428** in place of % fields. The result of formatting this string
429** is written to iotrace.
430*/
rsebe0a9092007-07-30 18:24:38 +0000431#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000432static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000433 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000434 char *z;
drhb0603412007-02-28 04:47:26 +0000435 if( iotrace==0 ) return;
436 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000437 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000438 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000439 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000440 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000441}
rsebe0a9092007-07-30 18:24:38 +0000442#endif
drhb0603412007-02-28 04:47:26 +0000443
drh6887e8f2017-04-17 13:18:42 +0000444/*
445** Output string zUtf to stream pOut as w characters. If w is negative,
446** then right-justify the text. W is the width in UTF-8 characters, not
447** in bytes. This is different from the %*.*s specification in printf
448** since with %*.*s the width is measured in bytes, not characters.
449*/
450static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
451 int i;
452 int n;
453 int aw = w<0 ? -w : w;
454 char zBuf[1000];
drhf8a2e8c2017-05-06 17:12:52 +0000455 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
drh6887e8f2017-04-17 13:18:42 +0000456 for(i=n=0; zUtf[i]; i++){
457 if( (zUtf[i]&0xc0)!=0x80 ){
458 n++;
459 if( n==aw ){
460 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
461 break;
462 }
463 }
464 }
465 if( n>=aw ){
466 utf8_printf(pOut, "%.*s", i, zUtf);
467 }else if( w<0 ){
468 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
469 }else{
470 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
471 }
472}
473
drh44c2eb12003-04-30 11:38:26 +0000474
persicom7e2dfdd2002-04-18 02:46:52 +0000475/*
drh83965662003-04-17 02:54:13 +0000476** Determines if a string is a number of not.
477*/
danielk19772e588c72005-12-09 14:25:08 +0000478static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000479 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000480 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000481 return 0;
482 }
483 z++;
484 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000485 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000486 if( *z=='.' ){
487 z++;
drhf0693c82011-10-11 20:41:54 +0000488 if( !IsDigit(*z) ) return 0;
489 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000490 if( realnum ) *realnum = 1;
491 }
492 if( *z=='e' || *z=='E' ){
493 z++;
494 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000495 if( !IsDigit(*z) ) return 0;
496 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000497 if( realnum ) *realnum = 1;
498 }
499 return *z==0;
500}
drh83965662003-04-17 02:54:13 +0000501
502/*
drhe05461c2015-12-30 13:36:57 +0000503** Compute a string length that is limited to what can be stored in
504** lower 30 bits of a 32-bit signed integer.
505*/
506static int strlen30(const char *z){
507 const char *z2 = z;
508 while( *z2 ){ z2++; }
509 return 0x3fffffff & (int)(z2 - z);
510}
511
512/*
drh64bf76d2017-06-05 12:29:26 +0000513** Return the length of a string in characters. Multibyte UTF8 characters
514** count as a single character.
515*/
516static int strlenChar(const char *z){
517 int n = 0;
518 while( *z ){
519 if( (0xc0&*(z++))!=0x80 ) n++;
520 }
521 return n;
522}
523
524/*
drhfeac5f82004-08-01 00:10:45 +0000525** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000526** the text in memory obtained from malloc() and returns a pointer
527** to the text. NULL is returned at end of file, or if malloc()
528** fails.
529**
drh9f099fd2013-08-06 14:01:46 +0000530** If zLine is not NULL then it is a malloced buffer returned from
531** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000532*/
drh9f099fd2013-08-06 14:01:46 +0000533static char *local_getline(char *zLine, FILE *in){
534 int nLine = zLine==0 ? 0 : 100;
535 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000536
drhb07028f2011-10-14 21:49:18 +0000537 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000538 if( n+100>nLine ){
539 nLine = nLine*2 + 100;
540 zLine = realloc(zLine, nLine);
541 if( zLine==0 ) return 0;
542 }
drhdaffd0e2001-04-11 14:28:42 +0000543 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000544 if( n==0 ){
545 free(zLine);
546 return 0;
547 }
548 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000549 break;
550 }
drh9f099fd2013-08-06 14:01:46 +0000551 while( zLine[n] ) n++;
552 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000553 n--;
shaneh13b36022009-12-17 21:07:15 +0000554 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000555 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000556 break;
drh8e7e7a22000-05-30 18:45:23 +0000557 }
558 }
drhe05461c2015-12-30 13:36:57 +0000559#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000560 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000561 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000562 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000563 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000564 if( zTrans ){
565 int nTrans = strlen30(zTrans)+1;
566 if( nTrans>nLine ){
567 zLine = realloc(zLine, nTrans);
568 if( zLine==0 ){
569 sqlite3_free(zTrans);
570 return 0;
571 }
572 }
573 memcpy(zLine, zTrans, nTrans);
574 sqlite3_free(zTrans);
575 }
576 }
577#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000578 return zLine;
579}
580
581/*
drhc28490c2006-10-26 14:25:58 +0000582** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000583**
drh9f099fd2013-08-06 14:01:46 +0000584** If in==0 then read from standard input and prompt before each line.
585** If isContinuation is true, then a continuation prompt is appropriate.
586** If isContinuation is zero, then the main prompt should be used.
587**
588** If zPrior is not NULL then it is a buffer from a prior call to this
589** routine that can be reused.
590**
591** The result is stored in space obtained from malloc() and must either
592** be freed by the caller or else passed back into this routine via the
593** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000594*/
drh9f099fd2013-08-06 14:01:46 +0000595static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000596 char *zPrompt;
597 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000598 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000599 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000600 }else{
drh9f099fd2013-08-06 14:01:46 +0000601 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000602#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000603 printf("%s", zPrompt);
604 fflush(stdout);
605 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000606#else
607 free(zPrior);
608 zResult = shell_readline(zPrompt);
609 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000610#endif
drh9f099fd2013-08-06 14:01:46 +0000611 }
drh8e7e7a22000-05-30 18:45:23 +0000612 return zResult;
613}
drhf42d3182017-03-08 12:25:18 +0000614/*
615** A variable length string to which one can append text.
616*/
617typedef struct ShellText ShellText;
618struct ShellText {
619 char *z;
620 int n;
621 int nAlloc;
622};
623
624/*
625** Initialize and destroy a ShellText object
626*/
627static void initText(ShellText *p){
628 memset(p, 0, sizeof(*p));
629}
630static void freeText(ShellText *p){
631 free(p->z);
632 initText(p);
633}
634
635/* zIn is either a pointer to a NULL-terminated string in memory obtained
636** from malloc(), or a NULL pointer. The string pointed to by zAppend is
637** added to zIn, and the result returned in memory obtained from malloc().
638** zIn, if it was not NULL, is freed.
639**
640** If the third argument, quote, is not '\0', then it is used as a
641** quote character for zAppend.
642*/
643static void appendText(ShellText *p, char const *zAppend, char quote){
644 int len;
645 int i;
646 int nAppend = strlen30(zAppend);
647
648 len = nAppend+p->n+1;
649 if( quote ){
650 len += 2;
651 for(i=0; i<nAppend; i++){
652 if( zAppend[i]==quote ) len++;
653 }
654 }
655
656 if( p->n+len>=p->nAlloc ){
657 p->nAlloc = p->nAlloc*2 + len + 20;
658 p->z = realloc(p->z, p->nAlloc);
659 if( p->z==0 ){
660 memset(p, 0, sizeof(*p));
661 return;
662 }
663 }
664
665 if( quote ){
666 char *zCsr = p->z+p->n;
667 *zCsr++ = quote;
668 for(i=0; i<nAppend; i++){
669 *zCsr++ = zAppend[i];
670 if( zAppend[i]==quote ) *zCsr++ = quote;
671 }
672 *zCsr++ = quote;
673 p->n = (int)(zCsr - p->z);
674 *zCsr = '\0';
675 }else{
676 memcpy(p->z+p->n, zAppend, nAppend);
677 p->n += nAppend;
678 p->z[p->n] = '\0';
679 }
680}
681
682/*
683** Attempt to determine if identifier zName needs to be quoted, either
684** because it contains non-alphanumeric characters, or because it is an
685** SQLite keyword. Be conservative in this estimate: When in doubt assume
686** that quoting is required.
687**
688** Return '"' if quoting is required. Return 0 if no quoting is required.
689*/
690static char quoteChar(const char *zName){
691 /* All SQLite keywords, in alphabetical order */
692 static const char *azKeywords[] = {
693 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
694 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
695 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
696 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
697 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
698 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
699 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
700 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
701 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
702 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
703 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
704 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
705 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
706 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
707 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
708 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
709 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
710 "WITH", "WITHOUT",
711 };
712 int i, lwr, upr, mid, c;
713 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
714 for(i=0; zName[i]; i++){
715 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
716 }
717 lwr = 0;
718 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
719 while( lwr<=upr ){
720 mid = (lwr+upr)/2;
721 c = sqlite3_stricmp(azKeywords[mid], zName);
722 if( c==0 ) return '"';
723 if( c<0 ){
724 lwr = mid+1;
725 }else{
726 upr = mid-1;
727 }
728 }
729 return 0;
730}
drh8e7e7a22000-05-30 18:45:23 +0000731
drh1554bc82017-03-08 16:10:34 +0000732/******************************************************************************
733** SHA3 hash implementation copied from ../ext/misc/shathree.c
734*/
735typedef sqlite3_uint64 u64;
736/*
737** Macros to determine whether the machine is big or little endian,
738** and whether or not that determination is run-time or compile-time.
739**
740** For best performance, an attempt is made to guess at the byte-order
741** using C-preprocessor macros. If that is unsuccessful, or if
742** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
743** at run-time.
744*/
745#ifndef SHA3_BYTEORDER
746# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
747 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
748 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
749 defined(__arm__)
750# define SHA3_BYTEORDER 1234
751# elif defined(sparc) || defined(__ppc__)
752# define SHA3_BYTEORDER 4321
753# else
754# define SHA3_BYTEORDER 0
755# endif
756#endif
757
758
759/*
760** State structure for a SHA3 hash in progress
761*/
762typedef struct SHA3Context SHA3Context;
763struct SHA3Context {
764 union {
765 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
766 unsigned char x[1600]; /* ... or 1600 bytes */
767 } u;
768 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
769 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
770 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
771};
772
drh050b1242017-05-04 11:13:50 +0000773/* Allow the following routine to use the B0 variable, which is also
774** a macro in the termios.h header file */
775#undef B0
776
drh1554bc82017-03-08 16:10:34 +0000777/*
778** A single step of the Keccak mixing function for a 1600-bit state
779*/
780static void KeccakF1600Step(SHA3Context *p){
781 int i;
782 u64 B0, B1, B2, B3, B4;
783 u64 C0, C1, C2, C3, C4;
784 u64 D0, D1, D2, D3, D4;
785 static const u64 RC[] = {
786 0x0000000000000001ULL, 0x0000000000008082ULL,
787 0x800000000000808aULL, 0x8000000080008000ULL,
788 0x000000000000808bULL, 0x0000000080000001ULL,
789 0x8000000080008081ULL, 0x8000000000008009ULL,
790 0x000000000000008aULL, 0x0000000000000088ULL,
791 0x0000000080008009ULL, 0x000000008000000aULL,
792 0x000000008000808bULL, 0x800000000000008bULL,
793 0x8000000000008089ULL, 0x8000000000008003ULL,
794 0x8000000000008002ULL, 0x8000000000000080ULL,
795 0x000000000000800aULL, 0x800000008000000aULL,
796 0x8000000080008081ULL, 0x8000000000008080ULL,
797 0x0000000080000001ULL, 0x8000000080008008ULL
798 };
799# define A00 (p->u.s[0])
800# define A01 (p->u.s[1])
801# define A02 (p->u.s[2])
802# define A03 (p->u.s[3])
803# define A04 (p->u.s[4])
804# define A10 (p->u.s[5])
805# define A11 (p->u.s[6])
806# define A12 (p->u.s[7])
807# define A13 (p->u.s[8])
808# define A14 (p->u.s[9])
809# define A20 (p->u.s[10])
810# define A21 (p->u.s[11])
811# define A22 (p->u.s[12])
812# define A23 (p->u.s[13])
813# define A24 (p->u.s[14])
814# define A30 (p->u.s[15])
815# define A31 (p->u.s[16])
816# define A32 (p->u.s[17])
817# define A33 (p->u.s[18])
818# define A34 (p->u.s[19])
819# define A40 (p->u.s[20])
820# define A41 (p->u.s[21])
821# define A42 (p->u.s[22])
822# define A43 (p->u.s[23])
823# define A44 (p->u.s[24])
824# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
825
826 for(i=0; i<24; i+=4){
827 C0 = A00^A10^A20^A30^A40;
828 C1 = A01^A11^A21^A31^A41;
829 C2 = A02^A12^A22^A32^A42;
830 C3 = A03^A13^A23^A33^A43;
831 C4 = A04^A14^A24^A34^A44;
832 D0 = C4^ROL64(C1, 1);
833 D1 = C0^ROL64(C2, 1);
834 D2 = C1^ROL64(C3, 1);
835 D3 = C2^ROL64(C4, 1);
836 D4 = C3^ROL64(C0, 1);
837
838 B0 = (A00^D0);
839 B1 = ROL64((A11^D1), 44);
840 B2 = ROL64((A22^D2), 43);
841 B3 = ROL64((A33^D3), 21);
842 B4 = ROL64((A44^D4), 14);
843 A00 = B0 ^((~B1)& B2 );
844 A00 ^= RC[i];
845 A11 = B1 ^((~B2)& B3 );
846 A22 = B2 ^((~B3)& B4 );
847 A33 = B3 ^((~B4)& B0 );
848 A44 = B4 ^((~B0)& B1 );
849
850 B2 = ROL64((A20^D0), 3);
851 B3 = ROL64((A31^D1), 45);
852 B4 = ROL64((A42^D2), 61);
853 B0 = ROL64((A03^D3), 28);
854 B1 = ROL64((A14^D4), 20);
855 A20 = B0 ^((~B1)& B2 );
856 A31 = B1 ^((~B2)& B3 );
857 A42 = B2 ^((~B3)& B4 );
858 A03 = B3 ^((~B4)& B0 );
859 A14 = B4 ^((~B0)& B1 );
860
861 B4 = ROL64((A40^D0), 18);
862 B0 = ROL64((A01^D1), 1);
863 B1 = ROL64((A12^D2), 6);
864 B2 = ROL64((A23^D3), 25);
865 B3 = ROL64((A34^D4), 8);
866 A40 = B0 ^((~B1)& B2 );
867 A01 = B1 ^((~B2)& B3 );
868 A12 = B2 ^((~B3)& B4 );
869 A23 = B3 ^((~B4)& B0 );
870 A34 = B4 ^((~B0)& B1 );
871
872 B1 = ROL64((A10^D0), 36);
873 B2 = ROL64((A21^D1), 10);
874 B3 = ROL64((A32^D2), 15);
875 B4 = ROL64((A43^D3), 56);
876 B0 = ROL64((A04^D4), 27);
877 A10 = B0 ^((~B1)& B2 );
878 A21 = B1 ^((~B2)& B3 );
879 A32 = B2 ^((~B3)& B4 );
880 A43 = B3 ^((~B4)& B0 );
881 A04 = B4 ^((~B0)& B1 );
882
883 B3 = ROL64((A30^D0), 41);
884 B4 = ROL64((A41^D1), 2);
885 B0 = ROL64((A02^D2), 62);
886 B1 = ROL64((A13^D3), 55);
887 B2 = ROL64((A24^D4), 39);
888 A30 = B0 ^((~B1)& B2 );
889 A41 = B1 ^((~B2)& B3 );
890 A02 = B2 ^((~B3)& B4 );
891 A13 = B3 ^((~B4)& B0 );
892 A24 = B4 ^((~B0)& B1 );
893
894 C0 = A00^A20^A40^A10^A30;
895 C1 = A11^A31^A01^A21^A41;
896 C2 = A22^A42^A12^A32^A02;
897 C3 = A33^A03^A23^A43^A13;
898 C4 = A44^A14^A34^A04^A24;
899 D0 = C4^ROL64(C1, 1);
900 D1 = C0^ROL64(C2, 1);
901 D2 = C1^ROL64(C3, 1);
902 D3 = C2^ROL64(C4, 1);
903 D4 = C3^ROL64(C0, 1);
904
905 B0 = (A00^D0);
906 B1 = ROL64((A31^D1), 44);
907 B2 = ROL64((A12^D2), 43);
908 B3 = ROL64((A43^D3), 21);
909 B4 = ROL64((A24^D4), 14);
910 A00 = B0 ^((~B1)& B2 );
911 A00 ^= RC[i+1];
912 A31 = B1 ^((~B2)& B3 );
913 A12 = B2 ^((~B3)& B4 );
914 A43 = B3 ^((~B4)& B0 );
915 A24 = B4 ^((~B0)& B1 );
916
917 B2 = ROL64((A40^D0), 3);
918 B3 = ROL64((A21^D1), 45);
919 B4 = ROL64((A02^D2), 61);
920 B0 = ROL64((A33^D3), 28);
921 B1 = ROL64((A14^D4), 20);
922 A40 = B0 ^((~B1)& B2 );
923 A21 = B1 ^((~B2)& B3 );
924 A02 = B2 ^((~B3)& B4 );
925 A33 = B3 ^((~B4)& B0 );
926 A14 = B4 ^((~B0)& B1 );
927
928 B4 = ROL64((A30^D0), 18);
929 B0 = ROL64((A11^D1), 1);
930 B1 = ROL64((A42^D2), 6);
931 B2 = ROL64((A23^D3), 25);
932 B3 = ROL64((A04^D4), 8);
933 A30 = B0 ^((~B1)& B2 );
934 A11 = B1 ^((~B2)& B3 );
935 A42 = B2 ^((~B3)& B4 );
936 A23 = B3 ^((~B4)& B0 );
937 A04 = B4 ^((~B0)& B1 );
938
939 B1 = ROL64((A20^D0), 36);
940 B2 = ROL64((A01^D1), 10);
941 B3 = ROL64((A32^D2), 15);
942 B4 = ROL64((A13^D3), 56);
943 B0 = ROL64((A44^D4), 27);
944 A20 = B0 ^((~B1)& B2 );
945 A01 = B1 ^((~B2)& B3 );
946 A32 = B2 ^((~B3)& B4 );
947 A13 = B3 ^((~B4)& B0 );
948 A44 = B4 ^((~B0)& B1 );
949
950 B3 = ROL64((A10^D0), 41);
951 B4 = ROL64((A41^D1), 2);
952 B0 = ROL64((A22^D2), 62);
953 B1 = ROL64((A03^D3), 55);
954 B2 = ROL64((A34^D4), 39);
955 A10 = B0 ^((~B1)& B2 );
956 A41 = B1 ^((~B2)& B3 );
957 A22 = B2 ^((~B3)& B4 );
958 A03 = B3 ^((~B4)& B0 );
959 A34 = B4 ^((~B0)& B1 );
960
961 C0 = A00^A40^A30^A20^A10;
962 C1 = A31^A21^A11^A01^A41;
963 C2 = A12^A02^A42^A32^A22;
964 C3 = A43^A33^A23^A13^A03;
965 C4 = A24^A14^A04^A44^A34;
966 D0 = C4^ROL64(C1, 1);
967 D1 = C0^ROL64(C2, 1);
968 D2 = C1^ROL64(C3, 1);
969 D3 = C2^ROL64(C4, 1);
970 D4 = C3^ROL64(C0, 1);
971
972 B0 = (A00^D0);
973 B1 = ROL64((A21^D1), 44);
974 B2 = ROL64((A42^D2), 43);
975 B3 = ROL64((A13^D3), 21);
976 B4 = ROL64((A34^D4), 14);
977 A00 = B0 ^((~B1)& B2 );
978 A00 ^= RC[i+2];
979 A21 = B1 ^((~B2)& B3 );
980 A42 = B2 ^((~B3)& B4 );
981 A13 = B3 ^((~B4)& B0 );
982 A34 = B4 ^((~B0)& B1 );
983
984 B2 = ROL64((A30^D0), 3);
985 B3 = ROL64((A01^D1), 45);
986 B4 = ROL64((A22^D2), 61);
987 B0 = ROL64((A43^D3), 28);
988 B1 = ROL64((A14^D4), 20);
989 A30 = B0 ^((~B1)& B2 );
990 A01 = B1 ^((~B2)& B3 );
991 A22 = B2 ^((~B3)& B4 );
992 A43 = B3 ^((~B4)& B0 );
993 A14 = B4 ^((~B0)& B1 );
994
995 B4 = ROL64((A10^D0), 18);
996 B0 = ROL64((A31^D1), 1);
997 B1 = ROL64((A02^D2), 6);
998 B2 = ROL64((A23^D3), 25);
999 B3 = ROL64((A44^D4), 8);
1000 A10 = B0 ^((~B1)& B2 );
1001 A31 = B1 ^((~B2)& B3 );
1002 A02 = B2 ^((~B3)& B4 );
1003 A23 = B3 ^((~B4)& B0 );
1004 A44 = B4 ^((~B0)& B1 );
1005
1006 B1 = ROL64((A40^D0), 36);
1007 B2 = ROL64((A11^D1), 10);
1008 B3 = ROL64((A32^D2), 15);
1009 B4 = ROL64((A03^D3), 56);
1010 B0 = ROL64((A24^D4), 27);
1011 A40 = B0 ^((~B1)& B2 );
1012 A11 = B1 ^((~B2)& B3 );
1013 A32 = B2 ^((~B3)& B4 );
1014 A03 = B3 ^((~B4)& B0 );
1015 A24 = B4 ^((~B0)& B1 );
1016
1017 B3 = ROL64((A20^D0), 41);
1018 B4 = ROL64((A41^D1), 2);
1019 B0 = ROL64((A12^D2), 62);
1020 B1 = ROL64((A33^D3), 55);
1021 B2 = ROL64((A04^D4), 39);
1022 A20 = B0 ^((~B1)& B2 );
1023 A41 = B1 ^((~B2)& B3 );
1024 A12 = B2 ^((~B3)& B4 );
1025 A33 = B3 ^((~B4)& B0 );
1026 A04 = B4 ^((~B0)& B1 );
1027
1028 C0 = A00^A30^A10^A40^A20;
1029 C1 = A21^A01^A31^A11^A41;
1030 C2 = A42^A22^A02^A32^A12;
1031 C3 = A13^A43^A23^A03^A33;
1032 C4 = A34^A14^A44^A24^A04;
1033 D0 = C4^ROL64(C1, 1);
1034 D1 = C0^ROL64(C2, 1);
1035 D2 = C1^ROL64(C3, 1);
1036 D3 = C2^ROL64(C4, 1);
1037 D4 = C3^ROL64(C0, 1);
1038
1039 B0 = (A00^D0);
1040 B1 = ROL64((A01^D1), 44);
1041 B2 = ROL64((A02^D2), 43);
1042 B3 = ROL64((A03^D3), 21);
1043 B4 = ROL64((A04^D4), 14);
1044 A00 = B0 ^((~B1)& B2 );
1045 A00 ^= RC[i+3];
1046 A01 = B1 ^((~B2)& B3 );
1047 A02 = B2 ^((~B3)& B4 );
1048 A03 = B3 ^((~B4)& B0 );
1049 A04 = B4 ^((~B0)& B1 );
1050
1051 B2 = ROL64((A10^D0), 3);
1052 B3 = ROL64((A11^D1), 45);
1053 B4 = ROL64((A12^D2), 61);
1054 B0 = ROL64((A13^D3), 28);
1055 B1 = ROL64((A14^D4), 20);
1056 A10 = B0 ^((~B1)& B2 );
1057 A11 = B1 ^((~B2)& B3 );
1058 A12 = B2 ^((~B3)& B4 );
1059 A13 = B3 ^((~B4)& B0 );
1060 A14 = B4 ^((~B0)& B1 );
1061
1062 B4 = ROL64((A20^D0), 18);
1063 B0 = ROL64((A21^D1), 1);
1064 B1 = ROL64((A22^D2), 6);
1065 B2 = ROL64((A23^D3), 25);
1066 B3 = ROL64((A24^D4), 8);
1067 A20 = B0 ^((~B1)& B2 );
1068 A21 = B1 ^((~B2)& B3 );
1069 A22 = B2 ^((~B3)& B4 );
1070 A23 = B3 ^((~B4)& B0 );
1071 A24 = B4 ^((~B0)& B1 );
1072
1073 B1 = ROL64((A30^D0), 36);
1074 B2 = ROL64((A31^D1), 10);
1075 B3 = ROL64((A32^D2), 15);
1076 B4 = ROL64((A33^D3), 56);
1077 B0 = ROL64((A34^D4), 27);
1078 A30 = B0 ^((~B1)& B2 );
1079 A31 = B1 ^((~B2)& B3 );
1080 A32 = B2 ^((~B3)& B4 );
1081 A33 = B3 ^((~B4)& B0 );
1082 A34 = B4 ^((~B0)& B1 );
1083
1084 B3 = ROL64((A40^D0), 41);
1085 B4 = ROL64((A41^D1), 2);
1086 B0 = ROL64((A42^D2), 62);
1087 B1 = ROL64((A43^D3), 55);
1088 B2 = ROL64((A44^D4), 39);
1089 A40 = B0 ^((~B1)& B2 );
1090 A41 = B1 ^((~B2)& B3 );
1091 A42 = B2 ^((~B3)& B4 );
1092 A43 = B3 ^((~B4)& B0 );
1093 A44 = B4 ^((~B0)& B1 );
1094 }
1095}
1096
1097/*
1098** Initialize a new hash. iSize determines the size of the hash
1099** in bits and should be one of 224, 256, 384, or 512. Or iSize
1100** can be zero to use the default hash size of 256 bits.
1101*/
1102static void SHA3Init(SHA3Context *p, int iSize){
1103 memset(p, 0, sizeof(*p));
1104 if( iSize>=128 && iSize<=512 ){
1105 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1106 }else{
1107 p->nRate = (1600 - 2*256)/8;
1108 }
1109#if SHA3_BYTEORDER==1234
1110 /* Known to be little-endian at compile-time. No-op */
1111#elif SHA3_BYTEORDER==4321
1112 p->ixMask = 7; /* Big-endian */
1113#else
1114 {
1115 static unsigned int one = 1;
1116 if( 1==*(unsigned char*)&one ){
1117 /* Little endian. No byte swapping. */
1118 p->ixMask = 0;
1119 }else{
1120 /* Big endian. Byte swap. */
1121 p->ixMask = 7;
1122 }
1123 }
1124#endif
1125}
1126
1127/*
1128** Make consecutive calls to the SHA3Update function to add new content
1129** to the hash
1130*/
1131static void SHA3Update(
1132 SHA3Context *p,
1133 const unsigned char *aData,
1134 unsigned int nData
1135){
1136 unsigned int i = 0;
1137#if SHA3_BYTEORDER==1234
1138 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1139 for(; i+7<nData; i+=8){
1140 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1141 p->nLoaded += 8;
1142 if( p->nLoaded>=p->nRate ){
1143 KeccakF1600Step(p);
1144 p->nLoaded = 0;
1145 }
1146 }
1147 }
1148#endif
1149 for(; i<nData; i++){
1150#if SHA3_BYTEORDER==1234
1151 p->u.x[p->nLoaded] ^= aData[i];
1152#elif SHA3_BYTEORDER==4321
1153 p->u.x[p->nLoaded^0x07] ^= aData[i];
1154#else
1155 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1156#endif
1157 p->nLoaded++;
1158 if( p->nLoaded==p->nRate ){
1159 KeccakF1600Step(p);
1160 p->nLoaded = 0;
1161 }
1162 }
1163}
1164
1165/*
1166** After all content has been added, invoke SHA3Final() to compute
1167** the final hash. The function returns a pointer to the binary
1168** hash value.
1169*/
1170static unsigned char *SHA3Final(SHA3Context *p){
1171 unsigned int i;
1172 if( p->nLoaded==p->nRate-1 ){
1173 const unsigned char c1 = 0x86;
1174 SHA3Update(p, &c1, 1);
1175 }else{
1176 const unsigned char c2 = 0x06;
1177 const unsigned char c3 = 0x80;
1178 SHA3Update(p, &c2, 1);
1179 p->nLoaded = p->nRate - 1;
1180 SHA3Update(p, &c3, 1);
1181 }
1182 for(i=0; i<p->nRate; i++){
1183 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1184 }
1185 return &p->u.x[p->nRate];
1186}
1187
1188/*
1189** Implementation of the sha3(X,SIZE) function.
1190**
1191** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
mistachkine16a3502017-05-29 03:48:13 +00001192** size is 256. If X is a BLOB, it is hashed as is.
drh1554bc82017-03-08 16:10:34 +00001193** For all other non-NULL types of input, X is converted into a UTF-8 string
1194** and the string is hashed without the trailing 0x00 terminator. The hash
1195** of a NULL value is NULL.
1196*/
1197static void sha3Func(
1198 sqlite3_context *context,
1199 int argc,
1200 sqlite3_value **argv
1201){
1202 SHA3Context cx;
1203 int eType = sqlite3_value_type(argv[0]);
1204 int nByte = sqlite3_value_bytes(argv[0]);
1205 int iSize;
1206 if( argc==1 ){
1207 iSize = 256;
1208 }else{
1209 iSize = sqlite3_value_int(argv[1]);
1210 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1211 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1212 "384 512", -1);
1213 return;
1214 }
1215 }
1216 if( eType==SQLITE_NULL ) return;
1217 SHA3Init(&cx, iSize);
1218 if( eType==SQLITE_BLOB ){
1219 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1220 }else{
1221 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1222 }
1223 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1224}
1225
1226/* Compute a string using sqlite3_vsnprintf() with a maximum length
1227** of 50 bytes and add it to the hash.
1228*/
1229static void hash_step_vformat(
1230 SHA3Context *p, /* Add content to this context */
1231 const char *zFormat,
1232 ...
1233){
1234 va_list ap;
1235 int n;
1236 char zBuf[50];
1237 va_start(ap, zFormat);
1238 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1239 va_end(ap);
1240 n = (int)strlen(zBuf);
1241 SHA3Update(p, (unsigned char*)zBuf, n);
1242}
1243
1244/*
1245** Implementation of the sha3_query(SQL,SIZE) function.
1246**
1247** This function compiles and runs the SQL statement(s) given in the
1248** argument. The results are hashed using a SIZE-bit SHA3. The default
1249** size is 256.
1250**
1251** The format of the byte stream that is hashed is summarized as follows:
1252**
1253** S<n>:<sql>
1254** R
1255** N
1256** I<int>
1257** F<ieee-float>
1258** B<size>:<bytes>
1259** T<size>:<text>
1260**
1261** <sql> is the original SQL text for each statement run and <n> is
1262** the size of that text. The SQL text is UTF-8. A single R character
1263** occurs before the start of each row. N means a NULL value.
1264** I mean an 8-byte little-endian integer <int>. F is a floating point
1265** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1266** B means blobs of <size> bytes. T means text rendered as <size>
1267** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1268** text integers.
1269**
1270** For each SQL statement in the X input, there is one S segment. Each
1271** S segment is followed by zero or more R segments, one for each row in the
1272** result set. After each R, there are one or more N, I, F, B, or T segments,
1273** one for each column in the result set. Segments are concatentated directly
1274** with no delimiters of any kind.
1275*/
1276static void sha3QueryFunc(
1277 sqlite3_context *context,
1278 int argc,
1279 sqlite3_value **argv
1280){
1281 sqlite3 *db = sqlite3_context_db_handle(context);
1282 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1283 sqlite3_stmt *pStmt = 0;
1284 int nCol; /* Number of columns in the result set */
1285 int i; /* Loop counter */
1286 int rc;
1287 int n;
1288 const char *z;
1289 SHA3Context cx;
1290 int iSize;
1291
1292 if( argc==1 ){
1293 iSize = 256;
1294 }else{
1295 iSize = sqlite3_value_int(argv[1]);
1296 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1297 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1298 "384 512", -1);
1299 return;
1300 }
1301 }
1302 if( zSql==0 ) return;
1303 SHA3Init(&cx, iSize);
1304 while( zSql[0] ){
1305 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1306 if( rc ){
1307 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1308 zSql, sqlite3_errmsg(db));
1309 sqlite3_finalize(pStmt);
1310 sqlite3_result_error(context, zMsg, -1);
1311 sqlite3_free(zMsg);
1312 return;
1313 }
1314 if( !sqlite3_stmt_readonly(pStmt) ){
1315 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1316 sqlite3_finalize(pStmt);
1317 sqlite3_result_error(context, zMsg, -1);
1318 sqlite3_free(zMsg);
1319 return;
1320 }
1321 nCol = sqlite3_column_count(pStmt);
1322 z = sqlite3_sql(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00001323 if( z==0 ){
1324 sqlite3_finalize(pStmt);
1325 continue;
1326 }
drh1554bc82017-03-08 16:10:34 +00001327 n = (int)strlen(z);
1328 hash_step_vformat(&cx,"S%d:",n);
1329 SHA3Update(&cx,(unsigned char*)z,n);
1330
1331 /* Compute a hash over the result of the query */
1332 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1333 SHA3Update(&cx,(const unsigned char*)"R",1);
1334 for(i=0; i<nCol; i++){
1335 switch( sqlite3_column_type(pStmt,i) ){
1336 case SQLITE_NULL: {
1337 SHA3Update(&cx, (const unsigned char*)"N",1);
1338 break;
1339 }
1340 case SQLITE_INTEGER: {
1341 sqlite3_uint64 u;
1342 int j;
1343 unsigned char x[9];
1344 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1345 memcpy(&u, &v, 8);
1346 for(j=8; j>=1; j--){
1347 x[j] = u & 0xff;
1348 u >>= 8;
1349 }
1350 x[0] = 'I';
1351 SHA3Update(&cx, x, 9);
1352 break;
1353 }
1354 case SQLITE_FLOAT: {
1355 sqlite3_uint64 u;
1356 int j;
1357 unsigned char x[9];
1358 double r = sqlite3_column_double(pStmt,i);
1359 memcpy(&u, &r, 8);
1360 for(j=8; j>=1; j--){
1361 x[j] = u & 0xff;
1362 u >>= 8;
1363 }
1364 x[0] = 'F';
1365 SHA3Update(&cx,x,9);
1366 break;
1367 }
1368 case SQLITE_TEXT: {
1369 int n2 = sqlite3_column_bytes(pStmt, i);
1370 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1371 hash_step_vformat(&cx,"T%d:",n2);
1372 SHA3Update(&cx, z2, n2);
1373 break;
1374 }
1375 case SQLITE_BLOB: {
1376 int n2 = sqlite3_column_bytes(pStmt, i);
1377 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1378 hash_step_vformat(&cx,"B%d:",n2);
1379 SHA3Update(&cx, z2, n2);
1380 break;
1381 }
1382 }
1383 }
1384 }
1385 sqlite3_finalize(pStmt);
1386 }
1387 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1388}
1389/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1390********************************************************************************/
1391
drhe6229612014-08-18 15:08:26 +00001392#if defined(SQLITE_ENABLE_SESSION)
1393/*
1394** State information for a single open session
1395*/
1396typedef struct OpenSession OpenSession;
1397struct OpenSession {
1398 char *zName; /* Symbolic name for this session */
1399 int nFilter; /* Number of xFilter rejection GLOB patterns */
1400 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1401 sqlite3_session *p; /* The open session */
1402};
1403#endif
1404
drhdcd87a92014-08-18 13:45:42 +00001405/*
mistachkin1fe36bb2016-04-04 02:16:44 +00001406** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00001407** saved so that it can be restored by ".explain off"
1408*/
1409typedef struct SavedModeInfo SavedModeInfo;
1410struct SavedModeInfo {
1411 int valid; /* Is there legit data in here? */
1412 int mode; /* Mode prior to ".explain on" */
1413 int showHeader; /* The ".header" setting prior to ".explain on" */
1414 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00001415};
drh45e29d82006-11-20 16:21:10 +00001416
drh8e7e7a22000-05-30 18:45:23 +00001417/*
drhdcd87a92014-08-18 13:45:42 +00001418** State information about the database connection is contained in an
1419** instance of the following structure.
drh75897232000-05-29 14:26:00 +00001420*/
drhdcd87a92014-08-18 13:45:42 +00001421typedef struct ShellState ShellState;
1422struct ShellState {
shane626a6e42009-10-22 17:30:15 +00001423 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00001424 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00001425 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00001426 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00001427 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00001428 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00001429 int cnt; /* Number of records displayed so far */
1430 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00001431 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00001432 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00001433 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00001434 int cMode; /* temporary output mode for the current query */
1435 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00001436 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00001437 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00001438 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00001439 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00001440 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00001441 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00001442 char colSeparator[20]; /* Column separator character for several modes */
1443 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00001444 int colWidth[100]; /* Requested width of each column when in column mode*/
1445 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00001446 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00001447 ** the database */
drh44c2eb12003-04-30 11:38:26 +00001448 char outfile[FILENAME_MAX]; /* Filename for *out */
1449 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00001450 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00001451 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00001452 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00001453 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00001454 int *aiIndent; /* Array of indents used in MODE_Explain */
1455 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00001456 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00001457#if defined(SQLITE_ENABLE_SESSION)
1458 int nSession; /* Number of active sessions */
1459 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1460#endif
drh75897232000-05-29 14:26:00 +00001461};
1462
1463/*
drh44dec872014-08-30 15:49:25 +00001464** These are the allowed shellFlgs values
1465*/
drhe6e1d122017-03-09 13:50:49 +00001466#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1467#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1468#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1469#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1470#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1471#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1472#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1473
1474/*
1475** Macros for testing and setting shellFlgs
1476*/
1477#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1478#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1479#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00001480
1481/*
drh75897232000-05-29 14:26:00 +00001482** These are the allowed modes.
1483*/
drh967e8b72000-06-21 13:59:10 +00001484#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00001485#define MODE_Column 1 /* One record per line in neat columns */
1486#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00001487#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1488#define MODE_Html 4 /* Generate an XHTML table */
1489#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00001490#define MODE_Quote 6 /* Quote values as for SQL */
1491#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1492#define MODE_Csv 8 /* Quote strings, numbers are plain */
1493#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1494#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1495#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00001496
drh66ce4d02008-02-15 17:38:06 +00001497static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00001498 "line",
1499 "column",
1500 "list",
1501 "semi",
1502 "html",
drhfeac5f82004-08-01 00:10:45 +00001503 "insert",
drh41f5f6e2016-10-21 17:39:30 +00001504 "quote",
drhfeac5f82004-08-01 00:10:45 +00001505 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00001506 "csv",
drh66ce4d02008-02-15 17:38:06 +00001507 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00001508 "ascii",
drh4926fec2016-04-13 15:33:42 +00001509 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00001510};
drh75897232000-05-29 14:26:00 +00001511
1512/*
mistachkinfad42082014-07-24 22:13:12 +00001513** These are the column/row/line separators used by the various
1514** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00001515*/
mistachkinfad42082014-07-24 22:13:12 +00001516#define SEP_Column "|"
1517#define SEP_Row "\n"
1518#define SEP_Tab "\t"
1519#define SEP_Space " "
1520#define SEP_Comma ","
1521#define SEP_CrLf "\r\n"
1522#define SEP_Unit "\x1F"
1523#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00001524
1525/*
drh75897232000-05-29 14:26:00 +00001526** Number of elements in an array
1527*/
drh902b9ee2008-12-05 17:17:07 +00001528#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00001529
1530/*
drh127f9d72010-02-23 01:47:00 +00001531** A callback for the sqlite3_log() interface.
1532*/
1533static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00001534 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00001535 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00001536 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00001537 fflush(p->pLog);
1538}
1539
1540/*
shane626a6e42009-10-22 17:30:15 +00001541** Output the given string as a hex-encoded blob (eg. X'1234' )
1542*/
1543static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1544 int i;
1545 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00001546 raw_printf(out,"X'");
1547 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1548 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00001549}
1550
1551/*
drh6193d492017-04-07 11:45:58 +00001552** Find a string that is not found anywhere in z[]. Return a pointer
1553** to that string.
1554**
1555** Try to use zA and zB first. If both of those are already found in z[]
1556** then make up some string and store it in the buffer zBuf.
1557*/
1558static const char *unused_string(
1559 const char *z, /* Result must not appear anywhere in z */
1560 const char *zA, const char *zB, /* Try these first */
1561 char *zBuf /* Space to store a generated string */
1562){
1563 unsigned i = 0;
1564 if( strstr(z, zA)==0 ) return zA;
1565 if( strstr(z, zB)==0 ) return zB;
1566 do{
1567 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1568 }while( strstr(z,zBuf)!=0 );
1569 return zBuf;
1570}
1571
1572/*
drh28bd4bc2000-06-15 15:57:22 +00001573** Output the given string as a quoted string using SQL quoting conventions.
drh708b22b2017-03-11 01:56:41 +00001574**
drh13fe1382017-04-08 13:42:55 +00001575** See also: output_quoted_escaped_string()
drh28bd4bc2000-06-15 15:57:22 +00001576*/
1577static void output_quoted_string(FILE *out, const char *z){
1578 int i;
drh708b22b2017-03-11 01:56:41 +00001579 char c;
mistachkin1fe36bb2016-04-04 02:16:44 +00001580 setBinaryMode(out, 1);
drh13fe1382017-04-08 13:42:55 +00001581 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1582 if( c==0 ){
1583 utf8_printf(out,"'%s'",z);
1584 }else{
1585 raw_printf(out, "'");
1586 while( *z ){
1587 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
1588 if( c=='\'' ) i++;
1589 if( i ){
1590 utf8_printf(out, "%.*s", i, z);
1591 z += i;
1592 }
1593 if( c=='\'' ){
1594 raw_printf(out, "'");
1595 continue;
1596 }
1597 if( c==0 ){
1598 break;
1599 }
1600 z++;
1601 }
1602 raw_printf(out, "'");
1603 }
1604 setTextMode(out, 1);
1605}
1606
1607/*
1608** Output the given string as a quoted string using SQL quoting conventions.
1609** Additionallly , escape the "\n" and "\r" characters so that they do not
1610** get corrupted by end-of-line translation facilities in some operating
1611** systems.
1612**
1613** This is like output_quoted_string() but with the addition of the \r\n
1614** escape mechanism.
1615*/
1616static void output_quoted_escaped_string(FILE *out, const char *z){
1617 int i;
1618 char c;
1619 setBinaryMode(out, 1);
drh708b22b2017-03-11 01:56:41 +00001620 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1621 if( c==0 ){
drhe05461c2015-12-30 13:36:57 +00001622 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00001623 }else{
drh6193d492017-04-07 11:45:58 +00001624 const char *zNL = 0;
1625 const char *zCR = 0;
1626 int nNL = 0;
1627 int nCR = 0;
1628 char zBuf1[20], zBuf2[20];
1629 for(i=0; z[i]; i++){
1630 if( z[i]=='\n' ) nNL++;
1631 if( z[i]=='\r' ) nCR++;
1632 }
1633 if( nNL ){
1634 raw_printf(out, "replace(");
1635 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1636 }
1637 if( nCR ){
1638 raw_printf(out, "replace(");
1639 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1640 }
1641 raw_printf(out, "'");
drh28bd4bc2000-06-15 15:57:22 +00001642 while( *z ){
drh708b22b2017-03-11 01:56:41 +00001643 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1644 if( c=='\'' ) i++;
1645 if( i ){
drh708b22b2017-03-11 01:56:41 +00001646 utf8_printf(out, "%.*s", i, z);
1647 z += i;
drh708b22b2017-03-11 01:56:41 +00001648 }
1649 if( c=='\'' ){
1650 raw_printf(out, "'");
1651 continue;
1652 }
drh708b22b2017-03-11 01:56:41 +00001653 if( c==0 ){
drh28bd4bc2000-06-15 15:57:22 +00001654 break;
1655 }
drh6193d492017-04-07 11:45:58 +00001656 z++;
1657 if( c=='\n' ){
1658 raw_printf(out, "%s", zNL);
1659 continue;
drh708b22b2017-03-11 01:56:41 +00001660 }
drh6193d492017-04-07 11:45:58 +00001661 raw_printf(out, "%s", zCR);
drh28bd4bc2000-06-15 15:57:22 +00001662 }
drh6193d492017-04-07 11:45:58 +00001663 raw_printf(out, "'");
1664 if( nCR ){
1665 raw_printf(out, ",'%s',char(13))", zCR);
1666 }
1667 if( nNL ){
1668 raw_printf(out, ",'%s',char(10))", zNL);
1669 }
drh28bd4bc2000-06-15 15:57:22 +00001670 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001671 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001672}
1673
1674/*
drhfeac5f82004-08-01 00:10:45 +00001675** Output the given string as a quoted according to C or TCL quoting rules.
1676*/
1677static void output_c_string(FILE *out, const char *z){
1678 unsigned int c;
1679 fputc('"', out);
1680 while( (c = *(z++))!=0 ){
1681 if( c=='\\' ){
1682 fputc(c, out);
1683 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00001684 }else if( c=='"' ){
1685 fputc('\\', out);
1686 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00001687 }else if( c=='\t' ){
1688 fputc('\\', out);
1689 fputc('t', out);
1690 }else if( c=='\n' ){
1691 fputc('\\', out);
1692 fputc('n', out);
1693 }else if( c=='\r' ){
1694 fputc('\\', out);
1695 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00001696 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00001697 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00001698 }else{
1699 fputc(c, out);
1700 }
1701 }
1702 fputc('"', out);
1703}
1704
1705/*
drhc08a4f12000-06-15 16:49:48 +00001706** Output the given string with characters that are special to
1707** HTML escaped.
1708*/
1709static void output_html_string(FILE *out, const char *z){
1710 int i;
drhc3d6ba42014-01-13 20:38:35 +00001711 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00001712 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00001713 for(i=0; z[i]
1714 && z[i]!='<'
1715 && z[i]!='&'
1716 && z[i]!='>'
1717 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00001718 && z[i]!='\'';
1719 i++){}
drhc08a4f12000-06-15 16:49:48 +00001720 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00001721 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00001722 }
1723 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00001724 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00001725 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00001726 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00001727 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00001728 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00001729 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00001730 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00001731 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00001732 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00001733 }else{
1734 break;
1735 }
1736 z += i + 1;
1737 }
1738}
1739
1740/*
drhc49f44e2006-10-26 18:15:42 +00001741** If a field contains any character identified by a 1 in the following
1742** array, then the string must be quoted for CSV.
1743*/
1744static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00001745 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1746 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1747 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1748 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1749 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1750 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1751 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1752 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1753 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1754 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1755 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1756 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1757 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1758 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1759 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1760 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00001761};
1762
1763/*
mistachkindd11f2d2014-12-11 04:49:46 +00001764** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00001765** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00001766** the null value. Strings are quoted if necessary. The separator
1767** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00001768*/
drhdcd87a92014-08-18 13:45:42 +00001769static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00001770 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00001771 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00001772 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00001773 }else{
drhc49f44e2006-10-26 18:15:42 +00001774 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00001775 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00001776 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00001777 if( needCsvQuote[((unsigned char*)z)[i]]
1778 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00001779 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00001780 i = 0;
1781 break;
1782 }
1783 }
1784 if( i==0 ){
1785 putc('"', out);
1786 for(i=0; z[i]; i++){
1787 if( z[i]=='"' ) putc('"', out);
1788 putc(z[i], out);
1789 }
1790 putc('"', out);
1791 }else{
drhe05461c2015-12-30 13:36:57 +00001792 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00001793 }
drh8e64d1c2004-10-07 00:32:39 +00001794 }
1795 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00001796 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001797 }
1798}
1799
danielk19774af00c62005-01-23 23:43:21 +00001800#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00001801/*
drh4c504392000-10-16 22:06:40 +00001802** This routine runs when the user presses Ctrl-C
1803*/
1804static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00001805 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00001806 seenInterrupt++;
1807 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00001808 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00001809}
danielk19774af00c62005-01-23 23:43:21 +00001810#endif
drh4c504392000-10-16 22:06:40 +00001811
drha0daa752016-09-16 11:53:10 +00001812#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00001813/*
drhde613c62016-04-04 17:23:10 +00001814** When the ".auth ON" is set, the following authorizer callback is
1815** invoked. It always returns SQLITE_OK.
1816*/
1817static int shellAuth(
1818 void *pClientData,
1819 int op,
1820 const char *zA1,
1821 const char *zA2,
1822 const char *zA3,
1823 const char *zA4
1824){
1825 ShellState *p = (ShellState*)pClientData;
1826 static const char *azAction[] = { 0,
1827 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1828 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1829 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1830 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1831 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1832 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1833 "PRAGMA", "READ", "SELECT",
1834 "TRANSACTION", "UPDATE", "ATTACH",
1835 "DETACH", "ALTER_TABLE", "REINDEX",
1836 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1837 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1838 };
1839 int i;
1840 const char *az[4];
1841 az[0] = zA1;
1842 az[1] = zA2;
1843 az[2] = zA3;
1844 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00001845 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00001846 for(i=0; i<4; i++){
1847 raw_printf(p->out, " ");
1848 if( az[i] ){
1849 output_c_string(p->out, az[i]);
1850 }else{
1851 raw_printf(p->out, "NULL");
1852 }
1853 }
1854 raw_printf(p->out, "\n");
1855 return SQLITE_OK;
1856}
drha0daa752016-09-16 11:53:10 +00001857#endif
mistachkin8145fc62016-09-16 20:39:21 +00001858
drh79f20e92016-12-13 23:22:39 +00001859/*
1860** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1861**
1862** This routine converts some CREATE TABLE statements for shadow tables
1863** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1864*/
1865static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1866 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1867 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1868 }else{
1869 utf8_printf(out, "%s%s", z, zTail);
1870 }
1871}
1872static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1873 char c = z[n];
1874 z[n] = 0;
1875 printSchemaLine(out, z, zTail);
1876 z[n] = c;
1877}
drhde613c62016-04-04 17:23:10 +00001878
1879/*
shane626a6e42009-10-22 17:30:15 +00001880** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00001881** invokes for each row of a query result.
1882*/
drh4ace5362014-11-10 14:42:28 +00001883static int shell_callback(
1884 void *pArg,
1885 int nArg, /* Number of result columns */
1886 char **azArg, /* Text of each result column */
1887 char **azCol, /* Column names */
1888 int *aiType /* Column types */
1889){
drh75897232000-05-29 14:26:00 +00001890 int i;
drhdcd87a92014-08-18 13:45:42 +00001891 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00001892
drh700c2522016-02-09 18:39:25 +00001893 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00001894 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00001895 int w = 5;
drh6a535342001-10-19 16:44:56 +00001896 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00001897 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00001898 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00001899 if( len>w ) w = len;
1900 }
drhe05461c2015-12-30 13:36:57 +00001901 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001902 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001903 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00001904 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001905 }
1906 break;
1907 }
danielk19770d78bae2008-01-03 07:09:48 +00001908 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00001909 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00001910 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1911 const int *colWidth;
1912 int showHdr;
1913 char *rowSep;
1914 if( p->cMode==MODE_Column ){
1915 colWidth = p->colWidth;
1916 showHdr = p->showHeader;
1917 rowSep = p->rowSeparator;
1918 }else{
1919 colWidth = aExplainWidths;
1920 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00001921 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00001922 }
drha0c66f52000-07-29 13:20:21 +00001923 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00001924 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00001925 int w, n;
1926 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00001927 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00001928 }else{
danielk19770d78bae2008-01-03 07:09:48 +00001929 w = 0;
drh75897232000-05-29 14:26:00 +00001930 }
drh078b1fd2012-09-21 13:40:02 +00001931 if( w==0 ){
drh64bf76d2017-06-05 12:29:26 +00001932 w = strlenChar(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00001933 if( w<10 ) w = 10;
drh64bf76d2017-06-05 12:29:26 +00001934 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00001935 if( w<n ) w = n;
1936 }
1937 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00001938 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00001939 }
drh700c2522016-02-09 18:39:25 +00001940 if( showHdr ){
drh6887e8f2017-04-17 13:18:42 +00001941 utf8_width_print(p->out, w, azCol[i]);
1942 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001943 }
1944 }
drh700c2522016-02-09 18:39:25 +00001945 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00001946 for(i=0; i<nArg; i++){
1947 int w;
1948 if( i<ArraySize(p->actualWidth) ){
1949 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00001950 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00001951 }else{
1952 w = 10;
1953 }
mistachkinaae280e2015-12-31 19:06:24 +00001954 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00001955 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00001956 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00001957 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001958 }
drh75897232000-05-29 14:26:00 +00001959 }
1960 }
drh6a535342001-10-19 16:44:56 +00001961 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00001962 for(i=0; i<nArg; i++){
1963 int w;
drha0c66f52000-07-29 13:20:21 +00001964 if( i<ArraySize(p->actualWidth) ){
1965 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00001966 }else{
1967 w = 10;
1968 }
drh64bf76d2017-06-05 12:29:26 +00001969 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
1970 w = strlenChar(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00001971 }
dana98bf362013-11-13 18:35:01 +00001972 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00001973 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00001974 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00001975 }
danc4650bb2013-11-18 08:41:06 +00001976 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00001977 }
drh6887e8f2017-04-17 13:18:42 +00001978 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
1979 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drh75897232000-05-29 14:26:00 +00001980 }
1981 break;
1982 }
drh4926fec2016-04-13 15:33:42 +00001983 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00001984 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00001985 break;
1986 }
1987 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1988 char *z;
drh07d683f2016-04-13 21:00:36 +00001989 int j;
drh4926fec2016-04-13 15:33:42 +00001990 int nParen = 0;
1991 char cEnd = 0;
1992 char c;
1993 int nLine = 0;
1994 assert( nArg==1 );
1995 if( azArg[0]==0 ) break;
1996 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1997 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1998 ){
1999 utf8_printf(p->out, "%s;\n", azArg[0]);
2000 break;
2001 }
2002 z = sqlite3_mprintf("%s", azArg[0]);
2003 j = 0;
2004 for(i=0; IsSpace(z[i]); i++){}
2005 for(; (c = z[i])!=0; i++){
2006 if( IsSpace(c) ){
2007 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2008 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2009 j--;
2010 }
2011 z[j++] = c;
2012 }
2013 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2014 z[j] = 0;
2015 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00002016 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00002017 if( c==cEnd ){
2018 cEnd = 0;
2019 }else if( c=='"' || c=='\'' || c=='`' ){
2020 cEnd = c;
2021 }else if( c=='[' ){
2022 cEnd = ']';
2023 }else if( c=='(' ){
2024 nParen++;
2025 }else if( c==')' ){
2026 nParen--;
2027 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00002028 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00002029 j = 0;
2030 }
2031 }
2032 z[j++] = c;
2033 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
2034 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00002035 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00002036 j = 0;
2037 nLine++;
2038 while( IsSpace(z[i+1]) ){ i++; }
2039 }
2040 }
2041 z[j] = 0;
2042 }
drh79f20e92016-12-13 23:22:39 +00002043 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00002044 sqlite3_free(z);
2045 break;
2046 }
drh75897232000-05-29 14:26:00 +00002047 case MODE_List: {
2048 if( p->cnt++==0 && p->showHeader ){
2049 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002050 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00002051 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00002052 }
2053 }
drh6a535342001-10-19 16:44:56 +00002054 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002055 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00002056 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00002057 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00002058 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00002059 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00002060 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00002061 }else{
drhe05461c2015-12-30 13:36:57 +00002062 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00002063 }
drh75897232000-05-29 14:26:00 +00002064 }
2065 break;
2066 }
drh1e5d0e92000-05-31 23:33:17 +00002067 case MODE_Html: {
2068 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00002069 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002070 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002071 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00002072 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00002073 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00002074 }
mistachkinaae280e2015-12-31 19:06:24 +00002075 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002076 }
drh6a535342001-10-19 16:44:56 +00002077 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00002078 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002079 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002080 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00002081 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00002082 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00002083 }
mistachkinaae280e2015-12-31 19:06:24 +00002084 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002085 break;
2086 }
drhfeac5f82004-08-01 00:10:45 +00002087 case MODE_Tcl: {
2088 if( p->cnt++==0 && p->showHeader ){
2089 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002090 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00002091 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002092 }
drhe05461c2015-12-30 13:36:57 +00002093 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002094 }
2095 if( azArg==0 ) break;
2096 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00002097 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00002098 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002099 }
drhe05461c2015-12-30 13:36:57 +00002100 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002101 break;
2102 }
drh8e64d1c2004-10-07 00:32:39 +00002103 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00002104 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002105 if( p->cnt++==0 && p->showHeader ){
2106 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002107 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00002108 }
drhe05461c2015-12-30 13:36:57 +00002109 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002110 }
drh40253262014-10-17 21:35:05 +00002111 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00002112 for(i=0; i<nArg; i++){
2113 output_csv(p, azArg[i], i<nArg-1);
2114 }
drhe05461c2015-12-30 13:36:57 +00002115 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002116 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002117 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002118 break;
2119 }
drh28bd4bc2000-06-15 15:57:22 +00002120 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00002121 if( azArg==0 ) break;
drh13fe1382017-04-08 13:42:55 +00002122 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2123 if( p->showHeader ){
2124 raw_printf(p->out,"(");
2125 for(i=0; i<nArg; i++){
2126 if( i>0 ) raw_printf(p->out, ",");
2127 if( quoteChar(azCol[i]) ){
2128 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2129 utf8_printf(p->out, "%s", z);
2130 sqlite3_free(z);
2131 }else{
2132 raw_printf(p->out, "%s", azCol[i]);
drh41f5f6e2016-10-21 17:39:30 +00002133 }
mistachkin151c75a2015-04-07 21:16:40 +00002134 }
drh13fe1382017-04-08 13:42:55 +00002135 raw_printf(p->out,")");
2136 }
2137 p->cnt++;
2138 for(i=0; i<nArg; i++){
2139 raw_printf(p->out, i>0 ? "," : " VALUES(");
2140 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2141 utf8_printf(p->out,"NULL");
2142 }else if( aiType && aiType[i]==SQLITE_TEXT ){
2143 output_quoted_escaped_string(p->out, azArg[i]);
2144 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2145 utf8_printf(p->out,"%s", azArg[i]);
2146 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2147 char z[50];
2148 double r = sqlite3_column_double(p->pStmt, i);
2149 sqlite3_snprintf(50,z,"%!.20g", r);
2150 raw_printf(p->out, "%s", z);
2151 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2152 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2153 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2154 output_hex_blob(p->out, pBlob, nBlob);
2155 }else if( isNumber(azArg[i], 0) ){
2156 utf8_printf(p->out,"%s", azArg[i]);
2157 }else{
2158 output_quoted_escaped_string(p->out, azArg[i]);
2159 }
2160 }
2161 raw_printf(p->out,");\n");
2162 break;
2163 }
2164 case MODE_Quote: {
2165 if( azArg==0 ) break;
2166 if( p->cnt==0 && p->showHeader ){
drh59ce2c42016-11-03 13:12:28 +00002167 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00002168 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00002169 output_quoted_string(p->out, azCol[i]);
2170 }
mistachkin2f9a6132016-11-11 05:19:45 +00002171 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002172 }
drh59ce2c42016-11-03 13:12:28 +00002173 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002174 for(i=0; i<nArg; i++){
drh13fe1382017-04-08 13:42:55 +00002175 if( i>0 ) raw_printf(p->out, ",");
shanead6b8d02009-10-22 18:12:58 +00002176 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
drh13fe1382017-04-08 13:42:55 +00002177 utf8_printf(p->out,"NULL");
shanead6b8d02009-10-22 18:12:58 +00002178 }else if( aiType && aiType[i]==SQLITE_TEXT ){
shanead6b8d02009-10-22 18:12:58 +00002179 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002180 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drh13fe1382017-04-08 13:42:55 +00002181 utf8_printf(p->out,"%s", azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002182 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2183 char z[50];
2184 double r = sqlite3_column_double(p->pStmt, i);
2185 sqlite3_snprintf(50,z,"%!.20g", r);
drh13fe1382017-04-08 13:42:55 +00002186 raw_printf(p->out, "%s", z);
shane626a6e42009-10-22 17:30:15 +00002187 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2188 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2189 int nBlob = sqlite3_column_bytes(p->pStmt, i);
shane626a6e42009-10-22 17:30:15 +00002190 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002191 }else if( isNumber(azArg[i], 0) ){
drh13fe1382017-04-08 13:42:55 +00002192 utf8_printf(p->out,"%s", azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002193 }else{
drh28bd4bc2000-06-15 15:57:22 +00002194 output_quoted_string(p->out, azArg[i]);
2195 }
2196 }
drh13fe1382017-04-08 13:42:55 +00002197 raw_printf(p->out,"\n");
drh6a535342001-10-19 16:44:56 +00002198 break;
drh28bd4bc2000-06-15 15:57:22 +00002199 }
mistachkin636bf9f2014-07-19 20:15:16 +00002200 case MODE_Ascii: {
2201 if( p->cnt++==0 && p->showHeader ){
2202 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002203 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2204 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002205 }
drhe05461c2015-12-30 13:36:57 +00002206 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002207 }
2208 if( azArg==0 ) break;
2209 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002210 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2211 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002212 }
drhe05461c2015-12-30 13:36:57 +00002213 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002214 break;
2215 }
persicom1d0b8722002-04-18 02:53:04 +00002216 }
drh75897232000-05-29 14:26:00 +00002217 return 0;
2218}
2219
2220/*
shane626a6e42009-10-22 17:30:15 +00002221** This is the callback routine that the SQLite library
2222** invokes for each row of a query result.
2223*/
2224static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2225 /* since we don't have type info, call the shell_callback with a NULL value */
2226 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2227}
2228
drhfb546af2017-03-09 22:00:33 +00002229/*
2230** This is the callback routine from sqlite3_exec() that appends all
2231** output onto the end of a ShellText object.
2232*/
2233static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2234 ShellText *p = (ShellText*)pArg;
2235 int i;
drh2fb79e92017-03-25 12:08:11 +00002236 UNUSED_PARAMETER(az);
drhfb546af2017-03-09 22:00:33 +00002237 if( p->n ) appendText(p, "|", 0);
2238 for(i=0; i<nArg; i++){
2239 if( i ) appendText(p, ",", 0);
2240 if( azArg[i] ) appendText(p, azArg[i], 0);
2241 }
2242 return 0;
2243}
2244
2245/*
2246** Generate an appropriate SELFTEST table in the main database.
2247*/
2248static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00002249 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00002250 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00002251 "SAVEPOINT selftest_init;\n"
2252 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00002253 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2254 " op TEXT,\n" /* Operator: memo run */
2255 " cmd TEXT,\n" /* Command text */
2256 " ans TEXT\n" /* Desired answer */
2257 ");"
drhf157d102017-03-10 01:05:38 +00002258 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2259 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2260 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2261 " 'memo','Tests generated by --init');\n"
2262 "INSERT INTO [_shell$self]\n"
2263 " SELECT 'run',\n"
2264 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2265 "FROM sqlite_master ORDER BY 2'',224))',\n"
2266 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2267 "FROM sqlite_master ORDER BY 2',224));\n"
2268 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002269 " SELECT 'run',"
2270 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2271 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2272 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2273 " FROM (\n"
2274 " SELECT name FROM sqlite_master\n"
2275 " WHERE type='table'\n"
2276 " AND name<>'selftest'\n"
2277 " AND coalesce(rootpage,0)>0\n"
2278 " )\n"
2279 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00002280 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002281 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00002282 "INSERT INTO selftest(tno,op,cmd,ans)"
2283 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2284 "DROP TABLE [_shell$self];"
2285 ,0,0,&zErrMsg);
2286 if( zErrMsg ){
2287 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2288 sqlite3_free(zErrMsg);
2289 }
2290 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00002291}
2292
drhf42d3182017-03-08 12:25:18 +00002293
shane626a6e42009-10-22 17:30:15 +00002294/*
drhdcd87a92014-08-18 13:45:42 +00002295** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00002296** the name of the table given. Escape any quote characters in the
2297** table name.
2298*/
drhdcd87a92014-08-18 13:45:42 +00002299static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00002300 int i, n;
drhf42d3182017-03-08 12:25:18 +00002301 int cQuote;
drh33048c02001-10-01 14:29:22 +00002302 char *z;
2303
2304 if( p->zDestTable ){
2305 free(p->zDestTable);
2306 p->zDestTable = 0;
2307 }
2308 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00002309 cQuote = quoteChar(zName);
2310 n = strlen30(zName);
2311 if( cQuote ) n += 2;
drh33048c02001-10-01 14:29:22 +00002312 z = p->zDestTable = malloc( n+1 );
2313 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002314 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00002315 exit(1);
2316 }
2317 n = 0;
drhf42d3182017-03-08 12:25:18 +00002318 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002319 for(i=0; zName[i]; i++){
2320 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00002321 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002322 }
drhf42d3182017-03-08 12:25:18 +00002323 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002324 z[n] = 0;
2325}
2326
drhdd3d4592004-08-30 01:54:05 +00002327
2328/*
drhb21a8e42012-01-28 21:08:51 +00002329** Execute a query statement that will generate SQL output. Print
2330** the result columns, comma-separated, on a line and then add a
2331** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00002332**
drhb21a8e42012-01-28 21:08:51 +00002333** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00002334** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00002335** "--" comment occurs at the end of the statement, the comment
2336** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00002337*/
drh157e29a2009-05-21 15:15:00 +00002338static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00002339 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00002340 const char *zSelect, /* SELECT statement to extract content */
2341 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00002342){
drhdd3d4592004-08-30 01:54:05 +00002343 sqlite3_stmt *pSelect;
2344 int rc;
drhb21a8e42012-01-28 21:08:51 +00002345 int nResult;
2346 int i;
2347 const char *z;
drhc7181902014-02-27 15:04:13 +00002348 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00002349 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00002350 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2351 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002352 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00002353 return rc;
2354 }
2355 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00002356 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00002357 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00002358 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00002359 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00002360 zFirstRow = 0;
2361 }
drhb21a8e42012-01-28 21:08:51 +00002362 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00002363 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00002364 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00002365 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00002366 }
2367 if( z==0 ) z = "";
2368 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2369 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00002370 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00002371 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002372 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00002373 }
drhdd3d4592004-08-30 01:54:05 +00002374 rc = sqlite3_step(pSelect);
2375 }
drh2f464a02011-10-13 00:41:49 +00002376 rc = sqlite3_finalize(pSelect);
2377 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00002378 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2379 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002380 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00002381 }
2382 return rc;
drhdd3d4592004-08-30 01:54:05 +00002383}
2384
shane626a6e42009-10-22 17:30:15 +00002385/*
2386** Allocate space and save off current error string.
2387*/
2388static char *save_err_msg(
2389 sqlite3 *db /* Database to query */
2390){
2391 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00002392 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00002393 if( zErrMsg ){
2394 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2395 }
2396 return zErrMsg;
2397}
2398
drh34784902016-02-27 17:12:36 +00002399#ifdef __linux__
2400/*
2401** Attempt to display I/O stats on Linux using /proc/PID/io
2402*/
2403static void displayLinuxIoStats(FILE *out){
2404 FILE *in;
2405 char z[200];
2406 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2407 in = fopen(z, "rb");
2408 if( in==0 ) return;
2409 while( fgets(z, sizeof(z), in)!=0 ){
2410 static const struct {
2411 const char *zPattern;
2412 const char *zDesc;
2413 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00002414 { "rchar: ", "Bytes received by read():" },
2415 { "wchar: ", "Bytes sent to write():" },
2416 { "syscr: ", "Read() system calls:" },
2417 { "syscw: ", "Write() system calls:" },
2418 { "read_bytes: ", "Bytes read from storage:" },
2419 { "write_bytes: ", "Bytes written to storage:" },
2420 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00002421 };
2422 int i;
2423 for(i=0; i<ArraySize(aTrans); i++){
2424 int n = (int)strlen(aTrans[i].zPattern);
2425 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00002426 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00002427 break;
2428 }
2429 }
2430 }
2431 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00002432}
drh34784902016-02-27 17:12:36 +00002433#endif
2434
drha2df53b2017-03-10 14:36:10 +00002435/*
2436** Display a single line of status using 64-bit values.
2437*/
2438static void displayStatLine(
2439 ShellState *p, /* The shell context */
2440 char *zLabel, /* Label for this one line */
2441 char *zFormat, /* Format for the result */
2442 int iStatusCtrl, /* Which status to display */
2443 int bReset /* True to reset the stats */
2444){
2445 sqlite3_int64 iCur = -1;
2446 sqlite3_int64 iHiwtr = -1;
2447 int i, nPercent;
2448 char zLine[200];
2449 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2450 for(i=0, nPercent=0; zFormat[i]; i++){
2451 if( zFormat[i]=='%' ) nPercent++;
2452 }
2453 if( nPercent>1 ){
2454 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2455 }else{
2456 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2457 }
2458 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2459}
drh34784902016-02-27 17:12:36 +00002460
shane626a6e42009-10-22 17:30:15 +00002461/*
shaneh642d8b82010-07-28 16:05:34 +00002462** Display memory stats.
2463*/
2464static int display_stats(
2465 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00002466 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00002467 int bReset /* True to reset the stats */
2468){
2469 int iCur;
2470 int iHiwtr;
2471
2472 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00002473 displayStatLine(pArg, "Memory Used:",
2474 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2475 displayStatLine(pArg, "Number of Outstanding Allocations:",
2476 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00002477 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00002478 displayStatLine(pArg, "Number of Pcache Pages Used:",
2479 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002480 }
drha2df53b2017-03-10 14:36:10 +00002481 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2482 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh44dec872014-08-30 15:49:25 +00002483 if( pArg->shellFlgs & SHFLG_Scratch ){
drha2df53b2017-03-10 14:36:10 +00002484 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2485 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002486 }
drha2df53b2017-03-10 14:36:10 +00002487 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2488 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2489 displayStatLine(pArg, "Largest Allocation:",
2490 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2491 displayStatLine(pArg, "Largest Pcache Allocation:",
2492 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2493 displayStatLine(pArg, "Largest Scratch Allocation:",
2494 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002495#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00002496 displayStatLine(pArg, "Deepest Parser Stack:",
2497 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002498#endif
2499 }
2500
2501 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00002502 if( pArg->shellFlgs & SHFLG_Lookaside ){
2503 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00002504 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2505 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002506 raw_printf(pArg->out,
2507 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00002508 iCur, iHiwtr);
2509 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2510 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002511 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2512 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002513 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2514 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002515 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2516 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002517 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2518 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002519 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2520 iHiwtr);
drh44dec872014-08-30 15:49:25 +00002521 }
shaneh642d8b82010-07-28 16:05:34 +00002522 iHiwtr = iCur = -1;
2523 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002524 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2525 iCur);
drh4ace5362014-11-10 14:42:28 +00002526 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00002527 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00002528 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00002529 iHiwtr = iCur = -1;
2530 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002531 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002532 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00002533 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002534 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00002535 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00002536 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002537 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002538 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002539 iHiwtr = iCur = -1;
2540 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002541 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002542 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002543 }
2544
2545 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00002546 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2547 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002548 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002549 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002550 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00002551 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002552 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00002553 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002554 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002555 }
2556
drh34784902016-02-27 17:12:36 +00002557#ifdef __linux__
2558 displayLinuxIoStats(pArg->out);
2559#endif
2560
dan5a790282015-08-07 20:06:14 +00002561 /* Do not remove this machine readable comment: extra-stats-output-here */
2562
shaneh642d8b82010-07-28 16:05:34 +00002563 return 0;
2564}
2565
2566/*
dan8d1edb92014-11-05 09:07:28 +00002567** Display scan stats.
2568*/
2569static void display_scanstats(
2570 sqlite3 *db, /* Database to query */
2571 ShellState *pArg /* Pointer to ShellState */
2572){
drhf5ed7ad2015-06-15 14:43:25 +00002573#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2574 UNUSED_PARAMETER(db);
2575 UNUSED_PARAMETER(pArg);
2576#else
drh15f23c22014-11-06 12:46:16 +00002577 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00002578 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00002579 mx = 0;
2580 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00002581 double rEstLoop = 1.0;
2582 for(i=n=0; 1; i++){
2583 sqlite3_stmt *p = pArg->pStmt;
2584 sqlite3_int64 nLoop, nVisit;
2585 double rEst;
2586 int iSid;
2587 const char *zExplain;
2588 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2589 break;
2590 }
2591 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00002592 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00002593 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00002594 if( n==0 ){
2595 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00002596 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00002597 }
drh42f30bc2014-11-06 12:08:21 +00002598 n++;
2599 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2600 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2601 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00002602 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00002603 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00002604 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00002605 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00002606 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00002607 );
dan8d1edb92014-11-05 09:07:28 +00002608 }
dan8d1edb92014-11-05 09:07:28 +00002609 }
mistachkinaae280e2015-12-31 19:06:24 +00002610 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00002611#endif
dan8d1edb92014-11-05 09:07:28 +00002612}
2613
2614/*
dana98bf362013-11-13 18:35:01 +00002615** Parameter azArray points to a zero-terminated array of strings. zStr
2616** points to a single nul-terminated string. Return non-zero if zStr
2617** is equal, according to strcmp(), to any of the strings in the array.
2618** Otherwise, return zero.
2619*/
2620static int str_in_array(const char *zStr, const char **azArray){
2621 int i;
2622 for(i=0; azArray[i]; i++){
2623 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2624 }
2625 return 0;
2626}
2627
2628/*
2629** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00002630** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00002631** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00002632**
2633** The indenting rules are:
2634**
2635** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2636** all opcodes that occur between the p2 jump destination and the opcode
2637** itself by 2 spaces.
2638**
drh01752bc2013-11-14 23:59:33 +00002639** * For each "Goto", if the jump destination is earlier in the program
2640** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00002641** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00002642** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00002643** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00002644** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00002645*/
drhdcd87a92014-08-18 13:45:42 +00002646static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00002647 const char *zSql; /* The text of the SQL statement */
2648 const char *z; /* Used to check if this is an EXPLAIN */
2649 int *abYield = 0; /* True if op is an OP_Yield */
2650 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00002651 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00002652
drh8ad0de32014-03-20 18:45:27 +00002653 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2654 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00002655 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2656 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00002657 const char *azGoto[] = { "Goto", 0 };
2658
2659 /* Try to figure out if this is really an EXPLAIN statement. If this
2660 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00002661 if( sqlite3_column_count(pSql)!=8 ){
2662 p->cMode = p->mode;
2663 return;
2664 }
dana98bf362013-11-13 18:35:01 +00002665 zSql = sqlite3_sql(pSql);
2666 if( zSql==0 ) return;
2667 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00002668 if( sqlite3_strnicmp(z, "explain", 7) ){
2669 p->cMode = p->mode;
2670 return;
2671 }
dana98bf362013-11-13 18:35:01 +00002672
2673 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2674 int i;
danc4650bb2013-11-18 08:41:06 +00002675 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00002676 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00002677
2678 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2679 ** p2 is an instruction address, set variable p2op to the index of that
2680 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2681 ** the current instruction is part of a sub-program generated by an
2682 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00002683 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00002684 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00002685
2686 /* Grow the p->aiIndent array as required */
2687 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00002688 if( iOp==0 ){
2689 /* Do further verfication that this is explain output. Abort if
2690 ** it is not */
2691 static const char *explainCols[] = {
2692 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2693 int jj;
2694 for(jj=0; jj<ArraySize(explainCols); jj++){
2695 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2696 p->cMode = p->mode;
2697 sqlite3_reset(pSql);
2698 return;
2699 }
2700 }
2701 }
dana98bf362013-11-13 18:35:01 +00002702 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00002703 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2704 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00002705 }
2706 abYield[iOp] = str_in_array(zOp, azYield);
2707 p->aiIndent[iOp] = 0;
2708 p->nIndent = iOp+1;
2709
2710 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00002711 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002712 }
drhfe705102014-03-06 13:38:37 +00002713 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2714 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2715 ){
drheacd29d2016-04-15 15:03:27 +00002716 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002717 }
2718 }
2719
danc4650bb2013-11-18 08:41:06 +00002720 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002721 sqlite3_free(abYield);
2722 sqlite3_reset(pSql);
2723}
2724
2725/*
2726** Free the array allocated by explain_data_prepare().
2727*/
drhdcd87a92014-08-18 13:45:42 +00002728static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00002729 sqlite3_free(p->aiIndent);
2730 p->aiIndent = 0;
2731 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00002732 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002733}
2734
2735/*
drheacd29d2016-04-15 15:03:27 +00002736** Disable and restore .wheretrace and .selecttrace settings.
2737*/
2738#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2739extern int sqlite3SelectTrace;
2740static int savedSelectTrace;
2741#endif
2742#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2743extern int sqlite3WhereTrace;
2744static int savedWhereTrace;
2745#endif
2746static void disable_debug_trace_modes(void){
2747#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2748 savedSelectTrace = sqlite3SelectTrace;
2749 sqlite3SelectTrace = 0;
2750#endif
2751#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2752 savedWhereTrace = sqlite3WhereTrace;
2753 sqlite3WhereTrace = 0;
2754#endif
2755}
2756static void restore_debug_trace_modes(void){
2757#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2758 sqlite3SelectTrace = savedSelectTrace;
2759#endif
2760#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2761 sqlite3WhereTrace = savedWhereTrace;
2762#endif
2763}
2764
2765/*
2766** Run a prepared statement
2767*/
2768static void exec_prepared_stmt(
2769 ShellState *pArg, /* Pointer to ShellState */
2770 sqlite3_stmt *pStmt, /* Statment to run */
2771 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2772){
2773 int rc;
2774
2775 /* perform the first step. this will tell us if we
2776 ** have a result set or not and how wide it is.
2777 */
2778 rc = sqlite3_step(pStmt);
2779 /* if we have a result set... */
2780 if( SQLITE_ROW == rc ){
2781 /* if we have a callback... */
2782 if( xCallback ){
2783 /* allocate space for col name ptr, value ptr, and type */
2784 int nCol = sqlite3_column_count(pStmt);
2785 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2786 if( !pData ){
2787 rc = SQLITE_NOMEM;
2788 }else{
2789 char **azCols = (char **)pData; /* Names of result columns */
2790 char **azVals = &azCols[nCol]; /* Results */
2791 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2792 int i, x;
2793 assert(sizeof(int) <= sizeof(char *));
2794 /* save off ptrs to column names */
2795 for(i=0; i<nCol; i++){
2796 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2797 }
2798 do{
2799 /* extract the data and data types */
2800 for(i=0; i<nCol; i++){
2801 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2802 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2803 azVals[i] = "";
2804 }else{
2805 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2806 }
2807 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2808 rc = SQLITE_NOMEM;
2809 break; /* from for */
2810 }
2811 } /* end for */
2812
2813 /* if data and types extracted successfully... */
2814 if( SQLITE_ROW == rc ){
2815 /* call the supplied callback with the result row data */
2816 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2817 rc = SQLITE_ABORT;
2818 }else{
2819 rc = sqlite3_step(pStmt);
2820 }
2821 }
2822 } while( SQLITE_ROW == rc );
2823 sqlite3_free(pData);
2824 }
2825 }else{
2826 do{
2827 rc = sqlite3_step(pStmt);
2828 } while( rc == SQLITE_ROW );
2829 }
2830 }
2831}
2832
2833/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002834** Execute a statement or set of statements. Print
2835** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00002836** set via the supplied callback.
2837**
mistachkin1fe36bb2016-04-04 02:16:44 +00002838** This is very similar to SQLite's built-in sqlite3_exec()
2839** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00002840** and callback data argument.
2841*/
2842static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00002843 sqlite3 *db, /* An open database */
2844 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00002845 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00002846 /* (not the same as sqlite3_exec) */
2847 ShellState *pArg, /* Pointer to ShellState */
2848 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00002849){
dan4564ced2010-01-05 04:59:56 +00002850 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2851 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00002852 int rc2;
dan4564ced2010-01-05 04:59:56 +00002853 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00002854
2855 if( pzErrMsg ){
2856 *pzErrMsg = NULL;
2857 }
2858
shaneb9fc17d2009-10-22 21:23:35 +00002859 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00002860 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00002861 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2862 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00002863 if( pzErrMsg ){
2864 *pzErrMsg = save_err_msg(db);
2865 }
2866 }else{
shaneb9fc17d2009-10-22 21:23:35 +00002867 if( !pStmt ){
2868 /* this happens for a comment or white-space */
2869 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002870 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00002871 continue;
2872 }
drheacd29d2016-04-15 15:03:27 +00002873 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00002874 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00002875 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00002876
shaneh642d8b82010-07-28 16:05:34 +00002877 /* save off the prepared statment handle and reset row count */
2878 if( pArg ){
2879 pArg->pStmt = pStmt;
2880 pArg->cnt = 0;
2881 }
2882
shanehb7977c52010-01-18 18:17:10 +00002883 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00002884 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00002885 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00002886 }
shanehb7977c52010-01-18 18:17:10 +00002887
drhefbf3b12014-02-28 20:47:24 +00002888 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00002889 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00002890 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00002891 char *zEQP;
2892 disable_debug_trace_modes();
2893 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00002894 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2895 if( rc==SQLITE_OK ){
2896 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00002897 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2898 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2899 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00002900 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00002901 }
2902 }
2903 sqlite3_finalize(pExplain);
2904 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00002905 if( pArg->autoEQP>=2 ){
2906 /* Also do an EXPLAIN for ".eqp full" mode */
2907 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2908 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2909 if( rc==SQLITE_OK ){
2910 pArg->cMode = MODE_Explain;
2911 explain_data_prepare(pArg, pExplain);
2912 exec_prepared_stmt(pArg, pExplain, xCallback);
2913 explain_data_delete(pArg);
2914 }
2915 sqlite3_finalize(pExplain);
2916 sqlite3_free(zEQP);
2917 }
2918 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00002919 }
2920
drh700c2522016-02-09 18:39:25 +00002921 if( pArg ){
2922 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00002923 if( pArg->autoExplain
2924 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00002925 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00002926 ){
2927 pArg->cMode = MODE_Explain;
2928 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002929
drh700c2522016-02-09 18:39:25 +00002930 /* If the shell is currently in ".explain" mode, gather the extra
2931 ** data required to add indents to the output.*/
2932 if( pArg->cMode==MODE_Explain ){
2933 explain_data_prepare(pArg, pStmt);
2934 }
dana98bf362013-11-13 18:35:01 +00002935 }
2936
drheacd29d2016-04-15 15:03:27 +00002937 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00002938 explain_data_delete(pArg);
2939
shaneh642d8b82010-07-28 16:05:34 +00002940 /* print usage stats if stats on */
2941 if( pArg && pArg->statsOn ){
2942 display_stats(db, pArg, 0);
2943 }
2944
dan8d1edb92014-11-05 09:07:28 +00002945 /* print loop-counters if required */
2946 if( pArg && pArg->scanstatsOn ){
2947 display_scanstats(db, pArg);
2948 }
2949
mistachkin1fe36bb2016-04-04 02:16:44 +00002950 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00002951 ** copy of the error message. Otherwise, set zSql to point to the
2952 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00002953 rc2 = sqlite3_finalize(pStmt);
2954 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00002955 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00002956 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002957 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00002958 }else if( pzErrMsg ){
2959 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00002960 }
shaneh642d8b82010-07-28 16:05:34 +00002961
2962 /* clear saved stmt handle */
2963 if( pArg ){
2964 pArg->pStmt = NULL;
2965 }
shane626a6e42009-10-22 17:30:15 +00002966 }
shaneb9fc17d2009-10-22 21:23:35 +00002967 } /* end while */
shane626a6e42009-10-22 17:30:15 +00002968
2969 return rc;
2970}
2971
drhe611f142017-03-08 11:44:00 +00002972/*
2973** Release memory previously allocated by tableColumnList().
2974*/
2975static void freeColumnList(char **azCol){
2976 int i;
2977 for(i=1; azCol[i]; i++){
2978 sqlite3_free(azCol[i]);
2979 }
2980 /* azCol[0] is a static string */
2981 sqlite3_free(azCol);
2982}
2983
2984/*
2985** Return a list of pointers to strings which are the names of all
2986** columns in table zTab. The memory to hold the names is dynamically
2987** allocated and must be released by the caller using a subsequent call
2988** to freeColumnList().
2989**
2990** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2991** value that needs to be preserved, then azCol[0] is filled in with the
2992** name of the rowid column.
2993**
2994** The first regular column in the table is azCol[1]. The list is terminated
2995** by an entry with azCol[i]==0.
2996*/
2997static char **tableColumnList(ShellState *p, const char *zTab){
2998 char **azCol = 0;
2999 sqlite3_stmt *pStmt;
3000 char *zSql;
3001 int nCol = 0;
3002 int nAlloc = 0;
3003 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3004 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00003005 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00003006 int rc;
3007
3008 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3009 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3010 sqlite3_free(zSql);
3011 if( rc ) return 0;
3012 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3013 if( nCol>=nAlloc-2 ){
3014 nAlloc = nAlloc*2 + nCol + 10;
3015 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3016 if( azCol==0 ){
3017 raw_printf(stderr, "Error: out of memory\n");
3018 exit(1);
3019 }
3020 }
3021 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3022 if( sqlite3_column_int(pStmt, 5) ){
3023 nPK++;
3024 if( nPK==1
3025 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
mistachkine16a3502017-05-29 03:48:13 +00003026 "INTEGER")==0
drhe611f142017-03-08 11:44:00 +00003027 ){
3028 isIPK = 1;
3029 }else{
3030 isIPK = 0;
3031 }
3032 }
3033 }
3034 sqlite3_finalize(pStmt);
3035 azCol[0] = 0;
3036 azCol[nCol+1] = 0;
3037
3038 /* The decision of whether or not a rowid really needs to be preserved
3039 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3040 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3041 ** rowids on tables where the rowid is inaccessible because there are other
3042 ** columns in the table named "rowid", "_rowid_", and "oid".
3043 */
3044 if( preserveRowid && isIPK ){
3045 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3046 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3047 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3048 ** ROWID aliases. To distinguish these cases, check to see if
3049 ** there is a "pk" entry in "PRAGMA index_list". There will be
3050 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3051 */
3052 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3053 " WHERE origin='pk'", zTab);
3054 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3055 sqlite3_free(zSql);
3056 if( rc ){
3057 freeColumnList(azCol);
3058 return 0;
3059 }
3060 rc = sqlite3_step(pStmt);
3061 sqlite3_finalize(pStmt);
3062 preserveRowid = rc==SQLITE_ROW;
3063 }
3064 if( preserveRowid ){
3065 /* Only preserve the rowid if we can find a name to use for the
3066 ** rowid */
3067 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3068 int i, j;
3069 for(j=0; j<3; j++){
3070 for(i=1; i<=nCol; i++){
3071 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3072 }
3073 if( i>nCol ){
3074 /* At this point, we know that azRowid[j] is not the name of any
3075 ** ordinary column in the table. Verify that azRowid[j] is a valid
3076 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3077 ** tables will fail this last check */
drhe611f142017-03-08 11:44:00 +00003078 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3079 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3080 break;
3081 }
3082 }
3083 }
3084 return azCol;
3085}
3086
drh33048c02001-10-01 14:29:22 +00003087/*
drhf8563c02017-03-09 18:13:52 +00003088** Toggle the reverse_unordered_selects setting.
3089*/
3090static void toggleSelectOrder(sqlite3 *db){
3091 sqlite3_stmt *pStmt = 0;
3092 int iSetting = 0;
3093 char zStmt[100];
3094 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3095 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3096 iSetting = sqlite3_column_int(pStmt, 0);
3097 }
3098 sqlite3_finalize(pStmt);
3099 sqlite3_snprintf(sizeof(zStmt), zStmt,
3100 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3101 sqlite3_exec(db, zStmt, 0, 0, 0);
3102}
3103
3104/*
drh4c653a02000-06-07 01:27:47 +00003105** This is a different callback routine used for dumping the database.
3106** Each row received by this callback consists of a table name,
3107** the table type ("index" or "table") and SQL to create the table.
3108** This routine should print text sufficient to recreate the table.
3109*/
drh701ff6a2017-03-22 12:51:34 +00003110static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
danielk19772a02e332004-06-05 08:04:36 +00003111 int rc;
3112 const char *zTable;
3113 const char *zType;
3114 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00003115 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00003116
drh701ff6a2017-03-22 12:51:34 +00003117 UNUSED_PARAMETER(azNotUsed);
drh4c653a02000-06-07 01:27:47 +00003118 if( nArg!=3 ) return 1;
danielk19772a02e332004-06-05 08:04:36 +00003119 zTable = azArg[0];
3120 zType = azArg[1];
3121 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00003122
drh00b950d2005-09-11 02:03:03 +00003123 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00003124 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00003125 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003126 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00003127 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3128 return 0;
drh45e29d82006-11-20 16:21:10 +00003129 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3130 char *zIns;
3131 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00003132 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00003133 p->writableSchema = 1;
3134 }
3135 zIns = sqlite3_mprintf(
3136 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3137 "VALUES('table','%q','%q',0,'%q');",
3138 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00003139 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00003140 sqlite3_free(zIns);
3141 return 0;
drh00b950d2005-09-11 02:03:03 +00003142 }else{
drh79f20e92016-12-13 23:22:39 +00003143 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00003144 }
danielk19772a02e332004-06-05 08:04:36 +00003145
3146 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00003147 ShellText sSelect;
3148 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00003149 char **azCol;
3150 int i;
3151 char *savedDestTable;
3152 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00003153
drhe611f142017-03-08 11:44:00 +00003154 azCol = tableColumnList(p, zTable);
3155 if( azCol==0 ){
3156 p->nErr++;
3157 return 0;
danielk19772a02e332004-06-05 08:04:36 +00003158 }
3159
drhbf92ec02012-03-22 12:50:34 +00003160 /* Always quote the table name, even if it appears to be pure ascii,
3161 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00003162 initText(&sTable);
3163 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003164 /* If preserving the rowid, add a column list after the table name.
3165 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3166 ** instead of the usual "INSERT INTO tab VALUES(...)".
3167 */
3168 if( azCol[0] ){
3169 appendText(&sTable, "(", 0);
3170 appendText(&sTable, azCol[0], 0);
3171 for(i=1; azCol[i]; i++){
3172 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003173 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003174 }
drhe611f142017-03-08 11:44:00 +00003175 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003176 }
danielk19772a02e332004-06-05 08:04:36 +00003177
drhe611f142017-03-08 11:44:00 +00003178 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003179 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003180 appendText(&sSelect, "SELECT ", 0);
3181 if( azCol[0] ){
3182 appendText(&sSelect, azCol[0], 0);
3183 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003184 }
drhe611f142017-03-08 11:44:00 +00003185 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003186 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003187 if( azCol[i+1] ){
3188 appendText(&sSelect, ",", 0);
3189 }
3190 }
3191 freeColumnList(azCol);
3192 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003193 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003194
3195 savedDestTable = p->zDestTable;
3196 savedMode = p->mode;
3197 p->zDestTable = sTable.z;
3198 p->mode = p->cMode = MODE_Insert;
3199 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003200 if( (rc&0xff)==SQLITE_CORRUPT ){
3201 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3202 toggleSelectOrder(p->db);
3203 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3204 toggleSelectOrder(p->db);
3205 }
drhe611f142017-03-08 11:44:00 +00003206 p->zDestTable = savedDestTable;
3207 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003208 freeText(&sTable);
3209 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003210 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003211 }
drh4c653a02000-06-07 01:27:47 +00003212 return 0;
3213}
3214
3215/*
drh45e29d82006-11-20 16:21:10 +00003216** Run zQuery. Use dump_callback() as the callback routine so that
3217** the contents of the query are output as SQL statements.
3218**
drhdd3d4592004-08-30 01:54:05 +00003219** If we get a SQLITE_CORRUPT error, rerun the query after appending
3220** "ORDER BY rowid DESC" to the end.
3221*/
3222static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003223 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003224 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003225){
3226 int rc;
drh2f464a02011-10-13 00:41:49 +00003227 char *zErr = 0;
3228 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003229 if( rc==SQLITE_CORRUPT ){
3230 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00003231 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00003232 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00003233 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00003234 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003235 sqlite3_free(zErr);
3236 zErr = 0;
3237 }
drhdd3d4592004-08-30 01:54:05 +00003238 zQ2 = malloc( len+100 );
3239 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00003240 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00003241 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3242 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003243 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003244 }else{
3245 rc = SQLITE_CORRUPT;
3246 }
3247 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00003248 free(zQ2);
3249 }
3250 return rc;
3251}
3252
3253/*
drh75897232000-05-29 14:26:00 +00003254** Text of a help message
3255*/
persicom1d0b8722002-04-18 02:53:04 +00003256static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00003257#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00003258 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00003259#endif
drh9ff849f2009-02-04 20:55:57 +00003260 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00003261 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00003262 ".binary on|off Turn binary output on or off. Default OFF\n"
drh453ca042017-05-22 18:00:34 +00003263 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
drhdf12f1c2015-12-07 21:46:19 +00003264 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00003265 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00003266 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00003267 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00003268 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00003269 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00003270 " If TABLE specified, only dump tables matching\n"
3271 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00003272 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00003273 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00003274 ".exit Exit this program\n"
drh700c2522016-02-09 18:39:25 +00003275 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
drh4926fec2016-04-13 15:33:42 +00003276 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003277 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003278 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003279 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003280#ifndef SQLITE_OMIT_TEST_CONTROL
3281 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3282#endif
drh0e55db12015-02-06 14:51:13 +00003283 ".indexes ?TABLE? Show names of all indexes\n"
3284 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003285 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003286#ifdef SQLITE_ENABLE_IOTRACE
3287 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3288#endif
drh1a513372015-05-02 17:40:23 +00003289 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003290 ".lint OPTIONS Report potential schema issues. Options:\n"
3291 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003292#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003293 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003294#endif
drh127f9d72010-02-23 01:47:00 +00003295 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003296 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003297 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003298 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003299 " column Left-aligned columns. (See .width)\n"
3300 " html HTML <table> code\n"
3301 " insert SQL insert statements for TABLE\n"
3302 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003303 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003304 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003305 " tabs Tab-separated values\n"
3306 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003307 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003308 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkine16a3502017-05-29 03:48:13 +00003309 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
3310 " The --new option starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003311 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003312 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003313 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003314 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003315 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003316 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003317 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003318 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003319 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3320 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00003321 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00003322 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3323 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003324#if defined(SQLITE_ENABLE_SESSION)
3325 ".session CMD ... Create or control sessions\n"
3326#endif
drh1554bc82017-03-08 16:10:34 +00003327 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003328 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003329 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003330 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003331 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003332 ".tables ?TABLE? List names of tables\n"
3333 " If TABLE specified, only list tables matching\n"
3334 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003335 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003336 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003337 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003338 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003339 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003340 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003341 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003342 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003343 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003344;
3345
drhe6229612014-08-18 15:08:26 +00003346#if defined(SQLITE_ENABLE_SESSION)
3347/*
3348** Print help information for the ".sessions" command
3349*/
3350void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003351 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003352 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3353 "If ?NAME? is omitted, the first defined session is used.\n"
3354 "Subcommands:\n"
3355 " attach TABLE Attach TABLE\n"
3356 " changeset FILE Write a changeset into FILE\n"
3357 " close Close one session\n"
3358 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003359 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003360 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3361 " isempty Query whether the session is empty\n"
3362 " list List currently open session names\n"
3363 " open DB NAME Open a new session on DB\n"
3364 " patchset FILE Write a patchset into FILE\n"
3365 );
3366}
3367#endif
3368
3369
drhdaffd0e2001-04-11 14:28:42 +00003370/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003371static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003372
drh2db82112016-09-15 21:35:24 +00003373/*
dan11da0022016-12-17 08:18:05 +00003374** Read the content of file zName into memory obtained from sqlite3_malloc64()
mistachkine16a3502017-05-29 03:48:13 +00003375** and return a pointer to the buffer. The caller is responsible for freeing
3376** the memory.
drh2db82112016-09-15 21:35:24 +00003377**
dan11da0022016-12-17 08:18:05 +00003378** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3379** read.
3380**
3381** For convenience, a nul-terminator byte is always appended to the data read
3382** from the file before the buffer is returned. This byte is not included in
3383** the final value of (*pnByte), if applicable.
3384**
3385** NULL is returned if any error is encountered. The final value of *pnByte
3386** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003387*/
dan11da0022016-12-17 08:18:05 +00003388static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003389 FILE *in = fopen(zName, "rb");
3390 long nIn;
drhd1459152016-09-16 19:11:03 +00003391 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003392 char *pBuf;
3393 if( in==0 ) return 0;
3394 fseek(in, 0, SEEK_END);
3395 nIn = ftell(in);
3396 rewind(in);
drhd1459152016-09-16 19:11:03 +00003397 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003398 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003399 nRead = fread(pBuf, nIn, 1, in);
3400 fclose(in);
3401 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003402 sqlite3_free(pBuf);
3403 return 0;
3404 }
drhd1459152016-09-16 19:11:03 +00003405 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003406 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003407 return pBuf;
3408}
3409
drhba5b0932014-07-24 12:39:59 +00003410/*
3411** Implementation of the "readfile(X)" SQL function. The entire content
3412** of the file named X is read and returned as a BLOB. NULL is returned
3413** if the file does not exist or is unreadable.
3414*/
3415static void readfileFunc(
3416 sqlite3_context *context,
3417 int argc,
3418 sqlite3_value **argv
3419){
3420 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003421 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003422 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003423
drhf5ed7ad2015-06-15 14:43:25 +00003424 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003425 zName = (const char*)sqlite3_value_text(argv[0]);
3426 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003427 pBuf = readFile(zName, &nBuf);
3428 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003429}
3430
3431/*
3432** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3433** is written into file X. The number of bytes written is returned. Or
3434** NULL is returned if something goes wrong, such as being unable to open
3435** file X for writing.
3436*/
3437static void writefileFunc(
3438 sqlite3_context *context,
3439 int argc,
3440 sqlite3_value **argv
3441){
3442 FILE *out;
3443 const char *z;
drhba5b0932014-07-24 12:39:59 +00003444 sqlite3_int64 rc;
3445 const char *zFile;
3446
drhf5ed7ad2015-06-15 14:43:25 +00003447 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003448 zFile = (const char*)sqlite3_value_text(argv[0]);
3449 if( zFile==0 ) return;
3450 out = fopen(zFile, "wb");
3451 if( out==0 ) return;
3452 z = (const char*)sqlite3_value_blob(argv[1]);
3453 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003454 rc = 0;
3455 }else{
drh490fe862014-08-11 14:21:32 +00003456 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003457 }
3458 fclose(out);
3459 sqlite3_result_int64(context, rc);
3460}
drhdaffd0e2001-04-11 14:28:42 +00003461
drhe6229612014-08-18 15:08:26 +00003462#if defined(SQLITE_ENABLE_SESSION)
3463/*
3464** Close a single OpenSession object and release all of its associated
3465** resources.
3466*/
3467static void session_close(OpenSession *pSession){
3468 int i;
3469 sqlite3session_delete(pSession->p);
3470 sqlite3_free(pSession->zName);
3471 for(i=0; i<pSession->nFilter; i++){
3472 sqlite3_free(pSession->azFilter[i]);
3473 }
3474 sqlite3_free(pSession->azFilter);
3475 memset(pSession, 0, sizeof(OpenSession));
3476}
3477#endif
3478
3479/*
drh51b55a32016-04-04 12:38:05 +00003480** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003481*/
drhe6229612014-08-18 15:08:26 +00003482#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003483static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003484 int i;
3485 for(i=0; i<p->nSession; i++){
3486 session_close(&p->aSession[i]);
3487 }
3488 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003489}
drh51b55a32016-04-04 12:38:05 +00003490#else
3491# define session_close_all(X)
3492#endif
drhe6229612014-08-18 15:08:26 +00003493
drh75897232000-05-29 14:26:00 +00003494/*
drh03168ca2014-08-18 20:01:31 +00003495** Implementation of the xFilter function for an open session. Omit
3496** any tables named by ".session filter" but let all other table through.
3497*/
3498#if defined(SQLITE_ENABLE_SESSION)
3499static int session_filter(void *pCtx, const char *zTab){
3500 OpenSession *pSession = (OpenSession*)pCtx;
3501 int i;
3502 for(i=0; i<pSession->nFilter; i++){
3503 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3504 }
3505 return 1;
3506}
3507#endif
3508
3509/*
drh44c2eb12003-04-30 11:38:26 +00003510** Make sure the database is open. If it is not, then open it. If
3511** the database fails to open, print an error message and exit.
3512*/
drhdcd87a92014-08-18 13:45:42 +00003513static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003514 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003515 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003516 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003517 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003518 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003519 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003520 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003521 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003522 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003523 }
drhc2e87a32006-06-27 15:16:14 +00003524#ifndef SQLITE_OMIT_LOAD_EXTENSION
3525 sqlite3_enable_load_extension(p->db, 1);
3526#endif
mistachkin8e189222015-04-19 21:43:16 +00003527 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003528 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003529 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003530 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003531 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3532 sha3Func, 0, 0);
3533 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3534 sha3Func, 0, 0);
3535 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3536 sha3QueryFunc, 0, 0);
3537 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3538 sha3QueryFunc, 0, 0);
drh44c2eb12003-04-30 11:38:26 +00003539 }
3540}
3541
3542/*
drhfeac5f82004-08-01 00:10:45 +00003543** Do C-language style dequoting.
3544**
mistachkinf21979d2015-01-18 05:35:01 +00003545** \a -> alarm
3546** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003547** \t -> tab
3548** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003549** \v -> vertical tab
3550** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003551** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003552** \s -> space
drh4c56b992013-06-27 13:26:55 +00003553** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003554** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003555** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003556** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003557*/
3558static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003559 int i, j;
3560 char c;
drhc2ce0be2014-05-29 12:36:14 +00003561 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003562 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003563 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003564 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003565 if( c=='a' ){
3566 c = '\a';
3567 }else if( c=='b' ){
3568 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003569 }else if( c=='t' ){
3570 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003571 }else if( c=='n' ){
3572 c = '\n';
3573 }else if( c=='v' ){
3574 c = '\v';
3575 }else if( c=='f' ){
3576 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003577 }else if( c=='r' ){
3578 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003579 }else if( c=='"' ){
3580 c = '"';
3581 }else if( c=='\'' ){
3582 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003583 }else if( c=='\\' ){
3584 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003585 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003586 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003587 if( z[i+1]>='0' && z[i+1]<='7' ){
3588 i++;
3589 c = (c<<3) + z[i] - '0';
3590 if( z[i+1]>='0' && z[i+1]<='7' ){
3591 i++;
3592 c = (c<<3) + z[i] - '0';
3593 }
3594 }
3595 }
3596 }
3597 z[j] = c;
3598 }
drhc2ce0be2014-05-29 12:36:14 +00003599 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003600}
3601
3602/*
drh348d19c2013-06-03 12:47:43 +00003603** Return the value of a hexadecimal digit. Return -1 if the input
3604** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003605*/
drh348d19c2013-06-03 12:47:43 +00003606static int hexDigitValue(char c){
3607 if( c>='0' && c<='9' ) return c - '0';
3608 if( c>='a' && c<='f' ) return c - 'a' + 10;
3609 if( c>='A' && c<='F' ) return c - 'A' + 10;
3610 return -1;
drhc28490c2006-10-26 14:25:58 +00003611}
3612
3613/*
drh7d9f3942013-04-03 01:26:54 +00003614** Interpret zArg as an integer value, possibly with suffixes.
3615*/
3616static sqlite3_int64 integerValue(const char *zArg){
3617 sqlite3_int64 v = 0;
3618 static const struct { char *zSuffix; int iMult; } aMult[] = {
3619 { "KiB", 1024 },
3620 { "MiB", 1024*1024 },
3621 { "GiB", 1024*1024*1024 },
3622 { "KB", 1000 },
3623 { "MB", 1000000 },
3624 { "GB", 1000000000 },
3625 { "K", 1000 },
3626 { "M", 1000000 },
3627 { "G", 1000000000 },
3628 };
3629 int i;
3630 int isNeg = 0;
3631 if( zArg[0]=='-' ){
3632 isNeg = 1;
3633 zArg++;
3634 }else if( zArg[0]=='+' ){
3635 zArg++;
3636 }
drh348d19c2013-06-03 12:47:43 +00003637 if( zArg[0]=='0' && zArg[1]=='x' ){
3638 int x;
3639 zArg += 2;
3640 while( (x = hexDigitValue(zArg[0]))>=0 ){
3641 v = (v<<4) + x;
3642 zArg++;
3643 }
3644 }else{
3645 while( IsDigit(zArg[0]) ){
3646 v = v*10 + zArg[0] - '0';
3647 zArg++;
3648 }
drh7d9f3942013-04-03 01:26:54 +00003649 }
drhc2bed0a2013-05-24 11:57:50 +00003650 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003651 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3652 v *= aMult[i].iMult;
3653 break;
3654 }
3655 }
3656 return isNeg? -v : v;
3657}
3658
3659/*
drh348d19c2013-06-03 12:47:43 +00003660** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3661** for TRUE and FALSE. Return the integer value if appropriate.
3662*/
drhe6e1d122017-03-09 13:50:49 +00003663static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003664 int i;
3665 if( zArg[0]=='0' && zArg[1]=='x' ){
3666 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3667 }else{
3668 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3669 }
3670 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3671 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3672 return 1;
3673 }
3674 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3675 return 0;
3676 }
mistachkinaae280e2015-12-31 19:06:24 +00003677 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003678 zArg);
3679 return 0;
3680}
3681
3682/*
drhe6e1d122017-03-09 13:50:49 +00003683** Set or clear a shell flag according to a boolean value.
3684*/
3685static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3686 if( booleanValue(zArg) ){
3687 ShellSetFlag(p, mFlag);
3688 }else{
3689 ShellClearFlag(p, mFlag);
3690 }
3691}
3692
3693/*
drh42f64e52012-04-04 16:56:23 +00003694** Close an output file, assuming it is not stderr or stdout
3695*/
3696static void output_file_close(FILE *f){
3697 if( f && f!=stdout && f!=stderr ) fclose(f);
3698}
3699
3700/*
3701** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003702** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003703** filename is "off".
3704*/
3705static FILE *output_file_open(const char *zFile){
3706 FILE *f;
3707 if( strcmp(zFile,"stdout")==0 ){
3708 f = stdout;
3709 }else if( strcmp(zFile, "stderr")==0 ){
3710 f = stderr;
3711 }else if( strcmp(zFile, "off")==0 ){
3712 f = 0;
3713 }else{
3714 f = fopen(zFile, "wb");
3715 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003716 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003717 }
3718 }
3719 return f;
3720}
3721
drhd12602a2016-12-07 15:49:02 +00003722#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003723#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003724/*
3725** A routine for handling output from sqlite3_trace().
3726*/
drh4b363a52016-07-23 20:27:41 +00003727static int sql_trace_callback(
3728 unsigned mType,
3729 void *pArg,
3730 void *pP,
3731 void *pX
3732){
drh42f64e52012-04-04 16:56:23 +00003733 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003734 UNUSED_PARAMETER(mType);
3735 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003736 if( f ){
drh4b363a52016-07-23 20:27:41 +00003737 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003738 int i = (int)strlen(z);
3739 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003740 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003741 }
drh4b363a52016-07-23 20:27:41 +00003742 return 0;
drh42f64e52012-04-04 16:56:23 +00003743}
drhc10b9da2016-11-20 17:59:59 +00003744#endif
3745#endif
drh42f64e52012-04-04 16:56:23 +00003746
3747/*
drhd8621b92012-04-17 09:09:33 +00003748** A no-op routine that runs with the ".breakpoint" doc-command. This is
3749** a useful spot to set a debugger breakpoint.
3750*/
3751static void test_breakpoint(void){
3752 static int nCall = 0;
3753 nCall++;
3754}
3755
3756/*
mistachkin636bf9f2014-07-19 20:15:16 +00003757** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003758*/
mistachkin636bf9f2014-07-19 20:15:16 +00003759typedef struct ImportCtx ImportCtx;
3760struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003761 const char *zFile; /* Name of the input file */
3762 FILE *in; /* Read the CSV text from this input stream */
3763 char *z; /* Accumulated text for a field */
3764 int n; /* Number of bytes in z */
3765 int nAlloc; /* Space allocated for z[] */
3766 int nLine; /* Current line number */
3767 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003768 int cColSep; /* The column separator character. (Usually ",") */
3769 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003770};
3771
3772/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003773static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003774 if( p->n+1>=p->nAlloc ){
3775 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003776 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003777 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003778 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003779 exit(1);
3780 }
3781 }
3782 p->z[p->n++] = (char)c;
3783}
3784
3785/* Read a single field of CSV text. Compatible with rfc4180 and extended
3786** with the option of having a separator other than ",".
3787**
3788** + Input comes from p->in.
3789** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003790** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003791** + Use p->cSep as the column separator. The default is ",".
3792** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003793** + Keep track of the line number in p->nLine.
3794** + Store the character that terminates the field in p->cTerm. Store
3795** EOF on end-of-file.
3796** + Report syntax errors on stderr
3797*/
mistachkin44723ce2015-03-21 02:22:37 +00003798static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003799 int c;
3800 int cSep = p->cColSep;
3801 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003802 p->n = 0;
3803 c = fgetc(p->in);
3804 if( c==EOF || seenInterrupt ){
3805 p->cTerm = EOF;
3806 return 0;
3807 }
3808 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003809 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003810 int startLine = p->nLine;
3811 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003812 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003813 while( 1 ){
3814 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003815 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003816 if( c==cQuote ){
3817 if( pc==cQuote ){
3818 pc = 0;
3819 continue;
3820 }
3821 }
3822 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003823 || (c==rSep && pc==cQuote)
3824 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003825 || (c==EOF && pc==cQuote)
3826 ){
3827 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003828 p->cTerm = c;
3829 break;
3830 }
3831 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003832 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003833 p->zFile, p->nLine, cQuote);
3834 }
3835 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003836 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003837 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003838 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003839 break;
3840 }
mistachkin636bf9f2014-07-19 20:15:16 +00003841 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003842 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003843 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003844 }
drhdb95f682013-06-26 22:46:00 +00003845 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00003846 while( c!=EOF && c!=cSep && c!=rSep ){
3847 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003848 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003849 }
mistachkin636bf9f2014-07-19 20:15:16 +00003850 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003851 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003852 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003853 }
drhdb95f682013-06-26 22:46:00 +00003854 p->cTerm = c;
3855 }
drh8dd675e2013-07-12 21:09:24 +00003856 if( p->z ) p->z[p->n] = 0;
drhdb95f682013-06-26 22:46:00 +00003857 return p->z;
3858}
3859
mistachkin636bf9f2014-07-19 20:15:16 +00003860/* Read a single field of ASCII delimited text.
3861**
3862** + Input comes from p->in.
3863** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003864** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003865** + Use p->cSep as the column separator. The default is "\x1F".
3866** + Use p->rSep as the row separator. The default is "\x1E".
3867** + Keep track of the row number in p->nLine.
3868** + Store the character that terminates the field in p->cTerm. Store
3869** EOF on end-of-file.
3870** + Report syntax errors on stderr
3871*/
mistachkin44723ce2015-03-21 02:22:37 +00003872static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003873 int c;
3874 int cSep = p->cColSep;
3875 int rSep = p->cRowSep;
3876 p->n = 0;
3877 c = fgetc(p->in);
3878 if( c==EOF || seenInterrupt ){
3879 p->cTerm = EOF;
3880 return 0;
3881 }
3882 while( c!=EOF && c!=cSep && c!=rSep ){
3883 import_append_char(p, c);
3884 c = fgetc(p->in);
3885 }
3886 if( c==rSep ){
3887 p->nLine++;
3888 }
3889 p->cTerm = c;
3890 if( p->z ) p->z[p->n] = 0;
3891 return p->z;
3892}
3893
drhdb95f682013-06-26 22:46:00 +00003894/*
drh4bbcf102014-02-06 02:46:08 +00003895** Try to transfer data for table zTable. If an error is seen while
3896** moving forward, try to go backwards. The backwards movement won't
3897** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003898*/
mistachkine31ae902014-02-06 01:15:29 +00003899static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003900 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003901 sqlite3 *newDb,
3902 const char *zTable
3903){
mistachkin1fe36bb2016-04-04 02:16:44 +00003904 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003905 sqlite3_stmt *pInsert = 0;
3906 char *zQuery = 0;
3907 char *zInsert = 0;
3908 int rc;
3909 int i, j, n;
3910 int nTable = (int)strlen(zTable);
3911 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003912 int cnt = 0;
3913 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003914
3915 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3916 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3917 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003918 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003919 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3920 zQuery);
3921 goto end_data_xfer;
3922 }
3923 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00003924 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00003925 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003926 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00003927 goto end_data_xfer;
3928 }
3929 sqlite3_snprintf(200+nTable,zInsert,
3930 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3931 i = (int)strlen(zInsert);
3932 for(j=1; j<n; j++){
3933 memcpy(zInsert+i, ",?", 2);
3934 i += 2;
3935 }
3936 memcpy(zInsert+i, ");", 3);
3937 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3938 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003939 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003940 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3941 zQuery);
3942 goto end_data_xfer;
3943 }
3944 for(k=0; k<2; k++){
3945 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3946 for(i=0; i<n; i++){
3947 switch( sqlite3_column_type(pQuery, i) ){
3948 case SQLITE_NULL: {
3949 sqlite3_bind_null(pInsert, i+1);
3950 break;
3951 }
3952 case SQLITE_INTEGER: {
3953 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3954 break;
3955 }
3956 case SQLITE_FLOAT: {
3957 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3958 break;
3959 }
3960 case SQLITE_TEXT: {
3961 sqlite3_bind_text(pInsert, i+1,
3962 (const char*)sqlite3_column_text(pQuery,i),
3963 -1, SQLITE_STATIC);
3964 break;
3965 }
3966 case SQLITE_BLOB: {
3967 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3968 sqlite3_column_bytes(pQuery,i),
3969 SQLITE_STATIC);
3970 break;
3971 }
3972 }
3973 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00003974 rc = sqlite3_step(pInsert);
3975 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00003976 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00003977 sqlite3_errmsg(newDb));
3978 }
drh3350ce92014-02-06 00:49:12 +00003979 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00003980 cnt++;
3981 if( (cnt%spinRate)==0 ){
3982 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3983 fflush(stdout);
3984 }
drh3350ce92014-02-06 00:49:12 +00003985 } /* End while */
3986 if( rc==SQLITE_DONE ) break;
3987 sqlite3_finalize(pQuery);
3988 sqlite3_free(zQuery);
3989 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3990 zTable);
3991 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3992 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003993 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00003994 break;
drh3350ce92014-02-06 00:49:12 +00003995 }
3996 } /* End for(k=0...) */
3997
3998end_data_xfer:
3999 sqlite3_finalize(pQuery);
4000 sqlite3_finalize(pInsert);
4001 sqlite3_free(zQuery);
4002 sqlite3_free(zInsert);
4003}
4004
4005
4006/*
4007** Try to transfer all rows of the schema that match zWhere. For
4008** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00004009** If an error is encountered while moving forward through the
4010** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00004011*/
mistachkine31ae902014-02-06 01:15:29 +00004012static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00004013 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00004014 sqlite3 *newDb,
4015 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00004016 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00004017){
4018 sqlite3_stmt *pQuery = 0;
4019 char *zQuery = 0;
4020 int rc;
4021 const unsigned char *zName;
4022 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00004023 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00004024
4025 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4026 " WHERE %s", zWhere);
4027 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4028 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004029 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004030 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4031 zQuery);
4032 goto end_schema_xfer;
4033 }
4034 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4035 zName = sqlite3_column_text(pQuery, 0);
4036 zSql = sqlite3_column_text(pQuery, 1);
4037 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004038 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4039 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004040 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004041 sqlite3_free(zErrMsg);
4042 zErrMsg = 0;
4043 }
drh3350ce92014-02-06 00:49:12 +00004044 if( xForEach ){
4045 xForEach(p, newDb, (const char*)zName);
4046 }
4047 printf("done\n");
4048 }
4049 if( rc!=SQLITE_DONE ){
4050 sqlite3_finalize(pQuery);
4051 sqlite3_free(zQuery);
4052 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4053 " WHERE %s ORDER BY rowid DESC", zWhere);
4054 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4055 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004056 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004057 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4058 zQuery);
4059 goto end_schema_xfer;
4060 }
4061 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4062 zName = sqlite3_column_text(pQuery, 0);
4063 zSql = sqlite3_column_text(pQuery, 1);
4064 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004065 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4066 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004067 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004068 sqlite3_free(zErrMsg);
4069 zErrMsg = 0;
4070 }
drh3350ce92014-02-06 00:49:12 +00004071 if( xForEach ){
4072 xForEach(p, newDb, (const char*)zName);
4073 }
4074 printf("done\n");
4075 }
4076 }
4077end_schema_xfer:
4078 sqlite3_finalize(pQuery);
4079 sqlite3_free(zQuery);
4080}
4081
4082/*
4083** Open a new database file named "zNewDb". Try to recover as much information
4084** as possible out of the main database (which might be corrupt) and write it
4085** into zNewDb.
4086*/
drhdcd87a92014-08-18 13:45:42 +00004087static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00004088 int rc;
4089 sqlite3 *newDb = 0;
4090 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004091 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00004092 return;
4093 }
4094 rc = sqlite3_open(zNewDb, &newDb);
4095 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004096 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00004097 sqlite3_errmsg(newDb));
4098 }else{
drh54d0d2d2014-04-03 00:32:13 +00004099 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004100 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00004101 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4102 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00004103 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00004104 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004105 }
4106 sqlite3_close(newDb);
4107}
4108
4109/*
drhc2ce0be2014-05-29 12:36:14 +00004110** Change the output file back to stdout
4111*/
drhdcd87a92014-08-18 13:45:42 +00004112static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00004113 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004114#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00004115 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004116#endif
drhc2ce0be2014-05-29 12:36:14 +00004117 }else{
4118 output_file_close(p->out);
4119 }
4120 p->outfile[0] = 0;
4121 p->out = stdout;
4122}
4123
4124/*
drhf7502f02015-02-06 14:19:44 +00004125** Run an SQL command and return the single integer result.
4126*/
4127static int db_int(ShellState *p, const char *zSql){
4128 sqlite3_stmt *pStmt;
4129 int res = 0;
4130 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4131 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4132 res = sqlite3_column_int(pStmt,0);
4133 }
4134 sqlite3_finalize(pStmt);
4135 return res;
4136}
4137
4138/*
4139** Convert a 2-byte or 4-byte big-endian integer into a native integer
4140*/
drha0620ac2016-07-13 13:05:13 +00004141static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004142 return (a[0]<<8) + a[1];
4143}
drha0620ac2016-07-13 13:05:13 +00004144static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004145 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4146}
4147
4148/*
4149** Implementation of the ".info" command.
4150**
4151** Return 1 on error, 2 to exit, and 0 otherwise.
4152*/
drh0e55db12015-02-06 14:51:13 +00004153static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004154 static const struct { const char *zName; int ofst; } aField[] = {
4155 { "file change counter:", 24 },
4156 { "database page count:", 28 },
4157 { "freelist page count:", 36 },
4158 { "schema cookie:", 40 },
4159 { "schema format:", 44 },
4160 { "default cache size:", 48 },
4161 { "autovacuum top root:", 52 },
4162 { "incremental vacuum:", 64 },
4163 { "text encoding:", 56 },
4164 { "user version:", 60 },
4165 { "application id:", 68 },
4166 { "software version:", 96 },
4167 };
drh0e55db12015-02-06 14:51:13 +00004168 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4169 { "number of tables:",
4170 "SELECT count(*) FROM %s WHERE type='table'" },
4171 { "number of indexes:",
4172 "SELECT count(*) FROM %s WHERE type='index'" },
4173 { "number of triggers:",
4174 "SELECT count(*) FROM %s WHERE type='trigger'" },
4175 { "number of views:",
4176 "SELECT count(*) FROM %s WHERE type='view'" },
4177 { "schema size:",
4178 "SELECT total(length(sql)) FROM %s" },
4179 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004180 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004181 int i;
4182 char *zSchemaTab;
4183 char *zDb = nArg>=2 ? azArg[1] : "main";
4184 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004185 open_db(p, 0);
4186 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004187 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004188 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4189 return 1;
4190 }
4191 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4192 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004193 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004194 return 1;
4195 }
4196 i = get2byteInt(aHdr+16);
4197 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004198 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4199 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4200 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4201 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004202 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004203 int ofst = aField[i].ofst;
4204 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004205 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004206 switch( ofst ){
4207 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004208 if( val==1 ) raw_printf(p->out, " (utf8)");
4209 if( val==2 ) raw_printf(p->out, " (utf16le)");
4210 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004211 }
4212 }
mistachkinaae280e2015-12-31 19:06:24 +00004213 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004214 }
drh0e55db12015-02-06 14:51:13 +00004215 if( zDb==0 ){
4216 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4217 }else if( strcmp(zDb,"temp")==0 ){
4218 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4219 }else{
4220 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4221 }
drhf5ed7ad2015-06-15 14:43:25 +00004222 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004223 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4224 int val = db_int(p, zSql);
4225 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004226 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004227 }
4228 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004229 return 0;
4230}
4231
dand95bb392015-09-30 11:19:05 +00004232/*
4233** Print the current sqlite3_errmsg() value to stderr and return 1.
4234*/
4235static int shellDatabaseError(sqlite3 *db){
4236 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004237 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004238 return 1;
4239}
4240
4241/*
4242** Print an out-of-memory message to stderr and return 1.
4243*/
4244static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004245 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004246 return 1;
4247}
drhf7502f02015-02-06 14:19:44 +00004248
drh2db82112016-09-15 21:35:24 +00004249/*
4250** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4251** if they match and FALSE (0) if they do not match.
4252**
4253** Globbing rules:
4254**
4255** '*' Matches any sequence of zero or more characters.
4256**
4257** '?' Matches exactly one character.
4258**
4259** [...] Matches one character from the enclosed list of
4260** characters.
4261**
4262** [^...] Matches one character not in the enclosed list.
4263**
4264** '#' Matches any sequence of one or more digits with an
4265** optional + or - sign in front
4266**
4267** ' ' Any span of whitespace matches any other span of
4268** whitespace.
4269**
4270** Extra whitespace at the end of z[] is ignored.
4271*/
4272static int testcase_glob(const char *zGlob, const char *z){
4273 int c, c2;
4274 int invert;
4275 int seen;
4276
4277 while( (c = (*(zGlob++)))!=0 ){
4278 if( IsSpace(c) ){
4279 if( !IsSpace(*z) ) return 0;
4280 while( IsSpace(*zGlob) ) zGlob++;
4281 while( IsSpace(*z) ) z++;
4282 }else if( c=='*' ){
4283 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4284 if( c=='?' && (*(z++))==0 ) return 0;
4285 }
4286 if( c==0 ){
4287 return 1;
4288 }else if( c=='[' ){
4289 while( *z && testcase_glob(zGlob-1,z)==0 ){
4290 z++;
4291 }
4292 return (*z)!=0;
4293 }
4294 while( (c2 = (*(z++)))!=0 ){
4295 while( c2!=c ){
4296 c2 = *(z++);
4297 if( c2==0 ) return 0;
4298 }
4299 if( testcase_glob(zGlob,z) ) return 1;
4300 }
4301 return 0;
4302 }else if( c=='?' ){
4303 if( (*(z++))==0 ) return 0;
4304 }else if( c=='[' ){
4305 int prior_c = 0;
4306 seen = 0;
4307 invert = 0;
4308 c = *(z++);
4309 if( c==0 ) return 0;
4310 c2 = *(zGlob++);
4311 if( c2=='^' ){
4312 invert = 1;
4313 c2 = *(zGlob++);
4314 }
4315 if( c2==']' ){
4316 if( c==']' ) seen = 1;
4317 c2 = *(zGlob++);
4318 }
4319 while( c2 && c2!=']' ){
4320 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4321 c2 = *(zGlob++);
4322 if( c>=prior_c && c<=c2 ) seen = 1;
4323 prior_c = 0;
4324 }else{
4325 if( c==c2 ){
4326 seen = 1;
4327 }
4328 prior_c = c2;
4329 }
4330 c2 = *(zGlob++);
4331 }
4332 if( c2==0 || (seen ^ invert)==0 ) return 0;
4333 }else if( c=='#' ){
4334 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4335 if( !IsDigit(z[0]) ) return 0;
4336 z++;
4337 while( IsDigit(z[0]) ){ z++; }
4338 }else{
4339 if( c!=(*(z++)) ) return 0;
4340 }
4341 }
4342 while( IsSpace(*z) ){ z++; }
4343 return *z==0;
4344}
drh2db82112016-09-15 21:35:24 +00004345
4346
drhf7502f02015-02-06 14:19:44 +00004347/*
drh4926fec2016-04-13 15:33:42 +00004348** Compare the string as a command-line option with either one or two
4349** initial "-" characters.
4350*/
4351static int optionMatch(const char *zStr, const char *zOpt){
4352 if( zStr[0]!='-' ) return 0;
4353 zStr++;
4354 if( zStr[0]=='-' ) zStr++;
4355 return strcmp(zStr, zOpt)==0;
4356}
4357
4358/*
drhcd0509e2016-09-16 00:26:08 +00004359** Delete a file.
4360*/
4361int shellDeleteFile(const char *zFilename){
4362 int rc;
4363#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004364 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004365 rc = _wunlink(z);
4366 sqlite3_free(z);
4367#else
4368 rc = unlink(zFilename);
4369#endif
4370 return rc;
4371}
4372
dan35ac58e2016-12-14 19:28:27 +00004373
dan35ac58e2016-12-14 19:28:27 +00004374/*
dandd9e0be2016-12-16 16:44:27 +00004375** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004376** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004377** called with four arguments - the parent table name, the parent column name,
4378** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004379**
4380** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4381**
4382** If either of the named tables or columns do not exist, this function
mistachkine16a3502017-05-29 03:48:13 +00004383** returns an empty string. An empty string is also returned if both tables
dan35ac58e2016-12-14 19:28:27 +00004384** and columns exist but have the same default collation sequence. Or,
4385** if both exist but the default collation sequences are different, this
4386** function returns the string " COLLATE <parent-collation>", where
4387** <parent-collation> is the default collation sequence of the parent column.
4388*/
4389static void shellFkeyCollateClause(
mistachkine16a3502017-05-29 03:48:13 +00004390 sqlite3_context *pCtx,
4391 int nVal,
dan35ac58e2016-12-14 19:28:27 +00004392 sqlite3_value **apVal
4393){
4394 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4395 const char *zParent;
4396 const char *zParentCol;
4397 const char *zParentSeq;
4398 const char *zChild;
4399 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004400 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004401 int rc;
mistachkine16a3502017-05-29 03:48:13 +00004402
dan35ac58e2016-12-14 19:28:27 +00004403 assert( nVal==4 );
4404 zParent = (const char*)sqlite3_value_text(apVal[0]);
4405 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4406 zChild = (const char*)sqlite3_value_text(apVal[2]);
4407 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4408
4409 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4410 rc = sqlite3_table_column_metadata(
4411 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4412 );
4413 if( rc==SQLITE_OK ){
4414 rc = sqlite3_table_column_metadata(
4415 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4416 );
4417 }
4418
4419 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4420 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4421 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4422 sqlite3_free(z);
4423 }
4424}
4425
4426
4427/*
dan3c7ebeb2016-12-16 17:28:56 +00004428** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004429*/
dan3c7ebeb2016-12-16 17:28:56 +00004430static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004431 ShellState *pState, /* Current shell tool state */
4432 char **azArg, /* Array of arguments passed to dot command */
4433 int nArg /* Number of entries in azArg[] */
4434){
dandd9e0be2016-12-16 16:44:27 +00004435 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4436 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004437 int bVerbose = 0; /* If -verbose is present */
4438 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004439 int i; /* To iterate through azArg[] */
4440 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4441 int rc; /* Return code */
4442 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004443
dandd9e0be2016-12-16 16:44:27 +00004444 /*
4445 ** This SELECT statement returns one row for each foreign key constraint
4446 ** in the schema of the main database. The column values are:
4447 **
4448 ** 0. The text of an SQL statement similar to:
4449 **
4450 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4451 **
4452 ** This is the same SELECT that the foreign keys implementation needs
4453 ** to run internally on child tables. If there is an index that can
4454 ** be used to optimize this query, then it can also be used by the FK
4455 ** implementation to optimize DELETE or UPDATE statements on the parent
4456 ** table.
4457 **
4458 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4459 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4460 ** contains an index that can be used to optimize the query.
4461 **
4462 ** 2. Human readable text that describes the child table and columns. e.g.
4463 **
4464 ** "child_table(child_key1, child_key2)"
4465 **
4466 ** 3. Human readable text that describes the parent table and columns. e.g.
4467 **
4468 ** "parent_table(parent_key1, parent_key2)"
4469 **
4470 ** 4. A full CREATE INDEX statement for an index that could be used to
4471 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4472 **
4473 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4474 **
4475 ** 5. The name of the parent table.
4476 **
4477 ** These six values are used by the C logic below to generate the report.
4478 */
dan35ac58e2016-12-14 19:28:27 +00004479 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004480 "SELECT "
4481 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4482 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00004483 " || fkey_collate_clause("
4484 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004485 ", "
dandd9e0be2016-12-16 16:44:27 +00004486 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004487 " || group_concat('*=?', ' AND ') || ')'"
4488 ", "
dandd9e0be2016-12-16 16:44:27 +00004489 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004490 ", "
dan50da9382017-04-06 12:06:56 +00004491 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00004492 ", "
dandd9e0be2016-12-16 16:44:27 +00004493 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4494 " || ' ON ' || quote(s.name) || '('"
4495 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00004496 " fkey_collate_clause("
4497 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004498 " || ');'"
danf9647b62016-12-15 06:01:40 +00004499 ", "
dandd9e0be2016-12-16 16:44:27 +00004500 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00004501 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00004502 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00004503 "GROUP BY s.name, f.id "
4504 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004505 ;
dan54e2efc2017-04-06 14:56:26 +00004506 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00004507
dan3c7ebeb2016-12-16 17:28:56 +00004508 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004509 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004510 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4511 bVerbose = 1;
4512 }
4513 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4514 bGroupByParent = 1;
4515 zIndent = " ";
4516 }
4517 else{
dan3c7ebeb2016-12-16 17:28:56 +00004518 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4519 azArg[0], azArg[1]
4520 );
danf9647b62016-12-15 06:01:40 +00004521 return SQLITE_ERROR;
4522 }
dan35ac58e2016-12-14 19:28:27 +00004523 }
mistachkine16a3502017-05-29 03:48:13 +00004524
dan35ac58e2016-12-14 19:28:27 +00004525 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004526 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4527 0, shellFkeyCollateClause, 0, 0
4528 );
dan35ac58e2016-12-14 19:28:27 +00004529
4530
4531 if( rc==SQLITE_OK ){
4532 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4533 }
danf9647b62016-12-15 06:01:40 +00004534 if( rc==SQLITE_OK ){
4535 sqlite3_bind_int(pSql, 1, bGroupByParent);
4536 }
dan35ac58e2016-12-14 19:28:27 +00004537
4538 if( rc==SQLITE_OK ){
4539 int rc2;
danf9647b62016-12-15 06:01:40 +00004540 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004541 while( SQLITE_ROW==sqlite3_step(pSql) ){
4542 int res = -1;
4543 sqlite3_stmt *pExplain = 0;
4544 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4545 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4546 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4547 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4548 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004549 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004550
4551 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4552 if( rc!=SQLITE_OK ) break;
4553 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4554 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00004555 res = (
4556 0==sqlite3_strglob(zGlob, zPlan)
4557 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4558 );
dan35ac58e2016-12-14 19:28:27 +00004559 }
4560 rc = sqlite3_finalize(pExplain);
4561 if( rc!=SQLITE_OK ) break;
4562
4563 if( res<0 ){
4564 raw_printf(stderr, "Error: internal error");
4565 break;
danf9647b62016-12-15 06:01:40 +00004566 }else{
mistachkine16a3502017-05-29 03:48:13 +00004567 if( bGroupByParent
danf9647b62016-12-15 06:01:40 +00004568 && (bVerbose || res==0)
mistachkine16a3502017-05-29 03:48:13 +00004569 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
danf9647b62016-12-15 06:01:40 +00004570 ){
4571 raw_printf(out, "-- Parent table %s\n", zParent);
4572 sqlite3_free(zPrev);
4573 zPrev = sqlite3_mprintf("%s", zParent);
4574 }
4575
4576 if( res==0 ){
4577 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4578 }else if( bVerbose ){
mistachkine16a3502017-05-29 03:48:13 +00004579 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
danf9647b62016-12-15 06:01:40 +00004580 zIndent, zFrom, zTarget
4581 );
4582 }
dan35ac58e2016-12-14 19:28:27 +00004583 }
4584 }
danf9647b62016-12-15 06:01:40 +00004585 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004586
4587 if( rc!=SQLITE_OK ){
4588 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4589 }
4590
4591 rc2 = sqlite3_finalize(pSql);
4592 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4593 rc = rc2;
4594 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4595 }
4596 }else{
4597 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4598 }
4599
4600 return rc;
4601}
dan3c7ebeb2016-12-16 17:28:56 +00004602
dan35ac58e2016-12-14 19:28:27 +00004603/*
dan3c7ebeb2016-12-16 17:28:56 +00004604** Implementation of ".lint" dot command.
4605*/
4606static int lintDotCommand(
4607 ShellState *pState, /* Current shell tool state */
4608 char **azArg, /* Array of arguments passed to dot command */
4609 int nArg /* Number of entries in azArg[] */
4610){
4611 int n;
drh96ada592016-12-29 19:48:46 +00004612 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004613 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4614 return lintFkeyIndexes(pState, azArg, nArg);
4615
4616 usage:
4617 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4618 raw_printf(stderr, "Where sub-commands are:\n");
4619 raw_printf(stderr, " fkey-indexes\n");
4620 return SQLITE_ERROR;
4621}
4622
dan35ac58e2016-12-14 19:28:27 +00004623
drhcd0509e2016-09-16 00:26:08 +00004624/*
drh75897232000-05-29 14:26:00 +00004625** If an input line begins with "." then invoke this routine to
4626** process that line.
drh67505e72002-04-19 12:34:06 +00004627**
drh47ad6842006-11-08 12:25:42 +00004628** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004629*/
drhdcd87a92014-08-18 13:45:42 +00004630static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004631 int h = 1;
drh75897232000-05-29 14:26:00 +00004632 int nArg = 0;
4633 int n, c;
drh67505e72002-04-19 12:34:06 +00004634 int rc = 0;
drh75897232000-05-29 14:26:00 +00004635 char *azArg[50];
4636
4637 /* Parse the input line into tokens.
4638 */
mistachkin8e189222015-04-19 21:43:16 +00004639 while( zLine[h] && nArg<ArraySize(azArg) ){
4640 while( IsSpace(zLine[h]) ){ h++; }
4641 if( zLine[h]==0 ) break;
4642 if( zLine[h]=='\'' || zLine[h]=='"' ){
4643 int delim = zLine[h++];
4644 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004645 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004646 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004647 h++;
drh4c56b992013-06-27 13:26:55 +00004648 }
mistachkin8e189222015-04-19 21:43:16 +00004649 if( zLine[h]==delim ){
4650 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004651 }
drhfeac5f82004-08-01 00:10:45 +00004652 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004653 }else{
mistachkin8e189222015-04-19 21:43:16 +00004654 azArg[nArg++] = &zLine[h];
4655 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4656 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004657 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004658 }
4659 }
4660
4661 /* Process the input line.
4662 */
shane9bd1b442009-10-23 01:27:39 +00004663 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004664 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004665 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004666
drha0daa752016-09-16 11:53:10 +00004667#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004668 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4669 if( nArg!=2 ){
4670 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4671 rc = 1;
4672 goto meta_command_exit;
4673 }
4674 open_db(p, 0);
4675 if( booleanValue(azArg[1]) ){
4676 sqlite3_set_authorizer(p->db, shellAuth, p);
4677 }else{
4678 sqlite3_set_authorizer(p->db, 0, 0);
4679 }
4680 }else
drha0daa752016-09-16 11:53:10 +00004681#endif
drhde613c62016-04-04 17:23:10 +00004682
drh5c7976f2014-02-10 19:59:27 +00004683 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4684 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4685 ){
drhbc46f022013-01-23 18:53:23 +00004686 const char *zDestFile = 0;
4687 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004688 sqlite3 *pDest;
4689 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004690 int j;
4691 for(j=1; j<nArg; j++){
4692 const char *z = azArg[j];
4693 if( z[0]=='-' ){
4694 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004695 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004696 {
mistachkinaae280e2015-12-31 19:06:24 +00004697 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004698 return 1;
4699 }
4700 }else if( zDestFile==0 ){
4701 zDestFile = azArg[j];
4702 }else if( zDb==0 ){
4703 zDb = zDestFile;
4704 zDestFile = azArg[j];
4705 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004706 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004707 return 1;
4708 }
drh9ff849f2009-02-04 20:55:57 +00004709 }
drhbc46f022013-01-23 18:53:23 +00004710 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004711 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004712 return 1;
4713 }
4714 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004715 rc = sqlite3_open(zDestFile, &pDest);
4716 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004717 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004718 sqlite3_close(pDest);
4719 return 1;
4720 }
drh05782482013-10-24 15:20:20 +00004721 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004722 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4723 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004724 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004725 sqlite3_close(pDest);
4726 return 1;
4727 }
4728 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4729 sqlite3_backup_finish(pBackup);
4730 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004731 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004732 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004733 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004734 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004735 }
4736 sqlite3_close(pDest);
4737 }else
4738
drhc2ce0be2014-05-29 12:36:14 +00004739 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4740 if( nArg==2 ){
4741 bail_on_error = booleanValue(azArg[1]);
4742 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004743 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004744 rc = 1;
4745 }
drhc49f44e2006-10-26 18:15:42 +00004746 }else
4747
mistachkinf21979d2015-01-18 05:35:01 +00004748 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4749 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004750 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004751 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004752 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004753 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004754 }
mistachkinf21979d2015-01-18 05:35:01 +00004755 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004756 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004757 rc = 1;
4758 }
4759 }else
4760
drh453ca042017-05-22 18:00:34 +00004761 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
4762 if( nArg==2 ){
4763#if defined(_WIN32) || defined(WIN32)
4764 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
4765 rc = !SetCurrentDirectoryW(z);
4766 sqlite3_free(z);
4767#else
4768 rc = chdir(azArg[1]);
4769#endif
4770 if( rc ){
4771 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
4772 rc = 1;
4773 }
4774 }else{
4775 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
4776 rc = 1;
4777 }
4778 }else
4779
drhd8621b92012-04-17 09:09:33 +00004780 /* The undocumented ".breakpoint" command causes a call to the no-op
4781 ** routine named test_breakpoint().
4782 */
4783 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4784 test_breakpoint();
4785 }else
4786
drhdf12f1c2015-12-07 21:46:19 +00004787 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4788 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004789 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004790 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004791 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004792 rc = 1;
4793 }
4794 }else
4795
drh2db82112016-09-15 21:35:24 +00004796 /* Cancel output redirection, if it is currently set (by .testcase)
4797 ** Then read the content of the testcase-out.txt file and compare against
4798 ** azArg[1]. If there are differences, report an error and exit.
4799 */
4800 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4801 char *zRes = 0;
4802 output_reset(p);
4803 if( nArg!=2 ){
4804 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004805 rc = 2;
dan11da0022016-12-17 08:18:05 +00004806 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004807 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4808 rc = 2;
4809 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004810 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004811 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4812 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004813 rc = 2;
drh760c8162016-09-16 02:52:22 +00004814 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004815 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004816 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004817 }
4818 sqlite3_free(zRes);
4819 }else
drh2db82112016-09-15 21:35:24 +00004820
drhc2ce0be2014-05-29 12:36:14 +00004821 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4822 if( nArg==2 ){
4823 tryToClone(p, azArg[1]);
4824 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004825 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004826 rc = 1;
4827 }
mistachkine31ae902014-02-06 01:15:29 +00004828 }else
4829
drhc2ce0be2014-05-29 12:36:14 +00004830 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004831 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004832 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004833 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004834 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004835 data.showHeader = 0;
4836 data.cMode = data.mode = MODE_List;
4837 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004838 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004839 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4840 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004841 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004842 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004843 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004844 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004845 }
4846 }else
4847
drh0e55db12015-02-06 14:51:13 +00004848 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4849 rc = shell_dbinfo_command(p, nArg, azArg);
4850 }else
4851
drhc2ce0be2014-05-29 12:36:14 +00004852 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004853 const char *zLike = 0;
4854 int i;
drh72507d42017-04-08 00:55:13 +00004855 int savedShowHeader = p->showHeader;
drhe6e1d122017-03-09 13:50:49 +00004856 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004857 for(i=1; i<nArg; i++){
4858 if( azArg[i][0]=='-' ){
4859 const char *z = azArg[i]+1;
4860 if( z[0]=='-' ) z++;
4861 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00004862#ifdef SQLITE_OMIT_VIRTUALTABLE
4863 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4864 " with SQLITE_OMIT_VIRTUALTABLE\n");
4865 rc = 1;
4866 goto meta_command_exit;
4867#else
drhe6e1d122017-03-09 13:50:49 +00004868 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00004869#endif
drhe611f142017-03-08 11:44:00 +00004870 }else
4871 {
4872 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4873 rc = 1;
4874 goto meta_command_exit;
4875 }
4876 }else if( zLike ){
4877 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4878 rc = 1;
4879 goto meta_command_exit;
4880 }else{
4881 zLike = azArg[i];
4882 }
4883 }
drh05782482013-10-24 15:20:20 +00004884 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004885 /* When playing back a "dump", the content might appear in an order
4886 ** which causes immediate foreign key constraints to be violated.
4887 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004888 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4889 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004890 p->writableSchema = 0;
drh72507d42017-04-08 00:55:13 +00004891 p->showHeader = 0;
drhe611f142017-03-08 11:44:00 +00004892 /* Set writable_schema=ON since doing so forces SQLite to initialize
4893 ** as much of the schema as it can even if the sqlite_master table is
4894 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004895 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004896 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004897 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004898 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004899 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004900 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004901 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004902 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004903 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004904 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004905 );
drh2f464a02011-10-13 00:41:49 +00004906 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004907 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004908 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004909 );
drh4c653a02000-06-07 01:27:47 +00004910 }else{
drhe611f142017-03-08 11:44:00 +00004911 char *zSql;
4912 zSql = sqlite3_mprintf(
4913 "SELECT name, type, sql FROM sqlite_master "
4914 "WHERE tbl_name LIKE %Q AND type=='table'"
4915 " AND sql NOT NULL", zLike);
4916 run_schema_dump_query(p,zSql);
4917 sqlite3_free(zSql);
4918 zSql = sqlite3_mprintf(
4919 "SELECT sql FROM sqlite_master "
4920 "WHERE sql NOT NULL"
4921 " AND type IN ('index','trigger','view')"
4922 " AND tbl_name LIKE %Q", zLike);
4923 run_table_dump_query(p, zSql, 0);
4924 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00004925 }
drh45e29d82006-11-20 16:21:10 +00004926 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00004927 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00004928 p->writableSchema = 0;
4929 }
drh56197952011-10-13 16:30:13 +00004930 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4931 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00004932 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh72507d42017-04-08 00:55:13 +00004933 p->showHeader = savedShowHeader;
drh4c653a02000-06-07 01:27:47 +00004934 }else
drh75897232000-05-29 14:26:00 +00004935
drhc2ce0be2014-05-29 12:36:14 +00004936 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4937 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004938 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00004939 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004940 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004941 rc = 1;
4942 }
drhdaffd0e2001-04-11 14:28:42 +00004943 }else
4944
drhc2ce0be2014-05-29 12:36:14 +00004945 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4946 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00004947 if( strcmp(azArg[1],"full")==0 ){
4948 p->autoEQP = 2;
4949 }else{
4950 p->autoEQP = booleanValue(azArg[1]);
4951 }
drhc2ce0be2014-05-29 12:36:14 +00004952 }else{
drheacd29d2016-04-15 15:03:27 +00004953 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00004954 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00004955 }
drhefbf3b12014-02-28 20:47:24 +00004956 }else
4957
drhd3ac7d92013-01-25 18:33:43 +00004958 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00004959 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00004960 rc = 2;
drh75897232000-05-29 14:26:00 +00004961 }else
4962
drhc2ce0be2014-05-29 12:36:14 +00004963 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00004964 int val = 1;
4965 if( nArg>=2 ){
4966 if( strcmp(azArg[1],"auto")==0 ){
4967 val = 99;
4968 }else{
4969 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00004970 }
drh700c2522016-02-09 18:39:25 +00004971 }
4972 if( val==1 && p->mode!=MODE_Explain ){
4973 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00004974 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00004975 p->autoExplain = 0;
4976 }else if( val==0 ){
4977 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4978 p->autoExplain = 0;
4979 }else if( val==99 ){
4980 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4981 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00004982 }
drh75897232000-05-29 14:26:00 +00004983 }else
4984
drhc1971542014-06-23 23:28:13 +00004985 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004986 ShellState data;
drhc1971542014-06-23 23:28:13 +00004987 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00004988 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00004989 memcpy(&data, p, sizeof(data));
4990 data.showHeader = 0;
4991 data.cMode = data.mode = MODE_Semi;
4992 if( nArg==2 && optionMatch(azArg[1], "indent") ){
4993 data.cMode = data.mode = MODE_Pretty;
4994 nArg = 1;
4995 }
drhc1971542014-06-23 23:28:13 +00004996 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00004997 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00004998 rc = 1;
4999 goto meta_command_exit;
5000 }
5001 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00005002 rc = sqlite3_exec(p->db,
5003 "SELECT sql FROM"
5004 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5005 " FROM sqlite_master UNION ALL"
5006 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005007 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00005008 "ORDER BY rowid",
5009 callback, &data, &zErrMsg
5010 );
drh56f674c2014-07-18 14:43:29 +00005011 if( rc==SQLITE_OK ){
5012 sqlite3_stmt *pStmt;
5013 rc = sqlite3_prepare_v2(p->db,
5014 "SELECT rowid FROM sqlite_master"
5015 " WHERE name GLOB 'sqlite_stat[134]'",
5016 -1, &pStmt, 0);
5017 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5018 sqlite3_finalize(pStmt);
5019 }
5020 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005021 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00005022 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005023 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005024 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5025 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00005026 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00005027 data.zDestTable = "sqlite_stat1";
5028 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5029 shell_callback, &data,&zErrMsg);
5030 data.zDestTable = "sqlite_stat3";
5031 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5032 shell_callback, &data,&zErrMsg);
5033 data.zDestTable = "sqlite_stat4";
5034 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5035 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00005036 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005037 }
drhc1971542014-06-23 23:28:13 +00005038 }else
5039
drhc2ce0be2014-05-29 12:36:14 +00005040 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5041 if( nArg==2 ){
5042 p->showHeader = booleanValue(azArg[1]);
5043 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005044 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005045 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00005046 }
drh75897232000-05-29 14:26:00 +00005047 }else
5048
drhc2ce0be2014-05-29 12:36:14 +00005049 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005050 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00005051 }else
5052
5053 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00005054 char *zTable; /* Insert data into this table */
5055 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00005056 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00005057 int nCol; /* Number of columns in the table */
5058 int nByte; /* Number of bytes in an SQL string */
5059 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00005060 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00005061 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00005062 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00005063 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00005064 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5065 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00005066
drhc2ce0be2014-05-29 12:36:14 +00005067 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005068 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00005069 goto meta_command_exit;
5070 }
drh01f37542014-05-31 15:43:33 +00005071 zFile = azArg[1];
5072 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00005073 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00005074 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00005075 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005076 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00005077 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005078 raw_printf(stderr,
5079 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00005080 return 1;
drhfeac5f82004-08-01 00:10:45 +00005081 }
drhdb95f682013-06-26 22:46:00 +00005082 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005083 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00005084 " for import\n");
5085 return 1;
5086 }
mistachkin636bf9f2014-07-19 20:15:16 +00005087 nSep = strlen30(p->rowSeparator);
5088 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005089 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005090 return 1;
5091 }
mistachkine0d68852014-12-11 03:12:33 +00005092 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5093 /* When importing CSV (only), if the row separator is set to the
5094 ** default output row separator, change it to the default input
5095 ** row separator. This avoids having to maintain different input
5096 ** and output row separators. */
5097 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5098 nSep = strlen30(p->rowSeparator);
5099 }
mistachkin636bf9f2014-07-19 20:15:16 +00005100 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005101 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00005102 " for import\n");
5103 return 1;
5104 }
5105 sCtx.zFile = zFile;
5106 sCtx.nLine = 1;
5107 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005108#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005109 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005110 return 1;
5111#else
mistachkin636bf9f2014-07-19 20:15:16 +00005112 sCtx.in = popen(sCtx.zFile+1, "r");
5113 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00005114 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00005115#endif
drh5bde8162013-06-27 14:07:53 +00005116 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00005117 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00005118 xCloser = fclose;
5119 }
mistachkin636bf9f2014-07-19 20:15:16 +00005120 if( p->mode==MODE_Ascii ){
5121 xRead = ascii_read_one_field;
5122 }else{
5123 xRead = csv_read_one_field;
5124 }
5125 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005126 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00005127 return 1;
5128 }
mistachkin636bf9f2014-07-19 20:15:16 +00005129 sCtx.cColSep = p->colSeparator[0];
5130 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00005131 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00005132 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005133 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005134 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005135 return 1;
5136 }
drh4f21c4a2008-12-10 22:15:00 +00005137 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005138 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005139 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005140 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005141 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5142 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005143 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005144 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005145 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005146 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005147 }
drh5bde8162013-06-27 14:07:53 +00005148 if( cSep=='(' ){
5149 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005150 sqlite3_free(sCtx.z);
5151 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005152 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005153 return 1;
5154 }
drhdb95f682013-06-26 22:46:00 +00005155 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5156 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5157 sqlite3_free(zCreate);
5158 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005159 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005160 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005161 sqlite3_free(sCtx.z);
5162 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005163 return 1;
5164 }
drhc7181902014-02-27 15:04:13 +00005165 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005166 }
drhfeac5f82004-08-01 00:10:45 +00005167 sqlite3_free(zSql);
5168 if( rc ){
shane916f9612009-10-23 00:37:15 +00005169 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005170 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005171 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005172 return 1;
drhfeac5f82004-08-01 00:10:45 +00005173 }
shane916f9612009-10-23 00:37:15 +00005174 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005175 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005176 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005177 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005178 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005179 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005180 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005181 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005182 return 1;
5183 }
drhdb95f682013-06-26 22:46:00 +00005184 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005185 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005186 for(i=1; i<nCol; i++){
5187 zSql[j++] = ',';
5188 zSql[j++] = '?';
5189 }
5190 zSql[j++] = ')';
5191 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005192 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005193 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005194 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005195 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005196 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00005197 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00005198 return 1;
drhfeac5f82004-08-01 00:10:45 +00005199 }
mistachkin8e189222015-04-19 21:43:16 +00005200 needCommit = sqlite3_get_autocommit(p->db);
5201 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00005202 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005203 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005204 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005205 char *z = xRead(&sCtx);
5206 /*
5207 ** Did we reach end-of-file before finding any columns?
5208 ** If so, stop instead of NULL filling the remaining columns.
5209 */
drhdb95f682013-06-26 22:46:00 +00005210 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005211 /*
5212 ** Did we reach end-of-file OR end-of-line before finding any
5213 ** columns in ASCII mode? If so, stop instead of NULL filling
5214 ** the remaining columns.
5215 */
5216 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005217 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005218 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005219 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005220 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005221 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005222 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005223 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005224 }
drhfeac5f82004-08-01 00:10:45 +00005225 }
mistachkin636bf9f2014-07-19 20:15:16 +00005226 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005227 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005228 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005229 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005230 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005231 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005232 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005233 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005234 }
drhdb95f682013-06-26 22:46:00 +00005235 if( i>=nCol ){
5236 sqlite3_step(pStmt);
5237 rc = sqlite3_reset(pStmt);
5238 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005239 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5240 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005241 }
5242 }
mistachkin636bf9f2014-07-19 20:15:16 +00005243 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005244
mistachkin636bf9f2014-07-19 20:15:16 +00005245 xCloser(sCtx.in);
5246 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005247 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005248 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005249 }else
5250
drhd12602a2016-12-07 15:49:02 +00005251#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005252 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5253 char *zSql;
5254 char *zCollist = 0;
5255 sqlite3_stmt *pStmt;
5256 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005257 int i;
drh16eb5942016-11-03 13:01:38 +00005258 if( nArg!=3 ){
5259 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5260 rc = 1;
5261 goto meta_command_exit;
5262 }
5263 open_db(p, 0);
5264 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5265 " WHERE name='%q' AND type='index'", azArg[1]);
5266 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5267 sqlite3_free(zSql);
5268 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5269 tnum = sqlite3_column_int(pStmt, 0);
5270 }
5271 sqlite3_finalize(pStmt);
5272 if( tnum==0 ){
5273 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5274 rc = 1;
5275 goto meta_command_exit;
5276 }
5277 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5278 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5279 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005280 i = 0;
drh16eb5942016-11-03 13:01:38 +00005281 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005282 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005283 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005284 i++;
5285 if( zCol==0 ){
5286 if( sqlite3_column_int(pStmt,1)==-1 ){
5287 zCol = "_ROWID_";
5288 }else{
5289 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5290 zCol = zLabel;
5291 }
5292 }
drh16eb5942016-11-03 13:01:38 +00005293 if( zCollist==0 ){
5294 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5295 }else{
5296 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5297 }
5298 }
5299 sqlite3_finalize(pStmt);
5300 zSql = sqlite3_mprintf(
5301 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5302 azArg[2], zCollist, zCollist);
5303 sqlite3_free(zCollist);
5304 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5305 if( rc==SQLITE_OK ){
5306 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5307 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5308 if( rc ){
5309 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5310 }else{
5311 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005312 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005313 "WARNING: writing to an imposter table will corrupt the index!\n"
5314 );
5315 }
5316 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005317 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005318 rc = 1;
5319 }
5320 sqlite3_free(zSql);
5321 }else
5322#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5323
drhae5e4452007-05-03 17:18:36 +00005324#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005325 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005326 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005327 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5328 iotrace = 0;
5329 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005330 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005331 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005332 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005333 iotrace = stdout;
5334 }else{
5335 iotrace = fopen(azArg[1], "w");
5336 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005337 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005338 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005339 rc = 1;
drhb0603412007-02-28 04:47:26 +00005340 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005341 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005342 }
5343 }
5344 }else
drhae5e4452007-05-03 17:18:36 +00005345#endif
drh16eb5942016-11-03 13:01:38 +00005346
drh1a513372015-05-02 17:40:23 +00005347 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5348 static const struct {
5349 const char *zLimitName; /* Name of a limit */
5350 int limitCode; /* Integer code for that limit */
5351 } aLimit[] = {
5352 { "length", SQLITE_LIMIT_LENGTH },
5353 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5354 { "column", SQLITE_LIMIT_COLUMN },
5355 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5356 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5357 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5358 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5359 { "attached", SQLITE_LIMIT_ATTACHED },
5360 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5361 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5362 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5363 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5364 };
5365 int i, n2;
5366 open_db(p, 0);
5367 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005368 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005369 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005370 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5371 }
5372 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005373 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005374 rc = 1;
5375 goto meta_command_exit;
5376 }else{
5377 int iLimit = -1;
5378 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005379 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005380 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5381 if( iLimit<0 ){
5382 iLimit = i;
5383 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005384 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005385 rc = 1;
5386 goto meta_command_exit;
5387 }
5388 }
5389 }
5390 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005391 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005392 "enter \".limits\" with no arguments for a list.\n",
5393 azArg[1]);
5394 rc = 1;
5395 goto meta_command_exit;
5396 }
5397 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005398 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5399 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005400 }
5401 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5402 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5403 }
5404 }else
drhb0603412007-02-28 04:47:26 +00005405
dan3c7ebeb2016-12-16 17:28:56 +00005406 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005407 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005408 lintDotCommand(p, azArg, nArg);
5409 }else
5410
drh70df4fe2006-06-13 15:12:21 +00005411#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005412 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005413 const char *zFile, *zProc;
5414 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005415 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005416 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005417 rc = 1;
5418 goto meta_command_exit;
5419 }
drh1e397f82006-06-08 15:28:43 +00005420 zFile = azArg[1];
5421 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005422 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005423 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5424 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005425 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005426 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005427 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005428 }
5429 }else
drh70df4fe2006-06-13 15:12:21 +00005430#endif
drh1e397f82006-06-08 15:28:43 +00005431
drhc2ce0be2014-05-29 12:36:14 +00005432 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5433 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005434 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005435 rc = 1;
5436 }else{
5437 const char *zFile = azArg[1];
5438 output_file_close(p->pLog);
5439 p->pLog = output_file_open(zFile);
5440 }
drh127f9d72010-02-23 01:47:00 +00005441 }else
5442
drhc2ce0be2014-05-29 12:36:14 +00005443 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5444 const char *zMode = nArg>=2 ? azArg[1] : "";
5445 int n2 = (int)strlen(zMode);
5446 int c2 = zMode[0];
5447 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005448 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005449 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005450 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005451 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005452 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005453 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005454 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005455 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5456 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005457 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005458 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005459 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005460 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005461 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005462 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005463 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005464 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005465 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005466 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005467 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005468 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005469 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005470 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005471 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005472 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005473 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5474 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005475 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5476 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005477 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5478 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drhdaffd0e2001-04-11 14:28:42 +00005479 }else {
mistachkinaae280e2015-12-31 19:06:24 +00005480 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005481 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005482 rc = 1;
drh75897232000-05-29 14:26:00 +00005483 }
drh700c2522016-02-09 18:39:25 +00005484 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005485 }else
5486
drhc2ce0be2014-05-29 12:36:14 +00005487 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5488 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005489 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5490 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005491 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005492 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005493 rc = 1;
5494 }
5495 }else
5496
drh05782482013-10-24 15:20:20 +00005497 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005498 char *zNewFilename; /* Name of the database file to open */
5499 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005500 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005501 /* Close the existing database */
5502 session_close_all(p);
5503 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005504 p->db = 0;
dan21472212017-03-01 11:30:27 +00005505 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005506 sqlite3_free(p->zFreeOnClose);
5507 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005508 /* Check for command-line arguments */
5509 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5510 const char *z = azArg[iName];
5511 if( optionMatch(z,"new") ){
5512 newFlag = 1;
5513 }else if( z[0]=='-' ){
5514 utf8_printf(stderr, "unknown option: %s\n", z);
5515 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005516 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005517 }
drhcd0509e2016-09-16 00:26:08 +00005518 }
5519 /* If a filename is specified, try to open it first */
5520 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5521 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005522 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005523 p->zDbFilename = zNewFilename;
5524 open_db(p, 1);
5525 if( p->db==0 ){
5526 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5527 sqlite3_free(zNewFilename);
5528 }else{
5529 p->zFreeOnClose = zNewFilename;
5530 }
5531 }
5532 if( p->db==0 ){
5533 /* As a fall-back open a TEMP database */
5534 p->zDbFilename = 0;
5535 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005536 }
5537 }else
5538
drhc2ce0be2014-05-29 12:36:14 +00005539 if( c=='o'
5540 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5541 ){
5542 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5543 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005544 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005545 rc = 1;
5546 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005547 }
drhc2ce0be2014-05-29 12:36:14 +00005548 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5549 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005550 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005551 rc = 1;
5552 goto meta_command_exit;
5553 }
5554 p->outCount = 2;
5555 }else{
5556 p->outCount = 0;
5557 }
5558 output_reset(p);
5559 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005560#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005561 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005562 rc = 1;
5563 p->out = stdout;
5564#else
drhc2ce0be2014-05-29 12:36:14 +00005565 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005566 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005567 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005568 p->out = stdout;
5569 rc = 1;
5570 }else{
drhc2ce0be2014-05-29 12:36:14 +00005571 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005572 }
drh8cd5b252015-03-02 22:06:43 +00005573#endif
drh75897232000-05-29 14:26:00 +00005574 }else{
drhc2ce0be2014-05-29 12:36:14 +00005575 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005576 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005577 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005578 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005579 }
drh75897232000-05-29 14:26:00 +00005580 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005581 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005582 } else {
drhc2ce0be2014-05-29 12:36:14 +00005583 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005584 }
5585 }
5586 }else
5587
drh078b1fd2012-09-21 13:40:02 +00005588 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5589 int i;
5590 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005591 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005592 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005593 }
mistachkinaae280e2015-12-31 19:06:24 +00005594 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005595 }else
5596
drhc2ce0be2014-05-29 12:36:14 +00005597 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005598 if( nArg >= 2) {
5599 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5600 }
5601 if( nArg >= 3) {
5602 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5603 }
5604 }else
5605
drhc2ce0be2014-05-29 12:36:14 +00005606 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005607 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005608 }else
5609
drhc2ce0be2014-05-29 12:36:14 +00005610 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5611 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005612 if( nArg!=2 ){
5613 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005614 rc = 1;
5615 goto meta_command_exit;
5616 }
drh4e8142c2016-11-11 14:54:22 +00005617 alt = fopen(azArg[1], "rb");
5618 if( alt==0 ){
5619 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5620 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005621 }else{
drh4e8142c2016-11-11 14:54:22 +00005622 rc = process_input(p, alt);
5623 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005624 }
5625 }else
5626
drhc2ce0be2014-05-29 12:36:14 +00005627 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005628 const char *zSrcFile;
5629 const char *zDb;
5630 sqlite3 *pSrc;
5631 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005632 int nTimeout = 0;
5633
drh9ff849f2009-02-04 20:55:57 +00005634 if( nArg==2 ){
5635 zSrcFile = azArg[1];
5636 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005637 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005638 zSrcFile = azArg[2];
5639 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005640 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005641 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005642 rc = 1;
5643 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005644 }
5645 rc = sqlite3_open(zSrcFile, &pSrc);
5646 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005647 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005648 sqlite3_close(pSrc);
5649 return 1;
5650 }
drh05782482013-10-24 15:20:20 +00005651 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005652 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5653 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005654 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005655 sqlite3_close(pSrc);
5656 return 1;
5657 }
drhdc2c4912009-02-04 22:46:47 +00005658 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5659 || rc==SQLITE_BUSY ){
5660 if( rc==SQLITE_BUSY ){
5661 if( nTimeout++ >= 3 ) break;
5662 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005663 }
5664 }
5665 sqlite3_backup_finish(pBackup);
5666 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005667 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005668 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005669 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005670 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005671 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005672 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005673 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005674 }
5675 sqlite3_close(pSrc);
5676 }else
5677
dan8d1edb92014-11-05 09:07:28 +00005678
5679 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5680 if( nArg==2 ){
5681 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005682#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005683 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005684#endif
dan8d1edb92014-11-05 09:07:28 +00005685 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005686 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005687 rc = 1;
5688 }
5689 }else
5690
drhc2ce0be2014-05-29 12:36:14 +00005691 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005692 ShellState data;
drh75897232000-05-29 14:26:00 +00005693 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00005694 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005695 memcpy(&data, p, sizeof(data));
5696 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005697 data.cMode = data.mode = MODE_Semi;
drh4926fec2016-04-13 15:33:42 +00005698 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5699 data.cMode = data.mode = MODE_Pretty;
5700 nArg--;
5701 if( nArg==2 ) azArg[1] = azArg[2];
5702 }
5703 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005704 int i;
drhf0693c82011-10-11 20:41:54 +00005705 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005706 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005707 char *new_argv[2], *new_colv[2];
5708 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5709 " type text,\n"
5710 " name text,\n"
5711 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005712 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005713 " sql text\n"
5714 ")";
5715 new_argv[1] = 0;
5716 new_colv[0] = "sql";
5717 new_colv[1] = 0;
5718 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005719 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005720 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005721 char *new_argv[2], *new_colv[2];
5722 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5723 " type text,\n"
5724 " name text,\n"
5725 " tbl_name text,\n"
5726 " rootpage integer,\n"
5727 " sql text\n"
5728 ")";
5729 new_argv[1] = 0;
5730 new_colv[0] = "sql";
5731 new_colv[1] = 0;
5732 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005733 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005734 }else{
drhe611f142017-03-08 11:44:00 +00005735 char *zSql;
5736 zSql = sqlite3_mprintf(
drhe0bc4042002-06-25 01:09:11 +00005737 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005738 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005739 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005740 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drhe611f142017-03-08 11:44:00 +00005741 "WHERE lower(tbl_name) LIKE %Q"
drh6ac7a582011-11-04 00:35:56 +00005742 " AND type!='meta' AND sql NOTNULL "
drhe611f142017-03-08 11:44:00 +00005743 "ORDER BY rowid", azArg[1]);
5744 rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
5745 sqlite3_free(zSql);
drha18c5682000-10-08 22:20:57 +00005746 }
drhc2ce0be2014-05-29 12:36:14 +00005747 }else if( nArg==1 ){
shane9bd1b442009-10-23 01:27:39 +00005748 rc = sqlite3_exec(p->db,
drhe0bc4042002-06-25 01:09:11 +00005749 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005750 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005751 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005752 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005753 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drh1ba00292013-05-06 21:01:06 +00005754 "ORDER BY rowid",
drha18c5682000-10-08 22:20:57 +00005755 callback, &data, &zErrMsg
5756 );
drhc2ce0be2014-05-29 12:36:14 +00005757 }else{
drh4926fec2016-04-13 15:33:42 +00005758 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005759 rc = 1;
5760 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005761 }
drh75897232000-05-29 14:26:00 +00005762 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005763 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005764 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005765 rc = 1;
5766 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005767 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005768 rc = 1;
5769 }else{
5770 rc = 0;
drh75897232000-05-29 14:26:00 +00005771 }
5772 }else
5773
drhabd4c722014-09-20 18:18:33 +00005774#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5775 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005776 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005777 }else
5778#endif
5779
drhe6229612014-08-18 15:08:26 +00005780#if defined(SQLITE_ENABLE_SESSION)
5781 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5782 OpenSession *pSession = &p->aSession[0];
5783 char **azCmd = &azArg[1];
5784 int iSes = 0;
5785 int nCmd = nArg - 1;
5786 int i;
5787 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005788 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005789 if( nArg>=3 ){
5790 for(iSes=0; iSes<p->nSession; iSes++){
5791 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5792 }
5793 if( iSes<p->nSession ){
5794 pSession = &p->aSession[iSes];
5795 azCmd++;
5796 nCmd--;
5797 }else{
5798 pSession = &p->aSession[0];
5799 iSes = 0;
5800 }
5801 }
5802
drh3a67b042014-08-18 17:56:31 +00005803 /* .session attach TABLE
5804 ** Invoke the sqlite3session_attach() interface to attach a particular
5805 ** table so that it is never filtered.
5806 */
5807 if( strcmp(azCmd[0],"attach")==0 ){
5808 if( nCmd!=2 ) goto session_syntax_error;
5809 if( pSession->p==0 ){
5810 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005811 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005812 }else{
5813 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5814 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005815 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005816 rc = 0;
5817 }
5818 }
5819 }else
5820
5821 /* .session changeset FILE
5822 ** .session patchset FILE
5823 ** Write a changeset or patchset into a file. The file is overwritten.
5824 */
5825 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5826 FILE *out = 0;
5827 if( nCmd!=2 ) goto session_syntax_error;
5828 if( pSession->p==0 ) goto session_not_open;
5829 out = fopen(azCmd[1], "wb");
5830 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005831 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005832 }else{
5833 int szChng;
5834 void *pChng;
5835 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005836 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005837 }else{
drh2967e0c2014-08-19 00:26:17 +00005838 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5839 }
5840 if( rc ){
5841 printf("Error: error code %d\n", rc);
5842 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005843 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005844 if( pChng
drh3a67b042014-08-18 17:56:31 +00005845 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005846 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005847 szChng);
5848 }
5849 sqlite3_free(pChng);
5850 fclose(out);
5851 }
5852 }else
5853
drhe6229612014-08-18 15:08:26 +00005854 /* .session close
5855 ** Close the identified session
5856 */
5857 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005858 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005859 if( p->nSession ){
5860 session_close(pSession);
5861 p->aSession[iSes] = p->aSession[--p->nSession];
5862 }
5863 }else
5864
drh03168ca2014-08-18 20:01:31 +00005865 /* .session enable ?BOOLEAN?
5866 ** Query or set the enable flag
5867 */
5868 if( strcmp(azCmd[0], "enable")==0 ){
5869 int ii;
5870 if( nCmd>2 ) goto session_syntax_error;
5871 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5872 if( p->nSession ){
5873 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005874 utf8_printf(p->out, "session %s enable flag = %d\n",
5875 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005876 }
5877 }else
5878
5879 /* .session filter GLOB ....
5880 ** Set a list of GLOB patterns of table names to be excluded.
5881 */
5882 if( strcmp(azCmd[0], "filter")==0 ){
5883 int ii, nByte;
5884 if( nCmd<2 ) goto session_syntax_error;
5885 if( p->nSession ){
5886 for(ii=0; ii<pSession->nFilter; ii++){
5887 sqlite3_free(pSession->azFilter[ii]);
5888 }
5889 sqlite3_free(pSession->azFilter);
5890 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5891 pSession->azFilter = sqlite3_malloc( nByte );
5892 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005893 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00005894 exit(1);
5895 }
5896 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005897 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00005898 }
5899 pSession->nFilter = ii-1;
5900 }
5901 }else
5902
5903 /* .session indirect ?BOOLEAN?
5904 ** Query or set the indirect flag
5905 */
5906 if( strcmp(azCmd[0], "indirect")==0 ){
5907 int ii;
5908 if( nCmd>2 ) goto session_syntax_error;
5909 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5910 if( p->nSession ){
5911 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005912 utf8_printf(p->out, "session %s indirect flag = %d\n",
5913 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005914 }
5915 }else
5916
5917 /* .session isempty
5918 ** Determine if the session is empty
5919 */
5920 if( strcmp(azCmd[0], "isempty")==0 ){
5921 int ii;
5922 if( nCmd!=1 ) goto session_syntax_error;
5923 if( p->nSession ){
5924 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00005925 utf8_printf(p->out, "session %s isempty flag = %d\n",
5926 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005927 }
5928 }else
5929
drhe6229612014-08-18 15:08:26 +00005930 /* .session list
5931 ** List all currently open sessions
5932 */
5933 if( strcmp(azCmd[0],"list")==0 ){
5934 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00005935 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00005936 }
5937 }else
5938
5939 /* .session open DB NAME
5940 ** Open a new session called NAME on the attached database DB.
5941 ** DB is normally "main".
5942 */
5943 if( strcmp(azCmd[0],"open")==0 ){
5944 char *zName;
5945 if( nCmd!=3 ) goto session_syntax_error;
5946 zName = azCmd[2];
5947 if( zName[0]==0 ) goto session_syntax_error;
5948 for(i=0; i<p->nSession; i++){
5949 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005950 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00005951 goto meta_command_exit;
5952 }
5953 }
5954 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00005955 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00005956 goto meta_command_exit;
5957 }
5958 pSession = &p->aSession[p->nSession];
5959 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5960 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005961 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005962 rc = 0;
drhe6229612014-08-18 15:08:26 +00005963 goto meta_command_exit;
5964 }
drh03168ca2014-08-18 20:01:31 +00005965 pSession->nFilter = 0;
5966 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00005967 p->nSession++;
5968 pSession->zName = sqlite3_mprintf("%s", zName);
5969 }else
5970 /* If no command name matches, show a syntax error */
5971 session_syntax_error:
5972 session_help(p);
5973 }else
5974#endif
5975
drh340f5822013-06-27 13:01:21 +00005976#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00005977 /* Undocumented commands for internal testing. Subject to change
5978 ** without notice. */
5979 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5980 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5981 int i, v;
5982 for(i=1; i<nArg; i++){
5983 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00005984 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00005985 }
5986 }
5987 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5988 int i; sqlite3_int64 v;
5989 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00005990 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00005991 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00005992 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00005993 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00005994 }
5995 }
5996 }else
drh340f5822013-06-27 13:01:21 +00005997#endif
drh348d19c2013-06-03 12:47:43 +00005998
drhfb546af2017-03-09 22:00:33 +00005999 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6000 int bIsInit = 0; /* True to initialize the SELFTEST table */
6001 int bVerbose = 0; /* Verbose output */
6002 int bSelftestExists; /* True if SELFTEST already exists */
drhc5d353f2017-06-09 02:27:49 +00006003 int i, k; /* Loop counters */
drhfb546af2017-03-09 22:00:33 +00006004 int nTest = 0; /* Number of tests runs */
6005 int nErr = 0; /* Number of errors seen */
6006 ShellText str; /* Answer for a query */
drhc5d353f2017-06-09 02:27:49 +00006007 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
drhfb546af2017-03-09 22:00:33 +00006008
6009 open_db(p,0);
6010 for(i=1; i<nArg; i++){
6011 const char *z = azArg[i];
6012 if( z[0]=='-' && z[1]=='-' ) z++;
6013 if( strcmp(z,"-init")==0 ){
6014 bIsInit = 1;
6015 }else
6016 if( strcmp(z,"-v")==0 ){
6017 bVerbose++;
6018 }else
6019 {
6020 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6021 azArg[i], azArg[0]);
6022 raw_printf(stderr, "Should be one of: --init -v\n");
6023 rc = 1;
6024 goto meta_command_exit;
6025 }
6026 }
6027 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6028 != SQLITE_OK ){
6029 bSelftestExists = 0;
6030 }else{
6031 bSelftestExists = 1;
6032 }
6033 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006034 createSelftestTable(p);
6035 bSelftestExists = 1;
6036 }
drhc5d353f2017-06-09 02:27:49 +00006037 initText(&str);
6038 appendText(&str, "x", 0);
6039 for(k=bSelftestExists; k>=0; k--){
6040 if( k==1 ){
6041 rc = sqlite3_prepare_v2(p->db,
6042 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6043 -1, &pStmt, 0);
6044 }else{
6045 rc = sqlite3_prepare_v2(p->db,
6046 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6047 " (1,'run','PRAGMA integrity_check','ok')",
6048 -1, &pStmt, 0);
6049 }
drhfb546af2017-03-09 22:00:33 +00006050 if( rc ){
6051 raw_printf(stderr, "Error querying the selftest table\n");
6052 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006053 sqlite3_finalize(pStmt);
drhfb546af2017-03-09 22:00:33 +00006054 goto meta_command_exit;
drhfb546af2017-03-09 22:00:33 +00006055 }
drhc5d353f2017-06-09 02:27:49 +00006056 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6057 int tno = sqlite3_column_int(pStmt, 0);
6058 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6059 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6060 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
mistachkine16a3502017-05-29 03:48:13 +00006061
drhc5d353f2017-06-09 02:27:49 +00006062 k = 0;
6063 if( bVerbose>0 ){
6064 char *zQuote = sqlite3_mprintf("%q", zSql);
6065 printf("%d: %s %s\n", tno, zOp, zSql);
6066 sqlite3_free(zQuote);
drhfb546af2017-03-09 22:00:33 +00006067 }
drhc5d353f2017-06-09 02:27:49 +00006068 if( strcmp(zOp,"memo")==0 ){
6069 utf8_printf(p->out, "%s\n", zSql);
6070 }else
6071 if( strcmp(zOp,"run")==0 ){
6072 char *zErrMsg = 0;
6073 str.n = 0;
6074 str.z[0] = 0;
6075 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6076 nTest++;
6077 if( bVerbose ){
6078 utf8_printf(p->out, "Result: %s\n", str.z);
6079 }
6080 if( rc || zErrMsg ){
6081 nErr++;
6082 rc = 1;
6083 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6084 sqlite3_free(zErrMsg);
6085 }else if( strcmp(zAns,str.z)!=0 ){
6086 nErr++;
6087 rc = 1;
6088 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6089 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6090 }
6091 }else
6092 {
6093 utf8_printf(stderr,
6094 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
drhfb546af2017-03-09 22:00:33 +00006095 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006096 break;
drhfb546af2017-03-09 22:00:33 +00006097 }
drhc5d353f2017-06-09 02:27:49 +00006098 } /* End loop over rows of content from SELFTEST */
6099 sqlite3_finalize(pStmt);
6100 } /* End loop over k */
drhfb546af2017-03-09 22:00:33 +00006101 freeText(&str);
drhfb546af2017-03-09 22:00:33 +00006102 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6103 }else
6104
drhc2ce0be2014-05-29 12:36:14 +00006105 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006106 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006107 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006108 rc = 1;
6109 }
drh6976c212014-07-24 12:09:47 +00006110 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006111 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006112 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006113 }
6114 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006115 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6116 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006117 }
drh75897232000-05-29 14:26:00 +00006118 }else
6119
drh1554bc82017-03-08 16:10:34 +00006120 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6121 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6122 int i; /* Loop counter */
6123 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006124 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006125 int iSize = 224; /* Hash algorithm to use */
6126 int bDebug = 0; /* Only show the query that would have run */
6127 sqlite3_stmt *pStmt; /* For querying tables names */
6128 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006129 char *zSep; /* Separator */
6130 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006131 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006132 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006133 for(i=1; i<nArg; i++){
6134 const char *z = azArg[i];
6135 if( z[0]=='-' ){
6136 z++;
6137 if( z[0]=='-' ) z++;
6138 if( strcmp(z,"schema")==0 ){
6139 bSchema = 1;
6140 }else
mistachkine16a3502017-05-29 03:48:13 +00006141 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6142 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
drh1554bc82017-03-08 16:10:34 +00006143 ){
6144 iSize = atoi(&z[5]);
6145 }else
6146 if( strcmp(z,"debug")==0 ){
6147 bDebug = 1;
6148 }else
6149 {
6150 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006151 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006152 raw_printf(stderr, "Should be one of: --schema"
6153 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6154 rc = 1;
6155 goto meta_command_exit;
6156 }
6157 }else if( zLike ){
6158 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6159 rc = 1;
6160 goto meta_command_exit;
6161 }else{
6162 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006163 bSeparate = 1;
6164 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006165 }
6166 }
6167 if( bSchema ){
6168 zSql = "SELECT lower(name) FROM sqlite_master"
6169 " WHERE type='table' AND coalesce(rootpage,0)>1"
6170 " UNION ALL SELECT 'sqlite_master'"
6171 " ORDER BY 1 collate nocase";
6172 }else{
6173 zSql = "SELECT lower(name) FROM sqlite_master"
6174 " WHERE type='table' AND coalesce(rootpage,0)>1"
6175 " AND name NOT LIKE 'sqlite_%'"
6176 " ORDER BY 1 collate nocase";
6177 }
6178 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6179 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006180 initText(&sSql);
6181 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6182 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006183 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6184 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6185 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6186 if( strncmp(zTab, "sqlite_",7)!=0 ){
6187 appendText(&sQuery,"SELECT * FROM ", 0);
6188 appendText(&sQuery,zTab,'"');
6189 appendText(&sQuery," NOT INDEXED;", 0);
6190 }else if( strcmp(zTab, "sqlite_master")==0 ){
6191 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6192 " ORDER BY name;", 0);
6193 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6194 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6195 " ORDER BY name;", 0);
6196 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6197 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6198 " ORDER BY tbl,idx;", 0);
6199 }else if( strcmp(zTab, "sqlite_stat3")==0
6200 || strcmp(zTab, "sqlite_stat4")==0 ){
6201 appendText(&sQuery, "SELECT * FROM ", 0);
6202 appendText(&sQuery, zTab, 0);
6203 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6204 }
drh3ee83ef2017-03-08 17:56:54 +00006205 appendText(&sSql, zSep, 0);
6206 appendText(&sSql, sQuery.z, '\'');
6207 sQuery.n = 0;
6208 appendText(&sSql, ",", 0);
6209 appendText(&sSql, zTab, '\'');
6210 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006211 }
6212 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006213 if( bSeparate ){
6214 zSql = sqlite3_mprintf(
6215 "%s))"
6216 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6217 " FROM [sha3sum$query]",
6218 sSql.z, iSize);
6219 }else{
6220 zSql = sqlite3_mprintf(
6221 "%s))"
6222 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6223 " FROM [sha3sum$query]",
6224 sSql.z, iSize);
6225 }
drh1554bc82017-03-08 16:10:34 +00006226 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006227 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006228 if( bDebug ){
6229 utf8_printf(p->out, "%s\n", zSql);
6230 }else{
6231 shell_exec(p->db, zSql, shell_callback, p, 0);
6232 }
6233 sqlite3_free(zSql);
6234 }else
6235
drh62cdde52014-05-28 20:22:28 +00006236 if( c=='s'
6237 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006238 ){
6239 char *zCmd;
drh54027102014-08-06 14:36:53 +00006240 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006241 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006242 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006243 rc = 1;
6244 goto meta_command_exit;
6245 }
drhdcb3e3d2014-05-29 03:17:29 +00006246 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006247 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006248 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6249 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006250 }
drh54027102014-08-06 14:36:53 +00006251 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006252 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006253 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006254 }else
6255
drhc2ce0be2014-05-29 12:36:14 +00006256 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006257 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006258 int i;
drhc2ce0be2014-05-29 12:36:14 +00006259 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006260 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006261 rc = 1;
6262 goto meta_command_exit;
6263 }
drhe6e1d122017-03-09 13:50:49 +00006264 utf8_printf(p->out, "%12.12s: %s\n","echo",
6265 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006266 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006267 utf8_printf(p->out, "%12.12s: %s\n","explain",
6268 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006269 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006270 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6271 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006272 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006273 raw_printf(p->out, "\n");
6274 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006275 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006276 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006277 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006278 raw_printf(p->out, "\n");
6279 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006280 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006281 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006282 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006283 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006284 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006285 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006286 }
mistachkinaae280e2015-12-31 19:06:24 +00006287 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006288 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6289 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006290 }else
6291
drhc2ce0be2014-05-29 12:36:14 +00006292 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6293 if( nArg==2 ){
6294 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006295 }else if( nArg==1 ){
6296 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006297 }else{
drh34784902016-02-27 17:12:36 +00006298 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006299 rc = 1;
6300 }
shaneh642d8b82010-07-28 16:05:34 +00006301 }else
6302
drh6a5a4202016-12-24 21:32:40 +00006303 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6304 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6305 || strncmp(azArg[0], "indexes", n)==0) )
6306 ){
drh98781232012-04-23 12:38:05 +00006307 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006308 char **azResult;
drh98781232012-04-23 12:38:05 +00006309 int nRow, nAlloc;
6310 char *zSql = 0;
6311 int ii;
drh05782482013-10-24 15:20:20 +00006312 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006313 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006314 if( rc ) return shellDatabaseError(p->db);
6315
6316 /* Create an SQL statement to query for the list of tables in the
6317 ** main and all attached databases where the table name matches the
6318 ** LIKE pattern bound to variable "?1". */
drh6a5a4202016-12-24 21:32:40 +00006319 if( c=='t' ){
6320 zSql = sqlite3_mprintf(
6321 "SELECT name FROM sqlite_master"
6322 " WHERE type IN ('table','view')"
6323 " AND name NOT LIKE 'sqlite_%%'"
6324 " AND name LIKE ?1");
6325 }else if( nArg>2 ){
6326 /* It is an historical accident that the .indexes command shows an error
6327 ** when called with the wrong number of arguments whereas the .tables
6328 ** command does not. */
6329 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6330 rc = 1;
6331 goto meta_command_exit;
6332 }else{
6333 zSql = sqlite3_mprintf(
6334 "SELECT name FROM sqlite_master"
6335 " WHERE type='index'"
6336 " AND tbl_name LIKE ?1");
6337 }
drha4b81d22016-12-24 18:04:28 +00006338 for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006339 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drha4b81d22016-12-24 18:04:28 +00006340 if( zDbName==0 || ii==0 ) continue;
drh6a5a4202016-12-24 21:32:40 +00006341 if( c=='t' ){
drh98781232012-04-23 12:38:05 +00006342 zSql = sqlite3_mprintf(
6343 "%z UNION ALL "
6344 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6345 " WHERE type IN ('table','view')"
6346 " AND name NOT LIKE 'sqlite_%%'"
6347 " AND name LIKE ?1", zSql, zDbName, zDbName);
drh6a5a4202016-12-24 21:32:40 +00006348 }else{
6349 zSql = sqlite3_mprintf(
6350 "%z UNION ALL "
6351 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6352 " WHERE type='index'"
6353 " AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
drh98781232012-04-23 12:38:05 +00006354 }
drha50da102000-08-08 20:19:09 +00006355 }
dand95bb392015-09-30 11:19:05 +00006356 rc = sqlite3_finalize(pStmt);
6357 if( zSql && rc==SQLITE_OK ){
6358 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6359 if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6360 }
drh98781232012-04-23 12:38:05 +00006361 sqlite3_free(zSql);
dand95bb392015-09-30 11:19:05 +00006362 if( !zSql ) return shellNomemError();
6363 if( rc ) return shellDatabaseError(p->db);
6364
6365 /* Run the SQL statement prepared by the above block. Store the results
6366 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006367 nRow = nAlloc = 0;
6368 azResult = 0;
6369 if( nArg>1 ){
6370 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006371 }else{
drh98781232012-04-23 12:38:05 +00006372 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6373 }
6374 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6375 if( nRow>=nAlloc ){
6376 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006377 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006378 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006379 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006380 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006381 break;
6382 }
mistachkin8e189222015-04-19 21:43:16 +00006383 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006384 azResult = azNew;
6385 }
6386 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006387 if( 0==azResult[nRow] ){
6388 rc = shellNomemError();
6389 break;
6390 }
6391 nRow++;
drh98781232012-04-23 12:38:05 +00006392 }
dand95bb392015-09-30 11:19:05 +00006393 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6394 rc = shellDatabaseError(p->db);
6395 }
6396
6397 /* Pretty-print the contents of array azResult[] to the output */
6398 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006399 int len, maxlen = 0;
6400 int i, j;
6401 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006402 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006403 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006404 if( len>maxlen ) maxlen = len;
6405 }
6406 nPrintCol = 80/(maxlen+2);
6407 if( nPrintCol<1 ) nPrintCol = 1;
6408 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6409 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006410 for(j=i; j<nRow; j+=nPrintRow){
6411 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006412 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6413 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006414 }
mistachkinaae280e2015-12-31 19:06:24 +00006415 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006416 }
6417 }
dand95bb392015-09-30 11:19:05 +00006418
drh98781232012-04-23 12:38:05 +00006419 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6420 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006421 }else
6422
drh2db82112016-09-15 21:35:24 +00006423 /* Begin redirecting output to the file "testcase-out.txt" */
6424 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6425 output_reset(p);
6426 p->out = output_file_open("testcase-out.txt");
6427 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006428 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006429 }
drh760c8162016-09-16 02:52:22 +00006430 if( nArg>=2 ){
6431 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6432 }else{
6433 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6434 }
drh2db82112016-09-15 21:35:24 +00006435 }else
drh2db82112016-09-15 21:35:24 +00006436
drhd12602a2016-12-07 15:49:02 +00006437#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006438 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006439 static const struct {
6440 const char *zCtrlName; /* Name of a test-control option */
6441 int ctrlCode; /* Integer code for that option */
6442 } aCtrl[] = {
6443 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6444 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6445 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6446 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6447 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6448 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6449 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6450 { "assert", SQLITE_TESTCTRL_ASSERT },
6451 { "always", SQLITE_TESTCTRL_ALWAYS },
6452 { "reserve", SQLITE_TESTCTRL_RESERVE },
6453 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6454 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006455 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006456 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006457 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006458 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006459 };
shaneh96887e12011-02-10 21:08:58 +00006460 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006461 int rc2 = 0;
6462 int i, n2;
drh05782482013-10-24 15:20:20 +00006463 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006464
drhd416fe72011-03-17 16:45:50 +00006465 /* convert testctrl text option to value. allow any unique prefix
6466 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006467 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006468 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006469 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006470 if( testctrl<0 ){
6471 testctrl = aCtrl[i].ctrlCode;
6472 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006473 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006474 testctrl = -1;
6475 break;
6476 }
6477 }
6478 }
drh348d19c2013-06-03 12:47:43 +00006479 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006480 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006481 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006482 }else{
6483 switch(testctrl){
6484
6485 /* sqlite3_test_control(int, db, int) */
6486 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006487 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006488 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006489 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006490 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006491 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006492 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006493 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006494 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006495 }
6496 break;
6497
6498 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006499 case SQLITE_TESTCTRL_PRNG_SAVE:
6500 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006501 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006502 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006503 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006504 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006505 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006506 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006507 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6508 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006509 }
6510 break;
6511
6512 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006513 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006514 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006515 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006516 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006517 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006518 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006519 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006520 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006521 }
6522 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006523
shaneh96887e12011-02-10 21:08:58 +00006524 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006525 case SQLITE_TESTCTRL_ASSERT:
6526 case SQLITE_TESTCTRL_ALWAYS:
6527 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006528 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006529 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006530 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006531 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006532 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006533 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006534 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006535 }
6536 break;
6537
6538 /* sqlite3_test_control(int, char *) */
6539#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006540 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006541 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006542 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006543 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006544 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006545 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006546 utf8_printf(stderr,
6547 "Error: testctrl %s takes a single char * option\n",
6548 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006549 }
6550 break;
6551#endif
6552
drh1ffede82015-01-30 20:59:27 +00006553 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006554 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006555 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006556 azArg[2],
drh8964b342015-01-29 17:54:52 +00006557 integerValue(azArg[3]),
6558 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006559 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006560 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006561 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006562 }
6563 break;
6564
mistachkin1fe36bb2016-04-04 02:16:44 +00006565 case SQLITE_TESTCTRL_BITVEC_TEST:
6566 case SQLITE_TESTCTRL_FAULT_INSTALL:
6567 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6568 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006569 default:
mistachkinaae280e2015-12-31 19:06:24 +00006570 utf8_printf(stderr,
6571 "Error: CLI support for testctrl %s not implemented\n",
6572 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006573 break;
6574 }
6575 }
6576 }else
drhf1969722017-02-17 23:52:00 +00006577#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006578
drhc2ce0be2014-05-29 12:36:14 +00006579 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006580 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006581 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006582 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006583
drhc2ce0be2014-05-29 12:36:14 +00006584 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6585 if( nArg==2 ){
6586 enableTimer = booleanValue(azArg[1]);
6587 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006588 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006589 enableTimer = 0;
6590 }
6591 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006592 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006593 rc = 1;
6594 }
shanehe2aa9d72009-11-06 17:20:17 +00006595 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006596
drhc2ce0be2014-05-29 12:36:14 +00006597 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006598 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006599 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006600 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006601 rc = 1;
6602 goto meta_command_exit;
6603 }
drh657b4a82015-03-19 13:30:41 +00006604 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006605 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006606#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006607 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006608 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006609 }else{
drh4b363a52016-07-23 20:27:41 +00006610 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006611 }
6612#endif
6613 }else
6614
drhf442e332014-09-10 19:01:14 +00006615#if SQLITE_USER_AUTHENTICATION
6616 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6617 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006618 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006619 rc = 1;
6620 goto meta_command_exit;
6621 }
drh7883ecf2014-09-11 16:19:31 +00006622 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006623 if( strcmp(azArg[1],"login")==0 ){
6624 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006625 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006626 rc = 1;
6627 goto meta_command_exit;
6628 }
drhd39c40f2014-09-11 00:27:53 +00006629 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6630 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006631 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006632 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006633 rc = 1;
6634 }
6635 }else if( strcmp(azArg[1],"add")==0 ){
6636 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006637 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006638 rc = 1;
6639 goto meta_command_exit;
6640 }
drhd39c40f2014-09-11 00:27:53 +00006641 rc = sqlite3_user_add(p->db, azArg[2],
6642 azArg[3], (int)strlen(azArg[3]),
6643 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006644 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006645 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006646 rc = 1;
6647 }
6648 }else if( strcmp(azArg[1],"edit")==0 ){
6649 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006650 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006651 rc = 1;
6652 goto meta_command_exit;
6653 }
drhd39c40f2014-09-11 00:27:53 +00006654 rc = sqlite3_user_change(p->db, azArg[2],
6655 azArg[3], (int)strlen(azArg[3]),
6656 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006657 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006658 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006659 rc = 1;
6660 }
6661 }else if( strcmp(azArg[1],"delete")==0 ){
6662 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006663 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006664 rc = 1;
6665 goto meta_command_exit;
6666 }
6667 rc = sqlite3_user_delete(p->db, azArg[2]);
6668 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006669 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006670 rc = 1;
6671 }
6672 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006673 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006674 rc = 1;
6675 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006676 }
drhf442e332014-09-10 19:01:14 +00006677 }else
6678#endif /* SQLITE_USER_AUTHENTICATION */
6679
drh9fd301b2011-06-03 13:28:22 +00006680 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006681 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006682 sqlite3_libversion(), sqlite3_sourceid());
6683 }else
6684
drh790f2872015-11-28 18:06:36 +00006685 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6686 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006687 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006688 if( p->db ){
6689 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6690 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006691 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6692 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6693 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6694 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006695 }
6696 }
6697 }else
6698
drhb19e7352016-01-12 19:37:20 +00006699 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6700 sqlite3_vfs *pVfs;
6701 sqlite3_vfs *pCurrent = 0;
6702 if( p->db ){
6703 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6704 }
6705 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6706 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6707 pVfs==pCurrent ? " <--- CURRENT" : "");
6708 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6709 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6710 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6711 if( pVfs->pNext ){
6712 raw_printf(p->out, "-----------------------------------\n");
6713 }
6714 }
6715 }else
6716
drhde60fc22011-12-14 17:53:36 +00006717 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6718 const char *zDbName = nArg==2 ? azArg[1] : "main";
6719 char *zVfsName = 0;
6720 if( p->db ){
6721 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6722 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006723 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006724 sqlite3_free(zVfsName);
6725 }
6726 }
6727 }else
6728
drhcef4fc82012-09-21 22:50:45 +00006729#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6730 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006731 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006732 }else
6733#endif
6734
drhc2ce0be2014-05-29 12:36:14 +00006735 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006736 int j;
drh43617e92006-03-06 20:55:46 +00006737 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006738 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006739 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006740 }
6741 }else
6742
6743 {
mistachkinaae280e2015-12-31 19:06:24 +00006744 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006745 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006746 rc = 1;
drh75897232000-05-29 14:26:00 +00006747 }
drh67505e72002-04-19 12:34:06 +00006748
drhc2ce0be2014-05-29 12:36:14 +00006749meta_command_exit:
6750 if( p->outCount ){
6751 p->outCount--;
6752 if( p->outCount==0 ) output_reset(p);
6753 }
drh67505e72002-04-19 12:34:06 +00006754 return rc;
drh75897232000-05-29 14:26:00 +00006755}
6756
drh67505e72002-04-19 12:34:06 +00006757/*
drh91a66392007-09-07 01:12:32 +00006758** Return TRUE if a semicolon occurs anywhere in the first N characters
6759** of string z[].
drh324ccef2003-02-05 14:06:20 +00006760*/
drh9f099fd2013-08-06 14:01:46 +00006761static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006762 int i;
6763 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6764 return 0;
drh324ccef2003-02-05 14:06:20 +00006765}
6766
6767/*
drh70c7a4b2003-04-26 03:03:06 +00006768** Test to see if a line consists entirely of whitespace.
6769*/
6770static int _all_whitespace(const char *z){
6771 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006772 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006773 if( *z=='/' && z[1]=='*' ){
6774 z += 2;
6775 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6776 if( *z==0 ) return 0;
6777 z++;
6778 continue;
6779 }
6780 if( *z=='-' && z[1]=='-' ){
6781 z += 2;
6782 while( *z && *z!='\n' ){ z++; }
6783 if( *z==0 ) return 1;
6784 continue;
6785 }
6786 return 0;
6787 }
6788 return 1;
6789}
6790
6791/*
drha9b17162003-04-29 18:01:28 +00006792** Return TRUE if the line typed in is an SQL command terminator other
6793** than a semi-colon. The SQL Server style "go" command is understood
6794** as is the Oracle "/".
6795*/
drh9f099fd2013-08-06 14:01:46 +00006796static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006797 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006798 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6799 return 1; /* Oracle */
6800 }
drhf0693c82011-10-11 20:41:54 +00006801 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006802 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006803 return 1; /* SQL Server */
6804 }
6805 return 0;
6806}
6807
6808/*
drh233a5312008-12-18 22:25:13 +00006809** Return true if zSql is a complete SQL statement. Return false if it
6810** ends in the middle of a string literal or C-style comment.
6811*/
drh9f099fd2013-08-06 14:01:46 +00006812static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006813 int rc;
6814 if( zSql==0 ) return 1;
6815 zSql[nSql] = ';';
6816 zSql[nSql+1] = 0;
6817 rc = sqlite3_complete(zSql);
6818 zSql[nSql] = 0;
6819 return rc;
6820}
6821
6822/*
drh4e8142c2016-11-11 14:54:22 +00006823** Run a single line of SQL
6824*/
6825static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6826 int rc;
6827 char *zErrMsg = 0;
6828
6829 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006830 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006831 BEGIN_TIMER;
6832 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6833 END_TIMER;
6834 if( rc || zErrMsg ){
6835 char zPrefix[100];
6836 if( in!=0 || !stdin_is_interactive ){
6837 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6838 "Error: near line %d:", startline);
6839 }else{
6840 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6841 }
6842 if( zErrMsg!=0 ){
6843 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6844 sqlite3_free(zErrMsg);
6845 zErrMsg = 0;
6846 }else{
6847 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6848 }
6849 return 1;
drhe6e1d122017-03-09 13:50:49 +00006850 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006851 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6852 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6853 }
6854 return 0;
6855}
6856
6857
6858/*
drh67505e72002-04-19 12:34:06 +00006859** Read input from *in and process it. If *in==0 then input
6860** is interactive - the user is typing it it. Otherwise, input
6861** is coming from a file or device. A prompt is issued and history
6862** is saved only if input is interactive. An interrupt signal will
6863** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006864**
6865** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006866*/
drhdcd87a92014-08-18 13:45:42 +00006867static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006868 char *zLine = 0; /* A single input line */
6869 char *zSql = 0; /* Accumulated SQL text */
6870 int nLine; /* Length of current line */
6871 int nSql = 0; /* Bytes of zSql[] used */
6872 int nAlloc = 0; /* Allocated zSql[] space */
6873 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006874 int rc; /* Error code */
6875 int errCnt = 0; /* Number of errors seen */
6876 int lineno = 0; /* Current line number */
6877 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006878
6879 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6880 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006881 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006882 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006883 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006884 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006885 break;
drhc49f44e2006-10-26 18:15:42 +00006886 }
drh67505e72002-04-19 12:34:06 +00006887 if( seenInterrupt ){
6888 if( in!=0 ) break;
6889 seenInterrupt = 0;
6890 }
drhc28490c2006-10-26 14:25:58 +00006891 lineno++;
drh849a9d92013-12-21 15:46:06 +00006892 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006893 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006894 continue;
6895 }
drh2af0b2d2002-02-21 02:25:02 +00006896 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006897 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006898 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006899 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006900 break;
6901 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006902 errCnt++;
6903 }
drhdaffd0e2001-04-11 14:28:42 +00006904 continue;
6905 }
drh9f099fd2013-08-06 14:01:46 +00006906 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00006907 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00006908 }
drh9f099fd2013-08-06 14:01:46 +00006909 nLine = strlen30(zLine);
6910 if( nSql+nLine+2>=nAlloc ){
6911 nAlloc = nSql+nLine+100;
6912 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00006913 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006914 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00006915 exit(1);
6916 }
drhdaffd0e2001-04-11 14:28:42 +00006917 }
drh9f099fd2013-08-06 14:01:46 +00006918 nSqlPrior = nSql;
6919 if( nSql==0 ){
6920 int i;
6921 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00006922 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00006923 memcpy(zSql, zLine+i, nLine+1-i);
6924 startline = lineno;
6925 nSql = nLine-i;
6926 }else{
6927 zSql[nSql++] = '\n';
6928 memcpy(zSql+nSql, zLine, nLine+1);
6929 nSql += nLine;
6930 }
6931 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00006932 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00006933 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006934 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00006935 if( p->outCount ){
6936 output_reset(p);
6937 p->outCount = 0;
6938 }
drh9f099fd2013-08-06 14:01:46 +00006939 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00006940 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00006941 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00006942 }
6943 }
drh4e8142c2016-11-11 14:54:22 +00006944 if( nSql && !_all_whitespace(zSql) ){
6945 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006946 }
drh1f9ca2c2015-08-25 16:57:52 +00006947 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00006948 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00006949 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00006950}
6951
drh67505e72002-04-19 12:34:06 +00006952/*
6953** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00006954** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00006955*/
drhd1459152016-09-16 19:11:03 +00006956static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00006957 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00006958 if( clearFlag ){
6959 free(home_dir);
6960 home_dir = 0;
6961 return 0;
6962 }
drh85e72432012-04-11 11:38:53 +00006963 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00006964
drh4ace5362014-11-10 14:42:28 +00006965#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6966 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00006967 {
6968 struct passwd *pwent;
6969 uid_t uid = getuid();
6970 if( (pwent=getpwuid(uid)) != NULL) {
6971 home_dir = pwent->pw_dir;
6972 }
drh67505e72002-04-19 12:34:06 +00006973 }
6974#endif
6975
chw65d3c132007-11-12 21:09:10 +00006976#if defined(_WIN32_WCE)
6977 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6978 */
drh85e72432012-04-11 11:38:53 +00006979 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00006980#else
6981
drh83905c92012-06-21 13:00:37 +00006982#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00006983 if (!home_dir) {
6984 home_dir = getenv("USERPROFILE");
6985 }
6986#endif
6987
drh67505e72002-04-19 12:34:06 +00006988 if (!home_dir) {
6989 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00006990 }
6991
drh83905c92012-06-21 13:00:37 +00006992#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00006993 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00006994 char *zDrive, *zPath;
6995 int n;
6996 zDrive = getenv("HOMEDRIVE");
6997 zPath = getenv("HOMEPATH");
6998 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00006999 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00007000 home_dir = malloc( n );
7001 if( home_dir==0 ) return 0;
7002 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7003 return home_dir;
7004 }
7005 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00007006 }
7007#endif
7008
chw65d3c132007-11-12 21:09:10 +00007009#endif /* !_WIN32_WCE */
7010
drh67505e72002-04-19 12:34:06 +00007011 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00007012 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00007013 char *z = malloc( n );
7014 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00007015 home_dir = z;
7016 }
drhe98d4fa2002-04-21 19:06:22 +00007017
drh67505e72002-04-19 12:34:06 +00007018 return home_dir;
7019}
7020
7021/*
7022** Read input from the file given by sqliterc_override. Or if that
7023** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007024**
7025** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007026*/
drh534f4df2015-02-28 14:03:35 +00007027static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007028 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007029 const char *sqliterc_override /* Name of config file. NULL to use default */
7030){
persicom7e2dfdd2002-04-18 02:46:52 +00007031 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007032 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007033 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007034 FILE *in = NULL;
7035
7036 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007037 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007038 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007039 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007040 " cannot read ~/.sqliterc\n");
7041 return;
drhe98d4fa2002-04-21 19:06:22 +00007042 }
drh2f3de322012-06-27 16:41:31 +00007043 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007044 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7045 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007046 }
drha1f9b5e2004-02-14 16:31:02 +00007047 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007048 if( in ){
drhc28490c2006-10-26 14:25:58 +00007049 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007050 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007051 }
drh534f4df2015-02-28 14:03:35 +00007052 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007053 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007054 }
drh85e72432012-04-11 11:38:53 +00007055 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007056}
7057
drh67505e72002-04-19 12:34:06 +00007058/*
drhe1e38c42003-05-04 18:30:59 +00007059** Show available command line options
7060*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007061static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007062 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007063 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007064 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007065 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007066 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007067 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007068 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007069 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007070 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007071#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7072 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7073#endif
drhcc3b4f82012-02-07 14:13:50 +00007074 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007075 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007076 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007077 " -line set output mode to 'line'\n"
7078 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007079 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007080 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007081#ifdef SQLITE_ENABLE_MULTIPLEX
7082 " -multiplex enable the multiplexor VFS\n"
7083#endif
mistachkine0d68852014-12-11 03:12:33 +00007084 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007085 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007086 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7087 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00007088 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007089 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007090 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007091 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007092#ifdef SQLITE_ENABLE_VFSTRACE
7093 " -vfstrace enable tracing of all VFS calls\n"
7094#endif
drhe1e38c42003-05-04 18:30:59 +00007095;
7096static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007097 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007098 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007099 "FILENAME is the name of an SQLite database. A new database is created\n"
7100 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007101 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007102 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007103 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007104 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007105 }
7106 exit(1);
7107}
7108
7109/*
drh67505e72002-04-19 12:34:06 +00007110** Initialize the state information in data
7111*/
drhdcd87a92014-08-18 13:45:42 +00007112static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007113 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007114 data->normalMode = data->cMode = data->mode = MODE_List;
7115 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007116 memcpy(data->colSeparator,SEP_Column, 2);
7117 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007118 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007119 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007120 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007121 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007122 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007123 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7124 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007125}
7126
drh98d312f2012-10-25 15:23:14 +00007127/*
drh5c7976f2014-02-10 19:59:27 +00007128** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007129*/
7130#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007131static void printBold(const char *zText){
7132 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7133 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7134 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7135 SetConsoleTextAttribute(out,
7136 FOREGROUND_RED|FOREGROUND_INTENSITY
7137 );
7138 printf("%s", zText);
7139 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007140}
7141#else
drh5c7976f2014-02-10 19:59:27 +00007142static void printBold(const char *zText){
7143 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007144}
7145#endif
7146
7147/*
drh98d312f2012-10-25 15:23:14 +00007148** Get the argument to an --option. Throw an error and die if no argument
7149** is available.
7150*/
7151static char *cmdline_option_value(int argc, char **argv, int i){
7152 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007153 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007154 argv[0], argv[argc-1]);
7155 exit(1);
7156 }
7157 return argv[i];
7158}
7159
mistachkin1fe36bb2016-04-04 02:16:44 +00007160#ifndef SQLITE_SHELL_IS_UTF8
7161# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7162# define SQLITE_SHELL_IS_UTF8 (0)
7163# else
7164# define SQLITE_SHELL_IS_UTF8 (1)
7165# endif
7166#endif
7167
7168#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007169int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007170#else
7171int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007172 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007173#endif
drh75897232000-05-29 14:26:00 +00007174 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007175 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007176 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007177 int i;
drhc28490c2006-10-26 14:25:58 +00007178 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007179 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007180 int readStdin = 1;
7181 int nCmd = 0;
7182 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007183
mistachkin1fe36bb2016-04-04 02:16:44 +00007184 setBinaryMode(stdin, 0);
7185 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007186 stdin_is_interactive = isatty(0);
7187 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007188
drh69b30ab2014-02-27 15:11:52 +00007189#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007190 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007191 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007192 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7193 exit(1);
7194 }
drhc7181902014-02-27 15:04:13 +00007195#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007196 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007197#if !SQLITE_SHELL_IS_UTF8
7198 sqlite3_initialize();
7199 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7200 if( argv==0 ){
7201 raw_printf(stderr, "out of memory\n");
7202 exit(1);
7203 }
7204 for(i=0; i<argc; i++){
7205 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7206 if( argv[i]==0 ){
7207 raw_printf(stderr, "out of memory\n");
7208 exit(1);
7209 }
7210 }
7211#endif
mistachkin1810f222016-04-04 02:33:34 +00007212 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007213 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007214
drh44c2eb12003-04-30 11:38:26 +00007215 /* Make sure we have a valid signal handler early, before anything
7216 ** else is done.
7217 */
drh4c504392000-10-16 22:06:40 +00007218#ifdef SIGINT
7219 signal(SIGINT, interrupt_handler);
7220#endif
drh44c2eb12003-04-30 11:38:26 +00007221
drhac5649a2014-11-28 13:35:03 +00007222#ifdef SQLITE_SHELL_DBNAME_PROC
7223 {
7224 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7225 ** of a C-function that will provide the name of the database file. Use
7226 ** this compile-time option to embed this shell program in larger
7227 ** applications. */
7228 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7229 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7230 warnInmemoryDb = 0;
7231 }
7232#endif
7233
drh22fbcb82004-02-01 01:22:50 +00007234 /* Do an initial pass through the command-line argument to locate
7235 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007236 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007237 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007238 */
drh98d312f2012-10-25 15:23:14 +00007239 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007240 char *z;
drhc28490c2006-10-26 14:25:58 +00007241 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007242 if( z[0]!='-' ){
7243 if( data.zDbFilename==0 ){
7244 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007245 }else{
7246 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7247 ** mean that nothing is read from stdin */
7248 readStdin = 0;
7249 nCmd++;
7250 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7251 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007252 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007253 exit(1);
7254 }
7255 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007256 }
drh98d312f2012-10-25 15:23:14 +00007257 }
drhcc3b4f82012-02-07 14:13:50 +00007258 if( z[1]=='-' ) z++;
7259 if( strcmp(z,"-separator")==0
7260 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007261 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007262 || strcmp(z,"-cmd")==0
7263 ){
drh98d312f2012-10-25 15:23:14 +00007264 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007265 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007266 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007267 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007268 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007269 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007270 ** we do the actual processing of arguments later in a second pass.
7271 */
shanef69573d2009-10-24 02:06:14 +00007272 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007273 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007274#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007275 const char *zSize;
7276 sqlite3_int64 szHeap;
7277
drh98d312f2012-10-25 15:23:14 +00007278 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007279 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007280 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007281 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007282#else
7283 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007284#endif
drh44dec872014-08-30 15:49:25 +00007285 }else if( strcmp(z,"-scratch")==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>400000 ) sz = 400000;
7289 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007290 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007291 if( n>10 ) n = 10;
7292 if( n<1 ) n = 1;
7293 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7294 data.shellFlgs |= SHFLG_Scratch;
7295 }else if( strcmp(z,"-pagecache")==0 ){
7296 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007297 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007298 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007299 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007300 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007301 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7302 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007303 data.shellFlgs |= SHFLG_Pagecache;
7304 }else if( strcmp(z,"-lookaside")==0 ){
7305 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007306 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007307 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007308 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007309 if( n<0 ) n = 0;
7310 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7311 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007312#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007313 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007314 extern int vfstrace_register(
7315 const char *zTraceName,
7316 const char *zOldVfsName,
7317 int (*xOut)(const char*,void*),
7318 void *pOutArg,
7319 int makeDefault
7320 );
drh2b625e22011-03-16 17:05:28 +00007321 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007322#endif
drh6f25e892011-07-08 17:02:57 +00007323#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007324 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007325 extern int sqlite3_multiple_initialize(const char*,int);
7326 sqlite3_multiplex_initialize(0, 1);
7327#endif
drh7d9f3942013-04-03 01:26:54 +00007328 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007329 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7330 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007331 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007332 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007333 if( pVfs ){
7334 sqlite3_vfs_register(pVfs, 1);
7335 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007336 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007337 exit(1);
7338 }
drh44c2eb12003-04-30 11:38:26 +00007339 }
7340 }
drh98d312f2012-10-25 15:23:14 +00007341 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007342#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007343 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007344 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007345#else
mistachkinaae280e2015-12-31 19:06:24 +00007346 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007347 return 1;
drh01b41712005-08-29 23:06:23 +00007348#endif
drh98d312f2012-10-25 15:23:14 +00007349 }
7350 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007351
drh44c2eb12003-04-30 11:38:26 +00007352 /* Go ahead and open the database file if it already exists. If the
7353 ** file does not exist, delay opening it. This prevents empty database
7354 ** files from being created if a user mistypes the database name argument
7355 ** to the sqlite command-line tool.
7356 */
drhc8d74412004-08-31 23:41:26 +00007357 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007358 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007359 }
7360
drh22fbcb82004-02-01 01:22:50 +00007361 /* Process the initialization file if there is one. If no -init option
7362 ** is given on the command line, look for a file named ~/.sqliterc and
7363 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007364 */
drh534f4df2015-02-28 14:03:35 +00007365 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007366
drh22fbcb82004-02-01 01:22:50 +00007367 /* Make a second pass through the command-line argument and set
7368 ** options. This second pass is delayed until after the initialization
7369 ** file is processed so that the command-line arguments will override
7370 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007371 */
drh98d312f2012-10-25 15:23:14 +00007372 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007373 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007374 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007375 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007376 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007377 i++;
7378 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007379 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007380 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007381 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007382 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007383 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007384 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007385 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007386 }else if( strcmp(z,"-csv")==0 ){
7387 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007388 memcpy(data.colSeparator,",",2);
7389 }else if( strcmp(z,"-ascii")==0 ){
7390 data.mode = MODE_Ascii;
7391 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007392 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007393 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007394 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007395 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007396 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007397 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007398 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007399 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007400 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007401 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007402 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007403 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007404 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007405 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007406 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007407 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007408 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007409 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007410 }else if( strcmp(z,"-eqp")==0 ){
7411 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007412 }else if( strcmp(z,"-eqpfull")==0 ){
7413 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007414 }else if( strcmp(z,"-stats")==0 ){
7415 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007416 }else if( strcmp(z,"-scanstats")==0 ){
7417 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007418 }else if( strcmp(z,"-backslash")==0 ){
7419 /* Undocumented command-line option: -backslash
7420 ** Causes C-style backslash escapes to be evaluated in SQL statements
7421 ** prior to sending the SQL into SQLite. Useful for injecting
7422 ** crazy bytes in the middle of SQL statements for testing and debugging.
7423 */
drhe6e1d122017-03-09 13:50:49 +00007424 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007425 }else if( strcmp(z,"-bail")==0 ){
7426 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007427 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007428 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007429 return 0;
drhc28490c2006-10-26 14:25:58 +00007430 }else if( strcmp(z,"-interactive")==0 ){
7431 stdin_is_interactive = 1;
7432 }else if( strcmp(z,"-batch")==0 ){
7433 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007434 }else if( strcmp(z,"-heap")==0 ){
7435 i++;
drh44dec872014-08-30 15:49:25 +00007436 }else if( strcmp(z,"-scratch")==0 ){
7437 i+=2;
7438 }else if( strcmp(z,"-pagecache")==0 ){
7439 i+=2;
7440 }else if( strcmp(z,"-lookaside")==0 ){
7441 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007442 }else if( strcmp(z,"-mmap")==0 ){
7443 i++;
drha7e61d82011-03-12 17:02:57 +00007444 }else if( strcmp(z,"-vfs")==0 ){
7445 i++;
drh6f25e892011-07-08 17:02:57 +00007446#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007447 }else if( strcmp(z,"-vfstrace")==0 ){
7448 i++;
drh6f25e892011-07-08 17:02:57 +00007449#endif
7450#ifdef SQLITE_ENABLE_MULTIPLEX
7451 }else if( strcmp(z,"-multiplex")==0 ){
7452 i++;
7453#endif
drhcc3b4f82012-02-07 14:13:50 +00007454 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007455 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007456 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007457 /* Run commands that follow -cmd first and separately from commands
7458 ** that simply appear on the command-line. This seems goofy. It would
7459 ** be better if all commands ran in the order that they appear. But
7460 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007461 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007462 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007463 if( z[0]=='.' ){
7464 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007465 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007466 }else{
drh05782482013-10-24 15:20:20 +00007467 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007468 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7469 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007470 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007471 if( bail_on_error ) return rc!=0 ? rc : 1;
7472 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007473 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007474 if( bail_on_error ) return rc;
7475 }
7476 }
drh1e5d0e92000-05-31 23:33:17 +00007477 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007478 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7479 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007480 return 1;
7481 }
drh700c2522016-02-09 18:39:25 +00007482 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007483 }
drh44c2eb12003-04-30 11:38:26 +00007484
drhac5649a2014-11-28 13:35:03 +00007485 if( !readStdin ){
7486 /* Run all arguments that do not begin with '-' as if they were separate
7487 ** command-line inputs, except for the argToSkip argument which contains
7488 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007489 */
drhac5649a2014-11-28 13:35:03 +00007490 for(i=0; i<nCmd; i++){
7491 if( azCmd[i][0]=='.' ){
7492 rc = do_meta_command(azCmd[i], &data);
7493 if( rc ) return rc==2 ? 0 : rc;
7494 }else{
7495 open_db(&data, 0);
7496 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7497 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007498 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007499 return rc!=0 ? rc : 1;
7500 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007501 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007502 return rc;
7503 }
drh6ff13852001-11-25 13:18:23 +00007504 }
drh75897232000-05-29 14:26:00 +00007505 }
drhac5649a2014-11-28 13:35:03 +00007506 free(azCmd);
drh75897232000-05-29 14:26:00 +00007507 }else{
drh44c2eb12003-04-30 11:38:26 +00007508 /* Run commands received from standard input
7509 */
drhc28490c2006-10-26 14:25:58 +00007510 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007511 char *zHome;
7512 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007513 int nHistory;
drh75897232000-05-29 14:26:00 +00007514 printf(
drh743e0032011-12-12 16:51:50 +00007515 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007516 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007517 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007518 );
drhb3735912014-02-10 16:13:42 +00007519 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007520 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007521 printBold("transient in-memory database");
7522 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007523 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007524 }
drhd1459152016-09-16 19:11:03 +00007525 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007526 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007527 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007528 if( (zHistory = malloc(nHistory))!=0 ){
7529 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7530 }
drh67505e72002-04-19 12:34:06 +00007531 }
drhf5ed7ad2015-06-15 14:43:25 +00007532 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007533 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007534 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007535 shell_stifle_history(100);
7536 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007537 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007538 }
drhdaffd0e2001-04-11 14:28:42 +00007539 }else{
drhc28490c2006-10-26 14:25:58 +00007540 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007541 }
7542 }
drh33048c02001-10-01 14:29:22 +00007543 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007544 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007545 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007546 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007547 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007548 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007549 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007550#if !SQLITE_SHELL_IS_UTF8
7551 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7552 sqlite3_free(argv);
7553#endif
drhc28490c2006-10-26 14:25:58 +00007554 return rc;
drh75897232000-05-29 14:26:00 +00007555}