blob: 6a436da4883db0af19431d0aef8e4a961fb2ed81 [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 */
6003 char **azTest = 0; /* Content of the SELFTEST table */
6004 int nRow = 0; /* Number of rows in the SELFTEST table */
6005 int nCol = 4; /* Number of columns in the SELFTEST table */
6006 int i; /* Loop counter */
6007 int nTest = 0; /* Number of tests runs */
6008 int nErr = 0; /* Number of errors seen */
6009 ShellText str; /* Answer for a query */
6010 static char *azDefaultTest[] = {
6011 0, 0, 0, 0,
6012 "0", "memo", "Missing SELFTEST table - default checks only", "",
6013 "1", "run", "PRAGMA integrity_check", "ok"
6014 };
6015 static const int nDefaultRow = 2;
6016
6017 open_db(p,0);
6018 for(i=1; i<nArg; i++){
6019 const char *z = azArg[i];
6020 if( z[0]=='-' && z[1]=='-' ) z++;
6021 if( strcmp(z,"-init")==0 ){
6022 bIsInit = 1;
6023 }else
6024 if( strcmp(z,"-v")==0 ){
6025 bVerbose++;
6026 }else
6027 {
6028 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6029 azArg[i], azArg[0]);
6030 raw_printf(stderr, "Should be one of: --init -v\n");
6031 rc = 1;
6032 goto meta_command_exit;
6033 }
6034 }
6035 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6036 != SQLITE_OK ){
6037 bSelftestExists = 0;
6038 }else{
6039 bSelftestExists = 1;
6040 }
6041 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006042 createSelftestTable(p);
6043 bSelftestExists = 1;
6044 }
6045 if( bSelftestExists ){
mistachkine16a3502017-05-29 03:48:13 +00006046 rc = sqlite3_get_table(p->db,
drhfb546af2017-03-09 22:00:33 +00006047 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6048 &azTest, &nRow, &nCol, 0);
6049 if( rc ){
6050 raw_printf(stderr, "Error querying the selftest table\n");
6051 rc = 1;
6052 sqlite3_free_table(azTest);
6053 goto meta_command_exit;
6054 }else if( nRow==0 ){
6055 sqlite3_free_table(azTest);
6056 azTest = azDefaultTest;
6057 nRow = nDefaultRow;
6058 }
6059 }else{
6060 azTest = azDefaultTest;
6061 nRow = nDefaultRow;
6062 }
6063 initText(&str);
6064 appendText(&str, "x", 0);
6065 for(i=1; i<=nRow; i++){
6066 int tno = atoi(azTest[i*nCol]);
6067 const char *zOp = azTest[i*nCol+1];
6068 const char *zSql = azTest[i*nCol+2];
6069 const char *zAns = azTest[i*nCol+3];
mistachkine16a3502017-05-29 03:48:13 +00006070
drhfb546af2017-03-09 22:00:33 +00006071 if( bVerbose>0 ){
6072 char *zQuote = sqlite3_mprintf("%q", zSql);
6073 printf("%d: %s %s\n", tno, zOp, zSql);
6074 sqlite3_free(zQuote);
6075 }
6076 if( strcmp(zOp,"memo")==0 ){
6077 utf8_printf(p->out, "%s\n", zSql);
6078 }else
6079 if( strcmp(zOp,"run")==0 ){
6080 char *zErrMsg = 0;
6081 str.n = 0;
6082 str.z[0] = 0;
6083 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6084 nTest++;
6085 if( bVerbose ){
6086 utf8_printf(p->out, "Result: %s\n", str.z);
6087 }
6088 if( rc || zErrMsg ){
6089 nErr++;
6090 rc = 1;
6091 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6092 sqlite3_free(zErrMsg);
6093 }else if( strcmp(zAns,str.z)!=0 ){
6094 nErr++;
6095 rc = 1;
6096 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6097 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6098 }
6099 }else
6100 {
6101 utf8_printf(stderr,
6102 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
6103 rc = 1;
6104 break;
6105 }
6106 }
6107 freeText(&str);
6108 if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
6109 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6110 }else
6111
drhc2ce0be2014-05-29 12:36:14 +00006112 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006113 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006114 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006115 rc = 1;
6116 }
drh6976c212014-07-24 12:09:47 +00006117 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006118 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006119 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006120 }
6121 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006122 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6123 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006124 }
drh75897232000-05-29 14:26:00 +00006125 }else
6126
drh1554bc82017-03-08 16:10:34 +00006127 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6128 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6129 int i; /* Loop counter */
6130 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006131 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006132 int iSize = 224; /* Hash algorithm to use */
6133 int bDebug = 0; /* Only show the query that would have run */
6134 sqlite3_stmt *pStmt; /* For querying tables names */
6135 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006136 char *zSep; /* Separator */
6137 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006138 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006139 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006140 for(i=1; i<nArg; i++){
6141 const char *z = azArg[i];
6142 if( z[0]=='-' ){
6143 z++;
6144 if( z[0]=='-' ) z++;
6145 if( strcmp(z,"schema")==0 ){
6146 bSchema = 1;
6147 }else
mistachkine16a3502017-05-29 03:48:13 +00006148 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6149 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
drh1554bc82017-03-08 16:10:34 +00006150 ){
6151 iSize = atoi(&z[5]);
6152 }else
6153 if( strcmp(z,"debug")==0 ){
6154 bDebug = 1;
6155 }else
6156 {
6157 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006158 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006159 raw_printf(stderr, "Should be one of: --schema"
6160 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6161 rc = 1;
6162 goto meta_command_exit;
6163 }
6164 }else if( zLike ){
6165 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6166 rc = 1;
6167 goto meta_command_exit;
6168 }else{
6169 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006170 bSeparate = 1;
6171 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006172 }
6173 }
6174 if( bSchema ){
6175 zSql = "SELECT lower(name) FROM sqlite_master"
6176 " WHERE type='table' AND coalesce(rootpage,0)>1"
6177 " UNION ALL SELECT 'sqlite_master'"
6178 " ORDER BY 1 collate nocase";
6179 }else{
6180 zSql = "SELECT lower(name) FROM sqlite_master"
6181 " WHERE type='table' AND coalesce(rootpage,0)>1"
6182 " AND name NOT LIKE 'sqlite_%'"
6183 " ORDER BY 1 collate nocase";
6184 }
6185 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6186 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006187 initText(&sSql);
6188 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6189 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006190 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6191 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6192 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6193 if( strncmp(zTab, "sqlite_",7)!=0 ){
6194 appendText(&sQuery,"SELECT * FROM ", 0);
6195 appendText(&sQuery,zTab,'"');
6196 appendText(&sQuery," NOT INDEXED;", 0);
6197 }else if( strcmp(zTab, "sqlite_master")==0 ){
6198 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6199 " ORDER BY name;", 0);
6200 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6201 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6202 " ORDER BY name;", 0);
6203 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6204 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6205 " ORDER BY tbl,idx;", 0);
6206 }else if( strcmp(zTab, "sqlite_stat3")==0
6207 || strcmp(zTab, "sqlite_stat4")==0 ){
6208 appendText(&sQuery, "SELECT * FROM ", 0);
6209 appendText(&sQuery, zTab, 0);
6210 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6211 }
drh3ee83ef2017-03-08 17:56:54 +00006212 appendText(&sSql, zSep, 0);
6213 appendText(&sSql, sQuery.z, '\'');
6214 sQuery.n = 0;
6215 appendText(&sSql, ",", 0);
6216 appendText(&sSql, zTab, '\'');
6217 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006218 }
6219 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006220 if( bSeparate ){
6221 zSql = sqlite3_mprintf(
6222 "%s))"
6223 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6224 " FROM [sha3sum$query]",
6225 sSql.z, iSize);
6226 }else{
6227 zSql = sqlite3_mprintf(
6228 "%s))"
6229 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6230 " FROM [sha3sum$query]",
6231 sSql.z, iSize);
6232 }
drh1554bc82017-03-08 16:10:34 +00006233 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006234 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006235 if( bDebug ){
6236 utf8_printf(p->out, "%s\n", zSql);
6237 }else{
6238 shell_exec(p->db, zSql, shell_callback, p, 0);
6239 }
6240 sqlite3_free(zSql);
6241 }else
6242
drh62cdde52014-05-28 20:22:28 +00006243 if( c=='s'
6244 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006245 ){
6246 char *zCmd;
drh54027102014-08-06 14:36:53 +00006247 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006248 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006249 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006250 rc = 1;
6251 goto meta_command_exit;
6252 }
drhdcb3e3d2014-05-29 03:17:29 +00006253 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006254 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006255 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6256 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006257 }
drh54027102014-08-06 14:36:53 +00006258 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006259 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006260 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006261 }else
6262
drhc2ce0be2014-05-29 12:36:14 +00006263 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006264 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006265 int i;
drhc2ce0be2014-05-29 12:36:14 +00006266 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006267 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006268 rc = 1;
6269 goto meta_command_exit;
6270 }
drhe6e1d122017-03-09 13:50:49 +00006271 utf8_printf(p->out, "%12.12s: %s\n","echo",
6272 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006273 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006274 utf8_printf(p->out, "%12.12s: %s\n","explain",
6275 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006276 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006277 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6278 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006279 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006280 raw_printf(p->out, "\n");
6281 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006282 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006283 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006284 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006285 raw_printf(p->out, "\n");
6286 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006287 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006288 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006289 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006290 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006291 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006292 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006293 }
mistachkinaae280e2015-12-31 19:06:24 +00006294 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006295 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6296 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006297 }else
6298
drhc2ce0be2014-05-29 12:36:14 +00006299 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6300 if( nArg==2 ){
6301 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006302 }else if( nArg==1 ){
6303 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006304 }else{
drh34784902016-02-27 17:12:36 +00006305 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006306 rc = 1;
6307 }
shaneh642d8b82010-07-28 16:05:34 +00006308 }else
6309
drh6a5a4202016-12-24 21:32:40 +00006310 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6311 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6312 || strncmp(azArg[0], "indexes", n)==0) )
6313 ){
drh98781232012-04-23 12:38:05 +00006314 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006315 char **azResult;
drh98781232012-04-23 12:38:05 +00006316 int nRow, nAlloc;
6317 char *zSql = 0;
6318 int ii;
drh05782482013-10-24 15:20:20 +00006319 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006320 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006321 if( rc ) return shellDatabaseError(p->db);
6322
6323 /* Create an SQL statement to query for the list of tables in the
6324 ** main and all attached databases where the table name matches the
6325 ** LIKE pattern bound to variable "?1". */
drh6a5a4202016-12-24 21:32:40 +00006326 if( c=='t' ){
6327 zSql = sqlite3_mprintf(
6328 "SELECT name FROM sqlite_master"
6329 " WHERE type IN ('table','view')"
6330 " AND name NOT LIKE 'sqlite_%%'"
6331 " AND name LIKE ?1");
6332 }else if( nArg>2 ){
6333 /* It is an historical accident that the .indexes command shows an error
6334 ** when called with the wrong number of arguments whereas the .tables
6335 ** command does not. */
6336 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6337 rc = 1;
6338 goto meta_command_exit;
6339 }else{
6340 zSql = sqlite3_mprintf(
6341 "SELECT name FROM sqlite_master"
6342 " WHERE type='index'"
6343 " AND tbl_name LIKE ?1");
6344 }
drha4b81d22016-12-24 18:04:28 +00006345 for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006346 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drha4b81d22016-12-24 18:04:28 +00006347 if( zDbName==0 || ii==0 ) continue;
drh6a5a4202016-12-24 21:32:40 +00006348 if( c=='t' ){
drh98781232012-04-23 12:38:05 +00006349 zSql = sqlite3_mprintf(
6350 "%z UNION ALL "
6351 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6352 " WHERE type IN ('table','view')"
6353 " AND name NOT LIKE 'sqlite_%%'"
6354 " AND name LIKE ?1", zSql, zDbName, zDbName);
drh6a5a4202016-12-24 21:32:40 +00006355 }else{
6356 zSql = sqlite3_mprintf(
6357 "%z UNION ALL "
6358 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6359 " WHERE type='index'"
6360 " AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
drh98781232012-04-23 12:38:05 +00006361 }
drha50da102000-08-08 20:19:09 +00006362 }
dand95bb392015-09-30 11:19:05 +00006363 rc = sqlite3_finalize(pStmt);
6364 if( zSql && rc==SQLITE_OK ){
6365 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6366 if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6367 }
drh98781232012-04-23 12:38:05 +00006368 sqlite3_free(zSql);
dand95bb392015-09-30 11:19:05 +00006369 if( !zSql ) return shellNomemError();
6370 if( rc ) return shellDatabaseError(p->db);
6371
6372 /* Run the SQL statement prepared by the above block. Store the results
6373 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006374 nRow = nAlloc = 0;
6375 azResult = 0;
6376 if( nArg>1 ){
6377 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006378 }else{
drh98781232012-04-23 12:38:05 +00006379 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6380 }
6381 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6382 if( nRow>=nAlloc ){
6383 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006384 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006385 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006386 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006387 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006388 break;
6389 }
mistachkin8e189222015-04-19 21:43:16 +00006390 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006391 azResult = azNew;
6392 }
6393 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006394 if( 0==azResult[nRow] ){
6395 rc = shellNomemError();
6396 break;
6397 }
6398 nRow++;
drh98781232012-04-23 12:38:05 +00006399 }
dand95bb392015-09-30 11:19:05 +00006400 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6401 rc = shellDatabaseError(p->db);
6402 }
6403
6404 /* Pretty-print the contents of array azResult[] to the output */
6405 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006406 int len, maxlen = 0;
6407 int i, j;
6408 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006409 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006410 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006411 if( len>maxlen ) maxlen = len;
6412 }
6413 nPrintCol = 80/(maxlen+2);
6414 if( nPrintCol<1 ) nPrintCol = 1;
6415 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6416 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006417 for(j=i; j<nRow; j+=nPrintRow){
6418 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006419 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6420 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006421 }
mistachkinaae280e2015-12-31 19:06:24 +00006422 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006423 }
6424 }
dand95bb392015-09-30 11:19:05 +00006425
drh98781232012-04-23 12:38:05 +00006426 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6427 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006428 }else
6429
drh2db82112016-09-15 21:35:24 +00006430 /* Begin redirecting output to the file "testcase-out.txt" */
6431 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6432 output_reset(p);
6433 p->out = output_file_open("testcase-out.txt");
6434 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006435 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006436 }
drh760c8162016-09-16 02:52:22 +00006437 if( nArg>=2 ){
6438 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6439 }else{
6440 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6441 }
drh2db82112016-09-15 21:35:24 +00006442 }else
drh2db82112016-09-15 21:35:24 +00006443
drhd12602a2016-12-07 15:49:02 +00006444#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006445 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006446 static const struct {
6447 const char *zCtrlName; /* Name of a test-control option */
6448 int ctrlCode; /* Integer code for that option */
6449 } aCtrl[] = {
6450 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6451 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6452 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6453 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6454 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6455 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6456 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6457 { "assert", SQLITE_TESTCTRL_ASSERT },
6458 { "always", SQLITE_TESTCTRL_ALWAYS },
6459 { "reserve", SQLITE_TESTCTRL_RESERVE },
6460 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6461 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006462 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006463 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006464 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006465 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006466 };
shaneh96887e12011-02-10 21:08:58 +00006467 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006468 int rc2 = 0;
6469 int i, n2;
drh05782482013-10-24 15:20:20 +00006470 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006471
drhd416fe72011-03-17 16:45:50 +00006472 /* convert testctrl text option to value. allow any unique prefix
6473 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006474 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006475 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006476 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006477 if( testctrl<0 ){
6478 testctrl = aCtrl[i].ctrlCode;
6479 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006480 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006481 testctrl = -1;
6482 break;
6483 }
6484 }
6485 }
drh348d19c2013-06-03 12:47:43 +00006486 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006487 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006488 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006489 }else{
6490 switch(testctrl){
6491
6492 /* sqlite3_test_control(int, db, int) */
6493 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006494 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006495 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006496 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006497 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006498 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006499 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006500 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006501 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006502 }
6503 break;
6504
6505 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006506 case SQLITE_TESTCTRL_PRNG_SAVE:
6507 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006508 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006509 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006510 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006511 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006512 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006513 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006514 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6515 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006516 }
6517 break;
6518
6519 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006520 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006521 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006522 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006523 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006524 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006525 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006526 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006527 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006528 }
6529 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006530
shaneh96887e12011-02-10 21:08:58 +00006531 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006532 case SQLITE_TESTCTRL_ASSERT:
6533 case SQLITE_TESTCTRL_ALWAYS:
6534 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006535 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006536 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006537 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006538 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006539 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006540 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006541 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006542 }
6543 break;
6544
6545 /* sqlite3_test_control(int, char *) */
6546#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006547 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006548 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006549 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006550 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006551 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006552 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006553 utf8_printf(stderr,
6554 "Error: testctrl %s takes a single char * option\n",
6555 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006556 }
6557 break;
6558#endif
6559
drh1ffede82015-01-30 20:59:27 +00006560 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006561 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006562 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006563 azArg[2],
drh8964b342015-01-29 17:54:52 +00006564 integerValue(azArg[3]),
6565 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006566 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006567 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006568 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006569 }
6570 break;
6571
mistachkin1fe36bb2016-04-04 02:16:44 +00006572 case SQLITE_TESTCTRL_BITVEC_TEST:
6573 case SQLITE_TESTCTRL_FAULT_INSTALL:
6574 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6575 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006576 default:
mistachkinaae280e2015-12-31 19:06:24 +00006577 utf8_printf(stderr,
6578 "Error: CLI support for testctrl %s not implemented\n",
6579 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006580 break;
6581 }
6582 }
6583 }else
drhf1969722017-02-17 23:52:00 +00006584#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006585
drhc2ce0be2014-05-29 12:36:14 +00006586 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006587 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006588 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006589 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006590
drhc2ce0be2014-05-29 12:36:14 +00006591 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6592 if( nArg==2 ){
6593 enableTimer = booleanValue(azArg[1]);
6594 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006595 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006596 enableTimer = 0;
6597 }
6598 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006599 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006600 rc = 1;
6601 }
shanehe2aa9d72009-11-06 17:20:17 +00006602 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006603
drhc2ce0be2014-05-29 12:36:14 +00006604 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006605 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006606 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006607 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006608 rc = 1;
6609 goto meta_command_exit;
6610 }
drh657b4a82015-03-19 13:30:41 +00006611 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006612 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006613#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006614 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006615 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006616 }else{
drh4b363a52016-07-23 20:27:41 +00006617 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006618 }
6619#endif
6620 }else
6621
drhf442e332014-09-10 19:01:14 +00006622#if SQLITE_USER_AUTHENTICATION
6623 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6624 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006625 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006626 rc = 1;
6627 goto meta_command_exit;
6628 }
drh7883ecf2014-09-11 16:19:31 +00006629 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006630 if( strcmp(azArg[1],"login")==0 ){
6631 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006632 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006633 rc = 1;
6634 goto meta_command_exit;
6635 }
drhd39c40f2014-09-11 00:27:53 +00006636 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6637 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006638 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006639 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006640 rc = 1;
6641 }
6642 }else if( strcmp(azArg[1],"add")==0 ){
6643 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006644 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006645 rc = 1;
6646 goto meta_command_exit;
6647 }
drhd39c40f2014-09-11 00:27:53 +00006648 rc = sqlite3_user_add(p->db, azArg[2],
6649 azArg[3], (int)strlen(azArg[3]),
6650 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006651 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006652 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006653 rc = 1;
6654 }
6655 }else if( strcmp(azArg[1],"edit")==0 ){
6656 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006657 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006658 rc = 1;
6659 goto meta_command_exit;
6660 }
drhd39c40f2014-09-11 00:27:53 +00006661 rc = sqlite3_user_change(p->db, azArg[2],
6662 azArg[3], (int)strlen(azArg[3]),
6663 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006664 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006665 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006666 rc = 1;
6667 }
6668 }else if( strcmp(azArg[1],"delete")==0 ){
6669 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006670 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006671 rc = 1;
6672 goto meta_command_exit;
6673 }
6674 rc = sqlite3_user_delete(p->db, azArg[2]);
6675 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006676 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006677 rc = 1;
6678 }
6679 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006680 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006681 rc = 1;
6682 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006683 }
drhf442e332014-09-10 19:01:14 +00006684 }else
6685#endif /* SQLITE_USER_AUTHENTICATION */
6686
drh9fd301b2011-06-03 13:28:22 +00006687 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006688 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006689 sqlite3_libversion(), sqlite3_sourceid());
6690 }else
6691
drh790f2872015-11-28 18:06:36 +00006692 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6693 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006694 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006695 if( p->db ){
6696 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6697 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006698 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6699 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6700 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6701 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006702 }
6703 }
6704 }else
6705
drhb19e7352016-01-12 19:37:20 +00006706 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6707 sqlite3_vfs *pVfs;
6708 sqlite3_vfs *pCurrent = 0;
6709 if( p->db ){
6710 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6711 }
6712 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6713 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6714 pVfs==pCurrent ? " <--- CURRENT" : "");
6715 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6716 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6717 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6718 if( pVfs->pNext ){
6719 raw_printf(p->out, "-----------------------------------\n");
6720 }
6721 }
6722 }else
6723
drhde60fc22011-12-14 17:53:36 +00006724 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6725 const char *zDbName = nArg==2 ? azArg[1] : "main";
6726 char *zVfsName = 0;
6727 if( p->db ){
6728 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6729 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006730 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006731 sqlite3_free(zVfsName);
6732 }
6733 }
6734 }else
6735
drhcef4fc82012-09-21 22:50:45 +00006736#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6737 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006738 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006739 }else
6740#endif
6741
drhc2ce0be2014-05-29 12:36:14 +00006742 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006743 int j;
drh43617e92006-03-06 20:55:46 +00006744 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006745 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006746 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006747 }
6748 }else
6749
6750 {
mistachkinaae280e2015-12-31 19:06:24 +00006751 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006752 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006753 rc = 1;
drh75897232000-05-29 14:26:00 +00006754 }
drh67505e72002-04-19 12:34:06 +00006755
drhc2ce0be2014-05-29 12:36:14 +00006756meta_command_exit:
6757 if( p->outCount ){
6758 p->outCount--;
6759 if( p->outCount==0 ) output_reset(p);
6760 }
drh67505e72002-04-19 12:34:06 +00006761 return rc;
drh75897232000-05-29 14:26:00 +00006762}
6763
drh67505e72002-04-19 12:34:06 +00006764/*
drh91a66392007-09-07 01:12:32 +00006765** Return TRUE if a semicolon occurs anywhere in the first N characters
6766** of string z[].
drh324ccef2003-02-05 14:06:20 +00006767*/
drh9f099fd2013-08-06 14:01:46 +00006768static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006769 int i;
6770 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6771 return 0;
drh324ccef2003-02-05 14:06:20 +00006772}
6773
6774/*
drh70c7a4b2003-04-26 03:03:06 +00006775** Test to see if a line consists entirely of whitespace.
6776*/
6777static int _all_whitespace(const char *z){
6778 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006779 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006780 if( *z=='/' && z[1]=='*' ){
6781 z += 2;
6782 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6783 if( *z==0 ) return 0;
6784 z++;
6785 continue;
6786 }
6787 if( *z=='-' && z[1]=='-' ){
6788 z += 2;
6789 while( *z && *z!='\n' ){ z++; }
6790 if( *z==0 ) return 1;
6791 continue;
6792 }
6793 return 0;
6794 }
6795 return 1;
6796}
6797
6798/*
drha9b17162003-04-29 18:01:28 +00006799** Return TRUE if the line typed in is an SQL command terminator other
6800** than a semi-colon. The SQL Server style "go" command is understood
6801** as is the Oracle "/".
6802*/
drh9f099fd2013-08-06 14:01:46 +00006803static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006804 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006805 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6806 return 1; /* Oracle */
6807 }
drhf0693c82011-10-11 20:41:54 +00006808 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006809 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006810 return 1; /* SQL Server */
6811 }
6812 return 0;
6813}
6814
6815/*
drh233a5312008-12-18 22:25:13 +00006816** Return true if zSql is a complete SQL statement. Return false if it
6817** ends in the middle of a string literal or C-style comment.
6818*/
drh9f099fd2013-08-06 14:01:46 +00006819static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006820 int rc;
6821 if( zSql==0 ) return 1;
6822 zSql[nSql] = ';';
6823 zSql[nSql+1] = 0;
6824 rc = sqlite3_complete(zSql);
6825 zSql[nSql] = 0;
6826 return rc;
6827}
6828
6829/*
drh4e8142c2016-11-11 14:54:22 +00006830** Run a single line of SQL
6831*/
6832static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6833 int rc;
6834 char *zErrMsg = 0;
6835
6836 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006837 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006838 BEGIN_TIMER;
6839 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6840 END_TIMER;
6841 if( rc || zErrMsg ){
6842 char zPrefix[100];
6843 if( in!=0 || !stdin_is_interactive ){
6844 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6845 "Error: near line %d:", startline);
6846 }else{
6847 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6848 }
6849 if( zErrMsg!=0 ){
6850 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6851 sqlite3_free(zErrMsg);
6852 zErrMsg = 0;
6853 }else{
6854 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6855 }
6856 return 1;
drhe6e1d122017-03-09 13:50:49 +00006857 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006858 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6859 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6860 }
6861 return 0;
6862}
6863
6864
6865/*
drh67505e72002-04-19 12:34:06 +00006866** Read input from *in and process it. If *in==0 then input
6867** is interactive - the user is typing it it. Otherwise, input
6868** is coming from a file or device. A prompt is issued and history
6869** is saved only if input is interactive. An interrupt signal will
6870** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006871**
6872** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006873*/
drhdcd87a92014-08-18 13:45:42 +00006874static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006875 char *zLine = 0; /* A single input line */
6876 char *zSql = 0; /* Accumulated SQL text */
6877 int nLine; /* Length of current line */
6878 int nSql = 0; /* Bytes of zSql[] used */
6879 int nAlloc = 0; /* Allocated zSql[] space */
6880 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006881 int rc; /* Error code */
6882 int errCnt = 0; /* Number of errors seen */
6883 int lineno = 0; /* Current line number */
6884 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006885
6886 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6887 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006888 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006889 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006890 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006891 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006892 break;
drhc49f44e2006-10-26 18:15:42 +00006893 }
drh67505e72002-04-19 12:34:06 +00006894 if( seenInterrupt ){
6895 if( in!=0 ) break;
6896 seenInterrupt = 0;
6897 }
drhc28490c2006-10-26 14:25:58 +00006898 lineno++;
drh849a9d92013-12-21 15:46:06 +00006899 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006900 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006901 continue;
6902 }
drh2af0b2d2002-02-21 02:25:02 +00006903 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006904 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006905 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006906 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006907 break;
6908 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006909 errCnt++;
6910 }
drhdaffd0e2001-04-11 14:28:42 +00006911 continue;
6912 }
drh9f099fd2013-08-06 14:01:46 +00006913 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00006914 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00006915 }
drh9f099fd2013-08-06 14:01:46 +00006916 nLine = strlen30(zLine);
6917 if( nSql+nLine+2>=nAlloc ){
6918 nAlloc = nSql+nLine+100;
6919 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00006920 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006921 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00006922 exit(1);
6923 }
drhdaffd0e2001-04-11 14:28:42 +00006924 }
drh9f099fd2013-08-06 14:01:46 +00006925 nSqlPrior = nSql;
6926 if( nSql==0 ){
6927 int i;
6928 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00006929 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00006930 memcpy(zSql, zLine+i, nLine+1-i);
6931 startline = lineno;
6932 nSql = nLine-i;
6933 }else{
6934 zSql[nSql++] = '\n';
6935 memcpy(zSql+nSql, zLine, nLine+1);
6936 nSql += nLine;
6937 }
6938 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00006939 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00006940 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006941 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00006942 if( p->outCount ){
6943 output_reset(p);
6944 p->outCount = 0;
6945 }
drh9f099fd2013-08-06 14:01:46 +00006946 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00006947 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00006948 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00006949 }
6950 }
drh4e8142c2016-11-11 14:54:22 +00006951 if( nSql && !_all_whitespace(zSql) ){
6952 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006953 }
drh1f9ca2c2015-08-25 16:57:52 +00006954 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00006955 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00006956 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00006957}
6958
drh67505e72002-04-19 12:34:06 +00006959/*
6960** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00006961** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00006962*/
drhd1459152016-09-16 19:11:03 +00006963static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00006964 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00006965 if( clearFlag ){
6966 free(home_dir);
6967 home_dir = 0;
6968 return 0;
6969 }
drh85e72432012-04-11 11:38:53 +00006970 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00006971
drh4ace5362014-11-10 14:42:28 +00006972#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6973 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00006974 {
6975 struct passwd *pwent;
6976 uid_t uid = getuid();
6977 if( (pwent=getpwuid(uid)) != NULL) {
6978 home_dir = pwent->pw_dir;
6979 }
drh67505e72002-04-19 12:34:06 +00006980 }
6981#endif
6982
chw65d3c132007-11-12 21:09:10 +00006983#if defined(_WIN32_WCE)
6984 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6985 */
drh85e72432012-04-11 11:38:53 +00006986 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00006987#else
6988
drh83905c92012-06-21 13:00:37 +00006989#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00006990 if (!home_dir) {
6991 home_dir = getenv("USERPROFILE");
6992 }
6993#endif
6994
drh67505e72002-04-19 12:34:06 +00006995 if (!home_dir) {
6996 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00006997 }
6998
drh83905c92012-06-21 13:00:37 +00006999#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00007000 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00007001 char *zDrive, *zPath;
7002 int n;
7003 zDrive = getenv("HOMEDRIVE");
7004 zPath = getenv("HOMEPATH");
7005 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00007006 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00007007 home_dir = malloc( n );
7008 if( home_dir==0 ) return 0;
7009 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7010 return home_dir;
7011 }
7012 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00007013 }
7014#endif
7015
chw65d3c132007-11-12 21:09:10 +00007016#endif /* !_WIN32_WCE */
7017
drh67505e72002-04-19 12:34:06 +00007018 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00007019 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00007020 char *z = malloc( n );
7021 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00007022 home_dir = z;
7023 }
drhe98d4fa2002-04-21 19:06:22 +00007024
drh67505e72002-04-19 12:34:06 +00007025 return home_dir;
7026}
7027
7028/*
7029** Read input from the file given by sqliterc_override. Or if that
7030** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007031**
7032** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007033*/
drh534f4df2015-02-28 14:03:35 +00007034static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007035 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007036 const char *sqliterc_override /* Name of config file. NULL to use default */
7037){
persicom7e2dfdd2002-04-18 02:46:52 +00007038 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007039 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007040 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007041 FILE *in = NULL;
7042
7043 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007044 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007045 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007046 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007047 " cannot read ~/.sqliterc\n");
7048 return;
drhe98d4fa2002-04-21 19:06:22 +00007049 }
drh2f3de322012-06-27 16:41:31 +00007050 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007051 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7052 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007053 }
drha1f9b5e2004-02-14 16:31:02 +00007054 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007055 if( in ){
drhc28490c2006-10-26 14:25:58 +00007056 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007057 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007058 }
drh534f4df2015-02-28 14:03:35 +00007059 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007060 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007061 }
drh85e72432012-04-11 11:38:53 +00007062 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007063}
7064
drh67505e72002-04-19 12:34:06 +00007065/*
drhe1e38c42003-05-04 18:30:59 +00007066** Show available command line options
7067*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007068static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007069 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007070 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007071 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007072 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007073 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007074 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007075 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007076 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007077 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007078#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7079 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7080#endif
drhcc3b4f82012-02-07 14:13:50 +00007081 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007082 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007083 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007084 " -line set output mode to 'line'\n"
7085 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007086 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007087 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007088#ifdef SQLITE_ENABLE_MULTIPLEX
7089 " -multiplex enable the multiplexor VFS\n"
7090#endif
mistachkine0d68852014-12-11 03:12:33 +00007091 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007092 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007093 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
7094 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00007095 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007096 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007097 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007098 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007099#ifdef SQLITE_ENABLE_VFSTRACE
7100 " -vfstrace enable tracing of all VFS calls\n"
7101#endif
drhe1e38c42003-05-04 18:30:59 +00007102;
7103static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007104 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007105 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007106 "FILENAME is the name of an SQLite database. A new database is created\n"
7107 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007108 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007109 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007110 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007111 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007112 }
7113 exit(1);
7114}
7115
7116/*
drh67505e72002-04-19 12:34:06 +00007117** Initialize the state information in data
7118*/
drhdcd87a92014-08-18 13:45:42 +00007119static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007120 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007121 data->normalMode = data->cMode = data->mode = MODE_List;
7122 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007123 memcpy(data->colSeparator,SEP_Column, 2);
7124 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007125 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007126 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007127 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007128 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007129 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007130 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7131 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007132}
7133
drh98d312f2012-10-25 15:23:14 +00007134/*
drh5c7976f2014-02-10 19:59:27 +00007135** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007136*/
7137#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007138static void printBold(const char *zText){
7139 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7140 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7141 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7142 SetConsoleTextAttribute(out,
7143 FOREGROUND_RED|FOREGROUND_INTENSITY
7144 );
7145 printf("%s", zText);
7146 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007147}
7148#else
drh5c7976f2014-02-10 19:59:27 +00007149static void printBold(const char *zText){
7150 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007151}
7152#endif
7153
7154/*
drh98d312f2012-10-25 15:23:14 +00007155** Get the argument to an --option. Throw an error and die if no argument
7156** is available.
7157*/
7158static char *cmdline_option_value(int argc, char **argv, int i){
7159 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007160 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007161 argv[0], argv[argc-1]);
7162 exit(1);
7163 }
7164 return argv[i];
7165}
7166
mistachkin1fe36bb2016-04-04 02:16:44 +00007167#ifndef SQLITE_SHELL_IS_UTF8
7168# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7169# define SQLITE_SHELL_IS_UTF8 (0)
7170# else
7171# define SQLITE_SHELL_IS_UTF8 (1)
7172# endif
7173#endif
7174
7175#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007176int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007177#else
7178int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007179 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007180#endif
drh75897232000-05-29 14:26:00 +00007181 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007182 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007183 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007184 int i;
drhc28490c2006-10-26 14:25:58 +00007185 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007186 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007187 int readStdin = 1;
7188 int nCmd = 0;
7189 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007190
mistachkin1fe36bb2016-04-04 02:16:44 +00007191 setBinaryMode(stdin, 0);
7192 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007193 stdin_is_interactive = isatty(0);
7194 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007195
drh69b30ab2014-02-27 15:11:52 +00007196#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007197 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007198 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007199 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7200 exit(1);
7201 }
drhc7181902014-02-27 15:04:13 +00007202#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007203 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007204#if !SQLITE_SHELL_IS_UTF8
7205 sqlite3_initialize();
7206 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7207 if( argv==0 ){
7208 raw_printf(stderr, "out of memory\n");
7209 exit(1);
7210 }
7211 for(i=0; i<argc; i++){
7212 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7213 if( argv[i]==0 ){
7214 raw_printf(stderr, "out of memory\n");
7215 exit(1);
7216 }
7217 }
7218#endif
mistachkin1810f222016-04-04 02:33:34 +00007219 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007220 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007221
drh44c2eb12003-04-30 11:38:26 +00007222 /* Make sure we have a valid signal handler early, before anything
7223 ** else is done.
7224 */
drh4c504392000-10-16 22:06:40 +00007225#ifdef SIGINT
7226 signal(SIGINT, interrupt_handler);
7227#endif
drh44c2eb12003-04-30 11:38:26 +00007228
drhac5649a2014-11-28 13:35:03 +00007229#ifdef SQLITE_SHELL_DBNAME_PROC
7230 {
7231 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7232 ** of a C-function that will provide the name of the database file. Use
7233 ** this compile-time option to embed this shell program in larger
7234 ** applications. */
7235 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7236 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7237 warnInmemoryDb = 0;
7238 }
7239#endif
7240
drh22fbcb82004-02-01 01:22:50 +00007241 /* Do an initial pass through the command-line argument to locate
7242 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007243 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007244 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007245 */
drh98d312f2012-10-25 15:23:14 +00007246 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007247 char *z;
drhc28490c2006-10-26 14:25:58 +00007248 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007249 if( z[0]!='-' ){
7250 if( data.zDbFilename==0 ){
7251 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007252 }else{
7253 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7254 ** mean that nothing is read from stdin */
7255 readStdin = 0;
7256 nCmd++;
7257 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7258 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007259 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007260 exit(1);
7261 }
7262 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007263 }
drh98d312f2012-10-25 15:23:14 +00007264 }
drhcc3b4f82012-02-07 14:13:50 +00007265 if( z[1]=='-' ) z++;
7266 if( strcmp(z,"-separator")==0
7267 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007268 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007269 || strcmp(z,"-cmd")==0
7270 ){
drh98d312f2012-10-25 15:23:14 +00007271 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007272 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007273 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007274 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007275 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007276 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007277 ** we do the actual processing of arguments later in a second pass.
7278 */
shanef69573d2009-10-24 02:06:14 +00007279 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007280 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007281#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007282 const char *zSize;
7283 sqlite3_int64 szHeap;
7284
drh98d312f2012-10-25 15:23:14 +00007285 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007286 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007287 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007288 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007289#else
7290 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007291#endif
drh44dec872014-08-30 15:49:25 +00007292 }else if( strcmp(z,"-scratch")==0 ){
7293 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007294 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007295 if( sz>400000 ) sz = 400000;
7296 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007297 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007298 if( n>10 ) n = 10;
7299 if( n<1 ) n = 1;
7300 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7301 data.shellFlgs |= SHFLG_Scratch;
7302 }else if( strcmp(z,"-pagecache")==0 ){
7303 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007304 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007305 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007306 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007307 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007308 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7309 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007310 data.shellFlgs |= SHFLG_Pagecache;
7311 }else if( strcmp(z,"-lookaside")==0 ){
7312 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007313 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007314 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007315 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007316 if( n<0 ) n = 0;
7317 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7318 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007319#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007320 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007321 extern int vfstrace_register(
7322 const char *zTraceName,
7323 const char *zOldVfsName,
7324 int (*xOut)(const char*,void*),
7325 void *pOutArg,
7326 int makeDefault
7327 );
drh2b625e22011-03-16 17:05:28 +00007328 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007329#endif
drh6f25e892011-07-08 17:02:57 +00007330#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007331 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007332 extern int sqlite3_multiple_initialize(const char*,int);
7333 sqlite3_multiplex_initialize(0, 1);
7334#endif
drh7d9f3942013-04-03 01:26:54 +00007335 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007336 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7337 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007338 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007339 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007340 if( pVfs ){
7341 sqlite3_vfs_register(pVfs, 1);
7342 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007343 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007344 exit(1);
7345 }
drh44c2eb12003-04-30 11:38:26 +00007346 }
7347 }
drh98d312f2012-10-25 15:23:14 +00007348 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007349#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007350 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007351 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007352#else
mistachkinaae280e2015-12-31 19:06:24 +00007353 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007354 return 1;
drh01b41712005-08-29 23:06:23 +00007355#endif
drh98d312f2012-10-25 15:23:14 +00007356 }
7357 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007358
drh44c2eb12003-04-30 11:38:26 +00007359 /* Go ahead and open the database file if it already exists. If the
7360 ** file does not exist, delay opening it. This prevents empty database
7361 ** files from being created if a user mistypes the database name argument
7362 ** to the sqlite command-line tool.
7363 */
drhc8d74412004-08-31 23:41:26 +00007364 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007365 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007366 }
7367
drh22fbcb82004-02-01 01:22:50 +00007368 /* Process the initialization file if there is one. If no -init option
7369 ** is given on the command line, look for a file named ~/.sqliterc and
7370 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007371 */
drh534f4df2015-02-28 14:03:35 +00007372 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007373
drh22fbcb82004-02-01 01:22:50 +00007374 /* Make a second pass through the command-line argument and set
7375 ** options. This second pass is delayed until after the initialization
7376 ** file is processed so that the command-line arguments will override
7377 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007378 */
drh98d312f2012-10-25 15:23:14 +00007379 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007380 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007381 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007382 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007383 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007384 i++;
7385 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007386 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007387 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007388 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007389 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007390 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007391 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007392 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007393 }else if( strcmp(z,"-csv")==0 ){
7394 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007395 memcpy(data.colSeparator,",",2);
7396 }else if( strcmp(z,"-ascii")==0 ){
7397 data.mode = MODE_Ascii;
7398 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007399 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007400 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007401 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007402 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007403 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007404 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007405 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007406 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007407 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007408 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007409 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007410 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007411 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007412 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007413 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007414 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007415 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007416 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007417 }else if( strcmp(z,"-eqp")==0 ){
7418 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007419 }else if( strcmp(z,"-eqpfull")==0 ){
7420 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007421 }else if( strcmp(z,"-stats")==0 ){
7422 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007423 }else if( strcmp(z,"-scanstats")==0 ){
7424 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007425 }else if( strcmp(z,"-backslash")==0 ){
7426 /* Undocumented command-line option: -backslash
7427 ** Causes C-style backslash escapes to be evaluated in SQL statements
7428 ** prior to sending the SQL into SQLite. Useful for injecting
7429 ** crazy bytes in the middle of SQL statements for testing and debugging.
7430 */
drhe6e1d122017-03-09 13:50:49 +00007431 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007432 }else if( strcmp(z,"-bail")==0 ){
7433 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007434 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007435 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007436 return 0;
drhc28490c2006-10-26 14:25:58 +00007437 }else if( strcmp(z,"-interactive")==0 ){
7438 stdin_is_interactive = 1;
7439 }else if( strcmp(z,"-batch")==0 ){
7440 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007441 }else if( strcmp(z,"-heap")==0 ){
7442 i++;
drh44dec872014-08-30 15:49:25 +00007443 }else if( strcmp(z,"-scratch")==0 ){
7444 i+=2;
7445 }else if( strcmp(z,"-pagecache")==0 ){
7446 i+=2;
7447 }else if( strcmp(z,"-lookaside")==0 ){
7448 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007449 }else if( strcmp(z,"-mmap")==0 ){
7450 i++;
drha7e61d82011-03-12 17:02:57 +00007451 }else if( strcmp(z,"-vfs")==0 ){
7452 i++;
drh6f25e892011-07-08 17:02:57 +00007453#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007454 }else if( strcmp(z,"-vfstrace")==0 ){
7455 i++;
drh6f25e892011-07-08 17:02:57 +00007456#endif
7457#ifdef SQLITE_ENABLE_MULTIPLEX
7458 }else if( strcmp(z,"-multiplex")==0 ){
7459 i++;
7460#endif
drhcc3b4f82012-02-07 14:13:50 +00007461 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007462 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007463 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007464 /* Run commands that follow -cmd first and separately from commands
7465 ** that simply appear on the command-line. This seems goofy. It would
7466 ** be better if all commands ran in the order that they appear. But
7467 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007468 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007469 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007470 if( z[0]=='.' ){
7471 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007472 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007473 }else{
drh05782482013-10-24 15:20:20 +00007474 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007475 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7476 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007477 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007478 if( bail_on_error ) return rc!=0 ? rc : 1;
7479 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007480 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007481 if( bail_on_error ) return rc;
7482 }
7483 }
drh1e5d0e92000-05-31 23:33:17 +00007484 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007485 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7486 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007487 return 1;
7488 }
drh700c2522016-02-09 18:39:25 +00007489 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007490 }
drh44c2eb12003-04-30 11:38:26 +00007491
drhac5649a2014-11-28 13:35:03 +00007492 if( !readStdin ){
7493 /* Run all arguments that do not begin with '-' as if they were separate
7494 ** command-line inputs, except for the argToSkip argument which contains
7495 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007496 */
drhac5649a2014-11-28 13:35:03 +00007497 for(i=0; i<nCmd; i++){
7498 if( azCmd[i][0]=='.' ){
7499 rc = do_meta_command(azCmd[i], &data);
7500 if( rc ) return rc==2 ? 0 : rc;
7501 }else{
7502 open_db(&data, 0);
7503 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7504 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007505 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007506 return rc!=0 ? rc : 1;
7507 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007508 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007509 return rc;
7510 }
drh6ff13852001-11-25 13:18:23 +00007511 }
drh75897232000-05-29 14:26:00 +00007512 }
drhac5649a2014-11-28 13:35:03 +00007513 free(azCmd);
drh75897232000-05-29 14:26:00 +00007514 }else{
drh44c2eb12003-04-30 11:38:26 +00007515 /* Run commands received from standard input
7516 */
drhc28490c2006-10-26 14:25:58 +00007517 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007518 char *zHome;
7519 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007520 int nHistory;
drh75897232000-05-29 14:26:00 +00007521 printf(
drh743e0032011-12-12 16:51:50 +00007522 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007523 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007524 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007525 );
drhb3735912014-02-10 16:13:42 +00007526 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007527 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007528 printBold("transient in-memory database");
7529 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007530 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007531 }
drhd1459152016-09-16 19:11:03 +00007532 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007533 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007534 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007535 if( (zHistory = malloc(nHistory))!=0 ){
7536 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7537 }
drh67505e72002-04-19 12:34:06 +00007538 }
drhf5ed7ad2015-06-15 14:43:25 +00007539 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007540 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007541 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007542 shell_stifle_history(100);
7543 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007544 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007545 }
drhdaffd0e2001-04-11 14:28:42 +00007546 }else{
drhc28490c2006-10-26 14:25:58 +00007547 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007548 }
7549 }
drh33048c02001-10-01 14:29:22 +00007550 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007551 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007552 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007553 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007554 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007555 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007556 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007557#if !SQLITE_SHELL_IS_UTF8
7558 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7559 sqlite3_free(argv);
7560#endif
drhc28490c2006-10-26 14:25:58 +00007561 return rc;
drh75897232000-05-29 14:26:00 +00007562}