blob: 2b77d482e629c30a88fdc98c685b10153a65a917 [file] [log] [blame]
drh2ce15c32017-07-11 13:34:40 +00001/* DO NOT EDIT!
2** This file is automatically generated by the script in the canonical
3** SQLite source tree at tool/mkshellc.tcl. That script combines source
4** code from various constituent source files of SQLite into this single
5** "shell.c" file used to implement the SQLite command-line shell.
6**
7** Most of the code found below comes from the "src/shell.c.in" file in
8** the canonical SQLite source tree. That main file contains "INCLUDE"
9** lines that specify other files in the canonical source tree that are
10** inserted to getnerate this complete program source file.
11**
12** The code from multiple files is combined into this single "shell.c"
13** source file to help make the command-line program easier to compile.
14**
15** To modify this program, get a copy of the canonical SQLite source tree,
16** edit the src/shell.c.in" and/or some of the other files that are included
17** by "src/shell.c.in", then rerun the tool/mkshellc.tcl script.
18*/
drh75897232000-05-29 14:26:00 +000019/*
drhb19a2bc2001-09-16 00:13:26 +000020** 2001 September 15
drh75897232000-05-29 14:26:00 +000021**
drhb19a2bc2001-09-16 00:13:26 +000022** The author disclaims copyright to this source code. In place of
23** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +000024**
drhb19a2bc2001-09-16 00:13:26 +000025** May you do good and not evil.
26** May you find forgiveness for yourself and forgive others.
27** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000028**
29*************************************************************************
30** This file contains code to implement the "sqlite" command line
31** utility for accessing SQLite databases.
drh75897232000-05-29 14:26:00 +000032*/
mistachkina3b2ff52011-09-16 20:16:36 +000033#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
shane18e526c2008-12-10 22:30:24 +000034/* This needs to come before any includes for MSVC compiler */
35#define _CRT_SECURE_NO_WARNINGS
36#endif
37
drh36f7dd32011-10-13 16:02:17 +000038/*
drhce13b992017-05-23 20:00:00 +000039** Warning pragmas copied from msvc.h in the core.
mistachkin2318d332015-01-12 18:02:52 +000040*/
drhce13b992017-05-23 20:00:00 +000041#if defined(_MSC_VER)
42#pragma warning(disable : 4054)
43#pragma warning(disable : 4055)
44#pragma warning(disable : 4100)
45#pragma warning(disable : 4127)
46#pragma warning(disable : 4130)
47#pragma warning(disable : 4152)
48#pragma warning(disable : 4189)
49#pragma warning(disable : 4206)
50#pragma warning(disable : 4210)
51#pragma warning(disable : 4232)
52#pragma warning(disable : 4244)
53#pragma warning(disable : 4305)
54#pragma warning(disable : 4306)
55#pragma warning(disable : 4702)
56#pragma warning(disable : 4706)
57#endif /* defined(_MSC_VER) */
mistachkin2318d332015-01-12 18:02:52 +000058
59/*
drh8cd5b252015-03-02 22:06:43 +000060** No support for loadable extensions in VxWorks.
61*/
drhada3f2b2015-03-23 21:32:50 +000062#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
drh8cd5b252015-03-02 22:06:43 +000063# define SQLITE_OMIT_LOAD_EXTENSION 1
64#endif
65
66/*
drh36f7dd32011-10-13 16:02:17 +000067** Enable large-file support for fopen() and friends on unix.
68*/
69#ifndef SQLITE_DISABLE_LFS
70# define _LARGE_FILE 1
71# ifndef _FILE_OFFSET_BITS
72# define _FILE_OFFSET_BITS 64
73# endif
74# define _LARGEFILE_SOURCE 1
75#endif
76
drh75897232000-05-29 14:26:00 +000077#include <stdlib.h>
78#include <string.h>
79#include <stdio.h>
danielk19772a02e332004-06-05 08:04:36 +000080#include <assert.h>
drh1d482dd2004-05-31 18:23:07 +000081#include "sqlite3.h"
drhf442e332014-09-10 19:01:14 +000082#if SQLITE_USER_AUTHENTICATION
83# include "sqlite3userauth.h"
84#endif
drh75897232000-05-29 14:26:00 +000085#include <ctype.h>
drhb0603412007-02-28 04:47:26 +000086#include <stdarg.h>
persicom7e2dfdd2002-04-18 02:46:52 +000087
drh83905c92012-06-21 13:00:37 +000088#if !defined(_WIN32) && !defined(WIN32)
drh4c504392000-10-16 22:06:40 +000089# include <signal.h>
chw97185482008-11-17 08:05:31 +000090# if !defined(__RTP__) && !defined(_WRS_KERNEL)
91# include <pwd.h>
92# endif
drhdd45df82002-04-18 12:39:03 +000093# include <unistd.h>
94# include <sys/types.h>
drh4c504392000-10-16 22:06:40 +000095#endif
drh75897232000-05-29 14:26:00 +000096
drh0ede9eb2015-01-10 16:49:23 +000097#if HAVE_READLINE
drh8e7e7a22000-05-30 18:45:23 +000098# include <readline/readline.h>
99# include <readline/history.h>
drh81d7fd12010-12-08 00:02:26 +0000100#endif
danfd34d6d2015-02-25 10:54:53 +0000101
drh0ede9eb2015-01-10 16:49:23 +0000102#if HAVE_EDITLINE
drhaaa21b42014-02-11 14:37:51 +0000103# include <editline/readline.h>
104#endif
danfd34d6d2015-02-25 10:54:53 +0000105
106#if HAVE_EDITLINE || HAVE_READLINE
107
108# define shell_add_history(X) add_history(X)
109# define shell_read_history(X) read_history(X)
110# define shell_write_history(X) write_history(X)
111# define shell_stifle_history(X) stifle_history(X)
112# define shell_readline(X) readline(X)
113
114#elif HAVE_LINENOISE
115
116# include "linenoise.h"
117# define shell_add_history(X) linenoiseHistoryAdd(X)
118# define shell_read_history(X) linenoiseHistoryLoad(X)
119# define shell_write_history(X) linenoiseHistorySave(X)
120# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
121# define shell_readline(X) linenoise(X)
122
123#else
124
mistachkin1fe36bb2016-04-04 02:16:44 +0000125# define shell_read_history(X)
danfd34d6d2015-02-25 10:54:53 +0000126# define shell_write_history(X)
127# define shell_stifle_history(X)
128
129# define SHELL_USE_LOCAL_GETLINE 1
drh75897232000-05-29 14:26:00 +0000130#endif
131
danfd34d6d2015-02-25 10:54:53 +0000132
adamd2e8464a2006-09-06 21:39:40 +0000133#if defined(_WIN32) || defined(WIN32)
134# include <io.h>
drh6976c212014-07-24 12:09:47 +0000135# include <fcntl.h>
mistachkin073664d2015-06-17 18:57:37 +0000136# define isatty(h) _isatty(h)
137# ifndef access
138# define access(f,m) _access((f),(m))
139# endif
140# undef popen
141# define popen _popen
142# undef pclose
143# define pclose _pclose
adamd2e8464a2006-09-06 21:39:40 +0000144#else
mistachkin073664d2015-06-17 18:57:37 +0000145 /* Make sure isatty() has a prototype. */
146 extern int isatty(int);
drh4328c8b2003-04-26 02:50:11 +0000147
mistachkin073664d2015-06-17 18:57:37 +0000148# if !defined(__RTP__) && !defined(_WRS_KERNEL)
149 /* popen and pclose are not C89 functions and so are
150 ** sometimes omitted from the <stdio.h> header */
151 extern FILE *popen(const char*,const char*);
152 extern int pclose(FILE*);
153# else
154# define SQLITE_OMIT_POPEN 1
155# endif
mistachkinf6418892013-08-28 01:54:12 +0000156#endif
drh53371f92013-07-25 17:07:03 +0000157
chw65d3c132007-11-12 21:09:10 +0000158#if defined(_WIN32_WCE)
159/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
160 * thus we always assume that we have a console. That can be
161 * overridden with the -batch command line option.
162 */
163#define isatty(x) 1
164#endif
165
drhf0693c82011-10-11 20:41:54 +0000166/* ctype macros that work with signed characters */
167#define IsSpace(X) isspace((unsigned char)X)
168#define IsDigit(X) isdigit((unsigned char)X)
169#define ToLower(X) (char)tolower((unsigned char)X)
170
mistachkin1fe36bb2016-04-04 02:16:44 +0000171#if defined(_WIN32) || defined(WIN32)
172#include <windows.h>
173
174/* string conversion routines only needed on Win32 */
175extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
176extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
177extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
mistachkin8145fc62016-09-16 20:39:21 +0000178extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
mistachkin1fe36bb2016-04-04 02:16:44 +0000179#endif
180
drh047d4532015-01-18 20:30:23 +0000181/* On Windows, we normally run with output mode of TEXT so that \n characters
182** are automatically translated into \r\n. However, this behavior needs
183** to be disabled in some cases (ex: when generating CSV output and when
184** rendering quoted strings that contain \n characters). The following
185** routines take care of that.
186*/
187#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000188static void setBinaryMode(FILE *file, int isOutput){
189 if( isOutput ) fflush(file);
190 _setmode(_fileno(file), _O_BINARY);
drh047d4532015-01-18 20:30:23 +0000191}
mistachkin1fe36bb2016-04-04 02:16:44 +0000192static void setTextMode(FILE *file, int isOutput){
193 if( isOutput ) fflush(file);
194 _setmode(_fileno(file), _O_TEXT);
drh047d4532015-01-18 20:30:23 +0000195}
196#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000197# define setBinaryMode(X,Y)
198# define setTextMode(X,Y)
drh047d4532015-01-18 20:30:23 +0000199#endif
200
drh43408312013-10-30 12:43:36 +0000201
202/* True if the timer is enabled */
203static int enableTimer = 0;
204
205/* Return the current wall-clock time */
206static sqlite3_int64 timeOfDay(void){
207 static sqlite3_vfs *clockVfs = 0;
208 sqlite3_int64 t;
209 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
dan3fd415b2015-11-16 08:54:10 +0000210 if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
drh43408312013-10-30 12:43:36 +0000211 clockVfs->xCurrentTimeInt64(clockVfs, &t);
212 }else{
213 double r;
214 clockVfs->xCurrentTime(clockVfs, &r);
215 t = (sqlite3_int64)(r*86400000.0);
216 }
217 return t;
218}
219
drh91eb93c2015-03-03 19:56:20 +0000220#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
drh3b1a9882007-11-02 12:53:03 +0000221#include <sys/time.h>
222#include <sys/resource.h>
223
drh91eb93c2015-03-03 19:56:20 +0000224/* VxWorks does not support getrusage() as far as we can determine */
225#if defined(_WRS_KERNEL) || defined(__RTP__)
226struct rusage {
227 struct timeval ru_utime; /* user CPU time used */
228 struct timeval ru_stime; /* system CPU time used */
229};
230#define getrusage(A,B) memset(B,0,sizeof(*B))
231#endif
232
drhda108222009-02-25 19:07:24 +0000233/* Saved resource information for the beginning of an operation */
drh43408312013-10-30 12:43:36 +0000234static struct rusage sBegin; /* CPU time at start */
235static sqlite3_int64 iBegin; /* Wall-clock time at start */
drhda108222009-02-25 19:07:24 +0000236
drhda108222009-02-25 19:07:24 +0000237/*
238** Begin timing an operation
239*/
240static void beginTimer(void){
241 if( enableTimer ){
242 getrusage(RUSAGE_SELF, &sBegin);
drh43408312013-10-30 12:43:36 +0000243 iBegin = timeOfDay();
drhda108222009-02-25 19:07:24 +0000244 }
245}
246
247/* Return the difference of two time_structs in seconds */
248static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
mistachkin1fe36bb2016-04-04 02:16:44 +0000249 return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
drhda108222009-02-25 19:07:24 +0000250 (double)(pEnd->tv_sec - pStart->tv_sec);
251}
252
253/*
254** Print the timing results.
255*/
256static void endTimer(void){
257 if( enableTimer ){
drh43408312013-10-30 12:43:36 +0000258 sqlite3_int64 iEnd = timeOfDay();
drh91eb93c2015-03-03 19:56:20 +0000259 struct rusage sEnd;
drhda108222009-02-25 19:07:24 +0000260 getrusage(RUSAGE_SELF, &sEnd);
drh43408312013-10-30 12:43:36 +0000261 printf("Run Time: real %.3f user %f sys %f\n",
262 (iEnd - iBegin)*0.001,
drhda108222009-02-25 19:07:24 +0000263 timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
264 timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
265 }
266}
shaneb320ccd2009-10-21 03:42:58 +0000267
drhda108222009-02-25 19:07:24 +0000268#define BEGIN_TIMER beginTimer()
269#define END_TIMER endTimer()
270#define HAS_TIMER 1
shaneb320ccd2009-10-21 03:42:58 +0000271
272#elif (defined(_WIN32) || defined(WIN32))
273
shaneb320ccd2009-10-21 03:42:58 +0000274/* Saved resource information for the beginning of an operation */
275static HANDLE hProcess;
276static FILETIME ftKernelBegin;
277static FILETIME ftUserBegin;
drh43408312013-10-30 12:43:36 +0000278static sqlite3_int64 ftWallBegin;
drh4ace5362014-11-10 14:42:28 +0000279typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
280 LPFILETIME, LPFILETIME);
shaneb320ccd2009-10-21 03:42:58 +0000281static GETPROCTIMES getProcessTimesAddr = NULL;
282
shaneb320ccd2009-10-21 03:42:58 +0000283/*
284** Check to see if we have timer support. Return 1 if necessary
285** support found (or found previously).
286*/
287static int hasTimer(void){
288 if( getProcessTimesAddr ){
289 return 1;
290 } else {
drh4ace5362014-11-10 14:42:28 +0000291 /* GetProcessTimes() isn't supported in WIN95 and some other Windows
292 ** versions. See if the version we are running on has it, and if it
293 ** does, save off a pointer to it and the current process handle.
shaneb320ccd2009-10-21 03:42:58 +0000294 */
295 hProcess = GetCurrentProcess();
296 if( hProcess ){
297 HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
298 if( NULL != hinstLib ){
drh4ace5362014-11-10 14:42:28 +0000299 getProcessTimesAddr =
300 (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
shaneb320ccd2009-10-21 03:42:58 +0000301 if( NULL != getProcessTimesAddr ){
302 return 1;
303 }
mistachkin1fe36bb2016-04-04 02:16:44 +0000304 FreeLibrary(hinstLib);
shaneb320ccd2009-10-21 03:42:58 +0000305 }
306 }
307 }
308 return 0;
309}
310
311/*
312** Begin timing an operation
313*/
314static void beginTimer(void){
315 if( enableTimer && getProcessTimesAddr ){
316 FILETIME ftCreation, ftExit;
drh4ace5362014-11-10 14:42:28 +0000317 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
318 &ftKernelBegin,&ftUserBegin);
drh43408312013-10-30 12:43:36 +0000319 ftWallBegin = timeOfDay();
shaneb320ccd2009-10-21 03:42:58 +0000320 }
321}
322
323/* Return the difference of two FILETIME structs in seconds */
324static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
325 sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
326 sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
327 return (double) ((i64End - i64Start) / 10000000.0);
328}
329
330/*
331** Print the timing results.
332*/
333static void endTimer(void){
334 if( enableTimer && getProcessTimesAddr){
335 FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
drh43408312013-10-30 12:43:36 +0000336 sqlite3_int64 ftWallEnd = timeOfDay();
drh4ace5362014-11-10 14:42:28 +0000337 getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
drh43408312013-10-30 12:43:36 +0000338 printf("Run Time: real %.3f user %f sys %f\n",
339 (ftWallEnd - ftWallBegin)*0.001,
shaneb320ccd2009-10-21 03:42:58 +0000340 timeDiff(&ftUserBegin, &ftUserEnd),
341 timeDiff(&ftKernelBegin, &ftKernelEnd));
342 }
343}
344
345#define BEGIN_TIMER beginTimer()
346#define END_TIMER endTimer()
347#define HAS_TIMER hasTimer()
348
drhda108222009-02-25 19:07:24 +0000349#else
mistachkin1fe36bb2016-04-04 02:16:44 +0000350#define BEGIN_TIMER
drhda108222009-02-25 19:07:24 +0000351#define END_TIMER
352#define HAS_TIMER 0
353#endif
354
shanec0688ea2009-03-05 03:48:06 +0000355/*
356** Used to prevent warnings about unused parameters
357*/
358#define UNUSED_PARAMETER(x) (void)(x)
359
drhe91d16b2008-12-08 18:27:31 +0000360/*
drhc49f44e2006-10-26 18:15:42 +0000361** If the following flag is set, then command execution stops
362** at an error if we are not interactive.
363*/
364static int bail_on_error = 0;
365
366/*
drhc28490c2006-10-26 14:25:58 +0000367** Threat stdin as an interactive input if the following variable
368** is true. Otherwise, assume stdin is connected to a file or pipe.
369*/
370static int stdin_is_interactive = 1;
371
372/*
drhe05461c2015-12-30 13:36:57 +0000373** On Windows systems we have to know if standard output is a console
374** in order to translate UTF-8 into MBCS. The following variable is
375** true if translation is required.
376*/
377static int stdout_is_console = 1;
378
379/*
drh4c504392000-10-16 22:06:40 +0000380** The following is the open SQLite database. We make a pointer
381** to this database a static variable so that it can be accessed
382** by the SIGINT handler to interrupt database processing.
383*/
mistachkin8e189222015-04-19 21:43:16 +0000384static sqlite3 *globalDb = 0;
drh4c504392000-10-16 22:06:40 +0000385
386/*
drh67505e72002-04-19 12:34:06 +0000387** True if an interrupt (Control-C) has been received.
388*/
drh43617e92006-03-06 20:55:46 +0000389static volatile int seenInterrupt = 0;
drh67505e72002-04-19 12:34:06 +0000390
391/*
persicom7e2dfdd2002-04-18 02:46:52 +0000392** This is the name of our program. It is set in main(), used
393** in a number of other places, mostly for error messages.
394*/
395static char *Argv0;
396
397/*
398** Prompt strings. Initialized in main. Settable with
399** .prompt main continue
400*/
401static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/
402static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */
403
drhb0603412007-02-28 04:47:26 +0000404/*
mistachkin710b33b2016-01-03 18:59:28 +0000405** Render output like fprintf(). Except, if the output is going to the
406** console and if this is running on a Windows machine, translate the
407** output from UTF-8 into MBCS.
408*/
409#if defined(_WIN32) || defined(WIN32)
410void utf8_printf(FILE *out, const char *zFormat, ...){
411 va_list ap;
412 va_start(ap, zFormat);
413 if( stdout_is_console && (out==stdout || out==stderr) ){
mistachkin710b33b2016-01-03 18:59:28 +0000414 char *z1 = sqlite3_vmprintf(zFormat, ap);
mistachkin1fe36bb2016-04-04 02:16:44 +0000415 char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
mistachkin710b33b2016-01-03 18:59:28 +0000416 sqlite3_free(z1);
417 fputs(z2, out);
418 sqlite3_free(z2);
419 }else{
420 vfprintf(out, zFormat, ap);
421 }
422 va_end(ap);
423}
424#elif !defined(utf8_printf)
425# define utf8_printf fprintf
426#endif
427
428/*
429** Render output like fprintf(). This should not be used on anything that
430** includes string formatting (e.g. "%s").
431*/
432#if !defined(raw_printf)
433# define raw_printf fprintf
434#endif
435
436/*
drhb0603412007-02-28 04:47:26 +0000437** Write I/O traces to the following stream.
438*/
rsebe0a9092007-07-30 18:24:38 +0000439#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +0000440static FILE *iotrace = 0;
rsebe0a9092007-07-30 18:24:38 +0000441#endif
drhb0603412007-02-28 04:47:26 +0000442
443/*
444** This routine works like printf in that its first argument is a
445** format string and subsequent arguments are values to be substituted
446** in place of % fields. The result of formatting this string
447** is written to iotrace.
448*/
rsebe0a9092007-07-30 18:24:38 +0000449#ifdef SQLITE_ENABLE_IOTRACE
mistachkin9871a932015-03-27 00:21:52 +0000450static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
drhb0603412007-02-28 04:47:26 +0000451 va_list ap;
drhf075cd02007-02-28 06:14:25 +0000452 char *z;
drhb0603412007-02-28 04:47:26 +0000453 if( iotrace==0 ) return;
454 va_start(ap, zFormat);
drhf075cd02007-02-28 06:14:25 +0000455 z = sqlite3_vmprintf(zFormat, ap);
drhb0603412007-02-28 04:47:26 +0000456 va_end(ap);
mistachkin710b33b2016-01-03 18:59:28 +0000457 utf8_printf(iotrace, "%s", z);
drhf075cd02007-02-28 06:14:25 +0000458 sqlite3_free(z);
drhb0603412007-02-28 04:47:26 +0000459}
rsebe0a9092007-07-30 18:24:38 +0000460#endif
drhb0603412007-02-28 04:47:26 +0000461
drh6887e8f2017-04-17 13:18:42 +0000462/*
463** Output string zUtf to stream pOut as w characters. If w is negative,
464** then right-justify the text. W is the width in UTF-8 characters, not
465** in bytes. This is different from the %*.*s specification in printf
466** since with %*.*s the width is measured in bytes, not characters.
467*/
468static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
469 int i;
470 int n;
471 int aw = w<0 ? -w : w;
472 char zBuf[1000];
drhf8a2e8c2017-05-06 17:12:52 +0000473 if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
drh6887e8f2017-04-17 13:18:42 +0000474 for(i=n=0; zUtf[i]; i++){
475 if( (zUtf[i]&0xc0)!=0x80 ){
476 n++;
477 if( n==aw ){
478 do{ i++; }while( (zUtf[i]&0xc0)==0x80 );
479 break;
480 }
481 }
482 }
483 if( n>=aw ){
484 utf8_printf(pOut, "%.*s", i, zUtf);
485 }else if( w<0 ){
486 utf8_printf(pOut, "%*s%s", aw-n, "", zUtf);
487 }else{
488 utf8_printf(pOut, "%s%*s", zUtf, aw-n, "");
489 }
490}
491
drh44c2eb12003-04-30 11:38:26 +0000492
persicom7e2dfdd2002-04-18 02:46:52 +0000493/*
drh83965662003-04-17 02:54:13 +0000494** Determines if a string is a number of not.
495*/
danielk19772e588c72005-12-09 14:25:08 +0000496static int isNumber(const char *z, int *realnum){
drhc8d74412004-08-31 23:41:26 +0000497 if( *z=='-' || *z=='+' ) z++;
drhf0693c82011-10-11 20:41:54 +0000498 if( !IsDigit(*z) ){
drhc8d74412004-08-31 23:41:26 +0000499 return 0;
500 }
501 z++;
502 if( realnum ) *realnum = 0;
drhf0693c82011-10-11 20:41:54 +0000503 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000504 if( *z=='.' ){
505 z++;
drhf0693c82011-10-11 20:41:54 +0000506 if( !IsDigit(*z) ) return 0;
507 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000508 if( realnum ) *realnum = 1;
509 }
510 if( *z=='e' || *z=='E' ){
511 z++;
512 if( *z=='+' || *z=='-' ) z++;
drhf0693c82011-10-11 20:41:54 +0000513 if( !IsDigit(*z) ) return 0;
514 while( IsDigit(*z) ){ z++; }
drhc8d74412004-08-31 23:41:26 +0000515 if( realnum ) *realnum = 1;
516 }
517 return *z==0;
518}
drh83965662003-04-17 02:54:13 +0000519
520/*
drhe05461c2015-12-30 13:36:57 +0000521** Compute a string length that is limited to what can be stored in
522** lower 30 bits of a 32-bit signed integer.
523*/
524static int strlen30(const char *z){
525 const char *z2 = z;
526 while( *z2 ){ z2++; }
527 return 0x3fffffff & (int)(z2 - z);
528}
529
530/*
drh64bf76d2017-06-05 12:29:26 +0000531** Return the length of a string in characters. Multibyte UTF8 characters
532** count as a single character.
533*/
534static int strlenChar(const char *z){
535 int n = 0;
536 while( *z ){
537 if( (0xc0&*(z++))!=0x80 ) n++;
538 }
539 return n;
540}
541
542/*
drhfeac5f82004-08-01 00:10:45 +0000543** This routine reads a line of text from FILE in, stores
drh8e7e7a22000-05-30 18:45:23 +0000544** the text in memory obtained from malloc() and returns a pointer
545** to the text. NULL is returned at end of file, or if malloc()
546** fails.
547**
drh9f099fd2013-08-06 14:01:46 +0000548** If zLine is not NULL then it is a malloced buffer returned from
549** a previous call to this routine that may be reused.
drh8e7e7a22000-05-30 18:45:23 +0000550*/
drh9f099fd2013-08-06 14:01:46 +0000551static char *local_getline(char *zLine, FILE *in){
552 int nLine = zLine==0 ? 0 : 100;
553 int n = 0;
drh8e7e7a22000-05-30 18:45:23 +0000554
drhb07028f2011-10-14 21:49:18 +0000555 while( 1 ){
drh8e7e7a22000-05-30 18:45:23 +0000556 if( n+100>nLine ){
557 nLine = nLine*2 + 100;
558 zLine = realloc(zLine, nLine);
559 if( zLine==0 ) return 0;
560 }
drhdaffd0e2001-04-11 14:28:42 +0000561 if( fgets(&zLine[n], nLine - n, in)==0 ){
drh8e7e7a22000-05-30 18:45:23 +0000562 if( n==0 ){
563 free(zLine);
564 return 0;
565 }
566 zLine[n] = 0;
drh8e7e7a22000-05-30 18:45:23 +0000567 break;
568 }
drh9f099fd2013-08-06 14:01:46 +0000569 while( zLine[n] ) n++;
570 if( n>0 && zLine[n-1]=='\n' ){
drh8e7e7a22000-05-30 18:45:23 +0000571 n--;
shaneh13b36022009-12-17 21:07:15 +0000572 if( n>0 && zLine[n-1]=='\r' ) n--;
drh8e7e7a22000-05-30 18:45:23 +0000573 zLine[n] = 0;
drhb07028f2011-10-14 21:49:18 +0000574 break;
drh8e7e7a22000-05-30 18:45:23 +0000575 }
576 }
drhe05461c2015-12-30 13:36:57 +0000577#if defined(_WIN32) || defined(WIN32)
mistachkin1fe36bb2016-04-04 02:16:44 +0000578 /* For interactive input on Windows systems, translate the
drhe05461c2015-12-30 13:36:57 +0000579 ** multi-byte characterset characters into UTF-8. */
drhfc8b40f2016-09-07 10:10:18 +0000580 if( stdin_is_interactive && in==stdin ){
mistachkin1fe36bb2016-04-04 02:16:44 +0000581 char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
drhe05461c2015-12-30 13:36:57 +0000582 if( zTrans ){
583 int nTrans = strlen30(zTrans)+1;
584 if( nTrans>nLine ){
585 zLine = realloc(zLine, nTrans);
586 if( zLine==0 ){
587 sqlite3_free(zTrans);
588 return 0;
589 }
590 }
591 memcpy(zLine, zTrans, nTrans);
592 sqlite3_free(zTrans);
593 }
594 }
595#endif /* defined(_WIN32) || defined(WIN32) */
drh8e7e7a22000-05-30 18:45:23 +0000596 return zLine;
597}
598
599/*
drhc28490c2006-10-26 14:25:58 +0000600** Retrieve a single line of input text.
drh8e7e7a22000-05-30 18:45:23 +0000601**
drh9f099fd2013-08-06 14:01:46 +0000602** If in==0 then read from standard input and prompt before each line.
603** If isContinuation is true, then a continuation prompt is appropriate.
604** If isContinuation is zero, then the main prompt should be used.
605**
606** If zPrior is not NULL then it is a buffer from a prior call to this
607** routine that can be reused.
608**
609** The result is stored in space obtained from malloc() and must either
610** be freed by the caller or else passed back into this routine via the
611** zPrior argument for reuse.
drh8e7e7a22000-05-30 18:45:23 +0000612*/
drh9f099fd2013-08-06 14:01:46 +0000613static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
drh8e7e7a22000-05-30 18:45:23 +0000614 char *zPrompt;
615 char *zResult;
drhdaffd0e2001-04-11 14:28:42 +0000616 if( in!=0 ){
drh9f099fd2013-08-06 14:01:46 +0000617 zResult = local_getline(zPrior, in);
drh8e7e7a22000-05-30 18:45:23 +0000618 }else{
drh9f099fd2013-08-06 14:01:46 +0000619 zPrompt = isContinuation ? continuePrompt : mainPrompt;
danfd34d6d2015-02-25 10:54:53 +0000620#if SHELL_USE_LOCAL_GETLINE
drh9f099fd2013-08-06 14:01:46 +0000621 printf("%s", zPrompt);
622 fflush(stdout);
623 zResult = local_getline(zPrior, stdin);
danfd34d6d2015-02-25 10:54:53 +0000624#else
625 free(zPrior);
626 zResult = shell_readline(zPrompt);
627 if( zResult && *zResult ) shell_add_history(zResult);
danielk19774af00c62005-01-23 23:43:21 +0000628#endif
drh9f099fd2013-08-06 14:01:46 +0000629 }
drh8e7e7a22000-05-30 18:45:23 +0000630 return zResult;
631}
drhf42d3182017-03-08 12:25:18 +0000632/*
633** A variable length string to which one can append text.
634*/
635typedef struct ShellText ShellText;
636struct ShellText {
637 char *z;
638 int n;
639 int nAlloc;
640};
641
642/*
643** Initialize and destroy a ShellText object
644*/
645static void initText(ShellText *p){
646 memset(p, 0, sizeof(*p));
647}
648static void freeText(ShellText *p){
649 free(p->z);
650 initText(p);
651}
652
653/* zIn is either a pointer to a NULL-terminated string in memory obtained
654** from malloc(), or a NULL pointer. The string pointed to by zAppend is
655** added to zIn, and the result returned in memory obtained from malloc().
656** zIn, if it was not NULL, is freed.
657**
658** If the third argument, quote, is not '\0', then it is used as a
659** quote character for zAppend.
660*/
661static void appendText(ShellText *p, char const *zAppend, char quote){
662 int len;
663 int i;
664 int nAppend = strlen30(zAppend);
665
666 len = nAppend+p->n+1;
667 if( quote ){
668 len += 2;
669 for(i=0; i<nAppend; i++){
670 if( zAppend[i]==quote ) len++;
671 }
672 }
673
674 if( p->n+len>=p->nAlloc ){
675 p->nAlloc = p->nAlloc*2 + len + 20;
676 p->z = realloc(p->z, p->nAlloc);
677 if( p->z==0 ){
678 memset(p, 0, sizeof(*p));
679 return;
680 }
681 }
682
683 if( quote ){
684 char *zCsr = p->z+p->n;
685 *zCsr++ = quote;
686 for(i=0; i<nAppend; i++){
687 *zCsr++ = zAppend[i];
688 if( zAppend[i]==quote ) *zCsr++ = quote;
689 }
690 *zCsr++ = quote;
691 p->n = (int)(zCsr - p->z);
692 *zCsr = '\0';
693 }else{
694 memcpy(p->z+p->n, zAppend, nAppend);
695 p->n += nAppend;
696 p->z[p->n] = '\0';
697 }
698}
699
700/*
701** Attempt to determine if identifier zName needs to be quoted, either
702** because it contains non-alphanumeric characters, or because it is an
703** SQLite keyword. Be conservative in this estimate: When in doubt assume
704** that quoting is required.
705**
706** Return '"' if quoting is required. Return 0 if no quoting is required.
707*/
708static char quoteChar(const char *zName){
709 /* All SQLite keywords, in alphabetical order */
710 static const char *azKeywords[] = {
711 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
712 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
713 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
714 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
715 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
716 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
717 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
718 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
719 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
720 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
721 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
722 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
723 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
724 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
725 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
726 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
727 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
728 "WITH", "WITHOUT",
729 };
730 int i, lwr, upr, mid, c;
731 if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"';
732 for(i=0; zName[i]; i++){
733 if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"';
734 }
735 lwr = 0;
736 upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1;
737 while( lwr<=upr ){
738 mid = (lwr+upr)/2;
739 c = sqlite3_stricmp(azKeywords[mid], zName);
740 if( c==0 ) return '"';
741 if( c<0 ){
742 lwr = mid+1;
743 }else{
744 upr = mid-1;
745 }
746 }
747 return 0;
748}
drh8e7e7a22000-05-30 18:45:23 +0000749
drh09425592017-06-15 16:56:05 +0000750/*
751** SQL function: shell_add_schema(S,X)
752**
753** Add the schema name X to the CREATE statement in S and return the result.
754** Examples:
755**
756** CREATE TABLE t1(x) -> CREATE TABLE xyz.t1(x);
757**
758** Also works on
759**
760** CREATE INDEX
761** CREATE UNIQUE INDEX
762** CREATE VIEW
763** CREATE TRIGGER
764** CREATE VIRTUAL TABLE
765**
766** This UDF is used by the .schema command to insert the schema name of
767** attached databases into the middle of the sqlite_master.sql field.
768*/
769static void shellAddSchemaName(
770 sqlite3_context *pCtx,
771 int nVal,
772 sqlite3_value **apVal
773){
774 static const char *aPrefix[] = {
775 "TABLE",
776 "INDEX",
777 "UNIQUE INDEX",
778 "VIEW",
779 "TRIGGER",
780 "VIRTUAL TABLE"
781 };
782 int i = 0;
783 const char *zIn = (const char*)sqlite3_value_text(apVal[0]);
784 const char *zSchema = (const char*)sqlite3_value_text(apVal[1]);
785 assert( nVal==2 );
786 if( zIn!=0 && strncmp(zIn, "CREATE ", 7)==0 ){
drh89997982017-07-11 18:11:33 +0000787 for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
drh09425592017-06-15 16:56:05 +0000788 int n = strlen30(aPrefix[i]);
789 if( strncmp(zIn+7, aPrefix[i], n)==0 && zIn[n+7]==' ' ){
790 char cQuote = quoteChar(zSchema);
791 char *z;
792 if( cQuote ){
793 z = sqlite3_mprintf("%.*s \"%w\".%s", n+7, zIn, zSchema, zIn+n+8);
794 }else{
795 z = sqlite3_mprintf("%.*s %s.%s", n+7, zIn, zSchema, zIn+n+8);
796 }
797 sqlite3_result_text(pCtx, z, -1, sqlite3_free);
798 return;
799 }
800 }
801 }
802 sqlite3_result_value(pCtx, apVal[0]);
803}
804
drh2ce15c32017-07-11 13:34:40 +0000805/*
806** The source code for several run-time loadable extensions is inserted
807** below by the ../tool/mkshellc.tcl script. Before processing that included
808** code, we need to override some macros to make the included program code
809** work here in the middle of this regular program.
drh1554bc82017-03-08 16:10:34 +0000810*/
drh2ce15c32017-07-11 13:34:40 +0000811#define SQLITE_EXTENSION_INIT1
drh89997982017-07-11 18:11:33 +0000812#define SQLITE_EXTENSION_INIT2(X) (void)(X)
drh2ce15c32017-07-11 13:34:40 +0000813
814/************************* Begin ../ext/misc/shathree.c ******************/
815/*
816** 2017-03-08
817**
818** The author disclaims copyright to this source code. In place of
819** a legal notice, here is a blessing:
820**
821** May you do good and not evil.
822** May you find forgiveness for yourself and forgive others.
823** May you share freely, never taking more than you give.
824**
825******************************************************************************
826**
827** This SQLite extension implements a functions that compute SHA1 hashes.
828** Two SQL functions are implemented:
829**
830** sha3(X,SIZE)
831** sha3_query(Y,SIZE)
832**
833** The sha3(X) function computes the SHA3 hash of the input X, or NULL if
834** X is NULL.
835**
836** The sha3_query(Y) function evalutes all queries in the SQL statements of Y
837** and returns a hash of their results.
838**
839** The SIZE argument is optional. If omitted, the SHA3-256 hash algorithm
840** is used. If SIZE is included it must be one of the integers 224, 256,
841** 384, or 512, to determine SHA3 hash variant that is computed.
842*/
843SQLITE_EXTENSION_INIT1
844#include <assert.h>
845#include <string.h>
846#include <stdarg.h>
drh1554bc82017-03-08 16:10:34 +0000847typedef sqlite3_uint64 u64;
drh2ce15c32017-07-11 13:34:40 +0000848
849/******************************************************************************
850** The Hash Engine
851*/
drh1554bc82017-03-08 16:10:34 +0000852/*
853** Macros to determine whether the machine is big or little endian,
854** and whether or not that determination is run-time or compile-time.
855**
856** For best performance, an attempt is made to guess at the byte-order
857** using C-preprocessor macros. If that is unsuccessful, or if
858** -DSHA3_BYTEORDER=0 is set, then byte-order is determined
859** at run-time.
860*/
861#ifndef SHA3_BYTEORDER
862# if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
863 defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
864 defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
865 defined(__arm__)
866# define SHA3_BYTEORDER 1234
867# elif defined(sparc) || defined(__ppc__)
868# define SHA3_BYTEORDER 4321
869# else
870# define SHA3_BYTEORDER 0
871# endif
872#endif
873
874
875/*
876** State structure for a SHA3 hash in progress
877*/
878typedef struct SHA3Context SHA3Context;
879struct SHA3Context {
880 union {
881 u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
882 unsigned char x[1600]; /* ... or 1600 bytes */
883 } u;
884 unsigned nRate; /* Bytes of input accepted per Keccak iteration */
885 unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
886 unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
887};
888
889/*
890** A single step of the Keccak mixing function for a 1600-bit state
891*/
892static void KeccakF1600Step(SHA3Context *p){
893 int i;
894 u64 B0, B1, B2, B3, B4;
895 u64 C0, C1, C2, C3, C4;
896 u64 D0, D1, D2, D3, D4;
897 static const u64 RC[] = {
898 0x0000000000000001ULL, 0x0000000000008082ULL,
899 0x800000000000808aULL, 0x8000000080008000ULL,
900 0x000000000000808bULL, 0x0000000080000001ULL,
901 0x8000000080008081ULL, 0x8000000000008009ULL,
902 0x000000000000008aULL, 0x0000000000000088ULL,
903 0x0000000080008009ULL, 0x000000008000000aULL,
904 0x000000008000808bULL, 0x800000000000008bULL,
905 0x8000000000008089ULL, 0x8000000000008003ULL,
906 0x8000000000008002ULL, 0x8000000000000080ULL,
907 0x000000000000800aULL, 0x800000008000000aULL,
908 0x8000000080008081ULL, 0x8000000000008080ULL,
909 0x0000000080000001ULL, 0x8000000080008008ULL
910 };
911# define A00 (p->u.s[0])
912# define A01 (p->u.s[1])
913# define A02 (p->u.s[2])
914# define A03 (p->u.s[3])
915# define A04 (p->u.s[4])
916# define A10 (p->u.s[5])
917# define A11 (p->u.s[6])
918# define A12 (p->u.s[7])
919# define A13 (p->u.s[8])
920# define A14 (p->u.s[9])
921# define A20 (p->u.s[10])
922# define A21 (p->u.s[11])
923# define A22 (p->u.s[12])
924# define A23 (p->u.s[13])
925# define A24 (p->u.s[14])
926# define A30 (p->u.s[15])
927# define A31 (p->u.s[16])
928# define A32 (p->u.s[17])
929# define A33 (p->u.s[18])
930# define A34 (p->u.s[19])
931# define A40 (p->u.s[20])
932# define A41 (p->u.s[21])
933# define A42 (p->u.s[22])
934# define A43 (p->u.s[23])
935# define A44 (p->u.s[24])
936# define ROL64(a,x) ((a<<x)|(a>>(64-x)))
937
938 for(i=0; i<24; i+=4){
939 C0 = A00^A10^A20^A30^A40;
940 C1 = A01^A11^A21^A31^A41;
941 C2 = A02^A12^A22^A32^A42;
942 C3 = A03^A13^A23^A33^A43;
943 C4 = A04^A14^A24^A34^A44;
944 D0 = C4^ROL64(C1, 1);
945 D1 = C0^ROL64(C2, 1);
946 D2 = C1^ROL64(C3, 1);
947 D3 = C2^ROL64(C4, 1);
948 D4 = C3^ROL64(C0, 1);
949
950 B0 = (A00^D0);
951 B1 = ROL64((A11^D1), 44);
952 B2 = ROL64((A22^D2), 43);
953 B3 = ROL64((A33^D3), 21);
954 B4 = ROL64((A44^D4), 14);
955 A00 = B0 ^((~B1)& B2 );
956 A00 ^= RC[i];
957 A11 = B1 ^((~B2)& B3 );
958 A22 = B2 ^((~B3)& B4 );
959 A33 = B3 ^((~B4)& B0 );
960 A44 = B4 ^((~B0)& B1 );
961
962 B2 = ROL64((A20^D0), 3);
963 B3 = ROL64((A31^D1), 45);
964 B4 = ROL64((A42^D2), 61);
965 B0 = ROL64((A03^D3), 28);
966 B1 = ROL64((A14^D4), 20);
967 A20 = B0 ^((~B1)& B2 );
968 A31 = B1 ^((~B2)& B3 );
969 A42 = B2 ^((~B3)& B4 );
970 A03 = B3 ^((~B4)& B0 );
971 A14 = B4 ^((~B0)& B1 );
972
973 B4 = ROL64((A40^D0), 18);
974 B0 = ROL64((A01^D1), 1);
975 B1 = ROL64((A12^D2), 6);
976 B2 = ROL64((A23^D3), 25);
977 B3 = ROL64((A34^D4), 8);
978 A40 = B0 ^((~B1)& B2 );
979 A01 = B1 ^((~B2)& B3 );
980 A12 = B2 ^((~B3)& B4 );
981 A23 = B3 ^((~B4)& B0 );
982 A34 = B4 ^((~B0)& B1 );
983
984 B1 = ROL64((A10^D0), 36);
985 B2 = ROL64((A21^D1), 10);
986 B3 = ROL64((A32^D2), 15);
987 B4 = ROL64((A43^D3), 56);
988 B0 = ROL64((A04^D4), 27);
989 A10 = B0 ^((~B1)& B2 );
990 A21 = B1 ^((~B2)& B3 );
991 A32 = B2 ^((~B3)& B4 );
992 A43 = B3 ^((~B4)& B0 );
993 A04 = B4 ^((~B0)& B1 );
994
995 B3 = ROL64((A30^D0), 41);
996 B4 = ROL64((A41^D1), 2);
997 B0 = ROL64((A02^D2), 62);
998 B1 = ROL64((A13^D3), 55);
999 B2 = ROL64((A24^D4), 39);
1000 A30 = B0 ^((~B1)& B2 );
1001 A41 = B1 ^((~B2)& B3 );
1002 A02 = B2 ^((~B3)& B4 );
1003 A13 = B3 ^((~B4)& B0 );
1004 A24 = B4 ^((~B0)& B1 );
1005
1006 C0 = A00^A20^A40^A10^A30;
1007 C1 = A11^A31^A01^A21^A41;
1008 C2 = A22^A42^A12^A32^A02;
1009 C3 = A33^A03^A23^A43^A13;
1010 C4 = A44^A14^A34^A04^A24;
1011 D0 = C4^ROL64(C1, 1);
1012 D1 = C0^ROL64(C2, 1);
1013 D2 = C1^ROL64(C3, 1);
1014 D3 = C2^ROL64(C4, 1);
1015 D4 = C3^ROL64(C0, 1);
1016
1017 B0 = (A00^D0);
1018 B1 = ROL64((A31^D1), 44);
1019 B2 = ROL64((A12^D2), 43);
1020 B3 = ROL64((A43^D3), 21);
1021 B4 = ROL64((A24^D4), 14);
1022 A00 = B0 ^((~B1)& B2 );
1023 A00 ^= RC[i+1];
1024 A31 = B1 ^((~B2)& B3 );
1025 A12 = B2 ^((~B3)& B4 );
1026 A43 = B3 ^((~B4)& B0 );
1027 A24 = B4 ^((~B0)& B1 );
1028
1029 B2 = ROL64((A40^D0), 3);
1030 B3 = ROL64((A21^D1), 45);
1031 B4 = ROL64((A02^D2), 61);
1032 B0 = ROL64((A33^D3), 28);
1033 B1 = ROL64((A14^D4), 20);
1034 A40 = B0 ^((~B1)& B2 );
1035 A21 = B1 ^((~B2)& B3 );
1036 A02 = B2 ^((~B3)& B4 );
1037 A33 = B3 ^((~B4)& B0 );
1038 A14 = B4 ^((~B0)& B1 );
1039
1040 B4 = ROL64((A30^D0), 18);
1041 B0 = ROL64((A11^D1), 1);
1042 B1 = ROL64((A42^D2), 6);
1043 B2 = ROL64((A23^D3), 25);
1044 B3 = ROL64((A04^D4), 8);
1045 A30 = B0 ^((~B1)& B2 );
1046 A11 = B1 ^((~B2)& B3 );
1047 A42 = B2 ^((~B3)& B4 );
1048 A23 = B3 ^((~B4)& B0 );
1049 A04 = B4 ^((~B0)& B1 );
1050
1051 B1 = ROL64((A20^D0), 36);
1052 B2 = ROL64((A01^D1), 10);
1053 B3 = ROL64((A32^D2), 15);
1054 B4 = ROL64((A13^D3), 56);
1055 B0 = ROL64((A44^D4), 27);
1056 A20 = B0 ^((~B1)& B2 );
1057 A01 = B1 ^((~B2)& B3 );
1058 A32 = B2 ^((~B3)& B4 );
1059 A13 = B3 ^((~B4)& B0 );
1060 A44 = B4 ^((~B0)& B1 );
1061
1062 B3 = ROL64((A10^D0), 41);
1063 B4 = ROL64((A41^D1), 2);
1064 B0 = ROL64((A22^D2), 62);
1065 B1 = ROL64((A03^D3), 55);
1066 B2 = ROL64((A34^D4), 39);
1067 A10 = B0 ^((~B1)& B2 );
1068 A41 = B1 ^((~B2)& B3 );
1069 A22 = B2 ^((~B3)& B4 );
1070 A03 = B3 ^((~B4)& B0 );
1071 A34 = B4 ^((~B0)& B1 );
1072
1073 C0 = A00^A40^A30^A20^A10;
1074 C1 = A31^A21^A11^A01^A41;
1075 C2 = A12^A02^A42^A32^A22;
1076 C3 = A43^A33^A23^A13^A03;
1077 C4 = A24^A14^A04^A44^A34;
1078 D0 = C4^ROL64(C1, 1);
1079 D1 = C0^ROL64(C2, 1);
1080 D2 = C1^ROL64(C3, 1);
1081 D3 = C2^ROL64(C4, 1);
1082 D4 = C3^ROL64(C0, 1);
1083
1084 B0 = (A00^D0);
1085 B1 = ROL64((A21^D1), 44);
1086 B2 = ROL64((A42^D2), 43);
1087 B3 = ROL64((A13^D3), 21);
1088 B4 = ROL64((A34^D4), 14);
1089 A00 = B0 ^((~B1)& B2 );
1090 A00 ^= RC[i+2];
1091 A21 = B1 ^((~B2)& B3 );
1092 A42 = B2 ^((~B3)& B4 );
1093 A13 = B3 ^((~B4)& B0 );
1094 A34 = B4 ^((~B0)& B1 );
1095
1096 B2 = ROL64((A30^D0), 3);
1097 B3 = ROL64((A01^D1), 45);
1098 B4 = ROL64((A22^D2), 61);
1099 B0 = ROL64((A43^D3), 28);
1100 B1 = ROL64((A14^D4), 20);
1101 A30 = B0 ^((~B1)& B2 );
1102 A01 = B1 ^((~B2)& B3 );
1103 A22 = B2 ^((~B3)& B4 );
1104 A43 = B3 ^((~B4)& B0 );
1105 A14 = B4 ^((~B0)& B1 );
1106
1107 B4 = ROL64((A10^D0), 18);
1108 B0 = ROL64((A31^D1), 1);
1109 B1 = ROL64((A02^D2), 6);
1110 B2 = ROL64((A23^D3), 25);
1111 B3 = ROL64((A44^D4), 8);
1112 A10 = B0 ^((~B1)& B2 );
1113 A31 = B1 ^((~B2)& B3 );
1114 A02 = B2 ^((~B3)& B4 );
1115 A23 = B3 ^((~B4)& B0 );
1116 A44 = B4 ^((~B0)& B1 );
1117
1118 B1 = ROL64((A40^D0), 36);
1119 B2 = ROL64((A11^D1), 10);
1120 B3 = ROL64((A32^D2), 15);
1121 B4 = ROL64((A03^D3), 56);
1122 B0 = ROL64((A24^D4), 27);
1123 A40 = B0 ^((~B1)& B2 );
1124 A11 = B1 ^((~B2)& B3 );
1125 A32 = B2 ^((~B3)& B4 );
1126 A03 = B3 ^((~B4)& B0 );
1127 A24 = B4 ^((~B0)& B1 );
1128
1129 B3 = ROL64((A20^D0), 41);
1130 B4 = ROL64((A41^D1), 2);
1131 B0 = ROL64((A12^D2), 62);
1132 B1 = ROL64((A33^D3), 55);
1133 B2 = ROL64((A04^D4), 39);
1134 A20 = B0 ^((~B1)& B2 );
1135 A41 = B1 ^((~B2)& B3 );
1136 A12 = B2 ^((~B3)& B4 );
1137 A33 = B3 ^((~B4)& B0 );
1138 A04 = B4 ^((~B0)& B1 );
1139
1140 C0 = A00^A30^A10^A40^A20;
1141 C1 = A21^A01^A31^A11^A41;
1142 C2 = A42^A22^A02^A32^A12;
1143 C3 = A13^A43^A23^A03^A33;
1144 C4 = A34^A14^A44^A24^A04;
1145 D0 = C4^ROL64(C1, 1);
1146 D1 = C0^ROL64(C2, 1);
1147 D2 = C1^ROL64(C3, 1);
1148 D3 = C2^ROL64(C4, 1);
1149 D4 = C3^ROL64(C0, 1);
1150
1151 B0 = (A00^D0);
1152 B1 = ROL64((A01^D1), 44);
1153 B2 = ROL64((A02^D2), 43);
1154 B3 = ROL64((A03^D3), 21);
1155 B4 = ROL64((A04^D4), 14);
1156 A00 = B0 ^((~B1)& B2 );
1157 A00 ^= RC[i+3];
1158 A01 = B1 ^((~B2)& B3 );
1159 A02 = B2 ^((~B3)& B4 );
1160 A03 = B3 ^((~B4)& B0 );
1161 A04 = B4 ^((~B0)& B1 );
1162
1163 B2 = ROL64((A10^D0), 3);
1164 B3 = ROL64((A11^D1), 45);
1165 B4 = ROL64((A12^D2), 61);
1166 B0 = ROL64((A13^D3), 28);
1167 B1 = ROL64((A14^D4), 20);
1168 A10 = B0 ^((~B1)& B2 );
1169 A11 = B1 ^((~B2)& B3 );
1170 A12 = B2 ^((~B3)& B4 );
1171 A13 = B3 ^((~B4)& B0 );
1172 A14 = B4 ^((~B0)& B1 );
1173
1174 B4 = ROL64((A20^D0), 18);
1175 B0 = ROL64((A21^D1), 1);
1176 B1 = ROL64((A22^D2), 6);
1177 B2 = ROL64((A23^D3), 25);
1178 B3 = ROL64((A24^D4), 8);
1179 A20 = B0 ^((~B1)& B2 );
1180 A21 = B1 ^((~B2)& B3 );
1181 A22 = B2 ^((~B3)& B4 );
1182 A23 = B3 ^((~B4)& B0 );
1183 A24 = B4 ^((~B0)& B1 );
1184
1185 B1 = ROL64((A30^D0), 36);
1186 B2 = ROL64((A31^D1), 10);
1187 B3 = ROL64((A32^D2), 15);
1188 B4 = ROL64((A33^D3), 56);
1189 B0 = ROL64((A34^D4), 27);
1190 A30 = B0 ^((~B1)& B2 );
1191 A31 = B1 ^((~B2)& B3 );
1192 A32 = B2 ^((~B3)& B4 );
1193 A33 = B3 ^((~B4)& B0 );
1194 A34 = B4 ^((~B0)& B1 );
1195
1196 B3 = ROL64((A40^D0), 41);
1197 B4 = ROL64((A41^D1), 2);
1198 B0 = ROL64((A42^D2), 62);
1199 B1 = ROL64((A43^D3), 55);
1200 B2 = ROL64((A44^D4), 39);
1201 A40 = B0 ^((~B1)& B2 );
1202 A41 = B1 ^((~B2)& B3 );
1203 A42 = B2 ^((~B3)& B4 );
1204 A43 = B3 ^((~B4)& B0 );
1205 A44 = B4 ^((~B0)& B1 );
1206 }
1207}
1208
1209/*
1210** Initialize a new hash. iSize determines the size of the hash
1211** in bits and should be one of 224, 256, 384, or 512. Or iSize
1212** can be zero to use the default hash size of 256 bits.
1213*/
1214static void SHA3Init(SHA3Context *p, int iSize){
1215 memset(p, 0, sizeof(*p));
1216 if( iSize>=128 && iSize<=512 ){
1217 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8;
1218 }else{
1219 p->nRate = (1600 - 2*256)/8;
1220 }
1221#if SHA3_BYTEORDER==1234
1222 /* Known to be little-endian at compile-time. No-op */
1223#elif SHA3_BYTEORDER==4321
1224 p->ixMask = 7; /* Big-endian */
1225#else
1226 {
1227 static unsigned int one = 1;
1228 if( 1==*(unsigned char*)&one ){
1229 /* Little endian. No byte swapping. */
1230 p->ixMask = 0;
1231 }else{
1232 /* Big endian. Byte swap. */
1233 p->ixMask = 7;
1234 }
1235 }
1236#endif
1237}
1238
1239/*
1240** Make consecutive calls to the SHA3Update function to add new content
1241** to the hash
1242*/
1243static void SHA3Update(
1244 SHA3Context *p,
1245 const unsigned char *aData,
1246 unsigned int nData
1247){
1248 unsigned int i = 0;
1249#if SHA3_BYTEORDER==1234
1250 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){
1251 for(; i+7<nData; i+=8){
1252 p->u.s[p->nLoaded/8] ^= *(u64*)&aData[i];
1253 p->nLoaded += 8;
1254 if( p->nLoaded>=p->nRate ){
1255 KeccakF1600Step(p);
1256 p->nLoaded = 0;
1257 }
1258 }
1259 }
1260#endif
1261 for(; i<nData; i++){
1262#if SHA3_BYTEORDER==1234
1263 p->u.x[p->nLoaded] ^= aData[i];
1264#elif SHA3_BYTEORDER==4321
1265 p->u.x[p->nLoaded^0x07] ^= aData[i];
1266#else
1267 p->u.x[p->nLoaded^p->ixMask] ^= aData[i];
1268#endif
1269 p->nLoaded++;
1270 if( p->nLoaded==p->nRate ){
1271 KeccakF1600Step(p);
1272 p->nLoaded = 0;
1273 }
1274 }
1275}
1276
1277/*
1278** After all content has been added, invoke SHA3Final() to compute
1279** the final hash. The function returns a pointer to the binary
1280** hash value.
1281*/
1282static unsigned char *SHA3Final(SHA3Context *p){
1283 unsigned int i;
1284 if( p->nLoaded==p->nRate-1 ){
1285 const unsigned char c1 = 0x86;
1286 SHA3Update(p, &c1, 1);
1287 }else{
1288 const unsigned char c2 = 0x06;
1289 const unsigned char c3 = 0x80;
1290 SHA3Update(p, &c2, 1);
1291 p->nLoaded = p->nRate - 1;
1292 SHA3Update(p, &c3, 1);
1293 }
1294 for(i=0; i<p->nRate; i++){
1295 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask];
1296 }
1297 return &p->u.x[p->nRate];
1298}
drh2ce15c32017-07-11 13:34:40 +00001299/* End of the hashing logic
1300*****************************************************************************/
drh1554bc82017-03-08 16:10:34 +00001301
1302/*
1303** Implementation of the sha3(X,SIZE) function.
1304**
1305** Return a BLOB which is the SIZE-bit SHA3 hash of X. The default
drh2ce15c32017-07-11 13:34:40 +00001306** size is 256. If X is a BLOB, it is hashed as is.
drh1554bc82017-03-08 16:10:34 +00001307** For all other non-NULL types of input, X is converted into a UTF-8 string
1308** and the string is hashed without the trailing 0x00 terminator. The hash
1309** of a NULL value is NULL.
1310*/
1311static void sha3Func(
1312 sqlite3_context *context,
1313 int argc,
1314 sqlite3_value **argv
1315){
1316 SHA3Context cx;
1317 int eType = sqlite3_value_type(argv[0]);
1318 int nByte = sqlite3_value_bytes(argv[0]);
1319 int iSize;
1320 if( argc==1 ){
1321 iSize = 256;
1322 }else{
1323 iSize = sqlite3_value_int(argv[1]);
1324 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1325 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1326 "384 512", -1);
1327 return;
1328 }
1329 }
1330 if( eType==SQLITE_NULL ) return;
1331 SHA3Init(&cx, iSize);
1332 if( eType==SQLITE_BLOB ){
1333 SHA3Update(&cx, sqlite3_value_blob(argv[0]), nByte);
1334 }else{
1335 SHA3Update(&cx, sqlite3_value_text(argv[0]), nByte);
1336 }
1337 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1338}
1339
1340/* Compute a string using sqlite3_vsnprintf() with a maximum length
1341** of 50 bytes and add it to the hash.
1342*/
1343static void hash_step_vformat(
1344 SHA3Context *p, /* Add content to this context */
1345 const char *zFormat,
1346 ...
1347){
1348 va_list ap;
1349 int n;
1350 char zBuf[50];
1351 va_start(ap, zFormat);
1352 sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap);
1353 va_end(ap);
1354 n = (int)strlen(zBuf);
1355 SHA3Update(p, (unsigned char*)zBuf, n);
1356}
1357
1358/*
1359** Implementation of the sha3_query(SQL,SIZE) function.
1360**
1361** This function compiles and runs the SQL statement(s) given in the
1362** argument. The results are hashed using a SIZE-bit SHA3. The default
1363** size is 256.
1364**
1365** The format of the byte stream that is hashed is summarized as follows:
1366**
1367** S<n>:<sql>
1368** R
1369** N
1370** I<int>
1371** F<ieee-float>
1372** B<size>:<bytes>
1373** T<size>:<text>
1374**
1375** <sql> is the original SQL text for each statement run and <n> is
1376** the size of that text. The SQL text is UTF-8. A single R character
1377** occurs before the start of each row. N means a NULL value.
1378** I mean an 8-byte little-endian integer <int>. F is a floating point
1379** number with an 8-byte little-endian IEEE floating point value <ieee-float>.
1380** B means blobs of <size> bytes. T means text rendered as <size>
1381** bytes of UTF-8. The <n> and <size> values are expressed as an ASCII
1382** text integers.
1383**
1384** For each SQL statement in the X input, there is one S segment. Each
1385** S segment is followed by zero or more R segments, one for each row in the
1386** result set. After each R, there are one or more N, I, F, B, or T segments,
1387** one for each column in the result set. Segments are concatentated directly
1388** with no delimiters of any kind.
1389*/
1390static void sha3QueryFunc(
1391 sqlite3_context *context,
1392 int argc,
1393 sqlite3_value **argv
1394){
1395 sqlite3 *db = sqlite3_context_db_handle(context);
1396 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1397 sqlite3_stmt *pStmt = 0;
1398 int nCol; /* Number of columns in the result set */
1399 int i; /* Loop counter */
1400 int rc;
1401 int n;
1402 const char *z;
1403 SHA3Context cx;
1404 int iSize;
1405
1406 if( argc==1 ){
1407 iSize = 256;
1408 }else{
1409 iSize = sqlite3_value_int(argv[1]);
1410 if( iSize!=224 && iSize!=256 && iSize!=384 && iSize!=512 ){
1411 sqlite3_result_error(context, "SHA3 size should be one of: 224 256 "
1412 "384 512", -1);
1413 return;
1414 }
1415 }
1416 if( zSql==0 ) return;
1417 SHA3Init(&cx, iSize);
1418 while( zSql[0] ){
1419 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql);
1420 if( rc ){
1421 char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s",
1422 zSql, sqlite3_errmsg(db));
1423 sqlite3_finalize(pStmt);
1424 sqlite3_result_error(context, zMsg, -1);
1425 sqlite3_free(zMsg);
1426 return;
1427 }
1428 if( !sqlite3_stmt_readonly(pStmt) ){
1429 char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt));
1430 sqlite3_finalize(pStmt);
1431 sqlite3_result_error(context, zMsg, -1);
1432 sqlite3_free(zMsg);
1433 return;
1434 }
1435 nCol = sqlite3_column_count(pStmt);
1436 z = sqlite3_sql(pStmt);
1437 n = (int)strlen(z);
1438 hash_step_vformat(&cx,"S%d:",n);
1439 SHA3Update(&cx,(unsigned char*)z,n);
1440
1441 /* Compute a hash over the result of the query */
1442 while( SQLITE_ROW==sqlite3_step(pStmt) ){
1443 SHA3Update(&cx,(const unsigned char*)"R",1);
1444 for(i=0; i<nCol; i++){
1445 switch( sqlite3_column_type(pStmt,i) ){
1446 case SQLITE_NULL: {
1447 SHA3Update(&cx, (const unsigned char*)"N",1);
1448 break;
1449 }
1450 case SQLITE_INTEGER: {
1451 sqlite3_uint64 u;
1452 int j;
1453 unsigned char x[9];
1454 sqlite3_int64 v = sqlite3_column_int64(pStmt,i);
1455 memcpy(&u, &v, 8);
1456 for(j=8; j>=1; j--){
1457 x[j] = u & 0xff;
1458 u >>= 8;
1459 }
1460 x[0] = 'I';
1461 SHA3Update(&cx, x, 9);
1462 break;
1463 }
1464 case SQLITE_FLOAT: {
1465 sqlite3_uint64 u;
1466 int j;
1467 unsigned char x[9];
1468 double r = sqlite3_column_double(pStmt,i);
1469 memcpy(&u, &r, 8);
1470 for(j=8; j>=1; j--){
1471 x[j] = u & 0xff;
1472 u >>= 8;
1473 }
1474 x[0] = 'F';
1475 SHA3Update(&cx,x,9);
1476 break;
1477 }
1478 case SQLITE_TEXT: {
1479 int n2 = sqlite3_column_bytes(pStmt, i);
1480 const unsigned char *z2 = sqlite3_column_text(pStmt, i);
1481 hash_step_vformat(&cx,"T%d:",n2);
1482 SHA3Update(&cx, z2, n2);
1483 break;
1484 }
1485 case SQLITE_BLOB: {
1486 int n2 = sqlite3_column_bytes(pStmt, i);
1487 const unsigned char *z2 = sqlite3_column_blob(pStmt, i);
1488 hash_step_vformat(&cx,"B%d:",n2);
1489 SHA3Update(&cx, z2, n2);
1490 break;
1491 }
1492 }
1493 }
1494 }
1495 sqlite3_finalize(pStmt);
1496 }
1497 sqlite3_result_blob(context, SHA3Final(&cx), iSize/8, SQLITE_TRANSIENT);
1498}
drh2ce15c32017-07-11 13:34:40 +00001499
1500
1501#ifdef _WIN32
dan9c1cf322017-08-30 13:21:17 +00001502
drh2ce15c32017-07-11 13:34:40 +00001503#endif
1504int sqlite3_shathree_init(
1505 sqlite3 *db,
1506 char **pzErrMsg,
1507 const sqlite3_api_routines *pApi
1508){
1509 int rc = SQLITE_OK;
1510 SQLITE_EXTENSION_INIT2(pApi);
1511 (void)pzErrMsg; /* Unused parameter */
1512 rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
1513 sha3Func, 0, 0);
1514 if( rc==SQLITE_OK ){
1515 rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
1516 sha3Func, 0, 0);
1517 }
1518 if( rc==SQLITE_OK ){
1519 rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
1520 sha3QueryFunc, 0, 0);
1521 }
1522 if( rc==SQLITE_OK ){
1523 rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
1524 sha3QueryFunc, 0, 0);
1525 }
1526 return rc;
1527}
1528
1529/************************* End ../ext/misc/shathree.c ********************/
1530/************************* Begin ../ext/misc/fileio.c ******************/
1531/*
1532** 2014-06-13
1533**
1534** The author disclaims copyright to this source code. In place of
1535** a legal notice, here is a blessing:
1536**
1537** May you do good and not evil.
1538** May you find forgiveness for yourself and forgive others.
1539** May you share freely, never taking more than you give.
1540**
1541******************************************************************************
1542**
1543** This SQLite extension implements SQL functions readfile() and
1544** writefile().
1545*/
1546SQLITE_EXTENSION_INIT1
1547#include <stdio.h>
1548
1549/*
1550** Implementation of the "readfile(X)" SQL function. The entire content
1551** of the file named X is read and returned as a BLOB. NULL is returned
1552** if the file does not exist or is unreadable.
1553*/
1554static void readfileFunc(
1555 sqlite3_context *context,
1556 int argc,
1557 sqlite3_value **argv
1558){
1559 const char *zName;
1560 FILE *in;
1561 long nIn;
1562 void *pBuf;
1563
drh89997982017-07-11 18:11:33 +00001564 (void)(argc); /* Unused parameter */
drh2ce15c32017-07-11 13:34:40 +00001565 zName = (const char*)sqlite3_value_text(argv[0]);
1566 if( zName==0 ) return;
1567 in = fopen(zName, "rb");
1568 if( in==0 ) return;
1569 fseek(in, 0, SEEK_END);
1570 nIn = ftell(in);
1571 rewind(in);
1572 pBuf = sqlite3_malloc( nIn );
1573 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
1574 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
1575 }else{
1576 sqlite3_free(pBuf);
1577 }
1578 fclose(in);
1579}
1580
1581/*
1582** Implementation of the "writefile(X,Y)" SQL function. The argument Y
1583** is written into file X. The number of bytes written is returned. Or
1584** NULL is returned if something goes wrong, such as being unable to open
1585** file X for writing.
1586*/
1587static void writefileFunc(
1588 sqlite3_context *context,
1589 int argc,
1590 sqlite3_value **argv
1591){
1592 FILE *out;
1593 const char *z;
1594 sqlite3_int64 rc;
1595 const char *zFile;
1596
drh89997982017-07-11 18:11:33 +00001597 (void)(argc); /* Unused parameter */
drh2ce15c32017-07-11 13:34:40 +00001598 zFile = (const char*)sqlite3_value_text(argv[0]);
1599 if( zFile==0 ) return;
1600 out = fopen(zFile, "wb");
1601 if( out==0 ) return;
1602 z = (const char*)sqlite3_value_blob(argv[1]);
1603 if( z==0 ){
1604 rc = 0;
1605 }else{
1606 rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
1607 }
1608 fclose(out);
1609 sqlite3_result_int64(context, rc);
1610}
1611
1612
1613#ifdef _WIN32
dan9c1cf322017-08-30 13:21:17 +00001614
drh2ce15c32017-07-11 13:34:40 +00001615#endif
1616int sqlite3_fileio_init(
1617 sqlite3 *db,
1618 char **pzErrMsg,
1619 const sqlite3_api_routines *pApi
1620){
1621 int rc = SQLITE_OK;
1622 SQLITE_EXTENSION_INIT2(pApi);
1623 (void)pzErrMsg; /* Unused parameter */
1624 rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
1625 readfileFunc, 0, 0);
1626 if( rc==SQLITE_OK ){
1627 rc = sqlite3_create_function(db, "writefile", 2, SQLITE_UTF8, 0,
1628 writefileFunc, 0, 0);
1629 }
1630 return rc;
1631}
1632
1633/************************* End ../ext/misc/fileio.c ********************/
drh56eb09b2017-07-11 13:59:07 +00001634/************************* Begin ../ext/misc/completion.c ******************/
1635/*
1636** 2017-07-10
1637**
1638** The author disclaims copyright to this source code. In place of
1639** a legal notice, here is a blessing:
1640**
1641** May you do good and not evil.
1642** May you find forgiveness for yourself and forgive others.
1643** May you share freely, never taking more than you give.
1644**
1645*************************************************************************
1646**
1647** This file implements an eponymous virtual table that returns suggested
1648** completions for a partial SQL input.
1649**
1650** Suggested usage:
1651**
1652** SELECT DISTINCT candidate COLLATE nocase
1653** FROM completion($prefix,$wholeline)
1654** ORDER BY 1;
1655**
1656** The two query parameters are optional. $prefix is the text of the
1657** current word being typed and that is to be completed. $wholeline is
1658** the complete input line, used for context.
1659**
1660** The raw completion() table might return the same candidate multiple
1661** times, for example if the same column name is used to two or more
1662** tables. And the candidates are returned in an arbitrary order. Hence,
1663** the DISTINCT and ORDER BY are recommended.
1664**
1665** This virtual table operates at the speed of human typing, and so there
1666** is no attempt to make it fast. Even a slow implementation will be much
1667** faster than any human can type.
1668**
1669*/
1670SQLITE_EXTENSION_INIT1
1671#include <assert.h>
1672#include <string.h>
1673#include <ctype.h>
1674
1675#ifndef SQLITE_OMIT_VIRTUALTABLE
1676
1677/* completion_vtab is a subclass of sqlite3_vtab which will
1678** serve as the underlying representation of a completion virtual table
1679*/
1680typedef struct completion_vtab completion_vtab;
1681struct completion_vtab {
1682 sqlite3_vtab base; /* Base class - must be first */
1683 sqlite3 *db; /* Database connection for this completion vtab */
1684};
1685
1686/* completion_cursor is a subclass of sqlite3_vtab_cursor which will
1687** serve as the underlying representation of a cursor that scans
1688** over rows of the result
1689*/
1690typedef struct completion_cursor completion_cursor;
1691struct completion_cursor {
1692 sqlite3_vtab_cursor base; /* Base class - must be first */
1693 sqlite3 *db; /* Database connection for this cursor */
1694 int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
1695 char *zPrefix; /* The prefix for the word we want to complete */
1696 char *zLine; /* The whole that we want to complete */
1697 const char *zCurrentRow; /* Current output row */
1698 sqlite3_stmt *pStmt; /* Current statement */
1699 sqlite3_int64 iRowid; /* The rowid */
1700 int ePhase; /* Current phase */
1701 int j; /* inter-phase counter */
1702};
1703
1704/* Values for ePhase:
1705*/
1706#define COMPLETION_FIRST_PHASE 1
1707#define COMPLETION_KEYWORDS 1
1708#define COMPLETION_PRAGMAS 2
1709#define COMPLETION_FUNCTIONS 3
1710#define COMPLETION_COLLATIONS 4
1711#define COMPLETION_INDEXES 5
1712#define COMPLETION_TRIGGERS 6
1713#define COMPLETION_DATABASES 7
1714#define COMPLETION_TABLES 8
1715#define COMPLETION_COLUMNS 9
1716#define COMPLETION_MODULES 10
1717#define COMPLETION_EOF 11
1718
1719/*
1720** The completionConnect() method is invoked to create a new
1721** completion_vtab that describes the completion virtual table.
1722**
1723** Think of this routine as the constructor for completion_vtab objects.
1724**
1725** All this routine needs to do is:
1726**
1727** (1) Allocate the completion_vtab object and initialize all fields.
1728**
1729** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
1730** result set of queries against completion will look like.
1731*/
1732static int completionConnect(
1733 sqlite3 *db,
1734 void *pAux,
1735 int argc, const char *const*argv,
1736 sqlite3_vtab **ppVtab,
1737 char **pzErr
1738){
1739 completion_vtab *pNew;
1740 int rc;
1741
drh89997982017-07-11 18:11:33 +00001742 (void)(pAux); /* Unused parameter */
1743 (void)(argc); /* Unused parameter */
1744 (void)(argv); /* Unused parameter */
1745 (void)(pzErr); /* Unused parameter */
1746
drh56eb09b2017-07-11 13:59:07 +00001747/* Column numbers */
1748#define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
1749#define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
1750#define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
1751#define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
1752
1753 rc = sqlite3_declare_vtab(db,
1754 "CREATE TABLE x("
1755 " candidate TEXT,"
1756 " prefix TEXT HIDDEN,"
1757 " wholeline TEXT HIDDEN,"
1758 " phase INT HIDDEN" /* Used for debugging only */
1759 ")");
1760 if( rc==SQLITE_OK ){
1761 pNew = sqlite3_malloc( sizeof(*pNew) );
1762 *ppVtab = (sqlite3_vtab*)pNew;
1763 if( pNew==0 ) return SQLITE_NOMEM;
1764 memset(pNew, 0, sizeof(*pNew));
1765 pNew->db = db;
1766 }
1767 return rc;
1768}
1769
1770/*
1771** This method is the destructor for completion_cursor objects.
1772*/
1773static int completionDisconnect(sqlite3_vtab *pVtab){
1774 sqlite3_free(pVtab);
1775 return SQLITE_OK;
1776}
1777
1778/*
1779** Constructor for a new completion_cursor object.
1780*/
1781static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
1782 completion_cursor *pCur;
1783 pCur = sqlite3_malloc( sizeof(*pCur) );
1784 if( pCur==0 ) return SQLITE_NOMEM;
1785 memset(pCur, 0, sizeof(*pCur));
1786 pCur->db = ((completion_vtab*)p)->db;
1787 *ppCursor = &pCur->base;
1788 return SQLITE_OK;
1789}
1790
1791/*
1792** Reset the completion_cursor.
1793*/
1794static void completionCursorReset(completion_cursor *pCur){
1795 sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
1796 sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
1797 sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
1798 pCur->j = 0;
1799}
1800
1801/*
1802** Destructor for a completion_cursor.
1803*/
1804static int completionClose(sqlite3_vtab_cursor *cur){
1805 completionCursorReset((completion_cursor*)cur);
1806 sqlite3_free(cur);
1807 return SQLITE_OK;
1808}
1809
1810/*
1811** All SQL keywords understood by SQLite
1812*/
1813static const char *completionKwrds[] = {
1814 "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
1815 "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
1816 "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
1817 "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
1818 "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
1819 "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
1820 "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
1821 "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
1822 "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
1823 "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
1824 "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
1825 "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
1826 "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
1827 "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
1828 "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
1829 "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
1830 "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
1831 "WITH", "WITHOUT",
1832};
drh89997982017-07-11 18:11:33 +00001833#define completionKwCount \
1834 (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0]))
drh56eb09b2017-07-11 13:59:07 +00001835
1836/*
1837** Advance a completion_cursor to its next row of output.
1838**
1839** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
1840** record the current state of the scan. This routine sets ->zCurrentRow
1841** to the current row of output and then returns. If no more rows remain,
1842** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
1843** table that has reached the end of its scan.
1844**
1845** The current implementation just lists potential identifiers and
1846** keywords and filters them by zPrefix. Future enhancements should
1847** take zLine into account to try to restrict the set of identifiers and
1848** keywords based on what would be legal at the current point of input.
1849*/
1850static int completionNext(sqlite3_vtab_cursor *cur){
1851 completion_cursor *pCur = (completion_cursor*)cur;
1852 int eNextPhase = 0; /* Next phase to try if current phase reaches end */
1853 int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
1854 pCur->iRowid++;
1855 while( pCur->ePhase!=COMPLETION_EOF ){
1856 switch( pCur->ePhase ){
1857 case COMPLETION_KEYWORDS: {
drh89997982017-07-11 18:11:33 +00001858 if( pCur->j >= completionKwCount ){
drh56eb09b2017-07-11 13:59:07 +00001859 pCur->zCurrentRow = 0;
1860 pCur->ePhase = COMPLETION_DATABASES;
1861 }else{
1862 pCur->zCurrentRow = completionKwrds[pCur->j++];
1863 }
1864 iCol = -1;
1865 break;
1866 }
1867 case COMPLETION_DATABASES: {
1868 if( pCur->pStmt==0 ){
1869 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
1870 &pCur->pStmt, 0);
1871 }
1872 iCol = 1;
1873 eNextPhase = COMPLETION_TABLES;
1874 break;
1875 }
1876 case COMPLETION_TABLES: {
1877 if( pCur->pStmt==0 ){
1878 sqlite3_stmt *pS2;
1879 char *zSql = 0;
1880 const char *zSep = "";
1881 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
1882 while( sqlite3_step(pS2)==SQLITE_ROW ){
1883 const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
1884 zSql = sqlite3_mprintf(
1885 "%z%s"
1886 "SELECT name FROM \"%w\".sqlite_master"
1887 " WHERE type='table'",
1888 zSql, zSep, zDb
1889 );
1890 if( zSql==0 ) return SQLITE_NOMEM;
1891 zSep = " UNION ";
1892 }
1893 sqlite3_finalize(pS2);
1894 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
1895 sqlite3_free(zSql);
1896 }
1897 iCol = 0;
1898 eNextPhase = COMPLETION_COLUMNS;
1899 break;
1900 }
1901 case COMPLETION_COLUMNS: {
1902 if( pCur->pStmt==0 ){
1903 sqlite3_stmt *pS2;
1904 char *zSql = 0;
1905 const char *zSep = "";
1906 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
1907 while( sqlite3_step(pS2)==SQLITE_ROW ){
1908 const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
1909 zSql = sqlite3_mprintf(
1910 "%z%s"
1911 "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
1912 " JOIN pragma_table_info(sm.name,%Q) AS pti"
1913 " WHERE sm.type='table'",
1914 zSql, zSep, zDb, zDb
1915 );
1916 if( zSql==0 ) return SQLITE_NOMEM;
1917 zSep = " UNION ";
1918 }
1919 sqlite3_finalize(pS2);
1920 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
1921 sqlite3_free(zSql);
1922 }
1923 iCol = 0;
1924 eNextPhase = COMPLETION_EOF;
1925 break;
1926 }
1927 }
1928 if( iCol<0 ){
1929 /* This case is when the phase presets zCurrentRow */
1930 if( pCur->zCurrentRow==0 ) continue;
1931 }else{
1932 if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
1933 /* Extract the next row of content */
1934 pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
1935 }else{
1936 /* When all rows are finished, advance to the next phase */
1937 sqlite3_finalize(pCur->pStmt);
1938 pCur->pStmt = 0;
1939 pCur->ePhase = eNextPhase;
1940 continue;
1941 }
1942 }
1943 if( pCur->nPrefix==0 ) break;
1944 if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){
1945 break;
1946 }
1947 }
1948
1949 return SQLITE_OK;
1950}
1951
1952/*
1953** Return values of columns for the row at which the completion_cursor
1954** is currently pointing.
1955*/
1956static int completionColumn(
1957 sqlite3_vtab_cursor *cur, /* The cursor */
1958 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
1959 int i /* Which column to return */
1960){
1961 completion_cursor *pCur = (completion_cursor*)cur;
1962 switch( i ){
1963 case COMPLETION_COLUMN_CANDIDATE: {
1964 sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT);
1965 break;
1966 }
1967 case COMPLETION_COLUMN_PREFIX: {
1968 sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
1969 break;
1970 }
1971 case COMPLETION_COLUMN_WHOLELINE: {
1972 sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
1973 break;
1974 }
1975 case COMPLETION_COLUMN_PHASE: {
1976 sqlite3_result_int(ctx, pCur->ePhase);
1977 break;
1978 }
1979 }
1980 return SQLITE_OK;
1981}
1982
1983/*
1984** Return the rowid for the current row. In this implementation, the
1985** rowid is the same as the output value.
1986*/
1987static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
1988 completion_cursor *pCur = (completion_cursor*)cur;
1989 *pRowid = pCur->iRowid;
1990 return SQLITE_OK;
1991}
1992
1993/*
1994** Return TRUE if the cursor has been moved off of the last
1995** row of output.
1996*/
1997static int completionEof(sqlite3_vtab_cursor *cur){
1998 completion_cursor *pCur = (completion_cursor*)cur;
1999 return pCur->ePhase >= COMPLETION_EOF;
2000}
2001
2002/*
2003** This method is called to "rewind" the completion_cursor object back
2004** to the first row of output. This method is always called at least
2005** once prior to any call to completionColumn() or completionRowid() or
2006** completionEof().
2007*/
2008static int completionFilter(
2009 sqlite3_vtab_cursor *pVtabCursor,
2010 int idxNum, const char *idxStr,
2011 int argc, sqlite3_value **argv
2012){
2013 completion_cursor *pCur = (completion_cursor *)pVtabCursor;
2014 int iArg = 0;
drh89997982017-07-11 18:11:33 +00002015 (void)(idxStr); /* Unused parameter */
2016 (void)(argc); /* Unused parameter */
drh56eb09b2017-07-11 13:59:07 +00002017 completionCursorReset(pCur);
2018 if( idxNum & 1 ){
2019 pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
2020 if( pCur->nPrefix>0 ){
2021 pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
2022 if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
2023 }
2024 iArg++;
2025 }
2026 if( idxNum & 2 ){
2027 pCur->nLine = sqlite3_value_bytes(argv[iArg]);
2028 if( pCur->nLine>0 ){
2029 pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
2030 if( pCur->zLine==0 ) return SQLITE_NOMEM;
2031 }
2032 iArg++;
2033 }
2034 if( pCur->zLine!=0 && pCur->zPrefix==0 ){
2035 int i = pCur->nLine;
2036 while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
2037 i--;
2038 }
2039 pCur->nPrefix = pCur->nLine - i;
2040 if( pCur->nPrefix>0 ){
2041 pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
2042 if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
2043 }
2044 }
2045 pCur->iRowid = 0;
2046 pCur->ePhase = COMPLETION_FIRST_PHASE;
2047 return completionNext(pVtabCursor);
2048}
2049
2050/*
2051** SQLite will invoke this method one or more times while planning a query
2052** that uses the completion virtual table. This routine needs to create
2053** a query plan for each invocation and compute an estimated cost for that
2054** plan.
2055**
2056** There are two hidden parameters that act as arguments to the table-valued
2057** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
2058** is available and bit 1 is set if "wholeline" is available.
2059*/
2060static int completionBestIndex(
2061 sqlite3_vtab *tab,
2062 sqlite3_index_info *pIdxInfo
2063){
2064 int i; /* Loop over constraints */
2065 int idxNum = 0; /* The query plan bitmask */
2066 int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
2067 int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
2068 int nArg = 0; /* Number of arguments that completeFilter() expects */
2069 const struct sqlite3_index_constraint *pConstraint;
2070
drh89997982017-07-11 18:11:33 +00002071 (void)(tab); /* Unused parameter */
drh56eb09b2017-07-11 13:59:07 +00002072 pConstraint = pIdxInfo->aConstraint;
2073 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
2074 if( pConstraint->usable==0 ) continue;
2075 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
2076 switch( pConstraint->iColumn ){
2077 case COMPLETION_COLUMN_PREFIX:
2078 prefixIdx = i;
2079 idxNum |= 1;
2080 break;
2081 case COMPLETION_COLUMN_WHOLELINE:
2082 wholelineIdx = i;
2083 idxNum |= 2;
2084 break;
2085 }
2086 }
2087 if( prefixIdx>=0 ){
2088 pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
2089 pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
2090 }
2091 if( wholelineIdx>=0 ){
2092 pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
2093 pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
2094 }
2095 pIdxInfo->idxNum = idxNum;
2096 pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
2097 pIdxInfo->estimatedRows = 500 - 100*nArg;
2098 return SQLITE_OK;
2099}
2100
2101/*
2102** This following structure defines all the methods for the
2103** completion virtual table.
2104*/
2105static sqlite3_module completionModule = {
2106 0, /* iVersion */
2107 0, /* xCreate */
2108 completionConnect, /* xConnect */
2109 completionBestIndex, /* xBestIndex */
2110 completionDisconnect, /* xDisconnect */
2111 0, /* xDestroy */
2112 completionOpen, /* xOpen - open a cursor */
2113 completionClose, /* xClose - close a cursor */
2114 completionFilter, /* xFilter - configure scan constraints */
2115 completionNext, /* xNext - advance a cursor */
2116 completionEof, /* xEof - check for end of scan */
2117 completionColumn, /* xColumn - read data */
2118 completionRowid, /* xRowid - read data */
2119 0, /* xUpdate */
2120 0, /* xBegin */
2121 0, /* xSync */
2122 0, /* xCommit */
2123 0, /* xRollback */
2124 0, /* xFindMethod */
2125 0, /* xRename */
drh89997982017-07-11 18:11:33 +00002126 0, /* xSavepoint */
2127 0, /* xRelease */
2128 0 /* xRollbackTo */
drh56eb09b2017-07-11 13:59:07 +00002129};
2130
2131#endif /* SQLITE_OMIT_VIRTUALTABLE */
2132
2133int sqlite3CompletionVtabInit(sqlite3 *db){
2134 int rc = SQLITE_OK;
2135#ifndef SQLITE_OMIT_VIRTUALTABLE
2136 rc = sqlite3_create_module(db, "completion", &completionModule, 0);
2137#endif
2138 return rc;
2139}
2140
2141#ifdef _WIN32
dan9c1cf322017-08-30 13:21:17 +00002142
drh56eb09b2017-07-11 13:59:07 +00002143#endif
2144int sqlite3_completion_init(
2145 sqlite3 *db,
2146 char **pzErrMsg,
2147 const sqlite3_api_routines *pApi
2148){
2149 int rc = SQLITE_OK;
2150 SQLITE_EXTENSION_INIT2(pApi);
drh89997982017-07-11 18:11:33 +00002151 (void)(pzErrMsg); /* Unused parameter */
drh56eb09b2017-07-11 13:59:07 +00002152#ifndef SQLITE_OMIT_VIRTUALTABLE
2153 rc = sqlite3CompletionVtabInit(db);
2154#endif
2155 return rc;
2156}
2157
2158/************************* End ../ext/misc/completion.c ********************/
drh1554bc82017-03-08 16:10:34 +00002159
drhe6229612014-08-18 15:08:26 +00002160#if defined(SQLITE_ENABLE_SESSION)
2161/*
2162** State information for a single open session
2163*/
2164typedef struct OpenSession OpenSession;
2165struct OpenSession {
2166 char *zName; /* Symbolic name for this session */
2167 int nFilter; /* Number of xFilter rejection GLOB patterns */
2168 char **azFilter; /* Array of xFilter rejection GLOB patterns */
2169 sqlite3_session *p; /* The open session */
2170};
2171#endif
2172
drhdcd87a92014-08-18 13:45:42 +00002173/*
mistachkin1fe36bb2016-04-04 02:16:44 +00002174** Shell output mode information from before ".explain on",
drhdcd87a92014-08-18 13:45:42 +00002175** saved so that it can be restored by ".explain off"
2176*/
2177typedef struct SavedModeInfo SavedModeInfo;
2178struct SavedModeInfo {
2179 int valid; /* Is there legit data in here? */
2180 int mode; /* Mode prior to ".explain on" */
2181 int showHeader; /* The ".header" setting prior to ".explain on" */
2182 int colWidth[100]; /* Column widths prior to ".explain on" */
persicom7e2dfdd2002-04-18 02:46:52 +00002183};
drh45e29d82006-11-20 16:21:10 +00002184
drh8e7e7a22000-05-30 18:45:23 +00002185/*
drhdcd87a92014-08-18 13:45:42 +00002186** State information about the database connection is contained in an
2187** instance of the following structure.
drh75897232000-05-29 14:26:00 +00002188*/
drhdcd87a92014-08-18 13:45:42 +00002189typedef struct ShellState ShellState;
2190struct ShellState {
shane626a6e42009-10-22 17:30:15 +00002191 sqlite3 *db; /* The database */
drh700c2522016-02-09 18:39:25 +00002192 int autoExplain; /* Automatically turn on .explain mode */
drhc2ce0be2014-05-29 12:36:14 +00002193 int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
shaneh642d8b82010-07-28 16:05:34 +00002194 int statsOn; /* True to display memory stats before each finalize */
dan8d1edb92014-11-05 09:07:28 +00002195 int scanstatsOn; /* True to display scan stats before each finalize */
drhc2ce0be2014-05-29 12:36:14 +00002196 int outCount; /* Revert to stdout when reaching zero */
drh28bd4bc2000-06-15 15:57:22 +00002197 int cnt; /* Number of records displayed so far */
2198 FILE *out; /* Write results here */
drh42f64e52012-04-04 16:56:23 +00002199 FILE *traceOut; /* Output for sqlite3_trace() */
drh2f464a02011-10-13 00:41:49 +00002200 int nErr; /* Number of errors seen */
drh28bd4bc2000-06-15 15:57:22 +00002201 int mode; /* An output mode setting */
drh700c2522016-02-09 18:39:25 +00002202 int cMode; /* temporary output mode for the current query */
2203 int normalMode; /* Output mode before ".explain on" */
drh45e29d82006-11-20 16:21:10 +00002204 int writableSchema; /* True if PRAGMA writable_schema=ON */
drh28bd4bc2000-06-15 15:57:22 +00002205 int showHeader; /* True to show column names in List or Column mode */
drh760c8162016-09-16 02:52:22 +00002206 int nCheck; /* Number of ".check" commands run */
drh44dec872014-08-30 15:49:25 +00002207 unsigned shellFlgs; /* Various flags */
drh33048c02001-10-01 14:29:22 +00002208 char *zDestTable; /* Name of destination table when MODE_Insert */
drh760c8162016-09-16 02:52:22 +00002209 char zTestcase[30]; /* Name of current test case */
mistachkin636bf9f2014-07-19 20:15:16 +00002210 char colSeparator[20]; /* Column separator character for several modes */
2211 char rowSeparator[20]; /* Row separator character for MODE_Ascii */
drha0c66f52000-07-29 13:20:21 +00002212 int colWidth[100]; /* Requested width of each column when in column mode*/
2213 int actualWidth[100]; /* Actual width of each column */
mistachkin44b99f72014-12-11 03:29:14 +00002214 char nullValue[20]; /* The text to print when a NULL comes back from
drh83965662003-04-17 02:54:13 +00002215 ** the database */
drh44c2eb12003-04-30 11:38:26 +00002216 char outfile[FILENAME_MAX]; /* Filename for *out */
2217 const char *zDbFilename; /* name of the database file */
drh05782482013-10-24 15:20:20 +00002218 char *zFreeOnClose; /* Filename to free when closing */
drha7e61d82011-03-12 17:02:57 +00002219 const char *zVfs; /* Name of VFS to use */
shane626a6e42009-10-22 17:30:15 +00002220 sqlite3_stmt *pStmt; /* Current statement if any. */
drh127f9d72010-02-23 01:47:00 +00002221 FILE *pLog; /* Write log output here */
dana98bf362013-11-13 18:35:01 +00002222 int *aiIndent; /* Array of indents used in MODE_Explain */
2223 int nIndent; /* Size of array aiIndent[] */
danc4650bb2013-11-18 08:41:06 +00002224 int iIndent; /* Index of current op in aiIndent[] */
drhe6229612014-08-18 15:08:26 +00002225#if defined(SQLITE_ENABLE_SESSION)
2226 int nSession; /* Number of active sessions */
2227 OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */
2228#endif
drh75897232000-05-29 14:26:00 +00002229};
2230
2231/*
drh44dec872014-08-30 15:49:25 +00002232** These are the allowed shellFlgs values
2233*/
dan9c1cf322017-08-30 13:21:17 +00002234#define SHFLG_Pagecache 0x00000001 /* The --pagecache option is used */
2235#define SHFLG_Lookaside 0x00000002 /* Lookaside memory is used */
2236#define SHFLG_Backslash 0x00000004 /* The --backslash option is used */
2237#define SHFLG_PreserveRowid 0x00000008 /* .dump preserves rowid values */
2238#define SHFLG_Newlines 0x00000010 /* .dump --newline flag */
2239#define SHFLG_CountChanges 0x00000020 /* .changes setting */
2240#define SHFLG_Echo 0x00000040 /* .echo or --echo setting */
drhe6e1d122017-03-09 13:50:49 +00002241
2242/*
2243** Macros for testing and setting shellFlgs
2244*/
2245#define ShellHasFlag(P,X) (((P)->shellFlgs & (X))!=0)
2246#define ShellSetFlag(P,X) ((P)->shellFlgs|=(X))
2247#define ShellClearFlag(P,X) ((P)->shellFlgs&=(~(X)))
drh44dec872014-08-30 15:49:25 +00002248
2249/*
drh75897232000-05-29 14:26:00 +00002250** These are the allowed modes.
2251*/
drh967e8b72000-06-21 13:59:10 +00002252#define MODE_Line 0 /* One column per line. Blank line between records */
drh75897232000-05-29 14:26:00 +00002253#define MODE_Column 1 /* One record per line in neat columns */
2254#define MODE_List 2 /* One record per line with a separator */
drhe3710332000-09-29 13:30:53 +00002255#define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */
2256#define MODE_Html 4 /* Generate an XHTML table */
2257#define MODE_Insert 5 /* Generate SQL "insert" statements */
drh41f5f6e2016-10-21 17:39:30 +00002258#define MODE_Quote 6 /* Quote values as for SQL */
2259#define MODE_Tcl 7 /* Generate ANSI-C or TCL quoted elements */
2260#define MODE_Csv 8 /* Quote strings, numbers are plain */
2261#define MODE_Explain 9 /* Like MODE_Column, but do not truncate data */
2262#define MODE_Ascii 10 /* Use ASCII unit and record separators (0x1F/0x1E) */
2263#define MODE_Pretty 11 /* Pretty-print schemas */
persicom7e2dfdd2002-04-18 02:46:52 +00002264
drh66ce4d02008-02-15 17:38:06 +00002265static const char *modeDescr[] = {
persicom7e2dfdd2002-04-18 02:46:52 +00002266 "line",
2267 "column",
2268 "list",
2269 "semi",
2270 "html",
drhfeac5f82004-08-01 00:10:45 +00002271 "insert",
drh41f5f6e2016-10-21 17:39:30 +00002272 "quote",
drhfeac5f82004-08-01 00:10:45 +00002273 "tcl",
drh8e64d1c2004-10-07 00:32:39 +00002274 "csv",
drh66ce4d02008-02-15 17:38:06 +00002275 "explain",
mistachkin636bf9f2014-07-19 20:15:16 +00002276 "ascii",
drh4926fec2016-04-13 15:33:42 +00002277 "prettyprint",
persicom7e2dfdd2002-04-18 02:46:52 +00002278};
drh75897232000-05-29 14:26:00 +00002279
2280/*
mistachkinfad42082014-07-24 22:13:12 +00002281** These are the column/row/line separators used by the various
2282** import/export modes.
mistachkin636bf9f2014-07-19 20:15:16 +00002283*/
mistachkinfad42082014-07-24 22:13:12 +00002284#define SEP_Column "|"
2285#define SEP_Row "\n"
2286#define SEP_Tab "\t"
2287#define SEP_Space " "
2288#define SEP_Comma ","
2289#define SEP_CrLf "\r\n"
2290#define SEP_Unit "\x1F"
2291#define SEP_Record "\x1E"
mistachkin636bf9f2014-07-19 20:15:16 +00002292
2293/*
drh75897232000-05-29 14:26:00 +00002294** Number of elements in an array
2295*/
drh902b9ee2008-12-05 17:17:07 +00002296#define ArraySize(X) (int)(sizeof(X)/sizeof(X[0]))
drh75897232000-05-29 14:26:00 +00002297
2298/*
drh127f9d72010-02-23 01:47:00 +00002299** A callback for the sqlite3_log() interface.
2300*/
2301static void shellLog(void *pArg, int iErrCode, const char *zMsg){
drhdcd87a92014-08-18 13:45:42 +00002302 ShellState *p = (ShellState*)pArg;
drh127f9d72010-02-23 01:47:00 +00002303 if( p->pLog==0 ) return;
mistachkinaae280e2015-12-31 19:06:24 +00002304 utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
drh127f9d72010-02-23 01:47:00 +00002305 fflush(p->pLog);
2306}
2307
2308/*
shane626a6e42009-10-22 17:30:15 +00002309** Output the given string as a hex-encoded blob (eg. X'1234' )
2310*/
2311static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
2312 int i;
2313 char *zBlob = (char *)pBlob;
mistachkinaae280e2015-12-31 19:06:24 +00002314 raw_printf(out,"X'");
2315 for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
2316 raw_printf(out,"'");
shane626a6e42009-10-22 17:30:15 +00002317}
2318
2319/*
drh6193d492017-04-07 11:45:58 +00002320** Find a string that is not found anywhere in z[]. Return a pointer
2321** to that string.
2322**
2323** Try to use zA and zB first. If both of those are already found in z[]
2324** then make up some string and store it in the buffer zBuf.
2325*/
2326static const char *unused_string(
2327 const char *z, /* Result must not appear anywhere in z */
2328 const char *zA, const char *zB, /* Try these first */
2329 char *zBuf /* Space to store a generated string */
2330){
2331 unsigned i = 0;
2332 if( strstr(z, zA)==0 ) return zA;
2333 if( strstr(z, zB)==0 ) return zB;
2334 do{
2335 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++);
2336 }while( strstr(z,zBuf)!=0 );
2337 return zBuf;
2338}
2339
2340/*
drh28bd4bc2000-06-15 15:57:22 +00002341** Output the given string as a quoted string using SQL quoting conventions.
drh708b22b2017-03-11 01:56:41 +00002342**
drh13fe1382017-04-08 13:42:55 +00002343** See also: output_quoted_escaped_string()
drh28bd4bc2000-06-15 15:57:22 +00002344*/
2345static void output_quoted_string(FILE *out, const char *z){
2346 int i;
drh708b22b2017-03-11 01:56:41 +00002347 char c;
mistachkin1fe36bb2016-04-04 02:16:44 +00002348 setBinaryMode(out, 1);
drh13fe1382017-04-08 13:42:55 +00002349 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
2350 if( c==0 ){
2351 utf8_printf(out,"'%s'",z);
2352 }else{
2353 raw_printf(out, "'");
2354 while( *z ){
2355 for(i=0; (c = z[i])!=0 && c!='\''; i++){}
2356 if( c=='\'' ) i++;
2357 if( i ){
2358 utf8_printf(out, "%.*s", i, z);
2359 z += i;
2360 }
2361 if( c=='\'' ){
2362 raw_printf(out, "'");
2363 continue;
2364 }
2365 if( c==0 ){
2366 break;
2367 }
2368 z++;
2369 }
2370 raw_printf(out, "'");
2371 }
2372 setTextMode(out, 1);
2373}
2374
2375/*
2376** Output the given string as a quoted string using SQL quoting conventions.
2377** Additionallly , escape the "\n" and "\r" characters so that they do not
2378** get corrupted by end-of-line translation facilities in some operating
2379** systems.
2380**
2381** This is like output_quoted_string() but with the addition of the \r\n
2382** escape mechanism.
2383*/
2384static void output_quoted_escaped_string(FILE *out, const char *z){
2385 int i;
2386 char c;
2387 setBinaryMode(out, 1);
drh708b22b2017-03-11 01:56:41 +00002388 for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
2389 if( c==0 ){
drhe05461c2015-12-30 13:36:57 +00002390 utf8_printf(out,"'%s'",z);
drh28bd4bc2000-06-15 15:57:22 +00002391 }else{
drh6193d492017-04-07 11:45:58 +00002392 const char *zNL = 0;
2393 const char *zCR = 0;
2394 int nNL = 0;
2395 int nCR = 0;
2396 char zBuf1[20], zBuf2[20];
2397 for(i=0; z[i]; i++){
2398 if( z[i]=='\n' ) nNL++;
2399 if( z[i]=='\r' ) nCR++;
2400 }
2401 if( nNL ){
2402 raw_printf(out, "replace(");
2403 zNL = unused_string(z, "\\n", "\\012", zBuf1);
2404 }
2405 if( nCR ){
2406 raw_printf(out, "replace(");
2407 zCR = unused_string(z, "\\r", "\\015", zBuf2);
2408 }
2409 raw_printf(out, "'");
drh28bd4bc2000-06-15 15:57:22 +00002410 while( *z ){
drh708b22b2017-03-11 01:56:41 +00002411 for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
2412 if( c=='\'' ) i++;
2413 if( i ){
drh708b22b2017-03-11 01:56:41 +00002414 utf8_printf(out, "%.*s", i, z);
2415 z += i;
drh708b22b2017-03-11 01:56:41 +00002416 }
2417 if( c=='\'' ){
2418 raw_printf(out, "'");
2419 continue;
2420 }
drh708b22b2017-03-11 01:56:41 +00002421 if( c==0 ){
drh28bd4bc2000-06-15 15:57:22 +00002422 break;
2423 }
drh6193d492017-04-07 11:45:58 +00002424 z++;
2425 if( c=='\n' ){
2426 raw_printf(out, "%s", zNL);
2427 continue;
drh708b22b2017-03-11 01:56:41 +00002428 }
drh6193d492017-04-07 11:45:58 +00002429 raw_printf(out, "%s", zCR);
drh28bd4bc2000-06-15 15:57:22 +00002430 }
drh6193d492017-04-07 11:45:58 +00002431 raw_printf(out, "'");
2432 if( nCR ){
2433 raw_printf(out, ",'%s',char(13))", zCR);
2434 }
2435 if( nNL ){
2436 raw_printf(out, ",'%s',char(10))", zNL);
2437 }
drh28bd4bc2000-06-15 15:57:22 +00002438 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002439 setTextMode(out, 1);
drh28bd4bc2000-06-15 15:57:22 +00002440}
2441
2442/*
drhfeac5f82004-08-01 00:10:45 +00002443** Output the given string as a quoted according to C or TCL quoting rules.
2444*/
2445static void output_c_string(FILE *out, const char *z){
2446 unsigned int c;
2447 fputc('"', out);
2448 while( (c = *(z++))!=0 ){
2449 if( c=='\\' ){
2450 fputc(c, out);
2451 fputc(c, out);
mistachkin585dcb22012-12-04 00:23:43 +00002452 }else if( c=='"' ){
2453 fputc('\\', out);
2454 fputc('"', out);
drhfeac5f82004-08-01 00:10:45 +00002455 }else if( c=='\t' ){
2456 fputc('\\', out);
2457 fputc('t', out);
2458 }else if( c=='\n' ){
2459 fputc('\\', out);
2460 fputc('n', out);
2461 }else if( c=='\r' ){
2462 fputc('\\', out);
2463 fputc('r', out);
mistachkinf6418892013-08-28 01:54:12 +00002464 }else if( !isprint(c&0xff) ){
mistachkinaae280e2015-12-31 19:06:24 +00002465 raw_printf(out, "\\%03o", c&0xff);
drhfeac5f82004-08-01 00:10:45 +00002466 }else{
2467 fputc(c, out);
2468 }
2469 }
2470 fputc('"', out);
2471}
2472
2473/*
drhc08a4f12000-06-15 16:49:48 +00002474** Output the given string with characters that are special to
2475** HTML escaped.
2476*/
2477static void output_html_string(FILE *out, const char *z){
2478 int i;
drhc3d6ba42014-01-13 20:38:35 +00002479 if( z==0 ) z = "";
drhc08a4f12000-06-15 16:49:48 +00002480 while( *z ){
mistachkin1fe36bb2016-04-04 02:16:44 +00002481 for(i=0; z[i]
2482 && z[i]!='<'
2483 && z[i]!='&'
2484 && z[i]!='>'
2485 && z[i]!='\"'
shane43d9cb22009-10-21 14:11:48 +00002486 && z[i]!='\'';
2487 i++){}
drhc08a4f12000-06-15 16:49:48 +00002488 if( i>0 ){
drhe05461c2015-12-30 13:36:57 +00002489 utf8_printf(out,"%.*s",i,z);
drhc08a4f12000-06-15 16:49:48 +00002490 }
2491 if( z[i]=='<' ){
mistachkinaae280e2015-12-31 19:06:24 +00002492 raw_printf(out,"&lt;");
drhc08a4f12000-06-15 16:49:48 +00002493 }else if( z[i]=='&' ){
mistachkinaae280e2015-12-31 19:06:24 +00002494 raw_printf(out,"&amp;");
shane43d9cb22009-10-21 14:11:48 +00002495 }else if( z[i]=='>' ){
mistachkinaae280e2015-12-31 19:06:24 +00002496 raw_printf(out,"&gt;");
shane43d9cb22009-10-21 14:11:48 +00002497 }else if( z[i]=='\"' ){
mistachkinaae280e2015-12-31 19:06:24 +00002498 raw_printf(out,"&quot;");
shane43d9cb22009-10-21 14:11:48 +00002499 }else if( z[i]=='\'' ){
mistachkinaae280e2015-12-31 19:06:24 +00002500 raw_printf(out,"&#39;");
drhc08a4f12000-06-15 16:49:48 +00002501 }else{
2502 break;
2503 }
2504 z += i + 1;
2505 }
2506}
2507
2508/*
drhc49f44e2006-10-26 18:15:42 +00002509** If a field contains any character identified by a 1 in the following
2510** array, then the string must be quoted for CSV.
2511*/
2512static const char needCsvQuote[] = {
mistachkin1fe36bb2016-04-04 02:16:44 +00002513 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2514 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2515 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
2516 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2517 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2518 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2519 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2520 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
2521 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2522 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2523 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2526 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2527 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2528 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
drhc49f44e2006-10-26 18:15:42 +00002529};
2530
2531/*
mistachkindd11f2d2014-12-11 04:49:46 +00002532** Output a single term of CSV. Actually, p->colSeparator is used for
mistachkin44b99f72014-12-11 03:29:14 +00002533** the separator, which may or may not be a comma. p->nullValue is
drh6976c212014-07-24 12:09:47 +00002534** the null value. Strings are quoted if necessary. The separator
2535** is only issued if bSep is true.
drh8e64d1c2004-10-07 00:32:39 +00002536*/
drhdcd87a92014-08-18 13:45:42 +00002537static void output_csv(ShellState *p, const char *z, int bSep){
drhc49f44e2006-10-26 18:15:42 +00002538 FILE *out = p->out;
drh8e64d1c2004-10-07 00:32:39 +00002539 if( z==0 ){
drhe05461c2015-12-30 13:36:57 +00002540 utf8_printf(out,"%s",p->nullValue);
drh8e64d1c2004-10-07 00:32:39 +00002541 }else{
drhc49f44e2006-10-26 18:15:42 +00002542 int i;
mistachkin636bf9f2014-07-19 20:15:16 +00002543 int nSep = strlen30(p->colSeparator);
drhc49f44e2006-10-26 18:15:42 +00002544 for(i=0; z[i]; i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00002545 if( needCsvQuote[((unsigned char*)z)[i]]
2546 || (z[i]==p->colSeparator[0] &&
mistachkin636bf9f2014-07-19 20:15:16 +00002547 (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
drhc49f44e2006-10-26 18:15:42 +00002548 i = 0;
2549 break;
2550 }
2551 }
2552 if( i==0 ){
2553 putc('"', out);
2554 for(i=0; z[i]; i++){
2555 if( z[i]=='"' ) putc('"', out);
2556 putc(z[i], out);
2557 }
2558 putc('"', out);
2559 }else{
drhe05461c2015-12-30 13:36:57 +00002560 utf8_printf(out, "%s", z);
drhc49f44e2006-10-26 18:15:42 +00002561 }
drh8e64d1c2004-10-07 00:32:39 +00002562 }
2563 if( bSep ){
drhe05461c2015-12-30 13:36:57 +00002564 utf8_printf(p->out, "%s", p->colSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002565 }
2566}
2567
danielk19774af00c62005-01-23 23:43:21 +00002568#ifdef SIGINT
drh8e64d1c2004-10-07 00:32:39 +00002569/*
drh4c504392000-10-16 22:06:40 +00002570** This routine runs when the user presses Ctrl-C
2571*/
2572static void interrupt_handler(int NotUsed){
drh902b9ee2008-12-05 17:17:07 +00002573 UNUSED_PARAMETER(NotUsed);
drh43ae8f62014-05-23 12:03:47 +00002574 seenInterrupt++;
2575 if( seenInterrupt>2 ) exit(1);
mistachkin8e189222015-04-19 21:43:16 +00002576 if( globalDb ) sqlite3_interrupt(globalDb);
drh4c504392000-10-16 22:06:40 +00002577}
danielk19774af00c62005-01-23 23:43:21 +00002578#endif
drh4c504392000-10-16 22:06:40 +00002579
drha0daa752016-09-16 11:53:10 +00002580#ifndef SQLITE_OMIT_AUTHORIZATION
drh4c504392000-10-16 22:06:40 +00002581/*
drhde613c62016-04-04 17:23:10 +00002582** When the ".auth ON" is set, the following authorizer callback is
2583** invoked. It always returns SQLITE_OK.
2584*/
2585static int shellAuth(
2586 void *pClientData,
2587 int op,
2588 const char *zA1,
2589 const char *zA2,
2590 const char *zA3,
2591 const char *zA4
2592){
2593 ShellState *p = (ShellState*)pClientData;
2594 static const char *azAction[] = { 0,
2595 "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX",
2596 "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW",
2597 "CREATE_TRIGGER", "CREATE_VIEW", "DELETE",
2598 "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX",
2599 "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW",
2600 "DROP_TRIGGER", "DROP_VIEW", "INSERT",
2601 "PRAGMA", "READ", "SELECT",
2602 "TRANSACTION", "UPDATE", "ATTACH",
2603 "DETACH", "ALTER_TABLE", "REINDEX",
2604 "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE",
2605 "FUNCTION", "SAVEPOINT", "RECURSIVE"
2606 };
2607 int i;
2608 const char *az[4];
2609 az[0] = zA1;
2610 az[1] = zA2;
2611 az[2] = zA3;
2612 az[3] = zA4;
mistachkin8145fc62016-09-16 20:39:21 +00002613 utf8_printf(p->out, "authorizer: %s", azAction[op]);
drhde613c62016-04-04 17:23:10 +00002614 for(i=0; i<4; i++){
2615 raw_printf(p->out, " ");
2616 if( az[i] ){
2617 output_c_string(p->out, az[i]);
2618 }else{
2619 raw_printf(p->out, "NULL");
2620 }
2621 }
2622 raw_printf(p->out, "\n");
2623 return SQLITE_OK;
2624}
drha0daa752016-09-16 11:53:10 +00002625#endif
mistachkin8145fc62016-09-16 20:39:21 +00002626
drh79f20e92016-12-13 23:22:39 +00002627/*
2628** Print a schema statement. Part of MODE_Semi and MODE_Pretty output.
2629**
2630** This routine converts some CREATE TABLE statements for shadow tables
2631** in FTS3/4/5 into CREATE TABLE IF NOT EXISTS statements.
2632*/
2633static void printSchemaLine(FILE *out, const char *z, const char *zTail){
2634 if( sqlite3_strglob("CREATE TABLE ['\"]*", z)==0 ){
2635 utf8_printf(out, "CREATE TABLE IF NOT EXISTS %s%s", z+13, zTail);
2636 }else{
2637 utf8_printf(out, "%s%s", z, zTail);
2638 }
2639}
2640static void printSchemaLineN(FILE *out, char *z, int n, const char *zTail){
2641 char c = z[n];
2642 z[n] = 0;
2643 printSchemaLine(out, z, zTail);
2644 z[n] = c;
2645}
drhde613c62016-04-04 17:23:10 +00002646
2647/*
shane626a6e42009-10-22 17:30:15 +00002648** This is the callback routine that the shell
drh75897232000-05-29 14:26:00 +00002649** invokes for each row of a query result.
2650*/
drh4ace5362014-11-10 14:42:28 +00002651static int shell_callback(
2652 void *pArg,
2653 int nArg, /* Number of result columns */
2654 char **azArg, /* Text of each result column */
2655 char **azCol, /* Column names */
2656 int *aiType /* Column types */
2657){
drh75897232000-05-29 14:26:00 +00002658 int i;
drhdcd87a92014-08-18 13:45:42 +00002659 ShellState *p = (ShellState*)pArg;
shaneb9fc17d2009-10-22 21:23:35 +00002660
drh20554382017-08-28 11:12:57 +00002661 if( azArg==0 ) return 0;
drh700c2522016-02-09 18:39:25 +00002662 switch( p->cMode ){
drh75897232000-05-29 14:26:00 +00002663 case MODE_Line: {
drhe3710332000-09-29 13:30:53 +00002664 int w = 5;
drh6a535342001-10-19 16:44:56 +00002665 if( azArg==0 ) break;
drhe3710332000-09-29 13:30:53 +00002666 for(i=0; i<nArg; i++){
drh4f21c4a2008-12-10 22:15:00 +00002667 int len = strlen30(azCol[i] ? azCol[i] : "");
drhe3710332000-09-29 13:30:53 +00002668 if( len>w ) w = len;
2669 }
drhe05461c2015-12-30 13:36:57 +00002670 if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
drh75897232000-05-29 14:26:00 +00002671 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002672 utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
mistachkin44b99f72014-12-11 03:29:14 +00002673 azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
drh75897232000-05-29 14:26:00 +00002674 }
2675 break;
2676 }
danielk19770d78bae2008-01-03 07:09:48 +00002677 case MODE_Explain:
drh75897232000-05-29 14:26:00 +00002678 case MODE_Column: {
drh700c2522016-02-09 18:39:25 +00002679 static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
2680 const int *colWidth;
2681 int showHdr;
2682 char *rowSep;
2683 if( p->cMode==MODE_Column ){
2684 colWidth = p->colWidth;
2685 showHdr = p->showHeader;
2686 rowSep = p->rowSeparator;
2687 }else{
2688 colWidth = aExplainWidths;
2689 showHdr = 1;
mistachkin6d945552016-02-09 20:31:50 +00002690 rowSep = SEP_Row;
drh700c2522016-02-09 18:39:25 +00002691 }
drha0c66f52000-07-29 13:20:21 +00002692 if( p->cnt++==0 ){
drh75897232000-05-29 14:26:00 +00002693 for(i=0; i<nArg; i++){
drha0c66f52000-07-29 13:20:21 +00002694 int w, n;
2695 if( i<ArraySize(p->colWidth) ){
drh700c2522016-02-09 18:39:25 +00002696 w = colWidth[i];
drh75897232000-05-29 14:26:00 +00002697 }else{
danielk19770d78bae2008-01-03 07:09:48 +00002698 w = 0;
drh75897232000-05-29 14:26:00 +00002699 }
drh078b1fd2012-09-21 13:40:02 +00002700 if( w==0 ){
drh64bf76d2017-06-05 12:29:26 +00002701 w = strlenChar(azCol[i] ? azCol[i] : "");
drha0c66f52000-07-29 13:20:21 +00002702 if( w<10 ) w = 10;
drh64bf76d2017-06-05 12:29:26 +00002703 n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
drha0c66f52000-07-29 13:20:21 +00002704 if( w<n ) w = n;
2705 }
2706 if( i<ArraySize(p->actualWidth) ){
persicom1d0b8722002-04-18 02:53:04 +00002707 p->actualWidth[i] = w;
drha0c66f52000-07-29 13:20:21 +00002708 }
drh700c2522016-02-09 18:39:25 +00002709 if( showHdr ){
drh6887e8f2017-04-17 13:18:42 +00002710 utf8_width_print(p->out, w, azCol[i]);
2711 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00002712 }
2713 }
drh700c2522016-02-09 18:39:25 +00002714 if( showHdr ){
drha0c66f52000-07-29 13:20:21 +00002715 for(i=0; i<nArg; i++){
2716 int w;
2717 if( i<ArraySize(p->actualWidth) ){
2718 w = p->actualWidth[i];
drh078b1fd2012-09-21 13:40:02 +00002719 if( w<0 ) w = -w;
drha0c66f52000-07-29 13:20:21 +00002720 }else{
2721 w = 10;
2722 }
mistachkinaae280e2015-12-31 19:06:24 +00002723 utf8_printf(p->out,"%-*.*s%s",w,w,
drhe05461c2015-12-30 13:36:57 +00002724 "----------------------------------------------------------"
drha0c66f52000-07-29 13:20:21 +00002725 "----------------------------------------------------------",
drh700c2522016-02-09 18:39:25 +00002726 i==nArg-1 ? rowSep : " ");
drha0c66f52000-07-29 13:20:21 +00002727 }
drh75897232000-05-29 14:26:00 +00002728 }
2729 }
drh6a535342001-10-19 16:44:56 +00002730 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002731 for(i=0; i<nArg; i++){
2732 int w;
drha0c66f52000-07-29 13:20:21 +00002733 if( i<ArraySize(p->actualWidth) ){
2734 w = p->actualWidth[i];
drh75897232000-05-29 14:26:00 +00002735 }else{
2736 w = 10;
2737 }
drh64bf76d2017-06-05 12:29:26 +00002738 if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
2739 w = strlenChar(azArg[i]);
danielk19770d78bae2008-01-03 07:09:48 +00002740 }
dana98bf362013-11-13 18:35:01 +00002741 if( i==1 && p->aiIndent && p->pStmt ){
danc4650bb2013-11-18 08:41:06 +00002742 if( p->iIndent<p->nIndent ){
mistachkinaae280e2015-12-31 19:06:24 +00002743 utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
dana98bf362013-11-13 18:35:01 +00002744 }
danc4650bb2013-11-18 08:41:06 +00002745 p->iIndent++;
dana98bf362013-11-13 18:35:01 +00002746 }
drh6887e8f2017-04-17 13:18:42 +00002747 utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
2748 utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : " ");
drh75897232000-05-29 14:26:00 +00002749 }
2750 break;
2751 }
drh4926fec2016-04-13 15:33:42 +00002752 case MODE_Semi: { /* .schema and .fullschema output */
drh79f20e92016-12-13 23:22:39 +00002753 printSchemaLine(p->out, azArg[0], ";\n");
drh4926fec2016-04-13 15:33:42 +00002754 break;
2755 }
2756 case MODE_Pretty: { /* .schema and .fullschema with --indent */
2757 char *z;
drh07d683f2016-04-13 21:00:36 +00002758 int j;
drh4926fec2016-04-13 15:33:42 +00002759 int nParen = 0;
2760 char cEnd = 0;
2761 char c;
2762 int nLine = 0;
2763 assert( nArg==1 );
2764 if( azArg[0]==0 ) break;
2765 if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
2766 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
2767 ){
2768 utf8_printf(p->out, "%s;\n", azArg[0]);
2769 break;
2770 }
2771 z = sqlite3_mprintf("%s", azArg[0]);
2772 j = 0;
2773 for(i=0; IsSpace(z[i]); i++){}
2774 for(; (c = z[i])!=0; i++){
2775 if( IsSpace(c) ){
drhc3cbd672017-10-05 19:12:10 +00002776 if( z[j-1]=='\r' ) z[j-1] = '\n';
drh4926fec2016-04-13 15:33:42 +00002777 if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
2778 }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
2779 j--;
2780 }
2781 z[j++] = c;
2782 }
2783 while( j>0 && IsSpace(z[j-1]) ){ j--; }
2784 z[j] = 0;
2785 if( strlen30(z)>=79 ){
drh07d683f2016-04-13 21:00:36 +00002786 for(i=j=0; (c = z[i])!=0; i++){
drh4926fec2016-04-13 15:33:42 +00002787 if( c==cEnd ){
2788 cEnd = 0;
2789 }else if( c=='"' || c=='\'' || c=='`' ){
2790 cEnd = c;
2791 }else if( c=='[' ){
2792 cEnd = ']';
2793 }else if( c=='(' ){
2794 nParen++;
2795 }else if( c==')' ){
2796 nParen--;
2797 if( nLine>0 && nParen==0 && j>0 ){
drh79f20e92016-12-13 23:22:39 +00002798 printSchemaLineN(p->out, z, j, "\n");
drh4926fec2016-04-13 15:33:42 +00002799 j = 0;
2800 }
2801 }
2802 z[j++] = c;
2803 if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
2804 if( c=='\n' ) j--;
drh79f20e92016-12-13 23:22:39 +00002805 printSchemaLineN(p->out, z, j, "\n ");
drh4926fec2016-04-13 15:33:42 +00002806 j = 0;
2807 nLine++;
2808 while( IsSpace(z[i+1]) ){ i++; }
2809 }
2810 }
2811 z[j] = 0;
2812 }
drh79f20e92016-12-13 23:22:39 +00002813 printSchemaLine(p->out, z, ";\n");
drh4926fec2016-04-13 15:33:42 +00002814 sqlite3_free(z);
2815 break;
2816 }
drh75897232000-05-29 14:26:00 +00002817 case MODE_List: {
2818 if( p->cnt++==0 && p->showHeader ){
2819 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002820 utf8_printf(p->out,"%s%s",azCol[i],
mistachkin636bf9f2014-07-19 20:15:16 +00002821 i==nArg-1 ? p->rowSeparator : p->colSeparator);
drh75897232000-05-29 14:26:00 +00002822 }
2823 }
drh6a535342001-10-19 16:44:56 +00002824 if( azArg==0 ) break;
drh75897232000-05-29 14:26:00 +00002825 for(i=0; i<nArg; i++){
drh4c653a02000-06-07 01:27:47 +00002826 char *z = azArg[i];
mistachkin44b99f72014-12-11 03:29:14 +00002827 if( z==0 ) z = p->nullValue;
drhe05461c2015-12-30 13:36:57 +00002828 utf8_printf(p->out, "%s", z);
drhe3710332000-09-29 13:30:53 +00002829 if( i<nArg-1 ){
drhe05461c2015-12-30 13:36:57 +00002830 utf8_printf(p->out, "%s", p->colSeparator);
drhe3710332000-09-29 13:30:53 +00002831 }else{
drhe05461c2015-12-30 13:36:57 +00002832 utf8_printf(p->out, "%s", p->rowSeparator);
drhe3710332000-09-29 13:30:53 +00002833 }
drh75897232000-05-29 14:26:00 +00002834 }
2835 break;
2836 }
drh1e5d0e92000-05-31 23:33:17 +00002837 case MODE_Html: {
2838 if( p->cnt++==0 && p->showHeader ){
mistachkinaae280e2015-12-31 19:06:24 +00002839 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002840 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002841 raw_printf(p->out,"<TH>");
shane43d9cb22009-10-21 14:11:48 +00002842 output_html_string(p->out, azCol[i]);
mistachkinaae280e2015-12-31 19:06:24 +00002843 raw_printf(p->out,"</TH>\n");
drh1e5d0e92000-05-31 23:33:17 +00002844 }
mistachkinaae280e2015-12-31 19:06:24 +00002845 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002846 }
drh6a535342001-10-19 16:44:56 +00002847 if( azArg==0 ) break;
mistachkinaae280e2015-12-31 19:06:24 +00002848 raw_printf(p->out,"<TR>");
drh1e5d0e92000-05-31 23:33:17 +00002849 for(i=0; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00002850 raw_printf(p->out,"<TD>");
mistachkin44b99f72014-12-11 03:29:14 +00002851 output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00002852 raw_printf(p->out,"</TD>\n");
drh1e5d0e92000-05-31 23:33:17 +00002853 }
mistachkinaae280e2015-12-31 19:06:24 +00002854 raw_printf(p->out,"</TR>\n");
drh1e5d0e92000-05-31 23:33:17 +00002855 break;
2856 }
drhfeac5f82004-08-01 00:10:45 +00002857 case MODE_Tcl: {
2858 if( p->cnt++==0 && p->showHeader ){
2859 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002860 output_c_string(p->out,azCol[i] ? azCol[i] : "");
drhe05461c2015-12-30 13:36:57 +00002861 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002862 }
drhe05461c2015-12-30 13:36:57 +00002863 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002864 }
2865 if( azArg==0 ) break;
2866 for(i=0; i<nArg; i++){
mistachkin44b99f72014-12-11 03:29:14 +00002867 output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
drhe05461c2015-12-30 13:36:57 +00002868 if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00002869 }
drhe05461c2015-12-30 13:36:57 +00002870 utf8_printf(p->out, "%s", p->rowSeparator);
drhfeac5f82004-08-01 00:10:45 +00002871 break;
2872 }
drh8e64d1c2004-10-07 00:32:39 +00002873 case MODE_Csv: {
mistachkin1fe36bb2016-04-04 02:16:44 +00002874 setBinaryMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002875 if( p->cnt++==0 && p->showHeader ){
2876 for(i=0; i<nArg; i++){
drh2cc55692006-06-27 20:39:04 +00002877 output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
drh8e64d1c2004-10-07 00:32:39 +00002878 }
drhe05461c2015-12-30 13:36:57 +00002879 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002880 }
drh40253262014-10-17 21:35:05 +00002881 if( nArg>0 ){
drh6976c212014-07-24 12:09:47 +00002882 for(i=0; i<nArg; i++){
2883 output_csv(p, azArg[i], i<nArg-1);
2884 }
drhe05461c2015-12-30 13:36:57 +00002885 utf8_printf(p->out, "%s", p->rowSeparator);
drh8e64d1c2004-10-07 00:32:39 +00002886 }
mistachkin1fe36bb2016-04-04 02:16:44 +00002887 setTextMode(p->out, 1);
drh8e64d1c2004-10-07 00:32:39 +00002888 break;
2889 }
drh28bd4bc2000-06-15 15:57:22 +00002890 case MODE_Insert: {
drh6a535342001-10-19 16:44:56 +00002891 if( azArg==0 ) break;
drh13fe1382017-04-08 13:42:55 +00002892 utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
2893 if( p->showHeader ){
2894 raw_printf(p->out,"(");
2895 for(i=0; i<nArg; i++){
2896 if( i>0 ) raw_printf(p->out, ",");
2897 if( quoteChar(azCol[i]) ){
2898 char *z = sqlite3_mprintf("\"%w\"", azCol[i]);
2899 utf8_printf(p->out, "%s", z);
2900 sqlite3_free(z);
2901 }else{
2902 raw_printf(p->out, "%s", azCol[i]);
drh41f5f6e2016-10-21 17:39:30 +00002903 }
mistachkin151c75a2015-04-07 21:16:40 +00002904 }
drh13fe1382017-04-08 13:42:55 +00002905 raw_printf(p->out,")");
2906 }
2907 p->cnt++;
2908 for(i=0; i<nArg; i++){
2909 raw_printf(p->out, i>0 ? "," : " VALUES(");
2910 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
2911 utf8_printf(p->out,"NULL");
2912 }else if( aiType && aiType[i]==SQLITE_TEXT ){
drhdbc26722017-07-10 18:04:41 +00002913 if( ShellHasFlag(p, SHFLG_Newlines) ){
2914 output_quoted_string(p->out, azArg[i]);
2915 }else{
2916 output_quoted_escaped_string(p->out, azArg[i]);
2917 }
drh13fe1382017-04-08 13:42:55 +00002918 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
2919 utf8_printf(p->out,"%s", azArg[i]);
2920 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2921 char z[50];
2922 double r = sqlite3_column_double(p->pStmt, i);
2923 sqlite3_snprintf(50,z,"%!.20g", r);
2924 raw_printf(p->out, "%s", z);
2925 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2926 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2927 int nBlob = sqlite3_column_bytes(p->pStmt, i);
2928 output_hex_blob(p->out, pBlob, nBlob);
2929 }else if( isNumber(azArg[i], 0) ){
2930 utf8_printf(p->out,"%s", azArg[i]);
drhdbc26722017-07-10 18:04:41 +00002931 }else if( ShellHasFlag(p, SHFLG_Newlines) ){
2932 output_quoted_string(p->out, azArg[i]);
drh13fe1382017-04-08 13:42:55 +00002933 }else{
2934 output_quoted_escaped_string(p->out, azArg[i]);
2935 }
2936 }
2937 raw_printf(p->out,");\n");
2938 break;
2939 }
2940 case MODE_Quote: {
2941 if( azArg==0 ) break;
2942 if( p->cnt==0 && p->showHeader ){
drh59ce2c42016-11-03 13:12:28 +00002943 for(i=0; i<nArg; i++){
mistachkin2f9a6132016-11-11 05:19:45 +00002944 if( i>0 ) raw_printf(p->out, ",");
drh59ce2c42016-11-03 13:12:28 +00002945 output_quoted_string(p->out, azCol[i]);
2946 }
mistachkin2f9a6132016-11-11 05:19:45 +00002947 raw_printf(p->out,"\n");
mistachkin151c75a2015-04-07 21:16:40 +00002948 }
drh59ce2c42016-11-03 13:12:28 +00002949 p->cnt++;
drh28bd4bc2000-06-15 15:57:22 +00002950 for(i=0; i<nArg; i++){
drh13fe1382017-04-08 13:42:55 +00002951 if( i>0 ) raw_printf(p->out, ",");
shanead6b8d02009-10-22 18:12:58 +00002952 if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
drh13fe1382017-04-08 13:42:55 +00002953 utf8_printf(p->out,"NULL");
shanead6b8d02009-10-22 18:12:58 +00002954 }else if( aiType && aiType[i]==SQLITE_TEXT ){
shanead6b8d02009-10-22 18:12:58 +00002955 output_quoted_string(p->out, azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002956 }else if( aiType && aiType[i]==SQLITE_INTEGER ){
drh13fe1382017-04-08 13:42:55 +00002957 utf8_printf(p->out,"%s", azArg[i]);
drh891d6b42017-03-11 00:46:57 +00002958 }else if( aiType && aiType[i]==SQLITE_FLOAT ){
2959 char z[50];
2960 double r = sqlite3_column_double(p->pStmt, i);
2961 sqlite3_snprintf(50,z,"%!.20g", r);
drh13fe1382017-04-08 13:42:55 +00002962 raw_printf(p->out, "%s", z);
shane626a6e42009-10-22 17:30:15 +00002963 }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
2964 const void *pBlob = sqlite3_column_blob(p->pStmt, i);
2965 int nBlob = sqlite3_column_bytes(p->pStmt, i);
shane626a6e42009-10-22 17:30:15 +00002966 output_hex_blob(p->out, pBlob, nBlob);
drhc8d74412004-08-31 23:41:26 +00002967 }else if( isNumber(azArg[i], 0) ){
drh13fe1382017-04-08 13:42:55 +00002968 utf8_printf(p->out,"%s", azArg[i]);
drh28bd4bc2000-06-15 15:57:22 +00002969 }else{
drh28bd4bc2000-06-15 15:57:22 +00002970 output_quoted_string(p->out, azArg[i]);
2971 }
2972 }
drh13fe1382017-04-08 13:42:55 +00002973 raw_printf(p->out,"\n");
drh6a535342001-10-19 16:44:56 +00002974 break;
drh28bd4bc2000-06-15 15:57:22 +00002975 }
mistachkin636bf9f2014-07-19 20:15:16 +00002976 case MODE_Ascii: {
2977 if( p->cnt++==0 && p->showHeader ){
2978 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002979 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2980 utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
mistachkin636bf9f2014-07-19 20:15:16 +00002981 }
drhe05461c2015-12-30 13:36:57 +00002982 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002983 }
2984 if( azArg==0 ) break;
2985 for(i=0; i<nArg; i++){
drhe05461c2015-12-30 13:36:57 +00002986 if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
2987 utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
mistachkin636bf9f2014-07-19 20:15:16 +00002988 }
drhe05461c2015-12-30 13:36:57 +00002989 utf8_printf(p->out, "%s", p->rowSeparator);
mistachkin636bf9f2014-07-19 20:15:16 +00002990 break;
2991 }
persicom1d0b8722002-04-18 02:53:04 +00002992 }
drh75897232000-05-29 14:26:00 +00002993 return 0;
2994}
2995
2996/*
shane626a6e42009-10-22 17:30:15 +00002997** This is the callback routine that the SQLite library
2998** invokes for each row of a query result.
2999*/
3000static int callback(void *pArg, int nArg, char **azArg, char **azCol){
3001 /* since we don't have type info, call the shell_callback with a NULL value */
3002 return shell_callback(pArg, nArg, azArg, azCol, NULL);
3003}
3004
drhfb546af2017-03-09 22:00:33 +00003005/*
3006** This is the callback routine from sqlite3_exec() that appends all
3007** output onto the end of a ShellText object.
3008*/
3009static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
3010 ShellText *p = (ShellText*)pArg;
3011 int i;
drh2fb79e92017-03-25 12:08:11 +00003012 UNUSED_PARAMETER(az);
drh20554382017-08-28 11:12:57 +00003013 if( azArg==0 ) return 0;
drhfb546af2017-03-09 22:00:33 +00003014 if( p->n ) appendText(p, "|", 0);
3015 for(i=0; i<nArg; i++){
3016 if( i ) appendText(p, ",", 0);
3017 if( azArg[i] ) appendText(p, azArg[i], 0);
3018 }
3019 return 0;
3020}
3021
3022/*
3023** Generate an appropriate SELFTEST table in the main database.
3024*/
3025static void createSelftestTable(ShellState *p){
drhf157d102017-03-10 01:05:38 +00003026 char *zErrMsg = 0;
drhfb546af2017-03-09 22:00:33 +00003027 sqlite3_exec(p->db,
drhf157d102017-03-10 01:05:38 +00003028 "SAVEPOINT selftest_init;\n"
3029 "CREATE TABLE IF NOT EXISTS selftest(\n"
drhfb546af2017-03-09 22:00:33 +00003030 " tno INTEGER PRIMARY KEY,\n" /* Test number */
3031 " op TEXT,\n" /* Operator: memo run */
3032 " cmd TEXT,\n" /* Command text */
3033 " ans TEXT\n" /* Desired answer */
3034 ");"
drhf157d102017-03-10 01:05:38 +00003035 "CREATE TEMP TABLE [_shell$self](op,cmd,ans);\n"
3036 "INSERT INTO [_shell$self](rowid,op,cmd)\n"
3037 " VALUES(coalesce((SELECT (max(tno)+100)/10 FROM selftest),10),\n"
3038 " 'memo','Tests generated by --init');\n"
3039 "INSERT INTO [_shell$self]\n"
3040 " SELECT 'run',\n"
3041 " 'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
3042 "FROM sqlite_master ORDER BY 2'',224))',\n"
3043 " hex(sha3_query('SELECT type,name,tbl_name,sql "
3044 "FROM sqlite_master ORDER BY 2',224));\n"
3045 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00003046 " SELECT 'run',"
3047 " 'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
3048 " printf('%w',name) || '\" NOT INDEXED'',224))',\n"
3049 " hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
3050 " FROM (\n"
3051 " SELECT name FROM sqlite_master\n"
3052 " WHERE type='table'\n"
3053 " AND name<>'selftest'\n"
3054 " AND coalesce(rootpage,0)>0\n"
3055 " )\n"
3056 " ORDER BY name;\n"
drhf157d102017-03-10 01:05:38 +00003057 "INSERT INTO [_shell$self]\n"
drhfb546af2017-03-09 22:00:33 +00003058 " VALUES('run','PRAGMA integrity_check','ok');\n"
drhf157d102017-03-10 01:05:38 +00003059 "INSERT INTO selftest(tno,op,cmd,ans)"
3060 " SELECT rowid*10,op,cmd,ans FROM [_shell$self];\n"
3061 "DROP TABLE [_shell$self];"
3062 ,0,0,&zErrMsg);
3063 if( zErrMsg ){
3064 utf8_printf(stderr, "SELFTEST initialization failure: %s\n", zErrMsg);
3065 sqlite3_free(zErrMsg);
3066 }
3067 sqlite3_exec(p->db, "RELEASE selftest_init",0,0,0);
drhfb546af2017-03-09 22:00:33 +00003068}
3069
drhf42d3182017-03-08 12:25:18 +00003070
shane626a6e42009-10-22 17:30:15 +00003071/*
drhdcd87a92014-08-18 13:45:42 +00003072** Set the destination table field of the ShellState structure to
drh33048c02001-10-01 14:29:22 +00003073** the name of the table given. Escape any quote characters in the
3074** table name.
3075*/
drhdcd87a92014-08-18 13:45:42 +00003076static void set_table_name(ShellState *p, const char *zName){
drh33048c02001-10-01 14:29:22 +00003077 int i, n;
mistachkin2158a0c2017-09-09 00:51:36 +00003078 char cQuote;
drh33048c02001-10-01 14:29:22 +00003079 char *z;
3080
3081 if( p->zDestTable ){
3082 free(p->zDestTable);
3083 p->zDestTable = 0;
3084 }
3085 if( zName==0 ) return;
drhf42d3182017-03-08 12:25:18 +00003086 cQuote = quoteChar(zName);
3087 n = strlen30(zName);
drh45e7d7d2017-06-24 13:31:40 +00003088 if( cQuote ) n += n+2;
drh33048c02001-10-01 14:29:22 +00003089 z = p->zDestTable = malloc( n+1 );
3090 if( z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003091 raw_printf(stderr,"Error: out of memory\n");
drh33048c02001-10-01 14:29:22 +00003092 exit(1);
3093 }
3094 n = 0;
drhf42d3182017-03-08 12:25:18 +00003095 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00003096 for(i=0; zName[i]; i++){
3097 z[n++] = zName[i];
drhf42d3182017-03-08 12:25:18 +00003098 if( zName[i]==cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00003099 }
drhf42d3182017-03-08 12:25:18 +00003100 if( cQuote ) z[n++] = cQuote;
drh33048c02001-10-01 14:29:22 +00003101 z[n] = 0;
3102}
3103
drhdd3d4592004-08-30 01:54:05 +00003104
3105/*
drhb21a8e42012-01-28 21:08:51 +00003106** Execute a query statement that will generate SQL output. Print
3107** the result columns, comma-separated, on a line and then add a
3108** semicolon terminator to the end of that line.
drh45e29d82006-11-20 16:21:10 +00003109**
drhb21a8e42012-01-28 21:08:51 +00003110** If the number of columns is 1 and that column contains text "--"
mistachkin1fe36bb2016-04-04 02:16:44 +00003111** then write the semicolon on a separate line. That way, if a
drhb21a8e42012-01-28 21:08:51 +00003112** "--" comment occurs at the end of the statement, the comment
3113** won't consume the semicolon terminator.
drhdd3d4592004-08-30 01:54:05 +00003114*/
drh157e29a2009-05-21 15:15:00 +00003115static int run_table_dump_query(
drhdcd87a92014-08-18 13:45:42 +00003116 ShellState *p, /* Query context */
drh2f464a02011-10-13 00:41:49 +00003117 const char *zSelect, /* SELECT statement to extract content */
3118 const char *zFirstRow /* Print before first row, if not NULL */
drh157e29a2009-05-21 15:15:00 +00003119){
drhdd3d4592004-08-30 01:54:05 +00003120 sqlite3_stmt *pSelect;
3121 int rc;
drhb21a8e42012-01-28 21:08:51 +00003122 int nResult;
3123 int i;
3124 const char *z;
drhc7181902014-02-27 15:04:13 +00003125 rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
drhdd3d4592004-08-30 01:54:05 +00003126 if( rc!=SQLITE_OK || !pSelect ){
mistachkinaae280e2015-12-31 19:06:24 +00003127 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
3128 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00003129 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drhdd3d4592004-08-30 01:54:05 +00003130 return rc;
3131 }
3132 rc = sqlite3_step(pSelect);
drhb21a8e42012-01-28 21:08:51 +00003133 nResult = sqlite3_column_count(pSelect);
drhdd3d4592004-08-30 01:54:05 +00003134 while( rc==SQLITE_ROW ){
drh157e29a2009-05-21 15:15:00 +00003135 if( zFirstRow ){
drhe05461c2015-12-30 13:36:57 +00003136 utf8_printf(p->out, "%s", zFirstRow);
drh157e29a2009-05-21 15:15:00 +00003137 zFirstRow = 0;
3138 }
drhb21a8e42012-01-28 21:08:51 +00003139 z = (const char*)sqlite3_column_text(pSelect, 0);
drhe05461c2015-12-30 13:36:57 +00003140 utf8_printf(p->out, "%s", z);
mistachkin1fe36bb2016-04-04 02:16:44 +00003141 for(i=1; i<nResult; i++){
drhe05461c2015-12-30 13:36:57 +00003142 utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
drhb21a8e42012-01-28 21:08:51 +00003143 }
3144 if( z==0 ) z = "";
3145 while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
3146 if( z[0] ){
mistachkinaae280e2015-12-31 19:06:24 +00003147 raw_printf(p->out, "\n;\n");
drhb21a8e42012-01-28 21:08:51 +00003148 }else{
mistachkinaae280e2015-12-31 19:06:24 +00003149 raw_printf(p->out, ";\n");
mistachkin1fe36bb2016-04-04 02:16:44 +00003150 }
drhdd3d4592004-08-30 01:54:05 +00003151 rc = sqlite3_step(pSelect);
3152 }
drh2f464a02011-10-13 00:41:49 +00003153 rc = sqlite3_finalize(pSelect);
3154 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00003155 utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
3156 sqlite3_errmsg(p->db));
drh4384e982013-10-01 15:30:05 +00003157 if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
drh2f464a02011-10-13 00:41:49 +00003158 }
3159 return rc;
drhdd3d4592004-08-30 01:54:05 +00003160}
3161
shane626a6e42009-10-22 17:30:15 +00003162/*
3163** Allocate space and save off current error string.
3164*/
3165static char *save_err_msg(
3166 sqlite3 *db /* Database to query */
3167){
3168 int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
drhf3cdcdc2015-04-29 16:50:28 +00003169 char *zErrMsg = sqlite3_malloc64(nErrMsg);
shane626a6e42009-10-22 17:30:15 +00003170 if( zErrMsg ){
3171 memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
3172 }
3173 return zErrMsg;
3174}
3175
drh34784902016-02-27 17:12:36 +00003176#ifdef __linux__
3177/*
3178** Attempt to display I/O stats on Linux using /proc/PID/io
3179*/
3180static void displayLinuxIoStats(FILE *out){
3181 FILE *in;
3182 char z[200];
3183 sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
3184 in = fopen(z, "rb");
3185 if( in==0 ) return;
3186 while( fgets(z, sizeof(z), in)!=0 ){
3187 static const struct {
3188 const char *zPattern;
3189 const char *zDesc;
3190 } aTrans[] = {
drhfc1a84c2016-02-27 19:19:22 +00003191 { "rchar: ", "Bytes received by read():" },
3192 { "wchar: ", "Bytes sent to write():" },
3193 { "syscr: ", "Read() system calls:" },
3194 { "syscw: ", "Write() system calls:" },
3195 { "read_bytes: ", "Bytes read from storage:" },
3196 { "write_bytes: ", "Bytes written to storage:" },
3197 { "cancelled_write_bytes: ", "Cancelled write bytes:" },
drh34784902016-02-27 17:12:36 +00003198 };
3199 int i;
3200 for(i=0; i<ArraySize(aTrans); i++){
3201 int n = (int)strlen(aTrans[i].zPattern);
3202 if( strncmp(aTrans[i].zPattern, z, n)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00003203 utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
drh34784902016-02-27 17:12:36 +00003204 break;
3205 }
3206 }
3207 }
3208 fclose(in);
mistachkin1fe36bb2016-04-04 02:16:44 +00003209}
drh34784902016-02-27 17:12:36 +00003210#endif
3211
drha2df53b2017-03-10 14:36:10 +00003212/*
3213** Display a single line of status using 64-bit values.
3214*/
3215static void displayStatLine(
3216 ShellState *p, /* The shell context */
3217 char *zLabel, /* Label for this one line */
3218 char *zFormat, /* Format for the result */
3219 int iStatusCtrl, /* Which status to display */
3220 int bReset /* True to reset the stats */
3221){
3222 sqlite3_int64 iCur = -1;
3223 sqlite3_int64 iHiwtr = -1;
3224 int i, nPercent;
3225 char zLine[200];
3226 sqlite3_status64(iStatusCtrl, &iCur, &iHiwtr, bReset);
3227 for(i=0, nPercent=0; zFormat[i]; i++){
3228 if( zFormat[i]=='%' ) nPercent++;
3229 }
3230 if( nPercent>1 ){
3231 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iCur, iHiwtr);
3232 }else{
3233 sqlite3_snprintf(sizeof(zLine), zLine, zFormat, iHiwtr);
3234 }
3235 raw_printf(p->out, "%-36s %s\n", zLabel, zLine);
3236}
drh34784902016-02-27 17:12:36 +00003237
shane626a6e42009-10-22 17:30:15 +00003238/*
shaneh642d8b82010-07-28 16:05:34 +00003239** Display memory stats.
3240*/
3241static int display_stats(
3242 sqlite3 *db, /* Database to query */
drhdcd87a92014-08-18 13:45:42 +00003243 ShellState *pArg, /* Pointer to ShellState */
shaneh642d8b82010-07-28 16:05:34 +00003244 int bReset /* True to reset the stats */
3245){
3246 int iCur;
3247 int iHiwtr;
3248
3249 if( pArg && pArg->out ){
drha2df53b2017-03-10 14:36:10 +00003250 displayStatLine(pArg, "Memory Used:",
3251 "%lld (max %lld) bytes", SQLITE_STATUS_MEMORY_USED, bReset);
3252 displayStatLine(pArg, "Number of Outstanding Allocations:",
3253 "%lld (max %lld)", SQLITE_STATUS_MALLOC_COUNT, bReset);
drh44dec872014-08-30 15:49:25 +00003254 if( pArg->shellFlgs & SHFLG_Pagecache ){
drha2df53b2017-03-10 14:36:10 +00003255 displayStatLine(pArg, "Number of Pcache Pages Used:",
3256 "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
drh44dec872014-08-30 15:49:25 +00003257 }
drha2df53b2017-03-10 14:36:10 +00003258 displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
3259 "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
drha2df53b2017-03-10 14:36:10 +00003260 displayStatLine(pArg, "Largest Allocation:",
3261 "%lld bytes", SQLITE_STATUS_MALLOC_SIZE, bReset);
3262 displayStatLine(pArg, "Largest Pcache Allocation:",
3263 "%lld bytes", SQLITE_STATUS_PAGECACHE_SIZE, bReset);
shaneh642d8b82010-07-28 16:05:34 +00003264#ifdef YYTRACKMAXSTACKDEPTH
drha2df53b2017-03-10 14:36:10 +00003265 displayStatLine(pArg, "Deepest Parser Stack:",
3266 "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
shaneh642d8b82010-07-28 16:05:34 +00003267#endif
3268 }
3269
3270 if( pArg && pArg->out && db ){
drh44dec872014-08-30 15:49:25 +00003271 if( pArg->shellFlgs & SHFLG_Lookaside ){
3272 iHiwtr = iCur = -1;
drh4ace5362014-11-10 14:42:28 +00003273 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
3274 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003275 raw_printf(pArg->out,
3276 "Lookaside Slots Used: %d (max %d)\n",
drh4ace5362014-11-10 14:42:28 +00003277 iCur, iHiwtr);
3278 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
3279 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003280 raw_printf(pArg->out, "Successful lookaside attempts: %d\n",
3281 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00003282 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
3283 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003284 raw_printf(pArg->out, "Lookaside failures due to size: %d\n",
3285 iHiwtr);
drh4ace5362014-11-10 14:42:28 +00003286 sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
3287 &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003288 raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n",
3289 iHiwtr);
drh44dec872014-08-30 15:49:25 +00003290 }
shaneh642d8b82010-07-28 16:05:34 +00003291 iHiwtr = iCur = -1;
3292 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003293 raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n",
3294 iCur);
drh4ace5362014-11-10 14:42:28 +00003295 iHiwtr = iCur = -1;
drhc78e6e42011-09-23 18:58:23 +00003296 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
mistachkinaae280e2015-12-31 19:06:24 +00003297 raw_printf(pArg->out, "Page cache hits: %d\n", iCur);
drhc78e6e42011-09-23 18:58:23 +00003298 iHiwtr = iCur = -1;
3299 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00003300 raw_printf(pArg->out, "Page cache misses: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00003301 iHiwtr = iCur = -1;
drhfbbcd5d2012-03-24 20:09:33 +00003302 sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
mistachkin1fe36bb2016-04-04 02:16:44 +00003303 raw_printf(pArg->out, "Page cache writes: %d\n", iCur);
drhfbbcd5d2012-03-24 20:09:33 +00003304 iHiwtr = iCur = -1;
shaneh642d8b82010-07-28 16:05:34 +00003305 sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003306 raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00003307 iCur);
shaneh642d8b82010-07-28 16:05:34 +00003308 iHiwtr = iCur = -1;
3309 sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003310 raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n",
mistachkin1fe36bb2016-04-04 02:16:44 +00003311 iCur);
shaneh642d8b82010-07-28 16:05:34 +00003312 }
3313
3314 if( pArg && pArg->out && db && pArg->pStmt ){
drh4ace5362014-11-10 14:42:28 +00003315 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
3316 bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003317 raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00003318 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003319 raw_printf(pArg->out, "Sort Operations: %d\n", iCur);
drh4ace5362014-11-10 14:42:28 +00003320 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003321 raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur);
drhbf159fa2013-06-25 22:01:22 +00003322 iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
mistachkinaae280e2015-12-31 19:06:24 +00003323 raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur);
shaneh642d8b82010-07-28 16:05:34 +00003324 }
3325
drh34784902016-02-27 17:12:36 +00003326#ifdef __linux__
3327 displayLinuxIoStats(pArg->out);
3328#endif
3329
dan5a790282015-08-07 20:06:14 +00003330 /* Do not remove this machine readable comment: extra-stats-output-here */
3331
shaneh642d8b82010-07-28 16:05:34 +00003332 return 0;
3333}
3334
3335/*
dan8d1edb92014-11-05 09:07:28 +00003336** Display scan stats.
3337*/
3338static void display_scanstats(
3339 sqlite3 *db, /* Database to query */
3340 ShellState *pArg /* Pointer to ShellState */
3341){
drhf5ed7ad2015-06-15 14:43:25 +00003342#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
3343 UNUSED_PARAMETER(db);
3344 UNUSED_PARAMETER(pArg);
3345#else
drh15f23c22014-11-06 12:46:16 +00003346 int i, k, n, mx;
mistachkinaae280e2015-12-31 19:06:24 +00003347 raw_printf(pArg->out, "-------- scanstats --------\n");
drh15f23c22014-11-06 12:46:16 +00003348 mx = 0;
3349 for(k=0; k<=mx; k++){
drh42f30bc2014-11-06 12:08:21 +00003350 double rEstLoop = 1.0;
3351 for(i=n=0; 1; i++){
3352 sqlite3_stmt *p = pArg->pStmt;
3353 sqlite3_int64 nLoop, nVisit;
3354 double rEst;
3355 int iSid;
3356 const char *zExplain;
3357 if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
3358 break;
3359 }
3360 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
drh15f23c22014-11-06 12:46:16 +00003361 if( iSid>mx ) mx = iSid;
drh42f30bc2014-11-06 12:08:21 +00003362 if( iSid!=k ) continue;
drh179bac32014-11-06 12:17:24 +00003363 if( n==0 ){
3364 rEstLoop = (double)nLoop;
mistachkinaae280e2015-12-31 19:06:24 +00003365 if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
drh179bac32014-11-06 12:17:24 +00003366 }
drh42f30bc2014-11-06 12:08:21 +00003367 n++;
3368 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
3369 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
3370 sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
drhe05461c2015-12-30 13:36:57 +00003371 utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
drh42f30bc2014-11-06 12:08:21 +00003372 rEstLoop *= rEst;
mistachkin1fe36bb2016-04-04 02:16:44 +00003373 raw_printf(pArg->out,
drh4ace5362014-11-10 14:42:28 +00003374 " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
drh9a06d302014-11-07 13:52:44 +00003375 nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
drh42f30bc2014-11-06 12:08:21 +00003376 );
dan8d1edb92014-11-05 09:07:28 +00003377 }
dan8d1edb92014-11-05 09:07:28 +00003378 }
mistachkinaae280e2015-12-31 19:06:24 +00003379 raw_printf(pArg->out, "---------------------------\n");
drh15f23c22014-11-06 12:46:16 +00003380#endif
dan8d1edb92014-11-05 09:07:28 +00003381}
3382
3383/*
dana98bf362013-11-13 18:35:01 +00003384** Parameter azArray points to a zero-terminated array of strings. zStr
3385** points to a single nul-terminated string. Return non-zero if zStr
3386** is equal, according to strcmp(), to any of the strings in the array.
3387** Otherwise, return zero.
3388*/
3389static int str_in_array(const char *zStr, const char **azArray){
3390 int i;
3391 for(i=0; azArray[i]; i++){
3392 if( 0==strcmp(zStr, azArray[i]) ) return 1;
3393 }
3394 return 0;
3395}
3396
3397/*
3398** If compiled statement pSql appears to be an EXPLAIN statement, allocate
drhdcd87a92014-08-18 13:45:42 +00003399** and populate the ShellState.aiIndent[] array with the number of
mistachkin1fe36bb2016-04-04 02:16:44 +00003400** spaces each opcode should be indented before it is output.
dana98bf362013-11-13 18:35:01 +00003401**
3402** The indenting rules are:
3403**
3404** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
3405** all opcodes that occur between the p2 jump destination and the opcode
3406** itself by 2 spaces.
3407**
drh01752bc2013-11-14 23:59:33 +00003408** * For each "Goto", if the jump destination is earlier in the program
3409** and ends on one of:
drhe73f0592014-01-21 22:25:45 +00003410** Yield SeekGt SeekLt RowSetRead Rewind
drhfe705102014-03-06 13:38:37 +00003411** or if the P1 parameter is one instead of zero,
drh01752bc2013-11-14 23:59:33 +00003412** then indent all opcodes between the earlier instruction
drhd2447442013-11-13 19:01:41 +00003413** and "Goto" by 2 spaces.
dana98bf362013-11-13 18:35:01 +00003414*/
drhdcd87a92014-08-18 13:45:42 +00003415static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
dana98bf362013-11-13 18:35:01 +00003416 const char *zSql; /* The text of the SQL statement */
3417 const char *z; /* Used to check if this is an EXPLAIN */
3418 int *abYield = 0; /* True if op is an OP_Yield */
3419 int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */
danc4650bb2013-11-18 08:41:06 +00003420 int iOp; /* Index of operation in p->aiIndent[] */
dana98bf362013-11-13 18:35:01 +00003421
drh8ad0de32014-03-20 18:45:27 +00003422 const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
3423 "NextIfOpen", "PrevIfOpen", 0 };
drh4ace5362014-11-10 14:42:28 +00003424 const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
3425 "Rewind", 0 };
dana98bf362013-11-13 18:35:01 +00003426 const char *azGoto[] = { "Goto", 0 };
3427
3428 /* Try to figure out if this is really an EXPLAIN statement. If this
3429 ** cannot be verified, return early. */
drh87a24aa2016-02-09 20:04:07 +00003430 if( sqlite3_column_count(pSql)!=8 ){
3431 p->cMode = p->mode;
3432 return;
3433 }
dana98bf362013-11-13 18:35:01 +00003434 zSql = sqlite3_sql(pSql);
3435 if( zSql==0 ) return;
3436 for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
drh87a24aa2016-02-09 20:04:07 +00003437 if( sqlite3_strnicmp(z, "explain", 7) ){
3438 p->cMode = p->mode;
3439 return;
3440 }
dana98bf362013-11-13 18:35:01 +00003441
3442 for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
3443 int i;
danc4650bb2013-11-18 08:41:06 +00003444 int iAddr = sqlite3_column_int(pSql, 0);
dana98bf362013-11-13 18:35:01 +00003445 const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
danc4650bb2013-11-18 08:41:06 +00003446
3447 /* Set p2 to the P2 field of the current opcode. Then, assuming that
3448 ** p2 is an instruction address, set variable p2op to the index of that
3449 ** instruction in the aiIndent[] array. p2 and p2op may be different if
3450 ** the current instruction is part of a sub-program generated by an
3451 ** SQL trigger or foreign key. */
dana98bf362013-11-13 18:35:01 +00003452 int p2 = sqlite3_column_int(pSql, 3);
danc4650bb2013-11-18 08:41:06 +00003453 int p2op = (p2 + (iOp-iAddr));
dana98bf362013-11-13 18:35:01 +00003454
3455 /* Grow the p->aiIndent array as required */
3456 if( iOp>=nAlloc ){
drh87a24aa2016-02-09 20:04:07 +00003457 if( iOp==0 ){
3458 /* Do further verfication that this is explain output. Abort if
3459 ** it is not */
3460 static const char *explainCols[] = {
3461 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
3462 int jj;
3463 for(jj=0; jj<ArraySize(explainCols); jj++){
3464 if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
3465 p->cMode = p->mode;
3466 sqlite3_reset(pSql);
3467 return;
3468 }
3469 }
3470 }
dana98bf362013-11-13 18:35:01 +00003471 nAlloc += 100;
drhf3cdcdc2015-04-29 16:50:28 +00003472 p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
3473 abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
dana98bf362013-11-13 18:35:01 +00003474 }
3475 abYield[iOp] = str_in_array(zOp, azYield);
3476 p->aiIndent[iOp] = 0;
3477 p->nIndent = iOp+1;
3478
3479 if( str_in_array(zOp, azNext) ){
danc4650bb2013-11-18 08:41:06 +00003480 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00003481 }
drhfe705102014-03-06 13:38:37 +00003482 if( str_in_array(zOp, azGoto) && p2op<p->nIndent
3483 && (abYield[p2op] || sqlite3_column_int(pSql, 2))
3484 ){
drheacd29d2016-04-15 15:03:27 +00003485 for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
dana98bf362013-11-13 18:35:01 +00003486 }
3487 }
3488
danc4650bb2013-11-18 08:41:06 +00003489 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00003490 sqlite3_free(abYield);
3491 sqlite3_reset(pSql);
3492}
3493
3494/*
3495** Free the array allocated by explain_data_prepare().
3496*/
drhdcd87a92014-08-18 13:45:42 +00003497static void explain_data_delete(ShellState *p){
dana98bf362013-11-13 18:35:01 +00003498 sqlite3_free(p->aiIndent);
3499 p->aiIndent = 0;
3500 p->nIndent = 0;
danc4650bb2013-11-18 08:41:06 +00003501 p->iIndent = 0;
dana98bf362013-11-13 18:35:01 +00003502}
3503
3504/*
drheacd29d2016-04-15 15:03:27 +00003505** Disable and restore .wheretrace and .selecttrace settings.
3506*/
3507#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
3508extern int sqlite3SelectTrace;
3509static int savedSelectTrace;
3510#endif
3511#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
3512extern int sqlite3WhereTrace;
3513static int savedWhereTrace;
3514#endif
3515static void disable_debug_trace_modes(void){
3516#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
3517 savedSelectTrace = sqlite3SelectTrace;
3518 sqlite3SelectTrace = 0;
3519#endif
3520#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
3521 savedWhereTrace = sqlite3WhereTrace;
3522 sqlite3WhereTrace = 0;
3523#endif
3524}
3525static void restore_debug_trace_modes(void){
3526#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
3527 sqlite3SelectTrace = savedSelectTrace;
3528#endif
3529#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
3530 sqlite3WhereTrace = savedWhereTrace;
3531#endif
3532}
3533
3534/*
3535** Run a prepared statement
3536*/
3537static void exec_prepared_stmt(
3538 ShellState *pArg, /* Pointer to ShellState */
3539 sqlite3_stmt *pStmt, /* Statment to run */
3540 int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */
3541){
3542 int rc;
3543
3544 /* perform the first step. this will tell us if we
3545 ** have a result set or not and how wide it is.
3546 */
3547 rc = sqlite3_step(pStmt);
3548 /* if we have a result set... */
3549 if( SQLITE_ROW == rc ){
3550 /* if we have a callback... */
3551 if( xCallback ){
3552 /* allocate space for col name ptr, value ptr, and type */
3553 int nCol = sqlite3_column_count(pStmt);
3554 void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1);
3555 if( !pData ){
3556 rc = SQLITE_NOMEM;
3557 }else{
3558 char **azCols = (char **)pData; /* Names of result columns */
3559 char **azVals = &azCols[nCol]; /* Results */
3560 int *aiTypes = (int *)&azVals[nCol]; /* Result types */
3561 int i, x;
3562 assert(sizeof(int) <= sizeof(char *));
3563 /* save off ptrs to column names */
3564 for(i=0; i<nCol; i++){
3565 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
3566 }
3567 do{
3568 /* extract the data and data types */
3569 for(i=0; i<nCol; i++){
3570 aiTypes[i] = x = sqlite3_column_type(pStmt, i);
3571 if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
3572 azVals[i] = "";
3573 }else{
3574 azVals[i] = (char*)sqlite3_column_text(pStmt, i);
3575 }
3576 if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
3577 rc = SQLITE_NOMEM;
3578 break; /* from for */
3579 }
3580 } /* end for */
3581
3582 /* if data and types extracted successfully... */
3583 if( SQLITE_ROW == rc ){
3584 /* call the supplied callback with the result row data */
3585 if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
3586 rc = SQLITE_ABORT;
3587 }else{
3588 rc = sqlite3_step(pStmt);
3589 }
3590 }
3591 } while( SQLITE_ROW == rc );
3592 sqlite3_free(pData);
3593 }
3594 }else{
3595 do{
3596 rc = sqlite3_step(pStmt);
3597 } while( rc == SQLITE_ROW );
3598 }
3599 }
3600}
3601
3602/*
mistachkin1fe36bb2016-04-04 02:16:44 +00003603** Execute a statement or set of statements. Print
3604** any result rows/columns depending on the current mode
shane626a6e42009-10-22 17:30:15 +00003605** set via the supplied callback.
3606**
mistachkin1fe36bb2016-04-04 02:16:44 +00003607** This is very similar to SQLite's built-in sqlite3_exec()
3608** function except it takes a slightly different callback
shane626a6e42009-10-22 17:30:15 +00003609** and callback data argument.
3610*/
3611static int shell_exec(
drhdcd87a92014-08-18 13:45:42 +00003612 sqlite3 *db, /* An open database */
3613 const char *zSql, /* SQL to be evaluated */
shane626a6e42009-10-22 17:30:15 +00003614 int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */
drhdcd87a92014-08-18 13:45:42 +00003615 /* (not the same as sqlite3_exec) */
3616 ShellState *pArg, /* Pointer to ShellState */
3617 char **pzErrMsg /* Error msg written here */
shane626a6e42009-10-22 17:30:15 +00003618){
dan4564ced2010-01-05 04:59:56 +00003619 sqlite3_stmt *pStmt = NULL; /* Statement to execute. */
3620 int rc = SQLITE_OK; /* Return Code */
drhb07028f2011-10-14 21:49:18 +00003621 int rc2;
dan4564ced2010-01-05 04:59:56 +00003622 const char *zLeftover; /* Tail of unprocessed SQL */
shane626a6e42009-10-22 17:30:15 +00003623
3624 if( pzErrMsg ){
3625 *pzErrMsg = NULL;
3626 }
3627
shaneb9fc17d2009-10-22 21:23:35 +00003628 while( zSql[0] && (SQLITE_OK == rc) ){
drheacd29d2016-04-15 15:03:27 +00003629 static const char *zStmtSql;
shaneb9fc17d2009-10-22 21:23:35 +00003630 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
3631 if( SQLITE_OK != rc ){
shane626a6e42009-10-22 17:30:15 +00003632 if( pzErrMsg ){
3633 *pzErrMsg = save_err_msg(db);
3634 }
3635 }else{
shaneb9fc17d2009-10-22 21:23:35 +00003636 if( !pStmt ){
3637 /* this happens for a comment or white-space */
3638 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00003639 while( IsSpace(zSql[0]) ) zSql++;
shaneb9fc17d2009-10-22 21:23:35 +00003640 continue;
3641 }
drheacd29d2016-04-15 15:03:27 +00003642 zStmtSql = sqlite3_sql(pStmt);
drh60275612016-11-03 02:25:30 +00003643 if( zStmtSql==0 ) zStmtSql = "";
drheacd29d2016-04-15 15:03:27 +00003644 while( IsSpace(zStmtSql[0]) ) zStmtSql++;
shane626a6e42009-10-22 17:30:15 +00003645
shaneh642d8b82010-07-28 16:05:34 +00003646 /* save off the prepared statment handle and reset row count */
3647 if( pArg ){
3648 pArg->pStmt = pStmt;
3649 pArg->cnt = 0;
3650 }
3651
shanehb7977c52010-01-18 18:17:10 +00003652 /* echo the sql statement if echo on */
drhe6e1d122017-03-09 13:50:49 +00003653 if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
drhe05461c2015-12-30 13:36:57 +00003654 utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
drha8c62df2010-02-15 15:47:18 +00003655 }
shanehb7977c52010-01-18 18:17:10 +00003656
drhefbf3b12014-02-28 20:47:24 +00003657 /* Show the EXPLAIN QUERY PLAN if .eqp is on */
drheacd29d2016-04-15 15:03:27 +00003658 if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
drhefbf3b12014-02-28 20:47:24 +00003659 sqlite3_stmt *pExplain;
drheacd29d2016-04-15 15:03:27 +00003660 char *zEQP;
3661 disable_debug_trace_modes();
3662 zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
drhefbf3b12014-02-28 20:47:24 +00003663 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3664 if( rc==SQLITE_OK ){
3665 while( sqlite3_step(pExplain)==SQLITE_ROW ){
mistachkinaae280e2015-12-31 19:06:24 +00003666 raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
3667 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
3668 raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
drhe05461c2015-12-30 13:36:57 +00003669 utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
drhefbf3b12014-02-28 20:47:24 +00003670 }
3671 }
3672 sqlite3_finalize(pExplain);
3673 sqlite3_free(zEQP);
drheacd29d2016-04-15 15:03:27 +00003674 if( pArg->autoEQP>=2 ){
3675 /* Also do an EXPLAIN for ".eqp full" mode */
3676 zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
3677 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
3678 if( rc==SQLITE_OK ){
3679 pArg->cMode = MODE_Explain;
3680 explain_data_prepare(pArg, pExplain);
3681 exec_prepared_stmt(pArg, pExplain, xCallback);
3682 explain_data_delete(pArg);
3683 }
3684 sqlite3_finalize(pExplain);
3685 sqlite3_free(zEQP);
3686 }
3687 restore_debug_trace_modes();
drhefbf3b12014-02-28 20:47:24 +00003688 }
3689
drh700c2522016-02-09 18:39:25 +00003690 if( pArg ){
3691 pArg->cMode = pArg->mode;
drh87a24aa2016-02-09 20:04:07 +00003692 if( pArg->autoExplain
3693 && sqlite3_column_count(pStmt)==8
drheacd29d2016-04-15 15:03:27 +00003694 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
drh700c2522016-02-09 18:39:25 +00003695 ){
3696 pArg->cMode = MODE_Explain;
3697 }
mistachkin1fe36bb2016-04-04 02:16:44 +00003698
drh700c2522016-02-09 18:39:25 +00003699 /* If the shell is currently in ".explain" mode, gather the extra
3700 ** data required to add indents to the output.*/
3701 if( pArg->cMode==MODE_Explain ){
3702 explain_data_prepare(pArg, pStmt);
3703 }
dana98bf362013-11-13 18:35:01 +00003704 }
3705
drheacd29d2016-04-15 15:03:27 +00003706 exec_prepared_stmt(pArg, pStmt, xCallback);
dana98bf362013-11-13 18:35:01 +00003707 explain_data_delete(pArg);
3708
shaneh642d8b82010-07-28 16:05:34 +00003709 /* print usage stats if stats on */
3710 if( pArg && pArg->statsOn ){
3711 display_stats(db, pArg, 0);
3712 }
3713
dan8d1edb92014-11-05 09:07:28 +00003714 /* print loop-counters if required */
3715 if( pArg && pArg->scanstatsOn ){
3716 display_scanstats(db, pArg);
3717 }
3718
mistachkin1fe36bb2016-04-04 02:16:44 +00003719 /* Finalize the statement just executed. If this fails, save a
dan4564ced2010-01-05 04:59:56 +00003720 ** copy of the error message. Otherwise, set zSql to point to the
3721 ** next statement to execute. */
drhb07028f2011-10-14 21:49:18 +00003722 rc2 = sqlite3_finalize(pStmt);
3723 if( rc!=SQLITE_NOMEM ) rc = rc2;
dan4564ced2010-01-05 04:59:56 +00003724 if( rc==SQLITE_OK ){
shaneb9fc17d2009-10-22 21:23:35 +00003725 zSql = zLeftover;
drhf0693c82011-10-11 20:41:54 +00003726 while( IsSpace(zSql[0]) ) zSql++;
dan4564ced2010-01-05 04:59:56 +00003727 }else if( pzErrMsg ){
3728 *pzErrMsg = save_err_msg(db);
shane626a6e42009-10-22 17:30:15 +00003729 }
shaneh642d8b82010-07-28 16:05:34 +00003730
3731 /* clear saved stmt handle */
3732 if( pArg ){
3733 pArg->pStmt = NULL;
3734 }
shane626a6e42009-10-22 17:30:15 +00003735 }
shaneb9fc17d2009-10-22 21:23:35 +00003736 } /* end while */
shane626a6e42009-10-22 17:30:15 +00003737
3738 return rc;
3739}
3740
drhe611f142017-03-08 11:44:00 +00003741/*
3742** Release memory previously allocated by tableColumnList().
3743*/
3744static void freeColumnList(char **azCol){
3745 int i;
3746 for(i=1; azCol[i]; i++){
3747 sqlite3_free(azCol[i]);
3748 }
3749 /* azCol[0] is a static string */
3750 sqlite3_free(azCol);
3751}
3752
3753/*
3754** Return a list of pointers to strings which are the names of all
3755** columns in table zTab. The memory to hold the names is dynamically
3756** allocated and must be released by the caller using a subsequent call
3757** to freeColumnList().
3758**
3759** The azCol[0] entry is usually NULL. However, if zTab contains a rowid
3760** value that needs to be preserved, then azCol[0] is filled in with the
3761** name of the rowid column.
3762**
3763** The first regular column in the table is azCol[1]. The list is terminated
3764** by an entry with azCol[i]==0.
3765*/
3766static char **tableColumnList(ShellState *p, const char *zTab){
3767 char **azCol = 0;
3768 sqlite3_stmt *pStmt;
3769 char *zSql;
3770 int nCol = 0;
3771 int nAlloc = 0;
3772 int nPK = 0; /* Number of PRIMARY KEY columns seen */
3773 int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */
drhe6e1d122017-03-09 13:50:49 +00003774 int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
drhe611f142017-03-08 11:44:00 +00003775 int rc;
3776
3777 zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab);
3778 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3779 sqlite3_free(zSql);
3780 if( rc ) return 0;
3781 while( sqlite3_step(pStmt)==SQLITE_ROW ){
3782 if( nCol>=nAlloc-2 ){
3783 nAlloc = nAlloc*2 + nCol + 10;
3784 azCol = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0]));
3785 if( azCol==0 ){
3786 raw_printf(stderr, "Error: out of memory\n");
3787 exit(1);
3788 }
3789 }
3790 azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1));
3791 if( sqlite3_column_int(pStmt, 5) ){
3792 nPK++;
3793 if( nPK==1
3794 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2),
mistachkine16a3502017-05-29 03:48:13 +00003795 "INTEGER")==0
drhe611f142017-03-08 11:44:00 +00003796 ){
3797 isIPK = 1;
3798 }else{
3799 isIPK = 0;
3800 }
3801 }
3802 }
3803 sqlite3_finalize(pStmt);
3804 azCol[0] = 0;
3805 azCol[nCol+1] = 0;
3806
3807 /* The decision of whether or not a rowid really needs to be preserved
3808 ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table
3809 ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve
3810 ** rowids on tables where the rowid is inaccessible because there are other
3811 ** columns in the table named "rowid", "_rowid_", and "oid".
3812 */
3813 if( preserveRowid && isIPK ){
3814 /* If a single PRIMARY KEY column with type INTEGER was seen, then it
3815 ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID
3816 ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
3817 ** ROWID aliases. To distinguish these cases, check to see if
3818 ** there is a "pk" entry in "PRAGMA index_list". There will be
3819 ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
3820 */
3821 zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
3822 " WHERE origin='pk'", zTab);
3823 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
3824 sqlite3_free(zSql);
3825 if( rc ){
3826 freeColumnList(azCol);
3827 return 0;
3828 }
3829 rc = sqlite3_step(pStmt);
3830 sqlite3_finalize(pStmt);
3831 preserveRowid = rc==SQLITE_ROW;
3832 }
3833 if( preserveRowid ){
3834 /* Only preserve the rowid if we can find a name to use for the
3835 ** rowid */
3836 static char *azRowid[] = { "rowid", "_rowid_", "oid" };
3837 int i, j;
3838 for(j=0; j<3; j++){
3839 for(i=1; i<=nCol; i++){
3840 if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
3841 }
3842 if( i>nCol ){
3843 /* At this point, we know that azRowid[j] is not the name of any
3844 ** ordinary column in the table. Verify that azRowid[j] is a valid
3845 ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID
3846 ** tables will fail this last check */
drhe611f142017-03-08 11:44:00 +00003847 rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
3848 if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
3849 break;
3850 }
3851 }
3852 }
3853 return azCol;
3854}
3855
drh33048c02001-10-01 14:29:22 +00003856/*
drhf8563c02017-03-09 18:13:52 +00003857** Toggle the reverse_unordered_selects setting.
3858*/
3859static void toggleSelectOrder(sqlite3 *db){
3860 sqlite3_stmt *pStmt = 0;
3861 int iSetting = 0;
3862 char zStmt[100];
3863 sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
3864 if( sqlite3_step(pStmt)==SQLITE_ROW ){
3865 iSetting = sqlite3_column_int(pStmt, 0);
3866 }
3867 sqlite3_finalize(pStmt);
3868 sqlite3_snprintf(sizeof(zStmt), zStmt,
3869 "PRAGMA reverse_unordered_selects(%d)", !iSetting);
3870 sqlite3_exec(db, zStmt, 0, 0, 0);
3871}
3872
3873/*
drh4c653a02000-06-07 01:27:47 +00003874** This is a different callback routine used for dumping the database.
3875** Each row received by this callback consists of a table name,
3876** the table type ("index" or "table") and SQL to create the table.
3877** This routine should print text sufficient to recreate the table.
3878*/
drh701ff6a2017-03-22 12:51:34 +00003879static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
danielk19772a02e332004-06-05 08:04:36 +00003880 int rc;
3881 const char *zTable;
3882 const char *zType;
3883 const char *zSql;
drhdcd87a92014-08-18 13:45:42 +00003884 ShellState *p = (ShellState *)pArg;
danielk19772a02e332004-06-05 08:04:36 +00003885
drh701ff6a2017-03-22 12:51:34 +00003886 UNUSED_PARAMETER(azNotUsed);
drh20554382017-08-28 11:12:57 +00003887 if( nArg!=3 || azArg==0 ) return 0;
danielk19772a02e332004-06-05 08:04:36 +00003888 zTable = azArg[0];
3889 zType = azArg[1];
3890 zSql = azArg[2];
mistachkin1fe36bb2016-04-04 02:16:44 +00003891
drh00b950d2005-09-11 02:03:03 +00003892 if( strcmp(zTable, "sqlite_sequence")==0 ){
drhe611f142017-03-08 11:44:00 +00003893 raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
drh7ed10322013-08-07 16:04:27 +00003894 }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00003895 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh00b950d2005-09-11 02:03:03 +00003896 }else if( strncmp(zTable, "sqlite_", 7)==0 ){
3897 return 0;
drh45e29d82006-11-20 16:21:10 +00003898 }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
3899 char *zIns;
3900 if( !p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00003901 raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
drh45e29d82006-11-20 16:21:10 +00003902 p->writableSchema = 1;
3903 }
3904 zIns = sqlite3_mprintf(
3905 "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
3906 "VALUES('table','%q','%q',0,'%q');",
3907 zTable, zTable, zSql);
drhe05461c2015-12-30 13:36:57 +00003908 utf8_printf(p->out, "%s\n", zIns);
drh45e29d82006-11-20 16:21:10 +00003909 sqlite3_free(zIns);
3910 return 0;
drh00b950d2005-09-11 02:03:03 +00003911 }else{
drh79f20e92016-12-13 23:22:39 +00003912 printSchemaLine(p->out, zSql, ";\n");
drhf8eb96a2005-02-03 00:42:34 +00003913 }
danielk19772a02e332004-06-05 08:04:36 +00003914
3915 if( strcmp(zType, "table")==0 ){
drhf42d3182017-03-08 12:25:18 +00003916 ShellText sSelect;
3917 ShellText sTable;
drhe611f142017-03-08 11:44:00 +00003918 char **azCol;
3919 int i;
3920 char *savedDestTable;
3921 int savedMode;
mistachkin1fe36bb2016-04-04 02:16:44 +00003922
drhe611f142017-03-08 11:44:00 +00003923 azCol = tableColumnList(p, zTable);
3924 if( azCol==0 ){
3925 p->nErr++;
3926 return 0;
danielk19772a02e332004-06-05 08:04:36 +00003927 }
3928
drhbf92ec02012-03-22 12:50:34 +00003929 /* Always quote the table name, even if it appears to be pure ascii,
3930 ** in case it is a keyword. Ex: INSERT INTO "table" ... */
drhf42d3182017-03-08 12:25:18 +00003931 initText(&sTable);
3932 appendText(&sTable, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003933 /* If preserving the rowid, add a column list after the table name.
3934 ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
3935 ** instead of the usual "INSERT INTO tab VALUES(...)".
3936 */
3937 if( azCol[0] ){
3938 appendText(&sTable, "(", 0);
3939 appendText(&sTable, azCol[0], 0);
3940 for(i=1; azCol[i]; i++){
3941 appendText(&sTable, ",", 0);
drhf42d3182017-03-08 12:25:18 +00003942 appendText(&sTable, azCol[i], quoteChar(azCol[i]));
danielk19772a02e332004-06-05 08:04:36 +00003943 }
drhe611f142017-03-08 11:44:00 +00003944 appendText(&sTable, ")", 0);
danielk19772a02e332004-06-05 08:04:36 +00003945 }
danielk19772a02e332004-06-05 08:04:36 +00003946
drhe611f142017-03-08 11:44:00 +00003947 /* Build an appropriate SELECT statement */
drhf42d3182017-03-08 12:25:18 +00003948 initText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003949 appendText(&sSelect, "SELECT ", 0);
3950 if( azCol[0] ){
3951 appendText(&sSelect, azCol[0], 0);
3952 appendText(&sSelect, ",", 0);
drhdd3d4592004-08-30 01:54:05 +00003953 }
drhe611f142017-03-08 11:44:00 +00003954 for(i=1; azCol[i]; i++){
drhf42d3182017-03-08 12:25:18 +00003955 appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
drhe611f142017-03-08 11:44:00 +00003956 if( azCol[i+1] ){
3957 appendText(&sSelect, ",", 0);
3958 }
3959 }
3960 freeColumnList(azCol);
3961 appendText(&sSelect, " FROM ", 0);
drhf42d3182017-03-08 12:25:18 +00003962 appendText(&sSelect, zTable, quoteChar(zTable));
drhe611f142017-03-08 11:44:00 +00003963
3964 savedDestTable = p->zDestTable;
3965 savedMode = p->mode;
3966 p->zDestTable = sTable.z;
3967 p->mode = p->cMode = MODE_Insert;
3968 rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
drhf8563c02017-03-09 18:13:52 +00003969 if( (rc&0xff)==SQLITE_CORRUPT ){
3970 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
3971 toggleSelectOrder(p->db);
3972 shell_exec(p->db, sSelect.z, shell_callback, p, 0);
3973 toggleSelectOrder(p->db);
3974 }
drhe611f142017-03-08 11:44:00 +00003975 p->zDestTable = savedDestTable;
3976 p->mode = savedMode;
drhf42d3182017-03-08 12:25:18 +00003977 freeText(&sTable);
3978 freeText(&sSelect);
drhe611f142017-03-08 11:44:00 +00003979 if( rc ) p->nErr++;
drh4c653a02000-06-07 01:27:47 +00003980 }
drh4c653a02000-06-07 01:27:47 +00003981 return 0;
3982}
3983
3984/*
drh45e29d82006-11-20 16:21:10 +00003985** Run zQuery. Use dump_callback() as the callback routine so that
3986** the contents of the query are output as SQL statements.
3987**
drhdd3d4592004-08-30 01:54:05 +00003988** If we get a SQLITE_CORRUPT error, rerun the query after appending
3989** "ORDER BY rowid DESC" to the end.
3990*/
3991static int run_schema_dump_query(
mistachkin1fe36bb2016-04-04 02:16:44 +00003992 ShellState *p,
drh2f464a02011-10-13 00:41:49 +00003993 const char *zQuery
drhdd3d4592004-08-30 01:54:05 +00003994){
3995 int rc;
drh2f464a02011-10-13 00:41:49 +00003996 char *zErr = 0;
3997 rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
drhdd3d4592004-08-30 01:54:05 +00003998 if( rc==SQLITE_CORRUPT ){
3999 char *zQ2;
drh4f21c4a2008-12-10 22:15:00 +00004000 int len = strlen30(zQuery);
mistachkinaae280e2015-12-31 19:06:24 +00004001 raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
drh2f464a02011-10-13 00:41:49 +00004002 if( zErr ){
mistachkinaae280e2015-12-31 19:06:24 +00004003 utf8_printf(p->out, "/****** %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00004004 sqlite3_free(zErr);
4005 zErr = 0;
4006 }
drhdd3d4592004-08-30 01:54:05 +00004007 zQ2 = malloc( len+100 );
4008 if( zQ2==0 ) return rc;
drh8c5058b2012-04-16 17:22:30 +00004009 sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
drh2f464a02011-10-13 00:41:49 +00004010 rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
4011 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004012 utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
drh2f464a02011-10-13 00:41:49 +00004013 }else{
4014 rc = SQLITE_CORRUPT;
4015 }
4016 sqlite3_free(zErr);
drhdd3d4592004-08-30 01:54:05 +00004017 free(zQ2);
4018 }
4019 return rc;
4020}
4021
4022/*
drh75897232000-05-29 14:26:00 +00004023** Text of a help message
4024*/
persicom1d0b8722002-04-18 02:53:04 +00004025static char zHelp[] =
drha0daa752016-09-16 11:53:10 +00004026#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00004027 ".auth ON|OFF Show authorizer callbacks\n"
drha0daa752016-09-16 11:53:10 +00004028#endif
drh9ff849f2009-02-04 20:55:57 +00004029 ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n"
drhc2ce0be2014-05-29 12:36:14 +00004030 ".bail on|off Stop after hitting an error. Default OFF\n"
mistachkinf21979d2015-01-18 05:35:01 +00004031 ".binary on|off Turn binary output on or off. Default OFF\n"
drh453ca042017-05-22 18:00:34 +00004032 ".cd DIRECTORY Change the working directory to DIRECTORY\n"
drhdf12f1c2015-12-07 21:46:19 +00004033 ".changes on|off Show number of rows changed by SQL\n"
drh2db82112016-09-15 21:35:24 +00004034 ".check GLOB Fail if output since .testcase does not match\n"
drh4bbcf102014-02-06 02:46:08 +00004035 ".clone NEWDB Clone data into NEWDB from the existing database\n"
jplyon6a65bb32003-05-04 07:25:57 +00004036 ".databases List names and files of attached databases\n"
drh0e55db12015-02-06 14:51:13 +00004037 ".dbinfo ?DB? Show status information about the database\n"
drhb860bc92004-08-04 15:16:55 +00004038 ".dump ?TABLE? ... Dump the database in an SQL text format\n"
shane86f5bdb2009-10-24 02:00:07 +00004039 " If TABLE specified, only dump tables matching\n"
4040 " LIKE pattern TABLE.\n"
drhc2ce0be2014-05-29 12:36:14 +00004041 ".echo on|off Turn command echo on or off\n"
drheacd29d2016-04-15 15:03:27 +00004042 ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n"
drh75897232000-05-29 14:26:00 +00004043 ".exit Exit this program\n"
drhc31b79d2017-06-29 21:11:27 +00004044/* Because explain mode comes on automatically now, the ".explain" mode
4045** is removed from the help screen. It is still supported for legacy, however */
4046/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
drh4926fec2016-04-13 15:33:42 +00004047 ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
drhc2ce0be2014-05-29 12:36:14 +00004048 ".headers on|off Turn display of headers on or off\n"
drh75897232000-05-29 14:26:00 +00004049 ".help Show this message\n"
drhb860bc92004-08-04 15:16:55 +00004050 ".import FILE TABLE Import data from FILE into TABLE\n"
drh16eb5942016-11-03 13:01:38 +00004051#ifndef SQLITE_OMIT_TEST_CONTROL
4052 ".imposter INDEX TABLE Create imposter table TABLE on index INDEX\n"
4053#endif
drh0e55db12015-02-06 14:51:13 +00004054 ".indexes ?TABLE? Show names of all indexes\n"
4055 " If TABLE specified, only show indexes for tables\n"
shane86f5bdb2009-10-24 02:00:07 +00004056 " matching LIKE pattern TABLE.\n"
drhae5e4452007-05-03 17:18:36 +00004057#ifdef SQLITE_ENABLE_IOTRACE
4058 ".iotrace FILE Enable I/O diagnostic logging to FILE\n"
4059#endif
drh1a513372015-05-02 17:40:23 +00004060 ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n"
drh3fd9f332016-12-16 18:41:11 +00004061 ".lint OPTIONS Report potential schema issues. Options:\n"
4062 " fkey-indexes Find missing foreign key indexes\n"
drh70df4fe2006-06-13 15:12:21 +00004063#ifndef SQLITE_OMIT_LOAD_EXTENSION
drh1e397f82006-06-08 15:28:43 +00004064 ".load FILE ?ENTRY? Load an extension library\n"
drh70df4fe2006-06-13 15:12:21 +00004065#endif
drh127f9d72010-02-23 01:47:00 +00004066 ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n"
danielk19776b77a362005-01-13 11:10:25 +00004067 ".mode MODE ?TABLE? Set output mode where MODE is one of:\n"
mistachkine0d68852014-12-11 03:12:33 +00004068 " ascii Columns/rows delimited by 0x1F and 0x1E\n"
drh3b584fa2004-09-24 12:50:03 +00004069 " csv Comma-separated values\n"
drhb860bc92004-08-04 15:16:55 +00004070 " column Left-aligned columns. (See .width)\n"
4071 " html HTML <table> code\n"
4072 " insert SQL insert statements for TABLE\n"
4073 " line One value per line\n"
drh0c5cd962017-02-14 21:47:46 +00004074 " list Values delimited by \"|\"\n"
drh41f5f6e2016-10-21 17:39:30 +00004075 " quote Escape answers as for SQL\n"
drhb860bc92004-08-04 15:16:55 +00004076 " tabs Tab-separated values\n"
4077 " tcl TCL list elements\n"
drh078b1fd2012-09-21 13:40:02 +00004078 ".nullvalue STRING Use STRING in place of NULL values\n"
drhc2ce0be2014-05-29 12:36:14 +00004079 ".once FILENAME Output for the next SQL command only to FILENAME\n"
mistachkine16a3502017-05-29 03:48:13 +00004080 ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
4081 " The --new option starts with an empty file\n"
drhc2ce0be2014-05-29 12:36:14 +00004082 ".output ?FILENAME? Send output to FILENAME or stdout\n"
drh078b1fd2012-09-21 13:40:02 +00004083 ".print STRING... Print literal STRING\n"
persicom7e2dfdd2002-04-18 02:46:52 +00004084 ".prompt MAIN CONTINUE Replace the standard prompts\n"
persicom7e2dfdd2002-04-18 02:46:52 +00004085 ".quit Exit this program\n"
drhdaffd0e2001-04-11 14:28:42 +00004086 ".read FILENAME Execute SQL in FILENAME\n"
drh9ff849f2009-02-04 20:55:57 +00004087 ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n"
drh5c7976f2014-02-10 19:59:27 +00004088 ".save FILE Write in-memory database into FILE\n"
drh15f23c22014-11-06 12:46:16 +00004089 ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n"
drh4926fec2016-04-13 15:33:42 +00004090 ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n"
4091 " Add --indent for pretty-printing\n"
drha5d75ba2017-03-15 14:20:34 +00004092 ".selftest ?--init? Run tests defined in the SELFTEST table\n"
mistachkine0d68852014-12-11 03:12:33 +00004093 ".separator COL ?ROW? Change the column separator and optionally the row\n"
4094 " separator for both the output mode and .import\n"
drhe6229612014-08-18 15:08:26 +00004095#if defined(SQLITE_ENABLE_SESSION)
4096 ".session CMD ... Create or control sessions\n"
4097#endif
drh1554bc82017-03-08 16:10:34 +00004098 ".sha3sum ?OPTIONS...? Compute a SHA3 hash of database content\n"
drh62cdde52014-05-28 20:22:28 +00004099 ".shell CMD ARGS... Run CMD ARGS... in a system shell\n"
drhdd45df82002-04-18 12:39:03 +00004100 ".show Show the current values for various settings\n"
drh34784902016-02-27 17:12:36 +00004101 ".stats ?on|off? Show stats or turn stats on or off\n"
drh62cdde52014-05-28 20:22:28 +00004102 ".system CMD ARGS... Run CMD ARGS... in a system shell\n"
shane86f5bdb2009-10-24 02:00:07 +00004103 ".tables ?TABLE? List names of tables\n"
4104 " If TABLE specified, only list tables matching\n"
4105 " LIKE pattern TABLE.\n"
drh760c8162016-09-16 02:52:22 +00004106 ".testcase NAME Begin redirecting output to 'testcase-out.txt'\n"
drh2dfbbca2000-07-28 14:32:48 +00004107 ".timeout MS Try opening locked tables for MS milliseconds\n"
drhc2ce0be2014-05-29 12:36:14 +00004108 ".timer on|off Turn SQL timer on or off\n"
drh42f64e52012-04-04 16:56:23 +00004109 ".trace FILE|off Output each SQL statement as it is run\n"
drh790f2872015-11-28 18:06:36 +00004110 ".vfsinfo ?AUX? Information about the top-level VFS\n"
drhb19e7352016-01-12 19:37:20 +00004111 ".vfslist List all available VFSes\n"
drhde60fc22011-12-14 17:53:36 +00004112 ".vfsname ?AUX? Print the name of the VFS stack\n"
shanehe2aa9d72009-11-06 17:20:17 +00004113 ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n"
drh62cdde52014-05-28 20:22:28 +00004114 " Negative values right-justify\n"
drh75897232000-05-29 14:26:00 +00004115;
4116
drhe6229612014-08-18 15:08:26 +00004117#if defined(SQLITE_ENABLE_SESSION)
4118/*
4119** Print help information for the ".sessions" command
4120*/
4121void session_help(ShellState *p){
mistachkin899c5c92016-04-03 20:50:02 +00004122 raw_printf(p->out,
drhe6229612014-08-18 15:08:26 +00004123 ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
4124 "If ?NAME? is omitted, the first defined session is used.\n"
4125 "Subcommands:\n"
4126 " attach TABLE Attach TABLE\n"
4127 " changeset FILE Write a changeset into FILE\n"
4128 " close Close one session\n"
4129 " enable ?BOOLEAN? Set or query the enable bit\n"
mistachkin1fe36bb2016-04-04 02:16:44 +00004130 " filter GLOB... Reject tables matching GLOBs\n"
drhe6229612014-08-18 15:08:26 +00004131 " indirect ?BOOLEAN? Mark or query the indirect status\n"
4132 " isempty Query whether the session is empty\n"
4133 " list List currently open session names\n"
4134 " open DB NAME Open a new session on DB\n"
4135 " patchset FILE Write a patchset into FILE\n"
4136 );
4137}
4138#endif
4139
4140
drhdaffd0e2001-04-11 14:28:42 +00004141/* Forward reference */
drhdcd87a92014-08-18 13:45:42 +00004142static int process_input(ShellState *p, FILE *in);
drh2db82112016-09-15 21:35:24 +00004143
drh2db82112016-09-15 21:35:24 +00004144/*
dan11da0022016-12-17 08:18:05 +00004145** Read the content of file zName into memory obtained from sqlite3_malloc64()
mistachkine16a3502017-05-29 03:48:13 +00004146** and return a pointer to the buffer. The caller is responsible for freeing
4147** the memory.
drh2db82112016-09-15 21:35:24 +00004148**
dan11da0022016-12-17 08:18:05 +00004149** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
4150** read.
4151**
4152** For convenience, a nul-terminator byte is always appended to the data read
4153** from the file before the buffer is returned. This byte is not included in
4154** the final value of (*pnByte), if applicable.
4155**
4156** NULL is returned if any error is encountered. The final value of *pnByte
4157** is undefined in this case.
drh2db82112016-09-15 21:35:24 +00004158*/
dan11da0022016-12-17 08:18:05 +00004159static char *readFile(const char *zName, int *pnByte){
drh2db82112016-09-15 21:35:24 +00004160 FILE *in = fopen(zName, "rb");
4161 long nIn;
drhd1459152016-09-16 19:11:03 +00004162 size_t nRead;
drh2db82112016-09-15 21:35:24 +00004163 char *pBuf;
4164 if( in==0 ) return 0;
4165 fseek(in, 0, SEEK_END);
4166 nIn = ftell(in);
4167 rewind(in);
drhd1459152016-09-16 19:11:03 +00004168 pBuf = sqlite3_malloc64( nIn+1 );
drh2db82112016-09-15 21:35:24 +00004169 if( pBuf==0 ) return 0;
drhd1459152016-09-16 19:11:03 +00004170 nRead = fread(pBuf, nIn, 1, in);
4171 fclose(in);
4172 if( nRead!=1 ){
drh2db82112016-09-15 21:35:24 +00004173 sqlite3_free(pBuf);
4174 return 0;
4175 }
drhd1459152016-09-16 19:11:03 +00004176 pBuf[nIn] = 0;
dan11da0022016-12-17 08:18:05 +00004177 if( pnByte ) *pnByte = nIn;
drh2db82112016-09-15 21:35:24 +00004178 return pBuf;
4179}
4180
drhe6229612014-08-18 15:08:26 +00004181#if defined(SQLITE_ENABLE_SESSION)
4182/*
4183** Close a single OpenSession object and release all of its associated
4184** resources.
4185*/
4186static void session_close(OpenSession *pSession){
4187 int i;
4188 sqlite3session_delete(pSession->p);
4189 sqlite3_free(pSession->zName);
4190 for(i=0; i<pSession->nFilter; i++){
4191 sqlite3_free(pSession->azFilter[i]);
4192 }
4193 sqlite3_free(pSession->azFilter);
4194 memset(pSession, 0, sizeof(OpenSession));
4195}
4196#endif
4197
4198/*
drh51b55a32016-04-04 12:38:05 +00004199** Close all OpenSession objects and release all associated resources.
drhe6229612014-08-18 15:08:26 +00004200*/
drhe6229612014-08-18 15:08:26 +00004201#if defined(SQLITE_ENABLE_SESSION)
drh51b55a32016-04-04 12:38:05 +00004202static void session_close_all(ShellState *p){
drhe6229612014-08-18 15:08:26 +00004203 int i;
4204 for(i=0; i<p->nSession; i++){
4205 session_close(&p->aSession[i]);
4206 }
4207 p->nSession = 0;
drhe6229612014-08-18 15:08:26 +00004208}
drh51b55a32016-04-04 12:38:05 +00004209#else
4210# define session_close_all(X)
4211#endif
drhe6229612014-08-18 15:08:26 +00004212
drh75897232000-05-29 14:26:00 +00004213/*
drh03168ca2014-08-18 20:01:31 +00004214** Implementation of the xFilter function for an open session. Omit
4215** any tables named by ".session filter" but let all other table through.
4216*/
4217#if defined(SQLITE_ENABLE_SESSION)
4218static int session_filter(void *pCtx, const char *zTab){
4219 OpenSession *pSession = (OpenSession*)pCtx;
4220 int i;
4221 for(i=0; i<pSession->nFilter; i++){
4222 if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
4223 }
4224 return 1;
4225}
4226#endif
4227
4228/*
drh44c2eb12003-04-30 11:38:26 +00004229** Make sure the database is open. If it is not, then open it. If
4230** the database fails to open, print an error message and exit.
4231*/
drhdcd87a92014-08-18 13:45:42 +00004232static void open_db(ShellState *p, int keepAlive){
drh44c2eb12003-04-30 11:38:26 +00004233 if( p->db==0 ){
drhbbb0be82012-06-27 16:12:27 +00004234 sqlite3_initialize();
danielk19774f057f92004-06-08 00:02:33 +00004235 sqlite3_open(p->zDbFilename, &p->db);
mistachkin8e189222015-04-19 21:43:16 +00004236 globalDb = p->db;
mistachkin8e189222015-04-19 21:43:16 +00004237 if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00004238 utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
mistachkin8e189222015-04-19 21:43:16 +00004239 p->zDbFilename, sqlite3_errmsg(p->db));
drh05782482013-10-24 15:20:20 +00004240 if( keepAlive ) return;
drh22fbcb82004-02-01 01:22:50 +00004241 exit(1);
drh44c2eb12003-04-30 11:38:26 +00004242 }
drhc2e87a32006-06-27 15:16:14 +00004243#ifndef SQLITE_OMIT_LOAD_EXTENSION
4244 sqlite3_enable_load_extension(p->db, 1);
4245#endif
drh2ce15c32017-07-11 13:34:40 +00004246 sqlite3_fileio_init(p->db, 0, 0);
4247 sqlite3_shathree_init(p->db, 0, 0);
drh56eb09b2017-07-11 13:59:07 +00004248 sqlite3_completion_init(p->db, 0, 0);
drh20c9c3f2017-06-15 12:21:09 +00004249 sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
4250 shellAddSchemaName, 0, 0);
drh44c2eb12003-04-30 11:38:26 +00004251 }
4252}
4253
drh56eb09b2017-07-11 13:59:07 +00004254#if HAVE_READLINE || HAVE_EDITLINE
4255/*
4256** Readline completion callbacks
4257*/
4258static char *readline_completion_generator(const char *text, int state){
4259 static sqlite3_stmt *pStmt = 0;
4260 char *zRet;
4261 if( state==0 ){
4262 char *zSql;
drh56eb09b2017-07-11 13:59:07 +00004263 sqlite3_finalize(pStmt);
4264 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4265 " FROM completion(%Q) ORDER BY 1", text);
4266 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4267 sqlite3_free(zSql);
4268 }
4269 if( sqlite3_step(pStmt)==SQLITE_ROW ){
drh968d8712017-07-14 00:28:28 +00004270 zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
drh56eb09b2017-07-11 13:59:07 +00004271 }else{
4272 sqlite3_finalize(pStmt);
4273 pStmt = 0;
4274 zRet = 0;
4275 }
4276 return zRet;
4277}
4278static char **readline_completion(const char *zText, int iStart, int iEnd){
4279 rl_attempted_completion_over = 1;
4280 return rl_completion_matches(zText, readline_completion_generator);
4281}
4282
4283#elif HAVE_LINENOISE
4284/*
4285** Linenoise completion callback
4286*/
4287static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
4288 int nLine = (int)strlen(zLine);
4289 int i, iStart;
4290 sqlite3_stmt *pStmt = 0;
4291 char *zSql;
4292 char zBuf[1000];
4293
4294 if( nLine>sizeof(zBuf)-30 ) return;
4295 if( zLine[0]=='.' ) return;
4296 for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
4297 if( i==nLine-1 ) return;
4298 iStart = i+1;
4299 memcpy(zBuf, zLine, iStart);
4300 zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
4301 " FROM completion(%Q,%Q) ORDER BY 1",
4302 &zLine[iStart], zLine);
4303 sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
4304 sqlite3_free(zSql);
4305 sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
4306 while( sqlite3_step(pStmt)==SQLITE_ROW ){
4307 const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
4308 int nCompletion = sqlite3_column_bytes(pStmt, 0);
4309 if( iStart+nCompletion < sizeof(zBuf)-1 ){
4310 memcpy(zBuf+iStart, zCompletion, nCompletion+1);
4311 linenoiseAddCompletion(lc, zBuf);
4312 }
4313 }
4314 sqlite3_finalize(pStmt);
4315}
4316#endif
4317
drh44c2eb12003-04-30 11:38:26 +00004318/*
drhfeac5f82004-08-01 00:10:45 +00004319** Do C-language style dequoting.
4320**
mistachkinf21979d2015-01-18 05:35:01 +00004321** \a -> alarm
4322** \b -> backspace
drhfeac5f82004-08-01 00:10:45 +00004323** \t -> tab
4324** \n -> newline
mistachkinf21979d2015-01-18 05:35:01 +00004325** \v -> vertical tab
4326** \f -> form feed
drhfeac5f82004-08-01 00:10:45 +00004327** \r -> carriage return
mistachkinf21979d2015-01-18 05:35:01 +00004328** \s -> space
drh4c56b992013-06-27 13:26:55 +00004329** \" -> "
mistachkinf21979d2015-01-18 05:35:01 +00004330** \' -> '
drhfeac5f82004-08-01 00:10:45 +00004331** \\ -> backslash
mistachkinf21979d2015-01-18 05:35:01 +00004332** \NNN -> ascii character NNN in octal
drhfeac5f82004-08-01 00:10:45 +00004333*/
4334static void resolve_backslashes(char *z){
shane7d3846a2008-12-11 02:58:26 +00004335 int i, j;
4336 char c;
drhc2ce0be2014-05-29 12:36:14 +00004337 while( *z && *z!='\\' ) z++;
drhfeac5f82004-08-01 00:10:45 +00004338 for(i=j=0; (c = z[i])!=0; i++, j++){
drh4b608032015-04-15 19:25:25 +00004339 if( c=='\\' && z[i+1]!=0 ){
drhfeac5f82004-08-01 00:10:45 +00004340 c = z[++i];
mistachkinf21979d2015-01-18 05:35:01 +00004341 if( c=='a' ){
4342 c = '\a';
4343 }else if( c=='b' ){
4344 c = '\b';
drhfeac5f82004-08-01 00:10:45 +00004345 }else if( c=='t' ){
4346 c = '\t';
mistachkinf21979d2015-01-18 05:35:01 +00004347 }else if( c=='n' ){
4348 c = '\n';
4349 }else if( c=='v' ){
4350 c = '\v';
4351 }else if( c=='f' ){
4352 c = '\f';
drhfeac5f82004-08-01 00:10:45 +00004353 }else if( c=='r' ){
4354 c = '\r';
mistachkinf21979d2015-01-18 05:35:01 +00004355 }else if( c=='"' ){
4356 c = '"';
4357 }else if( c=='\'' ){
4358 c = '\'';
drh4c56b992013-06-27 13:26:55 +00004359 }else if( c=='\\' ){
4360 c = '\\';
drhfeac5f82004-08-01 00:10:45 +00004361 }else if( c>='0' && c<='7' ){
drhaa816082005-12-29 12:53:09 +00004362 c -= '0';
drhfeac5f82004-08-01 00:10:45 +00004363 if( z[i+1]>='0' && z[i+1]<='7' ){
4364 i++;
4365 c = (c<<3) + z[i] - '0';
4366 if( z[i+1]>='0' && z[i+1]<='7' ){
4367 i++;
4368 c = (c<<3) + z[i] - '0';
4369 }
4370 }
4371 }
4372 }
4373 z[j] = c;
4374 }
drhc2ce0be2014-05-29 12:36:14 +00004375 if( j<i ) z[j] = 0;
drhfeac5f82004-08-01 00:10:45 +00004376}
4377
4378/*
drh348d19c2013-06-03 12:47:43 +00004379** Return the value of a hexadecimal digit. Return -1 if the input
4380** is not a hex digit.
drhc28490c2006-10-26 14:25:58 +00004381*/
drh348d19c2013-06-03 12:47:43 +00004382static int hexDigitValue(char c){
4383 if( c>='0' && c<='9' ) return c - '0';
4384 if( c>='a' && c<='f' ) return c - 'a' + 10;
4385 if( c>='A' && c<='F' ) return c - 'A' + 10;
4386 return -1;
drhc28490c2006-10-26 14:25:58 +00004387}
4388
4389/*
drh7d9f3942013-04-03 01:26:54 +00004390** Interpret zArg as an integer value, possibly with suffixes.
4391*/
4392static sqlite3_int64 integerValue(const char *zArg){
4393 sqlite3_int64 v = 0;
4394 static const struct { char *zSuffix; int iMult; } aMult[] = {
4395 { "KiB", 1024 },
4396 { "MiB", 1024*1024 },
4397 { "GiB", 1024*1024*1024 },
4398 { "KB", 1000 },
4399 { "MB", 1000000 },
4400 { "GB", 1000000000 },
4401 { "K", 1000 },
4402 { "M", 1000000 },
4403 { "G", 1000000000 },
4404 };
4405 int i;
4406 int isNeg = 0;
4407 if( zArg[0]=='-' ){
4408 isNeg = 1;
4409 zArg++;
4410 }else if( zArg[0]=='+' ){
4411 zArg++;
4412 }
drh348d19c2013-06-03 12:47:43 +00004413 if( zArg[0]=='0' && zArg[1]=='x' ){
4414 int x;
4415 zArg += 2;
4416 while( (x = hexDigitValue(zArg[0]))>=0 ){
4417 v = (v<<4) + x;
4418 zArg++;
4419 }
4420 }else{
4421 while( IsDigit(zArg[0]) ){
4422 v = v*10 + zArg[0] - '0';
4423 zArg++;
4424 }
drh7d9f3942013-04-03 01:26:54 +00004425 }
drhc2bed0a2013-05-24 11:57:50 +00004426 for(i=0; i<ArraySize(aMult); i++){
drh7d9f3942013-04-03 01:26:54 +00004427 if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
4428 v *= aMult[i].iMult;
4429 break;
4430 }
4431 }
4432 return isNeg? -v : v;
4433}
4434
4435/*
drh348d19c2013-06-03 12:47:43 +00004436** Interpret zArg as either an integer or a boolean value. Return 1 or 0
4437** for TRUE and FALSE. Return the integer value if appropriate.
4438*/
drhe6e1d122017-03-09 13:50:49 +00004439static int booleanValue(const char *zArg){
drh348d19c2013-06-03 12:47:43 +00004440 int i;
4441 if( zArg[0]=='0' && zArg[1]=='x' ){
4442 for(i=2; hexDigitValue(zArg[i])>=0; i++){}
4443 }else{
4444 for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
4445 }
4446 if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
4447 if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
4448 return 1;
4449 }
4450 if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
4451 return 0;
4452 }
mistachkinaae280e2015-12-31 19:06:24 +00004453 utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
drh348d19c2013-06-03 12:47:43 +00004454 zArg);
4455 return 0;
4456}
4457
4458/*
drhe6e1d122017-03-09 13:50:49 +00004459** Set or clear a shell flag according to a boolean value.
4460*/
4461static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
4462 if( booleanValue(zArg) ){
4463 ShellSetFlag(p, mFlag);
4464 }else{
4465 ShellClearFlag(p, mFlag);
4466 }
4467}
4468
4469/*
drh42f64e52012-04-04 16:56:23 +00004470** Close an output file, assuming it is not stderr or stdout
4471*/
4472static void output_file_close(FILE *f){
4473 if( f && f!=stdout && f!=stderr ) fclose(f);
4474}
4475
4476/*
4477** Try to open an output file. The names "stdout" and "stderr" are
mistachkin1fe36bb2016-04-04 02:16:44 +00004478** recognized and do the right thing. NULL is returned if the output
drh42f64e52012-04-04 16:56:23 +00004479** filename is "off".
4480*/
4481static FILE *output_file_open(const char *zFile){
4482 FILE *f;
4483 if( strcmp(zFile,"stdout")==0 ){
4484 f = stdout;
4485 }else if( strcmp(zFile, "stderr")==0 ){
4486 f = stderr;
4487 }else if( strcmp(zFile, "off")==0 ){
4488 f = 0;
4489 }else{
4490 f = fopen(zFile, "wb");
4491 if( f==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004492 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00004493 }
4494 }
4495 return f;
4496}
4497
drhd12602a2016-12-07 15:49:02 +00004498#if !defined(SQLITE_UNTESTABLE)
drhc10b9da2016-11-20 17:59:59 +00004499#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00004500/*
4501** A routine for handling output from sqlite3_trace().
4502*/
drh4b363a52016-07-23 20:27:41 +00004503static int sql_trace_callback(
4504 unsigned mType,
4505 void *pArg,
4506 void *pP,
4507 void *pX
4508){
drh42f64e52012-04-04 16:56:23 +00004509 FILE *f = (FILE*)pArg;
drhb0df5402016-08-01 17:06:44 +00004510 UNUSED_PARAMETER(mType);
4511 UNUSED_PARAMETER(pP);
drh4b2590e2014-08-19 19:28:00 +00004512 if( f ){
drh4b363a52016-07-23 20:27:41 +00004513 const char *z = (const char*)pX;
drh4b2590e2014-08-19 19:28:00 +00004514 int i = (int)strlen(z);
4515 while( i>0 && z[i-1]==';' ){ i--; }
drhe05461c2015-12-30 13:36:57 +00004516 utf8_printf(f, "%.*s;\n", i, z);
drh4b2590e2014-08-19 19:28:00 +00004517 }
drh4b363a52016-07-23 20:27:41 +00004518 return 0;
drh42f64e52012-04-04 16:56:23 +00004519}
drhc10b9da2016-11-20 17:59:59 +00004520#endif
4521#endif
drh42f64e52012-04-04 16:56:23 +00004522
4523/*
drhd8621b92012-04-17 09:09:33 +00004524** A no-op routine that runs with the ".breakpoint" doc-command. This is
4525** a useful spot to set a debugger breakpoint.
4526*/
4527static void test_breakpoint(void){
4528 static int nCall = 0;
4529 nCall++;
4530}
4531
4532/*
mistachkin636bf9f2014-07-19 20:15:16 +00004533** An object used to read a CSV and other files for import.
drhdb95f682013-06-26 22:46:00 +00004534*/
mistachkin636bf9f2014-07-19 20:15:16 +00004535typedef struct ImportCtx ImportCtx;
4536struct ImportCtx {
drhdb95f682013-06-26 22:46:00 +00004537 const char *zFile; /* Name of the input file */
4538 FILE *in; /* Read the CSV text from this input stream */
4539 char *z; /* Accumulated text for a field */
4540 int n; /* Number of bytes in z */
4541 int nAlloc; /* Space allocated for z[] */
4542 int nLine; /* Current line number */
drhd5fbde82017-06-26 18:42:23 +00004543 int bNotFirst; /* True if one or more bytes already read */
drhdb95f682013-06-26 22:46:00 +00004544 int cTerm; /* Character that terminated the most recent field */
mistachkin636bf9f2014-07-19 20:15:16 +00004545 int cColSep; /* The column separator character. (Usually ",") */
4546 int cRowSep; /* The row separator character. (Usually "\n") */
drhdb95f682013-06-26 22:46:00 +00004547};
4548
4549/* Append a single byte to z[] */
mistachkin636bf9f2014-07-19 20:15:16 +00004550static void import_append_char(ImportCtx *p, int c){
drhdb95f682013-06-26 22:46:00 +00004551 if( p->n+1>=p->nAlloc ){
4552 p->nAlloc += p->nAlloc + 100;
drhf3cdcdc2015-04-29 16:50:28 +00004553 p->z = sqlite3_realloc64(p->z, p->nAlloc);
drhdb95f682013-06-26 22:46:00 +00004554 if( p->z==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004555 raw_printf(stderr, "out of memory\n");
drhdb95f682013-06-26 22:46:00 +00004556 exit(1);
4557 }
4558 }
4559 p->z[p->n++] = (char)c;
4560}
4561
4562/* Read a single field of CSV text. Compatible with rfc4180 and extended
4563** with the option of having a separator other than ",".
4564**
4565** + Input comes from p->in.
4566** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00004567** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00004568** + Use p->cSep as the column separator. The default is ",".
4569** + Use p->rSep as the row separator. The default is "\n".
drhdb95f682013-06-26 22:46:00 +00004570** + Keep track of the line number in p->nLine.
4571** + Store the character that terminates the field in p->cTerm. Store
4572** EOF on end-of-file.
4573** + Report syntax errors on stderr
4574*/
mistachkin44723ce2015-03-21 02:22:37 +00004575static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00004576 int c;
4577 int cSep = p->cColSep;
4578 int rSep = p->cRowSep;
drhdb95f682013-06-26 22:46:00 +00004579 p->n = 0;
4580 c = fgetc(p->in);
4581 if( c==EOF || seenInterrupt ){
4582 p->cTerm = EOF;
4583 return 0;
4584 }
4585 if( c=='"' ){
mistachkin636bf9f2014-07-19 20:15:16 +00004586 int pc, ppc;
drhdb95f682013-06-26 22:46:00 +00004587 int startLine = p->nLine;
4588 int cQuote = c;
drha81ad172013-12-11 14:00:04 +00004589 pc = ppc = 0;
drhdb95f682013-06-26 22:46:00 +00004590 while( 1 ){
4591 c = fgetc(p->in);
mistachkin636bf9f2014-07-19 20:15:16 +00004592 if( c==rSep ) p->nLine++;
drhdb95f682013-06-26 22:46:00 +00004593 if( c==cQuote ){
4594 if( pc==cQuote ){
4595 pc = 0;
4596 continue;
4597 }
4598 }
4599 if( (c==cSep && pc==cQuote)
mistachkin636bf9f2014-07-19 20:15:16 +00004600 || (c==rSep && pc==cQuote)
4601 || (c==rSep && pc=='\r' && ppc==cQuote)
drhdb95f682013-06-26 22:46:00 +00004602 || (c==EOF && pc==cQuote)
4603 ){
4604 do{ p->n--; }while( p->z[p->n]!=cQuote );
drhdb95f682013-06-26 22:46:00 +00004605 p->cTerm = c;
4606 break;
4607 }
4608 if( pc==cQuote && c!='\r' ){
mistachkinaae280e2015-12-31 19:06:24 +00004609 utf8_printf(stderr, "%s:%d: unescaped %c character\n",
drhdb95f682013-06-26 22:46:00 +00004610 p->zFile, p->nLine, cQuote);
4611 }
4612 if( c==EOF ){
mistachkinaae280e2015-12-31 19:06:24 +00004613 utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
drhdb95f682013-06-26 22:46:00 +00004614 p->zFile, startLine, cQuote);
mistachkin636bf9f2014-07-19 20:15:16 +00004615 p->cTerm = c;
drhdb95f682013-06-26 22:46:00 +00004616 break;
4617 }
mistachkin636bf9f2014-07-19 20:15:16 +00004618 import_append_char(p, c);
drha81ad172013-12-11 14:00:04 +00004619 ppc = pc;
drhdb95f682013-06-26 22:46:00 +00004620 pc = c;
drhd0a64dc2013-06-30 20:24:26 +00004621 }
drhdb95f682013-06-26 22:46:00 +00004622 }else{
drhd5fbde82017-06-26 18:42:23 +00004623 /* If this is the first field being parsed and it begins with the
4624 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */
4625 if( (c&0xff)==0xef && p->bNotFirst==0 ){
4626 import_append_char(p, c);
4627 c = fgetc(p->in);
4628 if( (c&0xff)==0xbb ){
4629 import_append_char(p, c);
4630 c = fgetc(p->in);
4631 if( (c&0xff)==0xbf ){
4632 p->bNotFirst = 1;
4633 p->n = 0;
4634 return csv_read_one_field(p);
4635 }
4636 }
4637 }
mistachkin636bf9f2014-07-19 20:15:16 +00004638 while( c!=EOF && c!=cSep && c!=rSep ){
4639 import_append_char(p, c);
drhd0a64dc2013-06-30 20:24:26 +00004640 c = fgetc(p->in);
drhdb95f682013-06-26 22:46:00 +00004641 }
mistachkin636bf9f2014-07-19 20:15:16 +00004642 if( c==rSep ){
drhdb95f682013-06-26 22:46:00 +00004643 p->nLine++;
drh3852b682014-02-26 13:53:34 +00004644 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
drhdb95f682013-06-26 22:46:00 +00004645 }
drhdb95f682013-06-26 22:46:00 +00004646 p->cTerm = c;
4647 }
drh8dd675e2013-07-12 21:09:24 +00004648 if( p->z ) p->z[p->n] = 0;
drhd5fbde82017-06-26 18:42:23 +00004649 p->bNotFirst = 1;
drhdb95f682013-06-26 22:46:00 +00004650 return p->z;
4651}
4652
mistachkin636bf9f2014-07-19 20:15:16 +00004653/* Read a single field of ASCII delimited text.
4654**
4655** + Input comes from p->in.
4656** + Store results in p->z of length p->n. Space to hold p->z comes
drhf3cdcdc2015-04-29 16:50:28 +00004657** from sqlite3_malloc64().
mistachkin636bf9f2014-07-19 20:15:16 +00004658** + Use p->cSep as the column separator. The default is "\x1F".
4659** + Use p->rSep as the row separator. The default is "\x1E".
4660** + Keep track of the row number in p->nLine.
4661** + Store the character that terminates the field in p->cTerm. Store
4662** EOF on end-of-file.
4663** + Report syntax errors on stderr
4664*/
mistachkin44723ce2015-03-21 02:22:37 +00004665static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
mistachkin636bf9f2014-07-19 20:15:16 +00004666 int c;
4667 int cSep = p->cColSep;
4668 int rSep = p->cRowSep;
4669 p->n = 0;
4670 c = fgetc(p->in);
4671 if( c==EOF || seenInterrupt ){
4672 p->cTerm = EOF;
4673 return 0;
4674 }
4675 while( c!=EOF && c!=cSep && c!=rSep ){
4676 import_append_char(p, c);
4677 c = fgetc(p->in);
4678 }
4679 if( c==rSep ){
4680 p->nLine++;
4681 }
4682 p->cTerm = c;
4683 if( p->z ) p->z[p->n] = 0;
4684 return p->z;
4685}
4686
drhdb95f682013-06-26 22:46:00 +00004687/*
drh4bbcf102014-02-06 02:46:08 +00004688** Try to transfer data for table zTable. If an error is seen while
4689** moving forward, try to go backwards. The backwards movement won't
4690** work for WITHOUT ROWID tables.
drh3350ce92014-02-06 00:49:12 +00004691*/
mistachkine31ae902014-02-06 01:15:29 +00004692static void tryToCloneData(
drhdcd87a92014-08-18 13:45:42 +00004693 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00004694 sqlite3 *newDb,
4695 const char *zTable
4696){
mistachkin1fe36bb2016-04-04 02:16:44 +00004697 sqlite3_stmt *pQuery = 0;
drh3350ce92014-02-06 00:49:12 +00004698 sqlite3_stmt *pInsert = 0;
4699 char *zQuery = 0;
4700 char *zInsert = 0;
4701 int rc;
4702 int i, j, n;
4703 int nTable = (int)strlen(zTable);
4704 int k = 0;
drh4bbcf102014-02-06 02:46:08 +00004705 int cnt = 0;
4706 const int spinRate = 10000;
drh3350ce92014-02-06 00:49:12 +00004707
4708 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
4709 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4710 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004711 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004712 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4713 zQuery);
4714 goto end_data_xfer;
4715 }
4716 n = sqlite3_column_count(pQuery);
drhf3cdcdc2015-04-29 16:50:28 +00004717 zInsert = sqlite3_malloc64(200 + nTable + n*3);
drh3350ce92014-02-06 00:49:12 +00004718 if( zInsert==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004719 raw_printf(stderr, "out of memory\n");
drh3350ce92014-02-06 00:49:12 +00004720 goto end_data_xfer;
4721 }
4722 sqlite3_snprintf(200+nTable,zInsert,
4723 "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
4724 i = (int)strlen(zInsert);
4725 for(j=1; j<n; j++){
4726 memcpy(zInsert+i, ",?", 2);
4727 i += 2;
4728 }
4729 memcpy(zInsert+i, ");", 3);
4730 rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
4731 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004732 utf8_printf(stderr, "Error %d: %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004733 sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
4734 zQuery);
4735 goto end_data_xfer;
4736 }
4737 for(k=0; k<2; k++){
4738 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4739 for(i=0; i<n; i++){
4740 switch( sqlite3_column_type(pQuery, i) ){
4741 case SQLITE_NULL: {
4742 sqlite3_bind_null(pInsert, i+1);
4743 break;
4744 }
4745 case SQLITE_INTEGER: {
4746 sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
4747 break;
4748 }
4749 case SQLITE_FLOAT: {
4750 sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
4751 break;
4752 }
4753 case SQLITE_TEXT: {
4754 sqlite3_bind_text(pInsert, i+1,
4755 (const char*)sqlite3_column_text(pQuery,i),
4756 -1, SQLITE_STATIC);
4757 break;
4758 }
4759 case SQLITE_BLOB: {
4760 sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
4761 sqlite3_column_bytes(pQuery,i),
4762 SQLITE_STATIC);
4763 break;
4764 }
4765 }
4766 } /* End for */
drh4bbcf102014-02-06 02:46:08 +00004767 rc = sqlite3_step(pInsert);
4768 if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
mistachkinaae280e2015-12-31 19:06:24 +00004769 utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
drh4bbcf102014-02-06 02:46:08 +00004770 sqlite3_errmsg(newDb));
4771 }
drh3350ce92014-02-06 00:49:12 +00004772 sqlite3_reset(pInsert);
drh4bbcf102014-02-06 02:46:08 +00004773 cnt++;
4774 if( (cnt%spinRate)==0 ){
4775 printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
4776 fflush(stdout);
4777 }
drh3350ce92014-02-06 00:49:12 +00004778 } /* End while */
4779 if( rc==SQLITE_DONE ) break;
4780 sqlite3_finalize(pQuery);
4781 sqlite3_free(zQuery);
4782 zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
4783 zTable);
4784 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4785 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004786 utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
drh4bbcf102014-02-06 02:46:08 +00004787 break;
drh3350ce92014-02-06 00:49:12 +00004788 }
4789 } /* End for(k=0...) */
4790
4791end_data_xfer:
4792 sqlite3_finalize(pQuery);
4793 sqlite3_finalize(pInsert);
4794 sqlite3_free(zQuery);
4795 sqlite3_free(zInsert);
4796}
4797
4798
4799/*
4800** Try to transfer all rows of the schema that match zWhere. For
4801** each row, invoke xForEach() on the object defined by that row.
drh4bbcf102014-02-06 02:46:08 +00004802** If an error is encountered while moving forward through the
4803** sqlite_master table, try again moving backwards.
drh3350ce92014-02-06 00:49:12 +00004804*/
mistachkine31ae902014-02-06 01:15:29 +00004805static void tryToCloneSchema(
drhdcd87a92014-08-18 13:45:42 +00004806 ShellState *p,
drh3350ce92014-02-06 00:49:12 +00004807 sqlite3 *newDb,
4808 const char *zWhere,
drhdcd87a92014-08-18 13:45:42 +00004809 void (*xForEach)(ShellState*,sqlite3*,const char*)
drh3350ce92014-02-06 00:49:12 +00004810){
4811 sqlite3_stmt *pQuery = 0;
4812 char *zQuery = 0;
4813 int rc;
4814 const unsigned char *zName;
4815 const unsigned char *zSql;
drh4bbcf102014-02-06 02:46:08 +00004816 char *zErrMsg = 0;
drh3350ce92014-02-06 00:49:12 +00004817
4818 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4819 " WHERE %s", zWhere);
4820 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4821 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004822 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004823 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4824 zQuery);
4825 goto end_schema_xfer;
4826 }
4827 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4828 zName = sqlite3_column_text(pQuery, 0);
4829 zSql = sqlite3_column_text(pQuery, 1);
4830 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004831 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4832 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004833 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004834 sqlite3_free(zErrMsg);
4835 zErrMsg = 0;
4836 }
drh3350ce92014-02-06 00:49:12 +00004837 if( xForEach ){
4838 xForEach(p, newDb, (const char*)zName);
4839 }
4840 printf("done\n");
4841 }
4842 if( rc!=SQLITE_DONE ){
4843 sqlite3_finalize(pQuery);
4844 sqlite3_free(zQuery);
4845 zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
4846 " WHERE %s ORDER BY rowid DESC", zWhere);
4847 rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
4848 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004849 utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
drh3350ce92014-02-06 00:49:12 +00004850 sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
4851 zQuery);
4852 goto end_schema_xfer;
4853 }
4854 while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
4855 zName = sqlite3_column_text(pQuery, 0);
4856 zSql = sqlite3_column_text(pQuery, 1);
4857 printf("%s... ", zName); fflush(stdout);
drh4bbcf102014-02-06 02:46:08 +00004858 sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
4859 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00004860 utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
drh4bbcf102014-02-06 02:46:08 +00004861 sqlite3_free(zErrMsg);
4862 zErrMsg = 0;
4863 }
drh3350ce92014-02-06 00:49:12 +00004864 if( xForEach ){
4865 xForEach(p, newDb, (const char*)zName);
4866 }
4867 printf("done\n");
4868 }
4869 }
4870end_schema_xfer:
4871 sqlite3_finalize(pQuery);
4872 sqlite3_free(zQuery);
4873}
4874
4875/*
4876** Open a new database file named "zNewDb". Try to recover as much information
4877** as possible out of the main database (which might be corrupt) and write it
4878** into zNewDb.
4879*/
drhdcd87a92014-08-18 13:45:42 +00004880static void tryToClone(ShellState *p, const char *zNewDb){
drh3350ce92014-02-06 00:49:12 +00004881 int rc;
4882 sqlite3 *newDb = 0;
4883 if( access(zNewDb,0)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00004884 utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
drh3350ce92014-02-06 00:49:12 +00004885 return;
4886 }
4887 rc = sqlite3_open(zNewDb, &newDb);
4888 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00004889 utf8_printf(stderr, "Cannot create output database: %s\n",
drh3350ce92014-02-06 00:49:12 +00004890 sqlite3_errmsg(newDb));
4891 }else{
drh54d0d2d2014-04-03 00:32:13 +00004892 sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004893 sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
mistachkine31ae902014-02-06 01:15:29 +00004894 tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
4895 tryToCloneSchema(p, newDb, "type!='table'", 0);
drh3350ce92014-02-06 00:49:12 +00004896 sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
drh54d0d2d2014-04-03 00:32:13 +00004897 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
drh3350ce92014-02-06 00:49:12 +00004898 }
4899 sqlite3_close(newDb);
4900}
4901
4902/*
drhc2ce0be2014-05-29 12:36:14 +00004903** Change the output file back to stdout
4904*/
drhdcd87a92014-08-18 13:45:42 +00004905static void output_reset(ShellState *p){
drhc2ce0be2014-05-29 12:36:14 +00004906 if( p->outfile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00004907#ifndef SQLITE_OMIT_POPEN
drhc2ce0be2014-05-29 12:36:14 +00004908 pclose(p->out);
drh8cd5b252015-03-02 22:06:43 +00004909#endif
drhc2ce0be2014-05-29 12:36:14 +00004910 }else{
4911 output_file_close(p->out);
4912 }
4913 p->outfile[0] = 0;
4914 p->out = stdout;
4915}
4916
4917/*
drhf7502f02015-02-06 14:19:44 +00004918** Run an SQL command and return the single integer result.
4919*/
4920static int db_int(ShellState *p, const char *zSql){
4921 sqlite3_stmt *pStmt;
4922 int res = 0;
4923 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
4924 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
4925 res = sqlite3_column_int(pStmt,0);
4926 }
4927 sqlite3_finalize(pStmt);
4928 return res;
4929}
4930
4931/*
4932** Convert a 2-byte or 4-byte big-endian integer into a native integer
4933*/
drha0620ac2016-07-13 13:05:13 +00004934static unsigned int get2byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004935 return (a[0]<<8) + a[1];
4936}
drha0620ac2016-07-13 13:05:13 +00004937static unsigned int get4byteInt(unsigned char *a){
drhf7502f02015-02-06 14:19:44 +00004938 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
4939}
4940
4941/*
4942** Implementation of the ".info" command.
4943**
4944** Return 1 on error, 2 to exit, and 0 otherwise.
4945*/
drh0e55db12015-02-06 14:51:13 +00004946static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
drhf7502f02015-02-06 14:19:44 +00004947 static const struct { const char *zName; int ofst; } aField[] = {
4948 { "file change counter:", 24 },
4949 { "database page count:", 28 },
4950 { "freelist page count:", 36 },
4951 { "schema cookie:", 40 },
4952 { "schema format:", 44 },
4953 { "default cache size:", 48 },
4954 { "autovacuum top root:", 52 },
4955 { "incremental vacuum:", 64 },
4956 { "text encoding:", 56 },
4957 { "user version:", 60 },
4958 { "application id:", 68 },
4959 { "software version:", 96 },
4960 };
drh0e55db12015-02-06 14:51:13 +00004961 static const struct { const char *zName; const char *zSql; } aQuery[] = {
4962 { "number of tables:",
4963 "SELECT count(*) FROM %s WHERE type='table'" },
4964 { "number of indexes:",
4965 "SELECT count(*) FROM %s WHERE type='index'" },
4966 { "number of triggers:",
4967 "SELECT count(*) FROM %s WHERE type='trigger'" },
4968 { "number of views:",
4969 "SELECT count(*) FROM %s WHERE type='view'" },
4970 { "schema size:",
4971 "SELECT total(length(sql)) FROM %s" },
4972 };
drh0e55db12015-02-06 14:51:13 +00004973 int i;
4974 char *zSchemaTab;
4975 char *zDb = nArg>=2 ? azArg[1] : "main";
drh512e6c32017-10-11 17:51:08 +00004976 sqlite3_stmt *pStmt = 0;
drh0e55db12015-02-06 14:51:13 +00004977 unsigned char aHdr[100];
drhf7502f02015-02-06 14:19:44 +00004978 open_db(p, 0);
4979 if( p->db==0 ) return 1;
drh512e6c32017-10-11 17:51:08 +00004980 sqlite3_prepare_v2(p->db,"SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
4981 -1, &pStmt, 0);
4982 sqlite3_bind_text(pStmt, 1, zDb, -1, SQLITE_STATIC);
4983 if( sqlite3_step(pStmt)==SQLITE_ROW
4984 && sqlite3_column_bytes(pStmt,0)>100
4985 ){
4986 memcpy(aHdr, sqlite3_column_blob(pStmt,0), 100);
4987 sqlite3_finalize(pStmt);
4988 }else{
mistachkinaae280e2015-12-31 19:06:24 +00004989 raw_printf(stderr, "unable to read database header\n");
drh512e6c32017-10-11 17:51:08 +00004990 sqlite3_finalize(pStmt);
drhf7502f02015-02-06 14:19:44 +00004991 return 1;
4992 }
4993 i = get2byteInt(aHdr+16);
4994 if( i==1 ) i = 65536;
mistachkinaae280e2015-12-31 19:06:24 +00004995 utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
4996 utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
4997 utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
4998 utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
drhf5ed7ad2015-06-15 14:43:25 +00004999 for(i=0; i<ArraySize(aField); i++){
drhf7502f02015-02-06 14:19:44 +00005000 int ofst = aField[i].ofst;
5001 unsigned int val = get4byteInt(aHdr + ofst);
mistachkinaae280e2015-12-31 19:06:24 +00005002 utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
drhf7502f02015-02-06 14:19:44 +00005003 switch( ofst ){
5004 case 56: {
mistachkin1fe36bb2016-04-04 02:16:44 +00005005 if( val==1 ) raw_printf(p->out, " (utf8)");
5006 if( val==2 ) raw_printf(p->out, " (utf16le)");
5007 if( val==3 ) raw_printf(p->out, " (utf16be)");
drhf7502f02015-02-06 14:19:44 +00005008 }
5009 }
mistachkinaae280e2015-12-31 19:06:24 +00005010 raw_printf(p->out, "\n");
drhf7502f02015-02-06 14:19:44 +00005011 }
drh0e55db12015-02-06 14:51:13 +00005012 if( zDb==0 ){
5013 zSchemaTab = sqlite3_mprintf("main.sqlite_master");
5014 }else if( strcmp(zDb,"temp")==0 ){
5015 zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
5016 }else{
5017 zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
5018 }
drhf5ed7ad2015-06-15 14:43:25 +00005019 for(i=0; i<ArraySize(aQuery); i++){
drh0e55db12015-02-06 14:51:13 +00005020 char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
5021 int val = db_int(p, zSql);
5022 sqlite3_free(zSql);
drhe05461c2015-12-30 13:36:57 +00005023 utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
drh0e55db12015-02-06 14:51:13 +00005024 }
5025 sqlite3_free(zSchemaTab);
drhf7502f02015-02-06 14:19:44 +00005026 return 0;
5027}
5028
dand95bb392015-09-30 11:19:05 +00005029/*
5030** Print the current sqlite3_errmsg() value to stderr and return 1.
5031*/
5032static int shellDatabaseError(sqlite3 *db){
5033 const char *zErr = sqlite3_errmsg(db);
mistachkinaae280e2015-12-31 19:06:24 +00005034 utf8_printf(stderr, "Error: %s\n", zErr);
dand95bb392015-09-30 11:19:05 +00005035 return 1;
5036}
5037
5038/*
5039** Print an out-of-memory message to stderr and return 1.
5040*/
5041static int shellNomemError(void){
mistachkinaae280e2015-12-31 19:06:24 +00005042 raw_printf(stderr, "Error: out of memory\n");
dand95bb392015-09-30 11:19:05 +00005043 return 1;
5044}
drhf7502f02015-02-06 14:19:44 +00005045
drh2db82112016-09-15 21:35:24 +00005046/*
5047** Compare the pattern in zGlob[] against the text in z[]. Return TRUE
5048** if they match and FALSE (0) if they do not match.
5049**
5050** Globbing rules:
5051**
5052** '*' Matches any sequence of zero or more characters.
5053**
5054** '?' Matches exactly one character.
5055**
5056** [...] Matches one character from the enclosed list of
5057** characters.
5058**
5059** [^...] Matches one character not in the enclosed list.
5060**
5061** '#' Matches any sequence of one or more digits with an
5062** optional + or - sign in front
5063**
5064** ' ' Any span of whitespace matches any other span of
5065** whitespace.
5066**
5067** Extra whitespace at the end of z[] is ignored.
5068*/
5069static int testcase_glob(const char *zGlob, const char *z){
5070 int c, c2;
5071 int invert;
5072 int seen;
5073
5074 while( (c = (*(zGlob++)))!=0 ){
5075 if( IsSpace(c) ){
5076 if( !IsSpace(*z) ) return 0;
5077 while( IsSpace(*zGlob) ) zGlob++;
5078 while( IsSpace(*z) ) z++;
5079 }else if( c=='*' ){
5080 while( (c=(*(zGlob++))) == '*' || c=='?' ){
5081 if( c=='?' && (*(z++))==0 ) return 0;
5082 }
5083 if( c==0 ){
5084 return 1;
5085 }else if( c=='[' ){
5086 while( *z && testcase_glob(zGlob-1,z)==0 ){
5087 z++;
5088 }
5089 return (*z)!=0;
5090 }
5091 while( (c2 = (*(z++)))!=0 ){
5092 while( c2!=c ){
5093 c2 = *(z++);
5094 if( c2==0 ) return 0;
5095 }
5096 if( testcase_glob(zGlob,z) ) return 1;
5097 }
5098 return 0;
5099 }else if( c=='?' ){
5100 if( (*(z++))==0 ) return 0;
5101 }else if( c=='[' ){
5102 int prior_c = 0;
5103 seen = 0;
5104 invert = 0;
5105 c = *(z++);
5106 if( c==0 ) return 0;
5107 c2 = *(zGlob++);
5108 if( c2=='^' ){
5109 invert = 1;
5110 c2 = *(zGlob++);
5111 }
5112 if( c2==']' ){
5113 if( c==']' ) seen = 1;
5114 c2 = *(zGlob++);
5115 }
5116 while( c2 && c2!=']' ){
5117 if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
5118 c2 = *(zGlob++);
5119 if( c>=prior_c && c<=c2 ) seen = 1;
5120 prior_c = 0;
5121 }else{
5122 if( c==c2 ){
5123 seen = 1;
5124 }
5125 prior_c = c2;
5126 }
5127 c2 = *(zGlob++);
5128 }
5129 if( c2==0 || (seen ^ invert)==0 ) return 0;
5130 }else if( c=='#' ){
5131 if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
5132 if( !IsDigit(z[0]) ) return 0;
5133 z++;
5134 while( IsDigit(z[0]) ){ z++; }
5135 }else{
5136 if( c!=(*(z++)) ) return 0;
5137 }
5138 }
5139 while( IsSpace(*z) ){ z++; }
5140 return *z==0;
5141}
drh2db82112016-09-15 21:35:24 +00005142
5143
drhf7502f02015-02-06 14:19:44 +00005144/*
drh4926fec2016-04-13 15:33:42 +00005145** Compare the string as a command-line option with either one or two
5146** initial "-" characters.
5147*/
5148static int optionMatch(const char *zStr, const char *zOpt){
5149 if( zStr[0]!='-' ) return 0;
5150 zStr++;
5151 if( zStr[0]=='-' ) zStr++;
5152 return strcmp(zStr, zOpt)==0;
5153}
5154
5155/*
drhcd0509e2016-09-16 00:26:08 +00005156** Delete a file.
5157*/
5158int shellDeleteFile(const char *zFilename){
5159 int rc;
5160#ifdef _WIN32
mistachkin8145fc62016-09-16 20:39:21 +00005161 wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
drhcd0509e2016-09-16 00:26:08 +00005162 rc = _wunlink(z);
5163 sqlite3_free(z);
5164#else
5165 rc = unlink(zFilename);
5166#endif
5167 return rc;
5168}
5169
dan35ac58e2016-12-14 19:28:27 +00005170
dan35ac58e2016-12-14 19:28:27 +00005171/*
dandd9e0be2016-12-16 16:44:27 +00005172** The implementation of SQL scalar function fkey_collate_clause(), used
dan3c7ebeb2016-12-16 17:28:56 +00005173** by the ".lint fkey-indexes" command. This scalar function is always
dandd9e0be2016-12-16 16:44:27 +00005174** called with four arguments - the parent table name, the parent column name,
5175** the child table name and the child column name.
dan35ac58e2016-12-14 19:28:27 +00005176**
5177** fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
5178**
5179** If either of the named tables or columns do not exist, this function
mistachkine16a3502017-05-29 03:48:13 +00005180** returns an empty string. An empty string is also returned if both tables
dan35ac58e2016-12-14 19:28:27 +00005181** and columns exist but have the same default collation sequence. Or,
5182** if both exist but the default collation sequences are different, this
5183** function returns the string " COLLATE <parent-collation>", where
5184** <parent-collation> is the default collation sequence of the parent column.
5185*/
5186static void shellFkeyCollateClause(
mistachkine16a3502017-05-29 03:48:13 +00005187 sqlite3_context *pCtx,
5188 int nVal,
dan35ac58e2016-12-14 19:28:27 +00005189 sqlite3_value **apVal
5190){
5191 sqlite3 *db = sqlite3_context_db_handle(pCtx);
5192 const char *zParent;
5193 const char *zParentCol;
5194 const char *zParentSeq;
5195 const char *zChild;
5196 const char *zChildCol;
drh96ada592016-12-29 19:48:46 +00005197 const char *zChildSeq = 0; /* Initialize to avoid false-positive warning */
dan35ac58e2016-12-14 19:28:27 +00005198 int rc;
mistachkine16a3502017-05-29 03:48:13 +00005199
dan35ac58e2016-12-14 19:28:27 +00005200 assert( nVal==4 );
5201 zParent = (const char*)sqlite3_value_text(apVal[0]);
5202 zParentCol = (const char*)sqlite3_value_text(apVal[1]);
5203 zChild = (const char*)sqlite3_value_text(apVal[2]);
5204 zChildCol = (const char*)sqlite3_value_text(apVal[3]);
5205
5206 sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
5207 rc = sqlite3_table_column_metadata(
5208 db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
5209 );
5210 if( rc==SQLITE_OK ){
5211 rc = sqlite3_table_column_metadata(
5212 db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
5213 );
5214 }
5215
5216 if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
5217 char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
5218 sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
5219 sqlite3_free(z);
5220 }
5221}
5222
5223
5224/*
dan3c7ebeb2016-12-16 17:28:56 +00005225** The implementation of dot-command ".lint fkey-indexes".
dan35ac58e2016-12-14 19:28:27 +00005226*/
dan3c7ebeb2016-12-16 17:28:56 +00005227static int lintFkeyIndexes(
dan35ac58e2016-12-14 19:28:27 +00005228 ShellState *pState, /* Current shell tool state */
5229 char **azArg, /* Array of arguments passed to dot command */
5230 int nArg /* Number of entries in azArg[] */
5231){
dandd9e0be2016-12-16 16:44:27 +00005232 sqlite3 *db = pState->db; /* Database handle to query "main" db of */
5233 FILE *out = pState->out; /* Stream to write non-error output to */
danf9647b62016-12-15 06:01:40 +00005234 int bVerbose = 0; /* If -verbose is present */
5235 int bGroupByParent = 0; /* If -groupbyparent is present */
dandd9e0be2016-12-16 16:44:27 +00005236 int i; /* To iterate through azArg[] */
5237 const char *zIndent = ""; /* How much to indent CREATE INDEX by */
5238 int rc; /* Return code */
5239 sqlite3_stmt *pSql = 0; /* Compiled version of SQL statement below */
dan35ac58e2016-12-14 19:28:27 +00005240
dandd9e0be2016-12-16 16:44:27 +00005241 /*
5242 ** This SELECT statement returns one row for each foreign key constraint
5243 ** in the schema of the main database. The column values are:
5244 **
5245 ** 0. The text of an SQL statement similar to:
5246 **
5247 ** "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
5248 **
5249 ** This is the same SELECT that the foreign keys implementation needs
5250 ** to run internally on child tables. If there is an index that can
5251 ** be used to optimize this query, then it can also be used by the FK
5252 ** implementation to optimize DELETE or UPDATE statements on the parent
5253 ** table.
5254 **
5255 ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
5256 ** the EXPLAIN QUERY PLAN command matches this pattern, then the schema
5257 ** contains an index that can be used to optimize the query.
5258 **
5259 ** 2. Human readable text that describes the child table and columns. e.g.
5260 **
5261 ** "child_table(child_key1, child_key2)"
5262 **
5263 ** 3. Human readable text that describes the parent table and columns. e.g.
5264 **
5265 ** "parent_table(parent_key1, parent_key2)"
5266 **
5267 ** 4. A full CREATE INDEX statement for an index that could be used to
5268 ** optimize DELETE or UPDATE statements on the parent table. e.g.
5269 **
5270 ** "CREATE INDEX child_table_child_key ON child_table(child_key)"
5271 **
5272 ** 5. The name of the parent table.
5273 **
5274 ** These six values are used by the C logic below to generate the report.
5275 */
dan35ac58e2016-12-14 19:28:27 +00005276 const char *zSql =
dandd9e0be2016-12-16 16:44:27 +00005277 "SELECT "
5278 " 'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
5279 " || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
dan50da9382017-04-06 12:06:56 +00005280 " || fkey_collate_clause("
5281 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
dan35ac58e2016-12-14 19:28:27 +00005282 ", "
dandd9e0be2016-12-16 16:44:27 +00005283 " 'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
dan35ac58e2016-12-14 19:28:27 +00005284 " || group_concat('*=?', ' AND ') || ')'"
5285 ", "
dandd9e0be2016-12-16 16:44:27 +00005286 " s.name || '(' || group_concat(f.[from], ', ') || ')'"
dan35ac58e2016-12-14 19:28:27 +00005287 ", "
dan50da9382017-04-06 12:06:56 +00005288 " f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
dan35ac58e2016-12-14 19:28:27 +00005289 ", "
dandd9e0be2016-12-16 16:44:27 +00005290 " 'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
5291 " || ' ON ' || quote(s.name) || '('"
5292 " || group_concat(quote(f.[from]) ||"
dan50da9382017-04-06 12:06:56 +00005293 " fkey_collate_clause("
5294 " f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
dan35ac58e2016-12-14 19:28:27 +00005295 " || ');'"
danf9647b62016-12-15 06:01:40 +00005296 ", "
dandd9e0be2016-12-16 16:44:27 +00005297 " f.[table] "
dandd9e0be2016-12-16 16:44:27 +00005298 "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
dan50da9382017-04-06 12:06:56 +00005299 "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
dandd9e0be2016-12-16 16:44:27 +00005300 "GROUP BY s.name, f.id "
5301 "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
dan35ac58e2016-12-14 19:28:27 +00005302 ;
dan54e2efc2017-04-06 14:56:26 +00005303 const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
dan35ac58e2016-12-14 19:28:27 +00005304
dan3c7ebeb2016-12-16 17:28:56 +00005305 for(i=2; i<nArg; i++){
drh344a1bf2016-12-22 14:53:25 +00005306 int n = (int)strlen(azArg[i]);
danf9647b62016-12-15 06:01:40 +00005307 if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
5308 bVerbose = 1;
5309 }
5310 else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
5311 bGroupByParent = 1;
5312 zIndent = " ";
5313 }
5314 else{
dan3c7ebeb2016-12-16 17:28:56 +00005315 raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
5316 azArg[0], azArg[1]
5317 );
danf9647b62016-12-15 06:01:40 +00005318 return SQLITE_ERROR;
5319 }
dan35ac58e2016-12-14 19:28:27 +00005320 }
mistachkine16a3502017-05-29 03:48:13 +00005321
dan35ac58e2016-12-14 19:28:27 +00005322 /* Register the fkey_collate_clause() SQL function */
dandd9e0be2016-12-16 16:44:27 +00005323 rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
5324 0, shellFkeyCollateClause, 0, 0
5325 );
dan35ac58e2016-12-14 19:28:27 +00005326
5327
5328 if( rc==SQLITE_OK ){
5329 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
5330 }
danf9647b62016-12-15 06:01:40 +00005331 if( rc==SQLITE_OK ){
5332 sqlite3_bind_int(pSql, 1, bGroupByParent);
5333 }
dan35ac58e2016-12-14 19:28:27 +00005334
5335 if( rc==SQLITE_OK ){
5336 int rc2;
danf9647b62016-12-15 06:01:40 +00005337 char *zPrev = 0;
dan35ac58e2016-12-14 19:28:27 +00005338 while( SQLITE_ROW==sqlite3_step(pSql) ){
5339 int res = -1;
5340 sqlite3_stmt *pExplain = 0;
5341 const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
5342 const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
5343 const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
5344 const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
5345 const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
danf9647b62016-12-15 06:01:40 +00005346 const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
dan35ac58e2016-12-14 19:28:27 +00005347
5348 rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
5349 if( rc!=SQLITE_OK ) break;
5350 if( SQLITE_ROW==sqlite3_step(pExplain) ){
5351 const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
dan54e2efc2017-04-06 14:56:26 +00005352 res = (
5353 0==sqlite3_strglob(zGlob, zPlan)
5354 || 0==sqlite3_strglob(zGlobIPK, zPlan)
5355 );
dan35ac58e2016-12-14 19:28:27 +00005356 }
5357 rc = sqlite3_finalize(pExplain);
5358 if( rc!=SQLITE_OK ) break;
5359
5360 if( res<0 ){
5361 raw_printf(stderr, "Error: internal error");
5362 break;
danf9647b62016-12-15 06:01:40 +00005363 }else{
mistachkine16a3502017-05-29 03:48:13 +00005364 if( bGroupByParent
danf9647b62016-12-15 06:01:40 +00005365 && (bVerbose || res==0)
mistachkine16a3502017-05-29 03:48:13 +00005366 && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
danf9647b62016-12-15 06:01:40 +00005367 ){
5368 raw_printf(out, "-- Parent table %s\n", zParent);
5369 sqlite3_free(zPrev);
5370 zPrev = sqlite3_mprintf("%s", zParent);
5371 }
5372
5373 if( res==0 ){
5374 raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
5375 }else if( bVerbose ){
mistachkine16a3502017-05-29 03:48:13 +00005376 raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
danf9647b62016-12-15 06:01:40 +00005377 zIndent, zFrom, zTarget
5378 );
5379 }
dan35ac58e2016-12-14 19:28:27 +00005380 }
5381 }
danf9647b62016-12-15 06:01:40 +00005382 sqlite3_free(zPrev);
dan35ac58e2016-12-14 19:28:27 +00005383
5384 if( rc!=SQLITE_OK ){
5385 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5386 }
5387
5388 rc2 = sqlite3_finalize(pSql);
5389 if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
5390 rc = rc2;
5391 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5392 }
5393 }else{
5394 raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
5395 }
5396
5397 return rc;
5398}
dan3c7ebeb2016-12-16 17:28:56 +00005399
dan35ac58e2016-12-14 19:28:27 +00005400/*
dan3c7ebeb2016-12-16 17:28:56 +00005401** Implementation of ".lint" dot command.
5402*/
5403static int lintDotCommand(
5404 ShellState *pState, /* Current shell tool state */
5405 char **azArg, /* Array of arguments passed to dot command */
5406 int nArg /* Number of entries in azArg[] */
5407){
5408 int n;
drh96ada592016-12-29 19:48:46 +00005409 n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
dan3c7ebeb2016-12-16 17:28:56 +00005410 if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
5411 return lintFkeyIndexes(pState, azArg, nArg);
5412
5413 usage:
5414 raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
5415 raw_printf(stderr, "Where sub-commands are:\n");
5416 raw_printf(stderr, " fkey-indexes\n");
5417 return SQLITE_ERROR;
5418}
5419
dan35ac58e2016-12-14 19:28:27 +00005420
drhcd0509e2016-09-16 00:26:08 +00005421/*
drh75897232000-05-29 14:26:00 +00005422** If an input line begins with "." then invoke this routine to
5423** process that line.
drh67505e72002-04-19 12:34:06 +00005424**
drh47ad6842006-11-08 12:25:42 +00005425** Return 1 on error, 2 to exit, and 0 otherwise.
drh75897232000-05-29 14:26:00 +00005426*/
drhdcd87a92014-08-18 13:45:42 +00005427static int do_meta_command(char *zLine, ShellState *p){
mistachkin8e189222015-04-19 21:43:16 +00005428 int h = 1;
drh75897232000-05-29 14:26:00 +00005429 int nArg = 0;
5430 int n, c;
drh67505e72002-04-19 12:34:06 +00005431 int rc = 0;
drh75897232000-05-29 14:26:00 +00005432 char *azArg[50];
5433
5434 /* Parse the input line into tokens.
5435 */
mistachkin8e189222015-04-19 21:43:16 +00005436 while( zLine[h] && nArg<ArraySize(azArg) ){
5437 while( IsSpace(zLine[h]) ){ h++; }
5438 if( zLine[h]==0 ) break;
5439 if( zLine[h]=='\'' || zLine[h]=='"' ){
5440 int delim = zLine[h++];
5441 azArg[nArg++] = &zLine[h];
mistachkin1fe36bb2016-04-04 02:16:44 +00005442 while( zLine[h] && zLine[h]!=delim ){
mistachkin8e189222015-04-19 21:43:16 +00005443 if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
mistachkin1fe36bb2016-04-04 02:16:44 +00005444 h++;
drh4c56b992013-06-27 13:26:55 +00005445 }
mistachkin8e189222015-04-19 21:43:16 +00005446 if( zLine[h]==delim ){
5447 zLine[h++] = 0;
drh75897232000-05-29 14:26:00 +00005448 }
drhfeac5f82004-08-01 00:10:45 +00005449 if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00005450 }else{
mistachkin8e189222015-04-19 21:43:16 +00005451 azArg[nArg++] = &zLine[h];
5452 while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
5453 if( zLine[h] ) zLine[h++] = 0;
drhfeac5f82004-08-01 00:10:45 +00005454 resolve_backslashes(azArg[nArg-1]);
drh75897232000-05-29 14:26:00 +00005455 }
5456 }
5457
5458 /* Process the input line.
5459 */
shane9bd1b442009-10-23 01:27:39 +00005460 if( nArg==0 ) return 0; /* no tokens, no error */
drh4f21c4a2008-12-10 22:15:00 +00005461 n = strlen30(azArg[0]);
drh75897232000-05-29 14:26:00 +00005462 c = azArg[0][0];
drhde613c62016-04-04 17:23:10 +00005463
drha0daa752016-09-16 11:53:10 +00005464#ifndef SQLITE_OMIT_AUTHORIZATION
drhde613c62016-04-04 17:23:10 +00005465 if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
5466 if( nArg!=2 ){
5467 raw_printf(stderr, "Usage: .auth ON|OFF\n");
5468 rc = 1;
5469 goto meta_command_exit;
5470 }
5471 open_db(p, 0);
5472 if( booleanValue(azArg[1]) ){
5473 sqlite3_set_authorizer(p->db, shellAuth, p);
5474 }else{
5475 sqlite3_set_authorizer(p->db, 0, 0);
5476 }
5477 }else
drha0daa752016-09-16 11:53:10 +00005478#endif
drhde613c62016-04-04 17:23:10 +00005479
drh5c7976f2014-02-10 19:59:27 +00005480 if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
5481 || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
5482 ){
drhbc46f022013-01-23 18:53:23 +00005483 const char *zDestFile = 0;
5484 const char *zDb = 0;
drh9ff849f2009-02-04 20:55:57 +00005485 sqlite3 *pDest;
5486 sqlite3_backup *pBackup;
drhbc46f022013-01-23 18:53:23 +00005487 int j;
5488 for(j=1; j<nArg; j++){
5489 const char *z = azArg[j];
5490 if( z[0]=='-' ){
5491 while( z[0]=='-' ) z++;
drhaf664332013-07-18 20:28:29 +00005492 /* No options to process at this time */
drhbc46f022013-01-23 18:53:23 +00005493 {
mistachkinaae280e2015-12-31 19:06:24 +00005494 utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
drhbc46f022013-01-23 18:53:23 +00005495 return 1;
5496 }
5497 }else if( zDestFile==0 ){
5498 zDestFile = azArg[j];
5499 }else if( zDb==0 ){
5500 zDb = zDestFile;
5501 zDestFile = azArg[j];
5502 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005503 raw_printf(stderr, "too many arguments to .backup\n");
drhbc46f022013-01-23 18:53:23 +00005504 return 1;
5505 }
drh9ff849f2009-02-04 20:55:57 +00005506 }
drhbc46f022013-01-23 18:53:23 +00005507 if( zDestFile==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005508 raw_printf(stderr, "missing FILENAME argument on .backup\n");
drhbc46f022013-01-23 18:53:23 +00005509 return 1;
5510 }
5511 if( zDb==0 ) zDb = "main";
drh9ff849f2009-02-04 20:55:57 +00005512 rc = sqlite3_open(zDestFile, &pDest);
5513 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00005514 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
drh9ff849f2009-02-04 20:55:57 +00005515 sqlite3_close(pDest);
5516 return 1;
5517 }
drh05782482013-10-24 15:20:20 +00005518 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00005519 pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
5520 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005521 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
drh9ff849f2009-02-04 20:55:57 +00005522 sqlite3_close(pDest);
5523 return 1;
5524 }
5525 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
5526 sqlite3_backup_finish(pBackup);
5527 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00005528 rc = 0;
drh9ff849f2009-02-04 20:55:57 +00005529 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005530 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
shane9bd1b442009-10-23 01:27:39 +00005531 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00005532 }
5533 sqlite3_close(pDest);
5534 }else
5535
drhc2ce0be2014-05-29 12:36:14 +00005536 if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
5537 if( nArg==2 ){
5538 bail_on_error = booleanValue(azArg[1]);
5539 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005540 raw_printf(stderr, "Usage: .bail on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005541 rc = 1;
5542 }
drhc49f44e2006-10-26 18:15:42 +00005543 }else
5544
mistachkinf21979d2015-01-18 05:35:01 +00005545 if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
5546 if( nArg==2 ){
mistachkinbdffff92015-01-19 20:22:33 +00005547 if( booleanValue(azArg[1]) ){
mistachkin1fe36bb2016-04-04 02:16:44 +00005548 setBinaryMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00005549 }else{
mistachkin1fe36bb2016-04-04 02:16:44 +00005550 setTextMode(p->out, 1);
mistachkinbdffff92015-01-19 20:22:33 +00005551 }
mistachkinf21979d2015-01-18 05:35:01 +00005552 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005553 raw_printf(stderr, "Usage: .binary on|off\n");
mistachkinf21979d2015-01-18 05:35:01 +00005554 rc = 1;
5555 }
5556 }else
5557
drh453ca042017-05-22 18:00:34 +00005558 if( c=='c' && strcmp(azArg[0],"cd")==0 ){
5559 if( nArg==2 ){
5560#if defined(_WIN32) || defined(WIN32)
5561 wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
5562 rc = !SetCurrentDirectoryW(z);
5563 sqlite3_free(z);
5564#else
5565 rc = chdir(azArg[1]);
5566#endif
5567 if( rc ){
5568 utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
5569 rc = 1;
5570 }
5571 }else{
5572 raw_printf(stderr, "Usage: .cd DIRECTORY\n");
5573 rc = 1;
5574 }
5575 }else
5576
drhd8621b92012-04-17 09:09:33 +00005577 /* The undocumented ".breakpoint" command causes a call to the no-op
5578 ** routine named test_breakpoint().
5579 */
5580 if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
5581 test_breakpoint();
5582 }else
5583
drhdf12f1c2015-12-07 21:46:19 +00005584 if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
5585 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00005586 setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
drhdf12f1c2015-12-07 21:46:19 +00005587 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005588 raw_printf(stderr, "Usage: .changes on|off\n");
drhdf12f1c2015-12-07 21:46:19 +00005589 rc = 1;
5590 }
5591 }else
5592
drh2db82112016-09-15 21:35:24 +00005593 /* Cancel output redirection, if it is currently set (by .testcase)
5594 ** Then read the content of the testcase-out.txt file and compare against
5595 ** azArg[1]. If there are differences, report an error and exit.
5596 */
5597 if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
5598 char *zRes = 0;
5599 output_reset(p);
5600 if( nArg!=2 ){
5601 raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
drh760c8162016-09-16 02:52:22 +00005602 rc = 2;
dan11da0022016-12-17 08:18:05 +00005603 }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
drh2db82112016-09-15 21:35:24 +00005604 raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
5605 rc = 2;
5606 }else if( testcase_glob(azArg[1],zRes)==0 ){
mistachkin8145fc62016-09-16 20:39:21 +00005607 utf8_printf(stderr,
drh760c8162016-09-16 02:52:22 +00005608 "testcase-%s FAILED\n Expected: [%s]\n Got: [%s]\n",
5609 p->zTestcase, azArg[1], zRes);
drh2db82112016-09-15 21:35:24 +00005610 rc = 2;
drh760c8162016-09-16 02:52:22 +00005611 }else{
mistachkin8145fc62016-09-16 20:39:21 +00005612 utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
drh760c8162016-09-16 02:52:22 +00005613 p->nCheck++;
drh2db82112016-09-15 21:35:24 +00005614 }
5615 sqlite3_free(zRes);
5616 }else
drh2db82112016-09-15 21:35:24 +00005617
drhc2ce0be2014-05-29 12:36:14 +00005618 if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
5619 if( nArg==2 ){
5620 tryToClone(p, azArg[1]);
5621 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005622 raw_printf(stderr, "Usage: .clone FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00005623 rc = 1;
5624 }
mistachkine31ae902014-02-06 01:15:29 +00005625 }else
5626
drhc2ce0be2014-05-29 12:36:14 +00005627 if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005628 ShellState data;
jplyon672a1ed2003-05-11 20:07:05 +00005629 char *zErrMsg = 0;
drh05782482013-10-24 15:20:20 +00005630 open_db(p, 0);
jplyon672a1ed2003-05-11 20:07:05 +00005631 memcpy(&data, p, sizeof(data));
drhb20a61b2016-12-24 18:18:58 +00005632 data.showHeader = 0;
5633 data.cMode = data.mode = MODE_List;
5634 sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
drh0b2110c2004-10-26 00:08:10 +00005635 data.cnt = 0;
drhb20a61b2016-12-24 18:18:58 +00005636 sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
5637 callback, &data, &zErrMsg);
jplyon672a1ed2003-05-11 20:07:05 +00005638 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00005639 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00005640 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00005641 rc = 1;
jplyon6a65bb32003-05-04 07:25:57 +00005642 }
5643 }else
5644
drh0e55db12015-02-06 14:51:13 +00005645 if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
5646 rc = shell_dbinfo_command(p, nArg, azArg);
5647 }else
5648
drhc2ce0be2014-05-29 12:36:14 +00005649 if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
drhe611f142017-03-08 11:44:00 +00005650 const char *zLike = 0;
5651 int i;
drh72507d42017-04-08 00:55:13 +00005652 int savedShowHeader = p->showHeader;
drhdbc26722017-07-10 18:04:41 +00005653 ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
drhe611f142017-03-08 11:44:00 +00005654 for(i=1; i<nArg; i++){
5655 if( azArg[i][0]=='-' ){
5656 const char *z = azArg[i]+1;
5657 if( z[0]=='-' ) z++;
5658 if( strcmp(z,"preserve-rowids")==0 ){
drh34ad36b2017-03-25 18:15:05 +00005659#ifdef SQLITE_OMIT_VIRTUALTABLE
5660 raw_printf(stderr, "The --preserve-rowids option is not compatible"
5661 " with SQLITE_OMIT_VIRTUALTABLE\n");
5662 rc = 1;
5663 goto meta_command_exit;
5664#else
drhe6e1d122017-03-09 13:50:49 +00005665 ShellSetFlag(p, SHFLG_PreserveRowid);
drh34ad36b2017-03-25 18:15:05 +00005666#endif
drhe611f142017-03-08 11:44:00 +00005667 }else
drhdbc26722017-07-10 18:04:41 +00005668 if( strcmp(z,"newlines")==0 ){
5669 ShellSetFlag(p, SHFLG_Newlines);
5670 }else
drhe611f142017-03-08 11:44:00 +00005671 {
5672 raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
5673 rc = 1;
5674 goto meta_command_exit;
5675 }
5676 }else if( zLike ){
drhdbc26722017-07-10 18:04:41 +00005677 raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
5678 "?--newlines? ?LIKE-PATTERN?\n");
drhe611f142017-03-08 11:44:00 +00005679 rc = 1;
5680 goto meta_command_exit;
5681 }else{
5682 zLike = azArg[i];
5683 }
5684 }
drh05782482013-10-24 15:20:20 +00005685 open_db(p, 0);
drhf1dfc4f2009-09-23 15:51:35 +00005686 /* When playing back a "dump", the content might appear in an order
5687 ** which causes immediate foreign key constraints to be violated.
5688 ** So disable foreign-key constraint enforcement to prevent problems. */
mistachkinaae280e2015-12-31 19:06:24 +00005689 raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
5690 raw_printf(p->out, "BEGIN TRANSACTION;\n");
drh45e29d82006-11-20 16:21:10 +00005691 p->writableSchema = 0;
drh72507d42017-04-08 00:55:13 +00005692 p->showHeader = 0;
drhe611f142017-03-08 11:44:00 +00005693 /* Set writable_schema=ON since doing so forces SQLite to initialize
5694 ** as much of the schema as it can even if the sqlite_master table is
5695 ** corrupt. */
drh56197952011-10-13 16:30:13 +00005696 sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
drh2f464a02011-10-13 00:41:49 +00005697 p->nErr = 0;
drhe611f142017-03-08 11:44:00 +00005698 if( zLike==0 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00005699 run_schema_dump_query(p,
drha18c5682000-10-08 22:20:57 +00005700 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00005701 "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
drh4f324762009-05-21 14:51:03 +00005702 );
mistachkin1fe36bb2016-04-04 02:16:44 +00005703 run_schema_dump_query(p,
drh4f324762009-05-21 14:51:03 +00005704 "SELECT name, type, sql FROM sqlite_master "
drh2f464a02011-10-13 00:41:49 +00005705 "WHERE name=='sqlite_sequence'"
drh0b9a5942006-09-13 20:22:02 +00005706 );
drh2f464a02011-10-13 00:41:49 +00005707 run_table_dump_query(p,
drh0b9a5942006-09-13 20:22:02 +00005708 "SELECT sql FROM sqlite_master "
drh157e29a2009-05-21 15:15:00 +00005709 "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
drha18c5682000-10-08 22:20:57 +00005710 );
drh4c653a02000-06-07 01:27:47 +00005711 }else{
drhe611f142017-03-08 11:44:00 +00005712 char *zSql;
5713 zSql = sqlite3_mprintf(
5714 "SELECT name, type, sql FROM sqlite_master "
5715 "WHERE tbl_name LIKE %Q AND type=='table'"
5716 " AND sql NOT NULL", zLike);
5717 run_schema_dump_query(p,zSql);
5718 sqlite3_free(zSql);
5719 zSql = sqlite3_mprintf(
5720 "SELECT sql FROM sqlite_master "
5721 "WHERE sql NOT NULL"
5722 " AND type IN ('index','trigger','view')"
5723 " AND tbl_name LIKE %Q", zLike);
5724 run_table_dump_query(p, zSql, 0);
5725 sqlite3_free(zSql);
drh4c653a02000-06-07 01:27:47 +00005726 }
drh45e29d82006-11-20 16:21:10 +00005727 if( p->writableSchema ){
mistachkinaae280e2015-12-31 19:06:24 +00005728 raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
drh45e29d82006-11-20 16:21:10 +00005729 p->writableSchema = 0;
5730 }
drh56197952011-10-13 16:30:13 +00005731 sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
5732 sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
mistachkinaae280e2015-12-31 19:06:24 +00005733 raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
drh72507d42017-04-08 00:55:13 +00005734 p->showHeader = savedShowHeader;
drh4c653a02000-06-07 01:27:47 +00005735 }else
drh75897232000-05-29 14:26:00 +00005736
drhc2ce0be2014-05-29 12:36:14 +00005737 if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
5738 if( nArg==2 ){
drhe6e1d122017-03-09 13:50:49 +00005739 setOrClearFlag(p, SHFLG_Echo, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00005740 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005741 raw_printf(stderr, "Usage: .echo on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005742 rc = 1;
5743 }
drhdaffd0e2001-04-11 14:28:42 +00005744 }else
5745
drhc2ce0be2014-05-29 12:36:14 +00005746 if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
5747 if( nArg==2 ){
drheacd29d2016-04-15 15:03:27 +00005748 if( strcmp(azArg[1],"full")==0 ){
5749 p->autoEQP = 2;
5750 }else{
5751 p->autoEQP = booleanValue(azArg[1]);
5752 }
drhc2ce0be2014-05-29 12:36:14 +00005753 }else{
drheacd29d2016-04-15 15:03:27 +00005754 raw_printf(stderr, "Usage: .eqp on|off|full\n");
drhc2ce0be2014-05-29 12:36:14 +00005755 rc = 1;
mistachkin1fe36bb2016-04-04 02:16:44 +00005756 }
drhefbf3b12014-02-28 20:47:24 +00005757 }else
5758
drhd3ac7d92013-01-25 18:33:43 +00005759 if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
drh348d19c2013-06-03 12:47:43 +00005760 if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
drh47ad6842006-11-08 12:25:42 +00005761 rc = 2;
drh75897232000-05-29 14:26:00 +00005762 }else
5763
drhc31b79d2017-06-29 21:11:27 +00005764 /* The ".explain" command is automatic now. It is largely pointless. It
5765 ** retained purely for backwards compatibility */
drhc2ce0be2014-05-29 12:36:14 +00005766 if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
drh700c2522016-02-09 18:39:25 +00005767 int val = 1;
5768 if( nArg>=2 ){
5769 if( strcmp(azArg[1],"auto")==0 ){
5770 val = 99;
5771 }else{
5772 val = booleanValue(azArg[1]);
persicom7e2dfdd2002-04-18 02:46:52 +00005773 }
drh700c2522016-02-09 18:39:25 +00005774 }
5775 if( val==1 && p->mode!=MODE_Explain ){
5776 p->normalMode = p->mode;
danielk19770d78bae2008-01-03 07:09:48 +00005777 p->mode = MODE_Explain;
drh700c2522016-02-09 18:39:25 +00005778 p->autoExplain = 0;
5779 }else if( val==0 ){
5780 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5781 p->autoExplain = 0;
5782 }else if( val==99 ){
5783 if( p->mode==MODE_Explain ) p->mode = p->normalMode;
5784 p->autoExplain = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00005785 }
drh75897232000-05-29 14:26:00 +00005786 }else
5787
drhc1971542014-06-23 23:28:13 +00005788 if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
drhdcd87a92014-08-18 13:45:42 +00005789 ShellState data;
drhc1971542014-06-23 23:28:13 +00005790 char *zErrMsg = 0;
drh56f674c2014-07-18 14:43:29 +00005791 int doStats = 0;
drh4926fec2016-04-13 15:33:42 +00005792 memcpy(&data, p, sizeof(data));
5793 data.showHeader = 0;
5794 data.cMode = data.mode = MODE_Semi;
5795 if( nArg==2 && optionMatch(azArg[1], "indent") ){
5796 data.cMode = data.mode = MODE_Pretty;
5797 nArg = 1;
5798 }
drhc1971542014-06-23 23:28:13 +00005799 if( nArg!=1 ){
drh4926fec2016-04-13 15:33:42 +00005800 raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
drhc1971542014-06-23 23:28:13 +00005801 rc = 1;
5802 goto meta_command_exit;
5803 }
5804 open_db(p, 0);
drhc1971542014-06-23 23:28:13 +00005805 rc = sqlite3_exec(p->db,
5806 "SELECT sql FROM"
5807 " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
5808 " FROM sqlite_master UNION ALL"
5809 " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
drh4b2590e2014-08-19 19:28:00 +00005810 "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
drhc1971542014-06-23 23:28:13 +00005811 "ORDER BY rowid",
5812 callback, &data, &zErrMsg
5813 );
drh56f674c2014-07-18 14:43:29 +00005814 if( rc==SQLITE_OK ){
5815 sqlite3_stmt *pStmt;
5816 rc = sqlite3_prepare_v2(p->db,
5817 "SELECT rowid FROM sqlite_master"
5818 " WHERE name GLOB 'sqlite_stat[134]'",
5819 -1, &pStmt, 0);
5820 doStats = sqlite3_step(pStmt)==SQLITE_ROW;
5821 sqlite3_finalize(pStmt);
5822 }
5823 if( doStats==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005824 raw_printf(p->out, "/* No STAT tables available */\n");
drh56f674c2014-07-18 14:43:29 +00005825 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005826 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005827 sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
5828 callback, &data, &zErrMsg);
drh700c2522016-02-09 18:39:25 +00005829 data.cMode = data.mode = MODE_Insert;
drh56f674c2014-07-18 14:43:29 +00005830 data.zDestTable = "sqlite_stat1";
5831 shell_exec(p->db, "SELECT * FROM sqlite_stat1",
5832 shell_callback, &data,&zErrMsg);
5833 data.zDestTable = "sqlite_stat3";
5834 shell_exec(p->db, "SELECT * FROM sqlite_stat3",
5835 shell_callback, &data,&zErrMsg);
5836 data.zDestTable = "sqlite_stat4";
5837 shell_exec(p->db, "SELECT * FROM sqlite_stat4",
5838 shell_callback, &data, &zErrMsg);
mistachkinaae280e2015-12-31 19:06:24 +00005839 raw_printf(p->out, "ANALYZE sqlite_master;\n");
drh56f674c2014-07-18 14:43:29 +00005840 }
drhc1971542014-06-23 23:28:13 +00005841 }else
5842
drhc2ce0be2014-05-29 12:36:14 +00005843 if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
5844 if( nArg==2 ){
5845 p->showHeader = booleanValue(azArg[1]);
5846 }else{
mistachkinaae280e2015-12-31 19:06:24 +00005847 raw_printf(stderr, "Usage: .headers on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00005848 rc = 1;
shaneb320ccd2009-10-21 03:42:58 +00005849 }
drh75897232000-05-29 14:26:00 +00005850 }else
5851
drhc2ce0be2014-05-29 12:36:14 +00005852 if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005853 utf8_printf(p->out, "%s", zHelp);
drhc2ce0be2014-05-29 12:36:14 +00005854 }else
5855
5856 if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
drh01f37542014-05-31 15:43:33 +00005857 char *zTable; /* Insert data into this table */
5858 char *zFile; /* Name of file to extra content from */
shane916f9612009-10-23 00:37:15 +00005859 sqlite3_stmt *pStmt = NULL; /* A statement */
drhfeac5f82004-08-01 00:10:45 +00005860 int nCol; /* Number of columns in the table */
5861 int nByte; /* Number of bytes in an SQL string */
5862 int i, j; /* Loop counters */
drh2d463112013-08-06 14:36:36 +00005863 int needCommit; /* True to COMMIT or ROLLBACK at end */
mistachkin636bf9f2014-07-19 20:15:16 +00005864 int nSep; /* Number of bytes in p->colSeparator[] */
drhfeac5f82004-08-01 00:10:45 +00005865 char *zSql; /* An SQL statement */
mistachkin636bf9f2014-07-19 20:15:16 +00005866 ImportCtx sCtx; /* Reader context */
mistachkin44723ce2015-03-21 02:22:37 +00005867 char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
5868 int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */
drhfeac5f82004-08-01 00:10:45 +00005869
drhc2ce0be2014-05-29 12:36:14 +00005870 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00005871 raw_printf(stderr, "Usage: .import FILE TABLE\n");
drhc2ce0be2014-05-29 12:36:14 +00005872 goto meta_command_exit;
5873 }
drh01f37542014-05-31 15:43:33 +00005874 zFile = azArg[1];
5875 zTable = azArg[2];
drhdb95f682013-06-26 22:46:00 +00005876 seenInterrupt = 0;
mistachkin636bf9f2014-07-19 20:15:16 +00005877 memset(&sCtx, 0, sizeof(sCtx));
drh05782482013-10-24 15:20:20 +00005878 open_db(p, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005879 nSep = strlen30(p->colSeparator);
drhfeac5f82004-08-01 00:10:45 +00005880 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005881 raw_printf(stderr,
5882 "Error: non-null column separator required for import\n");
shane916f9612009-10-23 00:37:15 +00005883 return 1;
drhfeac5f82004-08-01 00:10:45 +00005884 }
drhdb95f682013-06-26 22:46:00 +00005885 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005886 raw_printf(stderr, "Error: multi-character column separators not allowed"
drhdb95f682013-06-26 22:46:00 +00005887 " for import\n");
5888 return 1;
5889 }
mistachkin636bf9f2014-07-19 20:15:16 +00005890 nSep = strlen30(p->rowSeparator);
5891 if( nSep==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005892 raw_printf(stderr, "Error: non-null row separator required for import\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005893 return 1;
5894 }
mistachkine0d68852014-12-11 03:12:33 +00005895 if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
5896 /* When importing CSV (only), if the row separator is set to the
5897 ** default output row separator, change it to the default input
5898 ** row separator. This avoids having to maintain different input
5899 ** and output row separators. */
5900 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
5901 nSep = strlen30(p->rowSeparator);
5902 }
mistachkin636bf9f2014-07-19 20:15:16 +00005903 if( nSep>1 ){
mistachkinaae280e2015-12-31 19:06:24 +00005904 raw_printf(stderr, "Error: multi-character row separators not allowed"
mistachkin636bf9f2014-07-19 20:15:16 +00005905 " for import\n");
5906 return 1;
5907 }
5908 sCtx.zFile = zFile;
5909 sCtx.nLine = 1;
5910 if( sCtx.zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00005911#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00005912 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00005913 return 1;
5914#else
mistachkin636bf9f2014-07-19 20:15:16 +00005915 sCtx.in = popen(sCtx.zFile+1, "r");
5916 sCtx.zFile = "<pipe>";
drh5bde8162013-06-27 14:07:53 +00005917 xCloser = pclose;
drh8cd5b252015-03-02 22:06:43 +00005918#endif
drh5bde8162013-06-27 14:07:53 +00005919 }else{
mistachkin636bf9f2014-07-19 20:15:16 +00005920 sCtx.in = fopen(sCtx.zFile, "rb");
drh5bde8162013-06-27 14:07:53 +00005921 xCloser = fclose;
5922 }
mistachkin636bf9f2014-07-19 20:15:16 +00005923 if( p->mode==MODE_Ascii ){
5924 xRead = ascii_read_one_field;
5925 }else{
5926 xRead = csv_read_one_field;
5927 }
5928 if( sCtx.in==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005929 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
drhdb95f682013-06-26 22:46:00 +00005930 return 1;
5931 }
mistachkin636bf9f2014-07-19 20:15:16 +00005932 sCtx.cColSep = p->colSeparator[0];
5933 sCtx.cRowSep = p->rowSeparator[0];
drh7b075e32011-09-28 01:10:00 +00005934 zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
shane916f9612009-10-23 00:37:15 +00005935 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005936 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005937 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005938 return 1;
5939 }
drh4f21c4a2008-12-10 22:15:00 +00005940 nByte = strlen30(zSql);
drhc7181902014-02-27 15:04:13 +00005941 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
mistachkin636bf9f2014-07-19 20:15:16 +00005942 import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */
mistachkin8e189222015-04-19 21:43:16 +00005943 if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
drhdb95f682013-06-26 22:46:00 +00005944 char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
5945 char cSep = '(';
mistachkin636bf9f2014-07-19 20:15:16 +00005946 while( xRead(&sCtx) ){
drhd8c22ac2016-02-25 13:33:02 +00005947 zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z);
drhdb95f682013-06-26 22:46:00 +00005948 cSep = ',';
mistachkin636bf9f2014-07-19 20:15:16 +00005949 if( sCtx.cTerm!=sCtx.cColSep ) break;
drhdb95f682013-06-26 22:46:00 +00005950 }
drh5bde8162013-06-27 14:07:53 +00005951 if( cSep=='(' ){
5952 sqlite3_free(zCreate);
mistachkin636bf9f2014-07-19 20:15:16 +00005953 sqlite3_free(sCtx.z);
5954 xCloser(sCtx.in);
mistachkinaae280e2015-12-31 19:06:24 +00005955 utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
drh5bde8162013-06-27 14:07:53 +00005956 return 1;
5957 }
drhdb95f682013-06-26 22:46:00 +00005958 zCreate = sqlite3_mprintf("%z\n)", zCreate);
5959 rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
5960 sqlite3_free(zCreate);
5961 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005962 utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
mistachkin8e189222015-04-19 21:43:16 +00005963 sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005964 sqlite3_free(sCtx.z);
5965 xCloser(sCtx.in);
drhdb95f682013-06-26 22:46:00 +00005966 return 1;
5967 }
drhc7181902014-02-27 15:04:13 +00005968 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005969 }
drhfeac5f82004-08-01 00:10:45 +00005970 sqlite3_free(zSql);
5971 if( rc ){
shane916f9612009-10-23 00:37:15 +00005972 if (pStmt) sqlite3_finalize(pStmt);
mistachkinaae280e2015-12-31 19:06:24 +00005973 utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
mistachkin636bf9f2014-07-19 20:15:16 +00005974 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005975 return 1;
drhfeac5f82004-08-01 00:10:45 +00005976 }
shane916f9612009-10-23 00:37:15 +00005977 nCol = sqlite3_column_count(pStmt);
drhfeac5f82004-08-01 00:10:45 +00005978 sqlite3_finalize(pStmt);
shane916f9612009-10-23 00:37:15 +00005979 pStmt = 0;
shane9bd1b442009-10-23 01:27:39 +00005980 if( nCol==0 ) return 0; /* no columns, no error */
drhf3cdcdc2015-04-29 16:50:28 +00005981 zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
shane916f9612009-10-23 00:37:15 +00005982 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00005983 raw_printf(stderr, "Error: out of memory\n");
mistachkin636bf9f2014-07-19 20:15:16 +00005984 xCloser(sCtx.in);
shane916f9612009-10-23 00:37:15 +00005985 return 1;
5986 }
drhdb95f682013-06-26 22:46:00 +00005987 sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
drh4f21c4a2008-12-10 22:15:00 +00005988 j = strlen30(zSql);
drhfeac5f82004-08-01 00:10:45 +00005989 for(i=1; i<nCol; i++){
5990 zSql[j++] = ',';
5991 zSql[j++] = '?';
5992 }
5993 zSql[j++] = ')';
5994 zSql[j] = 0;
drhc7181902014-02-27 15:04:13 +00005995 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
drhdb95f682013-06-26 22:46:00 +00005996 sqlite3_free(zSql);
drhfeac5f82004-08-01 00:10:45 +00005997 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00005998 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane916f9612009-10-23 00:37:15 +00005999 if (pStmt) sqlite3_finalize(pStmt);
mistachkin636bf9f2014-07-19 20:15:16 +00006000 xCloser(sCtx.in);
drh47ad6842006-11-08 12:25:42 +00006001 return 1;
drhfeac5f82004-08-01 00:10:45 +00006002 }
mistachkin8e189222015-04-19 21:43:16 +00006003 needCommit = sqlite3_get_autocommit(p->db);
6004 if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
drhdb95f682013-06-26 22:46:00 +00006005 do{
mistachkin636bf9f2014-07-19 20:15:16 +00006006 int startLine = sCtx.nLine;
drhfeac5f82004-08-01 00:10:45 +00006007 for(i=0; i<nCol; i++){
mistachkin636bf9f2014-07-19 20:15:16 +00006008 char *z = xRead(&sCtx);
6009 /*
6010 ** Did we reach end-of-file before finding any columns?
6011 ** If so, stop instead of NULL filling the remaining columns.
6012 */
drhdb95f682013-06-26 22:46:00 +00006013 if( z==0 && i==0 ) break;
mistachkin636bf9f2014-07-19 20:15:16 +00006014 /*
6015 ** Did we reach end-of-file OR end-of-line before finding any
6016 ** columns in ASCII mode? If so, stop instead of NULL filling
6017 ** the remaining columns.
6018 */
6019 if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
drhdb95f682013-06-26 22:46:00 +00006020 sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
mistachkin636bf9f2014-07-19 20:15:16 +00006021 if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
mistachkinaae280e2015-12-31 19:06:24 +00006022 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00006023 "filling the rest with NULL\n",
mistachkin636bf9f2014-07-19 20:15:16 +00006024 sCtx.zFile, startLine, nCol, i+1);
mistachkina0efb1a2015-02-12 22:45:25 +00006025 i += 2;
mistachkin6fe03382014-06-16 22:45:28 +00006026 while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
drh18f52e02012-01-16 16:56:31 +00006027 }
drhfeac5f82004-08-01 00:10:45 +00006028 }
mistachkin636bf9f2014-07-19 20:15:16 +00006029 if( sCtx.cTerm==sCtx.cColSep ){
drhdb95f682013-06-26 22:46:00 +00006030 do{
mistachkin636bf9f2014-07-19 20:15:16 +00006031 xRead(&sCtx);
drhdb95f682013-06-26 22:46:00 +00006032 i++;
mistachkin636bf9f2014-07-19 20:15:16 +00006033 }while( sCtx.cTerm==sCtx.cColSep );
mistachkinaae280e2015-12-31 19:06:24 +00006034 utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
drhdb95f682013-06-26 22:46:00 +00006035 "extras ignored\n",
mistachkin636bf9f2014-07-19 20:15:16 +00006036 sCtx.zFile, startLine, nCol, i);
drhfeac5f82004-08-01 00:10:45 +00006037 }
drhdb95f682013-06-26 22:46:00 +00006038 if( i>=nCol ){
6039 sqlite3_step(pStmt);
6040 rc = sqlite3_reset(pStmt);
6041 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00006042 utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
6043 startLine, sqlite3_errmsg(p->db));
drhdb95f682013-06-26 22:46:00 +00006044 }
6045 }
mistachkin636bf9f2014-07-19 20:15:16 +00006046 }while( sCtx.cTerm!=EOF );
drhdb95f682013-06-26 22:46:00 +00006047
mistachkin636bf9f2014-07-19 20:15:16 +00006048 xCloser(sCtx.in);
6049 sqlite3_free(sCtx.z);
drhfeac5f82004-08-01 00:10:45 +00006050 sqlite3_finalize(pStmt);
mistachkin8e189222015-04-19 21:43:16 +00006051 if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
drhfeac5f82004-08-01 00:10:45 +00006052 }else
6053
drhd12602a2016-12-07 15:49:02 +00006054#ifndef SQLITE_UNTESTABLE
drh16eb5942016-11-03 13:01:38 +00006055 if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
6056 char *zSql;
6057 char *zCollist = 0;
6058 sqlite3_stmt *pStmt;
6059 int tnum = 0;
drh59ce2c42016-11-03 13:12:28 +00006060 int i;
drh16eb5942016-11-03 13:01:38 +00006061 if( nArg!=3 ){
6062 utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
6063 rc = 1;
6064 goto meta_command_exit;
6065 }
6066 open_db(p, 0);
6067 zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
6068 " WHERE name='%q' AND type='index'", azArg[1]);
6069 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6070 sqlite3_free(zSql);
6071 if( sqlite3_step(pStmt)==SQLITE_ROW ){
6072 tnum = sqlite3_column_int(pStmt, 0);
6073 }
6074 sqlite3_finalize(pStmt);
6075 if( tnum==0 ){
6076 utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
6077 rc = 1;
6078 goto meta_command_exit;
6079 }
6080 zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
6081 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
6082 sqlite3_free(zSql);
drh59ce2c42016-11-03 13:12:28 +00006083 i = 0;
drh16eb5942016-11-03 13:01:38 +00006084 while( sqlite3_step(pStmt)==SQLITE_ROW ){
drh59ce2c42016-11-03 13:12:28 +00006085 char zLabel[20];
drh16eb5942016-11-03 13:01:38 +00006086 const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
drh59ce2c42016-11-03 13:12:28 +00006087 i++;
6088 if( zCol==0 ){
6089 if( sqlite3_column_int(pStmt,1)==-1 ){
6090 zCol = "_ROWID_";
6091 }else{
6092 sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
6093 zCol = zLabel;
6094 }
6095 }
drh16eb5942016-11-03 13:01:38 +00006096 if( zCollist==0 ){
6097 zCollist = sqlite3_mprintf("\"%w\"", zCol);
6098 }else{
6099 zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
6100 }
6101 }
6102 sqlite3_finalize(pStmt);
6103 zSql = sqlite3_mprintf(
6104 "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
6105 azArg[2], zCollist, zCollist);
6106 sqlite3_free(zCollist);
6107 rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
6108 if( rc==SQLITE_OK ){
6109 rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
6110 sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
6111 if( rc ){
6112 utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
6113 }else{
6114 utf8_printf(stdout, "%s;\n", zSql);
mistachkin2f9a6132016-11-11 05:19:45 +00006115 raw_printf(stdout,
drh16eb5942016-11-03 13:01:38 +00006116 "WARNING: writing to an imposter table will corrupt the index!\n"
6117 );
6118 }
6119 }else{
mistachkin2f9a6132016-11-11 05:19:45 +00006120 raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
drh16eb5942016-11-03 13:01:38 +00006121 rc = 1;
6122 }
6123 sqlite3_free(zSql);
6124 }else
6125#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
6126
drhae5e4452007-05-03 17:18:36 +00006127#ifdef SQLITE_ENABLE_IOTRACE
drhb0603412007-02-28 04:47:26 +00006128 if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
mistachkin9871a932015-03-27 00:21:52 +00006129 SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
drhb0603412007-02-28 04:47:26 +00006130 if( iotrace && iotrace!=stdout ) fclose(iotrace);
6131 iotrace = 0;
6132 if( nArg<2 ){
mlcreech3a00f902008-03-04 17:45:01 +00006133 sqlite3IoTrace = 0;
drhb0603412007-02-28 04:47:26 +00006134 }else if( strcmp(azArg[1], "-")==0 ){
mlcreech3a00f902008-03-04 17:45:01 +00006135 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00006136 iotrace = stdout;
6137 }else{
6138 iotrace = fopen(azArg[1], "w");
6139 if( iotrace==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006140 utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
mlcreech3a00f902008-03-04 17:45:01 +00006141 sqlite3IoTrace = 0;
shane9bd1b442009-10-23 01:27:39 +00006142 rc = 1;
drhb0603412007-02-28 04:47:26 +00006143 }else{
mlcreech3a00f902008-03-04 17:45:01 +00006144 sqlite3IoTrace = iotracePrintf;
drhb0603412007-02-28 04:47:26 +00006145 }
6146 }
6147 }else
drhae5e4452007-05-03 17:18:36 +00006148#endif
drh16eb5942016-11-03 13:01:38 +00006149
drh1a513372015-05-02 17:40:23 +00006150 if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
6151 static const struct {
6152 const char *zLimitName; /* Name of a limit */
6153 int limitCode; /* Integer code for that limit */
6154 } aLimit[] = {
6155 { "length", SQLITE_LIMIT_LENGTH },
6156 { "sql_length", SQLITE_LIMIT_SQL_LENGTH },
6157 { "column", SQLITE_LIMIT_COLUMN },
6158 { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH },
6159 { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT },
6160 { "vdbe_op", SQLITE_LIMIT_VDBE_OP },
6161 { "function_arg", SQLITE_LIMIT_FUNCTION_ARG },
6162 { "attached", SQLITE_LIMIT_ATTACHED },
6163 { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH },
6164 { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER },
6165 { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH },
6166 { "worker_threads", SQLITE_LIMIT_WORKER_THREADS },
6167 };
6168 int i, n2;
6169 open_db(p, 0);
6170 if( nArg==1 ){
drhf5ed7ad2015-06-15 14:43:25 +00006171 for(i=0; i<ArraySize(aLimit); i++){
mistachkin1fe36bb2016-04-04 02:16:44 +00006172 printf("%20s %d\n", aLimit[i].zLimitName,
drh1a513372015-05-02 17:40:23 +00006173 sqlite3_limit(p->db, aLimit[i].limitCode, -1));
6174 }
6175 }else if( nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006176 raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
drh1a513372015-05-02 17:40:23 +00006177 rc = 1;
6178 goto meta_command_exit;
6179 }else{
6180 int iLimit = -1;
6181 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00006182 for(i=0; i<ArraySize(aLimit); i++){
drh1a513372015-05-02 17:40:23 +00006183 if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
6184 if( iLimit<0 ){
6185 iLimit = i;
6186 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006187 utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
drh1a513372015-05-02 17:40:23 +00006188 rc = 1;
6189 goto meta_command_exit;
6190 }
6191 }
6192 }
6193 if( iLimit<0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006194 utf8_printf(stderr, "unknown limit: \"%s\"\n"
drh1a513372015-05-02 17:40:23 +00006195 "enter \".limits\" with no arguments for a list.\n",
6196 azArg[1]);
6197 rc = 1;
6198 goto meta_command_exit;
6199 }
6200 if( nArg==3 ){
mistachkin2c1820c2015-05-08 01:04:39 +00006201 sqlite3_limit(p->db, aLimit[iLimit].limitCode,
6202 (int)integerValue(azArg[2]));
drh1a513372015-05-02 17:40:23 +00006203 }
6204 printf("%20s %d\n", aLimit[iLimit].zLimitName,
6205 sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
6206 }
6207 }else
drhb0603412007-02-28 04:47:26 +00006208
dan3c7ebeb2016-12-16 17:28:56 +00006209 if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
drh3fd9f332016-12-16 18:41:11 +00006210 open_db(p, 0);
dan3c7ebeb2016-12-16 17:28:56 +00006211 lintDotCommand(p, azArg, nArg);
6212 }else
6213
drh70df4fe2006-06-13 15:12:21 +00006214#ifndef SQLITE_OMIT_LOAD_EXTENSION
drhc2ce0be2014-05-29 12:36:14 +00006215 if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
drh1e397f82006-06-08 15:28:43 +00006216 const char *zFile, *zProc;
6217 char *zErrMsg = 0;
drhc2ce0be2014-05-29 12:36:14 +00006218 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006219 raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
drhc2ce0be2014-05-29 12:36:14 +00006220 rc = 1;
6221 goto meta_command_exit;
6222 }
drh1e397f82006-06-08 15:28:43 +00006223 zFile = azArg[1];
6224 zProc = nArg>=3 ? azArg[2] : 0;
drh05782482013-10-24 15:20:20 +00006225 open_db(p, 0);
drh1e397f82006-06-08 15:28:43 +00006226 rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
6227 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00006228 utf8_printf(stderr, "Error: %s\n", zErrMsg);
drh1e397f82006-06-08 15:28:43 +00006229 sqlite3_free(zErrMsg);
drh47ad6842006-11-08 12:25:42 +00006230 rc = 1;
drh1e397f82006-06-08 15:28:43 +00006231 }
6232 }else
drh70df4fe2006-06-13 15:12:21 +00006233#endif
drh1e397f82006-06-08 15:28:43 +00006234
drhc2ce0be2014-05-29 12:36:14 +00006235 if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
6236 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006237 raw_printf(stderr, "Usage: .log FILENAME\n");
drhc2ce0be2014-05-29 12:36:14 +00006238 rc = 1;
6239 }else{
6240 const char *zFile = azArg[1];
6241 output_file_close(p->pLog);
6242 p->pLog = output_file_open(zFile);
6243 }
drh127f9d72010-02-23 01:47:00 +00006244 }else
6245
drhc2ce0be2014-05-29 12:36:14 +00006246 if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
6247 const char *zMode = nArg>=2 ? azArg[1] : "";
6248 int n2 = (int)strlen(zMode);
6249 int c2 = zMode[0];
6250 if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
drh75897232000-05-29 14:26:00 +00006251 p->mode = MODE_Line;
drh7aee83b2017-01-27 01:52:42 +00006252 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00006253 }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
drh75897232000-05-29 14:26:00 +00006254 p->mode = MODE_Column;
drh7aee83b2017-01-27 01:52:42 +00006255 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00006256 }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
drh75897232000-05-29 14:26:00 +00006257 p->mode = MODE_List;
drh7aee83b2017-01-27 01:52:42 +00006258 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
6259 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00006260 }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
drh1e5d0e92000-05-31 23:33:17 +00006261 p->mode = MODE_Html;
drhc2ce0be2014-05-29 12:36:14 +00006262 }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00006263 p->mode = MODE_Tcl;
mistachkinfad42082014-07-24 22:13:12 +00006264 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
drh7aee83b2017-01-27 01:52:42 +00006265 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
drhc2ce0be2014-05-29 12:36:14 +00006266 }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
drh8e64d1c2004-10-07 00:32:39 +00006267 p->mode = MODE_Csv;
mistachkinfad42082014-07-24 22:13:12 +00006268 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
mistachkine0d68852014-12-11 03:12:33 +00006269 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
drhc2ce0be2014-05-29 12:36:14 +00006270 }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
drhfeac5f82004-08-01 00:10:45 +00006271 p->mode = MODE_List;
mistachkinfad42082014-07-24 22:13:12 +00006272 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
drhc2ce0be2014-05-29 12:36:14 +00006273 }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
drh28bd4bc2000-06-15 15:57:22 +00006274 p->mode = MODE_Insert;
drhc2ce0be2014-05-29 12:36:14 +00006275 set_table_name(p, nArg>=3 ? azArg[2] : "table");
drh41f5f6e2016-10-21 17:39:30 +00006276 }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
6277 p->mode = MODE_Quote;
mistachkin636bf9f2014-07-19 20:15:16 +00006278 }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
6279 p->mode = MODE_Ascii;
mistachkinfad42082014-07-24 22:13:12 +00006280 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
6281 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
drha501f7d2017-06-29 21:33:25 +00006282 }else if( nArg==1 ){
6283 raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
6284 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006285 raw_printf(stderr, "Error: mode should be one of: "
drh36f49d02016-11-23 23:18:45 +00006286 "ascii column csv html insert line list quote tabs tcl\n");
shane9bd1b442009-10-23 01:27:39 +00006287 rc = 1;
drh75897232000-05-29 14:26:00 +00006288 }
drh700c2522016-02-09 18:39:25 +00006289 p->cMode = p->mode;
drh75897232000-05-29 14:26:00 +00006290 }else
6291
drhc2ce0be2014-05-29 12:36:14 +00006292 if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
6293 if( nArg==2 ){
mistachkin44b99f72014-12-11 03:29:14 +00006294 sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
6295 "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
drhc2ce0be2014-05-29 12:36:14 +00006296 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006297 raw_printf(stderr, "Usage: .nullvalue STRING\n");
shanehe2aa9d72009-11-06 17:20:17 +00006298 rc = 1;
6299 }
6300 }else
6301
drh05782482013-10-24 15:20:20 +00006302 if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
drhcd0509e2016-09-16 00:26:08 +00006303 char *zNewFilename; /* Name of the database file to open */
6304 int iName = 1; /* Index in azArg[] of the filename */
drh760c8162016-09-16 02:52:22 +00006305 int newFlag = 0; /* True to delete file before opening */
drhcd0509e2016-09-16 00:26:08 +00006306 /* Close the existing database */
6307 session_close_all(p);
6308 sqlite3_close(p->db);
drh05782482013-10-24 15:20:20 +00006309 p->db = 0;
dan21472212017-03-01 11:30:27 +00006310 p->zDbFilename = 0;
drhcd0509e2016-09-16 00:26:08 +00006311 sqlite3_free(p->zFreeOnClose);
6312 p->zFreeOnClose = 0;
drh760c8162016-09-16 02:52:22 +00006313 /* Check for command-line arguments */
6314 for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
6315 const char *z = azArg[iName];
6316 if( optionMatch(z,"new") ){
6317 newFlag = 1;
6318 }else if( z[0]=='-' ){
6319 utf8_printf(stderr, "unknown option: %s\n", z);
6320 rc = 1;
mistachkin8145fc62016-09-16 20:39:21 +00006321 goto meta_command_exit;
drh760c8162016-09-16 02:52:22 +00006322 }
drhcd0509e2016-09-16 00:26:08 +00006323 }
6324 /* If a filename is specified, try to open it first */
6325 zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
6326 if( zNewFilename ){
drh760c8162016-09-16 02:52:22 +00006327 if( newFlag ) shellDeleteFile(zNewFilename);
drhcd0509e2016-09-16 00:26:08 +00006328 p->zDbFilename = zNewFilename;
6329 open_db(p, 1);
6330 if( p->db==0 ){
6331 utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
6332 sqlite3_free(zNewFilename);
6333 }else{
6334 p->zFreeOnClose = zNewFilename;
6335 }
6336 }
6337 if( p->db==0 ){
6338 /* As a fall-back open a TEMP database */
6339 p->zDbFilename = 0;
6340 open_db(p, 0);
drh05782482013-10-24 15:20:20 +00006341 }
6342 }else
6343
drhc2ce0be2014-05-29 12:36:14 +00006344 if( c=='o'
6345 && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
6346 ){
6347 const char *zFile = nArg>=2 ? azArg[1] : "stdout";
6348 if( nArg>2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006349 utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
drhc2ce0be2014-05-29 12:36:14 +00006350 rc = 1;
6351 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00006352 }
drhc2ce0be2014-05-29 12:36:14 +00006353 if( n>1 && strncmp(azArg[0], "once", n)==0 ){
6354 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00006355 raw_printf(stderr, "Usage: .once FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00006356 rc = 1;
6357 goto meta_command_exit;
6358 }
6359 p->outCount = 2;
6360 }else{
6361 p->outCount = 0;
6362 }
6363 output_reset(p);
6364 if( zFile[0]=='|' ){
drh8cd5b252015-03-02 22:06:43 +00006365#ifdef SQLITE_OMIT_POPEN
mistachkinaae280e2015-12-31 19:06:24 +00006366 raw_printf(stderr, "Error: pipes are not supported in this OS\n");
drh8cd5b252015-03-02 22:06:43 +00006367 rc = 1;
6368 p->out = stdout;
6369#else
drhc2ce0be2014-05-29 12:36:14 +00006370 p->out = popen(zFile + 1, "w");
drhe1da8fa2012-03-30 00:05:57 +00006371 if( p->out==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006372 utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
drhe1da8fa2012-03-30 00:05:57 +00006373 p->out = stdout;
6374 rc = 1;
6375 }else{
drhc2ce0be2014-05-29 12:36:14 +00006376 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drhe1da8fa2012-03-30 00:05:57 +00006377 }
drh8cd5b252015-03-02 22:06:43 +00006378#endif
drh75897232000-05-29 14:26:00 +00006379 }else{
drhc2ce0be2014-05-29 12:36:14 +00006380 p->out = output_file_open(zFile);
drh75897232000-05-29 14:26:00 +00006381 if( p->out==0 ){
drhc2ce0be2014-05-29 12:36:14 +00006382 if( strcmp(zFile,"off")!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006383 utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
drh42f64e52012-04-04 16:56:23 +00006384 }
drh75897232000-05-29 14:26:00 +00006385 p->out = stdout;
shane9bd1b442009-10-23 01:27:39 +00006386 rc = 1;
persicom7e2dfdd2002-04-18 02:46:52 +00006387 } else {
drhc2ce0be2014-05-29 12:36:14 +00006388 sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
drh75897232000-05-29 14:26:00 +00006389 }
6390 }
6391 }else
6392
drh078b1fd2012-09-21 13:40:02 +00006393 if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
6394 int i;
6395 for(i=1; i<nArg; i++){
mistachkinaae280e2015-12-31 19:06:24 +00006396 if( i>1 ) raw_printf(p->out, " ");
drhe05461c2015-12-30 13:36:57 +00006397 utf8_printf(p->out, "%s", azArg[i]);
drh078b1fd2012-09-21 13:40:02 +00006398 }
mistachkinaae280e2015-12-31 19:06:24 +00006399 raw_printf(p->out, "\n");
drh078b1fd2012-09-21 13:40:02 +00006400 }else
6401
drhc2ce0be2014-05-29 12:36:14 +00006402 if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
persicom7e2dfdd2002-04-18 02:46:52 +00006403 if( nArg >= 2) {
6404 strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
6405 }
6406 if( nArg >= 3) {
6407 strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
6408 }
6409 }else
6410
drhc2ce0be2014-05-29 12:36:14 +00006411 if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
drh47ad6842006-11-08 12:25:42 +00006412 rc = 2;
persicom7e2dfdd2002-04-18 02:46:52 +00006413 }else
6414
drhc2ce0be2014-05-29 12:36:14 +00006415 if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
6416 FILE *alt;
drh4e8142c2016-11-11 14:54:22 +00006417 if( nArg!=2 ){
6418 raw_printf(stderr, "Usage: .read FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00006419 rc = 1;
6420 goto meta_command_exit;
6421 }
drh4e8142c2016-11-11 14:54:22 +00006422 alt = fopen(azArg[1], "rb");
6423 if( alt==0 ){
6424 utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
6425 rc = 1;
drhdaffd0e2001-04-11 14:28:42 +00006426 }else{
drh4e8142c2016-11-11 14:54:22 +00006427 rc = process_input(p, alt);
6428 fclose(alt);
drhdaffd0e2001-04-11 14:28:42 +00006429 }
6430 }else
6431
drhc2ce0be2014-05-29 12:36:14 +00006432 if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
drh9ff849f2009-02-04 20:55:57 +00006433 const char *zSrcFile;
6434 const char *zDb;
6435 sqlite3 *pSrc;
6436 sqlite3_backup *pBackup;
drhdc2c4912009-02-04 22:46:47 +00006437 int nTimeout = 0;
6438
drh9ff849f2009-02-04 20:55:57 +00006439 if( nArg==2 ){
6440 zSrcFile = azArg[1];
6441 zDb = "main";
drhc2ce0be2014-05-29 12:36:14 +00006442 }else if( nArg==3 ){
drh9ff849f2009-02-04 20:55:57 +00006443 zSrcFile = azArg[2];
6444 zDb = azArg[1];
drhc2ce0be2014-05-29 12:36:14 +00006445 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006446 raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
drhc2ce0be2014-05-29 12:36:14 +00006447 rc = 1;
6448 goto meta_command_exit;
drh9ff849f2009-02-04 20:55:57 +00006449 }
6450 rc = sqlite3_open(zSrcFile, &pSrc);
6451 if( rc!=SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00006452 utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
drh9ff849f2009-02-04 20:55:57 +00006453 sqlite3_close(pSrc);
6454 return 1;
6455 }
drh05782482013-10-24 15:20:20 +00006456 open_db(p, 0);
drh9ff849f2009-02-04 20:55:57 +00006457 pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
6458 if( pBackup==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00006459 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
drh9ff849f2009-02-04 20:55:57 +00006460 sqlite3_close(pSrc);
6461 return 1;
6462 }
drhdc2c4912009-02-04 22:46:47 +00006463 while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
6464 || rc==SQLITE_BUSY ){
6465 if( rc==SQLITE_BUSY ){
6466 if( nTimeout++ >= 3 ) break;
6467 sqlite3_sleep(100);
drh9ff849f2009-02-04 20:55:57 +00006468 }
6469 }
6470 sqlite3_backup_finish(pBackup);
6471 if( rc==SQLITE_DONE ){
shane9bd1b442009-10-23 01:27:39 +00006472 rc = 0;
drhdc2c4912009-02-04 22:46:47 +00006473 }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
mistachkinaae280e2015-12-31 19:06:24 +00006474 raw_printf(stderr, "Error: source database is busy\n");
shane9bd1b442009-10-23 01:27:39 +00006475 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00006476 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006477 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
shane9bd1b442009-10-23 01:27:39 +00006478 rc = 1;
drh9ff849f2009-02-04 20:55:57 +00006479 }
6480 sqlite3_close(pSrc);
6481 }else
6482
dan8d1edb92014-11-05 09:07:28 +00006483
6484 if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
6485 if( nArg==2 ){
6486 p->scanstatsOn = booleanValue(azArg[1]);
drh15f23c22014-11-06 12:46:16 +00006487#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
mistachkinaae280e2015-12-31 19:06:24 +00006488 raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
drh15f23c22014-11-06 12:46:16 +00006489#endif
dan8d1edb92014-11-05 09:07:28 +00006490 }else{
mistachkinaae280e2015-12-31 19:06:24 +00006491 raw_printf(stderr, "Usage: .scanstats on|off\n");
dan8d1edb92014-11-05 09:07:28 +00006492 rc = 1;
6493 }
6494 }else
6495
drhc2ce0be2014-05-29 12:36:14 +00006496 if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
drh20c9c3f2017-06-15 12:21:09 +00006497 ShellText sSelect;
drhdcd87a92014-08-18 13:45:42 +00006498 ShellState data;
drh75897232000-05-29 14:26:00 +00006499 char *zErrMsg = 0;
drh20c9c3f2017-06-15 12:21:09 +00006500 const char *zDiv = 0;
6501 int iSchema = 0;
6502
drh05782482013-10-24 15:20:20 +00006503 open_db(p, 0);
drh75897232000-05-29 14:26:00 +00006504 memcpy(&data, p, sizeof(data));
6505 data.showHeader = 0;
drh700c2522016-02-09 18:39:25 +00006506 data.cMode = data.mode = MODE_Semi;
drh20c9c3f2017-06-15 12:21:09 +00006507 initText(&sSelect);
drh4926fec2016-04-13 15:33:42 +00006508 if( nArg>=2 && optionMatch(azArg[1], "indent") ){
6509 data.cMode = data.mode = MODE_Pretty;
6510 nArg--;
6511 if( nArg==2 ) azArg[1] = azArg[2];
6512 }
6513 if( nArg==2 && azArg[1][0]!='-' ){
drhc8d74412004-08-31 23:41:26 +00006514 int i;
drhf0693c82011-10-11 20:41:54 +00006515 for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
drhc8d74412004-08-31 23:41:26 +00006516 if( strcmp(azArg[1],"sqlite_master")==0 ){
drha18c5682000-10-08 22:20:57 +00006517 char *new_argv[2], *new_colv[2];
6518 new_argv[0] = "CREATE TABLE sqlite_master (\n"
6519 " type text,\n"
6520 " name text,\n"
6521 " tbl_name text,\n"
drhadbca9c2001-09-27 15:11:53 +00006522 " rootpage integer,\n"
drha18c5682000-10-08 22:20:57 +00006523 " sql text\n"
6524 ")";
6525 new_argv[1] = 0;
6526 new_colv[0] = "sql";
6527 new_colv[1] = 0;
6528 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00006529 rc = SQLITE_OK;
drhc8d74412004-08-31 23:41:26 +00006530 }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
drhe0bc4042002-06-25 01:09:11 +00006531 char *new_argv[2], *new_colv[2];
6532 new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
6533 " type text,\n"
6534 " name text,\n"
6535 " tbl_name text,\n"
6536 " rootpage integer,\n"
6537 " sql text\n"
6538 ")";
6539 new_argv[1] = 0;
6540 new_colv[0] = "sql";
6541 new_colv[1] = 0;
6542 callback(&data, 1, new_argv, new_colv);
shane9bd1b442009-10-23 01:27:39 +00006543 rc = SQLITE_OK;
drha18c5682000-10-08 22:20:57 +00006544 }else{
drh20c9c3f2017-06-15 12:21:09 +00006545 zDiv = "(";
drha18c5682000-10-08 22:20:57 +00006546 }
drhc2ce0be2014-05-29 12:36:14 +00006547 }else if( nArg==1 ){
drh20c9c3f2017-06-15 12:21:09 +00006548 zDiv = "(";
drhc2ce0be2014-05-29 12:36:14 +00006549 }else{
drh4926fec2016-04-13 15:33:42 +00006550 raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
drhc2ce0be2014-05-29 12:36:14 +00006551 rc = 1;
6552 goto meta_command_exit;
drh75897232000-05-29 14:26:00 +00006553 }
drh20c9c3f2017-06-15 12:21:09 +00006554 if( zDiv ){
6555 sqlite3_stmt *pStmt = 0;
drha7a0bfa2017-07-07 18:06:49 +00006556 rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
6557 -1, &pStmt, 0);
6558 if( rc ){
6559 utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
6560 sqlite3_finalize(pStmt);
6561 rc = 1;
6562 goto meta_command_exit;
6563 }
drh20c9c3f2017-06-15 12:21:09 +00006564 appendText(&sSelect, "SELECT sql FROM", 0);
6565 iSchema = 0;
6566 while( sqlite3_step(pStmt)==SQLITE_ROW ){
6567 const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
6568 char zScNum[30];
6569 sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
6570 appendText(&sSelect, zDiv, 0);
6571 zDiv = " UNION ALL ";
6572 if( strcmp(zDb, "main")!=0 ){
6573 appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
drh90cdec02017-06-15 13:07:56 +00006574 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00006575 appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
6576 appendText(&sSelect, zScNum, 0);
6577 appendText(&sSelect, " AS snum, ", 0);
6578 appendText(&sSelect, zDb, '\'');
6579 appendText(&sSelect, " AS sname FROM ", 0);
drh90cdec02017-06-15 13:07:56 +00006580 appendText(&sSelect, zDb, '"');
drh20c9c3f2017-06-15 12:21:09 +00006581 appendText(&sSelect, ".sqlite_master", 0);
6582 }else{
6583 appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
6584 appendText(&sSelect, zScNum, 0);
6585 appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
6586 }
6587 }
6588 sqlite3_finalize(pStmt);
6589 appendText(&sSelect, ") WHERE ", 0);
6590 if( nArg>1 ){
6591 char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
6592 if( strchr(azArg[1], '.') ){
6593 appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
6594 }else{
6595 appendText(&sSelect, "lower(tbl_name)", 0);
6596 }
6597 appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
6598 appendText(&sSelect, zQarg, 0);
6599 appendText(&sSelect, " AND ", 0);
6600 sqlite3_free(zQarg);
6601 }
6602 appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
6603 " ORDER BY snum, rowid", 0);
6604 rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
6605 freeText(&sSelect);
6606 }
drh75897232000-05-29 14:26:00 +00006607 if( zErrMsg ){
mistachkinaae280e2015-12-31 19:06:24 +00006608 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drh3f4fedb2004-05-31 19:34:33 +00006609 sqlite3_free(zErrMsg);
shane9bd1b442009-10-23 01:27:39 +00006610 rc = 1;
6611 }else if( rc != SQLITE_OK ){
mistachkinaae280e2015-12-31 19:06:24 +00006612 raw_printf(stderr,"Error: querying schema information\n");
shane9bd1b442009-10-23 01:27:39 +00006613 rc = 1;
6614 }else{
6615 rc = 0;
drh75897232000-05-29 14:26:00 +00006616 }
6617 }else
6618
drhabd4c722014-09-20 18:18:33 +00006619#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
6620 if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
drh2b44fd92017-02-17 01:43:51 +00006621 sqlite3SelectTrace = (int)integerValue(azArg[1]);
drhabd4c722014-09-20 18:18:33 +00006622 }else
6623#endif
6624
drhe6229612014-08-18 15:08:26 +00006625#if defined(SQLITE_ENABLE_SESSION)
6626 if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
6627 OpenSession *pSession = &p->aSession[0];
6628 char **azCmd = &azArg[1];
6629 int iSes = 0;
6630 int nCmd = nArg - 1;
6631 int i;
6632 if( nArg<=1 ) goto session_syntax_error;
drh3a67b042014-08-18 17:56:31 +00006633 open_db(p, 0);
drhe6229612014-08-18 15:08:26 +00006634 if( nArg>=3 ){
6635 for(iSes=0; iSes<p->nSession; iSes++){
6636 if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
6637 }
6638 if( iSes<p->nSession ){
6639 pSession = &p->aSession[iSes];
6640 azCmd++;
6641 nCmd--;
6642 }else{
6643 pSession = &p->aSession[0];
6644 iSes = 0;
6645 }
6646 }
6647
drh3a67b042014-08-18 17:56:31 +00006648 /* .session attach TABLE
6649 ** Invoke the sqlite3session_attach() interface to attach a particular
6650 ** table so that it is never filtered.
6651 */
6652 if( strcmp(azCmd[0],"attach")==0 ){
6653 if( nCmd!=2 ) goto session_syntax_error;
6654 if( pSession->p==0 ){
6655 session_not_open:
mistachkin899c5c92016-04-03 20:50:02 +00006656 raw_printf(stderr, "ERROR: No sessions are open\n");
drh3a67b042014-08-18 17:56:31 +00006657 }else{
6658 rc = sqlite3session_attach(pSession->p, azCmd[1]);
6659 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00006660 raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
drh3a67b042014-08-18 17:56:31 +00006661 rc = 0;
6662 }
6663 }
6664 }else
6665
6666 /* .session changeset FILE
6667 ** .session patchset FILE
6668 ** Write a changeset or patchset into a file. The file is overwritten.
6669 */
6670 if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
6671 FILE *out = 0;
6672 if( nCmd!=2 ) goto session_syntax_error;
6673 if( pSession->p==0 ) goto session_not_open;
6674 out = fopen(azCmd[1], "wb");
6675 if( out==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006676 utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
drh3a67b042014-08-18 17:56:31 +00006677 }else{
6678 int szChng;
6679 void *pChng;
6680 if( azCmd[0][0]=='c' ){
drh2967e0c2014-08-19 00:26:17 +00006681 rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
drh3a67b042014-08-18 17:56:31 +00006682 }else{
drh2967e0c2014-08-19 00:26:17 +00006683 rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
6684 }
6685 if( rc ){
6686 printf("Error: error code %d\n", rc);
6687 rc = 0;
drh3a67b042014-08-18 17:56:31 +00006688 }
mistachkin1fe36bb2016-04-04 02:16:44 +00006689 if( pChng
drh3a67b042014-08-18 17:56:31 +00006690 && fwrite(pChng, szChng, 1, out)!=1 ){
mistachkin899c5c92016-04-03 20:50:02 +00006691 raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
drh3a67b042014-08-18 17:56:31 +00006692 szChng);
6693 }
6694 sqlite3_free(pChng);
6695 fclose(out);
6696 }
6697 }else
6698
drhe6229612014-08-18 15:08:26 +00006699 /* .session close
6700 ** Close the identified session
6701 */
6702 if( strcmp(azCmd[0], "close")==0 ){
drh03168ca2014-08-18 20:01:31 +00006703 if( nCmd!=1 ) goto session_syntax_error;
drhe6229612014-08-18 15:08:26 +00006704 if( p->nSession ){
6705 session_close(pSession);
6706 p->aSession[iSes] = p->aSession[--p->nSession];
6707 }
6708 }else
6709
drh03168ca2014-08-18 20:01:31 +00006710 /* .session enable ?BOOLEAN?
6711 ** Query or set the enable flag
6712 */
6713 if( strcmp(azCmd[0], "enable")==0 ){
6714 int ii;
6715 if( nCmd>2 ) goto session_syntax_error;
6716 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6717 if( p->nSession ){
6718 ii = sqlite3session_enable(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00006719 utf8_printf(p->out, "session %s enable flag = %d\n",
6720 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006721 }
6722 }else
6723
6724 /* .session filter GLOB ....
6725 ** Set a list of GLOB patterns of table names to be excluded.
6726 */
6727 if( strcmp(azCmd[0], "filter")==0 ){
6728 int ii, nByte;
6729 if( nCmd<2 ) goto session_syntax_error;
6730 if( p->nSession ){
6731 for(ii=0; ii<pSession->nFilter; ii++){
6732 sqlite3_free(pSession->azFilter[ii]);
6733 }
6734 sqlite3_free(pSession->azFilter);
6735 nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
6736 pSession->azFilter = sqlite3_malloc( nByte );
6737 if( pSession->azFilter==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006738 raw_printf(stderr, "Error: out or memory\n");
drh03168ca2014-08-18 20:01:31 +00006739 exit(1);
6740 }
6741 for(ii=1; ii<nCmd; ii++){
mistachkin1fe36bb2016-04-04 02:16:44 +00006742 pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
drh03168ca2014-08-18 20:01:31 +00006743 }
6744 pSession->nFilter = ii-1;
6745 }
6746 }else
6747
6748 /* .session indirect ?BOOLEAN?
6749 ** Query or set the indirect flag
6750 */
6751 if( strcmp(azCmd[0], "indirect")==0 ){
6752 int ii;
6753 if( nCmd>2 ) goto session_syntax_error;
6754 ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
6755 if( p->nSession ){
6756 ii = sqlite3session_indirect(pSession->p, ii);
mistachkin899c5c92016-04-03 20:50:02 +00006757 utf8_printf(p->out, "session %s indirect flag = %d\n",
6758 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006759 }
6760 }else
6761
6762 /* .session isempty
6763 ** Determine if the session is empty
6764 */
6765 if( strcmp(azCmd[0], "isempty")==0 ){
6766 int ii;
6767 if( nCmd!=1 ) goto session_syntax_error;
6768 if( p->nSession ){
6769 ii = sqlite3session_isempty(pSession->p);
mistachkin899c5c92016-04-03 20:50:02 +00006770 utf8_printf(p->out, "session %s isempty flag = %d\n",
6771 pSession->zName, ii);
drh03168ca2014-08-18 20:01:31 +00006772 }
6773 }else
6774
drhe6229612014-08-18 15:08:26 +00006775 /* .session list
6776 ** List all currently open sessions
6777 */
6778 if( strcmp(azCmd[0],"list")==0 ){
6779 for(i=0; i<p->nSession; i++){
mistachkin899c5c92016-04-03 20:50:02 +00006780 utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
drhe6229612014-08-18 15:08:26 +00006781 }
6782 }else
6783
6784 /* .session open DB NAME
6785 ** Open a new session called NAME on the attached database DB.
6786 ** DB is normally "main".
6787 */
6788 if( strcmp(azCmd[0],"open")==0 ){
6789 char *zName;
6790 if( nCmd!=3 ) goto session_syntax_error;
6791 zName = azCmd[2];
6792 if( zName[0]==0 ) goto session_syntax_error;
6793 for(i=0; i<p->nSession; i++){
6794 if( strcmp(p->aSession[i].zName,zName)==0 ){
mistachkin899c5c92016-04-03 20:50:02 +00006795 utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
drhe6229612014-08-18 15:08:26 +00006796 goto meta_command_exit;
6797 }
6798 }
6799 if( p->nSession>=ArraySize(p->aSession) ){
mistachkin899c5c92016-04-03 20:50:02 +00006800 raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
drhe6229612014-08-18 15:08:26 +00006801 goto meta_command_exit;
6802 }
6803 pSession = &p->aSession[p->nSession];
6804 rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
6805 if( rc ){
mistachkin899c5c92016-04-03 20:50:02 +00006806 raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
drh3a67b042014-08-18 17:56:31 +00006807 rc = 0;
drhe6229612014-08-18 15:08:26 +00006808 goto meta_command_exit;
6809 }
drh03168ca2014-08-18 20:01:31 +00006810 pSession->nFilter = 0;
6811 sqlite3session_table_filter(pSession->p, session_filter, pSession);
drhe6229612014-08-18 15:08:26 +00006812 p->nSession++;
6813 pSession->zName = sqlite3_mprintf("%s", zName);
6814 }else
6815 /* If no command name matches, show a syntax error */
6816 session_syntax_error:
6817 session_help(p);
6818 }else
6819#endif
6820
drh340f5822013-06-27 13:01:21 +00006821#ifdef SQLITE_DEBUG
drh348d19c2013-06-03 12:47:43 +00006822 /* Undocumented commands for internal testing. Subject to change
6823 ** without notice. */
6824 if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
6825 if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
6826 int i, v;
6827 for(i=1; i<nArg; i++){
6828 v = booleanValue(azArg[i]);
drhe05461c2015-12-30 13:36:57 +00006829 utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
drh348d19c2013-06-03 12:47:43 +00006830 }
6831 }
6832 if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
6833 int i; sqlite3_int64 v;
6834 for(i=1; i<nArg; i++){
drh340f5822013-06-27 13:01:21 +00006835 char zBuf[200];
drh348d19c2013-06-03 12:47:43 +00006836 v = integerValue(azArg[i]);
drhc2ce0be2014-05-29 12:36:14 +00006837 sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
drhe05461c2015-12-30 13:36:57 +00006838 utf8_printf(p->out, "%s", zBuf);
drh348d19c2013-06-03 12:47:43 +00006839 }
6840 }
6841 }else
drh340f5822013-06-27 13:01:21 +00006842#endif
drh348d19c2013-06-03 12:47:43 +00006843
drhfb546af2017-03-09 22:00:33 +00006844 if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
6845 int bIsInit = 0; /* True to initialize the SELFTEST table */
6846 int bVerbose = 0; /* Verbose output */
6847 int bSelftestExists; /* True if SELFTEST already exists */
drhc5d353f2017-06-09 02:27:49 +00006848 int i, k; /* Loop counters */
drhfb546af2017-03-09 22:00:33 +00006849 int nTest = 0; /* Number of tests runs */
6850 int nErr = 0; /* Number of errors seen */
6851 ShellText str; /* Answer for a query */
drhc5d353f2017-06-09 02:27:49 +00006852 sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
drhfb546af2017-03-09 22:00:33 +00006853
6854 open_db(p,0);
6855 for(i=1; i<nArg; i++){
6856 const char *z = azArg[i];
6857 if( z[0]=='-' && z[1]=='-' ) z++;
6858 if( strcmp(z,"-init")==0 ){
6859 bIsInit = 1;
6860 }else
6861 if( strcmp(z,"-v")==0 ){
6862 bVerbose++;
6863 }else
6864 {
6865 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
6866 azArg[i], azArg[0]);
6867 raw_printf(stderr, "Should be one of: --init -v\n");
6868 rc = 1;
6869 goto meta_command_exit;
6870 }
6871 }
6872 if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
6873 != SQLITE_OK ){
6874 bSelftestExists = 0;
6875 }else{
6876 bSelftestExists = 1;
6877 }
6878 if( bIsInit ){
drhfb546af2017-03-09 22:00:33 +00006879 createSelftestTable(p);
6880 bSelftestExists = 1;
6881 }
drhc5d353f2017-06-09 02:27:49 +00006882 initText(&str);
6883 appendText(&str, "x", 0);
6884 for(k=bSelftestExists; k>=0; k--){
6885 if( k==1 ){
6886 rc = sqlite3_prepare_v2(p->db,
6887 "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
6888 -1, &pStmt, 0);
6889 }else{
6890 rc = sqlite3_prepare_v2(p->db,
6891 "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
6892 " (1,'run','PRAGMA integrity_check','ok')",
6893 -1, &pStmt, 0);
6894 }
drhfb546af2017-03-09 22:00:33 +00006895 if( rc ){
6896 raw_printf(stderr, "Error querying the selftest table\n");
6897 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006898 sqlite3_finalize(pStmt);
drhfb546af2017-03-09 22:00:33 +00006899 goto meta_command_exit;
drhfb546af2017-03-09 22:00:33 +00006900 }
drhc5d353f2017-06-09 02:27:49 +00006901 for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
6902 int tno = sqlite3_column_int(pStmt, 0);
6903 const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
6904 const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
6905 const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
mistachkine16a3502017-05-29 03:48:13 +00006906
drhc5d353f2017-06-09 02:27:49 +00006907 k = 0;
6908 if( bVerbose>0 ){
6909 char *zQuote = sqlite3_mprintf("%q", zSql);
6910 printf("%d: %s %s\n", tno, zOp, zSql);
6911 sqlite3_free(zQuote);
drhfb546af2017-03-09 22:00:33 +00006912 }
drhc5d353f2017-06-09 02:27:49 +00006913 if( strcmp(zOp,"memo")==0 ){
6914 utf8_printf(p->out, "%s\n", zSql);
6915 }else
6916 if( strcmp(zOp,"run")==0 ){
6917 char *zErrMsg = 0;
6918 str.n = 0;
6919 str.z[0] = 0;
6920 rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
6921 nTest++;
6922 if( bVerbose ){
6923 utf8_printf(p->out, "Result: %s\n", str.z);
6924 }
6925 if( rc || zErrMsg ){
6926 nErr++;
6927 rc = 1;
6928 utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
6929 sqlite3_free(zErrMsg);
6930 }else if( strcmp(zAns,str.z)!=0 ){
6931 nErr++;
6932 rc = 1;
6933 utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
6934 utf8_printf(p->out, "%d: Got: [%s]\n", tno, str.z);
6935 }
6936 }else
6937 {
6938 utf8_printf(stderr,
6939 "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
drhfb546af2017-03-09 22:00:33 +00006940 rc = 1;
drhc5d353f2017-06-09 02:27:49 +00006941 break;
drhfb546af2017-03-09 22:00:33 +00006942 }
drhc5d353f2017-06-09 02:27:49 +00006943 } /* End loop over rows of content from SELFTEST */
6944 sqlite3_finalize(pStmt);
6945 } /* End loop over k */
drhfb546af2017-03-09 22:00:33 +00006946 freeText(&str);
drhfb546af2017-03-09 22:00:33 +00006947 utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
6948 }else
6949
drhc2ce0be2014-05-29 12:36:14 +00006950 if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
drh6976c212014-07-24 12:09:47 +00006951 if( nArg<2 || nArg>3 ){
mistachkinaae280e2015-12-31 19:06:24 +00006952 raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
drhc2ce0be2014-05-29 12:36:14 +00006953 rc = 1;
6954 }
drh6976c212014-07-24 12:09:47 +00006955 if( nArg>=2 ){
mistachkin636bf9f2014-07-19 20:15:16 +00006956 sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
mistachkin22c96382014-07-24 22:51:18 +00006957 "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
drh6976c212014-07-24 12:09:47 +00006958 }
6959 if( nArg>=3 ){
mistachkine0d68852014-12-11 03:12:33 +00006960 sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
6961 "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
drh6976c212014-07-24 12:09:47 +00006962 }
drh75897232000-05-29 14:26:00 +00006963 }else
6964
drh1554bc82017-03-08 16:10:34 +00006965 if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
6966 const char *zLike = 0; /* Which table to checksum. 0 means everything */
6967 int i; /* Loop counter */
6968 int bSchema = 0; /* Also hash the schema */
drh3ee83ef2017-03-08 17:56:54 +00006969 int bSeparate = 0; /* Hash each table separately */
drh1554bc82017-03-08 16:10:34 +00006970 int iSize = 224; /* Hash algorithm to use */
6971 int bDebug = 0; /* Only show the query that would have run */
6972 sqlite3_stmt *pStmt; /* For querying tables names */
6973 char *zSql; /* SQL to be run */
drh3ee83ef2017-03-08 17:56:54 +00006974 char *zSep; /* Separator */
6975 ShellText sSql; /* Complete SQL for the query to run the hash */
drh1554bc82017-03-08 16:10:34 +00006976 ShellText sQuery; /* Set of queries used to read all content */
drhf80d4ff2017-03-08 18:06:20 +00006977 open_db(p, 0);
drh1554bc82017-03-08 16:10:34 +00006978 for(i=1; i<nArg; i++){
6979 const char *z = azArg[i];
6980 if( z[0]=='-' ){
6981 z++;
6982 if( z[0]=='-' ) z++;
6983 if( strcmp(z,"schema")==0 ){
6984 bSchema = 1;
6985 }else
mistachkine16a3502017-05-29 03:48:13 +00006986 if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
6987 || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
drh1554bc82017-03-08 16:10:34 +00006988 ){
6989 iSize = atoi(&z[5]);
6990 }else
6991 if( strcmp(z,"debug")==0 ){
6992 bDebug = 1;
6993 }else
6994 {
6995 utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
drh3ee83ef2017-03-08 17:56:54 +00006996 azArg[i], azArg[0]);
drh1554bc82017-03-08 16:10:34 +00006997 raw_printf(stderr, "Should be one of: --schema"
6998 " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
6999 rc = 1;
7000 goto meta_command_exit;
7001 }
7002 }else if( zLike ){
7003 raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
7004 rc = 1;
7005 goto meta_command_exit;
7006 }else{
7007 zLike = z;
drh3ee83ef2017-03-08 17:56:54 +00007008 bSeparate = 1;
7009 if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
drh1554bc82017-03-08 16:10:34 +00007010 }
7011 }
7012 if( bSchema ){
7013 zSql = "SELECT lower(name) FROM sqlite_master"
7014 " WHERE type='table' AND coalesce(rootpage,0)>1"
7015 " UNION ALL SELECT 'sqlite_master'"
7016 " ORDER BY 1 collate nocase";
7017 }else{
7018 zSql = "SELECT lower(name) FROM sqlite_master"
7019 " WHERE type='table' AND coalesce(rootpage,0)>1"
7020 " AND name NOT LIKE 'sqlite_%'"
7021 " ORDER BY 1 collate nocase";
7022 }
7023 sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
7024 initText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00007025 initText(&sSql);
7026 appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
7027 zSep = "VALUES(";
drh1554bc82017-03-08 16:10:34 +00007028 while( SQLITE_ROW==sqlite3_step(pStmt) ){
7029 const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
7030 if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
7031 if( strncmp(zTab, "sqlite_",7)!=0 ){
7032 appendText(&sQuery,"SELECT * FROM ", 0);
7033 appendText(&sQuery,zTab,'"');
7034 appendText(&sQuery," NOT INDEXED;", 0);
7035 }else if( strcmp(zTab, "sqlite_master")==0 ){
7036 appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
7037 " ORDER BY name;", 0);
7038 }else if( strcmp(zTab, "sqlite_sequence")==0 ){
7039 appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
7040 " ORDER BY name;", 0);
7041 }else if( strcmp(zTab, "sqlite_stat1")==0 ){
7042 appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
7043 " ORDER BY tbl,idx;", 0);
7044 }else if( strcmp(zTab, "sqlite_stat3")==0
7045 || strcmp(zTab, "sqlite_stat4")==0 ){
7046 appendText(&sQuery, "SELECT * FROM ", 0);
7047 appendText(&sQuery, zTab, 0);
7048 appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
7049 }
drh3ee83ef2017-03-08 17:56:54 +00007050 appendText(&sSql, zSep, 0);
7051 appendText(&sSql, sQuery.z, '\'');
7052 sQuery.n = 0;
7053 appendText(&sSql, ",", 0);
7054 appendText(&sSql, zTab, '\'');
7055 zSep = "),(";
drh1554bc82017-03-08 16:10:34 +00007056 }
7057 sqlite3_finalize(pStmt);
drh3ee83ef2017-03-08 17:56:54 +00007058 if( bSeparate ){
7059 zSql = sqlite3_mprintf(
7060 "%s))"
7061 " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
7062 " FROM [sha3sum$query]",
7063 sSql.z, iSize);
7064 }else{
7065 zSql = sqlite3_mprintf(
7066 "%s))"
7067 " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
7068 " FROM [sha3sum$query]",
7069 sSql.z, iSize);
7070 }
drh1554bc82017-03-08 16:10:34 +00007071 freeText(&sQuery);
drh3ee83ef2017-03-08 17:56:54 +00007072 freeText(&sSql);
drh1554bc82017-03-08 16:10:34 +00007073 if( bDebug ){
7074 utf8_printf(p->out, "%s\n", zSql);
7075 }else{
7076 shell_exec(p->db, zSql, shell_callback, p, 0);
7077 }
7078 sqlite3_free(zSql);
7079 }else
7080
drh62cdde52014-05-28 20:22:28 +00007081 if( c=='s'
7082 && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
drh62cdde52014-05-28 20:22:28 +00007083 ){
7084 char *zCmd;
drh54027102014-08-06 14:36:53 +00007085 int i, x;
drhc2ce0be2014-05-29 12:36:14 +00007086 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00007087 raw_printf(stderr, "Usage: .system COMMAND\n");
drhc2ce0be2014-05-29 12:36:14 +00007088 rc = 1;
7089 goto meta_command_exit;
7090 }
drhdcb3e3d2014-05-29 03:17:29 +00007091 zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
drh62cdde52014-05-28 20:22:28 +00007092 for(i=2; i<nArg; i++){
drhdcb3e3d2014-05-29 03:17:29 +00007093 zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
7094 zCmd, azArg[i]);
drh62cdde52014-05-28 20:22:28 +00007095 }
drh54027102014-08-06 14:36:53 +00007096 x = system(zCmd);
drh62cdde52014-05-28 20:22:28 +00007097 sqlite3_free(zCmd);
mistachkinaae280e2015-12-31 19:06:24 +00007098 if( x ) raw_printf(stderr, "System command returns %d\n", x);
drh62cdde52014-05-28 20:22:28 +00007099 }else
7100
drhc2ce0be2014-05-29 12:36:14 +00007101 if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
drheacd29d2016-04-15 15:03:27 +00007102 static const char *azBool[] = { "off", "on", "full", "unk" };
persicom7e2dfdd2002-04-18 02:46:52 +00007103 int i;
drhc2ce0be2014-05-29 12:36:14 +00007104 if( nArg!=1 ){
mistachkinaae280e2015-12-31 19:06:24 +00007105 raw_printf(stderr, "Usage: .show\n");
drhc2ce0be2014-05-29 12:36:14 +00007106 rc = 1;
7107 goto meta_command_exit;
7108 }
drhe6e1d122017-03-09 13:50:49 +00007109 utf8_printf(p->out, "%12.12s: %s\n","echo",
7110 azBool[ShellHasFlag(p, SHFLG_Echo)]);
drheacd29d2016-04-15 15:03:27 +00007111 utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
drh700c2522016-02-09 18:39:25 +00007112 utf8_printf(p->out, "%12.12s: %s\n","explain",
7113 p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
drheacd29d2016-04-15 15:03:27 +00007114 utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00007115 utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
7116 utf8_printf(p->out, "%12.12s: ", "nullvalue");
mistachkin44b99f72014-12-11 03:29:14 +00007117 output_c_string(p->out, p->nullValue);
mistachkinaae280e2015-12-31 19:06:24 +00007118 raw_printf(p->out, "\n");
7119 utf8_printf(p->out,"%12.12s: %s\n","output",
drh4f21c4a2008-12-10 22:15:00 +00007120 strlen30(p->outfile) ? p->outfile : "stdout");
mistachkinaae280e2015-12-31 19:06:24 +00007121 utf8_printf(p->out,"%12.12s: ", "colseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00007122 output_c_string(p->out, p->colSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00007123 raw_printf(p->out, "\n");
7124 utf8_printf(p->out,"%12.12s: ", "rowseparator");
mistachkin636bf9f2014-07-19 20:15:16 +00007125 output_c_string(p->out, p->rowSeparator);
mistachkinaae280e2015-12-31 19:06:24 +00007126 raw_printf(p->out, "\n");
drheacd29d2016-04-15 15:03:27 +00007127 utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
mistachkinaae280e2015-12-31 19:06:24 +00007128 utf8_printf(p->out, "%12.12s: ", "width");
persicom7e2dfdd2002-04-18 02:46:52 +00007129 for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
mistachkinaae280e2015-12-31 19:06:24 +00007130 raw_printf(p->out, "%d ", p->colWidth[i]);
persicom7e2dfdd2002-04-18 02:46:52 +00007131 }
mistachkinaae280e2015-12-31 19:06:24 +00007132 raw_printf(p->out, "\n");
drhcd0509e2016-09-16 00:26:08 +00007133 utf8_printf(p->out, "%12.12s: %s\n", "filename",
7134 p->zDbFilename ? p->zDbFilename : "");
persicom7e2dfdd2002-04-18 02:46:52 +00007135 }else
7136
drhc2ce0be2014-05-29 12:36:14 +00007137 if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
7138 if( nArg==2 ){
7139 p->statsOn = booleanValue(azArg[1]);
drh34784902016-02-27 17:12:36 +00007140 }else if( nArg==1 ){
7141 display_stats(p->db, p, 0);
drhc2ce0be2014-05-29 12:36:14 +00007142 }else{
drh34784902016-02-27 17:12:36 +00007143 raw_printf(stderr, "Usage: .stats ?on|off?\n");
drhc2ce0be2014-05-29 12:36:14 +00007144 rc = 1;
7145 }
shaneh642d8b82010-07-28 16:05:34 +00007146 }else
7147
drh6a5a4202016-12-24 21:32:40 +00007148 if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
7149 || (c=='i' && (strncmp(azArg[0], "indices", n)==0
7150 || strncmp(azArg[0], "indexes", n)==0) )
7151 ){
drh98781232012-04-23 12:38:05 +00007152 sqlite3_stmt *pStmt;
drhe3710332000-09-29 13:30:53 +00007153 char **azResult;
drh98781232012-04-23 12:38:05 +00007154 int nRow, nAlloc;
drh98781232012-04-23 12:38:05 +00007155 int ii;
drh594ccd02017-06-15 12:50:47 +00007156 ShellText s;
7157 initText(&s);
drh05782482013-10-24 15:20:20 +00007158 open_db(p, 0);
drh98781232012-04-23 12:38:05 +00007159 rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
dand95bb392015-09-30 11:19:05 +00007160 if( rc ) return shellDatabaseError(p->db);
7161
drh594ccd02017-06-15 12:50:47 +00007162 if( nArg>2 && c=='i' ){
drh6a5a4202016-12-24 21:32:40 +00007163 /* It is an historical accident that the .indexes command shows an error
7164 ** when called with the wrong number of arguments whereas the .tables
7165 ** command does not. */
7166 raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
7167 rc = 1;
7168 goto meta_command_exit;
drh6a5a4202016-12-24 21:32:40 +00007169 }
drh594ccd02017-06-15 12:50:47 +00007170 for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
drh98781232012-04-23 12:38:05 +00007171 const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
drh594ccd02017-06-15 12:50:47 +00007172 if( zDbName==0 ) continue;
7173 if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
7174 if( sqlite3_stricmp(zDbName, "main")==0 ){
7175 appendText(&s, "SELECT name FROM ", 0);
drh6a5a4202016-12-24 21:32:40 +00007176 }else{
drh594ccd02017-06-15 12:50:47 +00007177 appendText(&s, "SELECT ", 0);
7178 appendText(&s, zDbName, '\'');
7179 appendText(&s, "||'.'||name FROM ", 0);
7180 }
7181 appendText(&s, zDbName, '"');
7182 appendText(&s, ".sqlite_master ", 0);
7183 if( c=='t' ){
7184 appendText(&s," WHERE type IN ('table','view')"
7185 " AND name NOT LIKE 'sqlite_%'"
7186 " AND name LIKE ?1", 0);
7187 }else{
7188 appendText(&s," WHERE type='index'"
7189 " AND tbl_name LIKE ?1", 0);
drh98781232012-04-23 12:38:05 +00007190 }
drha50da102000-08-08 20:19:09 +00007191 }
dand95bb392015-09-30 11:19:05 +00007192 rc = sqlite3_finalize(pStmt);
drh594ccd02017-06-15 12:50:47 +00007193 appendText(&s, " ORDER BY 1", 0);
7194 rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
7195 freeText(&s);
dand95bb392015-09-30 11:19:05 +00007196 if( rc ) return shellDatabaseError(p->db);
7197
7198 /* Run the SQL statement prepared by the above block. Store the results
7199 ** as an array of nul-terminated strings in azResult[]. */
drh98781232012-04-23 12:38:05 +00007200 nRow = nAlloc = 0;
7201 azResult = 0;
7202 if( nArg>1 ){
7203 sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
shane9bd1b442009-10-23 01:27:39 +00007204 }else{
drh98781232012-04-23 12:38:05 +00007205 sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
7206 }
7207 while( sqlite3_step(pStmt)==SQLITE_ROW ){
7208 if( nRow>=nAlloc ){
7209 char **azNew;
mistachkin8e189222015-04-19 21:43:16 +00007210 int n2 = nAlloc*2 + 10;
drhf3cdcdc2015-04-29 16:50:28 +00007211 azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
drh98781232012-04-23 12:38:05 +00007212 if( azNew==0 ){
dand95bb392015-09-30 11:19:05 +00007213 rc = shellNomemError();
drh98781232012-04-23 12:38:05 +00007214 break;
7215 }
mistachkin8e189222015-04-19 21:43:16 +00007216 nAlloc = n2;
drh98781232012-04-23 12:38:05 +00007217 azResult = azNew;
7218 }
7219 azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
dand95bb392015-09-30 11:19:05 +00007220 if( 0==azResult[nRow] ){
7221 rc = shellNomemError();
7222 break;
7223 }
7224 nRow++;
drh98781232012-04-23 12:38:05 +00007225 }
dand95bb392015-09-30 11:19:05 +00007226 if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
7227 rc = shellDatabaseError(p->db);
7228 }
7229
7230 /* Pretty-print the contents of array azResult[] to the output */
7231 if( rc==0 && nRow>0 ){
drhe3710332000-09-29 13:30:53 +00007232 int len, maxlen = 0;
7233 int i, j;
7234 int nPrintCol, nPrintRow;
drh98781232012-04-23 12:38:05 +00007235 for(i=0; i<nRow; i++){
drh4f21c4a2008-12-10 22:15:00 +00007236 len = strlen30(azResult[i]);
drhe3710332000-09-29 13:30:53 +00007237 if( len>maxlen ) maxlen = len;
7238 }
7239 nPrintCol = 80/(maxlen+2);
7240 if( nPrintCol<1 ) nPrintCol = 1;
7241 nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
7242 for(i=0; i<nPrintRow; i++){
drh98781232012-04-23 12:38:05 +00007243 for(j=i; j<nRow; j+=nPrintRow){
7244 char *zSp = j<nPrintRow ? "" : " ";
drhe05461c2015-12-30 13:36:57 +00007245 utf8_printf(p->out, "%s%-*s", zSp, maxlen,
7246 azResult[j] ? azResult[j]:"");
drhe3710332000-09-29 13:30:53 +00007247 }
mistachkinaae280e2015-12-31 19:06:24 +00007248 raw_printf(p->out, "\n");
drhe3710332000-09-29 13:30:53 +00007249 }
7250 }
dand95bb392015-09-30 11:19:05 +00007251
drh98781232012-04-23 12:38:05 +00007252 for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
7253 sqlite3_free(azResult);
drh75897232000-05-29 14:26:00 +00007254 }else
7255
drh2db82112016-09-15 21:35:24 +00007256 /* Begin redirecting output to the file "testcase-out.txt" */
7257 if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
7258 output_reset(p);
7259 p->out = output_file_open("testcase-out.txt");
7260 if( p->out==0 ){
mistachkin2f9a6132016-11-11 05:19:45 +00007261 raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
drh2db82112016-09-15 21:35:24 +00007262 }
drh760c8162016-09-16 02:52:22 +00007263 if( nArg>=2 ){
7264 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
7265 }else{
7266 sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
7267 }
drh2db82112016-09-15 21:35:24 +00007268 }else
drh2db82112016-09-15 21:35:24 +00007269
drhd12602a2016-12-07 15:49:02 +00007270#ifndef SQLITE_UNTESTABLE
shaneh96887e12011-02-10 21:08:58 +00007271 if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
drhd416fe72011-03-17 16:45:50 +00007272 static const struct {
7273 const char *zCtrlName; /* Name of a test-control option */
7274 int ctrlCode; /* Integer code for that option */
7275 } aCtrl[] = {
7276 { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE },
7277 { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE },
7278 { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET },
7279 { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST },
7280 { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL },
7281 { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS },
7282 { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE },
7283 { "assert", SQLITE_TESTCTRL_ASSERT },
7284 { "always", SQLITE_TESTCTRL_ALWAYS },
7285 { "reserve", SQLITE_TESTCTRL_RESERVE },
7286 { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS },
7287 { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD },
drh2cf4acb2014-04-18 00:06:02 +00007288 { "byteorder", SQLITE_TESTCTRL_BYTEORDER },
drhe4bb23a2015-01-19 15:05:54 +00007289 { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT },
drh1ffede82015-01-30 20:59:27 +00007290 { "imposter", SQLITE_TESTCTRL_IMPOSTER },
drhd416fe72011-03-17 16:45:50 +00007291 };
shaneh96887e12011-02-10 21:08:58 +00007292 int testctrl = -1;
mistachkin8e189222015-04-19 21:43:16 +00007293 int rc2 = 0;
7294 int i, n2;
drh05782482013-10-24 15:20:20 +00007295 open_db(p, 0);
shaneh96887e12011-02-10 21:08:58 +00007296
drhd416fe72011-03-17 16:45:50 +00007297 /* convert testctrl text option to value. allow any unique prefix
7298 ** of the option name, or a numerical value. */
mistachkin8e189222015-04-19 21:43:16 +00007299 n2 = strlen30(azArg[1]);
drhf5ed7ad2015-06-15 14:43:25 +00007300 for(i=0; i<ArraySize(aCtrl); i++){
mistachkin8e189222015-04-19 21:43:16 +00007301 if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
drhd416fe72011-03-17 16:45:50 +00007302 if( testctrl<0 ){
7303 testctrl = aCtrl[i].ctrlCode;
7304 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007305 utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
drhd416fe72011-03-17 16:45:50 +00007306 testctrl = -1;
7307 break;
7308 }
7309 }
7310 }
drh348d19c2013-06-03 12:47:43 +00007311 if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007312 if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
mistachkinaae280e2015-12-31 19:06:24 +00007313 utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007314 }else{
7315 switch(testctrl){
7316
7317 /* sqlite3_test_control(int, db, int) */
7318 case SQLITE_TESTCTRL_OPTIMIZATIONS:
mistachkin1fe36bb2016-04-04 02:16:44 +00007319 case SQLITE_TESTCTRL_RESERVE:
shaneh96887e12011-02-10 21:08:58 +00007320 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00007321 int opt = (int)strtol(azArg[2], 0, 0);
mistachkin8e189222015-04-19 21:43:16 +00007322 rc2 = sqlite3_test_control(testctrl, p->db, opt);
mistachkinaae280e2015-12-31 19:06:24 +00007323 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00007324 } else {
mistachkinaae280e2015-12-31 19:06:24 +00007325 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00007326 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007327 }
7328 break;
7329
7330 /* sqlite3_test_control(int) */
drh2cf4acb2014-04-18 00:06:02 +00007331 case SQLITE_TESTCTRL_PRNG_SAVE:
7332 case SQLITE_TESTCTRL_PRNG_RESTORE:
shaneh96887e12011-02-10 21:08:58 +00007333 case SQLITE_TESTCTRL_PRNG_RESET:
drh2cf4acb2014-04-18 00:06:02 +00007334 case SQLITE_TESTCTRL_BYTEORDER:
shaneh96887e12011-02-10 21:08:58 +00007335 if( nArg==2 ){
mistachkin8e189222015-04-19 21:43:16 +00007336 rc2 = sqlite3_test_control(testctrl);
mistachkinaae280e2015-12-31 19:06:24 +00007337 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00007338 } else {
mistachkinaae280e2015-12-31 19:06:24 +00007339 utf8_printf(stderr,"Error: testctrl %s takes no options\n",
7340 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007341 }
7342 break;
7343
7344 /* sqlite3_test_control(int, uint) */
mistachkin1fe36bb2016-04-04 02:16:44 +00007345 case SQLITE_TESTCTRL_PENDING_BYTE:
shaneh96887e12011-02-10 21:08:58 +00007346 if( nArg==3 ){
drhaf664332013-07-18 20:28:29 +00007347 unsigned int opt = (unsigned int)integerValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00007348 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00007349 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00007350 } else {
mistachkinaae280e2015-12-31 19:06:24 +00007351 utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
drhd416fe72011-03-17 16:45:50 +00007352 " int option\n", azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007353 }
7354 break;
mistachkin1fe36bb2016-04-04 02:16:44 +00007355
shaneh96887e12011-02-10 21:08:58 +00007356 /* sqlite3_test_control(int, int) */
mistachkin1fe36bb2016-04-04 02:16:44 +00007357 case SQLITE_TESTCTRL_ASSERT:
7358 case SQLITE_TESTCTRL_ALWAYS:
7359 case SQLITE_TESTCTRL_NEVER_CORRUPT:
shaneh96887e12011-02-10 21:08:58 +00007360 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00007361 int opt = booleanValue(azArg[2]);
mistachkin8e189222015-04-19 21:43:16 +00007362 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00007363 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00007364 } else {
mistachkinaae280e2015-12-31 19:06:24 +00007365 utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
drhd416fe72011-03-17 16:45:50 +00007366 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007367 }
7368 break;
7369
7370 /* sqlite3_test_control(int, char *) */
7371#ifdef SQLITE_N_KEYWORD
mistachkin1fe36bb2016-04-04 02:16:44 +00007372 case SQLITE_TESTCTRL_ISKEYWORD:
shaneh96887e12011-02-10 21:08:58 +00007373 if( nArg==3 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00007374 const char *opt = azArg[2];
mistachkin8e189222015-04-19 21:43:16 +00007375 rc2 = sqlite3_test_control(testctrl, opt);
mistachkinaae280e2015-12-31 19:06:24 +00007376 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
shaneh96887e12011-02-10 21:08:58 +00007377 } else {
mistachkinaae280e2015-12-31 19:06:24 +00007378 utf8_printf(stderr,
7379 "Error: testctrl %s takes a single char * option\n",
7380 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007381 }
7382 break;
7383#endif
7384
drh1ffede82015-01-30 20:59:27 +00007385 case SQLITE_TESTCTRL_IMPOSTER:
drh8964b342015-01-29 17:54:52 +00007386 if( nArg==5 ){
mistachkin1fe36bb2016-04-04 02:16:44 +00007387 rc2 = sqlite3_test_control(testctrl, p->db,
drh1ffede82015-01-30 20:59:27 +00007388 azArg[2],
drh8964b342015-01-29 17:54:52 +00007389 integerValue(azArg[3]),
7390 integerValue(azArg[4]));
mistachkinaae280e2015-12-31 19:06:24 +00007391 raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
drh8964b342015-01-29 17:54:52 +00007392 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007393 raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
drh8964b342015-01-29 17:54:52 +00007394 }
7395 break;
7396
mistachkin1fe36bb2016-04-04 02:16:44 +00007397 case SQLITE_TESTCTRL_BITVEC_TEST:
7398 case SQLITE_TESTCTRL_FAULT_INSTALL:
7399 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
shaneh96887e12011-02-10 21:08:58 +00007400 default:
mistachkinaae280e2015-12-31 19:06:24 +00007401 utf8_printf(stderr,
7402 "Error: CLI support for testctrl %s not implemented\n",
7403 azArg[1]);
shaneh96887e12011-02-10 21:08:58 +00007404 break;
7405 }
7406 }
7407 }else
drhf1969722017-02-17 23:52:00 +00007408#endif /* !defined(SQLITE_UNTESTABLE) */
shaneh96887e12011-02-10 21:08:58 +00007409
drhc2ce0be2014-05-29 12:36:14 +00007410 if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
drh05782482013-10-24 15:20:20 +00007411 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00007412 sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
shanehe2aa9d72009-11-06 17:20:17 +00007413 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00007414
drhc2ce0be2014-05-29 12:36:14 +00007415 if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
7416 if( nArg==2 ){
7417 enableTimer = booleanValue(azArg[1]);
7418 if( enableTimer && !HAS_TIMER ){
mistachkinaae280e2015-12-31 19:06:24 +00007419 raw_printf(stderr, "Error: timer not available on this system.\n");
drhc2ce0be2014-05-29 12:36:14 +00007420 enableTimer = 0;
7421 }
7422 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007423 raw_printf(stderr, "Usage: .timer on|off\n");
drhc2ce0be2014-05-29 12:36:14 +00007424 rc = 1;
7425 }
shanehe2aa9d72009-11-06 17:20:17 +00007426 }else
mistachkin1fe36bb2016-04-04 02:16:44 +00007427
drhc2ce0be2014-05-29 12:36:14 +00007428 if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
drh05782482013-10-24 15:20:20 +00007429 open_db(p, 0);
drhc2ce0be2014-05-29 12:36:14 +00007430 if( nArg!=2 ){
mistachkinaae280e2015-12-31 19:06:24 +00007431 raw_printf(stderr, "Usage: .trace FILE|off\n");
drhc2ce0be2014-05-29 12:36:14 +00007432 rc = 1;
7433 goto meta_command_exit;
7434 }
drh657b4a82015-03-19 13:30:41 +00007435 output_file_close(p->traceOut);
drh42f64e52012-04-04 16:56:23 +00007436 p->traceOut = output_file_open(azArg[1]);
drhbbb0be82012-06-27 16:12:27 +00007437#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
drh42f64e52012-04-04 16:56:23 +00007438 if( p->traceOut==0 ){
drh4b363a52016-07-23 20:27:41 +00007439 sqlite3_trace_v2(p->db, 0, 0, 0);
drh42f64e52012-04-04 16:56:23 +00007440 }else{
drh4b363a52016-07-23 20:27:41 +00007441 sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
drh42f64e52012-04-04 16:56:23 +00007442 }
7443#endif
7444 }else
7445
drhf442e332014-09-10 19:01:14 +00007446#if SQLITE_USER_AUTHENTICATION
7447 if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
7448 if( nArg<2 ){
mistachkinaae280e2015-12-31 19:06:24 +00007449 raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
drhf442e332014-09-10 19:01:14 +00007450 rc = 1;
7451 goto meta_command_exit;
7452 }
drh7883ecf2014-09-11 16:19:31 +00007453 open_db(p, 0);
drhf442e332014-09-10 19:01:14 +00007454 if( strcmp(azArg[1],"login")==0 ){
7455 if( nArg!=4 ){
mistachkinaae280e2015-12-31 19:06:24 +00007456 raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
drhf442e332014-09-10 19:01:14 +00007457 rc = 1;
7458 goto meta_command_exit;
7459 }
drhd39c40f2014-09-11 00:27:53 +00007460 rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
7461 (int)strlen(azArg[3]));
drhf442e332014-09-10 19:01:14 +00007462 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00007463 utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
drhf442e332014-09-10 19:01:14 +00007464 rc = 1;
7465 }
7466 }else if( strcmp(azArg[1],"add")==0 ){
7467 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00007468 raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00007469 rc = 1;
7470 goto meta_command_exit;
7471 }
drhd39c40f2014-09-11 00:27:53 +00007472 rc = sqlite3_user_add(p->db, azArg[2],
7473 azArg[3], (int)strlen(azArg[3]),
7474 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00007475 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00007476 raw_printf(stderr, "User-Add failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00007477 rc = 1;
7478 }
7479 }else if( strcmp(azArg[1],"edit")==0 ){
7480 if( nArg!=5 ){
mistachkinaae280e2015-12-31 19:06:24 +00007481 raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
drhf442e332014-09-10 19:01:14 +00007482 rc = 1;
7483 goto meta_command_exit;
7484 }
drhd39c40f2014-09-11 00:27:53 +00007485 rc = sqlite3_user_change(p->db, azArg[2],
7486 azArg[3], (int)strlen(azArg[3]),
7487 booleanValue(azArg[4]));
drhf442e332014-09-10 19:01:14 +00007488 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00007489 raw_printf(stderr, "User-Edit failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00007490 rc = 1;
7491 }
7492 }else if( strcmp(azArg[1],"delete")==0 ){
7493 if( nArg!=3 ){
mistachkinaae280e2015-12-31 19:06:24 +00007494 raw_printf(stderr, "Usage: .user delete USER\n");
drhf442e332014-09-10 19:01:14 +00007495 rc = 1;
7496 goto meta_command_exit;
7497 }
7498 rc = sqlite3_user_delete(p->db, azArg[2]);
7499 if( rc ){
mistachkinaae280e2015-12-31 19:06:24 +00007500 raw_printf(stderr, "User-Delete failed: %d\n", rc);
drhf442e332014-09-10 19:01:14 +00007501 rc = 1;
7502 }
7503 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007504 raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
drhf442e332014-09-10 19:01:14 +00007505 rc = 1;
7506 goto meta_command_exit;
mistachkin1fe36bb2016-04-04 02:16:44 +00007507 }
drhf442e332014-09-10 19:01:14 +00007508 }else
7509#endif /* SQLITE_USER_AUTHENTICATION */
7510
drh9fd301b2011-06-03 13:28:22 +00007511 if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007512 utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
drh9fd301b2011-06-03 13:28:22 +00007513 sqlite3_libversion(), sqlite3_sourceid());
7514 }else
7515
drh790f2872015-11-28 18:06:36 +00007516 if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
7517 const char *zDbName = nArg==2 ? azArg[1] : "main";
drh38305ab2017-01-22 16:34:35 +00007518 sqlite3_vfs *pVfs = 0;
drh790f2872015-11-28 18:06:36 +00007519 if( p->db ){
7520 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
7521 if( pVfs ){
mistachkinaae280e2015-12-31 19:06:24 +00007522 utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName);
7523 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7524 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7525 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
drh790f2872015-11-28 18:06:36 +00007526 }
7527 }
7528 }else
7529
drhb19e7352016-01-12 19:37:20 +00007530 if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
7531 sqlite3_vfs *pVfs;
7532 sqlite3_vfs *pCurrent = 0;
7533 if( p->db ){
7534 sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
7535 }
7536 for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
7537 utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName,
7538 pVfs==pCurrent ? " <--- CURRENT" : "");
7539 raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion);
7540 raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile);
7541 raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
7542 if( pVfs->pNext ){
7543 raw_printf(p->out, "-----------------------------------\n");
7544 }
7545 }
7546 }else
7547
drhde60fc22011-12-14 17:53:36 +00007548 if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
7549 const char *zDbName = nArg==2 ? azArg[1] : "main";
7550 char *zVfsName = 0;
7551 if( p->db ){
7552 sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
7553 if( zVfsName ){
mistachkinaae280e2015-12-31 19:06:24 +00007554 utf8_printf(p->out, "%s\n", zVfsName);
drhde60fc22011-12-14 17:53:36 +00007555 sqlite3_free(zVfsName);
7556 }
7557 }
7558 }else
7559
drhcef4fc82012-09-21 22:50:45 +00007560#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
7561 if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
drhc2ce0be2014-05-29 12:36:14 +00007562 sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
drhcef4fc82012-09-21 22:50:45 +00007563 }else
7564#endif
7565
drhc2ce0be2014-05-29 12:36:14 +00007566 if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
drh75897232000-05-29 14:26:00 +00007567 int j;
drh43617e92006-03-06 20:55:46 +00007568 assert( nArg<=ArraySize(azArg) );
drh75897232000-05-29 14:26:00 +00007569 for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
drh348d19c2013-06-03 12:47:43 +00007570 p->colWidth[j-1] = (int)integerValue(azArg[j]);
drh75897232000-05-29 14:26:00 +00007571 }
7572 }else
7573
7574 {
mistachkinaae280e2015-12-31 19:06:24 +00007575 utf8_printf(stderr, "Error: unknown command or invalid arguments: "
drh67505e72002-04-19 12:34:06 +00007576 " \"%s\". Enter \".help\" for help\n", azArg[0]);
shane9bd1b442009-10-23 01:27:39 +00007577 rc = 1;
drh75897232000-05-29 14:26:00 +00007578 }
drh67505e72002-04-19 12:34:06 +00007579
drhc2ce0be2014-05-29 12:36:14 +00007580meta_command_exit:
7581 if( p->outCount ){
7582 p->outCount--;
7583 if( p->outCount==0 ) output_reset(p);
7584 }
drh67505e72002-04-19 12:34:06 +00007585 return rc;
drh75897232000-05-29 14:26:00 +00007586}
7587
drh67505e72002-04-19 12:34:06 +00007588/*
drh91a66392007-09-07 01:12:32 +00007589** Return TRUE if a semicolon occurs anywhere in the first N characters
7590** of string z[].
drh324ccef2003-02-05 14:06:20 +00007591*/
drh9f099fd2013-08-06 14:01:46 +00007592static int line_contains_semicolon(const char *z, int N){
drh91a66392007-09-07 01:12:32 +00007593 int i;
7594 for(i=0; i<N; i++){ if( z[i]==';' ) return 1; }
7595 return 0;
drh324ccef2003-02-05 14:06:20 +00007596}
7597
7598/*
drh70c7a4b2003-04-26 03:03:06 +00007599** Test to see if a line consists entirely of whitespace.
7600*/
7601static int _all_whitespace(const char *z){
7602 for(; *z; z++){
drhf0693c82011-10-11 20:41:54 +00007603 if( IsSpace(z[0]) ) continue;
drh70c7a4b2003-04-26 03:03:06 +00007604 if( *z=='/' && z[1]=='*' ){
7605 z += 2;
7606 while( *z && (*z!='*' || z[1]!='/') ){ z++; }
7607 if( *z==0 ) return 0;
7608 z++;
7609 continue;
7610 }
7611 if( *z=='-' && z[1]=='-' ){
7612 z += 2;
7613 while( *z && *z!='\n' ){ z++; }
7614 if( *z==0 ) return 1;
7615 continue;
7616 }
7617 return 0;
7618 }
7619 return 1;
7620}
7621
7622/*
drha9b17162003-04-29 18:01:28 +00007623** Return TRUE if the line typed in is an SQL command terminator other
7624** than a semi-colon. The SQL Server style "go" command is understood
7625** as is the Oracle "/".
7626*/
drh9f099fd2013-08-06 14:01:46 +00007627static int line_is_command_terminator(const char *zLine){
drhf0693c82011-10-11 20:41:54 +00007628 while( IsSpace(zLine[0]) ){ zLine++; };
drh233a5312008-12-18 22:25:13 +00007629 if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
7630 return 1; /* Oracle */
7631 }
drhf0693c82011-10-11 20:41:54 +00007632 if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
drhc8d74412004-08-31 23:41:26 +00007633 && _all_whitespace(&zLine[2]) ){
drha9b17162003-04-29 18:01:28 +00007634 return 1; /* SQL Server */
7635 }
7636 return 0;
7637}
7638
7639/*
drh233a5312008-12-18 22:25:13 +00007640** Return true if zSql is a complete SQL statement. Return false if it
7641** ends in the middle of a string literal or C-style comment.
7642*/
drh9f099fd2013-08-06 14:01:46 +00007643static int line_is_complete(char *zSql, int nSql){
drh233a5312008-12-18 22:25:13 +00007644 int rc;
7645 if( zSql==0 ) return 1;
7646 zSql[nSql] = ';';
7647 zSql[nSql+1] = 0;
7648 rc = sqlite3_complete(zSql);
7649 zSql[nSql] = 0;
7650 return rc;
7651}
7652
7653/*
drh4e8142c2016-11-11 14:54:22 +00007654** Run a single line of SQL
7655*/
7656static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
7657 int rc;
7658 char *zErrMsg = 0;
7659
7660 open_db(p, 0);
drhe6e1d122017-03-09 13:50:49 +00007661 if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
drh4e8142c2016-11-11 14:54:22 +00007662 BEGIN_TIMER;
7663 rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
7664 END_TIMER;
7665 if( rc || zErrMsg ){
7666 char zPrefix[100];
7667 if( in!=0 || !stdin_is_interactive ){
7668 sqlite3_snprintf(sizeof(zPrefix), zPrefix,
7669 "Error: near line %d:", startline);
7670 }else{
7671 sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
7672 }
7673 if( zErrMsg!=0 ){
7674 utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
7675 sqlite3_free(zErrMsg);
7676 zErrMsg = 0;
7677 }else{
7678 utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
7679 }
7680 return 1;
drhe6e1d122017-03-09 13:50:49 +00007681 }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
drh4e8142c2016-11-11 14:54:22 +00007682 raw_printf(p->out, "changes: %3d total_changes: %d\n",
7683 sqlite3_changes(p->db), sqlite3_total_changes(p->db));
7684 }
7685 return 0;
7686}
7687
7688
7689/*
drh67505e72002-04-19 12:34:06 +00007690** Read input from *in and process it. If *in==0 then input
7691** is interactive - the user is typing it it. Otherwise, input
7692** is coming from a file or device. A prompt is issued and history
7693** is saved only if input is interactive. An interrupt signal will
7694** cause this routine to exit immediately, unless input is interactive.
drhc28490c2006-10-26 14:25:58 +00007695**
7696** Return the number of errors.
drh67505e72002-04-19 12:34:06 +00007697*/
drhdcd87a92014-08-18 13:45:42 +00007698static int process_input(ShellState *p, FILE *in){
drh9f099fd2013-08-06 14:01:46 +00007699 char *zLine = 0; /* A single input line */
7700 char *zSql = 0; /* Accumulated SQL text */
7701 int nLine; /* Length of current line */
7702 int nSql = 0; /* Bytes of zSql[] used */
7703 int nAlloc = 0; /* Allocated zSql[] space */
7704 int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */
drh9f099fd2013-08-06 14:01:46 +00007705 int rc; /* Error code */
7706 int errCnt = 0; /* Number of errors seen */
7707 int lineno = 0; /* Current line number */
7708 int startline = 0; /* Line number for start of current input */
drhc49f44e2006-10-26 18:15:42 +00007709
7710 while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
7711 fflush(p->out);
drh9f099fd2013-08-06 14:01:46 +00007712 zLine = one_input_line(in, zLine, nSql>0);
drhc49f44e2006-10-26 18:15:42 +00007713 if( zLine==0 ){
drh9b8d3572012-04-21 11:33:39 +00007714 /* End of input */
drhfc8b40f2016-09-07 10:10:18 +00007715 if( in==0 && stdin_is_interactive ) printf("\n");
drh9b8d3572012-04-21 11:33:39 +00007716 break;
drhc49f44e2006-10-26 18:15:42 +00007717 }
drh67505e72002-04-19 12:34:06 +00007718 if( seenInterrupt ){
7719 if( in!=0 ) break;
7720 seenInterrupt = 0;
7721 }
drhc28490c2006-10-26 14:25:58 +00007722 lineno++;
drh849a9d92013-12-21 15:46:06 +00007723 if( nSql==0 && _all_whitespace(zLine) ){
drhe6e1d122017-03-09 13:50:49 +00007724 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drh849a9d92013-12-21 15:46:06 +00007725 continue;
7726 }
drh2af0b2d2002-02-21 02:25:02 +00007727 if( zLine && zLine[0]=='.' && nSql==0 ){
drhe6e1d122017-03-09 13:50:49 +00007728 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
drhc49f44e2006-10-26 18:15:42 +00007729 rc = do_meta_command(zLine, p);
shane916f9612009-10-23 00:37:15 +00007730 if( rc==2 ){ /* exit requested */
drh47ad6842006-11-08 12:25:42 +00007731 break;
7732 }else if( rc ){
drhc49f44e2006-10-26 18:15:42 +00007733 errCnt++;
7734 }
drhdaffd0e2001-04-11 14:28:42 +00007735 continue;
7736 }
drh9f099fd2013-08-06 14:01:46 +00007737 if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
drh5bb3eb92007-05-04 13:15:55 +00007738 memcpy(zLine,";",2);
drha9b17162003-04-29 18:01:28 +00007739 }
drh9f099fd2013-08-06 14:01:46 +00007740 nLine = strlen30(zLine);
7741 if( nSql+nLine+2>=nAlloc ){
7742 nAlloc = nSql+nLine+100;
7743 zSql = realloc(zSql, nAlloc);
drhdaffd0e2001-04-11 14:28:42 +00007744 if( zSql==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007745 raw_printf(stderr, "Error: out of memory\n");
drhdaffd0e2001-04-11 14:28:42 +00007746 exit(1);
7747 }
drhdaffd0e2001-04-11 14:28:42 +00007748 }
drh9f099fd2013-08-06 14:01:46 +00007749 nSqlPrior = nSql;
7750 if( nSql==0 ){
7751 int i;
7752 for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
drh77dfd5b2013-08-19 11:15:48 +00007753 assert( nAlloc>0 && zSql!=0 );
drh9f099fd2013-08-06 14:01:46 +00007754 memcpy(zSql, zLine+i, nLine+1-i);
7755 startline = lineno;
7756 nSql = nLine-i;
7757 }else{
7758 zSql[nSql++] = '\n';
7759 memcpy(zSql+nSql, zLine, nLine+1);
7760 nSql += nLine;
7761 }
7762 if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
drh91a66392007-09-07 01:12:32 +00007763 && sqlite3_complete(zSql) ){
drh4e8142c2016-11-11 14:54:22 +00007764 errCnt += runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007765 nSql = 0;
drhc2ce0be2014-05-29 12:36:14 +00007766 if( p->outCount ){
7767 output_reset(p);
7768 p->outCount = 0;
7769 }
drh9f099fd2013-08-06 14:01:46 +00007770 }else if( nSql && _all_whitespace(zSql) ){
drhe6e1d122017-03-09 13:50:49 +00007771 if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
drh7a411f42013-04-17 17:33:17 +00007772 nSql = 0;
drhdaffd0e2001-04-11 14:28:42 +00007773 }
7774 }
drh4e8142c2016-11-11 14:54:22 +00007775 if( nSql && !_all_whitespace(zSql) ){
7776 runOneSqlLine(p, zSql, in, startline);
drhdaffd0e2001-04-11 14:28:42 +00007777 }
drh1f9ca2c2015-08-25 16:57:52 +00007778 free(zSql);
danielk19772ac27622007-07-03 05:31:16 +00007779 free(zLine);
drh4d15a0d2012-12-01 20:21:22 +00007780 return errCnt>0;
drhdaffd0e2001-04-11 14:28:42 +00007781}
7782
drh67505e72002-04-19 12:34:06 +00007783/*
7784** Return a pathname which is the user's home directory. A
drh85e72432012-04-11 11:38:53 +00007785** 0 return indicates an error of some kind.
drh67505e72002-04-19 12:34:06 +00007786*/
drhd1459152016-09-16 19:11:03 +00007787static char *find_home_dir(int clearFlag){
drh85e72432012-04-11 11:38:53 +00007788 static char *home_dir = NULL;
drhd1459152016-09-16 19:11:03 +00007789 if( clearFlag ){
7790 free(home_dir);
7791 home_dir = 0;
7792 return 0;
7793 }
drh85e72432012-04-11 11:38:53 +00007794 if( home_dir ) return home_dir;
persicom7e2dfdd2002-04-18 02:46:52 +00007795
drh4ace5362014-11-10 14:42:28 +00007796#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
7797 && !defined(__RTP__) && !defined(_WRS_KERNEL)
mistachkinc8bde372012-06-18 08:00:56 +00007798 {
7799 struct passwd *pwent;
7800 uid_t uid = getuid();
7801 if( (pwent=getpwuid(uid)) != NULL) {
7802 home_dir = pwent->pw_dir;
7803 }
drh67505e72002-04-19 12:34:06 +00007804 }
7805#endif
7806
chw65d3c132007-11-12 21:09:10 +00007807#if defined(_WIN32_WCE)
7808 /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
7809 */
drh85e72432012-04-11 11:38:53 +00007810 home_dir = "/";
chw65d3c132007-11-12 21:09:10 +00007811#else
7812
drh83905c92012-06-21 13:00:37 +00007813#if defined(_WIN32) || defined(WIN32)
drh164a1b62006-08-19 11:15:20 +00007814 if (!home_dir) {
7815 home_dir = getenv("USERPROFILE");
7816 }
7817#endif
7818
drh67505e72002-04-19 12:34:06 +00007819 if (!home_dir) {
7820 home_dir = getenv("HOME");
drh67505e72002-04-19 12:34:06 +00007821 }
7822
drh83905c92012-06-21 13:00:37 +00007823#if defined(_WIN32) || defined(WIN32)
drhe98d4fa2002-04-21 19:06:22 +00007824 if (!home_dir) {
drh164a1b62006-08-19 11:15:20 +00007825 char *zDrive, *zPath;
7826 int n;
7827 zDrive = getenv("HOMEDRIVE");
7828 zPath = getenv("HOMEPATH");
7829 if( zDrive && zPath ){
drh4f21c4a2008-12-10 22:15:00 +00007830 n = strlen30(zDrive) + strlen30(zPath) + 1;
drh164a1b62006-08-19 11:15:20 +00007831 home_dir = malloc( n );
7832 if( home_dir==0 ) return 0;
7833 sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
7834 return home_dir;
7835 }
7836 home_dir = "c:\\";
drhe98d4fa2002-04-21 19:06:22 +00007837 }
7838#endif
7839
chw65d3c132007-11-12 21:09:10 +00007840#endif /* !_WIN32_WCE */
7841
drh67505e72002-04-19 12:34:06 +00007842 if( home_dir ){
drh4f21c4a2008-12-10 22:15:00 +00007843 int n = strlen30(home_dir) + 1;
drh5bb3eb92007-05-04 13:15:55 +00007844 char *z = malloc( n );
7845 if( z ) memcpy(z, home_dir, n);
drh67505e72002-04-19 12:34:06 +00007846 home_dir = z;
7847 }
drhe98d4fa2002-04-21 19:06:22 +00007848
drh67505e72002-04-19 12:34:06 +00007849 return home_dir;
7850}
7851
7852/*
7853** Read input from the file given by sqliterc_override. Or if that
7854** parameter is NULL, take input from ~/.sqliterc
shane9bd1b442009-10-23 01:27:39 +00007855**
7856** Returns the number of errors.
drh67505e72002-04-19 12:34:06 +00007857*/
drh534f4df2015-02-28 14:03:35 +00007858static void process_sqliterc(
drhdcd87a92014-08-18 13:45:42 +00007859 ShellState *p, /* Configuration data */
drh22fbcb82004-02-01 01:22:50 +00007860 const char *sqliterc_override /* Name of config file. NULL to use default */
7861){
persicom7e2dfdd2002-04-18 02:46:52 +00007862 char *home_dir = NULL;
drh22fbcb82004-02-01 01:22:50 +00007863 const char *sqliterc = sqliterc_override;
drh43617e92006-03-06 20:55:46 +00007864 char *zBuf = 0;
persicom7e2dfdd2002-04-18 02:46:52 +00007865 FILE *in = NULL;
7866
7867 if (sqliterc == NULL) {
drhd1459152016-09-16 19:11:03 +00007868 home_dir = find_home_dir(0);
drhe98d4fa2002-04-21 19:06:22 +00007869 if( home_dir==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00007870 raw_printf(stderr, "-- warning: cannot find home directory;"
drh534f4df2015-02-28 14:03:35 +00007871 " cannot read ~/.sqliterc\n");
7872 return;
drhe98d4fa2002-04-21 19:06:22 +00007873 }
drh2f3de322012-06-27 16:41:31 +00007874 sqlite3_initialize();
drh85e72432012-04-11 11:38:53 +00007875 zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
7876 sqliterc = zBuf;
persicom7e2dfdd2002-04-18 02:46:52 +00007877 }
drha1f9b5e2004-02-14 16:31:02 +00007878 in = fopen(sqliterc,"rb");
drh22fbcb82004-02-01 01:22:50 +00007879 if( in ){
drhc28490c2006-10-26 14:25:58 +00007880 if( stdin_is_interactive ){
mistachkinaae280e2015-12-31 19:06:24 +00007881 utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
drh22fbcb82004-02-01 01:22:50 +00007882 }
drh534f4df2015-02-28 14:03:35 +00007883 process_input(p,in);
drhdd45df82002-04-18 12:39:03 +00007884 fclose(in);
persicom7e2dfdd2002-04-18 02:46:52 +00007885 }
drh85e72432012-04-11 11:38:53 +00007886 sqlite3_free(zBuf);
persicom7e2dfdd2002-04-18 02:46:52 +00007887}
7888
drh67505e72002-04-19 12:34:06 +00007889/*
drhe1e38c42003-05-04 18:30:59 +00007890** Show available command line options
7891*/
mistachkin1fe36bb2016-04-04 02:16:44 +00007892static const char zOptions[] =
mistachkin636bf9f2014-07-19 20:15:16 +00007893 " -ascii set output mode to 'ascii'\n"
drhc49f44e2006-10-26 18:15:42 +00007894 " -bail stop after hitting an error\n"
drhc49f44e2006-10-26 18:15:42 +00007895 " -batch force batch I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007896 " -column set output mode to 'column'\n"
mistachkin6d81d752012-10-25 15:43:28 +00007897 " -cmd COMMAND run \"COMMAND\" before reading stdin\n"
drhc49f44e2006-10-26 18:15:42 +00007898 " -csv set output mode to 'csv'\n"
drhcc3b4f82012-02-07 14:13:50 +00007899 " -echo print commands before execution\n"
mistachkin6d81d752012-10-25 15:43:28 +00007900 " -init FILENAME read/process named file\n"
drhcc3b4f82012-02-07 14:13:50 +00007901 " -[no]header turn headers on or off\n"
drh98d312f2012-10-25 15:23:14 +00007902#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
7903 " -heap SIZE Size of heap for memsys3 or memsys5\n"
7904#endif
drhcc3b4f82012-02-07 14:13:50 +00007905 " -help show this message\n"
drhe1e38c42003-05-04 18:30:59 +00007906 " -html set output mode to HTML\n"
drhcc3b4f82012-02-07 14:13:50 +00007907 " -interactive force interactive I/O\n"
drhe1e38c42003-05-04 18:30:59 +00007908 " -line set output mode to 'line'\n"
7909 " -list set output mode to 'list'\n"
drh44dec872014-08-30 15:49:25 +00007910 " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n"
drh7d9f3942013-04-03 01:26:54 +00007911 " -mmap N default mmap size set to N\n"
drhcc3b4f82012-02-07 14:13:50 +00007912#ifdef SQLITE_ENABLE_MULTIPLEX
7913 " -multiplex enable the multiplexor VFS\n"
7914#endif
mistachkine0d68852014-12-11 03:12:33 +00007915 " -newline SEP set output row separator. Default: '\\n'\n"
drh98d312f2012-10-25 15:23:14 +00007916 " -nullvalue TEXT set text string for NULL values. Default ''\n"
drh44dec872014-08-30 15:49:25 +00007917 " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n"
drha501f7d2017-06-29 21:33:25 +00007918 " -quote set output mode to 'quote'\n"
mistachkine0d68852014-12-11 03:12:33 +00007919 " -separator SEP set output column separator. Default: '|'\n"
shaneh642d8b82010-07-28 16:05:34 +00007920 " -stats print memory stats before each finalize\n"
drhe1e38c42003-05-04 18:30:59 +00007921 " -version show SQLite version\n"
drha7e61d82011-03-12 17:02:57 +00007922 " -vfs NAME use NAME as the default VFS\n"
drh2b625e22011-03-16 17:05:28 +00007923#ifdef SQLITE_ENABLE_VFSTRACE
7924 " -vfstrace enable tracing of all VFS calls\n"
7925#endif
drhe1e38c42003-05-04 18:30:59 +00007926;
7927static void usage(int showDetail){
mistachkinaae280e2015-12-31 19:06:24 +00007928 utf8_printf(stderr,
mistachkin1fe36bb2016-04-04 02:16:44 +00007929 "Usage: %s [OPTIONS] FILENAME [SQL]\n"
drh80e8be92006-08-29 12:04:19 +00007930 "FILENAME is the name of an SQLite database. A new database is created\n"
7931 "if the file does not previously exist.\n", Argv0);
drhe1e38c42003-05-04 18:30:59 +00007932 if( showDetail ){
mistachkinaae280e2015-12-31 19:06:24 +00007933 utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
drhe1e38c42003-05-04 18:30:59 +00007934 }else{
mistachkinaae280e2015-12-31 19:06:24 +00007935 raw_printf(stderr, "Use the -help option for additional information\n");
drhe1e38c42003-05-04 18:30:59 +00007936 }
7937 exit(1);
7938}
7939
7940/*
drh67505e72002-04-19 12:34:06 +00007941** Initialize the state information in data
7942*/
drhdcd87a92014-08-18 13:45:42 +00007943static void main_init(ShellState *data) {
persicom7e2dfdd2002-04-18 02:46:52 +00007944 memset(data, 0, sizeof(*data));
drh700c2522016-02-09 18:39:25 +00007945 data->normalMode = data->cMode = data->mode = MODE_List;
7946 data->autoExplain = 1;
mistachkinfad42082014-07-24 22:13:12 +00007947 memcpy(data->colSeparator,SEP_Column, 2);
7948 memcpy(data->rowSeparator,SEP_Row, 2);
persicom7e2dfdd2002-04-18 02:46:52 +00007949 data->showHeader = 0;
drh44dec872014-08-30 15:49:25 +00007950 data->shellFlgs = SHFLG_Lookaside;
drh52784bd2011-05-18 17:15:06 +00007951 sqlite3_config(SQLITE_CONFIG_URI, 1);
drh127f9d72010-02-23 01:47:00 +00007952 sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
drh44dec872014-08-30 15:49:25 +00007953 sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
drh5bb3eb92007-05-04 13:15:55 +00007954 sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
7955 sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> ");
persicom7e2dfdd2002-04-18 02:46:52 +00007956}
7957
drh98d312f2012-10-25 15:23:14 +00007958/*
drh5c7976f2014-02-10 19:59:27 +00007959** Output text to the console in a font that attracts extra attention.
drh1247aa42014-02-10 19:27:05 +00007960*/
7961#ifdef _WIN32
drh5c7976f2014-02-10 19:59:27 +00007962static void printBold(const char *zText){
7963 HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
7964 CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
7965 GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
7966 SetConsoleTextAttribute(out,
7967 FOREGROUND_RED|FOREGROUND_INTENSITY
7968 );
7969 printf("%s", zText);
7970 SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
drh1247aa42014-02-10 19:27:05 +00007971}
7972#else
drh5c7976f2014-02-10 19:59:27 +00007973static void printBold(const char *zText){
7974 printf("\033[1m%s\033[0m", zText);
drh1247aa42014-02-10 19:27:05 +00007975}
7976#endif
7977
7978/*
drh98d312f2012-10-25 15:23:14 +00007979** Get the argument to an --option. Throw an error and die if no argument
7980** is available.
7981*/
7982static char *cmdline_option_value(int argc, char **argv, int i){
7983 if( i==argc ){
mistachkinaae280e2015-12-31 19:06:24 +00007984 utf8_printf(stderr, "%s: Error: missing argument to %s\n",
drh98d312f2012-10-25 15:23:14 +00007985 argv[0], argv[argc-1]);
7986 exit(1);
7987 }
7988 return argv[i];
7989}
7990
mistachkin1fe36bb2016-04-04 02:16:44 +00007991#ifndef SQLITE_SHELL_IS_UTF8
7992# if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
7993# define SQLITE_SHELL_IS_UTF8 (0)
7994# else
7995# define SQLITE_SHELL_IS_UTF8 (1)
7996# endif
7997#endif
7998
7999#if SQLITE_SHELL_IS_UTF8
mistachkin44723ce2015-03-21 02:22:37 +00008000int SQLITE_CDECL main(int argc, char **argv){
mistachkin1fe36bb2016-04-04 02:16:44 +00008001#else
8002int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
mistachkin1810f222016-04-04 02:33:34 +00008003 char **argv;
mistachkin1fe36bb2016-04-04 02:16:44 +00008004#endif
drh75897232000-05-29 14:26:00 +00008005 char *zErrMsg = 0;
drhdcd87a92014-08-18 13:45:42 +00008006 ShellState data;
drh22fbcb82004-02-01 01:22:50 +00008007 const char *zInitFile = 0;
drh44c2eb12003-04-30 11:38:26 +00008008 int i;
drhc28490c2006-10-26 14:25:58 +00008009 int rc = 0;
drhb3735912014-02-10 16:13:42 +00008010 int warnInmemoryDb = 0;
drhac5649a2014-11-28 13:35:03 +00008011 int readStdin = 1;
8012 int nCmd = 0;
8013 char **azCmd = 0;
drh75897232000-05-29 14:26:00 +00008014
mistachkin1fe36bb2016-04-04 02:16:44 +00008015 setBinaryMode(stdin, 0);
8016 setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
mistachkin1810f222016-04-04 02:33:34 +00008017 stdin_is_interactive = isatty(0);
8018 stdout_is_console = isatty(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00008019
drh69b30ab2014-02-27 15:11:52 +00008020#if USE_SYSTEM_SQLITE+0!=1
drh0a02c722017-08-22 21:07:03 +00008021 if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00008022 utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
drh52784bd2011-05-18 17:15:06 +00008023 sqlite3_sourceid(), SQLITE_SOURCE_ID);
8024 exit(1);
8025 }
drhc7181902014-02-27 15:04:13 +00008026#endif
persicom7e2dfdd2002-04-18 02:46:52 +00008027 main_init(&data);
mistachkin1fe36bb2016-04-04 02:16:44 +00008028#if !SQLITE_SHELL_IS_UTF8
8029 sqlite3_initialize();
8030 argv = sqlite3_malloc64(sizeof(argv[0])*argc);
8031 if( argv==0 ){
8032 raw_printf(stderr, "out of memory\n");
8033 exit(1);
8034 }
8035 for(i=0; i<argc; i++){
8036 argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
8037 if( argv[i]==0 ){
8038 raw_printf(stderr, "out of memory\n");
8039 exit(1);
8040 }
8041 }
8042#endif
mistachkin1810f222016-04-04 02:33:34 +00008043 assert( argc>=1 && argv && argv[0] );
mistachkin1fe36bb2016-04-04 02:16:44 +00008044 Argv0 = argv[0];
persicom7e2dfdd2002-04-18 02:46:52 +00008045
drh44c2eb12003-04-30 11:38:26 +00008046 /* Make sure we have a valid signal handler early, before anything
8047 ** else is done.
8048 */
drh4c504392000-10-16 22:06:40 +00008049#ifdef SIGINT
8050 signal(SIGINT, interrupt_handler);
8051#endif
drh44c2eb12003-04-30 11:38:26 +00008052
drhac5649a2014-11-28 13:35:03 +00008053#ifdef SQLITE_SHELL_DBNAME_PROC
8054 {
8055 /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
8056 ** of a C-function that will provide the name of the database file. Use
8057 ** this compile-time option to embed this shell program in larger
8058 ** applications. */
8059 extern void SQLITE_SHELL_DBNAME_PROC(const char**);
8060 SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
8061 warnInmemoryDb = 0;
8062 }
8063#endif
8064
drh22fbcb82004-02-01 01:22:50 +00008065 /* Do an initial pass through the command-line argument to locate
8066 ** the name of the database file, the name of the initialization file,
drh9c88d682010-12-17 14:03:01 +00008067 ** the size of the alternative malloc heap,
drh22fbcb82004-02-01 01:22:50 +00008068 ** and the first command to execute.
drh44c2eb12003-04-30 11:38:26 +00008069 */
drh98d312f2012-10-25 15:23:14 +00008070 for(i=1; i<argc; i++){
drhc28490c2006-10-26 14:25:58 +00008071 char *z;
drhc28490c2006-10-26 14:25:58 +00008072 z = argv[i];
drh98d312f2012-10-25 15:23:14 +00008073 if( z[0]!='-' ){
8074 if( data.zDbFilename==0 ){
8075 data.zDbFilename = z;
drhac5649a2014-11-28 13:35:03 +00008076 }else{
8077 /* Excesss arguments are interpreted as SQL (or dot-commands) and
8078 ** mean that nothing is read from stdin */
8079 readStdin = 0;
8080 nCmd++;
8081 azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
8082 if( azCmd==0 ){
mistachkinaae280e2015-12-31 19:06:24 +00008083 raw_printf(stderr, "out of memory\n");
drhac5649a2014-11-28 13:35:03 +00008084 exit(1);
8085 }
8086 azCmd[nCmd-1] = z;
drh98d312f2012-10-25 15:23:14 +00008087 }
drh98d312f2012-10-25 15:23:14 +00008088 }
drhcc3b4f82012-02-07 14:13:50 +00008089 if( z[1]=='-' ) z++;
8090 if( strcmp(z,"-separator")==0
8091 || strcmp(z,"-nullvalue")==0
drh6976c212014-07-24 12:09:47 +00008092 || strcmp(z,"-newline")==0
drhcc3b4f82012-02-07 14:13:50 +00008093 || strcmp(z,"-cmd")==0
8094 ){
drh98d312f2012-10-25 15:23:14 +00008095 (void)cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00008096 }else if( strcmp(z,"-init")==0 ){
drh98d312f2012-10-25 15:23:14 +00008097 zInitFile = cmdline_option_value(argc, argv, ++i);
drhcc3b4f82012-02-07 14:13:50 +00008098 }else if( strcmp(z,"-batch")==0 ){
drh98d312f2012-10-25 15:23:14 +00008099 /* Need to check for batch mode here to so we can avoid printing
mistachkin1fe36bb2016-04-04 02:16:44 +00008100 ** informational messages (like from process_sqliterc) before
drh98d312f2012-10-25 15:23:14 +00008101 ** we do the actual processing of arguments later in a second pass.
8102 */
shanef69573d2009-10-24 02:06:14 +00008103 stdin_is_interactive = 0;
drhcc3b4f82012-02-07 14:13:50 +00008104 }else if( strcmp(z,"-heap")==0 ){
drhb07028f2011-10-14 21:49:18 +00008105#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
drh9c88d682010-12-17 14:03:01 +00008106 const char *zSize;
8107 sqlite3_int64 szHeap;
8108
drh98d312f2012-10-25 15:23:14 +00008109 zSize = cmdline_option_value(argc, argv, ++i);
drh7d9f3942013-04-03 01:26:54 +00008110 szHeap = integerValue(zSize);
drh9c88d682010-12-17 14:03:01 +00008111 if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
drh9c88d682010-12-17 14:03:01 +00008112 sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
drhc530b9c2016-07-25 11:27:22 +00008113#else
8114 (void)cmdline_option_value(argc, argv, ++i);
drh9c88d682010-12-17 14:03:01 +00008115#endif
drh44dec872014-08-30 15:49:25 +00008116 }else if( strcmp(z,"-pagecache")==0 ){
8117 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00008118 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00008119 if( sz>70000 ) sz = 70000;
drh3d38cec2015-11-11 15:28:52 +00008120 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00008121 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh3d38cec2015-11-11 15:28:52 +00008122 sqlite3_config(SQLITE_CONFIG_PAGECACHE,
8123 (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
drh44dec872014-08-30 15:49:25 +00008124 data.shellFlgs |= SHFLG_Pagecache;
8125 }else if( strcmp(z,"-lookaside")==0 ){
8126 int n, sz;
mistachkin31970cc2014-09-01 01:16:49 +00008127 sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00008128 if( sz<0 ) sz = 0;
mistachkin31970cc2014-09-01 01:16:49 +00008129 n = (int)integerValue(cmdline_option_value(argc,argv,++i));
drh44dec872014-08-30 15:49:25 +00008130 if( n<0 ) n = 0;
8131 sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
8132 if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
drh97ae8ff2011-03-16 16:56:29 +00008133#ifdef SQLITE_ENABLE_VFSTRACE
drhcc3b4f82012-02-07 14:13:50 +00008134 }else if( strcmp(z,"-vfstrace")==0 ){
drh97ae8ff2011-03-16 16:56:29 +00008135 extern int vfstrace_register(
8136 const char *zTraceName,
8137 const char *zOldVfsName,
8138 int (*xOut)(const char*,void*),
8139 void *pOutArg,
8140 int makeDefault
8141 );
drh2b625e22011-03-16 17:05:28 +00008142 vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
drh97ae8ff2011-03-16 16:56:29 +00008143#endif
drh6f25e892011-07-08 17:02:57 +00008144#ifdef SQLITE_ENABLE_MULTIPLEX
drhcc3b4f82012-02-07 14:13:50 +00008145 }else if( strcmp(z,"-multiplex")==0 ){
drh6f25e892011-07-08 17:02:57 +00008146 extern int sqlite3_multiple_initialize(const char*,int);
8147 sqlite3_multiplex_initialize(0, 1);
8148#endif
drh7d9f3942013-04-03 01:26:54 +00008149 }else if( strcmp(z,"-mmap")==0 ){
drh9b4c59f2013-04-15 17:03:42 +00008150 sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
8151 sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
drhcc3b4f82012-02-07 14:13:50 +00008152 }else if( strcmp(z,"-vfs")==0 ){
drh98d312f2012-10-25 15:23:14 +00008153 sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
drha7e61d82011-03-12 17:02:57 +00008154 if( pVfs ){
8155 sqlite3_vfs_register(pVfs, 1);
8156 }else{
mistachkinaae280e2015-12-31 19:06:24 +00008157 utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
drha7e61d82011-03-12 17:02:57 +00008158 exit(1);
8159 }
drh44c2eb12003-04-30 11:38:26 +00008160 }
8161 }
drh98d312f2012-10-25 15:23:14 +00008162 if( data.zDbFilename==0 ){
danielk197703aded42004-11-22 05:26:27 +00008163#ifndef SQLITE_OMIT_MEMORYDB
drh22fbcb82004-02-01 01:22:50 +00008164 data.zDbFilename = ":memory:";
drh1247aa42014-02-10 19:27:05 +00008165 warnInmemoryDb = argc==1;
danielk197703aded42004-11-22 05:26:27 +00008166#else
mistachkinaae280e2015-12-31 19:06:24 +00008167 utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
shane86f5bdb2009-10-24 02:00:07 +00008168 return 1;
drh01b41712005-08-29 23:06:23 +00008169#endif
drh98d312f2012-10-25 15:23:14 +00008170 }
8171 data.out = stdout;
drh01b41712005-08-29 23:06:23 +00008172
drh44c2eb12003-04-30 11:38:26 +00008173 /* Go ahead and open the database file if it already exists. If the
8174 ** file does not exist, delay opening it. This prevents empty database
8175 ** files from being created if a user mistypes the database name argument
8176 ** to the sqlite command-line tool.
8177 */
drhc8d74412004-08-31 23:41:26 +00008178 if( access(data.zDbFilename, 0)==0 ){
drh05782482013-10-24 15:20:20 +00008179 open_db(&data, 0);
drh44c2eb12003-04-30 11:38:26 +00008180 }
8181
drh22fbcb82004-02-01 01:22:50 +00008182 /* Process the initialization file if there is one. If no -init option
8183 ** is given on the command line, look for a file named ~/.sqliterc and
8184 ** try to process it.
drh44c2eb12003-04-30 11:38:26 +00008185 */
drh534f4df2015-02-28 14:03:35 +00008186 process_sqliterc(&data,zInitFile);
drh44c2eb12003-04-30 11:38:26 +00008187
drh22fbcb82004-02-01 01:22:50 +00008188 /* Make a second pass through the command-line argument and set
8189 ** options. This second pass is delayed until after the initialization
8190 ** file is processed so that the command-line arguments will override
8191 ** settings in the initialization file.
drh44c2eb12003-04-30 11:38:26 +00008192 */
drh98d312f2012-10-25 15:23:14 +00008193 for(i=1; i<argc; i++){
drh22fbcb82004-02-01 01:22:50 +00008194 char *z = argv[i];
drh98d312f2012-10-25 15:23:14 +00008195 if( z[0]!='-' ) continue;
drhc28490c2006-10-26 14:25:58 +00008196 if( z[1]=='-' ){ z++; }
drh2e584cd2006-09-25 13:09:22 +00008197 if( strcmp(z,"-init")==0 ){
drh22fbcb82004-02-01 01:22:50 +00008198 i++;
8199 }else if( strcmp(z,"-html")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00008200 data.mode = MODE_Html;
drh22fbcb82004-02-01 01:22:50 +00008201 }else if( strcmp(z,"-list")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00008202 data.mode = MODE_List;
drha501f7d2017-06-29 21:33:25 +00008203 }else if( strcmp(z,"-quote")==0 ){
8204 data.mode = MODE_Quote;
drh22fbcb82004-02-01 01:22:50 +00008205 }else if( strcmp(z,"-line")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00008206 data.mode = MODE_Line;
drh22fbcb82004-02-01 01:22:50 +00008207 }else if( strcmp(z,"-column")==0 ){
drh8b32e172002-04-08 02:42:57 +00008208 data.mode = MODE_Column;
drhc49f44e2006-10-26 18:15:42 +00008209 }else if( strcmp(z,"-csv")==0 ){
8210 data.mode = MODE_Csv;
mistachkin636bf9f2014-07-19 20:15:16 +00008211 memcpy(data.colSeparator,",",2);
8212 }else if( strcmp(z,"-ascii")==0 ){
8213 data.mode = MODE_Ascii;
8214 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
mistachkinfad42082014-07-24 22:13:12 +00008215 SEP_Unit);
mistachkin636bf9f2014-07-19 20:15:16 +00008216 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
mistachkinfad42082014-07-24 22:13:12 +00008217 SEP_Record);
drh22fbcb82004-02-01 01:22:50 +00008218 }else if( strcmp(z,"-separator")==0 ){
mistachkin636bf9f2014-07-19 20:15:16 +00008219 sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
drh98d312f2012-10-25 15:23:14 +00008220 "%s",cmdline_option_value(argc,argv,++i));
drh6976c212014-07-24 12:09:47 +00008221 }else if( strcmp(z,"-newline")==0 ){
mistachkine0d68852014-12-11 03:12:33 +00008222 sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
drh6976c212014-07-24 12:09:47 +00008223 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00008224 }else if( strcmp(z,"-nullvalue")==0 ){
mistachkin44b99f72014-12-11 03:29:14 +00008225 sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
drh98d312f2012-10-25 15:23:14 +00008226 "%s",cmdline_option_value(argc,argv,++i));
drh22fbcb82004-02-01 01:22:50 +00008227 }else if( strcmp(z,"-header")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00008228 data.showHeader = 1;
drh22fbcb82004-02-01 01:22:50 +00008229 }else if( strcmp(z,"-noheader")==0 ){
drh1e5d0e92000-05-31 23:33:17 +00008230 data.showHeader = 0;
drh22fbcb82004-02-01 01:22:50 +00008231 }else if( strcmp(z,"-echo")==0 ){
drhe6e1d122017-03-09 13:50:49 +00008232 ShellSetFlag(&data, SHFLG_Echo);
drhefbf3b12014-02-28 20:47:24 +00008233 }else if( strcmp(z,"-eqp")==0 ){
8234 data.autoEQP = 1;
drheacd29d2016-04-15 15:03:27 +00008235 }else if( strcmp(z,"-eqpfull")==0 ){
8236 data.autoEQP = 2;
shaneh642d8b82010-07-28 16:05:34 +00008237 }else if( strcmp(z,"-stats")==0 ){
8238 data.statsOn = 1;
dan8d1edb92014-11-05 09:07:28 +00008239 }else if( strcmp(z,"-scanstats")==0 ){
8240 data.scanstatsOn = 1;
drh9569f602015-04-16 15:05:04 +00008241 }else if( strcmp(z,"-backslash")==0 ){
8242 /* Undocumented command-line option: -backslash
8243 ** Causes C-style backslash escapes to be evaluated in SQL statements
8244 ** prior to sending the SQL into SQLite. Useful for injecting
8245 ** crazy bytes in the middle of SQL statements for testing and debugging.
8246 */
drhe6e1d122017-03-09 13:50:49 +00008247 ShellSetFlag(&data, SHFLG_Backslash);
drhc49f44e2006-10-26 18:15:42 +00008248 }else if( strcmp(z,"-bail")==0 ){
8249 bail_on_error = 1;
drh22fbcb82004-02-01 01:22:50 +00008250 }else if( strcmp(z,"-version")==0 ){
drh9fd301b2011-06-03 13:28:22 +00008251 printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
drh151e3e12006-06-06 12:32:21 +00008252 return 0;
drhc28490c2006-10-26 14:25:58 +00008253 }else if( strcmp(z,"-interactive")==0 ){
8254 stdin_is_interactive = 1;
8255 }else if( strcmp(z,"-batch")==0 ){
8256 stdin_is_interactive = 0;
drh9c88d682010-12-17 14:03:01 +00008257 }else if( strcmp(z,"-heap")==0 ){
8258 i++;
drh44dec872014-08-30 15:49:25 +00008259 }else if( strcmp(z,"-pagecache")==0 ){
8260 i+=2;
8261 }else if( strcmp(z,"-lookaside")==0 ){
8262 i+=2;
drh7d9f3942013-04-03 01:26:54 +00008263 }else if( strcmp(z,"-mmap")==0 ){
8264 i++;
drha7e61d82011-03-12 17:02:57 +00008265 }else if( strcmp(z,"-vfs")==0 ){
8266 i++;
drh6f25e892011-07-08 17:02:57 +00008267#ifdef SQLITE_ENABLE_VFSTRACE
drh97ae8ff2011-03-16 16:56:29 +00008268 }else if( strcmp(z,"-vfstrace")==0 ){
8269 i++;
drh6f25e892011-07-08 17:02:57 +00008270#endif
8271#ifdef SQLITE_ENABLE_MULTIPLEX
8272 }else if( strcmp(z,"-multiplex")==0 ){
8273 i++;
8274#endif
drhcc3b4f82012-02-07 14:13:50 +00008275 }else if( strcmp(z,"-help")==0 ){
drhe1e38c42003-05-04 18:30:59 +00008276 usage(1);
drhcc3b4f82012-02-07 14:13:50 +00008277 }else if( strcmp(z,"-cmd")==0 ){
drhac5649a2014-11-28 13:35:03 +00008278 /* Run commands that follow -cmd first and separately from commands
8279 ** that simply appear on the command-line. This seems goofy. It would
8280 ** be better if all commands ran in the order that they appear. But
8281 ** we retain the goofy behavior for historical compatibility. */
drhcc3b4f82012-02-07 14:13:50 +00008282 if( i==argc-1 ) break;
drh98d312f2012-10-25 15:23:14 +00008283 z = cmdline_option_value(argc,argv,++i);
drhcc3b4f82012-02-07 14:13:50 +00008284 if( z[0]=='.' ){
8285 rc = do_meta_command(z, &data);
drh99b39082013-04-17 12:19:48 +00008286 if( rc && bail_on_error ) return rc==2 ? 0 : rc;
drhcc3b4f82012-02-07 14:13:50 +00008287 }else{
drh05782482013-10-24 15:20:20 +00008288 open_db(&data, 0);
drhcc3b4f82012-02-07 14:13:50 +00008289 rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
8290 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00008291 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhcc3b4f82012-02-07 14:13:50 +00008292 if( bail_on_error ) return rc!=0 ? rc : 1;
8293 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00008294 utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
drhcc3b4f82012-02-07 14:13:50 +00008295 if( bail_on_error ) return rc;
8296 }
8297 }
drh1e5d0e92000-05-31 23:33:17 +00008298 }else{
mistachkinaae280e2015-12-31 19:06:24 +00008299 utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
8300 raw_printf(stderr,"Use -help for a list of options.\n");
drh1e5d0e92000-05-31 23:33:17 +00008301 return 1;
8302 }
drh700c2522016-02-09 18:39:25 +00008303 data.cMode = data.mode;
drh1e5d0e92000-05-31 23:33:17 +00008304 }
drh44c2eb12003-04-30 11:38:26 +00008305
drhac5649a2014-11-28 13:35:03 +00008306 if( !readStdin ){
8307 /* Run all arguments that do not begin with '-' as if they were separate
8308 ** command-line inputs, except for the argToSkip argument which contains
8309 ** the database filename.
drh44c2eb12003-04-30 11:38:26 +00008310 */
drhac5649a2014-11-28 13:35:03 +00008311 for(i=0; i<nCmd; i++){
8312 if( azCmd[i][0]=='.' ){
8313 rc = do_meta_command(azCmd[i], &data);
8314 if( rc ) return rc==2 ? 0 : rc;
8315 }else{
8316 open_db(&data, 0);
8317 rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
8318 if( zErrMsg!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00008319 utf8_printf(stderr,"Error: %s\n", zErrMsg);
drhac5649a2014-11-28 13:35:03 +00008320 return rc!=0 ? rc : 1;
8321 }else if( rc!=0 ){
mistachkinaae280e2015-12-31 19:06:24 +00008322 utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
drhac5649a2014-11-28 13:35:03 +00008323 return rc;
8324 }
drh6ff13852001-11-25 13:18:23 +00008325 }
drh75897232000-05-29 14:26:00 +00008326 }
drhac5649a2014-11-28 13:35:03 +00008327 free(azCmd);
drh75897232000-05-29 14:26:00 +00008328 }else{
drh44c2eb12003-04-30 11:38:26 +00008329 /* Run commands received from standard input
8330 */
drhc28490c2006-10-26 14:25:58 +00008331 if( stdin_is_interactive ){
drh67505e72002-04-19 12:34:06 +00008332 char *zHome;
8333 char *zHistory = 0;
drh5bb3eb92007-05-04 13:15:55 +00008334 int nHistory;
drh75897232000-05-29 14:26:00 +00008335 printf(
drh743e0032011-12-12 16:51:50 +00008336 "SQLite version %s %.19s\n" /*extra-version-info*/
drh1247aa42014-02-10 19:27:05 +00008337 "Enter \".help\" for usage hints.\n",
drh9fd301b2011-06-03 13:28:22 +00008338 sqlite3_libversion(), sqlite3_sourceid()
drh75897232000-05-29 14:26:00 +00008339 );
drhb3735912014-02-10 16:13:42 +00008340 if( warnInmemoryDb ){
drh1247aa42014-02-10 19:27:05 +00008341 printf("Connected to a ");
mistachkin378d01a2014-03-06 02:15:42 +00008342 printBold("transient in-memory database");
8343 printf(".\nUse \".open FILENAME\" to reopen on a "
drh1247aa42014-02-10 19:27:05 +00008344 "persistent database.\n");
drhb3735912014-02-10 16:13:42 +00008345 }
drhd1459152016-09-16 19:11:03 +00008346 zHome = find_home_dir(0);
drhea678832008-12-10 19:26:22 +00008347 if( zHome ){
drh4f21c4a2008-12-10 22:15:00 +00008348 nHistory = strlen30(zHome) + 20;
drhea678832008-12-10 19:26:22 +00008349 if( (zHistory = malloc(nHistory))!=0 ){
8350 sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
8351 }
drh67505e72002-04-19 12:34:06 +00008352 }
drhf5ed7ad2015-06-15 14:43:25 +00008353 if( zHistory ){ shell_read_history(zHistory); }
drh56eb09b2017-07-11 13:59:07 +00008354#if HAVE_READLINE || HAVE_EDITLINE
8355 rl_attempted_completion_function = readline_completion;
8356#elif HAVE_LINENOISE
8357 linenoiseSetCompletionCallback(linenoise_completion);
8358#endif
drhc28490c2006-10-26 14:25:58 +00008359 rc = process_input(&data, 0);
drh67505e72002-04-19 12:34:06 +00008360 if( zHistory ){
drh80f134c2017-07-18 14:41:44 +00008361 shell_stifle_history(2000);
danfd34d6d2015-02-25 10:54:53 +00008362 shell_write_history(zHistory);
adamd0a3daa32006-07-28 20:16:14 +00008363 free(zHistory);
drh67505e72002-04-19 12:34:06 +00008364 }
drhdaffd0e2001-04-11 14:28:42 +00008365 }else{
drhc28490c2006-10-26 14:25:58 +00008366 rc = process_input(&data, stdin);
drh75897232000-05-29 14:26:00 +00008367 }
8368 }
drh33048c02001-10-01 14:29:22 +00008369 set_table_name(&data, 0);
drh72af0772010-05-06 20:19:55 +00008370 if( data.db ){
drhe6229612014-08-18 15:08:26 +00008371 session_close_all(&data);
drhe14cd932010-12-08 03:28:17 +00008372 sqlite3_close(data.db);
adamd0a3daa32006-07-28 20:16:14 +00008373 }
mistachkin1fe36bb2016-04-04 02:16:44 +00008374 sqlite3_free(data.zFreeOnClose);
drhd1459152016-09-16 19:11:03 +00008375 find_home_dir(1);
mistachkin1fe36bb2016-04-04 02:16:44 +00008376#if !SQLITE_SHELL_IS_UTF8
8377 for(i=0; i<argc; i++) sqlite3_free(argv[i]);
8378 sqlite3_free(argv);
8379#endif
drhc28490c2006-10-26 14:25:58 +00008380 return rc;
drh75897232000-05-29 14:26:00 +00008381}