blob: 5562fd61c28763b405aa6b244930ad079233b47c [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
12** This file contains code to implement the "sqlite" command line
13** utility for accessing SQLite databases.
drh75897232000-05-29 14:26:00 +000014*/
mistachkina3b2ff52011-09-16 20:16:36 +000015#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
shane18e526c2008-12-10 22:30:24 +000016/* This needs to come before any includes for MSVC compiler */
17#define _CRT_SECURE_NO_WARNINGS
18#endif
19
drh36f7dd32011-10-13 16:02:17 +000020/*
mistachkin2318d332015-01-12 18:02:52 +000021** If requested, include the SQLite compiler options file for MSVC.
22*/
23#if defined(INCLUDE_MSVC_H)
24#include "msvc.h"
25#endif
26
27/*
drh8cd5b252015-03-02 22:06:43 +000028** No support for loadable extensions in VxWorks.
29*/
drhada3f2b2015-03-23 21:32:50 +000030#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000031# define SQLITE_OMIT_LOAD_EXTENSION 1
32#endif
33
34/*
drh36f7dd32011-10-13 16:02:17 +000035** Enable large-file support for fopen() and friends on unix.
36*/
37#ifndef SQLITE_DISABLE_LFS
38# define _LARGE_FILE 1
39# ifndef _FILE_OFFSET_BITS
40# define _FILE_OFFSET_BITS 64
41# endif
42# define _LARGEFILE_SOURCE 1
43#endif
44
drh75897232000-05-29 14:26:00 +000045#include <stdlib.h>
46#include <string.h>
47#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000048#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000049#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000050#if SQLITE_USER_AUTHENTICATION
51# include "sqlite3userauth.h"
52#endif
drh75897232000-05-29 14:26:00 +000053#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000054#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000055
drh83905c92012-06-21 13:00:37 +000056#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000057# include <signal.h>
chw97185482008-11-17 08:05:31 +000058# if !defined(__RTP__) && !defined(_WRS_KERNEL)
59# include <pwd.h>
60# endif
drhdd45df82002-04-18 12:39:03 +000061# include <unistd.h>
62# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000063#endif
drh75897232000-05-29 14:26:00 +000064
drh0ede9eb2015-01-10 16:49:23 +000065#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000066# include <readline/readline.h>
67# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +000068#endif
danfd34d6d2015-02-25 10:54:53 +000069
drh0ede9eb2015-01-10 16:49:23 +000070#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +000071# include <editline/readline.h>
72#endif
danfd34d6d2015-02-25 10:54:53 +000073
74#if HAVE_EDITLINE || HAVE_READLINE
75
76# define shell_add_history(X) add_history(X)
77# define shell_read_history(X) read_history(X)
78# define shell_write_history(X) write_history(X)
79# define shell_stifle_history(X) stifle_history(X)
80# define shell_readline(X) readline(X)
81
82#elif HAVE_LINENOISE
83
84# include "linenoise.h"
85# define shell_add_history(X) linenoiseHistoryAdd(X)
86# define shell_read_history(X) linenoiseHistoryLoad(X)
87# define shell_write_history(X) linenoiseHistorySave(X)
88# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
89# define shell_readline(X) linenoise(X)
90
91#else
92
mistachkin1fe36bb2016-04-04 02:16:44 +000093# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +000094# define shell_write_history(X)
95# define shell_stifle_history(X)
96
97# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +000098#endif
99
danfd34d6d2015-02-25 10:54:53 +0000100
adamd2e8464a2006-09-06 21:39:40 +0000101#if defined(_WIN32) || defined(WIN32)
102# include <io.h>
drh6976c212014-07-24 12:09:47 +0000103# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000104# define isatty(h) _isatty(h)
105# ifndef access
106# define access(f,m) _access((f),(m))
107# endif
108# undef popen
109# define popen _popen
110# undef pclose
111# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000112#else
mistachkin073664d2015-06-17 18:57:37 +0000113 /* Make sure isatty() has a prototype. */
114 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000115
mistachkin073664d2015-06-17 18:57:37 +0000116# if !defined(__RTP__) && !defined(_WRS_KERNEL)
117 /* popen and pclose are not C89 functions and so are
118 ** sometimes omitted from the <stdio.h> header */
119 extern FILE *popen(const char*,const char*);
120 extern int pclose(FILE*);
121# else
122# define SQLITE_OMIT_POPEN 1
123# endif
mistachkinf6418892013-08-28 01:54:12 +0000124#endif
drh53371f92013-07-25 17:07:03 +0000125
chw65d3c132007-11-12 21:09:10 +0000126#if defined(_WIN32_WCE)
127/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
128 * thus we always assume that we have a console. That can be
129 * overridden with the -batch command line option.
130 */
131#define isatty(x) 1
132#endif
133
drhf0693c82011-10-11 20:41:54 +0000134/* ctype macros that work with signed characters */
135#define IsSpace(X) isspace((unsigned char)X)
136#define IsDigit(X) isdigit((unsigned char)X)
137#define ToLower(X) (char)tolower((unsigned char)X)
138
mistachkin1fe36bb2016-04-04 02:16:44 +0000139#if defined(_WIN32) || defined(WIN32)
140#include <windows.h>
141
142/* string conversion routines only needed on Win32 */
143extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
144extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
145extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000146extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000147#endif
148
drh047d4532015-01-18 20:30:23 +0000149/* On Windows, we normally run with output mode of TEXT so that \n characters
150** are automatically translated into \r\n. However, this behavior needs
151** to be disabled in some cases (ex: when generating CSV output and when
152** rendering quoted strings that contain \n characters). The following
153** routines take care of that.
154*/
155#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000156static void setBinaryMode(FILE *file, int isOutput){
157 if( isOutput ) fflush(file);
158 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000159}
mistachkin1fe36bb2016-04-04 02:16:44 +0000160static void setTextMode(FILE *file, int isOutput){
161 if( isOutput ) fflush(file);
162 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000163}
164#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000165# define setBinaryMode(X,Y)
166# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000167#endif
168
drh43408312013-10-30 12:43:36 +0000169
170/* True if the timer is enabled */
171static int enableTimer = 0;
172
173/* Return the current wall-clock time */
174static sqlite3_int64 timeOfDay(void){
175 static sqlite3_vfs *clockVfs = 0;
176 sqlite3_int64 t;
177 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000178 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000179 clockVfs->xCurrentTimeInt64(clockVfs, &t);
180 }else{
181 double r;
182 clockVfs->xCurrentTime(clockVfs, &r);
183 t = (sqlite3_int64)(r*86400000.0);
184 }
185 return t;
186}
187
drh91eb93c2015-03-03 19:56:20 +0000188#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000189#include <sys/time.h>
190#include <sys/resource.h>
191
drh91eb93c2015-03-03 19:56:20 +0000192/* VxWorks does not support getrusage() as far as we can determine */
193#if defined(_WRS_KERNEL) || defined(__RTP__)
194struct rusage {
195 struct timeval ru_utime; /* user CPU time used */
196 struct timeval ru_stime; /* system CPU time used */
197};
198#define getrusage(A,B) memset(B,0,sizeof(*B))
199#endif
200
drhda108222009-02-25 19:07:24 +0000201/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000202static struct rusage sBegin; /* CPU time at start */
203static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000204
drhda108222009-02-25 19:07:24 +0000205/*
206** Begin timing an operation
207*/
208static void beginTimer(void){
209 if( enableTimer ){
210 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000211 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000212 }
213}
214
215/* Return the difference of two time_structs in seconds */
216static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000217 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000218 (double)(pEnd->tv_sec - pStart->tv_sec);
219}
220
221/*
222** Print the timing results.
223*/
224static void endTimer(void){
225 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000226 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000227 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000228 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000229 printf("Run Time: real %.3f user %f sys %f\n",
230 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000231 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
232 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
233 }
234}
shaneb320ccd2009-10-21 03:42:58 +0000235
drhda108222009-02-25 19:07:24 +0000236#define BEGIN_TIMER beginTimer()
237#define END_TIMER endTimer()
238#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000239
240#elif (defined(_WIN32) || defined(WIN32))
241
shaneb320ccd2009-10-21 03:42:58 +0000242/* Saved resource information for the beginning of an operation */
243static HANDLE hProcess;
244static FILETIME ftKernelBegin;
245static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000246static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000247typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
248 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000249static GETPROCTIMES getProcessTimesAddr = NULL;
250
shaneb320ccd2009-10-21 03:42:58 +0000251/*
252** Check to see if we have timer support. Return 1 if necessary
253** support found (or found previously).
254*/
255static int hasTimer(void){
256 if( getProcessTimesAddr ){
257 return 1;
258 } else {
drh4ace5362014-11-10 14:42:28 +0000259 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
260 ** versions. See if the version we are running on has it, and if it
261 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000262 */
263 hProcess = GetCurrentProcess();
264 if( hProcess ){
265 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
266 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000267 getProcessTimesAddr =
268 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000269 if( NULL != getProcessTimesAddr ){
270 return 1;
271 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000272 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000273 }
274 }
275 }
276 return 0;
277}
278
279/*
280** Begin timing an operation
281*/
282static void beginTimer(void){
283 if( enableTimer && getProcessTimesAddr ){
284 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000285 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
286 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000287 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000288 }
289}
290
291/* Return the difference of two FILETIME structs in seconds */
292static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
293 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
294 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
295 return (double) ((i64End - i64Start) / 10000000.0);
296}
297
298/*
299** Print the timing results.
300*/
301static void endTimer(void){
302 if( enableTimer && getProcessTimesAddr){
303 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000304 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000305 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000306 printf("Run Time: real %.3f user %f sys %f\n",
307 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000308 timeDiff(&ftUserBegin, &ftUserEnd),
309 timeDiff(&ftKernelBegin, &ftKernelEnd));
310 }
311}
312
313#define BEGIN_TIMER beginTimer()
314#define END_TIMER endTimer()
315#define HAS_TIMER hasTimer()
316
drhda108222009-02-25 19:07:24 +0000317#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000318#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000319#define END_TIMER
320#define HAS_TIMER 0
321#endif
322
shanec0688ea2009-03-05 03:48:06 +0000323/*
324** Used to prevent warnings about unused parameters
325*/
326#define UNUSED_PARAMETER(x) (void)(x)
327
drhe91d16b2008-12-08 18:27:31 +0000328/*
drhc49f44e2006-10-26 18:15:42 +0000329** If the following flag is set, then command execution stops
330** at an error if we are not interactive.
331*/
332static int bail_on_error = 0;
333
334/*
drhc28490c2006-10-26 14:25:58 +0000335** Threat stdin as an interactive input if the following variable
336** is true. Otherwise, assume stdin is connected to a file or pipe.
337*/
338static int stdin_is_interactive = 1;
339
340/*
drhe05461c2015-12-30 13:36:57 +0000341** On Windows systems we have to know if standard output is a console
342** in order to translate UTF-8 into MBCS. The following variable is
343** true if translation is required.
344*/
345static int stdout_is_console = 1;
346
347/*
drh4c504392000-10-16 22:06:40 +0000348** The following is the open SQLite database. We make a pointer
349** to this database a static variable so that it can be accessed
350** by the SIGINT handler to interrupt database processing.
351*/
mistachkin8e189222015-04-19 21:43:16 +0000352static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000353
354/*
drh67505e72002-04-19 12:34:06 +0000355** True if an interrupt (Control-C) has been received.
356*/
drh43617e92006-03-06 20:55:46 +0000357static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000358
359/*
persicom7e2dfdd2002-04-18 02:46:52 +0000360** This is the name of our program. It is set in main(), used
361** in a number of other places, mostly for error messages.
362*/
363static char *Argv0;
364
365/*
366** Prompt strings. Initialized in main. Settable with
367** .prompt main continue
368*/
369static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
370static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
371
drhb0603412007-02-28 04:47:26 +0000372/*
mistachkin710b33b2016-01-03 18:59:28 +0000373** Render output like fprintf(). Except, if the output is going to the
374** console and if this is running on a Windows machine, translate the
375** output from UTF-8 into MBCS.
376*/
377#if defined(_WIN32) || defined(WIN32)
378void utf8_printf(FILE *out, const char *zFormat, ...){
379 va_list ap;
380 va_start(ap, zFormat);
381 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000382 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000383 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000384 sqlite3_free(z1);
385 fputs(z2, out);
386 sqlite3_free(z2);
387 }else{
388 vfprintf(out, zFormat, ap);
389 }
390 va_end(ap);
391}
392#elif !defined(utf8_printf)
393# define utf8_printf fprintf
394#endif
395
396/*
397** Render output like fprintf(). This should not be used on anything that
398** includes string formatting (e.g. "%s").
399*/
400#if !defined(raw_printf)
401# define raw_printf fprintf
402#endif
403
404/*
drhb0603412007-02-28 04:47:26 +0000405** Write I/O traces to the following stream.
406*/
rsebe0a9092007-07-30 18:24:38 +0000407#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000408static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000409#endif
drhb0603412007-02-28 04:47:26 +0000410
411/*
412** This routine works like printf in that its first argument is a
413** format string and subsequent arguments are values to be substituted
414** in place of % fields. The result of formatting this string
415** is written to iotrace.
416*/
rsebe0a9092007-07-30 18:24:38 +0000417#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000418static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000419 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000420 char *z;
drhb0603412007-02-28 04:47:26 +0000421 if( iotrace==0 ) return;
422 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000423 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000424 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000425 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000426 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000427}
rsebe0a9092007-07-30 18:24:38 +0000428#endif
drhb0603412007-02-28 04:47:26 +0000429
drh44c2eb12003-04-30 11:38:26 +0000430
persicom7e2dfdd2002-04-18 02:46:52 +0000431/*
drh83965662003-04-17 02:54:13 +0000432** Determines if a string is a number of not.
433*/
danielk19772e588c72005-12-09 14:25:08 +0000434static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000435 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000436 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000437 return 0;
438 }
439 z++;
440 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000441 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000442 if( *z=='.' ){
443 z++;
drhf0693c82011-10-11 20:41:54 +0000444 if( !IsDigit(*z) ) return 0;
445 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000446 if( realnum ) *realnum = 1;
447 }
448 if( *z=='e' || *z=='E' ){
449 z++;
450 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000451 if( !IsDigit(*z) ) return 0;
452 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000453 if( realnum ) *realnum = 1;
454 }
455 return *z==0;
456}
drh83965662003-04-17 02:54:13 +0000457
458/*
drhe05461c2015-12-30 13:36:57 +0000459** Compute a string length that is limited to what can be stored in
460** lower 30 bits of a 32-bit signed integer.
461*/
462static int strlen30(const char *z){
463 const char *z2 = z;
464 while( *z2 ){ z2++; }
465 return 0x3fffffff & (int)(z2 - z);
466}
467
468/*
drhfeac5f82004-08-01 00:10:45 +0000469** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000470** the text in memory obtained from malloc() and returns a pointer
471** to the text. NULL is returned at end of file, or if malloc()
472** fails.
473**
drh9f099fd2013-08-06 14:01:46 +0000474** If zLine is not NULL then it is a malloced buffer returned from
475** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000476*/
drh9f099fd2013-08-06 14:01:46 +0000477static char *local_getline(char *zLine, FILE *in){
478 int nLine = zLine==0 ? 0 : 100;
479 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000480
drhb07028f2011-10-14 21:49:18 +0000481 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000482 if( n+100>nLine ){
483 nLine = nLine*2 + 100;
484 zLine = realloc(zLine, nLine);
485 if( zLine==0 ) return 0;
486 }
drhdaffd0e2001-04-11 14:28:42 +0000487 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000488 if( n==0 ){
489 free(zLine);
490 return 0;
491 }
492 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000493 break;
494 }
drh9f099fd2013-08-06 14:01:46 +0000495 while( zLine[n] ) n++;
496 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000497 n--;
shaneh13b36022009-12-17 21:07:15 +0000498 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000499 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000500 break;
drh8e7e7a22000-05-30 18:45:23 +0000501 }
502 }
drhe05461c2015-12-30 13:36:57 +0000503#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000504 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000505 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000506 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000507 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000508 if( zTrans ){
509 int nTrans = strlen30(zTrans)+1;
510 if( nTrans>nLine ){
511 zLine = realloc(zLine, nTrans);
512 if( zLine==0 ){
513 sqlite3_free(zTrans);
514 return 0;
515 }
516 }
517 memcpy(zLine, zTrans, nTrans);
518 sqlite3_free(zTrans);
519 }
520 }
521#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000522 return zLine;
523}
524
525/*
drhc28490c2006-10-26 14:25:58 +0000526** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000527**
drh9f099fd2013-08-06 14:01:46 +0000528** If in==0 then read from standard input and prompt before each line.
529** If isContinuation is true, then a continuation prompt is appropriate.
530** If isContinuation is zero, then the main prompt should be used.
531**
532** If zPrior is not NULL then it is a buffer from a prior call to this
533** routine that can be reused.
534**
535** The result is stored in space obtained from malloc() and must either
536** be freed by the caller or else passed back into this routine via the
537** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000538*/
drh9f099fd2013-08-06 14:01:46 +0000539static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000540 char *zPrompt;
541 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000542 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000543 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000544 }else{
drh9f099fd2013-08-06 14:01:46 +0000545 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000546#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000547 printf("%s", zPrompt);
548 fflush(stdout);
549 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000550#else
551 free(zPrior);
552 zResult = shell_readline(zPrompt);
553 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000554#endif
drh9f099fd2013-08-06 14:01:46 +0000555 }
drh8e7e7a22000-05-30 18:45:23 +0000556 return zResult;
557}
drhf42d3182017-03-08 12:25:18 +0000558/*
559** A variable length string to which one can append text.
560*/
561typedef struct ShellText ShellText;
562struct ShellText {
563 char *z;
564 int n;
565 int nAlloc;
566};
567
568/*
569** Initialize and destroy a ShellText object
570*/
571static void initText(ShellText *p){
572 memset(p, 0, sizeof(*p));
573}
574static void freeText(ShellText *p){
575 free(p->z);
576 initText(p);
577}
578
579/* zIn is either a pointer to a NULL-terminated string in memory obtained
580** from malloc(), or a NULL pointer. The string pointed to by zAppend is
581** added to zIn, and the result returned in memory obtained from malloc().
582** zIn, if it was not NULL, is freed.
583**
584** If the third argument, quote, is not '\0', then it is used as a
585** quote character for zAppend.
586*/
587static void appendText(ShellText *p, char const *zAppend, char quote){
588 int len;
589 int i;
590 int nAppend = strlen30(zAppend);
591
592 len = nAppend+p->n+1;
593 if( quote ){
594 len += 2;
595 for(i=0; i<nAppend; i++){
596 if( zAppend[i]==quote ) len++;
597 }
598 }
599
600 if( p->n+len>=p->nAlloc ){
601 p->nAlloc = p->nAlloc*2 + len + 20;
602 p->z = realloc(p->z, p->nAlloc);
603 if( p->z==0 ){
604 memset(p, 0, sizeof(*p));
605 return;
606 }
607 }
608
609 if( quote ){
610 char *zCsr = p->z+p->n;
611 *zCsr++ = quote;
612 for(i=0; i<nAppend; i++){
613 *zCsr++ = zAppend[i];
614 if( zAppend[i]==quote ) *zCsr++ = quote;
615 }
616 *zCsr++ = quote;
617 p->n = (int)(zCsr - p->z);
618 *zCsr = '\0';
619 }else{
620 memcpy(p->z+p->n, zAppend, nAppend);
621 p->n += nAppend;
622 p->z[p->n] = '\0';
623 }
624}
625
626/*
627** Attempt to determine if identifier zName needs to be quoted, either
628** because it contains non-alphanumeric characters, or because it is an
629** SQLite keyword. Be conservative in this estimate: When in doubt assume
630** that quoting is required.
631**
632** Return '"' if quoting is required. Return 0 if no quoting is required.
633*/
634static char quoteChar(const char *zName){
635 /* All SQLite keywords, in alphabetical order */
636 static const char *azKeywords[] = {
637 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
638 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
639 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
640 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
641 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
642 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
643 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
644 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
645 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
646 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
647 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
648 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
649 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
650 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
651 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
652 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
653 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
654 "WITH", "WITHOUT",
655 };
656 int i, lwr, upr, mid, c;
657 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
658 for(i=0; zName[i]; i++){
659 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
660 }
661 lwr = 0;
662 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
663 while( lwr<=upr ){
664 mid = (lwr+upr)/2;
665 c = sqlite3_stricmp(azKeywords[mid], zName);
666 if( c==0 ) return '"';
667 if( c<0 ){
668 lwr = mid+1;
669 }else{
670 upr = mid-1;
671 }
672 }
673 return 0;
674}
drh8e7e7a22000-05-30 18:45:23 +0000675
drh1554bc82017-03-08 16:10:34 +0000676/******************************************************************************
677** SHA3 hash implementation copied from ../ext/misc/shathree.c
678*/
679typedef sqlite3_uint64 u64;
680/*
681** Macros to determine whether the machine is big or little endian,
682** and whether or not that determination is run-time or compile-time.
683**
684** For best performance, an attempt is made to guess at the byte-order
685** using C-preprocessor macros. If that is unsuccessful, or if
686** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
687** at run-time.
688*/
689#ifndef SHA3_BYTEORDER
690# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
691 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
692 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
693 defined(__arm__)
694# define SHA3_BYTEORDER 1234
695# elif defined(sparc) || defined(__ppc__)
696# define SHA3_BYTEORDER 4321
697# else
698# define SHA3_BYTEORDER 0
699# endif
700#endif
701
702
703/*
704** State structure for a SHA3 hash in progress
705*/
706typedef struct SHA3Context SHA3Context;
707struct SHA3Context {
708 union {
709 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
710 unsigned char x[1600]; /* ... or 1600 bytes */
711 } u;
712 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
713 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
714 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
715};
716
717/*
718** A single step of the Keccak mixing function for a 1600-bit state
719*/
720static void KeccakF1600Step(SHA3Context *p){
721 int i;
722 u64 B0, B1, B2, B3, B4;
723 u64 C0, C1, C2, C3, C4;
724 u64 D0, D1, D2, D3, D4;
725 static const u64 RC[] = {
726 0x0000000000000001ULL, 0x0000000000008082ULL,
727 0x800000000000808aULL, 0x8000000080008000ULL,
728 0x000000000000808bULL, 0x0000000080000001ULL,
729 0x8000000080008081ULL, 0x8000000000008009ULL,
730 0x000000000000008aULL, 0x0000000000000088ULL,
731 0x0000000080008009ULL, 0x000000008000000aULL,
732 0x000000008000808bULL, 0x800000000000008bULL,
733 0x8000000000008089ULL, 0x8000000000008003ULL,
734 0x8000000000008002ULL, 0x8000000000000080ULL,
735 0x000000000000800aULL, 0x800000008000000aULL,
736 0x8000000080008081ULL, 0x8000000000008080ULL,
737 0x0000000080000001ULL, 0x8000000080008008ULL
738 };
739# define A00 (p->u.s[0])
740# define A01 (p->u.s[1])
741# define A02 (p->u.s[2])
742# define A03 (p->u.s[3])
743# define A04 (p->u.s[4])
744# define A10 (p->u.s[5])
745# define A11 (p->u.s[6])
746# define A12 (p->u.s[7])
747# define A13 (p->u.s[8])
748# define A14 (p->u.s[9])
749# define A20 (p->u.s[10])
750# define A21 (p->u.s[11])
751# define A22 (p->u.s[12])
752# define A23 (p->u.s[13])
753# define A24 (p->u.s[14])
754# define A30 (p->u.s[15])
755# define A31 (p->u.s[16])
756# define A32 (p->u.s[17])
757# define A33 (p->u.s[18])
758# define A34 (p->u.s[19])
759# define A40 (p->u.s[20])
760# define A41 (p->u.s[21])
761# define A42 (p->u.s[22])
762# define A43 (p->u.s[23])
763# define A44 (p->u.s[24])
764# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
765
766 for(i=0; i<24; i+=4){
767 C0 = A00^A10^A20^A30^A40;
768 C1 = A01^A11^A21^A31^A41;
769 C2 = A02^A12^A22^A32^A42;
770 C3 = A03^A13^A23^A33^A43;
771 C4 = A04^A14^A24^A34^A44;
772 D0 = C4^ROL64(C1, 1);
773 D1 = C0^ROL64(C2, 1);
774 D2 = C1^ROL64(C3, 1);
775 D3 = C2^ROL64(C4, 1);
776 D4 = C3^ROL64(C0, 1);
777
778 B0 = (A00^D0);
779 B1 = ROL64((A11^D1), 44);
780 B2 = ROL64((A22^D2), 43);
781 B3 = ROL64((A33^D3), 21);
782 B4 = ROL64((A44^D4), 14);
783 A00 = B0 ^((~B1)& B2 );
784 A00 ^= RC[i];
785 A11 = B1 ^((~B2)& B3 );
786 A22 = B2 ^((~B3)& B4 );
787 A33 = B3 ^((~B4)& B0 );
788 A44 = B4 ^((~B0)& B1 );
789
790 B2 = ROL64((A20^D0), 3);
791 B3 = ROL64((A31^D1), 45);
792 B4 = ROL64((A42^D2), 61);
793 B0 = ROL64((A03^D3), 28);
794 B1 = ROL64((A14^D4), 20);
795 A20 = B0 ^((~B1)& B2 );
796 A31 = B1 ^((~B2)& B3 );
797 A42 = B2 ^((~B3)& B4 );
798 A03 = B3 ^((~B4)& B0 );
799 A14 = B4 ^((~B0)& B1 );
800
801 B4 = ROL64((A40^D0), 18);
802 B0 = ROL64((A01^D1), 1);
803 B1 = ROL64((A12^D2), 6);
804 B2 = ROL64((A23^D3), 25);
805 B3 = ROL64((A34^D4), 8);
806 A40 = B0 ^((~B1)& B2 );
807 A01 = B1 ^((~B2)& B3 );
808 A12 = B2 ^((~B3)& B4 );
809 A23 = B3 ^((~B4)& B0 );
810 A34 = B4 ^((~B0)& B1 );
811
812 B1 = ROL64((A10^D0), 36);
813 B2 = ROL64((A21^D1), 10);
814 B3 = ROL64((A32^D2), 15);
815 B4 = ROL64((A43^D3), 56);
816 B0 = ROL64((A04^D4), 27);
817 A10 = B0 ^((~B1)& B2 );
818 A21 = B1 ^((~B2)& B3 );
819 A32 = B2 ^((~B3)& B4 );
820 A43 = B3 ^((~B4)& B0 );
821 A04 = B4 ^((~B0)& B1 );
822
823 B3 = ROL64((A30^D0), 41);
824 B4 = ROL64((A41^D1), 2);
825 B0 = ROL64((A02^D2), 62);
826 B1 = ROL64((A13^D3), 55);
827 B2 = ROL64((A24^D4), 39);
828 A30 = B0 ^((~B1)& B2 );
829 A41 = B1 ^((~B2)& B3 );
830 A02 = B2 ^((~B3)& B4 );
831 A13 = B3 ^((~B4)& B0 );
832 A24 = B4 ^((~B0)& B1 );
833
834 C0 = A00^A20^A40^A10^A30;
835 C1 = A11^A31^A01^A21^A41;
836 C2 = A22^A42^A12^A32^A02;
837 C3 = A33^A03^A23^A43^A13;
838 C4 = A44^A14^A34^A04^A24;
839 D0 = C4^ROL64(C1, 1);
840 D1 = C0^ROL64(C2, 1);
841 D2 = C1^ROL64(C3, 1);
842 D3 = C2^ROL64(C4, 1);
843 D4 = C3^ROL64(C0, 1);
844
845 B0 = (A00^D0);
846 B1 = ROL64((A31^D1), 44);
847 B2 = ROL64((A12^D2), 43);
848 B3 = ROL64((A43^D3), 21);
849 B4 = ROL64((A24^D4), 14);
850 A00 = B0 ^((~B1)& B2 );
851 A00 ^= RC[i+1];
852 A31 = B1 ^((~B2)& B3 );
853 A12 = B2 ^((~B3)& B4 );
854 A43 = B3 ^((~B4)& B0 );
855 A24 = B4 ^((~B0)& B1 );
856
857 B2 = ROL64((A40^D0), 3);
858 B3 = ROL64((A21^D1), 45);
859 B4 = ROL64((A02^D2), 61);
860 B0 = ROL64((A33^D3), 28);
861 B1 = ROL64((A14^D4), 20);
862 A40 = B0 ^((~B1)& B2 );
863 A21 = B1 ^((~B2)& B3 );
864 A02 = B2 ^((~B3)& B4 );
865 A33 = B3 ^((~B4)& B0 );
866 A14 = B4 ^((~B0)& B1 );
867
868 B4 = ROL64((A30^D0), 18);
869 B0 = ROL64((A11^D1), 1);
870 B1 = ROL64((A42^D2), 6);
871 B2 = ROL64((A23^D3), 25);
872 B3 = ROL64((A04^D4), 8);
873 A30 = B0 ^((~B1)& B2 );
874 A11 = B1 ^((~B2)& B3 );
875 A42 = B2 ^((~B3)& B4 );
876 A23 = B3 ^((~B4)& B0 );
877 A04 = B4 ^((~B0)& B1 );
878
879 B1 = ROL64((A20^D0), 36);
880 B2 = ROL64((A01^D1), 10);
881 B3 = ROL64((A32^D2), 15);
882 B4 = ROL64((A13^D3), 56);
883 B0 = ROL64((A44^D4), 27);
884 A20 = B0 ^((~B1)& B2 );
885 A01 = B1 ^((~B2)& B3 );
886 A32 = B2 ^((~B3)& B4 );
887 A13 = B3 ^((~B4)& B0 );
888 A44 = B4 ^((~B0)& B1 );
889
890 B3 = ROL64((A10^D0), 41);
891 B4 = ROL64((A41^D1), 2);
892 B0 = ROL64((A22^D2), 62);
893 B1 = ROL64((A03^D3), 55);
894 B2 = ROL64((A34^D4), 39);
895 A10 = B0 ^((~B1)& B2 );
896 A41 = B1 ^((~B2)& B3 );
897 A22 = B2 ^((~B3)& B4 );
898 A03 = B3 ^((~B4)& B0 );
899 A34 = B4 ^((~B0)& B1 );
900
901 C0 = A00^A40^A30^A20^A10;
902 C1 = A31^A21^A11^A01^A41;
903 C2 = A12^A02^A42^A32^A22;
904 C3 = A43^A33^A23^A13^A03;
905 C4 = A24^A14^A04^A44^A34;
906 D0 = C4^ROL64(C1, 1);
907 D1 = C0^ROL64(C2, 1);
908 D2 = C1^ROL64(C3, 1);
909 D3 = C2^ROL64(C4, 1);
910 D4 = C3^ROL64(C0, 1);
911
912 B0 = (A00^D0);
913 B1 = ROL64((A21^D1), 44);
914 B2 = ROL64((A42^D2), 43);
915 B3 = ROL64((A13^D3), 21);
916 B4 = ROL64((A34^D4), 14);
917 A00 = B0 ^((~B1)& B2 );
918 A00 ^= RC[i+2];
919 A21 = B1 ^((~B2)& B3 );
920 A42 = B2 ^((~B3)& B4 );
921 A13 = B3 ^((~B4)& B0 );
922 A34 = B4 ^((~B0)& B1 );
923
924 B2 = ROL64((A30^D0), 3);
925 B3 = ROL64((A01^D1), 45);
926 B4 = ROL64((A22^D2), 61);
927 B0 = ROL64((A43^D3), 28);
928 B1 = ROL64((A14^D4), 20);
929 A30 = B0 ^((~B1)& B2 );
930 A01 = B1 ^((~B2)& B3 );
931 A22 = B2 ^((~B3)& B4 );
932 A43 = B3 ^((~B4)& B0 );
933 A14 = B4 ^((~B0)& B1 );
934
935 B4 = ROL64((A10^D0), 18);
936 B0 = ROL64((A31^D1), 1);
937 B1 = ROL64((A02^D2), 6);
938 B2 = ROL64((A23^D3), 25);
939 B3 = ROL64((A44^D4), 8);
940 A10 = B0 ^((~B1)& B2 );
941 A31 = B1 ^((~B2)& B3 );
942 A02 = B2 ^((~B3)& B4 );
943 A23 = B3 ^((~B4)& B0 );
944 A44 = B4 ^((~B0)& B1 );
945
946 B1 = ROL64((A40^D0), 36);
947 B2 = ROL64((A11^D1), 10);
948 B3 = ROL64((A32^D2), 15);
949 B4 = ROL64((A03^D3), 56);
950 B0 = ROL64((A24^D4), 27);
951 A40 = B0 ^((~B1)& B2 );
952 A11 = B1 ^((~B2)& B3 );
953 A32 = B2 ^((~B3)& B4 );
954 A03 = B3 ^((~B4)& B0 );
955 A24 = B4 ^((~B0)& B1 );
956
957 B3 = ROL64((A20^D0), 41);
958 B4 = ROL64((A41^D1), 2);
959 B0 = ROL64((A12^D2), 62);
960 B1 = ROL64((A33^D3), 55);
961 B2 = ROL64((A04^D4), 39);
962 A20 = B0 ^((~B1)& B2 );
963 A41 = B1 ^((~B2)& B3 );
964 A12 = B2 ^((~B3)& B4 );
965 A33 = B3 ^((~B4)& B0 );
966 A04 = B4 ^((~B0)& B1 );
967
968 C0 = A00^A30^A10^A40^A20;
969 C1 = A21^A01^A31^A11^A41;
970 C2 = A42^A22^A02^A32^A12;
971 C3 = A13^A43^A23^A03^A33;
972 C4 = A34^A14^A44^A24^A04;
973 D0 = C4^ROL64(C1, 1);
974 D1 = C0^ROL64(C2, 1);
975 D2 = C1^ROL64(C3, 1);
976 D3 = C2^ROL64(C4, 1);
977 D4 = C3^ROL64(C0, 1);
978
979 B0 = (A00^D0);
980 B1 = ROL64((A01^D1), 44);
981 B2 = ROL64((A02^D2), 43);
982 B3 = ROL64((A03^D3), 21);
983 B4 = ROL64((A04^D4), 14);
984 A00 = B0 ^((~B1)& B2 );
985 A00 ^= RC[i+3];
986 A01 = B1 ^((~B2)& B3 );
987 A02 = B2 ^((~B3)& B4 );
988 A03 = B3 ^((~B4)& B0 );
989 A04 = B4 ^((~B0)& B1 );
990
991 B2 = ROL64((A10^D0), 3);
992 B3 = ROL64((A11^D1), 45);
993 B4 = ROL64((A12^D2), 61);
994 B0 = ROL64((A13^D3), 28);
995 B1 = ROL64((A14^D4), 20);
996 A10 = B0 ^((~B1)& B2 );
997 A11 = B1 ^((~B2)& B3 );
998 A12 = B2 ^((~B3)& B4 );
999 A13 = B3 ^((~B4)& B0 );
1000 A14 = B4 ^((~B0)& B1 );
1001
1002 B4 = ROL64((A20^D0), 18);
1003 B0 = ROL64((A21^D1), 1);
1004 B1 = ROL64((A22^D2), 6);
1005 B2 = ROL64((A23^D3), 25);
1006 B3 = ROL64((A24^D4), 8);
1007 A20 = B0 ^((~B1)& B2 );
1008 A21 = B1 ^((~B2)& B3 );
1009 A22 = B2 ^((~B3)& B4 );
1010 A23 = B3 ^((~B4)& B0 );
1011 A24 = B4 ^((~B0)& B1 );
1012
1013 B1 = ROL64((A30^D0), 36);
1014 B2 = ROL64((A31^D1), 10);
1015 B3 = ROL64((A32^D2), 15);
1016 B4 = ROL64((A33^D3), 56);
1017 B0 = ROL64((A34^D4), 27);
1018 A30 = B0 ^((~B1)& B2 );
1019 A31 = B1 ^((~B2)& B3 );
1020 A32 = B2 ^((~B3)& B4 );
1021 A33 = B3 ^((~B4)& B0 );
1022 A34 = B4 ^((~B0)& B1 );
1023
1024 B3 = ROL64((A40^D0), 41);
1025 B4 = ROL64((A41^D1), 2);
1026 B0 = ROL64((A42^D2), 62);
1027 B1 = ROL64((A43^D3), 55);
1028 B2 = ROL64((A44^D4), 39);
1029 A40 = B0 ^((~B1)& B2 );
1030 A41 = B1 ^((~B2)& B3 );
1031 A42 = B2 ^((~B3)& B4 );
1032 A43 = B3 ^((~B4)& B0 );
1033 A44 = B4 ^((~B0)& B1 );
1034 }
1035}
1036
1037/*
1038** Initialize a new hash. iSize determines the size of the hash
1039** in bits and should be one of 224, 256, 384, or 512. Or iSize
1040** can be zero to use the default hash size of 256 bits.
1041*/
1042static void SHA3Init(SHA3Context *p, int iSize){
1043 memset(p, 0, sizeof(*p));
1044 if( iSize>=128 && iSize<=512 ){
1045 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1046 }else{
1047 p->nRate = (1600 - 2*256)/8;
1048 }
1049#if SHA3_BYTEORDER==1234
1050 /* Known to be little-endian at compile-time. No-op */
1051#elif SHA3_BYTEORDER==4321
1052 p->ixMask = 7; /* Big-endian */
1053#else
1054 {
1055 static unsigned int one = 1;
1056 if( 1==*(unsigned char*)&one ){
1057 /* Little endian. No byte swapping. */
1058 p->ixMask = 0;
1059 }else{
1060 /* Big endian. Byte swap. */
1061 p->ixMask = 7;
1062 }
1063 }
1064#endif
1065}
1066
1067/*
1068** Make consecutive calls to the SHA3Update function to add new content
1069** to the hash
1070*/
1071static void SHA3Update(
1072 SHA3Context *p,
1073 const unsigned char *aData,
1074 unsigned int nData
1075){
1076 unsigned int i = 0;
1077#if SHA3_BYTEORDER==1234
1078 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1079 for(; i+7<nData; i+=8){
1080 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1081 p->nLoaded += 8;
1082 if( p->nLoaded>=p->nRate ){
1083 KeccakF1600Step(p);
1084 p->nLoaded = 0;
1085 }
1086 }
1087 }
1088#endif
1089 for(; i<nData; i++){
1090#if SHA3_BYTEORDER==1234
1091 p->u.x[p->nLoaded] ^= aData[i];
1092#elif SHA3_BYTEORDER==4321
1093 p->u.x[p->nLoaded^0x07] ^= aData[i];
1094#else
1095 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1096#endif
1097 p->nLoaded++;
1098 if( p->nLoaded==p->nRate ){
1099 KeccakF1600Step(p);
1100 p->nLoaded = 0;
1101 }
1102 }
1103}
1104
1105/*
1106** After all content has been added, invoke SHA3Final() to compute
1107** the final hash. The function returns a pointer to the binary
1108** hash value.
1109*/
1110static unsigned char *SHA3Final(SHA3Context *p){
1111 unsigned int i;
1112 if( p->nLoaded==p->nRate-1 ){
1113 const unsigned char c1 = 0x86;
1114 SHA3Update(p, &c1, 1);
1115 }else{
1116 const unsigned char c2 = 0x06;
1117 const unsigned char c3 = 0x80;
1118 SHA3Update(p, &c2, 1);
1119 p->nLoaded = p->nRate - 1;
1120 SHA3Update(p, &c3, 1);
1121 }
1122 for(i=0; i<p->nRate; i++){
1123 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1124 }
1125 return &p->u.x[p->nRate];
1126}
1127
1128/*
1129** Implementation of the sha3(X,SIZE) function.
1130**
1131** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
1132** size is 256. If X is a BLOB, it is hashed as is.
1133** For all other non-NULL types of input, X is converted into a UTF-8 string
1134** and the string is hashed without the trailing 0x00 terminator. The hash
1135** of a NULL value is NULL.
1136*/
1137static void sha3Func(
1138 sqlite3_context *context,
1139 int argc,
1140 sqlite3_value **argv
1141){
1142 SHA3Context cx;
1143 int eType = sqlite3_value_type(argv[0]);
1144 int nByte = sqlite3_value_bytes(argv[0]);
1145 int iSize;
1146 if( argc==1 ){
1147 iSize = 256;
1148 }else{
1149 iSize = sqlite3_value_int(argv[1]);
1150 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1151 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1152 "384 512", -1);
1153 return;
1154 }
1155 }
1156 if( eType==SQLITE_NULL ) return;
1157 SHA3Init(&cx, iSize);
1158 if( eType==SQLITE_BLOB ){
1159 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1160 }else{
1161 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1162 }
1163 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1164}
1165
1166/* Compute a string using sqlite3_vsnprintf() with a maximum length
1167** of 50 bytes and add it to the hash.
1168*/
1169static void hash_step_vformat(
1170 SHA3Context *p, /* Add content to this context */
1171 const char *zFormat,
1172 ...
1173){
1174 va_list ap;
1175 int n;
1176 char zBuf[50];
1177 va_start(ap, zFormat);
1178 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1179 va_end(ap);
1180 n = (int)strlen(zBuf);
1181 SHA3Update(p, (unsigned char*)zBuf, n);
1182}
1183
1184/*
1185** Implementation of the sha3_query(SQL,SIZE) function.
1186**
1187** This function compiles and runs the SQL statement(s) given in the
1188** argument. The results are hashed using a SIZE-bit SHA3. The default
1189** size is 256.
1190**
1191** The format of the byte stream that is hashed is summarized as follows:
1192**
1193** S<n>:<sql>
1194** R
1195** N
1196** I<int>
1197** F<ieee-float>
1198** B<size>:<bytes>
1199** T<size>:<text>
1200**
1201** <sql> is the original SQL text for each statement run and <n> is
1202** the size of that text. The SQL text is UTF-8. A single R character
1203** occurs before the start of each row. N means a NULL value.
1204** I mean an 8-byte little-endian integer <int>. F is a floating point
1205** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1206** B means blobs of <size> bytes. T means text rendered as <size>
1207** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1208** text integers.
1209**
1210** For each SQL statement in the X input, there is one S segment. Each
1211** S segment is followed by zero or more R segments, one for each row in the
1212** result set. After each R, there are one or more N, I, F, B, or T segments,
1213** one for each column in the result set. Segments are concatentated directly
1214** with no delimiters of any kind.
1215*/
1216static void sha3QueryFunc(
1217 sqlite3_context *context,
1218 int argc,
1219 sqlite3_value **argv
1220){
1221 sqlite3 *db = sqlite3_context_db_handle(context);
1222 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1223 sqlite3_stmt *pStmt = 0;
1224 int nCol; /* Number of columns in the result set */
1225 int i; /* Loop counter */
1226 int rc;
1227 int n;
1228 const char *z;
1229 SHA3Context cx;
1230 int iSize;
1231
1232 if( argc==1 ){
1233 iSize = 256;
1234 }else{
1235 iSize = sqlite3_value_int(argv[1]);
1236 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1237 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1238 "384 512", -1);
1239 return;
1240 }
1241 }
1242 if( zSql==0 ) return;
1243 SHA3Init(&cx, iSize);
1244 while( zSql[0] ){
1245 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1246 if( rc ){
1247 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1248 zSql, sqlite3_errmsg(db));
1249 sqlite3_finalize(pStmt);
1250 sqlite3_result_error(context, zMsg, -1);
1251 sqlite3_free(zMsg);
1252 return;
1253 }
1254 if( !sqlite3_stmt_readonly(pStmt) ){
1255 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1256 sqlite3_finalize(pStmt);
1257 sqlite3_result_error(context, zMsg, -1);
1258 sqlite3_free(zMsg);
1259 return;
1260 }
1261 nCol = sqlite3_column_count(pStmt);
1262 z = sqlite3_sql(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00001263 if( z==0 ){
1264 sqlite3_finalize(pStmt);
1265 continue;
1266 }
drh1554bc82017-03-08 16:10:34 +00001267 n = (int)strlen(z);
1268 hash_step_vformat(&cx,"S%d:",n);
1269 SHA3Update(&cx,(unsigned char*)z,n);
1270
1271 /* Compute a hash over the result of the query */
1272 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1273 SHA3Update(&cx,(const unsigned char*)"R",1);
1274 for(i=0; i<nCol; i++){
1275 switch( sqlite3_column_type(pStmt,i) ){
1276 case SQLITE_NULL: {
1277 SHA3Update(&cx, (const unsigned char*)"N",1);
1278 break;
1279 }
1280 case SQLITE_INTEGER: {
1281 sqlite3_uint64 u;
1282 int j;
1283 unsigned char x[9];
1284 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1285 memcpy(&u, &v, 8);
1286 for(j=8; j>=1; j--){
1287 x[j] = u & 0xff;
1288 u >>= 8;
1289 }
1290 x[0] = 'I';
1291 SHA3Update(&cx, x, 9);
1292 break;
1293 }
1294 case SQLITE_FLOAT: {
1295 sqlite3_uint64 u;
1296 int j;
1297 unsigned char x[9];
1298 double r = sqlite3_column_double(pStmt,i);
1299 memcpy(&u, &r, 8);
1300 for(j=8; j>=1; j--){
1301 x[j] = u & 0xff;
1302 u >>= 8;
1303 }
1304 x[0] = 'F';
1305 SHA3Update(&cx,x,9);
1306 break;
1307 }
1308 case SQLITE_TEXT: {
1309 int n2 = sqlite3_column_bytes(pStmt, i);
1310 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1311 hash_step_vformat(&cx,"T%d:",n2);
1312 SHA3Update(&cx, z2, n2);
1313 break;
1314 }
1315 case SQLITE_BLOB: {
1316 int n2 = sqlite3_column_bytes(pStmt, i);
1317 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1318 hash_step_vformat(&cx,"B%d:",n2);
1319 SHA3Update(&cx, z2, n2);
1320 break;
1321 }
1322 }
1323 }
1324 }
1325 sqlite3_finalize(pStmt);
1326 }
1327 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1328}
1329/* End of SHA3 hashing logic copy/pasted from ../ext/misc/shathree.c
1330********************************************************************************/
1331
drhe6229612014-08-18 15:08:26 +00001332#if defined(SQLITE_ENABLE_SESSION)
1333/*
1334** State information for a single open session
1335*/
1336typedef struct OpenSession OpenSession;
1337struct OpenSession {
1338 char *zName; /* Symbolic name for this session */
1339 int nFilter; /* Number of xFilter rejection GLOB patterns */
1340 char **azFilter; /* Array of xFilter rejection GLOB patterns */
1341 sqlite3_session *p; /* The open session */
1342};
1343#endif
1344
drhdcd87a92014-08-18 13:45:42 +00001345/*
mistachkin1fe36bb2016-04-04 02:16:44 +00001346** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00001347** saved so that it can be restored by ".explain off"
1348*/
1349typedef struct SavedModeInfo SavedModeInfo;
1350struct SavedModeInfo {
1351 int valid; /* Is there legit data in here? */
1352 int mode; /* Mode prior to ".explain on" */
1353 int showHeader; /* The ".header" setting prior to ".explain on" */
1354 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00001355};
drh45e29d82006-11-20 16:21:10 +00001356
drh8e7e7a22000-05-30 18:45:23 +00001357/*
drhdcd87a92014-08-18 13:45:42 +00001358** State information about the database connection is contained in an
1359** instance of the following structure.
drh75897232000-05-29 14:26:00 +00001360*/
drhdcd87a92014-08-18 13:45:42 +00001361typedef struct ShellState ShellState;
1362struct ShellState {
shane626a6e42009-10-22 17:30:15 +00001363 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00001364 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00001365 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00001366 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00001367 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00001368 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00001369 int cnt; /* Number of records displayed so far */
1370 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00001371 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00001372 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00001373 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00001374 int cMode; /* temporary output mode for the current query */
1375 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00001376 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00001377 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00001378 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00001379 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00001380 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00001381 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00001382 char colSeparator[20]; /* Column separator character for several modes */
1383 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00001384 int colWidth[100]; /* Requested width of each column when in column mode*/
1385 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00001386 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00001387 ** the database */
drh44c2eb12003-04-30 11:38:26 +00001388 char outfile[FILENAME_MAX]; /* Filename for *out */
1389 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00001390 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00001391 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00001392 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00001393 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00001394 int *aiIndent; /* Array of indents used in MODE_Explain */
1395 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00001396 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00001397#if defined(SQLITE_ENABLE_SESSION)
1398 int nSession; /* Number of active sessions */
1399 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
1400#endif
drh75897232000-05-29 14:26:00 +00001401};
1402
1403/*
drh44dec872014-08-30 15:49:25 +00001404** These are the allowed shellFlgs values
1405*/
drhe6e1d122017-03-09 13:50:49 +00001406#define SHFLG_Scratch 0x00000001 /* The --scratch option is used */
1407#define SHFLG_Pagecache 0x00000002 /* The --pagecache option is used */
1408#define SHFLG_Lookaside 0x00000004 /* Lookaside memory is used */
1409#define SHFLG_Backslash 0x00000008 /* The --backslash option is used */
1410#define SHFLG_PreserveRowid 0x00000010 /* .dump preserves rowid values */
1411#define SHFLG_CountChanges 0x00000020 /* .changes setting */
1412#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
1413
1414/*
1415** Macros for testing and setting shellFlgs
1416*/
1417#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
1418#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
1419#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00001420
1421/*
drh75897232000-05-29 14:26:00 +00001422** These are the allowed modes.
1423*/
drh967e8b72000-06-21 13:59:10 +00001424#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00001425#define MODE_Column 1 /* One record per line in neat columns */
1426#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00001427#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
1428#define MODE_Html 4 /* Generate an XHTML table */
1429#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00001430#define MODE_Quote 6 /* Quote values as for SQL */
1431#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
1432#define MODE_Csv 8 /* Quote strings, numbers are plain */
1433#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
1434#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
1435#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00001436
drh66ce4d02008-02-15 17:38:06 +00001437static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00001438 "line",
1439 "column",
1440 "list",
1441 "semi",
1442 "html",
drhfeac5f82004-08-01 00:10:45 +00001443 "insert",
drh41f5f6e2016-10-21 17:39:30 +00001444 "quote",
drhfeac5f82004-08-01 00:10:45 +00001445 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00001446 "csv",
drh66ce4d02008-02-15 17:38:06 +00001447 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00001448 "ascii",
drh4926fec2016-04-13 15:33:42 +00001449 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00001450};
drh75897232000-05-29 14:26:00 +00001451
1452/*
mistachkinfad42082014-07-24 22:13:12 +00001453** These are the column/row/line separators used by the various
1454** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00001455*/
mistachkinfad42082014-07-24 22:13:12 +00001456#define SEP_Column "|"
1457#define SEP_Row "\n"
1458#define SEP_Tab "\t"
1459#define SEP_Space " "
1460#define SEP_Comma ","
1461#define SEP_CrLf "\r\n"
1462#define SEP_Unit "\x1F"
1463#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00001464
1465/*
drh75897232000-05-29 14:26:00 +00001466** Number of elements in an array
1467*/
drh902b9ee2008-12-05 17:17:07 +00001468#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00001469
1470/*
drh127f9d72010-02-23 01:47:00 +00001471** A callback for the sqlite3_log() interface.
1472*/
1473static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00001474 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00001475 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00001476 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00001477 fflush(p->pLog);
1478}
1479
1480/*
shane626a6e42009-10-22 17:30:15 +00001481** Output the given string as a hex-encoded blob (eg. X'1234' )
1482*/
1483static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
1484 int i;
1485 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00001486 raw_printf(out,"X'");
1487 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
1488 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00001489}
1490
1491/*
drh6193d492017-04-07 11:45:58 +00001492** Find a string that is not found anywhere in z[]. Return a pointer
1493** to that string.
1494**
1495** Try to use zA and zB first. If both of those are already found in z[]
1496** then make up some string and store it in the buffer zBuf.
1497*/
1498static const char *unused_string(
1499 const char *z, /* Result must not appear anywhere in z */
1500 const char *zA, const char *zB, /* Try these first */
1501 char *zBuf /* Space to store a generated string */
1502){
1503 unsigned i = 0;
1504 if( strstr(z, zA)==0 ) return zA;
1505 if( strstr(z, zB)==0 ) return zB;
1506 do{
1507 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
1508 }while( strstr(z,zBuf)!=0 );
1509 return zBuf;
1510}
1511
1512/*
drh28bd4bc2000-06-15 15:57:22 +00001513** Output the given string as a quoted string using SQL quoting conventions.
drh708b22b2017-03-11 01:56:41 +00001514**
1515** The "\n" and "\r" characters are converted to char(10) and char(13)
1516** to prevent them from being transformed by end-of-line translators.
drh28bd4bc2000-06-15 15:57:22 +00001517*/
1518static void output_quoted_string(FILE *out, const char *z){
1519 int i;
drh708b22b2017-03-11 01:56:41 +00001520 char c;
mistachkin1fe36bb2016-04-04 02:16:44 +00001521 setBinaryMode(out, 1);
drh708b22b2017-03-11 01:56:41 +00001522 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
1523 if( c==0 ){
drhe05461c2015-12-30 13:36:57 +00001524 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00001525 }else{
drh6193d492017-04-07 11:45:58 +00001526 const char *zNL = 0;
1527 const char *zCR = 0;
1528 int nNL = 0;
1529 int nCR = 0;
1530 char zBuf1[20], zBuf2[20];
1531 for(i=0; z[i]; i++){
1532 if( z[i]=='\n' ) nNL++;
1533 if( z[i]=='\r' ) nCR++;
1534 }
1535 if( nNL ){
1536 raw_printf(out, "replace(");
1537 zNL = unused_string(z, "\\n", "\\012", zBuf1);
1538 }
1539 if( nCR ){
1540 raw_printf(out, "replace(");
1541 zCR = unused_string(z, "\\r", "\\015", zBuf2);
1542 }
1543 raw_printf(out, "'");
drh28bd4bc2000-06-15 15:57:22 +00001544 while( *z ){
drh708b22b2017-03-11 01:56:41 +00001545 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
1546 if( c=='\'' ) i++;
1547 if( i ){
drh708b22b2017-03-11 01:56:41 +00001548 utf8_printf(out, "%.*s", i, z);
1549 z += i;
drh708b22b2017-03-11 01:56:41 +00001550 }
1551 if( c=='\'' ){
1552 raw_printf(out, "'");
1553 continue;
1554 }
drh708b22b2017-03-11 01:56:41 +00001555 if( c==0 ){
drh28bd4bc2000-06-15 15:57:22 +00001556 break;
1557 }
drh6193d492017-04-07 11:45:58 +00001558 z++;
1559 if( c=='\n' ){
1560 raw_printf(out, "%s", zNL);
1561 continue;
drh708b22b2017-03-11 01:56:41 +00001562 }
drh6193d492017-04-07 11:45:58 +00001563 raw_printf(out, "%s", zCR);
drh28bd4bc2000-06-15 15:57:22 +00001564 }
drh6193d492017-04-07 11:45:58 +00001565 raw_printf(out, "'");
1566 if( nCR ){
1567 raw_printf(out, ",'%s',char(13))", zCR);
1568 }
1569 if( nNL ){
1570 raw_printf(out, ",'%s',char(10))", zNL);
1571 }
drh28bd4bc2000-06-15 15:57:22 +00001572 }
mistachkin1fe36bb2016-04-04 02:16:44 +00001573 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00001574}
1575
1576/*
drhfeac5f82004-08-01 00:10:45 +00001577** Output the given string as a quoted according to C or TCL quoting rules.
1578*/
1579static void output_c_string(FILE *out, const char *z){
1580 unsigned int c;
1581 fputc('"', out);
1582 while( (c = *(z++))!=0 ){
1583 if( c=='\\' ){
1584 fputc(c, out);
1585 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00001586 }else if( c=='"' ){
1587 fputc('\\', out);
1588 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00001589 }else if( c=='\t' ){
1590 fputc('\\', out);
1591 fputc('t', out);
1592 }else if( c=='\n' ){
1593 fputc('\\', out);
1594 fputc('n', out);
1595 }else if( c=='\r' ){
1596 fputc('\\', out);
1597 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00001598 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00001599 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00001600 }else{
1601 fputc(c, out);
1602 }
1603 }
1604 fputc('"', out);
1605}
1606
1607/*
drhc08a4f12000-06-15 16:49:48 +00001608** Output the given string with characters that are special to
1609** HTML escaped.
1610*/
1611static void output_html_string(FILE *out, const char *z){
1612 int i;
drhc3d6ba42014-01-13 20:38:35 +00001613 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00001614 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00001615 for(i=0; z[i]
1616 && z[i]!='<'
1617 && z[i]!='&'
1618 && z[i]!='>'
1619 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00001620 && z[i]!='\'';
1621 i++){}
drhc08a4f12000-06-15 16:49:48 +00001622 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00001623 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00001624 }
1625 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00001626 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00001627 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00001628 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00001629 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00001630 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00001631 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00001632 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00001633 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00001634 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00001635 }else{
1636 break;
1637 }
1638 z += i + 1;
1639 }
1640}
1641
1642/*
drhc49f44e2006-10-26 18:15:42 +00001643** If a field contains any character identified by a 1 in the following
1644** array, then the string must be quoted for CSV.
1645*/
1646static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00001647 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1648 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1649 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1650 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1651 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1652 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1653 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1654 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1655 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1656 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1657 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1658 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1659 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1660 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1661 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1662 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00001663};
1664
1665/*
mistachkindd11f2d2014-12-11 04:49:46 +00001666** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00001667** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00001668** the null value. Strings are quoted if necessary. The separator
1669** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00001670*/
drhdcd87a92014-08-18 13:45:42 +00001671static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00001672 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00001673 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00001674 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00001675 }else{
drhc49f44e2006-10-26 18:15:42 +00001676 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00001677 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00001678 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00001679 if( needCsvQuote[((unsigned char*)z)[i]]
1680 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00001681 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00001682 i = 0;
1683 break;
1684 }
1685 }
1686 if( i==0 ){
1687 putc('"', out);
1688 for(i=0; z[i]; i++){
1689 if( z[i]=='"' ) putc('"', out);
1690 putc(z[i], out);
1691 }
1692 putc('"', out);
1693 }else{
drhe05461c2015-12-30 13:36:57 +00001694 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00001695 }
drh8e64d1c2004-10-07 00:32:39 +00001696 }
1697 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00001698 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00001699 }
1700}
1701
danielk19774af00c62005-01-23 23:43:21 +00001702#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00001703/*
drh4c504392000-10-16 22:06:40 +00001704** This routine runs when the user presses Ctrl-C
1705*/
1706static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00001707 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00001708 seenInterrupt++;
1709 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00001710 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00001711}
danielk19774af00c62005-01-23 23:43:21 +00001712#endif
drh4c504392000-10-16 22:06:40 +00001713
drha0daa752016-09-16 11:53:10 +00001714#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00001715/*
drhde613c62016-04-04 17:23:10 +00001716** When the ".auth ON" is set, the following authorizer callback is
1717** invoked. It always returns SQLITE_OK.
1718*/
1719static int shellAuth(
1720 void *pClientData,
1721 int op,
1722 const char *zA1,
1723 const char *zA2,
1724 const char *zA3,
1725 const char *zA4
1726){
1727 ShellState *p = (ShellState*)pClientData;
1728 static const char *azAction[] = { 0,
1729 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
1730 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
1731 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
1732 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
1733 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
1734 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
1735 "PRAGMA", "READ", "SELECT",
1736 "TRANSACTION", "UPDATE", "ATTACH",
1737 "DETACH", "ALTER_TABLE", "REINDEX",
1738 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
1739 "FUNCTION", "SAVEPOINT", "RECURSIVE"
1740 };
1741 int i;
1742 const char *az[4];
1743 az[0] = zA1;
1744 az[1] = zA2;
1745 az[2] = zA3;
1746 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00001747 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00001748 for(i=0; i<4; i++){
1749 raw_printf(p->out, " ");
1750 if( az[i] ){
1751 output_c_string(p->out, az[i]);
1752 }else{
1753 raw_printf(p->out, "NULL");
1754 }
1755 }
1756 raw_printf(p->out, "\n");
1757 return SQLITE_OK;
1758}
drha0daa752016-09-16 11:53:10 +00001759#endif
mistachkin8145fc62016-09-16 20:39:21 +00001760
drh79f20e92016-12-13 23:22:39 +00001761/*
1762** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
1763**
1764** This routine converts some CREATE TABLE statements for shadow tables
1765** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
1766*/
1767static void printSchemaLine(FILE *out, const char *z, const char *zTail){
1768 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
1769 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
1770 }else{
1771 utf8_printf(out, "%s%s", z, zTail);
1772 }
1773}
1774static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
1775 char c = z[n];
1776 z[n] = 0;
1777 printSchemaLine(out, z, zTail);
1778 z[n] = c;
1779}
drhde613c62016-04-04 17:23:10 +00001780
1781/*
shane626a6e42009-10-22 17:30:15 +00001782** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00001783** invokes for each row of a query result.
1784*/
drh4ace5362014-11-10 14:42:28 +00001785static int shell_callback(
1786 void *pArg,
1787 int nArg, /* Number of result columns */
1788 char **azArg, /* Text of each result column */
1789 char **azCol, /* Column names */
1790 int *aiType /* Column types */
1791){
drh75897232000-05-29 14:26:00 +00001792 int i;
drhdcd87a92014-08-18 13:45:42 +00001793 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00001794
drh700c2522016-02-09 18:39:25 +00001795 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00001796 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00001797 int w = 5;
drh6a535342001-10-19 16:44:56 +00001798 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00001799 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00001800 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00001801 if( len>w ) w = len;
1802 }
drhe05461c2015-12-30 13:36:57 +00001803 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001804 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001805 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00001806 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00001807 }
1808 break;
1809 }
danielk19770d78bae2008-01-03 07:09:48 +00001810 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00001811 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00001812 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
1813 const int *colWidth;
1814 int showHdr;
1815 char *rowSep;
1816 if( p->cMode==MODE_Column ){
1817 colWidth = p->colWidth;
1818 showHdr = p->showHeader;
1819 rowSep = p->rowSeparator;
1820 }else{
1821 colWidth = aExplainWidths;
1822 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00001823 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00001824 }
drha0c66f52000-07-29 13:20:21 +00001825 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00001826 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00001827 int w, n;
1828 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00001829 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00001830 }else{
danielk19770d78bae2008-01-03 07:09:48 +00001831 w = 0;
drh75897232000-05-29 14:26:00 +00001832 }
drh078b1fd2012-09-21 13:40:02 +00001833 if( w==0 ){
drh4f21c4a2008-12-10 22:15:00 +00001834 w = strlen30(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00001835 if( w<10 ) w = 10;
mistachkin44b99f72014-12-11 03:29:14 +00001836 n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00001837 if( w<n ) w = n;
1838 }
1839 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00001840 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00001841 }
drh700c2522016-02-09 18:39:25 +00001842 if( showHdr ){
drh078b1fd2012-09-21 13:40:02 +00001843 if( w<0 ){
drhe05461c2015-12-30 13:36:57 +00001844 utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
drh700c2522016-02-09 18:39:25 +00001845 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001846 }else{
drhe05461c2015-12-30 13:36:57 +00001847 utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
drh700c2522016-02-09 18:39:25 +00001848 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001849 }
drha0c66f52000-07-29 13:20:21 +00001850 }
1851 }
drh700c2522016-02-09 18:39:25 +00001852 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00001853 for(i=0; i<nArg; i++){
1854 int w;
1855 if( i<ArraySize(p->actualWidth) ){
1856 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00001857 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00001858 }else{
1859 w = 10;
1860 }
mistachkinaae280e2015-12-31 19:06:24 +00001861 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00001862 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00001863 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00001864 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00001865 }
drh75897232000-05-29 14:26:00 +00001866 }
1867 }
drh6a535342001-10-19 16:44:56 +00001868 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00001869 for(i=0; i<nArg; i++){
1870 int w;
drha0c66f52000-07-29 13:20:21 +00001871 if( i<ArraySize(p->actualWidth) ){
1872 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00001873 }else{
1874 w = 10;
1875 }
drh700c2522016-02-09 18:39:25 +00001876 if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
drh4f21c4a2008-12-10 22:15:00 +00001877 w = strlen30(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00001878 }
dana98bf362013-11-13 18:35:01 +00001879 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00001880 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00001881 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00001882 }
danc4650bb2013-11-18 08:41:06 +00001883 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00001884 }
drh078b1fd2012-09-21 13:40:02 +00001885 if( w<0 ){
drhe05461c2015-12-30 13:36:57 +00001886 utf8_printf(p->out,"%*.*s%s",-w,-w,
mistachkin44b99f72014-12-11 03:29:14 +00001887 azArg[i] ? azArg[i] : p->nullValue,
drh700c2522016-02-09 18:39:25 +00001888 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001889 }else{
drhe05461c2015-12-30 13:36:57 +00001890 utf8_printf(p->out,"%-*.*s%s",w,w,
mistachkin44b99f72014-12-11 03:29:14 +00001891 azArg[i] ? azArg[i] : p->nullValue,
drh700c2522016-02-09 18:39:25 +00001892 i==nArg-1 ? rowSep : " ");
drh078b1fd2012-09-21 13:40:02 +00001893 }
drh75897232000-05-29 14:26:00 +00001894 }
1895 break;
1896 }
drh4926fec2016-04-13 15:33:42 +00001897 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00001898 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00001899 break;
1900 }
1901 case MODE_Pretty: { /* .schema and .fullschema with --indent */
1902 char *z;
drh07d683f2016-04-13 21:00:36 +00001903 int j;
drh4926fec2016-04-13 15:33:42 +00001904 int nParen = 0;
1905 char cEnd = 0;
1906 char c;
1907 int nLine = 0;
1908 assert( nArg==1 );
1909 if( azArg[0]==0 ) break;
1910 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
1911 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
1912 ){
1913 utf8_printf(p->out, "%s;\n", azArg[0]);
1914 break;
1915 }
1916 z = sqlite3_mprintf("%s", azArg[0]);
1917 j = 0;
1918 for(i=0; IsSpace(z[i]); i++){}
1919 for(; (c = z[i])!=0; i++){
1920 if( IsSpace(c) ){
1921 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
1922 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
1923 j--;
1924 }
1925 z[j++] = c;
1926 }
1927 while( j>0 && IsSpace(z[j-1]) ){ j--; }
1928 z[j] = 0;
1929 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00001930 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00001931 if( c==cEnd ){
1932 cEnd = 0;
1933 }else if( c=='"' || c=='\'' || c=='`' ){
1934 cEnd = c;
1935 }else if( c=='[' ){
1936 cEnd = ']';
1937 }else if( c=='(' ){
1938 nParen++;
1939 }else if( c==')' ){
1940 nParen--;
1941 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00001942 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00001943 j = 0;
1944 }
1945 }
1946 z[j++] = c;
1947 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
1948 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00001949 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00001950 j = 0;
1951 nLine++;
1952 while( IsSpace(z[i+1]) ){ i++; }
1953 }
1954 }
1955 z[j] = 0;
1956 }
drh79f20e92016-12-13 23:22:39 +00001957 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00001958 sqlite3_free(z);
1959 break;
1960 }
drh75897232000-05-29 14:26:00 +00001961 case MODE_List: {
1962 if( p->cnt++==0 && p->showHeader ){
1963 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00001964 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00001965 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00001966 }
1967 }
drh6a535342001-10-19 16:44:56 +00001968 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00001969 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00001970 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00001971 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00001972 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00001973 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00001974 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00001975 }else{
drhe05461c2015-12-30 13:36:57 +00001976 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00001977 }
drh75897232000-05-29 14:26:00 +00001978 }
1979 break;
1980 }
drh1e5d0e92000-05-31 23:33:17 +00001981 case MODE_Html: {
1982 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00001983 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00001984 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00001985 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00001986 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00001987 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00001988 }
mistachkinaae280e2015-12-31 19:06:24 +00001989 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00001990 }
drh6a535342001-10-19 16:44:56 +00001991 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00001992 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00001993 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00001994 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00001995 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00001996 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00001997 }
mistachkinaae280e2015-12-31 19:06:24 +00001998 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00001999 break;
2000 }
drhfeac5f82004-08-01 00:10:45 +00002001 case MODE_Tcl: {
2002 if( p->cnt++==0 && p->showHeader ){
2003 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002004 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00002005 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002006 }
drhe05461c2015-12-30 13:36:57 +00002007 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002008 }
2009 if( azArg==0 ) break;
2010 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00002011 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00002012 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002013 }
drhe05461c2015-12-30 13:36:57 +00002014 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002015 break;
2016 }
drh8e64d1c2004-10-07 00:32:39 +00002017 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00002018 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002019 if( p->cnt++==0 && p->showHeader ){
2020 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002021 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00002022 }
drhe05461c2015-12-30 13:36:57 +00002023 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002024 }
drh40253262014-10-17 21:35:05 +00002025 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00002026 for(i=0; i<nArg; i++){
2027 output_csv(p, azArg[i], i<nArg-1);
2028 }
drhe05461c2015-12-30 13:36:57 +00002029 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002030 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002031 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002032 break;
2033 }
drh41f5f6e2016-10-21 17:39:30 +00002034 case MODE_Quote:
drh28bd4bc2000-06-15 15:57:22 +00002035 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00002036 if( azArg==0 ) break;
drh41f5f6e2016-10-21 17:39:30 +00002037 if( p->cMode==MODE_Insert ){
2038 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2039 if( p->showHeader ){
2040 raw_printf(p->out,"(");
2041 for(i=0; i<nArg; i++){
2042 char *zSep = i>0 ? ",": "";
2043 utf8_printf(p->out, "%s%s", zSep, azCol[i]);
2044 }
2045 raw_printf(p->out,")");
mistachkin151c75a2015-04-07 21:16:40 +00002046 }
drh41f5f6e2016-10-21 17:39:30 +00002047 raw_printf(p->out," VALUES(");
drh59ce2c42016-11-03 13:12:28 +00002048 }else if( p->cnt==0 && p->showHeader ){
2049 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00002050 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00002051 output_quoted_string(p->out, azCol[i]);
2052 }
mistachkin2f9a6132016-11-11 05:19:45 +00002053 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002054 }
drh59ce2c42016-11-03 13:12:28 +00002055 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002056 for(i=0; i<nArg; i++){
2057 char *zSep = i>0 ? ",": "";
shanead6b8d02009-10-22 18:12:58 +00002058 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
mistachkinaae280e2015-12-31 19:06:24 +00002059 utf8_printf(p->out,"%sNULL",zSep);
shanead6b8d02009-10-22 18:12:58 +00002060 }else if( aiType && aiType[i]==SQLITE_TEXT ){
mistachkinaae280e2015-12-31 19:06:24 +00002061 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
shanead6b8d02009-10-22 18:12:58 +00002062 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002063 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drhe05461c2015-12-30 13:36:57 +00002064 utf8_printf(p->out,"%s%s",zSep, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002065 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2066 char z[50];
2067 double r = sqlite3_column_double(p->pStmt, i);
2068 sqlite3_snprintf(50,z,"%!.20g", r);
2069 raw_printf(p->out, "%s%s", zSep, z);
shane626a6e42009-10-22 17:30:15 +00002070 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2071 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2072 int nBlob = sqlite3_column_bytes(p->pStmt, i);
mistachkinaae280e2015-12-31 19:06:24 +00002073 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
shane626a6e42009-10-22 17:30:15 +00002074 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002075 }else if( isNumber(azArg[i], 0) ){
drhe05461c2015-12-30 13:36:57 +00002076 utf8_printf(p->out,"%s%s",zSep, azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002077 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002078 if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
drh28bd4bc2000-06-15 15:57:22 +00002079 output_quoted_string(p->out, azArg[i]);
2080 }
2081 }
drh41f5f6e2016-10-21 17:39:30 +00002082 raw_printf(p->out,p->cMode==MODE_Quote?"\n":");\n");
drh6a535342001-10-19 16:44:56 +00002083 break;
drh28bd4bc2000-06-15 15:57:22 +00002084 }
mistachkin636bf9f2014-07-19 20:15:16 +00002085 case MODE_Ascii: {
2086 if( p->cnt++==0 && p->showHeader ){
2087 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002088 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2089 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002090 }
drhe05461c2015-12-30 13:36:57 +00002091 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002092 }
2093 if( azArg==0 ) break;
2094 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002095 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2096 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002097 }
drhe05461c2015-12-30 13:36:57 +00002098 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002099 break;
2100 }
persicom1d0b8722002-04-18 02:53:04 +00002101 }
drh75897232000-05-29 14:26:00 +00002102 return 0;
2103}
2104
2105/*
shane626a6e42009-10-22 17:30:15 +00002106** This is the callback routine that the SQLite library
2107** invokes for each row of a query result.
2108*/
2109static int callback(void *pArg, int nArg, char **azArg, char **azCol){
2110 /* since we don't have type info, call the shell_callback with a NULL value */
2111 return shell_callback(pArg, nArg, azArg, azCol, NULL);
2112}
2113
drhfb546af2017-03-09 22:00:33 +00002114/*
2115** This is the callback routine from sqlite3_exec() that appends all
2116** output onto the end of a ShellText object.
2117*/
2118static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
2119 ShellText *p = (ShellText*)pArg;
2120 int i;
drh2fb79e92017-03-25 12:08:11 +00002121 UNUSED_PARAMETER(az);
drhfb546af2017-03-09 22:00:33 +00002122 if( p->n ) appendText(p, "|", 0);
2123 for(i=0; i<nArg; i++){
2124 if( i ) appendText(p, ",", 0);
2125 if( azArg[i] ) appendText(p, azArg[i], 0);
2126 }
2127 return 0;
2128}
2129
2130/*
2131** Generate an appropriate SELFTEST table in the main database.
2132*/
2133static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00002134 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00002135 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00002136 "SAVEPOINT selftest_init;\n"
2137 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00002138 " tno INTEGER PRIMARY KEY,\n" /* Test number */
2139 " op TEXT,\n" /* Operator: memo run */
2140 " cmd TEXT,\n" /* Command text */
2141 " ans TEXT\n" /* Desired answer */
2142 ");"
drhf157d102017-03-10 01:05:38 +00002143 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
2144 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
2145 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
2146 " 'memo','Tests generated by --init');\n"
2147 "INSERT INTO [_shell$self]\n"
2148 " SELECT 'run',\n"
2149 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
2150 "FROM sqlite_master ORDER BY 2'',224))',\n"
2151 " hex(sha3_query('SELECT type,name,tbl_name,sql "
2152 "FROM sqlite_master ORDER BY 2',224));\n"
2153 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002154 " SELECT 'run',"
2155 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
2156 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
2157 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
2158 " FROM (\n"
2159 " SELECT name FROM sqlite_master\n"
2160 " WHERE type='table'\n"
2161 " AND name<>'selftest'\n"
2162 " AND coalesce(rootpage,0)>0\n"
2163 " )\n"
2164 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00002165 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00002166 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00002167 "INSERT INTO selftest(tno,op,cmd,ans)"
2168 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
2169 "DROP TABLE [_shell$self];"
2170 ,0,0,&zErrMsg);
2171 if( zErrMsg ){
2172 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
2173 sqlite3_free(zErrMsg);
2174 }
2175 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00002176}
2177
drhf42d3182017-03-08 12:25:18 +00002178
shane626a6e42009-10-22 17:30:15 +00002179/*
drhdcd87a92014-08-18 13:45:42 +00002180** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00002181** the name of the table given. Escape any quote characters in the
2182** table name.
2183*/
drhdcd87a92014-08-18 13:45:42 +00002184static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00002185 int i, n;
drhf42d3182017-03-08 12:25:18 +00002186 int cQuote;
drh33048c02001-10-01 14:29:22 +00002187 char *z;
2188
2189 if( p->zDestTable ){
2190 free(p->zDestTable);
2191 p->zDestTable = 0;
2192 }
2193 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00002194 cQuote = quoteChar(zName);
2195 n = strlen30(zName);
2196 if( cQuote ) n += 2;
drh33048c02001-10-01 14:29:22 +00002197 z = p->zDestTable = malloc( n+1 );
2198 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00002199 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00002200 exit(1);
2201 }
2202 n = 0;
drhf42d3182017-03-08 12:25:18 +00002203 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002204 for(i=0; zName[i]; i++){
2205 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00002206 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002207 }
drhf42d3182017-03-08 12:25:18 +00002208 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00002209 z[n] = 0;
2210}
2211
drhdd3d4592004-08-30 01:54:05 +00002212
2213/*
drhb21a8e42012-01-28 21:08:51 +00002214** Execute a query statement that will generate SQL output. Print
2215** the result columns, comma-separated, on a line and then add a
2216** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00002217**
drhb21a8e42012-01-28 21:08:51 +00002218** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00002219** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00002220** "--" comment occurs at the end of the statement, the comment
2221** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00002222*/
drh157e29a2009-05-21 15:15:00 +00002223static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00002224 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00002225 const char *zSelect, /* SELECT statement to extract content */
2226 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00002227){
drhdd3d4592004-08-30 01:54:05 +00002228 sqlite3_stmt *pSelect;
2229 int rc;
drhb21a8e42012-01-28 21:08:51 +00002230 int nResult;
2231 int i;
2232 const char *z;
drhc7181902014-02-27 15:04:13 +00002233 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00002234 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00002235 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2236 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002237 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00002238 return rc;
2239 }
2240 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00002241 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00002242 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00002243 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00002244 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00002245 zFirstRow = 0;
2246 }
drhb21a8e42012-01-28 21:08:51 +00002247 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00002248 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00002249 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00002250 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00002251 }
2252 if( z==0 ) z = "";
2253 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
2254 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00002255 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00002256 }else{
mistachkinaae280e2015-12-31 19:06:24 +00002257 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00002258 }
drhdd3d4592004-08-30 01:54:05 +00002259 rc = sqlite3_step(pSelect);
2260 }
drh2f464a02011-10-13 00:41:49 +00002261 rc = sqlite3_finalize(pSelect);
2262 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00002263 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
2264 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00002265 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00002266 }
2267 return rc;
drhdd3d4592004-08-30 01:54:05 +00002268}
2269
shane626a6e42009-10-22 17:30:15 +00002270/*
2271** Allocate space and save off current error string.
2272*/
2273static char *save_err_msg(
2274 sqlite3 *db /* Database to query */
2275){
2276 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00002277 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00002278 if( zErrMsg ){
2279 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
2280 }
2281 return zErrMsg;
2282}
2283
drh34784902016-02-27 17:12:36 +00002284#ifdef __linux__
2285/*
2286** Attempt to display I/O stats on Linux using /proc/PID/io
2287*/
2288static void displayLinuxIoStats(FILE *out){
2289 FILE *in;
2290 char z[200];
2291 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
2292 in = fopen(z, "rb");
2293 if( in==0 ) return;
2294 while( fgets(z, sizeof(z), in)!=0 ){
2295 static const struct {
2296 const char *zPattern;
2297 const char *zDesc;
2298 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00002299 { "rchar: ", "Bytes received by read():" },
2300 { "wchar: ", "Bytes sent to write():" },
2301 { "syscr: ", "Read() system calls:" },
2302 { "syscw: ", "Write() system calls:" },
2303 { "read_bytes: ", "Bytes read from storage:" },
2304 { "write_bytes: ", "Bytes written to storage:" },
2305 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00002306 };
2307 int i;
2308 for(i=0; i<ArraySize(aTrans); i++){
2309 int n = (int)strlen(aTrans[i].zPattern);
2310 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00002311 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00002312 break;
2313 }
2314 }
2315 }
2316 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00002317}
drh34784902016-02-27 17:12:36 +00002318#endif
2319
drha2df53b2017-03-10 14:36:10 +00002320/*
2321** Display a single line of status using 64-bit values.
2322*/
2323static void displayStatLine(
2324 ShellState *p, /* The shell context */
2325 char *zLabel, /* Label for this one line */
2326 char *zFormat, /* Format for the result */
2327 int iStatusCtrl, /* Which status to display */
2328 int bReset /* True to reset the stats */
2329){
2330 sqlite3_int64 iCur = -1;
2331 sqlite3_int64 iHiwtr = -1;
2332 int i, nPercent;
2333 char zLine[200];
2334 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
2335 for(i=0, nPercent=0; zFormat[i]; i++){
2336 if( zFormat[i]=='%' ) nPercent++;
2337 }
2338 if( nPercent>1 ){
2339 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
2340 }else{
2341 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
2342 }
2343 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
2344}
drh34784902016-02-27 17:12:36 +00002345
shane626a6e42009-10-22 17:30:15 +00002346/*
shaneh642d8b82010-07-28 16:05:34 +00002347** Display memory stats.
2348*/
2349static int display_stats(
2350 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00002351 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00002352 int bReset /* True to reset the stats */
2353){
2354 int iCur;
2355 int iHiwtr;
2356
2357 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00002358 displayStatLine(pArg, "Memory Used:",
2359 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
2360 displayStatLine(pArg, "Number of Outstanding Allocations:",
2361 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00002362 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00002363 displayStatLine(pArg, "Number of Pcache Pages Used:",
2364 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002365 }
drha2df53b2017-03-10 14:36:10 +00002366 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
2367 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drh44dec872014-08-30 15:49:25 +00002368 if( pArg->shellFlgs & SHFLG_Scratch ){
drha2df53b2017-03-10 14:36:10 +00002369 displayStatLine(pArg, "Number of Scratch Allocations Used:",
2370 "%lld (max %lld)", SQLITE_STATUS_SCRATCH_USED, bReset);
drh44dec872014-08-30 15:49:25 +00002371 }
drha2df53b2017-03-10 14:36:10 +00002372 displayStatLine(pArg, "Number of Scratch Overflow Bytes:",
2373 "%lld (max %lld) bytes", SQLITE_STATUS_SCRATCH_OVERFLOW, bReset);
2374 displayStatLine(pArg, "Largest Allocation:",
2375 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
2376 displayStatLine(pArg, "Largest Pcache Allocation:",
2377 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
2378 displayStatLine(pArg, "Largest Scratch Allocation:",
2379 "%lld bytes", SQLITE_STATUS_SCRATCH_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002380#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00002381 displayStatLine(pArg, "Deepest Parser Stack:",
2382 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00002383#endif
2384 }
2385
2386 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00002387 if( pArg->shellFlgs & SHFLG_Lookaside ){
2388 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00002389 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
2390 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002391 raw_printf(pArg->out,
2392 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00002393 iCur, iHiwtr);
2394 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
2395 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002396 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
2397 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002398 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
2399 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002400 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
2401 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00002402 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
2403 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002404 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
2405 iHiwtr);
drh44dec872014-08-30 15:49:25 +00002406 }
shaneh642d8b82010-07-28 16:05:34 +00002407 iHiwtr = iCur = -1;
2408 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002409 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
2410 iCur);
drh4ace5362014-11-10 14:42:28 +00002411 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00002412 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00002413 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00002414 iHiwtr = iCur = -1;
2415 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002416 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002417 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00002418 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00002419 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00002420 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00002421 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002422 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002423 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002424 iHiwtr = iCur = -1;
2425 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002426 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00002427 iCur);
shaneh642d8b82010-07-28 16:05:34 +00002428 }
2429
2430 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00002431 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
2432 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002433 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002434 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002435 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00002436 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002437 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00002438 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00002439 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00002440 }
2441
drh34784902016-02-27 17:12:36 +00002442#ifdef __linux__
2443 displayLinuxIoStats(pArg->out);
2444#endif
2445
dan5a790282015-08-07 20:06:14 +00002446 /* Do not remove this machine readable comment: extra-stats-output-here */
2447
shaneh642d8b82010-07-28 16:05:34 +00002448 return 0;
2449}
2450
2451/*
dan8d1edb92014-11-05 09:07:28 +00002452** Display scan stats.
2453*/
2454static void display_scanstats(
2455 sqlite3 *db, /* Database to query */
2456 ShellState *pArg /* Pointer to ShellState */
2457){
drhf5ed7ad2015-06-15 14:43:25 +00002458#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
2459 UNUSED_PARAMETER(db);
2460 UNUSED_PARAMETER(pArg);
2461#else
drh15f23c22014-11-06 12:46:16 +00002462 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00002463 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00002464 mx = 0;
2465 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00002466 double rEstLoop = 1.0;
2467 for(i=n=0; 1; i++){
2468 sqlite3_stmt *p = pArg->pStmt;
2469 sqlite3_int64 nLoop, nVisit;
2470 double rEst;
2471 int iSid;
2472 const char *zExplain;
2473 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
2474 break;
2475 }
2476 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00002477 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00002478 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00002479 if( n==0 ){
2480 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00002481 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00002482 }
drh42f30bc2014-11-06 12:08:21 +00002483 n++;
2484 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
2485 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
2486 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00002487 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00002488 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00002489 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00002490 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00002491 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00002492 );
dan8d1edb92014-11-05 09:07:28 +00002493 }
dan8d1edb92014-11-05 09:07:28 +00002494 }
mistachkinaae280e2015-12-31 19:06:24 +00002495 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00002496#endif
dan8d1edb92014-11-05 09:07:28 +00002497}
2498
2499/*
dana98bf362013-11-13 18:35:01 +00002500** Parameter azArray points to a zero-terminated array of strings. zStr
2501** points to a single nul-terminated string. Return non-zero if zStr
2502** is equal, according to strcmp(), to any of the strings in the array.
2503** Otherwise, return zero.
2504*/
2505static int str_in_array(const char *zStr, const char **azArray){
2506 int i;
2507 for(i=0; azArray[i]; i++){
2508 if( 0==strcmp(zStr, azArray[i]) ) return 1;
2509 }
2510 return 0;
2511}
2512
2513/*
2514** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00002515** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00002516** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00002517**
2518** The indenting rules are:
2519**
2520** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
2521** all opcodes that occur between the p2 jump destination and the opcode
2522** itself by 2 spaces.
2523**
drh01752bc2013-11-14 23:59:33 +00002524** * For each "Goto", if the jump destination is earlier in the program
2525** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00002526** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00002527** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00002528** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00002529** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00002530*/
drhdcd87a92014-08-18 13:45:42 +00002531static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00002532 const char *zSql; /* The text of the SQL statement */
2533 const char *z; /* Used to check if this is an EXPLAIN */
2534 int *abYield = 0; /* True if op is an OP_Yield */
2535 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00002536 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00002537
drh8ad0de32014-03-20 18:45:27 +00002538 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
2539 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00002540 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
2541 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00002542 const char *azGoto[] = { "Goto", 0 };
2543
2544 /* Try to figure out if this is really an EXPLAIN statement. If this
2545 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00002546 if( sqlite3_column_count(pSql)!=8 ){
2547 p->cMode = p->mode;
2548 return;
2549 }
dana98bf362013-11-13 18:35:01 +00002550 zSql = sqlite3_sql(pSql);
2551 if( zSql==0 ) return;
2552 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00002553 if( sqlite3_strnicmp(z, "explain", 7) ){
2554 p->cMode = p->mode;
2555 return;
2556 }
dana98bf362013-11-13 18:35:01 +00002557
2558 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
2559 int i;
danc4650bb2013-11-18 08:41:06 +00002560 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00002561 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00002562
2563 /* Set p2 to the P2 field of the current opcode. Then, assuming that
2564 ** p2 is an instruction address, set variable p2op to the index of that
2565 ** instruction in the aiIndent[] array. p2 and p2op may be different if
2566 ** the current instruction is part of a sub-program generated by an
2567 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00002568 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00002569 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00002570
2571 /* Grow the p->aiIndent array as required */
2572 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00002573 if( iOp==0 ){
2574 /* Do further verfication that this is explain output. Abort if
2575 ** it is not */
2576 static const char *explainCols[] = {
2577 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
2578 int jj;
2579 for(jj=0; jj<ArraySize(explainCols); jj++){
2580 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
2581 p->cMode = p->mode;
2582 sqlite3_reset(pSql);
2583 return;
2584 }
2585 }
2586 }
dana98bf362013-11-13 18:35:01 +00002587 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00002588 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
2589 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00002590 }
2591 abYield[iOp] = str_in_array(zOp, azYield);
2592 p->aiIndent[iOp] = 0;
2593 p->nIndent = iOp+1;
2594
2595 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00002596 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002597 }
drhfe705102014-03-06 13:38:37 +00002598 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
2599 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
2600 ){
drheacd29d2016-04-15 15:03:27 +00002601 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00002602 }
2603 }
2604
danc4650bb2013-11-18 08:41:06 +00002605 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002606 sqlite3_free(abYield);
2607 sqlite3_reset(pSql);
2608}
2609
2610/*
2611** Free the array allocated by explain_data_prepare().
2612*/
drhdcd87a92014-08-18 13:45:42 +00002613static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00002614 sqlite3_free(p->aiIndent);
2615 p->aiIndent = 0;
2616 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00002617 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00002618}
2619
2620/*
drheacd29d2016-04-15 15:03:27 +00002621** Disable and restore .wheretrace and .selecttrace settings.
2622*/
2623#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2624extern int sqlite3SelectTrace;
2625static int savedSelectTrace;
2626#endif
2627#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2628extern int sqlite3WhereTrace;
2629static int savedWhereTrace;
2630#endif
2631static void disable_debug_trace_modes(void){
2632#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2633 savedSelectTrace = sqlite3SelectTrace;
2634 sqlite3SelectTrace = 0;
2635#endif
2636#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2637 savedWhereTrace = sqlite3WhereTrace;
2638 sqlite3WhereTrace = 0;
2639#endif
2640}
2641static void restore_debug_trace_modes(void){
2642#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
2643 sqlite3SelectTrace = savedSelectTrace;
2644#endif
2645#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
2646 sqlite3WhereTrace = savedWhereTrace;
2647#endif
2648}
2649
2650/*
2651** Run a prepared statement
2652*/
2653static void exec_prepared_stmt(
2654 ShellState *pArg, /* Pointer to ShellState */
2655 sqlite3_stmt *pStmt, /* Statment to run */
2656 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
2657){
2658 int rc;
2659
2660 /* perform the first step. this will tell us if we
2661 ** have a result set or not and how wide it is.
2662 */
2663 rc = sqlite3_step(pStmt);
2664 /* if we have a result set... */
2665 if( SQLITE_ROW == rc ){
2666 /* if we have a callback... */
2667 if( xCallback ){
2668 /* allocate space for col name ptr, value ptr, and type */
2669 int nCol = sqlite3_column_count(pStmt);
2670 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
2671 if( !pData ){
2672 rc = SQLITE_NOMEM;
2673 }else{
2674 char **azCols = (char **)pData; /* Names of result columns */
2675 char **azVals = &azCols[nCol]; /* Results */
2676 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
2677 int i, x;
2678 assert(sizeof(int) <= sizeof(char *));
2679 /* save off ptrs to column names */
2680 for(i=0; i<nCol; i++){
2681 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
2682 }
2683 do{
2684 /* extract the data and data types */
2685 for(i=0; i<nCol; i++){
2686 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
2687 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
2688 azVals[i] = "";
2689 }else{
2690 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
2691 }
2692 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
2693 rc = SQLITE_NOMEM;
2694 break; /* from for */
2695 }
2696 } /* end for */
2697
2698 /* if data and types extracted successfully... */
2699 if( SQLITE_ROW == rc ){
2700 /* call the supplied callback with the result row data */
2701 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
2702 rc = SQLITE_ABORT;
2703 }else{
2704 rc = sqlite3_step(pStmt);
2705 }
2706 }
2707 } while( SQLITE_ROW == rc );
2708 sqlite3_free(pData);
2709 }
2710 }else{
2711 do{
2712 rc = sqlite3_step(pStmt);
2713 } while( rc == SQLITE_ROW );
2714 }
2715 }
2716}
2717
2718/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002719** Execute a statement or set of statements. Print
2720** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00002721** set via the supplied callback.
2722**
mistachkin1fe36bb2016-04-04 02:16:44 +00002723** This is very similar to SQLite's built-in sqlite3_exec()
2724** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00002725** and callback data argument.
2726*/
2727static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00002728 sqlite3 *db, /* An open database */
2729 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00002730 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00002731 /* (not the same as sqlite3_exec) */
2732 ShellState *pArg, /* Pointer to ShellState */
2733 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00002734){
dan4564ced2010-01-05 04:59:56 +00002735 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
2736 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00002737 int rc2;
dan4564ced2010-01-05 04:59:56 +00002738 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00002739
2740 if( pzErrMsg ){
2741 *pzErrMsg = NULL;
2742 }
2743
shaneb9fc17d2009-10-22 21:23:35 +00002744 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00002745 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00002746 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
2747 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00002748 if( pzErrMsg ){
2749 *pzErrMsg = save_err_msg(db);
2750 }
2751 }else{
shaneb9fc17d2009-10-22 21:23:35 +00002752 if( !pStmt ){
2753 /* this happens for a comment or white-space */
2754 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002755 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00002756 continue;
2757 }
drheacd29d2016-04-15 15:03:27 +00002758 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00002759 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00002760 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00002761
shaneh642d8b82010-07-28 16:05:34 +00002762 /* save off the prepared statment handle and reset row count */
2763 if( pArg ){
2764 pArg->pStmt = pStmt;
2765 pArg->cnt = 0;
2766 }
2767
shanehb7977c52010-01-18 18:17:10 +00002768 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00002769 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00002770 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00002771 }
shanehb7977c52010-01-18 18:17:10 +00002772
drhefbf3b12014-02-28 20:47:24 +00002773 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00002774 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00002775 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00002776 char *zEQP;
2777 disable_debug_trace_modes();
2778 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00002779 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2780 if( rc==SQLITE_OK ){
2781 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00002782 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
2783 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
2784 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00002785 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00002786 }
2787 }
2788 sqlite3_finalize(pExplain);
2789 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00002790 if( pArg->autoEQP>=2 ){
2791 /* Also do an EXPLAIN for ".eqp full" mode */
2792 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
2793 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
2794 if( rc==SQLITE_OK ){
2795 pArg->cMode = MODE_Explain;
2796 explain_data_prepare(pArg, pExplain);
2797 exec_prepared_stmt(pArg, pExplain, xCallback);
2798 explain_data_delete(pArg);
2799 }
2800 sqlite3_finalize(pExplain);
2801 sqlite3_free(zEQP);
2802 }
2803 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00002804 }
2805
drh700c2522016-02-09 18:39:25 +00002806 if( pArg ){
2807 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00002808 if( pArg->autoExplain
2809 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00002810 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00002811 ){
2812 pArg->cMode = MODE_Explain;
2813 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002814
drh700c2522016-02-09 18:39:25 +00002815 /* If the shell is currently in ".explain" mode, gather the extra
2816 ** data required to add indents to the output.*/
2817 if( pArg->cMode==MODE_Explain ){
2818 explain_data_prepare(pArg, pStmt);
2819 }
dana98bf362013-11-13 18:35:01 +00002820 }
2821
drheacd29d2016-04-15 15:03:27 +00002822 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00002823 explain_data_delete(pArg);
2824
shaneh642d8b82010-07-28 16:05:34 +00002825 /* print usage stats if stats on */
2826 if( pArg && pArg->statsOn ){
2827 display_stats(db, pArg, 0);
2828 }
2829
dan8d1edb92014-11-05 09:07:28 +00002830 /* print loop-counters if required */
2831 if( pArg && pArg->scanstatsOn ){
2832 display_scanstats(db, pArg);
2833 }
2834
mistachkin1fe36bb2016-04-04 02:16:44 +00002835 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00002836 ** copy of the error message. Otherwise, set zSql to point to the
2837 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00002838 rc2 = sqlite3_finalize(pStmt);
2839 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00002840 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00002841 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00002842 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00002843 }else if( pzErrMsg ){
2844 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00002845 }
shaneh642d8b82010-07-28 16:05:34 +00002846
2847 /* clear saved stmt handle */
2848 if( pArg ){
2849 pArg->pStmt = NULL;
2850 }
shane626a6e42009-10-22 17:30:15 +00002851 }
shaneb9fc17d2009-10-22 21:23:35 +00002852 } /* end while */
shane626a6e42009-10-22 17:30:15 +00002853
2854 return rc;
2855}
2856
drhe611f142017-03-08 11:44:00 +00002857/*
2858** Release memory previously allocated by tableColumnList().
2859*/
2860static void freeColumnList(char **azCol){
2861 int i;
2862 for(i=1; azCol[i]; i++){
2863 sqlite3_free(azCol[i]);
2864 }
2865 /* azCol[0] is a static string */
2866 sqlite3_free(azCol);
2867}
2868
2869/*
2870** Return a list of pointers to strings which are the names of all
2871** columns in table zTab. The memory to hold the names is dynamically
2872** allocated and must be released by the caller using a subsequent call
2873** to freeColumnList().
2874**
2875** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
2876** value that needs to be preserved, then azCol[0] is filled in with the
2877** name of the rowid column.
2878**
2879** The first regular column in the table is azCol[1]. The list is terminated
2880** by an entry with azCol[i]==0.
2881*/
2882static char **tableColumnList(ShellState *p, const char *zTab){
2883 char **azCol = 0;
2884 sqlite3_stmt *pStmt;
2885 char *zSql;
2886 int nCol = 0;
2887 int nAlloc = 0;
2888 int nPK = 0; /* Number of PRIMARY KEY columns seen */
2889 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00002890 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00002891 int rc;
2892
2893 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
2894 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2895 sqlite3_free(zSql);
2896 if( rc ) return 0;
2897 while( sqlite3_step(pStmt)==SQLITE_ROW ){
2898 if( nCol>=nAlloc-2 ){
2899 nAlloc = nAlloc*2 + nCol + 10;
2900 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
2901 if( azCol==0 ){
2902 raw_printf(stderr, "Error: out of memory\n");
2903 exit(1);
2904 }
2905 }
2906 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
2907 if( sqlite3_column_int(pStmt, 5) ){
2908 nPK++;
2909 if( nPK==1
2910 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
2911 "INTEGER")==0
2912 ){
2913 isIPK = 1;
2914 }else{
2915 isIPK = 0;
2916 }
2917 }
2918 }
2919 sqlite3_finalize(pStmt);
2920 azCol[0] = 0;
2921 azCol[nCol+1] = 0;
2922
2923 /* The decision of whether or not a rowid really needs to be preserved
2924 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
2925 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
2926 ** rowids on tables where the rowid is inaccessible because there are other
2927 ** columns in the table named "rowid", "_rowid_", and "oid".
2928 */
2929 if( preserveRowid && isIPK ){
2930 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
2931 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
2932 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
2933 ** ROWID aliases. To distinguish these cases, check to see if
2934 ** there is a "pk" entry in "PRAGMA index_list". There will be
2935 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
2936 */
2937 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
2938 " WHERE origin='pk'", zTab);
2939 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
2940 sqlite3_free(zSql);
2941 if( rc ){
2942 freeColumnList(azCol);
2943 return 0;
2944 }
2945 rc = sqlite3_step(pStmt);
2946 sqlite3_finalize(pStmt);
2947 preserveRowid = rc==SQLITE_ROW;
2948 }
2949 if( preserveRowid ){
2950 /* Only preserve the rowid if we can find a name to use for the
2951 ** rowid */
2952 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
2953 int i, j;
2954 for(j=0; j<3; j++){
2955 for(i=1; i<=nCol; i++){
2956 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
2957 }
2958 if( i>nCol ){
2959 /* At this point, we know that azRowid[j] is not the name of any
2960 ** ordinary column in the table. Verify that azRowid[j] is a valid
2961 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
2962 ** tables will fail this last check */
drhe611f142017-03-08 11:44:00 +00002963 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
2964 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
2965 break;
2966 }
2967 }
2968 }
2969 return azCol;
2970}
2971
drh33048c02001-10-01 14:29:22 +00002972/*
drhf8563c02017-03-09 18:13:52 +00002973** Toggle the reverse_unordered_selects setting.
2974*/
2975static void toggleSelectOrder(sqlite3 *db){
2976 sqlite3_stmt *pStmt = 0;
2977 int iSetting = 0;
2978 char zStmt[100];
2979 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
2980 if( sqlite3_step(pStmt)==SQLITE_ROW ){
2981 iSetting = sqlite3_column_int(pStmt, 0);
2982 }
2983 sqlite3_finalize(pStmt);
2984 sqlite3_snprintf(sizeof(zStmt), zStmt,
2985 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
2986 sqlite3_exec(db, zStmt, 0, 0, 0);
2987}
2988
2989/*
drh4c653a02000-06-07 01:27:47 +00002990** This is a different callback routine used for dumping the database.
2991** Each row received by this callback consists of a table name,
2992** the table type ("index" or "table") and SQL to create the table.
2993** This routine should print text sufficient to recreate the table.
2994*/
drh701ff6a2017-03-22 12:51:34 +00002995static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
danielk19772a02e332004-06-05 08:04:36 +00002996 int rc;
2997 const char *zTable;
2998 const char *zType;
2999 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00003000 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00003001
drh701ff6a2017-03-22 12:51:34 +00003002 UNUSED_PARAMETER(azNotUsed);
drh4c653a02000-06-07 01:27:47 +00003003 if( nArg!=3 ) return 1;
danielk19772a02e332004-06-05 08:04:36 +00003004 zTable = azArg[0];
3005 zType = azArg[1];
3006 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00003007
drh00b950d2005-09-11 02:03:03 +00003008 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00003009 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00003010 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003011 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00003012 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3013 return 0;
drh45e29d82006-11-20 16:21:10 +00003014 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3015 char *zIns;
3016 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00003017 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00003018 p->writableSchema = 1;
3019 }
3020 zIns = sqlite3_mprintf(
3021 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3022 "VALUES('table','%q','%q',0,'%q');",
3023 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00003024 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00003025 sqlite3_free(zIns);
3026 return 0;
drh00b950d2005-09-11 02:03:03 +00003027 }else{
drh79f20e92016-12-13 23:22:39 +00003028 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00003029 }
danielk19772a02e332004-06-05 08:04:36 +00003030
3031 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00003032 ShellText sSelect;
3033 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00003034 char **azCol;
3035 int i;
3036 char *savedDestTable;
3037 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00003038
drhe611f142017-03-08 11:44:00 +00003039 azCol = tableColumnList(p, zTable);
3040 if( azCol==0 ){
3041 p->nErr++;
3042 return 0;
danielk19772a02e332004-06-05 08:04:36 +00003043 }
3044
drhbf92ec02012-03-22 12:50:34 +00003045 /* Always quote the table name, even if it appears to be pure ascii,
3046 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00003047 initText(&sTable);
3048 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003049 /* If preserving the rowid, add a column list after the table name.
3050 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3051 ** instead of the usual "INSERT INTO tab VALUES(...)".
3052 */
3053 if( azCol[0] ){
3054 appendText(&sTable, "(", 0);
3055 appendText(&sTable, azCol[0], 0);
3056 for(i=1; azCol[i]; i++){
3057 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003058 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003059 }
drhe611f142017-03-08 11:44:00 +00003060 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003061 }
danielk19772a02e332004-06-05 08:04:36 +00003062
drhe611f142017-03-08 11:44:00 +00003063 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003064 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003065 appendText(&sSelect, "SELECT ", 0);
3066 if( azCol[0] ){
3067 appendText(&sSelect, azCol[0], 0);
3068 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003069 }
drhe611f142017-03-08 11:44:00 +00003070 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003071 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003072 if( azCol[i+1] ){
3073 appendText(&sSelect, ",", 0);
3074 }
3075 }
3076 freeColumnList(azCol);
3077 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003078 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003079
3080 savedDestTable = p->zDestTable;
3081 savedMode = p->mode;
3082 p->zDestTable = sTable.z;
3083 p->mode = p->cMode = MODE_Insert;
3084 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003085 if( (rc&0xff)==SQLITE_CORRUPT ){
3086 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3087 toggleSelectOrder(p->db);
3088 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3089 toggleSelectOrder(p->db);
3090 }
drhe611f142017-03-08 11:44:00 +00003091 p->zDestTable = savedDestTable;
3092 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003093 freeText(&sTable);
3094 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003095 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003096 }
drh4c653a02000-06-07 01:27:47 +00003097 return 0;
3098}
3099
3100/*
drh45e29d82006-11-20 16:21:10 +00003101** Run zQuery. Use dump_callback() as the callback routine so that
3102** the contents of the query are output as SQL statements.
3103**
drhdd3d4592004-08-30 01:54:05 +00003104** If we get a SQLITE_CORRUPT error, rerun the query after appending
3105** "ORDER BY rowid DESC" to the end.
3106*/
3107static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003108 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003109 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003110){
3111 int rc;
drh2f464a02011-10-13 00:41:49 +00003112 char *zErr = 0;
3113 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003114 if( rc==SQLITE_CORRUPT ){
3115 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00003116 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00003117 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00003118 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00003119 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003120 sqlite3_free(zErr);
3121 zErr = 0;
3122 }
drhdd3d4592004-08-30 01:54:05 +00003123 zQ2 = malloc( len+100 );
3124 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00003125 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00003126 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
3127 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003128 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00003129 }else{
3130 rc = SQLITE_CORRUPT;
3131 }
3132 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00003133 free(zQ2);
3134 }
3135 return rc;
3136}
3137
3138/*
drh75897232000-05-29 14:26:00 +00003139** Text of a help message
3140*/
persicom1d0b8722002-04-18 02:53:04 +00003141static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00003142#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00003143 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00003144#endif
drh9ff849f2009-02-04 20:55:57 +00003145 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00003146 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00003147 ".binary on|off Turn binary output on or off. Default OFF\n"
drhdf12f1c2015-12-07 21:46:19 +00003148 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00003149 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00003150 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00003151 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00003152 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00003153 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00003154 " If TABLE specified, only dump tables matching\n"
3155 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00003156 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00003157 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00003158 ".exit Exit this program\n"
drh700c2522016-02-09 18:39:25 +00003159 ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
drh4926fec2016-04-13 15:33:42 +00003160 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00003161 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00003162 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00003163 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00003164#ifndef SQLITE_OMIT_TEST_CONTROL
3165 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
3166#endif
drh0e55db12015-02-06 14:51:13 +00003167 ".indexes ?TABLE? Show names of all indexes\n"
3168 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00003169 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00003170#ifdef SQLITE_ENABLE_IOTRACE
3171 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
3172#endif
drh1a513372015-05-02 17:40:23 +00003173 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00003174 ".lint OPTIONS Report potential schema issues. Options:\n"
3175 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00003176#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00003177 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00003178#endif
drh127f9d72010-02-23 01:47:00 +00003179 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00003180 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00003181 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00003182 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00003183 " column Left-aligned columns. (See .width)\n"
3184 " html HTML <table> code\n"
3185 " insert SQL insert statements for TABLE\n"
3186 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00003187 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00003188 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00003189 " tabs Tab-separated values\n"
3190 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00003191 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00003192 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkin8145fc62016-09-16 20:39:21 +00003193 ".open ?--new? ?FILE? Close existing database and reopen FILE\n"
drhcd0509e2016-09-16 00:26:08 +00003194 " The --new starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00003195 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00003196 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003197 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00003198 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00003199 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00003200 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00003201 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00003202 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00003203 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
3204 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00003205 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00003206 ".separator COL ?ROW? Change the column separator and optionally the row\n"
3207 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00003208#if defined(SQLITE_ENABLE_SESSION)
3209 ".session CMD ... Create or control sessions\n"
3210#endif
drh1554bc82017-03-08 16:10:34 +00003211 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00003212 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00003213 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00003214 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00003215 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00003216 ".tables ?TABLE? List names of tables\n"
3217 " If TABLE specified, only list tables matching\n"
3218 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00003219 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00003220 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00003221 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00003222 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00003223 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00003224 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00003225 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00003226 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00003227 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00003228;
3229
drhe6229612014-08-18 15:08:26 +00003230#if defined(SQLITE_ENABLE_SESSION)
3231/*
3232** Print help information for the ".sessions" command
3233*/
3234void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00003235 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00003236 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
3237 "If ?NAME? is omitted, the first defined session is used.\n"
3238 "Subcommands:\n"
3239 " attach TABLE Attach TABLE\n"
3240 " changeset FILE Write a changeset into FILE\n"
3241 " close Close one session\n"
3242 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00003243 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00003244 " indirect ?BOOLEAN? Mark or query the indirect status\n"
3245 " isempty Query whether the session is empty\n"
3246 " list List currently open session names\n"
3247 " open DB NAME Open a new session on DB\n"
3248 " patchset FILE Write a patchset into FILE\n"
3249 );
3250}
3251#endif
3252
3253
drhdaffd0e2001-04-11 14:28:42 +00003254/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00003255static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00003256
drh2db82112016-09-15 21:35:24 +00003257/*
dan11da0022016-12-17 08:18:05 +00003258** Read the content of file zName into memory obtained from sqlite3_malloc64()
3259** and return a pointer to the buffer. The caller is responsible for freeing
3260** the memory.
drh2db82112016-09-15 21:35:24 +00003261**
dan11da0022016-12-17 08:18:05 +00003262** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
3263** read.
3264**
3265** For convenience, a nul-terminator byte is always appended to the data read
3266** from the file before the buffer is returned. This byte is not included in
3267** the final value of (*pnByte), if applicable.
3268**
3269** NULL is returned if any error is encountered. The final value of *pnByte
3270** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00003271*/
dan11da0022016-12-17 08:18:05 +00003272static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00003273 FILE *in = fopen(zName, "rb");
3274 long nIn;
drhd1459152016-09-16 19:11:03 +00003275 size_t nRead;
drh2db82112016-09-15 21:35:24 +00003276 char *pBuf;
3277 if( in==0 ) return 0;
3278 fseek(in, 0, SEEK_END);
3279 nIn = ftell(in);
3280 rewind(in);
drhd1459152016-09-16 19:11:03 +00003281 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00003282 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00003283 nRead = fread(pBuf, nIn, 1, in);
3284 fclose(in);
3285 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00003286 sqlite3_free(pBuf);
3287 return 0;
3288 }
drhd1459152016-09-16 19:11:03 +00003289 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00003290 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00003291 return pBuf;
3292}
3293
drhba5b0932014-07-24 12:39:59 +00003294/*
3295** Implementation of the "readfile(X)" SQL function. The entire content
3296** of the file named X is read and returned as a BLOB. NULL is returned
3297** if the file does not exist or is unreadable.
3298*/
3299static void readfileFunc(
3300 sqlite3_context *context,
3301 int argc,
3302 sqlite3_value **argv
3303){
3304 const char *zName;
drhba5b0932014-07-24 12:39:59 +00003305 void *pBuf;
dan11da0022016-12-17 08:18:05 +00003306 int nBuf;
drhba5b0932014-07-24 12:39:59 +00003307
drhf5ed7ad2015-06-15 14:43:25 +00003308 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003309 zName = (const char*)sqlite3_value_text(argv[0]);
3310 if( zName==0 ) return;
dan11da0022016-12-17 08:18:05 +00003311 pBuf = readFile(zName, &nBuf);
3312 if( pBuf ) sqlite3_result_blob(context, pBuf, nBuf, sqlite3_free);
drhba5b0932014-07-24 12:39:59 +00003313}
3314
3315/*
3316** Implementation of the "writefile(X,Y)" SQL function. The argument Y
3317** is written into file X. The number of bytes written is returned. Or
3318** NULL is returned if something goes wrong, such as being unable to open
3319** file X for writing.
3320*/
3321static void writefileFunc(
3322 sqlite3_context *context,
3323 int argc,
3324 sqlite3_value **argv
3325){
3326 FILE *out;
3327 const char *z;
drhba5b0932014-07-24 12:39:59 +00003328 sqlite3_int64 rc;
3329 const char *zFile;
3330
drhf5ed7ad2015-06-15 14:43:25 +00003331 UNUSED_PARAMETER(argc);
drhba5b0932014-07-24 12:39:59 +00003332 zFile = (const char*)sqlite3_value_text(argv[0]);
3333 if( zFile==0 ) return;
3334 out = fopen(zFile, "wb");
3335 if( out==0 ) return;
3336 z = (const char*)sqlite3_value_blob(argv[1]);
3337 if( z==0 ){
drhba5b0932014-07-24 12:39:59 +00003338 rc = 0;
3339 }else{
drh490fe862014-08-11 14:21:32 +00003340 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
drhba5b0932014-07-24 12:39:59 +00003341 }
3342 fclose(out);
3343 sqlite3_result_int64(context, rc);
3344}
drhdaffd0e2001-04-11 14:28:42 +00003345
drhe6229612014-08-18 15:08:26 +00003346#if defined(SQLITE_ENABLE_SESSION)
3347/*
3348** Close a single OpenSession object and release all of its associated
3349** resources.
3350*/
3351static void session_close(OpenSession *pSession){
3352 int i;
3353 sqlite3session_delete(pSession->p);
3354 sqlite3_free(pSession->zName);
3355 for(i=0; i<pSession->nFilter; i++){
3356 sqlite3_free(pSession->azFilter[i]);
3357 }
3358 sqlite3_free(pSession->azFilter);
3359 memset(pSession, 0, sizeof(OpenSession));
3360}
3361#endif
3362
3363/*
drh51b55a32016-04-04 12:38:05 +00003364** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00003365*/
drhe6229612014-08-18 15:08:26 +00003366#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00003367static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00003368 int i;
3369 for(i=0; i<p->nSession; i++){
3370 session_close(&p->aSession[i]);
3371 }
3372 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00003373}
drh51b55a32016-04-04 12:38:05 +00003374#else
3375# define session_close_all(X)
3376#endif
drhe6229612014-08-18 15:08:26 +00003377
drh75897232000-05-29 14:26:00 +00003378/*
drh03168ca2014-08-18 20:01:31 +00003379** Implementation of the xFilter function for an open session. Omit
3380** any tables named by ".session filter" but let all other table through.
3381*/
3382#if defined(SQLITE_ENABLE_SESSION)
3383static int session_filter(void *pCtx, const char *zTab){
3384 OpenSession *pSession = (OpenSession*)pCtx;
3385 int i;
3386 for(i=0; i<pSession->nFilter; i++){
3387 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
3388 }
3389 return 1;
3390}
3391#endif
3392
3393/*
drh44c2eb12003-04-30 11:38:26 +00003394** Make sure the database is open. If it is not, then open it. If
3395** the database fails to open, print an error message and exit.
3396*/
drhdcd87a92014-08-18 13:45:42 +00003397static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00003398 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00003399 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00003400 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00003401 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00003402 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00003403 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00003404 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00003405 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00003406 exit(1);
drh44c2eb12003-04-30 11:38:26 +00003407 }
drhc2e87a32006-06-27 15:16:14 +00003408#ifndef SQLITE_OMIT_LOAD_EXTENSION
3409 sqlite3_enable_load_extension(p->db, 1);
3410#endif
mistachkin8e189222015-04-19 21:43:16 +00003411 sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003412 readfileFunc, 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00003413 sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
drhba5b0932014-07-24 12:39:59 +00003414 writefileFunc, 0, 0);
drh1554bc82017-03-08 16:10:34 +00003415 sqlite3_create_function(p->db, "sha3", 1, SQLITE_UTF8, 0,
3416 sha3Func, 0, 0);
3417 sqlite3_create_function(p->db, "sha3", 2, SQLITE_UTF8, 0,
3418 sha3Func, 0, 0);
3419 sqlite3_create_function(p->db, "sha3_query", 1, SQLITE_UTF8, 0,
3420 sha3QueryFunc, 0, 0);
3421 sqlite3_create_function(p->db, "sha3_query", 2, SQLITE_UTF8, 0,
3422 sha3QueryFunc, 0, 0);
drh44c2eb12003-04-30 11:38:26 +00003423 }
3424}
3425
3426/*
drhfeac5f82004-08-01 00:10:45 +00003427** Do C-language style dequoting.
3428**
mistachkinf21979d2015-01-18 05:35:01 +00003429** \a -> alarm
3430** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00003431** \t -> tab
3432** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00003433** \v -> vertical tab
3434** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00003435** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00003436** \s -> space
drh4c56b992013-06-27 13:26:55 +00003437** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00003438** \' -> '
drhfeac5f82004-08-01 00:10:45 +00003439** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00003440** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00003441*/
3442static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00003443 int i, j;
3444 char c;
drhc2ce0be2014-05-29 12:36:14 +00003445 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00003446 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00003447 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00003448 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00003449 if( c=='a' ){
3450 c = '\a';
3451 }else if( c=='b' ){
3452 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00003453 }else if( c=='t' ){
3454 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00003455 }else if( c=='n' ){
3456 c = '\n';
3457 }else if( c=='v' ){
3458 c = '\v';
3459 }else if( c=='f' ){
3460 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00003461 }else if( c=='r' ){
3462 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00003463 }else if( c=='"' ){
3464 c = '"';
3465 }else if( c=='\'' ){
3466 c = '\'';
drh4c56b992013-06-27 13:26:55 +00003467 }else if( c=='\\' ){
3468 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00003469 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00003470 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00003471 if( z[i+1]>='0' && z[i+1]<='7' ){
3472 i++;
3473 c = (c<<3) + z[i] - '0';
3474 if( z[i+1]>='0' && z[i+1]<='7' ){
3475 i++;
3476 c = (c<<3) + z[i] - '0';
3477 }
3478 }
3479 }
3480 }
3481 z[j] = c;
3482 }
drhc2ce0be2014-05-29 12:36:14 +00003483 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00003484}
3485
3486/*
drh348d19c2013-06-03 12:47:43 +00003487** Return the value of a hexadecimal digit. Return -1 if the input
3488** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00003489*/
drh348d19c2013-06-03 12:47:43 +00003490static int hexDigitValue(char c){
3491 if( c>='0' && c<='9' ) return c - '0';
3492 if( c>='a' && c<='f' ) return c - 'a' + 10;
3493 if( c>='A' && c<='F' ) return c - 'A' + 10;
3494 return -1;
drhc28490c2006-10-26 14:25:58 +00003495}
3496
3497/*
drh7d9f3942013-04-03 01:26:54 +00003498** Interpret zArg as an integer value, possibly with suffixes.
3499*/
3500static sqlite3_int64 integerValue(const char *zArg){
3501 sqlite3_int64 v = 0;
3502 static const struct { char *zSuffix; int iMult; } aMult[] = {
3503 { "KiB", 1024 },
3504 { "MiB", 1024*1024 },
3505 { "GiB", 1024*1024*1024 },
3506 { "KB", 1000 },
3507 { "MB", 1000000 },
3508 { "GB", 1000000000 },
3509 { "K", 1000 },
3510 { "M", 1000000 },
3511 { "G", 1000000000 },
3512 };
3513 int i;
3514 int isNeg = 0;
3515 if( zArg[0]=='-' ){
3516 isNeg = 1;
3517 zArg++;
3518 }else if( zArg[0]=='+' ){
3519 zArg++;
3520 }
drh348d19c2013-06-03 12:47:43 +00003521 if( zArg[0]=='0' && zArg[1]=='x' ){
3522 int x;
3523 zArg += 2;
3524 while( (x = hexDigitValue(zArg[0]))>=0 ){
3525 v = (v<<4) + x;
3526 zArg++;
3527 }
3528 }else{
3529 while( IsDigit(zArg[0]) ){
3530 v = v*10 + zArg[0] - '0';
3531 zArg++;
3532 }
drh7d9f3942013-04-03 01:26:54 +00003533 }
drhc2bed0a2013-05-24 11:57:50 +00003534 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00003535 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
3536 v *= aMult[i].iMult;
3537 break;
3538 }
3539 }
3540 return isNeg? -v : v;
3541}
3542
3543/*
drh348d19c2013-06-03 12:47:43 +00003544** Interpret zArg as either an integer or a boolean value. Return 1 or 0
3545** for TRUE and FALSE. Return the integer value if appropriate.
3546*/
drhe6e1d122017-03-09 13:50:49 +00003547static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00003548 int i;
3549 if( zArg[0]=='0' && zArg[1]=='x' ){
3550 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
3551 }else{
3552 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
3553 }
3554 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
3555 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
3556 return 1;
3557 }
3558 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
3559 return 0;
3560 }
mistachkinaae280e2015-12-31 19:06:24 +00003561 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00003562 zArg);
3563 return 0;
3564}
3565
3566/*
drhe6e1d122017-03-09 13:50:49 +00003567** Set or clear a shell flag according to a boolean value.
3568*/
3569static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
3570 if( booleanValue(zArg) ){
3571 ShellSetFlag(p, mFlag);
3572 }else{
3573 ShellClearFlag(p, mFlag);
3574 }
3575}
3576
3577/*
drh42f64e52012-04-04 16:56:23 +00003578** Close an output file, assuming it is not stderr or stdout
3579*/
3580static void output_file_close(FILE *f){
3581 if( f && f!=stdout && f!=stderr ) fclose(f);
3582}
3583
3584/*
3585** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00003586** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00003587** filename is "off".
3588*/
3589static FILE *output_file_open(const char *zFile){
3590 FILE *f;
3591 if( strcmp(zFile,"stdout")==0 ){
3592 f = stdout;
3593 }else if( strcmp(zFile, "stderr")==0 ){
3594 f = stderr;
3595 }else if( strcmp(zFile, "off")==0 ){
3596 f = 0;
3597 }else{
3598 f = fopen(zFile, "wb");
3599 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003600 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00003601 }
3602 }
3603 return f;
3604}
3605
drhd12602a2016-12-07 15:49:02 +00003606#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00003607#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00003608/*
3609** A routine for handling output from sqlite3_trace().
3610*/
drh4b363a52016-07-23 20:27:41 +00003611static int sql_trace_callback(
3612 unsigned mType,
3613 void *pArg,
3614 void *pP,
3615 void *pX
3616){
drh42f64e52012-04-04 16:56:23 +00003617 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00003618 UNUSED_PARAMETER(mType);
3619 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00003620 if( f ){
drh4b363a52016-07-23 20:27:41 +00003621 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00003622 int i = (int)strlen(z);
3623 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00003624 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00003625 }
drh4b363a52016-07-23 20:27:41 +00003626 return 0;
drh42f64e52012-04-04 16:56:23 +00003627}
drhc10b9da2016-11-20 17:59:59 +00003628#endif
3629#endif
drh42f64e52012-04-04 16:56:23 +00003630
3631/*
drhd8621b92012-04-17 09:09:33 +00003632** A no-op routine that runs with the ".breakpoint" doc-command. This is
3633** a useful spot to set a debugger breakpoint.
3634*/
3635static void test_breakpoint(void){
3636 static int nCall = 0;
3637 nCall++;
3638}
3639
3640/*
mistachkin636bf9f2014-07-19 20:15:16 +00003641** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00003642*/
mistachkin636bf9f2014-07-19 20:15:16 +00003643typedef struct ImportCtx ImportCtx;
3644struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00003645 const char *zFile; /* Name of the input file */
3646 FILE *in; /* Read the CSV text from this input stream */
3647 char *z; /* Accumulated text for a field */
3648 int n; /* Number of bytes in z */
3649 int nAlloc; /* Space allocated for z[] */
3650 int nLine; /* Current line number */
3651 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00003652 int cColSep; /* The column separator character. (Usually ",") */
3653 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00003654};
3655
3656/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00003657static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00003658 if( p->n+1>=p->nAlloc ){
3659 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00003660 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00003661 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003662 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00003663 exit(1);
3664 }
3665 }
3666 p->z[p->n++] = (char)c;
3667}
3668
3669/* Read a single field of CSV text. Compatible with rfc4180 and extended
3670** with the option of having a separator other than ",".
3671**
3672** + Input comes from p->in.
3673** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003674** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003675** + Use p->cSep as the column separator. The default is ",".
3676** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00003677** + Keep track of the line number in p->nLine.
3678** + Store the character that terminates the field in p->cTerm. Store
3679** EOF on end-of-file.
3680** + Report syntax errors on stderr
3681*/
mistachkin44723ce2015-03-21 02:22:37 +00003682static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003683 int c;
3684 int cSep = p->cColSep;
3685 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00003686 p->n = 0;
3687 c = fgetc(p->in);
3688 if( c==EOF || seenInterrupt ){
3689 p->cTerm = EOF;
3690 return 0;
3691 }
3692 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00003693 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00003694 int startLine = p->nLine;
3695 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00003696 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00003697 while( 1 ){
3698 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00003699 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00003700 if( c==cQuote ){
3701 if( pc==cQuote ){
3702 pc = 0;
3703 continue;
3704 }
3705 }
3706 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00003707 || (c==rSep && pc==cQuote)
3708 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00003709 || (c==EOF && pc==cQuote)
3710 ){
3711 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00003712 p->cTerm = c;
3713 break;
3714 }
3715 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00003716 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00003717 p->zFile, p->nLine, cQuote);
3718 }
3719 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00003720 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00003721 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00003722 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00003723 break;
3724 }
mistachkin636bf9f2014-07-19 20:15:16 +00003725 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00003726 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00003727 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00003728 }
drhdb95f682013-06-26 22:46:00 +00003729 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00003730 while( c!=EOF && c!=cSep && c!=rSep ){
3731 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00003732 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00003733 }
mistachkin636bf9f2014-07-19 20:15:16 +00003734 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00003735 p->nLine++;
drh3852b682014-02-26 13:53:34 +00003736 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00003737 }
drhdb95f682013-06-26 22:46:00 +00003738 p->cTerm = c;
3739 }
drh8dd675e2013-07-12 21:09:24 +00003740 if( p->z ) p->z[p->n] = 0;
drhdb95f682013-06-26 22:46:00 +00003741 return p->z;
3742}
3743
mistachkin636bf9f2014-07-19 20:15:16 +00003744/* Read a single field of ASCII delimited text.
3745**
3746** + Input comes from p->in.
3747** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00003748** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00003749** + Use p->cSep as the column separator. The default is "\x1F".
3750** + Use p->rSep as the row separator. The default is "\x1E".
3751** + Keep track of the row number in p->nLine.
3752** + Store the character that terminates the field in p->cTerm. Store
3753** EOF on end-of-file.
3754** + Report syntax errors on stderr
3755*/
mistachkin44723ce2015-03-21 02:22:37 +00003756static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00003757 int c;
3758 int cSep = p->cColSep;
3759 int rSep = p->cRowSep;
3760 p->n = 0;
3761 c = fgetc(p->in);
3762 if( c==EOF || seenInterrupt ){
3763 p->cTerm = EOF;
3764 return 0;
3765 }
3766 while( c!=EOF && c!=cSep && c!=rSep ){
3767 import_append_char(p, c);
3768 c = fgetc(p->in);
3769 }
3770 if( c==rSep ){
3771 p->nLine++;
3772 }
3773 p->cTerm = c;
3774 if( p->z ) p->z[p->n] = 0;
3775 return p->z;
3776}
3777
drhdb95f682013-06-26 22:46:00 +00003778/*
drh4bbcf102014-02-06 02:46:08 +00003779** Try to transfer data for table zTable. If an error is seen while
3780** moving forward, try to go backwards. The backwards movement won't
3781** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00003782*/
mistachkine31ae902014-02-06 01:15:29 +00003783static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00003784 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003785 sqlite3 *newDb,
3786 const char *zTable
3787){
mistachkin1fe36bb2016-04-04 02:16:44 +00003788 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00003789 sqlite3_stmt *pInsert = 0;
3790 char *zQuery = 0;
3791 char *zInsert = 0;
3792 int rc;
3793 int i, j, n;
3794 int nTable = (int)strlen(zTable);
3795 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00003796 int cnt = 0;
3797 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00003798
3799 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
3800 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3801 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003802 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003803 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3804 zQuery);
3805 goto end_data_xfer;
3806 }
3807 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00003808 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00003809 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003810 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00003811 goto end_data_xfer;
3812 }
3813 sqlite3_snprintf(200+nTable,zInsert,
3814 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
3815 i = (int)strlen(zInsert);
3816 for(j=1; j<n; j++){
3817 memcpy(zInsert+i, ",?", 2);
3818 i += 2;
3819 }
3820 memcpy(zInsert+i, ");", 3);
3821 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
3822 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003823 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003824 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
3825 zQuery);
3826 goto end_data_xfer;
3827 }
3828 for(k=0; k<2; k++){
3829 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3830 for(i=0; i<n; i++){
3831 switch( sqlite3_column_type(pQuery, i) ){
3832 case SQLITE_NULL: {
3833 sqlite3_bind_null(pInsert, i+1);
3834 break;
3835 }
3836 case SQLITE_INTEGER: {
3837 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
3838 break;
3839 }
3840 case SQLITE_FLOAT: {
3841 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
3842 break;
3843 }
3844 case SQLITE_TEXT: {
3845 sqlite3_bind_text(pInsert, i+1,
3846 (const char*)sqlite3_column_text(pQuery,i),
3847 -1, SQLITE_STATIC);
3848 break;
3849 }
3850 case SQLITE_BLOB: {
3851 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
3852 sqlite3_column_bytes(pQuery,i),
3853 SQLITE_STATIC);
3854 break;
3855 }
3856 }
3857 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00003858 rc = sqlite3_step(pInsert);
3859 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00003860 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00003861 sqlite3_errmsg(newDb));
3862 }
drh3350ce92014-02-06 00:49:12 +00003863 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00003864 cnt++;
3865 if( (cnt%spinRate)==0 ){
3866 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
3867 fflush(stdout);
3868 }
drh3350ce92014-02-06 00:49:12 +00003869 } /* End while */
3870 if( rc==SQLITE_DONE ) break;
3871 sqlite3_finalize(pQuery);
3872 sqlite3_free(zQuery);
3873 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
3874 zTable);
3875 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3876 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003877 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00003878 break;
drh3350ce92014-02-06 00:49:12 +00003879 }
3880 } /* End for(k=0...) */
3881
3882end_data_xfer:
3883 sqlite3_finalize(pQuery);
3884 sqlite3_finalize(pInsert);
3885 sqlite3_free(zQuery);
3886 sqlite3_free(zInsert);
3887}
3888
3889
3890/*
3891** Try to transfer all rows of the schema that match zWhere. For
3892** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00003893** If an error is encountered while moving forward through the
3894** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00003895*/
mistachkine31ae902014-02-06 01:15:29 +00003896static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00003897 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00003898 sqlite3 *newDb,
3899 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00003900 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00003901){
3902 sqlite3_stmt *pQuery = 0;
3903 char *zQuery = 0;
3904 int rc;
3905 const unsigned char *zName;
3906 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00003907 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00003908
3909 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3910 " WHERE %s", zWhere);
3911 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3912 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003913 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003914 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3915 zQuery);
3916 goto end_schema_xfer;
3917 }
3918 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3919 zName = sqlite3_column_text(pQuery, 0);
3920 zSql = sqlite3_column_text(pQuery, 1);
3921 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00003922 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3923 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00003924 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00003925 sqlite3_free(zErrMsg);
3926 zErrMsg = 0;
3927 }
drh3350ce92014-02-06 00:49:12 +00003928 if( xForEach ){
3929 xForEach(p, newDb, (const char*)zName);
3930 }
3931 printf("done\n");
3932 }
3933 if( rc!=SQLITE_DONE ){
3934 sqlite3_finalize(pQuery);
3935 sqlite3_free(zQuery);
3936 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
3937 " WHERE %s ORDER BY rowid DESC", zWhere);
3938 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
3939 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003940 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00003941 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
3942 zQuery);
3943 goto end_schema_xfer;
3944 }
3945 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
3946 zName = sqlite3_column_text(pQuery, 0);
3947 zSql = sqlite3_column_text(pQuery, 1);
3948 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00003949 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
3950 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00003951 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00003952 sqlite3_free(zErrMsg);
3953 zErrMsg = 0;
3954 }
drh3350ce92014-02-06 00:49:12 +00003955 if( xForEach ){
3956 xForEach(p, newDb, (const char*)zName);
3957 }
3958 printf("done\n");
3959 }
3960 }
3961end_schema_xfer:
3962 sqlite3_finalize(pQuery);
3963 sqlite3_free(zQuery);
3964}
3965
3966/*
3967** Open a new database file named "zNewDb". Try to recover as much information
3968** as possible out of the main database (which might be corrupt) and write it
3969** into zNewDb.
3970*/
drhdcd87a92014-08-18 13:45:42 +00003971static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00003972 int rc;
3973 sqlite3 *newDb = 0;
3974 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003975 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00003976 return;
3977 }
3978 rc = sqlite3_open(zNewDb, &newDb);
3979 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00003980 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00003981 sqlite3_errmsg(newDb));
3982 }else{
drh54d0d2d2014-04-03 00:32:13 +00003983 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00003984 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00003985 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
3986 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00003987 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00003988 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00003989 }
3990 sqlite3_close(newDb);
3991}
3992
3993/*
drhc2ce0be2014-05-29 12:36:14 +00003994** Change the output file back to stdout
3995*/
drhdcd87a92014-08-18 13:45:42 +00003996static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00003997 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00003998#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00003999 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004000#endif
drhc2ce0be2014-05-29 12:36:14 +00004001 }else{
4002 output_file_close(p->out);
4003 }
4004 p->outfile[0] = 0;
4005 p->out = stdout;
4006}
4007
4008/*
drhf7502f02015-02-06 14:19:44 +00004009** Run an SQL command and return the single integer result.
4010*/
4011static int db_int(ShellState *p, const char *zSql){
4012 sqlite3_stmt *pStmt;
4013 int res = 0;
4014 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4015 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4016 res = sqlite3_column_int(pStmt,0);
4017 }
4018 sqlite3_finalize(pStmt);
4019 return res;
4020}
4021
4022/*
4023** Convert a 2-byte or 4-byte big-endian integer into a native integer
4024*/
drha0620ac2016-07-13 13:05:13 +00004025static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004026 return (a[0]<<8) + a[1];
4027}
drha0620ac2016-07-13 13:05:13 +00004028static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004029 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4030}
4031
4032/*
4033** Implementation of the ".info" command.
4034**
4035** Return 1 on error, 2 to exit, and 0 otherwise.
4036*/
drh0e55db12015-02-06 14:51:13 +00004037static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004038 static const struct { const char *zName; int ofst; } aField[] = {
4039 { "file change counter:", 24 },
4040 { "database page count:", 28 },
4041 { "freelist page count:", 36 },
4042 { "schema cookie:", 40 },
4043 { "schema format:", 44 },
4044 { "default cache size:", 48 },
4045 { "autovacuum top root:", 52 },
4046 { "incremental vacuum:", 64 },
4047 { "text encoding:", 56 },
4048 { "user version:", 60 },
4049 { "application id:", 68 },
4050 { "software version:", 96 },
4051 };
drh0e55db12015-02-06 14:51:13 +00004052 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4053 { "number of tables:",
4054 "SELECT count(*) FROM %s WHERE type='table'" },
4055 { "number of indexes:",
4056 "SELECT count(*) FROM %s WHERE type='index'" },
4057 { "number of triggers:",
4058 "SELECT count(*) FROM %s WHERE type='trigger'" },
4059 { "number of views:",
4060 "SELECT count(*) FROM %s WHERE type='view'" },
4061 { "schema size:",
4062 "SELECT total(length(sql)) FROM %s" },
4063 };
mistachkinbfe8bd52015-11-17 19:17:14 +00004064 sqlite3_file *pFile = 0;
drh0e55db12015-02-06 14:51:13 +00004065 int i;
4066 char *zSchemaTab;
4067 char *zDb = nArg>=2 ? azArg[1] : "main";
4068 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004069 open_db(p, 0);
4070 if( p->db==0 ) return 1;
drh0e55db12015-02-06 14:51:13 +00004071 sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
drhf7502f02015-02-06 14:19:44 +00004072 if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
4073 return 1;
4074 }
4075 i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
4076 if( i!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004077 raw_printf(stderr, "unable to read database header\n");
drhf7502f02015-02-06 14:19:44 +00004078 return 1;
4079 }
4080 i = get2byteInt(aHdr+16);
4081 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004082 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4083 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4084 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4085 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004086 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00004087 int ofst = aField[i].ofst;
4088 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00004089 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00004090 switch( ofst ){
4091 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00004092 if( val==1 ) raw_printf(p->out, " (utf8)");
4093 if( val==2 ) raw_printf(p->out, " (utf16le)");
4094 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00004095 }
4096 }
mistachkinaae280e2015-12-31 19:06:24 +00004097 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00004098 }
drh0e55db12015-02-06 14:51:13 +00004099 if( zDb==0 ){
4100 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
4101 }else if( strcmp(zDb,"temp")==0 ){
4102 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
4103 }else{
4104 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
4105 }
drhf5ed7ad2015-06-15 14:43:25 +00004106 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00004107 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
4108 int val = db_int(p, zSql);
4109 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00004110 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00004111 }
4112 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00004113 return 0;
4114}
4115
dand95bb392015-09-30 11:19:05 +00004116/*
4117** Print the current sqlite3_errmsg() value to stderr and return 1.
4118*/
4119static int shellDatabaseError(sqlite3 *db){
4120 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00004121 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00004122 return 1;
4123}
4124
4125/*
4126** Print an out-of-memory message to stderr and return 1.
4127*/
4128static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00004129 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00004130 return 1;
4131}
drhf7502f02015-02-06 14:19:44 +00004132
drh2db82112016-09-15 21:35:24 +00004133/*
4134** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
4135** if they match and FALSE (0) if they do not match.
4136**
4137** Globbing rules:
4138**
4139** '*' Matches any sequence of zero or more characters.
4140**
4141** '?' Matches exactly one character.
4142**
4143** [...] Matches one character from the enclosed list of
4144** characters.
4145**
4146** [^...] Matches one character not in the enclosed list.
4147**
4148** '#' Matches any sequence of one or more digits with an
4149** optional + or - sign in front
4150**
4151** ' ' Any span of whitespace matches any other span of
4152** whitespace.
4153**
4154** Extra whitespace at the end of z[] is ignored.
4155*/
4156static int testcase_glob(const char *zGlob, const char *z){
4157 int c, c2;
4158 int invert;
4159 int seen;
4160
4161 while( (c = (*(zGlob++)))!=0 ){
4162 if( IsSpace(c) ){
4163 if( !IsSpace(*z) ) return 0;
4164 while( IsSpace(*zGlob) ) zGlob++;
4165 while( IsSpace(*z) ) z++;
4166 }else if( c=='*' ){
4167 while( (c=(*(zGlob++))) == '*' || c=='?' ){
4168 if( c=='?' && (*(z++))==0 ) return 0;
4169 }
4170 if( c==0 ){
4171 return 1;
4172 }else if( c=='[' ){
4173 while( *z && testcase_glob(zGlob-1,z)==0 ){
4174 z++;
4175 }
4176 return (*z)!=0;
4177 }
4178 while( (c2 = (*(z++)))!=0 ){
4179 while( c2!=c ){
4180 c2 = *(z++);
4181 if( c2==0 ) return 0;
4182 }
4183 if( testcase_glob(zGlob,z) ) return 1;
4184 }
4185 return 0;
4186 }else if( c=='?' ){
4187 if( (*(z++))==0 ) return 0;
4188 }else if( c=='[' ){
4189 int prior_c = 0;
4190 seen = 0;
4191 invert = 0;
4192 c = *(z++);
4193 if( c==0 ) return 0;
4194 c2 = *(zGlob++);
4195 if( c2=='^' ){
4196 invert = 1;
4197 c2 = *(zGlob++);
4198 }
4199 if( c2==']' ){
4200 if( c==']' ) seen = 1;
4201 c2 = *(zGlob++);
4202 }
4203 while( c2 && c2!=']' ){
4204 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
4205 c2 = *(zGlob++);
4206 if( c>=prior_c && c<=c2 ) seen = 1;
4207 prior_c = 0;
4208 }else{
4209 if( c==c2 ){
4210 seen = 1;
4211 }
4212 prior_c = c2;
4213 }
4214 c2 = *(zGlob++);
4215 }
4216 if( c2==0 || (seen ^ invert)==0 ) return 0;
4217 }else if( c=='#' ){
4218 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
4219 if( !IsDigit(z[0]) ) return 0;
4220 z++;
4221 while( IsDigit(z[0]) ){ z++; }
4222 }else{
4223 if( c!=(*(z++)) ) return 0;
4224 }
4225 }
4226 while( IsSpace(*z) ){ z++; }
4227 return *z==0;
4228}
drh2db82112016-09-15 21:35:24 +00004229
4230
drhf7502f02015-02-06 14:19:44 +00004231/*
drh4926fec2016-04-13 15:33:42 +00004232** Compare the string as a command-line option with either one or two
4233** initial "-" characters.
4234*/
4235static int optionMatch(const char *zStr, const char *zOpt){
4236 if( zStr[0]!='-' ) return 0;
4237 zStr++;
4238 if( zStr[0]=='-' ) zStr++;
4239 return strcmp(zStr, zOpt)==0;
4240}
4241
4242/*
drhcd0509e2016-09-16 00:26:08 +00004243** Delete a file.
4244*/
4245int shellDeleteFile(const char *zFilename){
4246 int rc;
4247#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00004248 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00004249 rc = _wunlink(z);
4250 sqlite3_free(z);
4251#else
4252 rc = unlink(zFilename);
4253#endif
4254 return rc;
4255}
4256
dan35ac58e2016-12-14 19:28:27 +00004257
dan35ac58e2016-12-14 19:28:27 +00004258/*
dandd9e0be2016-12-16 16:44:27 +00004259** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00004260** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00004261** called with four arguments - the parent table name, the parent column name,
4262** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00004263**
4264** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
4265**
4266** If either of the named tables or columns do not exist, this function
4267** returns an empty string. An empty string is also returned if both tables
4268** and columns exist but have the same default collation sequence. Or,
4269** if both exist but the default collation sequences are different, this
4270** function returns the string " COLLATE <parent-collation>", where
4271** <parent-collation> is the default collation sequence of the parent column.
4272*/
4273static void shellFkeyCollateClause(
4274 sqlite3_context *pCtx,
4275 int nVal,
4276 sqlite3_value **apVal
4277){
4278 sqlite3 *db = sqlite3_context_db_handle(pCtx);
4279 const char *zParent;
4280 const char *zParentCol;
4281 const char *zParentSeq;
4282 const char *zChild;
4283 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00004284 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00004285 int rc;
4286
4287 assert( nVal==4 );
4288 zParent = (const char*)sqlite3_value_text(apVal[0]);
4289 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
4290 zChild = (const char*)sqlite3_value_text(apVal[2]);
4291 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
4292
4293 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
4294 rc = sqlite3_table_column_metadata(
4295 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
4296 );
4297 if( rc==SQLITE_OK ){
4298 rc = sqlite3_table_column_metadata(
4299 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
4300 );
4301 }
4302
4303 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
4304 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
4305 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
4306 sqlite3_free(z);
4307 }
4308}
4309
4310
4311/*
dan3c7ebeb2016-12-16 17:28:56 +00004312** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00004313*/
dan3c7ebeb2016-12-16 17:28:56 +00004314static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00004315 ShellState *pState, /* Current shell tool state */
4316 char **azArg, /* Array of arguments passed to dot command */
4317 int nArg /* Number of entries in azArg[] */
4318){
dandd9e0be2016-12-16 16:44:27 +00004319 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
4320 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00004321 int bVerbose = 0; /* If -verbose is present */
4322 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00004323 int i; /* To iterate through azArg[] */
4324 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
4325 int rc; /* Return code */
4326 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00004327
dandd9e0be2016-12-16 16:44:27 +00004328 /*
4329 ** This SELECT statement returns one row for each foreign key constraint
4330 ** in the schema of the main database. The column values are:
4331 **
4332 ** 0. The text of an SQL statement similar to:
4333 **
4334 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
4335 **
4336 ** This is the same SELECT that the foreign keys implementation needs
4337 ** to run internally on child tables. If there is an index that can
4338 ** be used to optimize this query, then it can also be used by the FK
4339 ** implementation to optimize DELETE or UPDATE statements on the parent
4340 ** table.
4341 **
4342 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
4343 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
4344 ** contains an index that can be used to optimize the query.
4345 **
4346 ** 2. Human readable text that describes the child table and columns. e.g.
4347 **
4348 ** "child_table(child_key1, child_key2)"
4349 **
4350 ** 3. Human readable text that describes the parent table and columns. e.g.
4351 **
4352 ** "parent_table(parent_key1, parent_key2)"
4353 **
4354 ** 4. A full CREATE INDEX statement for an index that could be used to
4355 ** optimize DELETE or UPDATE statements on the parent table. e.g.
4356 **
4357 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
4358 **
4359 ** 5. The name of the parent table.
4360 **
4361 ** These six values are used by the C logic below to generate the report.
4362 */
dan35ac58e2016-12-14 19:28:27 +00004363 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00004364 "SELECT "
4365 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
4366 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00004367 " || fkey_collate_clause("
4368 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00004369 ", "
dandd9e0be2016-12-16 16:44:27 +00004370 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00004371 " || group_concat('*=?', ' AND ') || ')'"
4372 ", "
dandd9e0be2016-12-16 16:44:27 +00004373 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00004374 ", "
dan50da9382017-04-06 12:06:56 +00004375 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00004376 ", "
dandd9e0be2016-12-16 16:44:27 +00004377 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
4378 " || ' ON ' || quote(s.name) || '('"
4379 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00004380 " fkey_collate_clause("
4381 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00004382 " || ');'"
danf9647b62016-12-15 06:01:40 +00004383 ", "
dandd9e0be2016-12-16 16:44:27 +00004384 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00004385 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00004386 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00004387 "GROUP BY s.name, f.id "
4388 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00004389 ;
dan54e2efc2017-04-06 14:56:26 +00004390 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00004391
dan3c7ebeb2016-12-16 17:28:56 +00004392 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00004393 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00004394 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
4395 bVerbose = 1;
4396 }
4397 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
4398 bGroupByParent = 1;
4399 zIndent = " ";
4400 }
4401 else{
dan3c7ebeb2016-12-16 17:28:56 +00004402 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
4403 azArg[0], azArg[1]
4404 );
danf9647b62016-12-15 06:01:40 +00004405 return SQLITE_ERROR;
4406 }
dan35ac58e2016-12-14 19:28:27 +00004407 }
dan35ac58e2016-12-14 19:28:27 +00004408
4409 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00004410 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
4411 0, shellFkeyCollateClause, 0, 0
4412 );
dan35ac58e2016-12-14 19:28:27 +00004413
4414
4415 if( rc==SQLITE_OK ){
4416 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
4417 }
danf9647b62016-12-15 06:01:40 +00004418 if( rc==SQLITE_OK ){
4419 sqlite3_bind_int(pSql, 1, bGroupByParent);
4420 }
dan35ac58e2016-12-14 19:28:27 +00004421
4422 if( rc==SQLITE_OK ){
4423 int rc2;
danf9647b62016-12-15 06:01:40 +00004424 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00004425 while( SQLITE_ROW==sqlite3_step(pSql) ){
4426 int res = -1;
4427 sqlite3_stmt *pExplain = 0;
4428 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
4429 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
4430 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
4431 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
4432 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00004433 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00004434
4435 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
4436 if( rc!=SQLITE_OK ) break;
4437 if( SQLITE_ROW==sqlite3_step(pExplain) ){
4438 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00004439 res = (
4440 0==sqlite3_strglob(zGlob, zPlan)
4441 || 0==sqlite3_strglob(zGlobIPK, zPlan)
4442 );
dan35ac58e2016-12-14 19:28:27 +00004443 }
4444 rc = sqlite3_finalize(pExplain);
4445 if( rc!=SQLITE_OK ) break;
4446
4447 if( res<0 ){
4448 raw_printf(stderr, "Error: internal error");
4449 break;
danf9647b62016-12-15 06:01:40 +00004450 }else{
4451 if( bGroupByParent
4452 && (bVerbose || res==0)
4453 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
4454 ){
4455 raw_printf(out, "-- Parent table %s\n", zParent);
4456 sqlite3_free(zPrev);
4457 zPrev = sqlite3_mprintf("%s", zParent);
4458 }
4459
4460 if( res==0 ){
4461 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
4462 }else if( bVerbose ){
4463 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
4464 zIndent, zFrom, zTarget
4465 );
4466 }
dan35ac58e2016-12-14 19:28:27 +00004467 }
4468 }
danf9647b62016-12-15 06:01:40 +00004469 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00004470
4471 if( rc!=SQLITE_OK ){
4472 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4473 }
4474
4475 rc2 = sqlite3_finalize(pSql);
4476 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
4477 rc = rc2;
4478 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4479 }
4480 }else{
4481 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
4482 }
4483
4484 return rc;
4485}
dan3c7ebeb2016-12-16 17:28:56 +00004486
dan35ac58e2016-12-14 19:28:27 +00004487/*
dan3c7ebeb2016-12-16 17:28:56 +00004488** Implementation of ".lint" dot command.
4489*/
4490static int lintDotCommand(
4491 ShellState *pState, /* Current shell tool state */
4492 char **azArg, /* Array of arguments passed to dot command */
4493 int nArg /* Number of entries in azArg[] */
4494){
4495 int n;
drh96ada592016-12-29 19:48:46 +00004496 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00004497 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
4498 return lintFkeyIndexes(pState, azArg, nArg);
4499
4500 usage:
4501 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
4502 raw_printf(stderr, "Where sub-commands are:\n");
4503 raw_printf(stderr, " fkey-indexes\n");
4504 return SQLITE_ERROR;
4505}
4506
dan35ac58e2016-12-14 19:28:27 +00004507
drhcd0509e2016-09-16 00:26:08 +00004508/*
drh75897232000-05-29 14:26:00 +00004509** If an input line begins with "." then invoke this routine to
4510** process that line.
drh67505e72002-04-19 12:34:06 +00004511**
drh47ad6842006-11-08 12:25:42 +00004512** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00004513*/
drhdcd87a92014-08-18 13:45:42 +00004514static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00004515 int h = 1;
drh75897232000-05-29 14:26:00 +00004516 int nArg = 0;
4517 int n, c;
drh67505e72002-04-19 12:34:06 +00004518 int rc = 0;
drh75897232000-05-29 14:26:00 +00004519 char *azArg[50];
4520
4521 /* Parse the input line into tokens.
4522 */
mistachkin8e189222015-04-19 21:43:16 +00004523 while( zLine[h] && nArg<ArraySize(azArg) ){
4524 while( IsSpace(zLine[h]) ){ h++; }
4525 if( zLine[h]==0 ) break;
4526 if( zLine[h]=='\'' || zLine[h]=='"' ){
4527 int delim = zLine[h++];
4528 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00004529 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00004530 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00004531 h++;
drh4c56b992013-06-27 13:26:55 +00004532 }
mistachkin8e189222015-04-19 21:43:16 +00004533 if( zLine[h]==delim ){
4534 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00004535 }
drhfeac5f82004-08-01 00:10:45 +00004536 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004537 }else{
mistachkin8e189222015-04-19 21:43:16 +00004538 azArg[nArg++] = &zLine[h];
4539 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
4540 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00004541 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00004542 }
4543 }
4544
4545 /* Process the input line.
4546 */
shane9bd1b442009-10-23 01:27:39 +00004547 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00004548 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00004549 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00004550
drha0daa752016-09-16 11:53:10 +00004551#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004552 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
4553 if( nArg!=2 ){
4554 raw_printf(stderr, "Usage: .auth ON|OFF\n");
4555 rc = 1;
4556 goto meta_command_exit;
4557 }
4558 open_db(p, 0);
4559 if( booleanValue(azArg[1]) ){
4560 sqlite3_set_authorizer(p->db, shellAuth, p);
4561 }else{
4562 sqlite3_set_authorizer(p->db, 0, 0);
4563 }
4564 }else
drha0daa752016-09-16 11:53:10 +00004565#endif
drhde613c62016-04-04 17:23:10 +00004566
drh5c7976f2014-02-10 19:59:27 +00004567 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
4568 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
4569 ){
drhbc46f022013-01-23 18:53:23 +00004570 const char *zDestFile = 0;
4571 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00004572 sqlite3 *pDest;
4573 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00004574 int j;
4575 for(j=1; j<nArg; j++){
4576 const char *z = azArg[j];
4577 if( z[0]=='-' ){
4578 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00004579 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00004580 {
mistachkinaae280e2015-12-31 19:06:24 +00004581 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00004582 return 1;
4583 }
4584 }else if( zDestFile==0 ){
4585 zDestFile = azArg[j];
4586 }else if( zDb==0 ){
4587 zDb = zDestFile;
4588 zDestFile = azArg[j];
4589 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004590 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00004591 return 1;
4592 }
drh9ff849f2009-02-04 20:55:57 +00004593 }
drhbc46f022013-01-23 18:53:23 +00004594 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004595 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00004596 return 1;
4597 }
4598 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00004599 rc = sqlite3_open(zDestFile, &pDest);
4600 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00004601 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00004602 sqlite3_close(pDest);
4603 return 1;
4604 }
drh05782482013-10-24 15:20:20 +00004605 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00004606 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
4607 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004608 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00004609 sqlite3_close(pDest);
4610 return 1;
4611 }
4612 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
4613 sqlite3_backup_finish(pBackup);
4614 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00004615 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00004616 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004617 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00004618 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00004619 }
4620 sqlite3_close(pDest);
4621 }else
4622
drhc2ce0be2014-05-29 12:36:14 +00004623 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
4624 if( nArg==2 ){
4625 bail_on_error = booleanValue(azArg[1]);
4626 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004627 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004628 rc = 1;
4629 }
drhc49f44e2006-10-26 18:15:42 +00004630 }else
4631
mistachkinf21979d2015-01-18 05:35:01 +00004632 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
4633 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00004634 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004635 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004636 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00004637 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00004638 }
mistachkinf21979d2015-01-18 05:35:01 +00004639 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004640 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00004641 rc = 1;
4642 }
4643 }else
4644
drhd8621b92012-04-17 09:09:33 +00004645 /* The undocumented ".breakpoint" command causes a call to the no-op
4646 ** routine named test_breakpoint().
4647 */
4648 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
4649 test_breakpoint();
4650 }else
4651
drhdf12f1c2015-12-07 21:46:19 +00004652 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
4653 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004654 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00004655 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004656 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00004657 rc = 1;
4658 }
4659 }else
4660
drh2db82112016-09-15 21:35:24 +00004661 /* Cancel output redirection, if it is currently set (by .testcase)
4662 ** Then read the content of the testcase-out.txt file and compare against
4663 ** azArg[1]. If there are differences, report an error and exit.
4664 */
4665 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
4666 char *zRes = 0;
4667 output_reset(p);
4668 if( nArg!=2 ){
4669 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00004670 rc = 2;
dan11da0022016-12-17 08:18:05 +00004671 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00004672 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
4673 rc = 2;
4674 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00004675 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00004676 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
4677 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00004678 rc = 2;
drh760c8162016-09-16 02:52:22 +00004679 }else{
mistachkin8145fc62016-09-16 20:39:21 +00004680 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00004681 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00004682 }
4683 sqlite3_free(zRes);
4684 }else
drh2db82112016-09-15 21:35:24 +00004685
drhc2ce0be2014-05-29 12:36:14 +00004686 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
4687 if( nArg==2 ){
4688 tryToClone(p, azArg[1]);
4689 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004690 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00004691 rc = 1;
4692 }
mistachkine31ae902014-02-06 01:15:29 +00004693 }else
4694
drhc2ce0be2014-05-29 12:36:14 +00004695 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004696 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00004697 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00004698 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00004699 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00004700 data.showHeader = 0;
4701 data.cMode = data.mode = MODE_List;
4702 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00004703 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00004704 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
4705 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00004706 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004707 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00004708 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00004709 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00004710 }
4711 }else
4712
drh0e55db12015-02-06 14:51:13 +00004713 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
4714 rc = shell_dbinfo_command(p, nArg, azArg);
4715 }else
4716
drhc2ce0be2014-05-29 12:36:14 +00004717 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00004718 const char *zLike = 0;
4719 int i;
drhe6e1d122017-03-09 13:50:49 +00004720 ShellClearFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00004721 for(i=1; i<nArg; i++){
4722 if( azArg[i][0]=='-' ){
4723 const char *z = azArg[i]+1;
4724 if( z[0]=='-' ) z++;
4725 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00004726#ifdef SQLITE_OMIT_VIRTUALTABLE
4727 raw_printf(stderr, "The --preserve-rowids option is not compatible"
4728 " with SQLITE_OMIT_VIRTUALTABLE\n");
4729 rc = 1;
4730 goto meta_command_exit;
4731#else
drhe6e1d122017-03-09 13:50:49 +00004732 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00004733#endif
drhe611f142017-03-08 11:44:00 +00004734 }else
4735 {
4736 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
4737 rc = 1;
4738 goto meta_command_exit;
4739 }
4740 }else if( zLike ){
4741 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? ?LIKE-PATTERN?\n");
4742 rc = 1;
4743 goto meta_command_exit;
4744 }else{
4745 zLike = azArg[i];
4746 }
4747 }
drh05782482013-10-24 15:20:20 +00004748 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00004749 /* When playing back a "dump", the content might appear in an order
4750 ** which causes immediate foreign key constraints to be violated.
4751 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00004752 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
4753 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00004754 p->writableSchema = 0;
drhe611f142017-03-08 11:44:00 +00004755 /* Set writable_schema=ON since doing so forces SQLite to initialize
4756 ** as much of the schema as it can even if the sqlite_master table is
4757 ** corrupt. */
drh56197952011-10-13 16:30:13 +00004758 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00004759 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00004760 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004761 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00004762 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004763 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00004764 );
mistachkin1fe36bb2016-04-04 02:16:44 +00004765 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00004766 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00004767 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00004768 );
drh2f464a02011-10-13 00:41:49 +00004769 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00004770 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00004771 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00004772 );
drh4c653a02000-06-07 01:27:47 +00004773 }else{
drhe611f142017-03-08 11:44:00 +00004774 char *zSql;
4775 zSql = sqlite3_mprintf(
4776 "SELECT name, type, sql FROM sqlite_master "
4777 "WHERE tbl_name LIKE %Q AND type=='table'"
4778 " AND sql NOT NULL", zLike);
4779 run_schema_dump_query(p,zSql);
4780 sqlite3_free(zSql);
4781 zSql = sqlite3_mprintf(
4782 "SELECT sql FROM sqlite_master "
4783 "WHERE sql NOT NULL"
4784 " AND type IN ('index','trigger','view')"
4785 " AND tbl_name LIKE %Q", zLike);
4786 run_table_dump_query(p, zSql, 0);
4787 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00004788 }
drh45e29d82006-11-20 16:21:10 +00004789 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00004790 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00004791 p->writableSchema = 0;
4792 }
drh56197952011-10-13 16:30:13 +00004793 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
4794 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00004795 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh4c653a02000-06-07 01:27:47 +00004796 }else
drh75897232000-05-29 14:26:00 +00004797
drhc2ce0be2014-05-29 12:36:14 +00004798 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
4799 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00004800 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00004801 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004802 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004803 rc = 1;
4804 }
drhdaffd0e2001-04-11 14:28:42 +00004805 }else
4806
drhc2ce0be2014-05-29 12:36:14 +00004807 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
4808 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00004809 if( strcmp(azArg[1],"full")==0 ){
4810 p->autoEQP = 2;
4811 }else{
4812 p->autoEQP = booleanValue(azArg[1]);
4813 }
drhc2ce0be2014-05-29 12:36:14 +00004814 }else{
drheacd29d2016-04-15 15:03:27 +00004815 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00004816 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00004817 }
drhefbf3b12014-02-28 20:47:24 +00004818 }else
4819
drhd3ac7d92013-01-25 18:33:43 +00004820 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00004821 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00004822 rc = 2;
drh75897232000-05-29 14:26:00 +00004823 }else
4824
drhc2ce0be2014-05-29 12:36:14 +00004825 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00004826 int val = 1;
4827 if( nArg>=2 ){
4828 if( strcmp(azArg[1],"auto")==0 ){
4829 val = 99;
4830 }else{
4831 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00004832 }
drh700c2522016-02-09 18:39:25 +00004833 }
4834 if( val==1 && p->mode!=MODE_Explain ){
4835 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00004836 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00004837 p->autoExplain = 0;
4838 }else if( val==0 ){
4839 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4840 p->autoExplain = 0;
4841 }else if( val==99 ){
4842 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
4843 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00004844 }
drh75897232000-05-29 14:26:00 +00004845 }else
4846
drhc1971542014-06-23 23:28:13 +00004847 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00004848 ShellState data;
drhc1971542014-06-23 23:28:13 +00004849 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00004850 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00004851 memcpy(&data, p, sizeof(data));
4852 data.showHeader = 0;
4853 data.cMode = data.mode = MODE_Semi;
4854 if( nArg==2 && optionMatch(azArg[1], "indent") ){
4855 data.cMode = data.mode = MODE_Pretty;
4856 nArg = 1;
4857 }
drhc1971542014-06-23 23:28:13 +00004858 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00004859 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00004860 rc = 1;
4861 goto meta_command_exit;
4862 }
4863 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00004864 rc = sqlite3_exec(p->db,
4865 "SELECT sql FROM"
4866 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
4867 " FROM sqlite_master UNION ALL"
4868 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00004869 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00004870 "ORDER BY rowid",
4871 callback, &data, &zErrMsg
4872 );
drh56f674c2014-07-18 14:43:29 +00004873 if( rc==SQLITE_OK ){
4874 sqlite3_stmt *pStmt;
4875 rc = sqlite3_prepare_v2(p->db,
4876 "SELECT rowid FROM sqlite_master"
4877 " WHERE name GLOB 'sqlite_stat[134]'",
4878 -1, &pStmt, 0);
4879 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
4880 sqlite3_finalize(pStmt);
4881 }
4882 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004883 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00004884 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004885 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00004886 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
4887 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00004888 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00004889 data.zDestTable = "sqlite_stat1";
4890 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
4891 shell_callback, &data,&zErrMsg);
4892 data.zDestTable = "sqlite_stat3";
4893 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
4894 shell_callback, &data,&zErrMsg);
4895 data.zDestTable = "sqlite_stat4";
4896 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
4897 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00004898 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00004899 }
drhc1971542014-06-23 23:28:13 +00004900 }else
4901
drhc2ce0be2014-05-29 12:36:14 +00004902 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
4903 if( nArg==2 ){
4904 p->showHeader = booleanValue(azArg[1]);
4905 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004906 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00004907 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00004908 }
drh75897232000-05-29 14:26:00 +00004909 }else
4910
drhc2ce0be2014-05-29 12:36:14 +00004911 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004912 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00004913 }else
4914
4915 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00004916 char *zTable; /* Insert data into this table */
4917 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00004918 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00004919 int nCol; /* Number of columns in the table */
4920 int nByte; /* Number of bytes in an SQL string */
4921 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00004922 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00004923 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00004924 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00004925 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00004926 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
4927 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00004928
drhc2ce0be2014-05-29 12:36:14 +00004929 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00004930 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00004931 goto meta_command_exit;
4932 }
drh01f37542014-05-31 15:43:33 +00004933 zFile = azArg[1];
4934 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00004935 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00004936 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00004937 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00004938 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00004939 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004940 raw_printf(stderr,
4941 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00004942 return 1;
drhfeac5f82004-08-01 00:10:45 +00004943 }
drhdb95f682013-06-26 22:46:00 +00004944 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00004945 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00004946 " for import\n");
4947 return 1;
4948 }
mistachkin636bf9f2014-07-19 20:15:16 +00004949 nSep = strlen30(p->rowSeparator);
4950 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004951 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00004952 return 1;
4953 }
mistachkine0d68852014-12-11 03:12:33 +00004954 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
4955 /* When importing CSV (only), if the row separator is set to the
4956 ** default output row separator, change it to the default input
4957 ** row separator. This avoids having to maintain different input
4958 ** and output row separators. */
4959 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
4960 nSep = strlen30(p->rowSeparator);
4961 }
mistachkin636bf9f2014-07-19 20:15:16 +00004962 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00004963 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00004964 " for import\n");
4965 return 1;
4966 }
4967 sCtx.zFile = zFile;
4968 sCtx.nLine = 1;
4969 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004970#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00004971 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00004972 return 1;
4973#else
mistachkin636bf9f2014-07-19 20:15:16 +00004974 sCtx.in = popen(sCtx.zFile+1, "r");
4975 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00004976 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00004977#endif
drh5bde8162013-06-27 14:07:53 +00004978 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00004979 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00004980 xCloser = fclose;
4981 }
mistachkin636bf9f2014-07-19 20:15:16 +00004982 if( p->mode==MODE_Ascii ){
4983 xRead = ascii_read_one_field;
4984 }else{
4985 xRead = csv_read_one_field;
4986 }
4987 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004988 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00004989 return 1;
4990 }
mistachkin636bf9f2014-07-19 20:15:16 +00004991 sCtx.cColSep = p->colSeparator[0];
4992 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00004993 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00004994 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004995 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00004996 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00004997 return 1;
4998 }
drh4f21c4a2008-12-10 22:15:00 +00004999 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005000 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005001 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005002 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005003 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5004 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005005 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005006 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005007 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005008 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005009 }
drh5bde8162013-06-27 14:07:53 +00005010 if( cSep=='(' ){
5011 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005012 sqlite3_free(sCtx.z);
5013 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005014 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005015 return 1;
5016 }
drhdb95f682013-06-26 22:46:00 +00005017 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5018 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5019 sqlite3_free(zCreate);
5020 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005021 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005022 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005023 sqlite3_free(sCtx.z);
5024 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005025 return 1;
5026 }
drhc7181902014-02-27 15:04:13 +00005027 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005028 }
drhfeac5f82004-08-01 00:10:45 +00005029 sqlite3_free(zSql);
5030 if( rc ){
shane916f9612009-10-23 00:37:15 +00005031 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005032 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005033 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005034 return 1;
drhfeac5f82004-08-01 00:10:45 +00005035 }
shane916f9612009-10-23 00:37:15 +00005036 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005037 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005038 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005039 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005040 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005041 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005042 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005043 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005044 return 1;
5045 }
drhdb95f682013-06-26 22:46:00 +00005046 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005047 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005048 for(i=1; i<nCol; i++){
5049 zSql[j++] = ',';
5050 zSql[j++] = '?';
5051 }
5052 zSql[j++] = ')';
5053 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005054 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005055 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005056 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005057 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005058 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00005059 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00005060 return 1;
drhfeac5f82004-08-01 00:10:45 +00005061 }
mistachkin8e189222015-04-19 21:43:16 +00005062 needCommit = sqlite3_get_autocommit(p->db);
5063 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00005064 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005065 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00005066 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00005067 char *z = xRead(&sCtx);
5068 /*
5069 ** Did we reach end-of-file before finding any columns?
5070 ** If so, stop instead of NULL filling the remaining columns.
5071 */
drhdb95f682013-06-26 22:46:00 +00005072 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00005073 /*
5074 ** Did we reach end-of-file OR end-of-line before finding any
5075 ** columns in ASCII mode? If so, stop instead of NULL filling
5076 ** the remaining columns.
5077 */
5078 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00005079 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00005080 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00005081 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005082 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005083 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00005084 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00005085 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00005086 }
drhfeac5f82004-08-01 00:10:45 +00005087 }
mistachkin636bf9f2014-07-19 20:15:16 +00005088 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00005089 do{
mistachkin636bf9f2014-07-19 20:15:16 +00005090 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00005091 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00005092 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00005093 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00005094 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00005095 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00005096 }
drhdb95f682013-06-26 22:46:00 +00005097 if( i>=nCol ){
5098 sqlite3_step(pStmt);
5099 rc = sqlite3_reset(pStmt);
5100 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005101 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
5102 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00005103 }
5104 }
mistachkin636bf9f2014-07-19 20:15:16 +00005105 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00005106
mistachkin636bf9f2014-07-19 20:15:16 +00005107 xCloser(sCtx.in);
5108 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00005109 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00005110 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00005111 }else
5112
drhd12602a2016-12-07 15:49:02 +00005113#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00005114 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
5115 char *zSql;
5116 char *zCollist = 0;
5117 sqlite3_stmt *pStmt;
5118 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00005119 int i;
drh16eb5942016-11-03 13:01:38 +00005120 if( nArg!=3 ){
5121 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
5122 rc = 1;
5123 goto meta_command_exit;
5124 }
5125 open_db(p, 0);
5126 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
5127 " WHERE name='%q' AND type='index'", azArg[1]);
5128 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5129 sqlite3_free(zSql);
5130 if( sqlite3_step(pStmt)==SQLITE_ROW ){
5131 tnum = sqlite3_column_int(pStmt, 0);
5132 }
5133 sqlite3_finalize(pStmt);
5134 if( tnum==0 ){
5135 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
5136 rc = 1;
5137 goto meta_command_exit;
5138 }
5139 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
5140 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
5141 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00005142 i = 0;
drh16eb5942016-11-03 13:01:38 +00005143 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00005144 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00005145 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00005146 i++;
5147 if( zCol==0 ){
5148 if( sqlite3_column_int(pStmt,1)==-1 ){
5149 zCol = "_ROWID_";
5150 }else{
5151 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
5152 zCol = zLabel;
5153 }
5154 }
drh16eb5942016-11-03 13:01:38 +00005155 if( zCollist==0 ){
5156 zCollist = sqlite3_mprintf("\"%w\"", zCol);
5157 }else{
5158 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
5159 }
5160 }
5161 sqlite3_finalize(pStmt);
5162 zSql = sqlite3_mprintf(
5163 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
5164 azArg[2], zCollist, zCollist);
5165 sqlite3_free(zCollist);
5166 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
5167 if( rc==SQLITE_OK ){
5168 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
5169 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
5170 if( rc ){
5171 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
5172 }else{
5173 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00005174 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00005175 "WARNING: writing to an imposter table will corrupt the index!\n"
5176 );
5177 }
5178 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00005179 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00005180 rc = 1;
5181 }
5182 sqlite3_free(zSql);
5183 }else
5184#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
5185
drhae5e4452007-05-03 17:18:36 +00005186#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00005187 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00005188 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00005189 if( iotrace && iotrace!=stdout ) fclose(iotrace);
5190 iotrace = 0;
5191 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00005192 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00005193 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00005194 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005195 iotrace = stdout;
5196 }else{
5197 iotrace = fopen(azArg[1], "w");
5198 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005199 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00005200 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00005201 rc = 1;
drhb0603412007-02-28 04:47:26 +00005202 }else{
mlcreech3a00f902008-03-04 17:45:01 +00005203 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00005204 }
5205 }
5206 }else
drhae5e4452007-05-03 17:18:36 +00005207#endif
drh16eb5942016-11-03 13:01:38 +00005208
drh1a513372015-05-02 17:40:23 +00005209 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
5210 static const struct {
5211 const char *zLimitName; /* Name of a limit */
5212 int limitCode; /* Integer code for that limit */
5213 } aLimit[] = {
5214 { "length", SQLITE_LIMIT_LENGTH },
5215 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
5216 { "column", SQLITE_LIMIT_COLUMN },
5217 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
5218 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
5219 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
5220 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
5221 { "attached", SQLITE_LIMIT_ATTACHED },
5222 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
5223 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
5224 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
5225 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
5226 };
5227 int i, n2;
5228 open_db(p, 0);
5229 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00005230 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005231 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00005232 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
5233 }
5234 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005235 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00005236 rc = 1;
5237 goto meta_command_exit;
5238 }else{
5239 int iLimit = -1;
5240 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00005241 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00005242 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
5243 if( iLimit<0 ){
5244 iLimit = i;
5245 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005246 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00005247 rc = 1;
5248 goto meta_command_exit;
5249 }
5250 }
5251 }
5252 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005253 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00005254 "enter \".limits\" with no arguments for a list.\n",
5255 azArg[1]);
5256 rc = 1;
5257 goto meta_command_exit;
5258 }
5259 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00005260 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
5261 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00005262 }
5263 printf("%20s %d\n", aLimit[iLimit].zLimitName,
5264 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
5265 }
5266 }else
drhb0603412007-02-28 04:47:26 +00005267
dan3c7ebeb2016-12-16 17:28:56 +00005268 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00005269 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00005270 lintDotCommand(p, azArg, nArg);
5271 }else
5272
drh70df4fe2006-06-13 15:12:21 +00005273#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00005274 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00005275 const char *zFile, *zProc;
5276 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00005277 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005278 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00005279 rc = 1;
5280 goto meta_command_exit;
5281 }
drh1e397f82006-06-08 15:28:43 +00005282 zFile = azArg[1];
5283 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00005284 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00005285 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
5286 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005287 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00005288 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00005289 rc = 1;
drh1e397f82006-06-08 15:28:43 +00005290 }
5291 }else
drh70df4fe2006-06-13 15:12:21 +00005292#endif
drh1e397f82006-06-08 15:28:43 +00005293
drhc2ce0be2014-05-29 12:36:14 +00005294 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
5295 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005296 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005297 rc = 1;
5298 }else{
5299 const char *zFile = azArg[1];
5300 output_file_close(p->pLog);
5301 p->pLog = output_file_open(zFile);
5302 }
drh127f9d72010-02-23 01:47:00 +00005303 }else
5304
drhc2ce0be2014-05-29 12:36:14 +00005305 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
5306 const char *zMode = nArg>=2 ? azArg[1] : "";
5307 int n2 = (int)strlen(zMode);
5308 int c2 = zMode[0];
5309 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005310 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00005311 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005312 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005313 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00005314 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005315 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00005316 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00005317 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
5318 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005319 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00005320 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00005321 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005322 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00005323 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00005324 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00005325 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00005326 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00005327 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00005328 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00005329 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00005330 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00005331 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00005332 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00005333 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00005334 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00005335 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
5336 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00005337 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
5338 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00005339 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
5340 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drhdaffd0e2001-04-11 14:28:42 +00005341 }else {
mistachkinaae280e2015-12-31 19:06:24 +00005342 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00005343 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00005344 rc = 1;
drh75897232000-05-29 14:26:00 +00005345 }
drh700c2522016-02-09 18:39:25 +00005346 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00005347 }else
5348
drhc2ce0be2014-05-29 12:36:14 +00005349 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
5350 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00005351 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
5352 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005353 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005354 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00005355 rc = 1;
5356 }
5357 }else
5358
drh05782482013-10-24 15:20:20 +00005359 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00005360 char *zNewFilename; /* Name of the database file to open */
5361 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00005362 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00005363 /* Close the existing database */
5364 session_close_all(p);
5365 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00005366 p->db = 0;
dan21472212017-03-01 11:30:27 +00005367 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00005368 sqlite3_free(p->zFreeOnClose);
5369 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00005370 /* Check for command-line arguments */
5371 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
5372 const char *z = azArg[iName];
5373 if( optionMatch(z,"new") ){
5374 newFlag = 1;
5375 }else if( z[0]=='-' ){
5376 utf8_printf(stderr, "unknown option: %s\n", z);
5377 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00005378 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00005379 }
drhcd0509e2016-09-16 00:26:08 +00005380 }
5381 /* If a filename is specified, try to open it first */
5382 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
5383 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00005384 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00005385 p->zDbFilename = zNewFilename;
5386 open_db(p, 1);
5387 if( p->db==0 ){
5388 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
5389 sqlite3_free(zNewFilename);
5390 }else{
5391 p->zFreeOnClose = zNewFilename;
5392 }
5393 }
5394 if( p->db==0 ){
5395 /* As a fall-back open a TEMP database */
5396 p->zDbFilename = 0;
5397 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00005398 }
5399 }else
5400
drhc2ce0be2014-05-29 12:36:14 +00005401 if( c=='o'
5402 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
5403 ){
5404 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
5405 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005406 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00005407 rc = 1;
5408 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005409 }
drhc2ce0be2014-05-29 12:36:14 +00005410 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
5411 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00005412 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005413 rc = 1;
5414 goto meta_command_exit;
5415 }
5416 p->outCount = 2;
5417 }else{
5418 p->outCount = 0;
5419 }
5420 output_reset(p);
5421 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005422#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005423 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005424 rc = 1;
5425 p->out = stdout;
5426#else
drhc2ce0be2014-05-29 12:36:14 +00005427 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00005428 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005429 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00005430 p->out = stdout;
5431 rc = 1;
5432 }else{
drhc2ce0be2014-05-29 12:36:14 +00005433 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00005434 }
drh8cd5b252015-03-02 22:06:43 +00005435#endif
drh75897232000-05-29 14:26:00 +00005436 }else{
drhc2ce0be2014-05-29 12:36:14 +00005437 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00005438 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00005439 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005440 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00005441 }
drh75897232000-05-29 14:26:00 +00005442 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00005443 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005444 } else {
drhc2ce0be2014-05-29 12:36:14 +00005445 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00005446 }
5447 }
5448 }else
5449
drh078b1fd2012-09-21 13:40:02 +00005450 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
5451 int i;
5452 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00005453 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00005454 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00005455 }
mistachkinaae280e2015-12-31 19:06:24 +00005456 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00005457 }else
5458
drhc2ce0be2014-05-29 12:36:14 +00005459 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00005460 if( nArg >= 2) {
5461 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
5462 }
5463 if( nArg >= 3) {
5464 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
5465 }
5466 }else
5467
drhc2ce0be2014-05-29 12:36:14 +00005468 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00005469 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00005470 }else
5471
drhc2ce0be2014-05-29 12:36:14 +00005472 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
5473 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00005474 if( nArg!=2 ){
5475 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005476 rc = 1;
5477 goto meta_command_exit;
5478 }
drh4e8142c2016-11-11 14:54:22 +00005479 alt = fopen(azArg[1], "rb");
5480 if( alt==0 ){
5481 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
5482 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00005483 }else{
drh4e8142c2016-11-11 14:54:22 +00005484 rc = process_input(p, alt);
5485 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00005486 }
5487 }else
5488
drhc2ce0be2014-05-29 12:36:14 +00005489 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00005490 const char *zSrcFile;
5491 const char *zDb;
5492 sqlite3 *pSrc;
5493 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00005494 int nTimeout = 0;
5495
drh9ff849f2009-02-04 20:55:57 +00005496 if( nArg==2 ){
5497 zSrcFile = azArg[1];
5498 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00005499 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00005500 zSrcFile = azArg[2];
5501 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00005502 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005503 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00005504 rc = 1;
5505 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00005506 }
5507 rc = sqlite3_open(zSrcFile, &pSrc);
5508 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005509 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00005510 sqlite3_close(pSrc);
5511 return 1;
5512 }
drh05782482013-10-24 15:20:20 +00005513 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005514 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
5515 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005516 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00005517 sqlite3_close(pSrc);
5518 return 1;
5519 }
drhdc2c4912009-02-04 22:46:47 +00005520 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
5521 || rc==SQLITE_BUSY ){
5522 if( rc==SQLITE_BUSY ){
5523 if( nTimeout++ >= 3 ) break;
5524 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00005525 }
5526 }
5527 sqlite3_backup_finish(pBackup);
5528 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005529 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00005530 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00005531 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00005532 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005533 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005534 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00005535 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005536 }
5537 sqlite3_close(pSrc);
5538 }else
5539
dan8d1edb92014-11-05 09:07:28 +00005540
5541 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
5542 if( nArg==2 ){
5543 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00005544#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00005545 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00005546#endif
dan8d1edb92014-11-05 09:07:28 +00005547 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005548 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00005549 rc = 1;
5550 }
5551 }else
5552
drhc2ce0be2014-05-29 12:36:14 +00005553 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005554 ShellState data;
drh75897232000-05-29 14:26:00 +00005555 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00005556 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00005557 memcpy(&data, p, sizeof(data));
5558 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00005559 data.cMode = data.mode = MODE_Semi;
drh4926fec2016-04-13 15:33:42 +00005560 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
5561 data.cMode = data.mode = MODE_Pretty;
5562 nArg--;
5563 if( nArg==2 ) azArg[1] = azArg[2];
5564 }
5565 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00005566 int i;
drhf0693c82011-10-11 20:41:54 +00005567 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00005568 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00005569 char *new_argv[2], *new_colv[2];
5570 new_argv[0] = "CREATE TABLE sqlite_master (\n"
5571 " type text,\n"
5572 " name text,\n"
5573 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00005574 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00005575 " sql text\n"
5576 ")";
5577 new_argv[1] = 0;
5578 new_colv[0] = "sql";
5579 new_colv[1] = 0;
5580 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005581 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00005582 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00005583 char *new_argv[2], *new_colv[2];
5584 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
5585 " type text,\n"
5586 " name text,\n"
5587 " tbl_name text,\n"
5588 " rootpage integer,\n"
5589 " sql text\n"
5590 ")";
5591 new_argv[1] = 0;
5592 new_colv[0] = "sql";
5593 new_colv[1] = 0;
5594 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00005595 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00005596 }else{
drhe611f142017-03-08 11:44:00 +00005597 char *zSql;
5598 zSql = sqlite3_mprintf(
drhe0bc4042002-06-25 01:09:11 +00005599 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005600 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005601 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005602 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drhe611f142017-03-08 11:44:00 +00005603 "WHERE lower(tbl_name) LIKE %Q"
drh6ac7a582011-11-04 00:35:56 +00005604 " AND type!='meta' AND sql NOTNULL "
drhe611f142017-03-08 11:44:00 +00005605 "ORDER BY rowid", azArg[1]);
5606 rc = sqlite3_exec(p->db, zSql, callback, &data, &zErrMsg);
5607 sqlite3_free(zSql);
drha18c5682000-10-08 22:20:57 +00005608 }
drhc2ce0be2014-05-29 12:36:14 +00005609 }else if( nArg==1 ){
shane9bd1b442009-10-23 01:27:39 +00005610 rc = sqlite3_exec(p->db,
drhe0bc4042002-06-25 01:09:11 +00005611 "SELECT sql FROM "
drhac43e982012-05-21 03:15:06 +00005612 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
drh8f800a72009-01-14 23:17:55 +00005613 " FROM sqlite_master UNION ALL"
drhac43e982012-05-21 03:15:06 +00005614 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005615 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drh1ba00292013-05-06 21:01:06 +00005616 "ORDER BY rowid",
drha18c5682000-10-08 22:20:57 +00005617 callback, &data, &zErrMsg
5618 );
drhc2ce0be2014-05-29 12:36:14 +00005619 }else{
drh4926fec2016-04-13 15:33:42 +00005620 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00005621 rc = 1;
5622 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00005623 }
drh75897232000-05-29 14:26:00 +00005624 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005625 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005626 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005627 rc = 1;
5628 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005629 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00005630 rc = 1;
5631 }else{
5632 rc = 0;
drh75897232000-05-29 14:26:00 +00005633 }
5634 }else
5635
drhabd4c722014-09-20 18:18:33 +00005636#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
5637 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00005638 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00005639 }else
5640#endif
5641
drhe6229612014-08-18 15:08:26 +00005642#if defined(SQLITE_ENABLE_SESSION)
5643 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
5644 OpenSession *pSession = &p->aSession[0];
5645 char **azCmd = &azArg[1];
5646 int iSes = 0;
5647 int nCmd = nArg - 1;
5648 int i;
5649 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00005650 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00005651 if( nArg>=3 ){
5652 for(iSes=0; iSes<p->nSession; iSes++){
5653 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
5654 }
5655 if( iSes<p->nSession ){
5656 pSession = &p->aSession[iSes];
5657 azCmd++;
5658 nCmd--;
5659 }else{
5660 pSession = &p->aSession[0];
5661 iSes = 0;
5662 }
5663 }
5664
drh3a67b042014-08-18 17:56:31 +00005665 /* .session attach TABLE
5666 ** Invoke the sqlite3session_attach() interface to attach a particular
5667 ** table so that it is never filtered.
5668 */
5669 if( strcmp(azCmd[0],"attach")==0 ){
5670 if( nCmd!=2 ) goto session_syntax_error;
5671 if( pSession->p==0 ){
5672 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00005673 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00005674 }else{
5675 rc = sqlite3session_attach(pSession->p, azCmd[1]);
5676 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005677 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005678 rc = 0;
5679 }
5680 }
5681 }else
5682
5683 /* .session changeset FILE
5684 ** .session patchset FILE
5685 ** Write a changeset or patchset into a file. The file is overwritten.
5686 */
5687 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
5688 FILE *out = 0;
5689 if( nCmd!=2 ) goto session_syntax_error;
5690 if( pSession->p==0 ) goto session_not_open;
5691 out = fopen(azCmd[1], "wb");
5692 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005693 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00005694 }else{
5695 int szChng;
5696 void *pChng;
5697 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00005698 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00005699 }else{
drh2967e0c2014-08-19 00:26:17 +00005700 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
5701 }
5702 if( rc ){
5703 printf("Error: error code %d\n", rc);
5704 rc = 0;
drh3a67b042014-08-18 17:56:31 +00005705 }
mistachkin1fe36bb2016-04-04 02:16:44 +00005706 if( pChng
drh3a67b042014-08-18 17:56:31 +00005707 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00005708 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00005709 szChng);
5710 }
5711 sqlite3_free(pChng);
5712 fclose(out);
5713 }
5714 }else
5715
drhe6229612014-08-18 15:08:26 +00005716 /* .session close
5717 ** Close the identified session
5718 */
5719 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00005720 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00005721 if( p->nSession ){
5722 session_close(pSession);
5723 p->aSession[iSes] = p->aSession[--p->nSession];
5724 }
5725 }else
5726
drh03168ca2014-08-18 20:01:31 +00005727 /* .session enable ?BOOLEAN?
5728 ** Query or set the enable flag
5729 */
5730 if( strcmp(azCmd[0], "enable")==0 ){
5731 int ii;
5732 if( nCmd>2 ) goto session_syntax_error;
5733 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5734 if( p->nSession ){
5735 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005736 utf8_printf(p->out, "session %s enable flag = %d\n",
5737 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005738 }
5739 }else
5740
5741 /* .session filter GLOB ....
5742 ** Set a list of GLOB patterns of table names to be excluded.
5743 */
5744 if( strcmp(azCmd[0], "filter")==0 ){
5745 int ii, nByte;
5746 if( nCmd<2 ) goto session_syntax_error;
5747 if( p->nSession ){
5748 for(ii=0; ii<pSession->nFilter; ii++){
5749 sqlite3_free(pSession->azFilter[ii]);
5750 }
5751 sqlite3_free(pSession->azFilter);
5752 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
5753 pSession->azFilter = sqlite3_malloc( nByte );
5754 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005755 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00005756 exit(1);
5757 }
5758 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00005759 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00005760 }
5761 pSession->nFilter = ii-1;
5762 }
5763 }else
5764
5765 /* .session indirect ?BOOLEAN?
5766 ** Query or set the indirect flag
5767 */
5768 if( strcmp(azCmd[0], "indirect")==0 ){
5769 int ii;
5770 if( nCmd>2 ) goto session_syntax_error;
5771 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
5772 if( p->nSession ){
5773 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00005774 utf8_printf(p->out, "session %s indirect flag = %d\n",
5775 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005776 }
5777 }else
5778
5779 /* .session isempty
5780 ** Determine if the session is empty
5781 */
5782 if( strcmp(azCmd[0], "isempty")==0 ){
5783 int ii;
5784 if( nCmd!=1 ) goto session_syntax_error;
5785 if( p->nSession ){
5786 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00005787 utf8_printf(p->out, "session %s isempty flag = %d\n",
5788 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00005789 }
5790 }else
5791
drhe6229612014-08-18 15:08:26 +00005792 /* .session list
5793 ** List all currently open sessions
5794 */
5795 if( strcmp(azCmd[0],"list")==0 ){
5796 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00005797 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00005798 }
5799 }else
5800
5801 /* .session open DB NAME
5802 ** Open a new session called NAME on the attached database DB.
5803 ** DB is normally "main".
5804 */
5805 if( strcmp(azCmd[0],"open")==0 ){
5806 char *zName;
5807 if( nCmd!=3 ) goto session_syntax_error;
5808 zName = azCmd[2];
5809 if( zName[0]==0 ) goto session_syntax_error;
5810 for(i=0; i<p->nSession; i++){
5811 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00005812 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00005813 goto meta_command_exit;
5814 }
5815 }
5816 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00005817 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00005818 goto meta_command_exit;
5819 }
5820 pSession = &p->aSession[p->nSession];
5821 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
5822 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00005823 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00005824 rc = 0;
drhe6229612014-08-18 15:08:26 +00005825 goto meta_command_exit;
5826 }
drh03168ca2014-08-18 20:01:31 +00005827 pSession->nFilter = 0;
5828 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00005829 p->nSession++;
5830 pSession->zName = sqlite3_mprintf("%s", zName);
5831 }else
5832 /* If no command name matches, show a syntax error */
5833 session_syntax_error:
5834 session_help(p);
5835 }else
5836#endif
5837
drh340f5822013-06-27 13:01:21 +00005838#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00005839 /* Undocumented commands for internal testing. Subject to change
5840 ** without notice. */
5841 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
5842 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
5843 int i, v;
5844 for(i=1; i<nArg; i++){
5845 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00005846 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00005847 }
5848 }
5849 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
5850 int i; sqlite3_int64 v;
5851 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00005852 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00005853 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00005854 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00005855 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00005856 }
5857 }
5858 }else
drh340f5822013-06-27 13:01:21 +00005859#endif
drh348d19c2013-06-03 12:47:43 +00005860
drhfb546af2017-03-09 22:00:33 +00005861 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
5862 int bIsInit = 0; /* True to initialize the SELFTEST table */
5863 int bVerbose = 0; /* Verbose output */
5864 int bSelftestExists; /* True if SELFTEST already exists */
5865 char **azTest = 0; /* Content of the SELFTEST table */
5866 int nRow = 0; /* Number of rows in the SELFTEST table */
5867 int nCol = 4; /* Number of columns in the SELFTEST table */
5868 int i; /* Loop counter */
5869 int nTest = 0; /* Number of tests runs */
5870 int nErr = 0; /* Number of errors seen */
5871 ShellText str; /* Answer for a query */
5872 static char *azDefaultTest[] = {
5873 0, 0, 0, 0,
5874 "0", "memo", "Missing SELFTEST table - default checks only", "",
5875 "1", "run", "PRAGMA integrity_check", "ok"
5876 };
5877 static const int nDefaultRow = 2;
5878
5879 open_db(p,0);
5880 for(i=1; i<nArg; i++){
5881 const char *z = azArg[i];
5882 if( z[0]=='-' && z[1]=='-' ) z++;
5883 if( strcmp(z,"-init")==0 ){
5884 bIsInit = 1;
5885 }else
5886 if( strcmp(z,"-v")==0 ){
5887 bVerbose++;
5888 }else
5889 {
5890 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
5891 azArg[i], azArg[0]);
5892 raw_printf(stderr, "Should be one of: --init -v\n");
5893 rc = 1;
5894 goto meta_command_exit;
5895 }
5896 }
5897 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
5898 != SQLITE_OK ){
5899 bSelftestExists = 0;
5900 }else{
5901 bSelftestExists = 1;
5902 }
5903 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00005904 createSelftestTable(p);
5905 bSelftestExists = 1;
5906 }
5907 if( bSelftestExists ){
5908 rc = sqlite3_get_table(p->db,
5909 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
5910 &azTest, &nRow, &nCol, 0);
5911 if( rc ){
5912 raw_printf(stderr, "Error querying the selftest table\n");
5913 rc = 1;
5914 sqlite3_free_table(azTest);
5915 goto meta_command_exit;
5916 }else if( nRow==0 ){
5917 sqlite3_free_table(azTest);
5918 azTest = azDefaultTest;
5919 nRow = nDefaultRow;
5920 }
5921 }else{
5922 azTest = azDefaultTest;
5923 nRow = nDefaultRow;
5924 }
5925 initText(&str);
5926 appendText(&str, "x", 0);
5927 for(i=1; i<=nRow; i++){
5928 int tno = atoi(azTest[i*nCol]);
5929 const char *zOp = azTest[i*nCol+1];
5930 const char *zSql = azTest[i*nCol+2];
5931 const char *zAns = azTest[i*nCol+3];
5932
5933 if( bVerbose>0 ){
5934 char *zQuote = sqlite3_mprintf("%q", zSql);
5935 printf("%d: %s %s\n", tno, zOp, zSql);
5936 sqlite3_free(zQuote);
5937 }
5938 if( strcmp(zOp,"memo")==0 ){
5939 utf8_printf(p->out, "%s\n", zSql);
5940 }else
5941 if( strcmp(zOp,"run")==0 ){
5942 char *zErrMsg = 0;
5943 str.n = 0;
5944 str.z[0] = 0;
5945 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
5946 nTest++;
5947 if( bVerbose ){
5948 utf8_printf(p->out, "Result: %s\n", str.z);
5949 }
5950 if( rc || zErrMsg ){
5951 nErr++;
5952 rc = 1;
5953 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
5954 sqlite3_free(zErrMsg);
5955 }else if( strcmp(zAns,str.z)!=0 ){
5956 nErr++;
5957 rc = 1;
5958 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
5959 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
5960 }
5961 }else
5962 {
5963 utf8_printf(stderr,
5964 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
5965 rc = 1;
5966 break;
5967 }
5968 }
5969 freeText(&str);
5970 if( azTest!=azDefaultTest ) sqlite3_free_table(azTest);
5971 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
5972 }else
5973
drhc2ce0be2014-05-29 12:36:14 +00005974 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00005975 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005976 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00005977 rc = 1;
5978 }
drh6976c212014-07-24 12:09:47 +00005979 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00005980 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00005981 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00005982 }
5983 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00005984 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
5985 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00005986 }
drh75897232000-05-29 14:26:00 +00005987 }else
5988
drh1554bc82017-03-08 16:10:34 +00005989 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
5990 const char *zLike = 0; /* Which table to checksum. 0 means everything */
5991 int i; /* Loop counter */
5992 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00005993 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00005994 int iSize = 224; /* Hash algorithm to use */
5995 int bDebug = 0; /* Only show the query that would have run */
5996 sqlite3_stmt *pStmt; /* For querying tables names */
5997 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00005998 char *zSep; /* Separator */
5999 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006000 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006001 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006002 for(i=1; i<nArg; i++){
6003 const char *z = azArg[i];
6004 if( z[0]=='-' ){
6005 z++;
6006 if( z[0]=='-' ) z++;
6007 if( strcmp(z,"schema")==0 ){
6008 bSchema = 1;
6009 }else
6010 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6011 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
6012 ){
6013 iSize = atoi(&z[5]);
6014 }else
6015 if( strcmp(z,"debug")==0 ){
6016 bDebug = 1;
6017 }else
6018 {
6019 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006020 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006021 raw_printf(stderr, "Should be one of: --schema"
6022 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6023 rc = 1;
6024 goto meta_command_exit;
6025 }
6026 }else if( zLike ){
6027 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
6028 rc = 1;
6029 goto meta_command_exit;
6030 }else{
6031 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00006032 bSeparate = 1;
6033 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00006034 }
6035 }
6036 if( bSchema ){
6037 zSql = "SELECT lower(name) FROM sqlite_master"
6038 " WHERE type='table' AND coalesce(rootpage,0)>1"
6039 " UNION ALL SELECT 'sqlite_master'"
6040 " ORDER BY 1 collate nocase";
6041 }else{
6042 zSql = "SELECT lower(name) FROM sqlite_master"
6043 " WHERE type='table' AND coalesce(rootpage,0)>1"
6044 " AND name NOT LIKE 'sqlite_%'"
6045 " ORDER BY 1 collate nocase";
6046 }
6047 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6048 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006049 initText(&sSql);
6050 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
6051 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00006052 while( SQLITE_ROW==sqlite3_step(pStmt) ){
6053 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
6054 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
6055 if( strncmp(zTab, "sqlite_",7)!=0 ){
6056 appendText(&sQuery,"SELECT * FROM ", 0);
6057 appendText(&sQuery,zTab,'"');
6058 appendText(&sQuery," NOT INDEXED;", 0);
6059 }else if( strcmp(zTab, "sqlite_master")==0 ){
6060 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
6061 " ORDER BY name;", 0);
6062 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
6063 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
6064 " ORDER BY name;", 0);
6065 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
6066 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
6067 " ORDER BY tbl,idx;", 0);
6068 }else if( strcmp(zTab, "sqlite_stat3")==0
6069 || strcmp(zTab, "sqlite_stat4")==0 ){
6070 appendText(&sQuery, "SELECT * FROM ", 0);
6071 appendText(&sQuery, zTab, 0);
6072 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
6073 }
drh3ee83ef2017-03-08 17:56:54 +00006074 appendText(&sSql, zSep, 0);
6075 appendText(&sSql, sQuery.z, '\'');
6076 sQuery.n = 0;
6077 appendText(&sSql, ",", 0);
6078 appendText(&sSql, zTab, '\'');
6079 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00006080 }
6081 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00006082 if( bSeparate ){
6083 zSql = sqlite3_mprintf(
6084 "%s))"
6085 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
6086 " FROM [sha3sum$query]",
6087 sSql.z, iSize);
6088 }else{
6089 zSql = sqlite3_mprintf(
6090 "%s))"
6091 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
6092 " FROM [sha3sum$query]",
6093 sSql.z, iSize);
6094 }
drh1554bc82017-03-08 16:10:34 +00006095 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00006096 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00006097 if( bDebug ){
6098 utf8_printf(p->out, "%s\n", zSql);
6099 }else{
6100 shell_exec(p->db, zSql, shell_callback, p, 0);
6101 }
6102 sqlite3_free(zSql);
6103 }else
6104
drh62cdde52014-05-28 20:22:28 +00006105 if( c=='s'
6106 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00006107 ){
6108 char *zCmd;
drh54027102014-08-06 14:36:53 +00006109 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00006110 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006111 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00006112 rc = 1;
6113 goto meta_command_exit;
6114 }
drhdcb3e3d2014-05-29 03:17:29 +00006115 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00006116 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00006117 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
6118 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00006119 }
drh54027102014-08-06 14:36:53 +00006120 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00006121 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00006122 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00006123 }else
6124
drhc2ce0be2014-05-29 12:36:14 +00006125 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00006126 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00006127 int i;
drhc2ce0be2014-05-29 12:36:14 +00006128 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00006129 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00006130 rc = 1;
6131 goto meta_command_exit;
6132 }
drhe6e1d122017-03-09 13:50:49 +00006133 utf8_printf(p->out, "%12.12s: %s\n","echo",
6134 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00006135 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00006136 utf8_printf(p->out, "%12.12s: %s\n","explain",
6137 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00006138 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006139 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
6140 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00006141 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00006142 raw_printf(p->out, "\n");
6143 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00006144 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00006145 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006146 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006147 raw_printf(p->out, "\n");
6148 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00006149 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00006150 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00006151 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00006152 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00006153 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00006154 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00006155 }
mistachkinaae280e2015-12-31 19:06:24 +00006156 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00006157 utf8_printf(p->out, "%12.12s: %s\n", "filename",
6158 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00006159 }else
6160
drhc2ce0be2014-05-29 12:36:14 +00006161 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
6162 if( nArg==2 ){
6163 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00006164 }else if( nArg==1 ){
6165 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006166 }else{
drh34784902016-02-27 17:12:36 +00006167 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00006168 rc = 1;
6169 }
shaneh642d8b82010-07-28 16:05:34 +00006170 }else
6171
drh6a5a4202016-12-24 21:32:40 +00006172 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
6173 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
6174 || strncmp(azArg[0], "indexes", n)==0) )
6175 ){
drh98781232012-04-23 12:38:05 +00006176 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00006177 char **azResult;
drh98781232012-04-23 12:38:05 +00006178 int nRow, nAlloc;
6179 char *zSql = 0;
6180 int ii;
drh05782482013-10-24 15:20:20 +00006181 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00006182 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00006183 if( rc ) return shellDatabaseError(p->db);
6184
6185 /* Create an SQL statement to query for the list of tables in the
6186 ** main and all attached databases where the table name matches the
6187 ** LIKE pattern bound to variable "?1". */
drh6a5a4202016-12-24 21:32:40 +00006188 if( c=='t' ){
6189 zSql = sqlite3_mprintf(
6190 "SELECT name FROM sqlite_master"
6191 " WHERE type IN ('table','view')"
6192 " AND name NOT LIKE 'sqlite_%%'"
6193 " AND name LIKE ?1");
6194 }else if( nArg>2 ){
6195 /* It is an historical accident that the .indexes command shows an error
6196 ** when called with the wrong number of arguments whereas the .tables
6197 ** command does not. */
6198 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
6199 rc = 1;
6200 goto meta_command_exit;
6201 }else{
6202 zSql = sqlite3_mprintf(
6203 "SELECT name FROM sqlite_master"
6204 " WHERE type='index'"
6205 " AND tbl_name LIKE ?1");
6206 }
drha4b81d22016-12-24 18:04:28 +00006207 for(ii=0; zSql && sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00006208 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drha4b81d22016-12-24 18:04:28 +00006209 if( zDbName==0 || ii==0 ) continue;
drh6a5a4202016-12-24 21:32:40 +00006210 if( c=='t' ){
drh98781232012-04-23 12:38:05 +00006211 zSql = sqlite3_mprintf(
6212 "%z UNION ALL "
6213 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6214 " WHERE type IN ('table','view')"
6215 " AND name NOT LIKE 'sqlite_%%'"
6216 " AND name LIKE ?1", zSql, zDbName, zDbName);
drh6a5a4202016-12-24 21:32:40 +00006217 }else{
6218 zSql = sqlite3_mprintf(
6219 "%z UNION ALL "
6220 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
6221 " WHERE type='index'"
6222 " AND tbl_name LIKE ?1", zSql, zDbName, zDbName);
drh98781232012-04-23 12:38:05 +00006223 }
drha50da102000-08-08 20:19:09 +00006224 }
dand95bb392015-09-30 11:19:05 +00006225 rc = sqlite3_finalize(pStmt);
6226 if( zSql && rc==SQLITE_OK ){
6227 zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
6228 if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6229 }
drh98781232012-04-23 12:38:05 +00006230 sqlite3_free(zSql);
dand95bb392015-09-30 11:19:05 +00006231 if( !zSql ) return shellNomemError();
6232 if( rc ) return shellDatabaseError(p->db);
6233
6234 /* Run the SQL statement prepared by the above block. Store the results
6235 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00006236 nRow = nAlloc = 0;
6237 azResult = 0;
6238 if( nArg>1 ){
6239 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00006240 }else{
drh98781232012-04-23 12:38:05 +00006241 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
6242 }
6243 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6244 if( nRow>=nAlloc ){
6245 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00006246 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00006247 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00006248 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00006249 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00006250 break;
6251 }
mistachkin8e189222015-04-19 21:43:16 +00006252 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00006253 azResult = azNew;
6254 }
6255 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00006256 if( 0==azResult[nRow] ){
6257 rc = shellNomemError();
6258 break;
6259 }
6260 nRow++;
drh98781232012-04-23 12:38:05 +00006261 }
dand95bb392015-09-30 11:19:05 +00006262 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
6263 rc = shellDatabaseError(p->db);
6264 }
6265
6266 /* Pretty-print the contents of array azResult[] to the output */
6267 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00006268 int len, maxlen = 0;
6269 int i, j;
6270 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00006271 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00006272 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00006273 if( len>maxlen ) maxlen = len;
6274 }
6275 nPrintCol = 80/(maxlen+2);
6276 if( nPrintCol<1 ) nPrintCol = 1;
6277 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
6278 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00006279 for(j=i; j<nRow; j+=nPrintRow){
6280 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00006281 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
6282 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00006283 }
mistachkinaae280e2015-12-31 19:06:24 +00006284 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00006285 }
6286 }
dand95bb392015-09-30 11:19:05 +00006287
drh98781232012-04-23 12:38:05 +00006288 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
6289 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00006290 }else
6291
drh2db82112016-09-15 21:35:24 +00006292 /* Begin redirecting output to the file "testcase-out.txt" */
6293 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
6294 output_reset(p);
6295 p->out = output_file_open("testcase-out.txt");
6296 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00006297 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00006298 }
drh760c8162016-09-16 02:52:22 +00006299 if( nArg>=2 ){
6300 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
6301 }else{
6302 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
6303 }
drh2db82112016-09-15 21:35:24 +00006304 }else
drh2db82112016-09-15 21:35:24 +00006305
drhd12602a2016-12-07 15:49:02 +00006306#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00006307 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00006308 static const struct {
6309 const char *zCtrlName; /* Name of a test-control option */
6310 int ctrlCode; /* Integer code for that option */
6311 } aCtrl[] = {
6312 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
6313 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
6314 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
6315 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
6316 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
6317 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
6318 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
6319 { "assert", SQLITE_TESTCTRL_ASSERT },
6320 { "always", SQLITE_TESTCTRL_ALWAYS },
6321 { "reserve", SQLITE_TESTCTRL_RESERVE },
6322 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
6323 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drhd416fe72011-03-17 16:45:50 +00006324 { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC },
drh2cf4acb2014-04-18 00:06:02 +00006325 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00006326 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00006327 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00006328 };
shaneh96887e12011-02-10 21:08:58 +00006329 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00006330 int rc2 = 0;
6331 int i, n2;
drh05782482013-10-24 15:20:20 +00006332 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00006333
drhd416fe72011-03-17 16:45:50 +00006334 /* convert testctrl text option to value. allow any unique prefix
6335 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00006336 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006337 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00006338 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00006339 if( testctrl<0 ){
6340 testctrl = aCtrl[i].ctrlCode;
6341 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006342 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00006343 testctrl = -1;
6344 break;
6345 }
6346 }
6347 }
drh348d19c2013-06-03 12:47:43 +00006348 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006349 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00006350 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006351 }else{
6352 switch(testctrl){
6353
6354 /* sqlite3_test_control(int, db, int) */
6355 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00006356 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00006357 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006358 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00006359 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006360 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006361 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006362 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006363 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006364 }
6365 break;
6366
6367 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00006368 case SQLITE_TESTCTRL_PRNG_SAVE:
6369 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00006370 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00006371 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00006372 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00006373 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00006374 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006375 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006376 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
6377 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006378 }
6379 break;
6380
6381 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006382 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00006383 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00006384 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006385 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006386 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006387 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006388 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00006389 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006390 }
6391 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00006392
shaneh96887e12011-02-10 21:08:58 +00006393 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00006394 case SQLITE_TESTCTRL_ASSERT:
6395 case SQLITE_TESTCTRL_ALWAYS:
6396 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00006397 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006398 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00006399 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006400 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006401 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006402 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00006403 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006404 }
6405 break;
6406
6407 /* sqlite3_test_control(int, char *) */
6408#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00006409 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00006410 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006411 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00006412 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00006413 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00006414 } else {
mistachkinaae280e2015-12-31 19:06:24 +00006415 utf8_printf(stderr,
6416 "Error: testctrl %s takes a single char * option\n",
6417 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006418 }
6419 break;
6420#endif
6421
drh1ffede82015-01-30 20:59:27 +00006422 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00006423 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00006424 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00006425 azArg[2],
drh8964b342015-01-29 17:54:52 +00006426 integerValue(azArg[3]),
6427 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00006428 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00006429 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006430 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00006431 }
6432 break;
6433
mistachkin1fe36bb2016-04-04 02:16:44 +00006434 case SQLITE_TESTCTRL_BITVEC_TEST:
6435 case SQLITE_TESTCTRL_FAULT_INSTALL:
6436 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
6437 case SQLITE_TESTCTRL_SCRATCHMALLOC:
shaneh96887e12011-02-10 21:08:58 +00006438 default:
mistachkinaae280e2015-12-31 19:06:24 +00006439 utf8_printf(stderr,
6440 "Error: CLI support for testctrl %s not implemented\n",
6441 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00006442 break;
6443 }
6444 }
6445 }else
drhf1969722017-02-17 23:52:00 +00006446#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00006447
drhc2ce0be2014-05-29 12:36:14 +00006448 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00006449 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006450 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00006451 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006452
drhc2ce0be2014-05-29 12:36:14 +00006453 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
6454 if( nArg==2 ){
6455 enableTimer = booleanValue(azArg[1]);
6456 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00006457 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00006458 enableTimer = 0;
6459 }
6460 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006461 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006462 rc = 1;
6463 }
shanehe2aa9d72009-11-06 17:20:17 +00006464 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00006465
drhc2ce0be2014-05-29 12:36:14 +00006466 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00006467 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00006468 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006469 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00006470 rc = 1;
6471 goto meta_command_exit;
6472 }
drh657b4a82015-03-19 13:30:41 +00006473 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006474 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00006475#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00006476 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00006477 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00006478 }else{
drh4b363a52016-07-23 20:27:41 +00006479 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00006480 }
6481#endif
6482 }else
6483
drhf442e332014-09-10 19:01:14 +00006484#if SQLITE_USER_AUTHENTICATION
6485 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
6486 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006487 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00006488 rc = 1;
6489 goto meta_command_exit;
6490 }
drh7883ecf2014-09-11 16:19:31 +00006491 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00006492 if( strcmp(azArg[1],"login")==0 ){
6493 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00006494 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00006495 rc = 1;
6496 goto meta_command_exit;
6497 }
drhd39c40f2014-09-11 00:27:53 +00006498 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
6499 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00006500 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006501 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00006502 rc = 1;
6503 }
6504 }else if( strcmp(azArg[1],"add")==0 ){
6505 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006506 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006507 rc = 1;
6508 goto meta_command_exit;
6509 }
drhd39c40f2014-09-11 00:27:53 +00006510 rc = sqlite3_user_add(p->db, azArg[2],
6511 azArg[3], (int)strlen(azArg[3]),
6512 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006513 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006514 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006515 rc = 1;
6516 }
6517 }else if( strcmp(azArg[1],"edit")==0 ){
6518 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00006519 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00006520 rc = 1;
6521 goto meta_command_exit;
6522 }
drhd39c40f2014-09-11 00:27:53 +00006523 rc = sqlite3_user_change(p->db, azArg[2],
6524 azArg[3], (int)strlen(azArg[3]),
6525 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00006526 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006527 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006528 rc = 1;
6529 }
6530 }else if( strcmp(azArg[1],"delete")==0 ){
6531 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006532 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00006533 rc = 1;
6534 goto meta_command_exit;
6535 }
6536 rc = sqlite3_user_delete(p->db, azArg[2]);
6537 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00006538 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00006539 rc = 1;
6540 }
6541 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006542 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00006543 rc = 1;
6544 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00006545 }
drhf442e332014-09-10 19:01:14 +00006546 }else
6547#endif /* SQLITE_USER_AUTHENTICATION */
6548
drh9fd301b2011-06-03 13:28:22 +00006549 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006550 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00006551 sqlite3_libversion(), sqlite3_sourceid());
6552 }else
6553
drh790f2872015-11-28 18:06:36 +00006554 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
6555 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00006556 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00006557 if( p->db ){
6558 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
6559 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00006560 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
6561 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6562 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6563 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00006564 }
6565 }
6566 }else
6567
drhb19e7352016-01-12 19:37:20 +00006568 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
6569 sqlite3_vfs *pVfs;
6570 sqlite3_vfs *pCurrent = 0;
6571 if( p->db ){
6572 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
6573 }
6574 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
6575 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
6576 pVfs==pCurrent ? " <--- CURRENT" : "");
6577 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
6578 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
6579 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
6580 if( pVfs->pNext ){
6581 raw_printf(p->out, "-----------------------------------\n");
6582 }
6583 }
6584 }else
6585
drhde60fc22011-12-14 17:53:36 +00006586 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
6587 const char *zDbName = nArg==2 ? azArg[1] : "main";
6588 char *zVfsName = 0;
6589 if( p->db ){
6590 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
6591 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00006592 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00006593 sqlite3_free(zVfsName);
6594 }
6595 }
6596 }else
6597
drhcef4fc82012-09-21 22:50:45 +00006598#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
6599 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006600 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00006601 }else
6602#endif
6603
drhc2ce0be2014-05-29 12:36:14 +00006604 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00006605 int j;
drh43617e92006-03-06 20:55:46 +00006606 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00006607 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00006608 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00006609 }
6610 }else
6611
6612 {
mistachkinaae280e2015-12-31 19:06:24 +00006613 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00006614 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00006615 rc = 1;
drh75897232000-05-29 14:26:00 +00006616 }
drh67505e72002-04-19 12:34:06 +00006617
drhc2ce0be2014-05-29 12:36:14 +00006618meta_command_exit:
6619 if( p->outCount ){
6620 p->outCount--;
6621 if( p->outCount==0 ) output_reset(p);
6622 }
drh67505e72002-04-19 12:34:06 +00006623 return rc;
drh75897232000-05-29 14:26:00 +00006624}
6625
drh67505e72002-04-19 12:34:06 +00006626/*
drh91a66392007-09-07 01:12:32 +00006627** Return TRUE if a semicolon occurs anywhere in the first N characters
6628** of string z[].
drh324ccef2003-02-05 14:06:20 +00006629*/
drh9f099fd2013-08-06 14:01:46 +00006630static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00006631 int i;
6632 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
6633 return 0;
drh324ccef2003-02-05 14:06:20 +00006634}
6635
6636/*
drh70c7a4b2003-04-26 03:03:06 +00006637** Test to see if a line consists entirely of whitespace.
6638*/
6639static int _all_whitespace(const char *z){
6640 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00006641 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00006642 if( *z=='/' && z[1]=='*' ){
6643 z += 2;
6644 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
6645 if( *z==0 ) return 0;
6646 z++;
6647 continue;
6648 }
6649 if( *z=='-' && z[1]=='-' ){
6650 z += 2;
6651 while( *z && *z!='\n' ){ z++; }
6652 if( *z==0 ) return 1;
6653 continue;
6654 }
6655 return 0;
6656 }
6657 return 1;
6658}
6659
6660/*
drha9b17162003-04-29 18:01:28 +00006661** Return TRUE if the line typed in is an SQL command terminator other
6662** than a semi-colon. The SQL Server style "go" command is understood
6663** as is the Oracle "/".
6664*/
drh9f099fd2013-08-06 14:01:46 +00006665static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00006666 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00006667 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
6668 return 1; /* Oracle */
6669 }
drhf0693c82011-10-11 20:41:54 +00006670 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00006671 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00006672 return 1; /* SQL Server */
6673 }
6674 return 0;
6675}
6676
6677/*
drh233a5312008-12-18 22:25:13 +00006678** Return true if zSql is a complete SQL statement. Return false if it
6679** ends in the middle of a string literal or C-style comment.
6680*/
drh9f099fd2013-08-06 14:01:46 +00006681static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00006682 int rc;
6683 if( zSql==0 ) return 1;
6684 zSql[nSql] = ';';
6685 zSql[nSql+1] = 0;
6686 rc = sqlite3_complete(zSql);
6687 zSql[nSql] = 0;
6688 return rc;
6689}
6690
6691/*
drh4e8142c2016-11-11 14:54:22 +00006692** Run a single line of SQL
6693*/
6694static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
6695 int rc;
6696 char *zErrMsg = 0;
6697
6698 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00006699 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00006700 BEGIN_TIMER;
6701 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
6702 END_TIMER;
6703 if( rc || zErrMsg ){
6704 char zPrefix[100];
6705 if( in!=0 || !stdin_is_interactive ){
6706 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
6707 "Error: near line %d:", startline);
6708 }else{
6709 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
6710 }
6711 if( zErrMsg!=0 ){
6712 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
6713 sqlite3_free(zErrMsg);
6714 zErrMsg = 0;
6715 }else{
6716 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
6717 }
6718 return 1;
drhe6e1d122017-03-09 13:50:49 +00006719 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00006720 raw_printf(p->out, "changes: %3d total_changes: %d\n",
6721 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
6722 }
6723 return 0;
6724}
6725
6726
6727/*
drh67505e72002-04-19 12:34:06 +00006728** Read input from *in and process it. If *in==0 then input
6729** is interactive - the user is typing it it. Otherwise, input
6730** is coming from a file or device. A prompt is issued and history
6731** is saved only if input is interactive. An interrupt signal will
6732** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00006733**
6734** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00006735*/
drhdcd87a92014-08-18 13:45:42 +00006736static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00006737 char *zLine = 0; /* A single input line */
6738 char *zSql = 0; /* Accumulated SQL text */
6739 int nLine; /* Length of current line */
6740 int nSql = 0; /* Bytes of zSql[] used */
6741 int nAlloc = 0; /* Allocated zSql[] space */
6742 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00006743 int rc; /* Error code */
6744 int errCnt = 0; /* Number of errors seen */
6745 int lineno = 0; /* Current line number */
6746 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00006747
6748 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
6749 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00006750 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00006751 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00006752 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00006753 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00006754 break;
drhc49f44e2006-10-26 18:15:42 +00006755 }
drh67505e72002-04-19 12:34:06 +00006756 if( seenInterrupt ){
6757 if( in!=0 ) break;
6758 seenInterrupt = 0;
6759 }
drhc28490c2006-10-26 14:25:58 +00006760 lineno++;
drh849a9d92013-12-21 15:46:06 +00006761 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00006762 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00006763 continue;
6764 }
drh2af0b2d2002-02-21 02:25:02 +00006765 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00006766 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00006767 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00006768 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00006769 break;
6770 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00006771 errCnt++;
6772 }
drhdaffd0e2001-04-11 14:28:42 +00006773 continue;
6774 }
drh9f099fd2013-08-06 14:01:46 +00006775 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00006776 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00006777 }
drh9f099fd2013-08-06 14:01:46 +00006778 nLine = strlen30(zLine);
6779 if( nSql+nLine+2>=nAlloc ){
6780 nAlloc = nSql+nLine+100;
6781 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00006782 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006783 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00006784 exit(1);
6785 }
drhdaffd0e2001-04-11 14:28:42 +00006786 }
drh9f099fd2013-08-06 14:01:46 +00006787 nSqlPrior = nSql;
6788 if( nSql==0 ){
6789 int i;
6790 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00006791 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00006792 memcpy(zSql, zLine+i, nLine+1-i);
6793 startline = lineno;
6794 nSql = nLine-i;
6795 }else{
6796 zSql[nSql++] = '\n';
6797 memcpy(zSql+nSql, zLine, nLine+1);
6798 nSql += nLine;
6799 }
6800 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00006801 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00006802 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006803 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00006804 if( p->outCount ){
6805 output_reset(p);
6806 p->outCount = 0;
6807 }
drh9f099fd2013-08-06 14:01:46 +00006808 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00006809 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00006810 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00006811 }
6812 }
drh4e8142c2016-11-11 14:54:22 +00006813 if( nSql && !_all_whitespace(zSql) ){
6814 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00006815 }
drh1f9ca2c2015-08-25 16:57:52 +00006816 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00006817 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00006818 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00006819}
6820
drh67505e72002-04-19 12:34:06 +00006821/*
6822** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00006823** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00006824*/
drhd1459152016-09-16 19:11:03 +00006825static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00006826 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00006827 if( clearFlag ){
6828 free(home_dir);
6829 home_dir = 0;
6830 return 0;
6831 }
drh85e72432012-04-11 11:38:53 +00006832 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00006833
drh4ace5362014-11-10 14:42:28 +00006834#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
6835 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00006836 {
6837 struct passwd *pwent;
6838 uid_t uid = getuid();
6839 if( (pwent=getpwuid(uid)) != NULL) {
6840 home_dir = pwent->pw_dir;
6841 }
drh67505e72002-04-19 12:34:06 +00006842 }
6843#endif
6844
chw65d3c132007-11-12 21:09:10 +00006845#if defined(_WIN32_WCE)
6846 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
6847 */
drh85e72432012-04-11 11:38:53 +00006848 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00006849#else
6850
drh83905c92012-06-21 13:00:37 +00006851#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00006852 if (!home_dir) {
6853 home_dir = getenv("USERPROFILE");
6854 }
6855#endif
6856
drh67505e72002-04-19 12:34:06 +00006857 if (!home_dir) {
6858 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00006859 }
6860
drh83905c92012-06-21 13:00:37 +00006861#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00006862 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00006863 char *zDrive, *zPath;
6864 int n;
6865 zDrive = getenv("HOMEDRIVE");
6866 zPath = getenv("HOMEPATH");
6867 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00006868 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00006869 home_dir = malloc( n );
6870 if( home_dir==0 ) return 0;
6871 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
6872 return home_dir;
6873 }
6874 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00006875 }
6876#endif
6877
chw65d3c132007-11-12 21:09:10 +00006878#endif /* !_WIN32_WCE */
6879
drh67505e72002-04-19 12:34:06 +00006880 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00006881 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00006882 char *z = malloc( n );
6883 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00006884 home_dir = z;
6885 }
drhe98d4fa2002-04-21 19:06:22 +00006886
drh67505e72002-04-19 12:34:06 +00006887 return home_dir;
6888}
6889
6890/*
6891** Read input from the file given by sqliterc_override. Or if that
6892** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00006893**
6894** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00006895*/
drh534f4df2015-02-28 14:03:35 +00006896static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00006897 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00006898 const char *sqliterc_override /* Name of config file. NULL to use default */
6899){
persicom7e2dfdd2002-04-18 02:46:52 +00006900 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00006901 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00006902 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00006903 FILE *in = NULL;
6904
6905 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00006906 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00006907 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006908 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00006909 " cannot read ~/.sqliterc\n");
6910 return;
drhe98d4fa2002-04-21 19:06:22 +00006911 }
drh2f3de322012-06-27 16:41:31 +00006912 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00006913 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
6914 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00006915 }
drha1f9b5e2004-02-14 16:31:02 +00006916 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00006917 if( in ){
drhc28490c2006-10-26 14:25:58 +00006918 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00006919 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00006920 }
drh534f4df2015-02-28 14:03:35 +00006921 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00006922 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00006923 }
drh85e72432012-04-11 11:38:53 +00006924 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00006925}
6926
drh67505e72002-04-19 12:34:06 +00006927/*
drhe1e38c42003-05-04 18:30:59 +00006928** Show available command line options
6929*/
mistachkin1fe36bb2016-04-04 02:16:44 +00006930static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00006931 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00006932 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00006933 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00006934 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00006935 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00006936 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00006937 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00006938 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00006939 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00006940#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
6941 " -heap SIZE Size of heap for memsys3 or memsys5\n"
6942#endif
drhcc3b4f82012-02-07 14:13:50 +00006943 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00006944 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00006945 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00006946 " -line set output mode to 'line'\n"
6947 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00006948 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00006949 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00006950#ifdef SQLITE_ENABLE_MULTIPLEX
6951 " -multiplex enable the multiplexor VFS\n"
6952#endif
mistachkine0d68852014-12-11 03:12:33 +00006953 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00006954 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00006955 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
6956 " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n"
mistachkine0d68852014-12-11 03:12:33 +00006957 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00006958 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00006959 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00006960 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00006961#ifdef SQLITE_ENABLE_VFSTRACE
6962 " -vfstrace enable tracing of all VFS calls\n"
6963#endif
drhe1e38c42003-05-04 18:30:59 +00006964;
6965static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00006966 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00006967 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00006968 "FILENAME is the name of an SQLite database. A new database is created\n"
6969 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00006970 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00006971 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00006972 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006973 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00006974 }
6975 exit(1);
6976}
6977
6978/*
drh67505e72002-04-19 12:34:06 +00006979** Initialize the state information in data
6980*/
drhdcd87a92014-08-18 13:45:42 +00006981static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00006982 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00006983 data->normalMode = data->cMode = data->mode = MODE_List;
6984 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00006985 memcpy(data->colSeparator,SEP_Column, 2);
6986 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00006987 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00006988 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00006989 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00006990 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00006991 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00006992 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
6993 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00006994}
6995
drh98d312f2012-10-25 15:23:14 +00006996/*
drh5c7976f2014-02-10 19:59:27 +00006997** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00006998*/
6999#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007000static void printBold(const char *zText){
7001 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7002 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7003 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7004 SetConsoleTextAttribute(out,
7005 FOREGROUND_RED|FOREGROUND_INTENSITY
7006 );
7007 printf("%s", zText);
7008 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007009}
7010#else
drh5c7976f2014-02-10 19:59:27 +00007011static void printBold(const char *zText){
7012 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007013}
7014#endif
7015
7016/*
drh98d312f2012-10-25 15:23:14 +00007017** Get the argument to an --option. Throw an error and die if no argument
7018** is available.
7019*/
7020static char *cmdline_option_value(int argc, char **argv, int i){
7021 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007022 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007023 argv[0], argv[argc-1]);
7024 exit(1);
7025 }
7026 return argv[i];
7027}
7028
mistachkin1fe36bb2016-04-04 02:16:44 +00007029#ifndef SQLITE_SHELL_IS_UTF8
7030# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7031# define SQLITE_SHELL_IS_UTF8 (0)
7032# else
7033# define SQLITE_SHELL_IS_UTF8 (1)
7034# endif
7035#endif
7036
7037#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00007038int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00007039#else
7040int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00007041 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00007042#endif
drh75897232000-05-29 14:26:00 +00007043 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00007044 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00007045 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00007046 int i;
drhc28490c2006-10-26 14:25:58 +00007047 int rc = 0;
drhb3735912014-02-10 16:13:42 +00007048 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00007049 int readStdin = 1;
7050 int nCmd = 0;
7051 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00007052
mistachkin1fe36bb2016-04-04 02:16:44 +00007053 setBinaryMode(stdin, 0);
7054 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00007055 stdin_is_interactive = isatty(0);
7056 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007057
drh69b30ab2014-02-27 15:11:52 +00007058#if USE_SYSTEM_SQLITE+0!=1
drh52784bd2011-05-18 17:15:06 +00007059 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007060 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00007061 sqlite3_sourceid(), SQLITE_SOURCE_ID);
7062 exit(1);
7063 }
drhc7181902014-02-27 15:04:13 +00007064#endif
persicom7e2dfdd2002-04-18 02:46:52 +00007065 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00007066#if !SQLITE_SHELL_IS_UTF8
7067 sqlite3_initialize();
7068 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
7069 if( argv==0 ){
7070 raw_printf(stderr, "out of memory\n");
7071 exit(1);
7072 }
7073 for(i=0; i<argc; i++){
7074 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
7075 if( argv[i]==0 ){
7076 raw_printf(stderr, "out of memory\n");
7077 exit(1);
7078 }
7079 }
7080#endif
mistachkin1810f222016-04-04 02:33:34 +00007081 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00007082 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00007083
drh44c2eb12003-04-30 11:38:26 +00007084 /* Make sure we have a valid signal handler early, before anything
7085 ** else is done.
7086 */
drh4c504392000-10-16 22:06:40 +00007087#ifdef SIGINT
7088 signal(SIGINT, interrupt_handler);
7089#endif
drh44c2eb12003-04-30 11:38:26 +00007090
drhac5649a2014-11-28 13:35:03 +00007091#ifdef SQLITE_SHELL_DBNAME_PROC
7092 {
7093 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
7094 ** of a C-function that will provide the name of the database file. Use
7095 ** this compile-time option to embed this shell program in larger
7096 ** applications. */
7097 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
7098 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
7099 warnInmemoryDb = 0;
7100 }
7101#endif
7102
drh22fbcb82004-02-01 01:22:50 +00007103 /* Do an initial pass through the command-line argument to locate
7104 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00007105 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00007106 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00007107 */
drh98d312f2012-10-25 15:23:14 +00007108 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00007109 char *z;
drhc28490c2006-10-26 14:25:58 +00007110 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007111 if( z[0]!='-' ){
7112 if( data.zDbFilename==0 ){
7113 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00007114 }else{
7115 /* Excesss arguments are interpreted as SQL (or dot-commands) and
7116 ** mean that nothing is read from stdin */
7117 readStdin = 0;
7118 nCmd++;
7119 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
7120 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007121 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00007122 exit(1);
7123 }
7124 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00007125 }
drh98d312f2012-10-25 15:23:14 +00007126 }
drhcc3b4f82012-02-07 14:13:50 +00007127 if( z[1]=='-' ) z++;
7128 if( strcmp(z,"-separator")==0
7129 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00007130 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00007131 || strcmp(z,"-cmd")==0
7132 ){
drh98d312f2012-10-25 15:23:14 +00007133 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007134 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00007135 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00007136 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00007137 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00007138 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00007139 ** we do the actual processing of arguments later in a second pass.
7140 */
shanef69573d2009-10-24 02:06:14 +00007141 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00007142 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00007143#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00007144 const char *zSize;
7145 sqlite3_int64 szHeap;
7146
drh98d312f2012-10-25 15:23:14 +00007147 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00007148 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00007149 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00007150 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00007151#else
7152 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00007153#endif
drh44dec872014-08-30 15:49:25 +00007154 }else if( strcmp(z,"-scratch")==0 ){
7155 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007156 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007157 if( sz>400000 ) sz = 400000;
7158 if( sz<2500 ) sz = 2500;
mistachkin31970cc2014-09-01 01:16:49 +00007159 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007160 if( n>10 ) n = 10;
7161 if( n<1 ) n = 1;
7162 sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
7163 data.shellFlgs |= SHFLG_Scratch;
7164 }else if( strcmp(z,"-pagecache")==0 ){
7165 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007166 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007167 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00007168 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007169 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00007170 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
7171 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00007172 data.shellFlgs |= SHFLG_Pagecache;
7173 }else if( strcmp(z,"-lookaside")==0 ){
7174 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00007175 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007176 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00007177 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00007178 if( n<0 ) n = 0;
7179 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
7180 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00007181#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00007182 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00007183 extern int vfstrace_register(
7184 const char *zTraceName,
7185 const char *zOldVfsName,
7186 int (*xOut)(const char*,void*),
7187 void *pOutArg,
7188 int makeDefault
7189 );
drh2b625e22011-03-16 17:05:28 +00007190 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00007191#endif
drh6f25e892011-07-08 17:02:57 +00007192#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00007193 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00007194 extern int sqlite3_multiple_initialize(const char*,int);
7195 sqlite3_multiplex_initialize(0, 1);
7196#endif
drh7d9f3942013-04-03 01:26:54 +00007197 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00007198 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
7199 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00007200 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00007201 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00007202 if( pVfs ){
7203 sqlite3_vfs_register(pVfs, 1);
7204 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007205 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00007206 exit(1);
7207 }
drh44c2eb12003-04-30 11:38:26 +00007208 }
7209 }
drh98d312f2012-10-25 15:23:14 +00007210 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00007211#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00007212 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00007213 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00007214#else
mistachkinaae280e2015-12-31 19:06:24 +00007215 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00007216 return 1;
drh01b41712005-08-29 23:06:23 +00007217#endif
drh98d312f2012-10-25 15:23:14 +00007218 }
7219 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00007220
drh44c2eb12003-04-30 11:38:26 +00007221 /* Go ahead and open the database file if it already exists. If the
7222 ** file does not exist, delay opening it. This prevents empty database
7223 ** files from being created if a user mistypes the database name argument
7224 ** to the sqlite command-line tool.
7225 */
drhc8d74412004-08-31 23:41:26 +00007226 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00007227 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00007228 }
7229
drh22fbcb82004-02-01 01:22:50 +00007230 /* Process the initialization file if there is one. If no -init option
7231 ** is given on the command line, look for a file named ~/.sqliterc and
7232 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00007233 */
drh534f4df2015-02-28 14:03:35 +00007234 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00007235
drh22fbcb82004-02-01 01:22:50 +00007236 /* Make a second pass through the command-line argument and set
7237 ** options. This second pass is delayed until after the initialization
7238 ** file is processed so that the command-line arguments will override
7239 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00007240 */
drh98d312f2012-10-25 15:23:14 +00007241 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00007242 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00007243 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00007244 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00007245 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00007246 i++;
7247 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007248 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00007249 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007250 data.mode = MODE_List;
drh22fbcb82004-02-01 01:22:50 +00007251 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007252 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00007253 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00007254 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00007255 }else if( strcmp(z,"-csv")==0 ){
7256 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00007257 memcpy(data.colSeparator,",",2);
7258 }else if( strcmp(z,"-ascii")==0 ){
7259 data.mode = MODE_Ascii;
7260 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007261 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00007262 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00007263 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00007264 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00007265 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00007266 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00007267 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00007268 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00007269 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007270 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00007271 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00007272 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00007273 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007274 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00007275 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00007276 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00007277 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00007278 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00007279 }else if( strcmp(z,"-eqp")==0 ){
7280 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00007281 }else if( strcmp(z,"-eqpfull")==0 ){
7282 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00007283 }else if( strcmp(z,"-stats")==0 ){
7284 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00007285 }else if( strcmp(z,"-scanstats")==0 ){
7286 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00007287 }else if( strcmp(z,"-backslash")==0 ){
7288 /* Undocumented command-line option: -backslash
7289 ** Causes C-style backslash escapes to be evaluated in SQL statements
7290 ** prior to sending the SQL into SQLite. Useful for injecting
7291 ** crazy bytes in the middle of SQL statements for testing and debugging.
7292 */
drhe6e1d122017-03-09 13:50:49 +00007293 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00007294 }else if( strcmp(z,"-bail")==0 ){
7295 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00007296 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00007297 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00007298 return 0;
drhc28490c2006-10-26 14:25:58 +00007299 }else if( strcmp(z,"-interactive")==0 ){
7300 stdin_is_interactive = 1;
7301 }else if( strcmp(z,"-batch")==0 ){
7302 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00007303 }else if( strcmp(z,"-heap")==0 ){
7304 i++;
drh44dec872014-08-30 15:49:25 +00007305 }else if( strcmp(z,"-scratch")==0 ){
7306 i+=2;
7307 }else if( strcmp(z,"-pagecache")==0 ){
7308 i+=2;
7309 }else if( strcmp(z,"-lookaside")==0 ){
7310 i+=2;
drh7d9f3942013-04-03 01:26:54 +00007311 }else if( strcmp(z,"-mmap")==0 ){
7312 i++;
drha7e61d82011-03-12 17:02:57 +00007313 }else if( strcmp(z,"-vfs")==0 ){
7314 i++;
drh6f25e892011-07-08 17:02:57 +00007315#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00007316 }else if( strcmp(z,"-vfstrace")==0 ){
7317 i++;
drh6f25e892011-07-08 17:02:57 +00007318#endif
7319#ifdef SQLITE_ENABLE_MULTIPLEX
7320 }else if( strcmp(z,"-multiplex")==0 ){
7321 i++;
7322#endif
drhcc3b4f82012-02-07 14:13:50 +00007323 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00007324 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00007325 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00007326 /* Run commands that follow -cmd first and separately from commands
7327 ** that simply appear on the command-line. This seems goofy. It would
7328 ** be better if all commands ran in the order that they appear. But
7329 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00007330 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00007331 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00007332 if( z[0]=='.' ){
7333 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00007334 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00007335 }else{
drh05782482013-10-24 15:20:20 +00007336 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00007337 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
7338 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007339 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00007340 if( bail_on_error ) return rc!=0 ? rc : 1;
7341 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007342 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00007343 if( bail_on_error ) return rc;
7344 }
7345 }
drh1e5d0e92000-05-31 23:33:17 +00007346 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007347 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
7348 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00007349 return 1;
7350 }
drh700c2522016-02-09 18:39:25 +00007351 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00007352 }
drh44c2eb12003-04-30 11:38:26 +00007353
drhac5649a2014-11-28 13:35:03 +00007354 if( !readStdin ){
7355 /* Run all arguments that do not begin with '-' as if they were separate
7356 ** command-line inputs, except for the argToSkip argument which contains
7357 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00007358 */
drhac5649a2014-11-28 13:35:03 +00007359 for(i=0; i<nCmd; i++){
7360 if( azCmd[i][0]=='.' ){
7361 rc = do_meta_command(azCmd[i], &data);
7362 if( rc ) return rc==2 ? 0 : rc;
7363 }else{
7364 open_db(&data, 0);
7365 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
7366 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007367 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00007368 return rc!=0 ? rc : 1;
7369 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007370 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00007371 return rc;
7372 }
drh6ff13852001-11-25 13:18:23 +00007373 }
drh75897232000-05-29 14:26:00 +00007374 }
drhac5649a2014-11-28 13:35:03 +00007375 free(azCmd);
drh75897232000-05-29 14:26:00 +00007376 }else{
drh44c2eb12003-04-30 11:38:26 +00007377 /* Run commands received from standard input
7378 */
drhc28490c2006-10-26 14:25:58 +00007379 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00007380 char *zHome;
7381 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00007382 int nHistory;
drh75897232000-05-29 14:26:00 +00007383 printf(
drh743e0032011-12-12 16:51:50 +00007384 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00007385 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00007386 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00007387 );
drhb3735912014-02-10 16:13:42 +00007388 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00007389 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00007390 printBold("transient in-memory database");
7391 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00007392 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00007393 }
drhd1459152016-09-16 19:11:03 +00007394 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00007395 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00007396 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00007397 if( (zHistory = malloc(nHistory))!=0 ){
7398 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
7399 }
drh67505e72002-04-19 12:34:06 +00007400 }
drhf5ed7ad2015-06-15 14:43:25 +00007401 if( zHistory ){ shell_read_history(zHistory); }
drhc28490c2006-10-26 14:25:58 +00007402 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00007403 if( zHistory ){
danfd34d6d2015-02-25 10:54:53 +00007404 shell_stifle_history(100);
7405 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00007406 free(zHistory);
drh67505e72002-04-19 12:34:06 +00007407 }
drhdaffd0e2001-04-11 14:28:42 +00007408 }else{
drhc28490c2006-10-26 14:25:58 +00007409 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00007410 }
7411 }
drh33048c02001-10-01 14:29:22 +00007412 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00007413 if( data.db ){
drhe6229612014-08-18 15:08:26 +00007414 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00007415 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00007416 }
mistachkin1fe36bb2016-04-04 02:16:44 +00007417 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00007418 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00007419#if !SQLITE_SHELL_IS_UTF8
7420 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
7421 sqlite3_free(argv);
7422#endif
drhc28490c2006-10-26 14:25:58 +00007423 return rc;
drh75897232000-05-29 14:26:00 +00007424}