/ Check-in [36acc0a9]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:The src/shell.c file is now generated from src/shell.c.in, so remove shell.c from version control and update the makefiles to build it automatically.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: 36acc0a97fdcc6f54f29c68c4e131702f69c3e59e58237ff4e5c647928699956
User & Date: drh 2017-10-12 13:47:48
References
2017-10-12
14:13
Fix the "snapshot-tarball" makefile target, which was broken by the shell.c change of check-in [36acc0a9]. check-in: c643ace2 user: drh tags: branch-3.21
Context
2017-10-12
20:37
Add the sqlite_dbpage virtual table (enabled using SQLITE_ENABLE_DBPAGE_VTAB). Make that virtual table and dbstat available to the command-line shell. check-in: eaeeb09d user: drh tags: trunk
15:28
Add the experimental "sqlite_expert" extension. Used to find index definitions that might help with specified SQL queries. (Later:) Parked on a dead-end branch due to an assertion fault in TH3. We will merge again after the bug is fixed. Closed-Leaf check-in: d1ef9eab user: dan tags: withdrawn
14:13
Update this branch to match latest trunk. check-in: d325da6c user: dan tags: schemalint
14:03
Merge fixes from trunk. All changes are on makefiles and test scripts. There are no core code changes. check-in: 1fb87a0c user: drh tags: branch-3.21
13:47
The src/shell.c file is now generated from src/shell.c.in, so remove shell.c from version control and update the makefiles to build it automatically. check-in: 36acc0a9 user: drh tags: trunk
13:21
Merge fixes from the 3.21 branch. check-in: 29292169 user: drh tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to Makefile.in.

   261    261     $(TOP)/src/prepare.c \
   262    262     $(TOP)/src/printf.c \
   263    263     $(TOP)/src/random.c \
   264    264     $(TOP)/src/resolve.c \
   265    265     $(TOP)/src/rowset.c \
   266    266     $(TOP)/src/select.c \
   267    267     $(TOP)/src/status.c \
   268         -  $(TOP)/src/shell.c \
          268  +  $(TOP)/src/shell.c.in \
   269    269     $(TOP)/src/sqlite.h.in \
   270    270     $(TOP)/src/sqlite3ext.h \
   271    271     $(TOP)/src/sqliteInt.h \
   272    272     $(TOP)/src/sqliteLimit.h \
   273    273     $(TOP)/src/table.c \
   274    274     $(TOP)/src/tclsqlite.c \
   275    275     $(TOP)/src/threads.c \
................................................................................
   358    358   SRC += \
   359    359     keywordhash.h \
   360    360     opcodes.c \
   361    361     opcodes.h \
   362    362     parse.c \
   363    363     parse.h \
   364    364     config.h \
          365  +  shell.c \
   365    366     sqlite3.h
   366    367   
   367    368   # Source code to the test files.
   368    369   #
   369    370   TESTSRC = \
   370    371     $(TOP)/src/test1.c \
   371    372     $(TOP)/src/test2.c \
................................................................................
   593    594   libtclsqlite3.la:	tclsqlite.lo libsqlite3.la
   594    595   	$(LTLINK) -no-undefined -o $@ tclsqlite.lo \
   595    596   		libsqlite3.la @TCL_STUB_LIB_SPEC@ $(TLIBS) \
   596    597   		-rpath "$(TCLLIBDIR)" \
   597    598   		-version-info "8:6:8" \
   598    599   		-avoid-version
   599    600   
   600         -sqlite3$(TEXE):	$(TOP)/src/shell.c sqlite3.c
          601  +sqlite3$(TEXE):	shell.c sqlite3.c
   601    602   	$(LTLINK) $(READLINE_FLAGS) $(SHELL_OPT) -o $@ \
   602         -		$(TOP)/src/shell.c sqlite3.c \
          603  +		shell.c sqlite3.c \
   603    604   		$(LIBREADLINE) $(TLIBS) -rpath "$(libdir)"
   604    605   
   605    606   sqldiff$(TEXE):	$(TOP)/tool/sqldiff.c sqlite3.lo sqlite3.h
   606    607   	$(LTLINK) -o $@ $(TOP)/tool/sqldiff.c sqlite3.lo $(TLIBS)
   607    608   
   608    609   dbhash$(TEXE):	$(TOP)/tool/dbhash.c sqlite3.lo sqlite3.h
   609    610   	$(LTLINK) -o $@ $(TOP)/tool/dbhash.c sqlite3.lo $(TLIBS)
................................................................................
   966    967   
   967    968   sqlite3.h:	$(TOP)/src/sqlite.h.in $(TOP)/manifest mksourceid$(BEXE) $(TOP)/VERSION
   968    969   	$(TCLSH_CMD) $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h
   969    970   
   970    971   keywordhash.h:	$(TOP)/tool/mkkeywordhash.c
   971    972   	$(BCC) -o mkkeywordhash$(BEXE) $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)/tool/mkkeywordhash.c
   972    973   	./mkkeywordhash$(BEXE) >keywordhash.h
          974  +
          975  +# Source files that go into making shell.c
          976  +SHELL_SRC = \
          977  +	$(TOP)/src/shell.c.in \
          978  +	$(TOP)/ext/misc/shathree.c \
          979  +	$(TOP)/ext/misc/fileio.c \
          980  +	$(TOP)/ext/misc/completion.c
          981  +
          982  +shell.c:	$(SHELL_SRC) $(TOP)/tool/mkshellc.tcl
          983  +	$(TCLSH_CMD) $(TOP)/tool/mkshellc.tcl >shell.c
          984  +
   973    985   
   974    986   
   975    987   
   976    988   # Rules to build the extension objects.
   977    989   #
   978    990   icu.lo:	$(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR)
   979    991   	$(LTCOMPILE) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c

Changes to Makefile.msc.

  1216   1216     $(TOP)\src\vtab.c \
  1217   1217     $(TOP)\src\wal.c \
  1218   1218     $(TOP)\src\walker.c \
  1219   1219     $(TOP)\src\where.c \
  1220   1220     $(TOP)\src\wherecode.c \
  1221   1221     $(TOP)\src\whereexpr.c
  1222   1222   
  1223         -# Shell source code files.
  1224         -#
  1225         -SRC02 = \
  1226         -  $(TOP)\src\shell.c
  1227         -
  1228   1223   # Core miscellaneous files.
  1229   1224   #
  1230   1225   SRC03 = \
  1231   1226     $(TOP)\src\parse.y
  1232   1227   
  1233   1228   # Core header files, part 1.
  1234   1229   #
................................................................................
  1327   1322   
  1328   1323   # Generated header files
  1329   1324   #
  1330   1325   SRC11 = \
  1331   1326     keywordhash.h \
  1332   1327     opcodes.h \
  1333   1328     parse.h \
         1329  +  shell.c \
  1334   1330     $(SQLITE3H)
  1335   1331   
  1336   1332   # Generated Tcl header files
  1337   1333   #
  1338   1334   !IF $(USE_STDCALL)!=0 || $(FOR_WIN10)!=0
  1339   1335   SRC12 = \
  1340   1336     $(SQLITETCLH) \
................................................................................
  1341   1337     $(SQLITETCLDECLSH)
  1342   1338   !ELSE
  1343   1339   SRC12 =
  1344   1340   !ENDIF
  1345   1341   
  1346   1342   # All source code files.
  1347   1343   #
  1348         -SRC = $(SRC00) $(SRC01) $(SRC02) $(SRC03) $(SRC04) $(SRC05) $(SRC06) $(SRC07) $(SRC08) $(SRC09) $(SRC10) $(SRC11)
         1344  +SRC = $(SRC00) $(SRC01) $(SRC03) $(SRC04) $(SRC05) $(SRC06) $(SRC07) $(SRC08) $(SRC09) $(SRC10) $(SRC11)
  1349   1345   
  1350   1346   # Source code to the test files.
  1351   1347   #
  1352   1348   TESTSRC = \
  1353   1349     $(TOP)\src\test1.c \
  1354   1350     $(TOP)\src\test2.c \
  1355   1351     $(TOP)\src\test3.c \
................................................................................
  1565   1561   sqlite3.def:	libsqlite3.lib
  1566   1562   	echo EXPORTS > sqlite3.def
  1567   1563   	dumpbin /all libsqlite3.lib \
  1568   1564   		| $(TCLSH_CMD) $(TOP)\tool\replace.tcl include "^\s+1 _?(sqlite3(?:session|changeset|changegroup)?_[^@]*)(?:@\d+)?$$" \1 \
  1569   1565   		| sort >> sqlite3.def
  1570   1566   # <</block2>>
  1571   1567   
  1572         -$(SQLITE3EXE):	$(TOP)\src\shell.c $(SHELL_CORE_DEP) $(LIBRESOBJS) $(SHELL_CORE_SRC) $(SQLITE3H)
  1573         -	$(LTLINK) $(SHELL_COMPILE_OPTS) $(READLINE_FLAGS) $(TOP)\src\shell.c $(SHELL_CORE_SRC) \
         1568  +$(SQLITE3EXE):	shell.c $(SHELL_CORE_DEP) $(LIBRESOBJS) $(SHELL_CORE_SRC) $(SQLITE3H)
         1569  +	$(LTLINK) $(SHELL_COMPILE_OPTS) $(READLINE_FLAGS) shell.c $(SHELL_CORE_SRC) \
  1574   1570   		/link $(SQLITE3EXEPDB) $(LDFLAGS) $(LTLINKOPTS) $(SHELL_LINK_OPTS) $(LTLIBPATHS) $(LIBRESOBJS) $(LIBREADLINE) $(LTLIBS) $(TLIBS)
  1575   1571   
  1576   1572   # <<mark>>
  1577   1573   sqldiff.exe:	$(TOP)\tool\sqldiff.c $(SQLITE3C) $(SQLITE3H)
  1578   1574   	$(LTLINK) $(NO_WARN) $(TOP)\tool\sqldiff.c $(SQLITE3C) /link $(LDFLAGS) $(LTLINKOPTS)
  1579   1575   
  1580   1576   dbhash.exe:	$(TOP)\tool\dbhash.c $(SQLITE3C) $(SQLITE3H)
................................................................................
  1625   1621   # all that automatic generation.
  1626   1622   #
  1627   1623   .target_source:	$(SRC) $(TOP)\tool\vdbe-compress.tcl fts5.c $(SQLITE_TCL_DEP)
  1628   1624   	-rmdir /Q/S tsrc 2>NUL
  1629   1625   	-mkdir tsrc
  1630   1626   	for %i in ($(SRC00)) do copy /Y %i tsrc
  1631   1627   	for %i in ($(SRC01)) do copy /Y %i tsrc
  1632         -	for %i in ($(SRC02)) do copy /Y %i tsrc
  1633   1628   	for %i in ($(SRC03)) do copy /Y %i tsrc
  1634   1629   	for %i in ($(SRC04)) do copy /Y %i tsrc
  1635   1630   	for %i in ($(SRC05)) do copy /Y %i tsrc
  1636   1631   	for %i in ($(SRC06)) do copy /Y %i tsrc
  1637   1632   	for %i in ($(SRC07)) do copy /Y %i tsrc
  1638   1633   	for %i in ($(SRC08)) do copy /Y %i tsrc
  1639   1634   	for %i in ($(SRC09)) do copy /Y %i tsrc
................................................................................
  1970   1965   mkkeywordhash.exe:	$(TOP)\tool\mkkeywordhash.c
  1971   1966   	$(BCC) $(NO_WARN) -Fe$@ $(REQ_FEATURE_FLAGS) $(OPT_FEATURE_FLAGS) $(EXT_FEATURE_FLAGS) $(OPTS) \
  1972   1967   		$(TOP)\tool\mkkeywordhash.c /link $(LDFLAGS) $(NLTLINKOPTS) $(NLTLIBPATHS)
  1973   1968   
  1974   1969   keywordhash.h:	$(TOP)\tool\mkkeywordhash.c mkkeywordhash.exe
  1975   1970   	.\mkkeywordhash.exe > keywordhash.h
  1976   1971   
         1972  +# Source files that go into making shell.c
         1973  +SHELL_SRC = \
         1974  +	$(TOP)\src\shell.c.in \
         1975  +	$(TOP)\ext\misc\shathree.c \
         1976  +	$(TOP)\ext\misc\fileio.c \
         1977  +	$(TOP)\ext\misc\completion.c
         1978  +
         1979  +shell.c:	$(SHELL_SRC) $(TOP)/tool/mkshellc.tcl
         1980  +	$(TCLSH_CMD) $(TOP)/tool/mkshellc.tcl > shell.c
  1977   1981   
  1978   1982   
  1979   1983   # Rules to build the extension objects.
  1980   1984   #
  1981   1985   icu.lo:	$(TOP)\ext\icu\icu.c $(HDR) $(EXTHDR)
  1982   1986   	$(LTCOMPILE) $(CORE_COMPILE_OPTS) $(NO_WARN) -DSQLITE_CORE -c $(TOP)\ext\icu\icu.c
  1983   1987   

Changes to main.mk.

   142    142     $(TOP)/src/prepare.c \
   143    143     $(TOP)/src/printf.c \
   144    144     $(TOP)/src/random.c \
   145    145     $(TOP)/src/resolve.c \
   146    146     $(TOP)/src/rowset.c \
   147    147     $(TOP)/src/select.c \
   148    148     $(TOP)/src/status.c \
   149         -  $(TOP)/src/shell.c \
          149  +  $(TOP)/src/shell.c.in \
   150    150     $(TOP)/src/sqlite.h.in \
   151    151     $(TOP)/src/sqlite3ext.h \
   152    152     $(TOP)/src/sqliteInt.h \
   153    153     $(TOP)/src/sqliteLimit.h \
   154    154     $(TOP)/src/table.c \
   155    155     $(TOP)/src/tclsqlite.c \
   156    156     $(TOP)/src/threads.c \
................................................................................
   266    266   #
   267    267   SRC += \
   268    268     keywordhash.h \
   269    269     opcodes.c \
   270    270     opcodes.h \
   271    271     parse.c \
   272    272     parse.h \
          273  +  shell.c \
   273    274     sqlite3.h
   274    275   
   275    276   
   276    277   # Source code to the test files.
   277    278   #
   278    279   TESTSRC = \
   279    280     $(TOP)/ext/fts3/fts3_term.c \
................................................................................
   492    493   #
   493    494   all:	sqlite3.h libsqlite3.a sqlite3$(EXE)
   494    495   
   495    496   libsqlite3.a:	$(LIBOBJ)
   496    497   	$(AR) libsqlite3.a $(LIBOBJ)
   497    498   	$(RANLIB) libsqlite3.a
   498    499   
   499         -sqlite3$(EXE):	$(TOP)/src/shell.c libsqlite3.a sqlite3.h
          500  +sqlite3$(EXE):	shell.c libsqlite3.a sqlite3.h
   500    501   	$(TCCX) $(READLINE_FLAGS) -o sqlite3$(EXE) $(SHELL_OPT) \
   501         -		$(TOP)/src/shell.c libsqlite3.a $(LIBREADLINE) $(TLIBS) $(THREADLIB)
          502  +		shell.c libsqlite3.a $(LIBREADLINE) $(TLIBS) $(THREADLIB)
   502    503   
   503    504   sqldiff$(EXE):	$(TOP)/tool/sqldiff.c sqlite3.c sqlite3.h
   504    505   	$(TCCX) -o sqldiff$(EXE) -DSQLITE_THREADSAFE=0 \
   505    506   		$(TOP)/tool/sqldiff.c sqlite3.c $(TLIBS) $(THREADLIB)
   506    507   
   507    508   dbhash$(EXE):	$(TOP)/tool/dbhash.c sqlite3.c sqlite3.h
   508    509   	$(TCCX) -o dbhash$(EXE) -DSQLITE_THREADSAFE=0 \
................................................................................
   653    654   
   654    655   sqlite3.h:	$(TOP)/src/sqlite.h.in $(TOP)/manifest mksourceid $(TOP)/VERSION $(TOP)/ext/rtree/sqlite3rtree.h
   655    656   	tclsh $(TOP)/tool/mksqlite3h.tcl $(TOP) >sqlite3.h
   656    657   
   657    658   keywordhash.h:	$(TOP)/tool/mkkeywordhash.c
   658    659   	$(BCC) -o mkkeywordhash $(OPTS) $(TOP)/tool/mkkeywordhash.c
   659    660   	./mkkeywordhash >keywordhash.h
          661  +
          662  +# Source files that go into making shell.c
          663  +SHELL_SRC = \
          664  +	$(TOP)/src/shell.c.in \
          665  +	$(TOP)/ext/misc/shathree.c \
          666  +	$(TOP)/ext/misc/fileio.c \
          667  +	$(TOP)/ext/misc/completion.c
          668  +
          669  +shell.c:	$(SHELL_SRC) $(TOP)/tool/mkshellc.tcl
          670  +	tclsh $(TOP)/tool/mkshellc.tcl >shell.c
   660    671   
   661    672   
   662    673   
   663    674   # Rules to build the extension objects.
   664    675   #
   665    676   icu.o:	$(TOP)/ext/icu/icu.c $(HDR) $(EXTHDR)
   666    677   	$(TCCX) -DSQLITE_CORE -c $(TOP)/ext/icu/icu.c

Deleted src/shell.c.

     1         -/* 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         -*/
    19         -/*
    20         -** 2001 September 15
    21         -**
    22         -** The author disclaims copyright to this source code.  In place of
    23         -** a legal notice, here is a blessing:
    24         -**
    25         -**    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.
    28         -**
    29         -*************************************************************************
    30         -** This file contains code to implement the "sqlite" command line
    31         -** utility for accessing SQLite databases.
    32         -*/
    33         -#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
    34         -/* This needs to come before any includes for MSVC compiler */
    35         -#define _CRT_SECURE_NO_WARNINGS
    36         -#endif
    37         -
    38         -/*
    39         -** Warning pragmas copied from msvc.h in the core.
    40         -*/
    41         -#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) */
    58         -
    59         -/*
    60         -** No support for loadable extensions in VxWorks.
    61         -*/
    62         -#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
    63         -# define SQLITE_OMIT_LOAD_EXTENSION 1
    64         -#endif
    65         -
    66         -/*
    67         -** 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         -
    77         -#include <stdlib.h>
    78         -#include <string.h>
    79         -#include <stdio.h>
    80         -#include <assert.h>
    81         -#include "sqlite3.h"
    82         -#if SQLITE_USER_AUTHENTICATION
    83         -# include "sqlite3userauth.h"
    84         -#endif
    85         -#include <ctype.h>
    86         -#include <stdarg.h>
    87         -
    88         -#if !defined(_WIN32) && !defined(WIN32)
    89         -# include <signal.h>
    90         -# if !defined(__RTP__) && !defined(_WRS_KERNEL)
    91         -#  include <pwd.h>
    92         -# endif
    93         -# include <unistd.h>
    94         -# include <sys/types.h>
    95         -#endif
    96         -
    97         -#if HAVE_READLINE
    98         -# include <readline/readline.h>
    99         -# include <readline/history.h>
   100         -#endif
   101         -
   102         -#if HAVE_EDITLINE
   103         -# include <editline/readline.h>
   104         -#endif
   105         -
   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         -
   125         -# define shell_read_history(X)
   126         -# define shell_write_history(X)
   127         -# define shell_stifle_history(X)
   128         -
   129         -# define SHELL_USE_LOCAL_GETLINE 1
   130         -#endif
   131         -
   132         -
   133         -#if defined(_WIN32) || defined(WIN32)
   134         -# include <io.h>
   135         -# include <fcntl.h>
   136         -# 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
   144         -#else
   145         - /* Make sure isatty() has a prototype. */
   146         - extern int isatty(int);
   147         -
   148         -# 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
   156         -#endif
   157         -
   158         -#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         -
   166         -/* 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         -
   171         -#if defined(_WIN32) || defined(WIN32)
   172         -#include <windows.h>
   173         -
   174         -/* string conversion routines only needed on Win32 */
   175         -extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
   176         -extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
   177         -extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
   178         -extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
   179         -#endif
   180         -
   181         -/* 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)
   188         -static void setBinaryMode(FILE *file, int isOutput){
   189         -  if( isOutput ) fflush(file);
   190         -  _setmode(_fileno(file), _O_BINARY);
   191         -}
   192         -static void setTextMode(FILE *file, int isOutput){
   193         -  if( isOutput ) fflush(file);
   194         -  _setmode(_fileno(file), _O_TEXT);
   195         -}
   196         -#else
   197         -# define setBinaryMode(X,Y)
   198         -# define setTextMode(X,Y)
   199         -#endif
   200         -
   201         -
   202         -/* True if the timer is enabled */
   203         -static int enableTimer = 0;
   204         -
   205         -/* Return the current wall-clock time */
   206         -static sqlite3_int64 timeOfDay(void){
   207         -  static sqlite3_vfs *clockVfs = 0;
   208         -  sqlite3_int64 t;
   209         -  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
   210         -  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
   211         -    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         -
   220         -#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
   221         -#include <sys/time.h>
   222         -#include <sys/resource.h>
   223         -
   224         -/* VxWorks does not support getrusage() as far as we can determine */
   225         -#if defined(_WRS_KERNEL) || defined(__RTP__)
   226         -struct 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         -
   233         -/* Saved resource information for the beginning of an operation */
   234         -static struct rusage sBegin;  /* CPU time at start */
   235         -static sqlite3_int64 iBegin;  /* Wall-clock time at start */
   236         -
   237         -/*
   238         -** Begin timing an operation
   239         -*/
   240         -static void beginTimer(void){
   241         -  if( enableTimer ){
   242         -    getrusage(RUSAGE_SELF, &sBegin);
   243         -    iBegin = timeOfDay();
   244         -  }
   245         -}
   246         -
   247         -/* Return the difference of two time_structs in seconds */
   248         -static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
   249         -  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
   250         -         (double)(pEnd->tv_sec - pStart->tv_sec);
   251         -}
   252         -
   253         -/*
   254         -** Print the timing results.
   255         -*/
   256         -static void endTimer(void){
   257         -  if( enableTimer ){
   258         -    sqlite3_int64 iEnd = timeOfDay();
   259         -    struct rusage sEnd;
   260         -    getrusage(RUSAGE_SELF, &sEnd);
   261         -    printf("Run Time: real %.3f user %f sys %f\n",
   262         -       (iEnd - iBegin)*0.001,
   263         -       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
   264         -       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
   265         -  }
   266         -}
   267         -
   268         -#define BEGIN_TIMER beginTimer()
   269         -#define END_TIMER endTimer()
   270         -#define HAS_TIMER 1
   271         -
   272         -#elif (defined(_WIN32) || defined(WIN32))
   273         -
   274         -/* Saved resource information for the beginning of an operation */
   275         -static HANDLE hProcess;
   276         -static FILETIME ftKernelBegin;
   277         -static FILETIME ftUserBegin;
   278         -static sqlite3_int64 ftWallBegin;
   279         -typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME,
   280         -                                    LPFILETIME, LPFILETIME);
   281         -static GETPROCTIMES getProcessTimesAddr = NULL;
   282         -
   283         -/*
   284         -** Check to see if we have timer support.  Return 1 if necessary
   285         -** support found (or found previously).
   286         -*/
   287         -static int hasTimer(void){
   288         -  if( getProcessTimesAddr ){
   289         -    return 1;
   290         -  } else {
   291         -    /* 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.
   294         -    */
   295         -    hProcess = GetCurrentProcess();
   296         -    if( hProcess ){
   297         -      HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll"));
   298         -      if( NULL != hinstLib ){
   299         -        getProcessTimesAddr =
   300         -            (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes");
   301         -        if( NULL != getProcessTimesAddr ){
   302         -          return 1;
   303         -        }
   304         -        FreeLibrary(hinstLib);
   305         -      }
   306         -    }
   307         -  }
   308         -  return 0;
   309         -}
   310         -
   311         -/*
   312         -** Begin timing an operation
   313         -*/
   314         -static void beginTimer(void){
   315         -  if( enableTimer && getProcessTimesAddr ){
   316         -    FILETIME ftCreation, ftExit;
   317         -    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,
   318         -                        &ftKernelBegin,&ftUserBegin);
   319         -    ftWallBegin = timeOfDay();
   320         -  }
   321         -}
   322         -
   323         -/* Return the difference of two FILETIME structs in seconds */
   324         -static 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         -*/
   333         -static void endTimer(void){
   334         -  if( enableTimer && getProcessTimesAddr){
   335         -    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
   336         -    sqlite3_int64 ftWallEnd = timeOfDay();
   337         -    getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
   338         -    printf("Run Time: real %.3f user %f sys %f\n",
   339         -       (ftWallEnd - ftWallBegin)*0.001,
   340         -       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         -
   349         -#else
   350         -#define BEGIN_TIMER
   351         -#define END_TIMER
   352         -#define HAS_TIMER 0
   353         -#endif
   354         -
   355         -/*
   356         -** Used to prevent warnings about unused parameters
   357         -*/
   358         -#define UNUSED_PARAMETER(x) (void)(x)
   359         -
   360         -/*
   361         -** If the following flag is set, then command execution stops
   362         -** at an error if we are not interactive.
   363         -*/
   364         -static int bail_on_error = 0;
   365         -
   366         -/*
   367         -** Threat stdin as an interactive input if the following variable
   368         -** is true.  Otherwise, assume stdin is connected to a file or pipe.
   369         -*/
   370         -static int stdin_is_interactive = 1;
   371         -
   372         -/*
   373         -** 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         -*/
   377         -static int stdout_is_console = 1;
   378         -
   379         -/*
   380         -** 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         -*/
   384         -static sqlite3 *globalDb = 0;
   385         -
   386         -/*
   387         -** True if an interrupt (Control-C) has been received.
   388         -*/
   389         -static volatile int seenInterrupt = 0;
   390         -
   391         -/*
   392         -** 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         -*/
   395         -static char *Argv0;
   396         -
   397         -/*
   398         -** Prompt strings. Initialized in main. Settable with
   399         -**   .prompt main continue
   400         -*/
   401         -static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
   402         -static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
   403         -
   404         -/*
   405         -** 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)
   410         -void 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) ){
   414         -    char *z1 = sqlite3_vmprintf(zFormat, ap);
   415         -    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
   416         -    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         -/*
   437         -** Write I/O traces to the following stream.
   438         -*/
   439         -#ifdef SQLITE_ENABLE_IOTRACE
   440         -static FILE *iotrace = 0;
   441         -#endif
   442         -
   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         -*/
   449         -#ifdef SQLITE_ENABLE_IOTRACE
   450         -static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
   451         -  va_list ap;
   452         -  char *z;
   453         -  if( iotrace==0 ) return;
   454         -  va_start(ap, zFormat);
   455         -  z = sqlite3_vmprintf(zFormat, ap);
   456         -  va_end(ap);
   457         -  utf8_printf(iotrace, "%s", z);
   458         -  sqlite3_free(z);
   459         -}
   460         -#endif
   461         -
   462         -/*
   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         -*/
   468         -static 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];
   473         -  if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
   474         -  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         -
   492         -
   493         -/*
   494         -** Determines if a string is a number of not.
   495         -*/
   496         -static int isNumber(const char *z, int *realnum){
   497         -  if( *z=='-' || *z=='+' ) z++;
   498         -  if( !IsDigit(*z) ){
   499         -    return 0;
   500         -  }
   501         -  z++;
   502         -  if( realnum ) *realnum = 0;
   503         -  while( IsDigit(*z) ){ z++; }
   504         -  if( *z=='.' ){
   505         -    z++;
   506         -    if( !IsDigit(*z) ) return 0;
   507         -    while( IsDigit(*z) ){ z++; }
   508         -    if( realnum ) *realnum = 1;
   509         -  }
   510         -  if( *z=='e' || *z=='E' ){
   511         -    z++;
   512         -    if( *z=='+' || *z=='-' ) z++;
   513         -    if( !IsDigit(*z) ) return 0;
   514         -    while( IsDigit(*z) ){ z++; }
   515         -    if( realnum ) *realnum = 1;
   516         -  }
   517         -  return *z==0;
   518         -}
   519         -
   520         -/*
   521         -** Compute a string length that is limited to what can be stored in
   522         -** lower 30 bits of a 32-bit signed integer.
   523         -*/
   524         -static int strlen30(const char *z){
   525         -  const char *z2 = z;
   526         -  while( *z2 ){ z2++; }
   527         -  return 0x3fffffff & (int)(z2 - z);
   528         -}
   529         -
   530         -/*
   531         -** Return the length of a string in characters.  Multibyte UTF8 characters
   532         -** count as a single character.
   533         -*/
   534         -static 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         -/*
   543         -** This routine reads a line of text from FILE in, stores
   544         -** 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         -**
   548         -** If zLine is not NULL then it is a malloced buffer returned from
   549         -** a previous call to this routine that may be reused.
   550         -*/
   551         -static char *local_getline(char *zLine, FILE *in){
   552         -  int nLine = zLine==0 ? 0 : 100;
   553         -  int n = 0;
   554         -
   555         -  while( 1 ){
   556         -    if( n+100>nLine ){
   557         -      nLine = nLine*2 + 100;
   558         -      zLine = realloc(zLine, nLine);
   559         -      if( zLine==0 ) return 0;
   560         -    }
   561         -    if( fgets(&zLine[n], nLine - n, in)==0 ){
   562         -      if( n==0 ){
   563         -        free(zLine);
   564         -        return 0;
   565         -      }
   566         -      zLine[n] = 0;
   567         -      break;
   568         -    }
   569         -    while( zLine[n] ) n++;
   570         -    if( n>0 && zLine[n-1]=='\n' ){
   571         -      n--;
   572         -      if( n>0 && zLine[n-1]=='\r' ) n--;
   573         -      zLine[n] = 0;
   574         -      break;
   575         -    }
   576         -  }
   577         -#if defined(_WIN32) || defined(WIN32)
   578         -  /* For interactive input on Windows systems, translate the
   579         -  ** multi-byte characterset characters into UTF-8. */
   580         -  if( stdin_is_interactive && in==stdin ){
   581         -    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
   582         -    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) */
   596         -  return zLine;
   597         -}
   598         -
   599         -/*
   600         -** Retrieve a single line of input text.
   601         -**
   602         -** 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.
   612         -*/
   613         -static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
   614         -  char *zPrompt;
   615         -  char *zResult;
   616         -  if( in!=0 ){
   617         -    zResult = local_getline(zPrior, in);
   618         -  }else{
   619         -    zPrompt = isContinuation ? continuePrompt : mainPrompt;
   620         -#if SHELL_USE_LOCAL_GETLINE
   621         -    printf("%s", zPrompt);
   622         -    fflush(stdout);
   623         -    zResult = local_getline(zPrior, stdin);
   624         -#else
   625         -    free(zPrior);
   626         -    zResult = shell_readline(zPrompt);
   627         -    if( zResult && *zResult ) shell_add_history(zResult);
   628         -#endif
   629         -  }
   630         -  return zResult;
   631         -}
   632         -/*
   633         -** A variable length string to which one can append text.
   634         -*/
   635         -typedef struct ShellText ShellText;
   636         -struct ShellText {
   637         -  char *z;
   638         -  int n;
   639         -  int nAlloc;
   640         -};
   641         -
   642         -/*
   643         -** Initialize and destroy a ShellText object
   644         -*/
   645         -static void initText(ShellText *p){
   646         -  memset(p, 0, sizeof(*p));
   647         -}
   648         -static 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         -*/
   661         -static 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         -*/
   708         -static 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         -}
   749         -
   750         -/*
   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         -*/
   769         -static 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 ){
   787         -    for(i=0; i<(int)(sizeof(aPrefix)/sizeof(aPrefix[0])); i++){
   788         -      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         -
   805         -/*
   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.
   810         -*/
   811         -#define SQLITE_EXTENSION_INIT1
   812         -#define SQLITE_EXTENSION_INIT2(X) (void)(X)
   813         -
   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         -*/
   843         -SQLITE_EXTENSION_INIT1
   844         -#include <assert.h>
   845         -#include <string.h>
   846         -#include <stdarg.h>
   847         -typedef sqlite3_uint64 u64;
   848         -
   849         -/******************************************************************************
   850         -** The Hash Engine
   851         -*/
   852         -/*
   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         -*/
   878         -typedef struct SHA3Context SHA3Context;
   879         -struct 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         -*/
   892         -static 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         -*/
  1214         -static 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         -*/
  1243         -static 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         -*/
  1282         -static 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         -}
  1299         -/* End of the hashing logic
  1300         -*****************************************************************************/
  1301         -
  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
  1306         -** size is 256.  If X is a BLOB, it is hashed as is.  
  1307         -** 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         -*/
  1311         -static 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         -*/
  1343         -static 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         -*/
  1390         -static 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         -}
  1499         -
  1500         -
  1501         -#ifdef _WIN32
  1502         -
  1503         -#endif
  1504         -int 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         -*/
  1546         -SQLITE_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         -*/
  1554         -static 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         -
  1564         -  (void)(argc);  /* Unused parameter */
  1565         -  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         -*/
  1587         -static 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         -
  1597         -  (void)(argc);  /* Unused parameter */
  1598         -  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
  1614         -
  1615         -#endif
  1616         -int 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 ********************/
  1634         -/************************* 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         -*/
  1670         -SQLITE_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         -*/
  1680         -typedef struct completion_vtab completion_vtab;
  1681         -struct 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         -*/
  1690         -typedef struct completion_cursor completion_cursor;
  1691         -struct 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         -*/
  1732         -static 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         -
  1742         -  (void)(pAux);    /* Unused parameter */
  1743         -  (void)(argc);    /* Unused parameter */
  1744         -  (void)(argv);    /* Unused parameter */
  1745         -  (void)(pzErr);   /* Unused parameter */
  1746         -
  1747         -/* 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         -*/
  1773         -static 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         -*/
  1781         -static 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         -*/
  1794         -static 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         -*/
  1804         -static 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         -*/
  1813         -static 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         -};
  1833         -#define completionKwCount \
  1834         -   (int)(sizeof(completionKwrds)/sizeof(completionKwrds[0]))
  1835         -
  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         -*/
  1850         -static 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: {
  1858         -        if( pCur->j >= completionKwCount ){
  1859         -          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         -*/
  1956         -static 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         -*/
  1987         -static 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         -*/
  1997         -static 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         -*/
  2008         -static 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;
  2015         -  (void)(idxStr);   /* Unused parameter */
  2016         -  (void)(argc);     /* Unused parameter */
  2017         -  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         -*/
  2060         -static 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         -
  2071         -  (void)(tab);    /* Unused parameter */
  2072         -  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         -*/
  2105         -static 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 */
  2126         -  0,                         /* xSavepoint */
  2127         -  0,                         /* xRelease */
  2128         -  0                          /* xRollbackTo */
  2129         -};
  2130         -
  2131         -#endif /* SQLITE_OMIT_VIRTUALTABLE */
  2132         -
  2133         -int 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
  2142         -
  2143         -#endif
  2144         -int 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);
  2151         -  (void)(pzErrMsg);  /* Unused parameter */
  2152         -#ifndef SQLITE_OMIT_VIRTUALTABLE
  2153         -  rc = sqlite3CompletionVtabInit(db);
  2154         -#endif
  2155         -  return rc;
  2156         -}
  2157         -
  2158         -/************************* End ../ext/misc/completion.c ********************/
  2159         -
  2160         -#if defined(SQLITE_ENABLE_SESSION)
  2161         -/*
  2162         -** State information for a single open session
  2163         -*/
  2164         -typedef struct OpenSession OpenSession;
  2165         -struct 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         -
  2173         -/*
  2174         -** Shell output mode information from before ".explain on",
  2175         -** saved so that it can be restored by ".explain off"
  2176         -*/
  2177         -typedef struct SavedModeInfo SavedModeInfo;
  2178         -struct 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" */
  2183         -};
  2184         -
  2185         -/*
  2186         -** State information about the database connection is contained in an
  2187         -** instance of the following structure.
  2188         -*/
  2189         -typedef struct ShellState ShellState;
  2190         -struct ShellState {
  2191         -  sqlite3 *db;           /* The database */
  2192         -  int autoExplain;       /* Automatically turn on .explain mode */
  2193         -  int autoEQP;           /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
  2194         -  int statsOn;           /* True to display memory stats before each finalize */
  2195         -  int scanstatsOn;       /* True to display scan stats before each finalize */
  2196         -  int outCount;          /* Revert to stdout when reaching zero */
  2197         -  int cnt;               /* Number of records displayed so far */
  2198         -  FILE *out;             /* Write results here */
  2199         -  FILE *traceOut;        /* Output for sqlite3_trace() */
  2200         -  int nErr;              /* Number of errors seen */
  2201         -  int mode;              /* An output mode setting */
  2202         -  int cMode;             /* temporary output mode for the current query */
  2203         -  int normalMode;        /* Output mode before ".explain on" */
  2204         -  int writableSchema;    /* True if PRAGMA writable_schema=ON */
  2205         -  int showHeader;        /* True to show column names in List or Column mode */
  2206         -  int nCheck;            /* Number of ".check" commands run */
  2207         -  unsigned shellFlgs;    /* Various flags */
  2208         -  char *zDestTable;      /* Name of destination table when MODE_Insert */
  2209         -  char zTestcase[30];    /* Name of current test case */
  2210         -  char colSeparator[20]; /* Column separator character for several modes */
  2211         -  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
  2212         -  int colWidth[100];     /* Requested width of each column when in column mode*/
  2213         -  int actualWidth[100];  /* Actual width of each column */
  2214         -  char nullValue[20];    /* The text to print when a NULL comes back from
  2215         -                         ** the database */
  2216         -  char outfile[FILENAME_MAX]; /* Filename for *out */
  2217         -  const char *zDbFilename;    /* name of the database file */
  2218         -  char *zFreeOnClose;         /* Filename to free when closing */
  2219         -  const char *zVfs;           /* Name of VFS to use */
  2220         -  sqlite3_stmt *pStmt;   /* Current statement if any. */
  2221         -  FILE *pLog;            /* Write log output here */
  2222         -  int *aiIndent;         /* Array of indents used in MODE_Explain */
  2223         -  int nIndent;           /* Size of array aiIndent[] */
  2224         -  int iIndent;           /* Index of current op in aiIndent[] */
  2225         -#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
  2229         -};
  2230         -
  2231         -/*
  2232         -** These are the allowed shellFlgs values
  2233         -*/
  2234         -#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 */
  2241         -
  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)))
  2248         -
  2249         -/*
  2250         -** These are the allowed modes.
  2251         -*/
  2252         -#define MODE_Line     0  /* One column per line.  Blank line between records */
  2253         -#define MODE_Column   1  /* One record per line in neat columns */
  2254         -#define MODE_List     2  /* One record per line with a separator */
  2255         -#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 */
  2258         -#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 */
  2264         -
  2265         -static const char *modeDescr[] = {
  2266         -  "line",
  2267         -  "column",
  2268         -  "list",
  2269         -  "semi",
  2270         -  "html",
  2271         -  "insert",
  2272         -  "quote",
  2273         -  "tcl",
  2274         -  "csv",
  2275         -  "explain",
  2276         -  "ascii",
  2277         -  "prettyprint",
  2278         -};
  2279         -
  2280         -/*
  2281         -** These are the column/row/line separators used by the various
  2282         -** import/export modes.
  2283         -*/
  2284         -#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"
  2292         -
  2293         -/*
  2294         -** Number of elements in an array
  2295         -*/
  2296         -#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
  2297         -
  2298         -/*
  2299         -** A callback for the sqlite3_log() interface.
  2300         -*/
  2301         -static void shellLog(void *pArg, int iErrCode, const char *zMsg){
  2302         -  ShellState *p = (ShellState*)pArg;
  2303         -  if( p->pLog==0 ) return;
  2304         -  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
  2305         -  fflush(p->pLog);
  2306         -}
  2307         -
  2308         -/*
  2309         -** Output the given string as a hex-encoded blob (eg. X'1234' )
  2310         -*/
  2311         -static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  2312         -  int i;
  2313         -  char *zBlob = (char *)pBlob;
  2314         -  raw_printf(out,"X'");
  2315         -  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
  2316         -  raw_printf(out,"'");
  2317         -}
  2318         -
  2319         -/*
  2320         -** 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         -*/
  2326         -static 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         -/*
  2341         -** Output the given string as a quoted string using SQL quoting conventions.
  2342         -**
  2343         -** See also: output_quoted_escaped_string()
  2344         -*/
  2345         -static void output_quoted_string(FILE *out, const char *z){
  2346         -  int i;
  2347         -  char c;
  2348         -  setBinaryMode(out, 1);
  2349         -  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         -*/
  2384         -static void output_quoted_escaped_string(FILE *out, const char *z){
  2385         -  int i;
  2386         -  char c;
  2387         -  setBinaryMode(out, 1);
  2388         -  for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){}
  2389         -  if( c==0 ){
  2390         -    utf8_printf(out,"'%s'",z);
  2391         -  }else{
  2392         -    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, "'");
  2410         -    while( *z ){
  2411         -      for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){}
  2412         -      if( c=='\'' ) i++;
  2413         -      if( i ){
  2414         -        utf8_printf(out, "%.*s", i, z);
  2415         -        z += i;
  2416         -      }
  2417         -      if( c=='\'' ){
  2418         -        raw_printf(out, "'");
  2419         -        continue;
  2420         -      }
  2421         -      if( c==0 ){
  2422         -        break;
  2423         -      }
  2424         -      z++;
  2425         -      if( c=='\n' ){
  2426         -        raw_printf(out, "%s", zNL);
  2427         -        continue;
  2428         -      }
  2429         -      raw_printf(out, "%s", zCR);
  2430         -    }
  2431         -    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         -    }
  2438         -  }
  2439         -  setTextMode(out, 1);
  2440         -}
  2441         -
  2442         -/*
  2443         -** Output the given string as a quoted according to C or TCL quoting rules.
  2444         -*/
  2445         -static 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);
  2452         -    }else if( c=='"' ){
  2453         -      fputc('\\', out);
  2454         -      fputc('"', out);
  2455         -    }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);
  2464         -    }else if( !isprint(c&0xff) ){
  2465         -      raw_printf(out, "\\%03o", c&0xff);
  2466         -    }else{
  2467         -      fputc(c, out);
  2468         -    }
  2469         -  }
  2470         -  fputc('"', out);
  2471         -}
  2472         -
  2473         -/*
  2474         -** Output the given string with characters that are special to
  2475         -** HTML escaped.
  2476         -*/
  2477         -static void output_html_string(FILE *out, const char *z){
  2478         -  int i;
  2479         -  if( z==0 ) z = "";
  2480         -  while( *z ){
  2481         -    for(i=0;   z[i]
  2482         -            && z[i]!='<'
  2483         -            && z[i]!='&'
  2484         -            && z[i]!='>'
  2485         -            && z[i]!='\"'
  2486         -            && z[i]!='\'';
  2487         -        i++){}
  2488         -    if( i>0 ){
  2489         -      utf8_printf(out,"%.*s",i,z);
  2490         -    }
  2491         -    if( z[i]=='<' ){
  2492         -      raw_printf(out,"&lt;");
  2493         -    }else if( z[i]=='&' ){
  2494         -      raw_printf(out,"&amp;");
  2495         -    }else if( z[i]=='>' ){
  2496         -      raw_printf(out,"&gt;");
  2497         -    }else if( z[i]=='\"' ){
  2498         -      raw_printf(out,"&quot;");
  2499         -    }else if( z[i]=='\'' ){
  2500         -      raw_printf(out,"&#39;");
  2501         -    }else{
  2502         -      break;
  2503         -    }
  2504         -    z += i + 1;
  2505         -  }
  2506         -}
  2507         -
  2508         -/*
  2509         -** If a field contains any character identified by a 1 in the following
  2510         -** array, then the string must be quoted for CSV.
  2511         -*/
  2512         -static const char needCsvQuote[] = {
  2513         -  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,
  2529         -};
  2530         -
  2531         -/*
  2532         -** Output a single term of CSV.  Actually, p->colSeparator is used for
  2533         -** the separator, which may or may not be a comma.  p->nullValue is
  2534         -** the null value.  Strings are quoted if necessary.  The separator
  2535         -** is only issued if bSep is true.
  2536         -*/
  2537         -static void output_csv(ShellState *p, const char *z, int bSep){
  2538         -  FILE *out = p->out;
  2539         -  if( z==0 ){
  2540         -    utf8_printf(out,"%s",p->nullValue);
  2541         -  }else{
  2542         -    int i;
  2543         -    int nSep = strlen30(p->colSeparator);
  2544         -    for(i=0; z[i]; i++){
  2545         -      if( needCsvQuote[((unsigned char*)z)[i]]
  2546         -         || (z[i]==p->colSeparator[0] &&
  2547         -             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
  2548         -        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{
  2560         -      utf8_printf(out, "%s", z);
  2561         -    }
  2562         -  }
  2563         -  if( bSep ){
  2564         -    utf8_printf(p->out, "%s", p->colSeparator);
  2565         -  }
  2566         -}
  2567         -
  2568         -#ifdef SIGINT
  2569         -/*
  2570         -** This routine runs when the user presses Ctrl-C
  2571         -*/
  2572         -static void interrupt_handler(int NotUsed){
  2573         -  UNUSED_PARAMETER(NotUsed);
  2574         -  seenInterrupt++;
  2575         -  if( seenInterrupt>2 ) exit(1);
  2576         -  if( globalDb ) sqlite3_interrupt(globalDb);
  2577         -}
  2578         -#endif
  2579         -
  2580         -#ifndef SQLITE_OMIT_AUTHORIZATION
  2581         -/*
  2582         -** When the ".auth ON" is set, the following authorizer callback is
  2583         -** invoked.  It always returns SQLITE_OK.
  2584         -*/
  2585         -static 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;
  2613         -  utf8_printf(p->out, "authorizer: %s", azAction[op]);
  2614         -  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         -}
  2625         -#endif
  2626         -
  2627         -/*
  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         -*/
  2633         -static 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         -}
  2640         -static 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         -}
  2646         -
  2647         -/*
  2648         -** This is the callback routine that the shell
  2649         -** invokes for each row of a query result.
  2650         -*/
  2651         -static 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         -){
  2658         -  int i;
  2659         -  ShellState *p = (ShellState*)pArg;
  2660         -
  2661         -  if( azArg==0 ) return 0;
  2662         -  switch( p->cMode ){
  2663         -    case MODE_Line: {
  2664         -      int w = 5;
  2665         -      if( azArg==0 ) break;
  2666         -      for(i=0; i<nArg; i++){
  2667         -        int len = strlen30(azCol[i] ? azCol[i] : "");
  2668         -        if( len>w ) w = len;
  2669         -      }
  2670         -      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
  2671         -      for(i=0; i<nArg; i++){
  2672         -        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
  2673         -                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
  2674         -      }
  2675         -      break;
  2676         -    }
  2677         -    case MODE_Explain:
  2678         -    case MODE_Column: {
  2679         -      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;
  2690         -        rowSep = SEP_Row;
  2691         -      }
  2692         -      if( p->cnt++==0 ){
  2693         -        for(i=0; i<nArg; i++){
  2694         -          int w, n;
  2695         -          if( i<ArraySize(p->colWidth) ){
  2696         -            w = colWidth[i];
  2697         -          }else{
  2698         -            w = 0;
  2699         -          }
  2700         -          if( w==0 ){
  2701         -            w = strlenChar(azCol[i] ? azCol[i] : "");
  2702         -            if( w<10 ) w = 10;
  2703         -            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
  2704         -            if( w<n ) w = n;
  2705         -          }
  2706         -          if( i<ArraySize(p->actualWidth) ){
  2707         -            p->actualWidth[i] = w;
  2708         -          }
  2709         -          if( showHdr ){
  2710         -            utf8_width_print(p->out, w, azCol[i]);
  2711         -            utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
  2712         -          }
  2713         -        }
  2714         -        if( showHdr ){
  2715         -          for(i=0; i<nArg; i++){
  2716         -            int w;
  2717         -            if( i<ArraySize(p->actualWidth) ){
  2718         -               w = p->actualWidth[i];
  2719         -               if( w<0 ) w = -w;
  2720         -            }else{
  2721         -               w = 10;
  2722         -            }
  2723         -            utf8_printf(p->out,"%-*.*s%s",w,w,
  2724         -                   "----------------------------------------------------------"
  2725         -                   "----------------------------------------------------------",
  2726         -                    i==nArg-1 ? rowSep : "  ");
  2727         -          }
  2728         -        }
  2729         -      }
  2730         -      if( azArg==0 ) break;
  2731         -      for(i=0; i<nArg; i++){
  2732         -        int w;
  2733         -        if( i<ArraySize(p->actualWidth) ){
  2734         -           w = p->actualWidth[i];
  2735         -        }else{
  2736         -           w = 10;
  2737         -        }
  2738         -        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
  2739         -          w = strlenChar(azArg[i]);
  2740         -        }
  2741         -        if( i==1 && p->aiIndent && p->pStmt ){
  2742         -          if( p->iIndent<p->nIndent ){
  2743         -            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  2744         -          }
  2745         -          p->iIndent++;
  2746         -        }
  2747         -        utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
  2748         -        utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
  2749         -      }
  2750         -      break;
  2751         -    }
  2752         -    case MODE_Semi: {   /* .schema and .fullschema output */
  2753         -      printSchemaLine(p->out, azArg[0], ";\n");
  2754         -      break;
  2755         -    }
  2756         -    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
  2757         -      char *z;
  2758         -      int j;
  2759         -      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) ){
  2776         -          if( z[j-1]=='\r' ) z[j-1] = '\n';
  2777         -          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 ){
  2786         -        for(i=j=0; (c = z[i])!=0; i++){
  2787         -          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 ){
  2798         -              printSchemaLineN(p->out, z, j, "\n");
  2799         -              j = 0;
  2800         -            }
  2801         -          }
  2802         -          z[j++] = c;
  2803         -          if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
  2804         -            if( c=='\n' ) j--;
  2805         -            printSchemaLineN(p->out, z, j, "\n  ");
  2806         -            j = 0;
  2807         -            nLine++;
  2808         -            while( IsSpace(z[i+1]) ){ i++; }
  2809         -          }
  2810         -        }
  2811         -        z[j] = 0;
  2812         -      }
  2813         -      printSchemaLine(p->out, z, ";\n");
  2814         -      sqlite3_free(z);
  2815         -      break;
  2816         -    }
  2817         -    case MODE_List: {
  2818         -      if( p->cnt++==0 && p->showHeader ){
  2819         -        for(i=0; i<nArg; i++){
  2820         -          utf8_printf(p->out,"%s%s",azCol[i],
  2821         -                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
  2822         -        }
  2823         -      }
  2824         -      if( azArg==0 ) break;
  2825         -      for(i=0; i<nArg; i++){
  2826         -        char *z = azArg[i];
  2827         -        if( z==0 ) z = p->nullValue;
  2828         -        utf8_printf(p->out, "%s", z);
  2829         -        if( i<nArg-1 ){
  2830         -          utf8_printf(p->out, "%s", p->colSeparator);
  2831         -        }else{
  2832         -          utf8_printf(p->out, "%s", p->rowSeparator);
  2833         -        }
  2834         -      }
  2835         -      break;
  2836         -    }
  2837         -    case MODE_Html: {
  2838         -      if( p->cnt++==0 && p->showHeader ){
  2839         -        raw_printf(p->out,"<TR>");
  2840         -        for(i=0; i<nArg; i++){
  2841         -          raw_printf(p->out,"<TH>");
  2842         -          output_html_string(p->out, azCol[i]);
  2843         -          raw_printf(p->out,"</TH>\n");
  2844         -        }
  2845         -        raw_printf(p->out,"</TR>\n");
  2846         -      }
  2847         -      if( azArg==0 ) break;
  2848         -      raw_printf(p->out,"<TR>");
  2849         -      for(i=0; i<nArg; i++){
  2850         -        raw_printf(p->out,"<TD>");
  2851         -        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  2852         -        raw_printf(p->out,"</TD>\n");
  2853         -      }
  2854         -      raw_printf(p->out,"</TR>\n");
  2855         -      break;
  2856         -    }
  2857         -    case MODE_Tcl: {
  2858         -      if( p->cnt++==0 && p->showHeader ){
  2859         -        for(i=0; i<nArg; i++){
  2860         -          output_c_string(p->out,azCol[i] ? azCol[i] : "");
  2861         -          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  2862         -        }
  2863         -        utf8_printf(p->out, "%s", p->rowSeparator);
  2864         -      }
  2865         -      if( azArg==0 ) break;
  2866         -      for(i=0; i<nArg; i++){
  2867         -        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  2868         -        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  2869         -      }
  2870         -      utf8_printf(p->out, "%s", p->rowSeparator);
  2871         -      break;
  2872         -    }
  2873         -    case MODE_Csv: {
  2874         -      setBinaryMode(p->out, 1);
  2875         -      if( p->cnt++==0 && p->showHeader ){
  2876         -        for(i=0; i<nArg; i++){
  2877         -          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  2878         -        }
  2879         -        utf8_printf(p->out, "%s", p->rowSeparator);
  2880         -      }
  2881         -      if( nArg>0 ){
  2882         -        for(i=0; i<nArg; i++){
  2883         -          output_csv(p, azArg[i], i<nArg-1);
  2884         -        }
  2885         -        utf8_printf(p->out, "%s", p->rowSeparator);
  2886         -      }
  2887         -      setTextMode(p->out, 1);
  2888         -      break;
  2889         -    }
  2890         -    case MODE_Insert: {
  2891         -      if( azArg==0 ) break;
  2892         -      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]);
  2903         -          }
  2904         -        }
  2905         -        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 ){
  2913         -          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         -          }
  2918         -        }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]);
  2931         -        }else if( ShellHasFlag(p, SHFLG_Newlines) ){
  2932         -          output_quoted_string(p->out, azArg[i]);
  2933         -        }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 ){
  2943         -        for(i=0; i<nArg; i++){
  2944         -          if( i>0 ) raw_printf(p->out, ",");
  2945         -          output_quoted_string(p->out, azCol[i]);
  2946         -        }
  2947         -        raw_printf(p->out,"\n");
  2948         -      }
  2949         -      p->cnt++;
  2950         -      for(i=0; i<nArg; i++){
  2951         -        if( i>0 ) raw_printf(p->out, ",");
  2952         -        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  2953         -          utf8_printf(p->out,"NULL");
  2954         -        }else if( aiType && aiType[i]==SQLITE_TEXT ){
  2955         -          output_quoted_string(p->out, azArg[i]);
  2956         -        }else if( aiType && aiType[i]==SQLITE_INTEGER ){
  2957         -          utf8_printf(p->out,"%s", azArg[i]);
  2958         -        }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);
  2962         -          raw_printf(p->out, "%s", z);
  2963         -        }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);
  2966         -          output_hex_blob(p->out, pBlob, nBlob);
  2967         -        }else if( isNumber(azArg[i], 0) ){
  2968         -          utf8_printf(p->out,"%s", azArg[i]);
  2969         -        }else{
  2970         -          output_quoted_string(p->out, azArg[i]);
  2971         -        }
  2972         -      }
  2973         -      raw_printf(p->out,"\n");
  2974         -      break;
  2975         -    }
  2976         -    case MODE_Ascii: {
  2977         -      if( p->cnt++==0 && p->showHeader ){
  2978         -        for(i=0; i<nArg; i++){
  2979         -          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  2980         -          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  2981         -        }
  2982         -        utf8_printf(p->out, "%s", p->rowSeparator);
  2983         -      }
  2984         -      if( azArg==0 ) break;
  2985         -      for(i=0; i<nArg; i++){
  2986         -        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  2987         -        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  2988         -      }
  2989         -      utf8_printf(p->out, "%s", p->rowSeparator);
  2990         -      break;
  2991         -    }
  2992         -  }
  2993         -  return 0;
  2994         -}
  2995         -
  2996         -/*
  2997         -** This is the callback routine that the SQLite library
  2998         -** invokes for each row of a query result.
  2999         -*/
  3000         -static 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         -
  3005         -/*
  3006         -** This is the callback routine from sqlite3_exec() that appends all
  3007         -** output onto the end of a ShellText object.
  3008         -*/
  3009         -static int captureOutputCallback(void *pArg, int nArg, char **azArg, char **az){
  3010         -  ShellText *p = (ShellText*)pArg;
  3011         -  int i;
  3012         -  UNUSED_PARAMETER(az);
  3013         -  if( azArg==0 ) return 0;
  3014         -  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         -*/
  3025         -static void createSelftestTable(ShellState *p){
  3026         -  char *zErrMsg = 0;
  3027         -  sqlite3_exec(p->db,
  3028         -    "SAVEPOINT selftest_init;\n"
  3029         -    "CREATE TABLE IF NOT EXISTS selftest(\n"
  3030         -    "  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         -    ");"
  3035         -    "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"
  3046         -    "  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"
  3057         -    "INSERT INTO [_shell$self]\n"
  3058         -    "  VALUES('run','PRAGMA integrity_check','ok');\n"
  3059         -    "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);
  3068         -}
  3069         -
  3070         -
  3071         -/*
  3072         -** Set the destination table field of the ShellState structure to
  3073         -** the name of the table given.  Escape any quote characters in the
  3074         -** table name.
  3075         -*/
  3076         -static void set_table_name(ShellState *p, const char *zName){
  3077         -  int i, n;
  3078         -  char cQuote;
  3079         -  char *z;
  3080         -
  3081         -  if( p->zDestTable ){
  3082         -    free(p->zDestTable);
  3083         -    p->zDestTable = 0;
  3084         -  }
  3085         -  if( zName==0 ) return;
  3086         -  cQuote = quoteChar(zName);
  3087         -  n = strlen30(zName);
  3088         -  if( cQuote ) n += n+2;
  3089         -  z = p->zDestTable = malloc( n+1 );
  3090         -  if( z==0 ){
  3091         -    raw_printf(stderr,"Error: out of memory\n");
  3092         -    exit(1);
  3093         -  }
  3094         -  n = 0;
  3095         -  if( cQuote ) z[n++] = cQuote;
  3096         -  for(i=0; zName[i]; i++){
  3097         -    z[n++] = zName[i];
  3098         -    if( zName[i]==cQuote ) z[n++] = cQuote;
  3099         -  }
  3100         -  if( cQuote ) z[n++] = cQuote;
  3101         -  z[n] = 0;
  3102         -}
  3103         -
  3104         -
  3105         -/*
  3106         -** 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.
  3109         -**
  3110         -** If the number of columns is 1 and that column contains text "--"
  3111         -** then write the semicolon on a separate line.  That way, if a
  3112         -** "--" comment occurs at the end of the statement, the comment
  3113         -** won't consume the semicolon terminator.
  3114         -*/
  3115         -static int run_table_dump_query(
  3116         -  ShellState *p,           /* Query context */
  3117         -  const char *zSelect,     /* SELECT statement to extract content */
  3118         -  const char *zFirstRow    /* Print before first row, if not NULL */
  3119         -){
  3120         -  sqlite3_stmt *pSelect;
  3121         -  int rc;
  3122         -  int nResult;
  3123         -  int i;
  3124         -  const char *z;
  3125         -  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  3126         -  if( rc!=SQLITE_OK || !pSelect ){
  3127         -    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  3128         -                sqlite3_errmsg(p->db));
  3129         -    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  3130         -    return rc;
  3131         -  }
  3132         -  rc = sqlite3_step(pSelect);
  3133         -  nResult = sqlite3_column_count(pSelect);
  3134         -  while( rc==SQLITE_ROW ){
  3135         -    if( zFirstRow ){
  3136         -      utf8_printf(p->out, "%s", zFirstRow);
  3137         -      zFirstRow = 0;
  3138         -    }
  3139         -    z = (const char*)sqlite3_column_text(pSelect, 0);
  3140         -    utf8_printf(p->out, "%s", z);
  3141         -    for(i=1; i<nResult; i++){
  3142         -      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  3143         -    }
  3144         -    if( z==0 ) z = "";
  3145         -    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  3146         -    if( z[0] ){
  3147         -      raw_printf(p->out, "\n;\n");
  3148         -    }else{
  3149         -      raw_printf(p->out, ";\n");
  3150         -    }
  3151         -    rc = sqlite3_step(pSelect);
  3152         -  }
  3153         -  rc = sqlite3_finalize(pSelect);
  3154         -  if( rc!=SQLITE_OK ){
  3155         -    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  3156         -                sqlite3_errmsg(p->db));
  3157         -    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  3158         -  }
  3159         -  return rc;
  3160         -}
  3161         -
  3162         -/*
  3163         -** Allocate space and save off current error string.
  3164         -*/
  3165         -static char *save_err_msg(
  3166         -  sqlite3 *db            /* Database to query */
  3167         -){
  3168         -  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  3169         -  char *zErrMsg = sqlite3_malloc64(nErrMsg);
  3170         -  if( zErrMsg ){
  3171         -    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  3172         -  }
  3173         -  return zErrMsg;
  3174         -}
  3175         -
  3176         -#ifdef __linux__
  3177         -/*
  3178         -** Attempt to display I/O stats on Linux using /proc/PID/io
  3179         -*/
  3180         -static 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[] = {
  3191         -      { "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:"    },
  3198         -    };
  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 ){
  3203         -        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  3204         -        break;
  3205         -      }
  3206         -    }
  3207         -  }
  3208         -  fclose(in);
  3209         -}
  3210         -#endif
  3211         -
  3212         -/*
  3213         -** Display a single line of status using 64-bit values.
  3214         -*/
  3215         -static 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         -}
  3237         -
  3238         -/*
  3239         -** Display memory stats.
  3240         -*/
  3241         -static int display_stats(
  3242         -  sqlite3 *db,                /* Database to query */
  3243         -  ShellState *pArg,           /* Pointer to ShellState */
  3244         -  int bReset                  /* True to reset the stats */
  3245         -){
  3246         -  int iCur;
  3247         -  int iHiwtr;
  3248         -
  3249         -  if( pArg && pArg->out ){
  3250         -    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);
  3254         -    if( pArg->shellFlgs & SHFLG_Pagecache ){
  3255         -      displayStatLine(pArg, "Number of Pcache Pages Used:",
  3256         -         "%lld (max %lld) pages", SQLITE_STATUS_PAGECACHE_USED, bReset);
  3257         -    }
  3258         -    displayStatLine(pArg, "Number of Pcache Overflow Bytes:",
  3259         -       "%lld (max %lld) bytes", SQLITE_STATUS_PAGECACHE_OVERFLOW, bReset);
  3260         -    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);
  3264         -#ifdef YYTRACKMAXSTACKDEPTH
  3265         -    displayStatLine(pArg, "Deepest Parser Stack:",
  3266         -       "%lld (max %lld)", SQLITE_STATUS_PARSER_STACK, bReset);
  3267         -#endif
  3268         -  }
  3269         -
  3270         -  if( pArg && pArg->out && db ){
  3271         -    if( pArg->shellFlgs & SHFLG_Lookaside ){
  3272         -      iHiwtr = iCur = -1;
  3273         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  3274         -                        &iCur, &iHiwtr, bReset);
  3275         -      raw_printf(pArg->out,
  3276         -              "Lookaside Slots Used:                %d (max %d)\n",
  3277         -              iCur, iHiwtr);
  3278         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  3279         -                        &iCur, &iHiwtr, bReset);
  3280         -      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
  3281         -              iHiwtr);
  3282         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  3283         -                        &iCur, &iHiwtr, bReset);
  3284         -      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
  3285         -              iHiwtr);
  3286         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  3287         -                        &iCur, &iHiwtr, bReset);
  3288         -      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
  3289         -              iHiwtr);
  3290         -    }
  3291         -    iHiwtr = iCur = -1;
  3292         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  3293         -    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
  3294         -            iCur);
  3295         -    iHiwtr = iCur = -1;
  3296         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  3297         -    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
  3298         -    iHiwtr = iCur = -1;
  3299         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  3300         -    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
  3301         -    iHiwtr = iCur = -1;
  3302         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  3303         -    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
  3304         -    iHiwtr = iCur = -1;
  3305         -    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  3306         -    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
  3307         -            iCur);
  3308         -    iHiwtr = iCur = -1;
  3309         -    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  3310         -    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
  3311         -            iCur);
  3312         -  }
  3313         -
  3314         -  if( pArg && pArg->out && db && pArg->pStmt ){
  3315         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  3316         -                               bReset);
  3317         -    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
  3318         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  3319         -    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
  3320         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  3321         -    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
  3322         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  3323         -    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
  3324         -  }
  3325         -
  3326         -#ifdef __linux__
  3327         -  displayLinuxIoStats(pArg->out);
  3328         -#endif
  3329         -
  3330         -  /* Do not remove this machine readable comment: extra-stats-output-here */
  3331         -
  3332         -  return 0;
  3333         -}
  3334         -
  3335         -/*
  3336         -** Display scan stats.
  3337         -*/
  3338         -static void display_scanstats(
  3339         -  sqlite3 *db,                    /* Database to query */
  3340         -  ShellState *pArg                /* Pointer to ShellState */
  3341         -){
  3342         -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  3343         -  UNUSED_PARAMETER(db);
  3344         -  UNUSED_PARAMETER(pArg);
  3345         -#else
  3346         -  int i, k, n, mx;
  3347         -  raw_printf(pArg->out, "-------- scanstats --------\n");
  3348         -  mx = 0;
  3349         -  for(k=0; k<=mx; k++){
  3350         -    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);
  3361         -      if( iSid>mx ) mx = iSid;
  3362         -      if( iSid!=k ) continue;
  3363         -      if( n==0 ){
  3364         -        rEstLoop = (double)nLoop;
  3365         -        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  3366         -      }
  3367         -      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);
  3371         -      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  3372         -      rEstLoop *= rEst;
  3373         -      raw_printf(pArg->out,
  3374         -          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  3375         -          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  3376         -      );
  3377         -    }
  3378         -  }
  3379         -  raw_printf(pArg->out, "---------------------------\n");
  3380         -#endif
  3381         -}
  3382         -
  3383         -/*
  3384         -** 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         -*/
  3389         -static 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
  3399         -** and populate the ShellState.aiIndent[] array with the number of
  3400         -** spaces each opcode should be indented before it is output.
  3401         -**
  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         -**
  3408         -**     * For each "Goto", if the jump destination is earlier in the program
  3409         -**       and ends on one of:
  3410         -**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
  3411         -**       or if the P1 parameter is one instead of zero,
  3412         -**       then indent all opcodes between the earlier instruction
  3413         -**       and "Goto" by 2 spaces.
  3414         -*/
  3415         -static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  3416         -  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 */
  3420         -  int iOp;                        /* Index of operation in p->aiIndent[] */
  3421         -
  3422         -  const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  3423         -                           "NextIfOpen", "PrevIfOpen", 0 };
  3424         -  const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  3425         -                            "Rewind", 0 };
  3426         -  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.  */
  3430         -  if( sqlite3_column_count(pSql)!=8 ){
  3431         -    p->cMode = p->mode;
  3432         -    return;
  3433         -  }
  3434         -  zSql = sqlite3_sql(pSql);
  3435         -  if( zSql==0 ) return;
  3436         -  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  3437         -  if( sqlite3_strnicmp(z, "explain", 7) ){
  3438         -    p->cMode = p->mode;
  3439         -    return;
  3440         -  }
  3441         -
  3442         -  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  3443         -    int i;
  3444         -    int iAddr = sqlite3_column_int(pSql, 0);
  3445         -    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  3446         -
  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.  */
  3452         -    int p2 = sqlite3_column_int(pSql, 3);
  3453         -    int p2op = (p2 + (iOp-iAddr));
  3454         -
  3455         -    /* Grow the p->aiIndent array as required */
  3456         -    if( iOp>=nAlloc ){
  3457         -      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         -      }
  3471         -      nAlloc += 100;
  3472         -      p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int));
  3473         -      abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int));
  3474         -    }
  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) ){
  3480         -      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  3481         -    }
  3482         -    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  3483         -     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  3484         -    ){
  3485         -      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  3486         -    }
  3487         -  }
  3488         -
  3489         -  p->iIndent = 0;
  3490         -  sqlite3_free(abYield);
  3491         -  sqlite3_reset(pSql);
  3492         -}
  3493         -
  3494         -/*
  3495         -** Free the array allocated by explain_data_prepare().
  3496         -*/
  3497         -static void explain_data_delete(ShellState *p){
  3498         -  sqlite3_free(p->aiIndent);
  3499         -  p->aiIndent = 0;
  3500         -  p->nIndent = 0;
  3501         -  p->iIndent = 0;
  3502         -}
  3503         -
  3504         -/*
  3505         -** Disable and restore .wheretrace and .selecttrace settings.
  3506         -*/
  3507         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  3508         -extern int sqlite3SelectTrace;
  3509         -static int savedSelectTrace;
  3510         -#endif
  3511         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  3512         -extern int sqlite3WhereTrace;
  3513         -static int savedWhereTrace;
  3514         -#endif
  3515         -static 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         -}
  3525         -static 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         -*/
  3537         -static 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         -/*
  3603         -** Execute a statement or set of statements.  Print
  3604         -** any result rows/columns depending on the current mode
  3605         -** set via the supplied callback.
  3606         -**
  3607         -** This is very similar to SQLite's built-in sqlite3_exec()
  3608         -** function except it takes a slightly different callback
  3609         -** and callback data argument.
  3610         -*/
  3611         -static int shell_exec(
  3612         -  sqlite3 *db,                              /* An open database */
  3613         -  const char *zSql,                         /* SQL to be evaluated */
  3614         -  int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
  3615         -                                            /* (not the same as sqlite3_exec) */
  3616         -  ShellState *pArg,                         /* Pointer to ShellState */
  3617         -  char **pzErrMsg                           /* Error msg written here */
  3618         -){
  3619         -  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
  3620         -  int rc = SQLITE_OK;             /* Return Code */
  3621         -  int rc2;
  3622         -  const char *zLeftover;          /* Tail of unprocessed SQL */
  3623         -
  3624         -  if( pzErrMsg ){
  3625         -    *pzErrMsg = NULL;
  3626         -  }
  3627         -
  3628         -  while( zSql[0] && (SQLITE_OK == rc) ){
  3629         -    static const char *zStmtSql;
  3630         -    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  3631         -    if( SQLITE_OK != rc ){
  3632         -      if( pzErrMsg ){
  3633         -        *pzErrMsg = save_err_msg(db);
  3634         -      }
  3635         -    }else{
  3636         -      if( !pStmt ){
  3637         -        /* this happens for a comment or white-space */
  3638         -        zSql = zLeftover;
  3639         -        while( IsSpace(zSql[0]) ) zSql++;
  3640         -        continue;
  3641         -      }
  3642         -      zStmtSql = sqlite3_sql(pStmt);
  3643         -      if( zStmtSql==0 ) zStmtSql = "";
  3644         -      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  3645         -
  3646         -      /* save off the prepared statment handle and reset row count */
  3647         -      if( pArg ){
  3648         -        pArg->pStmt = pStmt;
  3649         -        pArg->cnt = 0;
  3650         -      }
  3651         -
  3652         -      /* echo the sql statement if echo on */
  3653         -      if( pArg && ShellHasFlag(pArg, SHFLG_Echo) ){
  3654         -        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  3655         -      }
  3656         -
  3657         -      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  3658         -      if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
  3659         -        sqlite3_stmt *pExplain;
  3660         -        char *zEQP;
  3661         -        disable_debug_trace_modes();
  3662         -        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  3663         -        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  3664         -        if( rc==SQLITE_OK ){
  3665         -          while( sqlite3_step(pExplain)==SQLITE_ROW ){
  3666         -            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));
  3669         -            utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
  3670         -          }
  3671         -        }
  3672         -        sqlite3_finalize(pExplain);
  3673         -        sqlite3_free(zEQP);
  3674         -        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();
  3688         -      }
  3689         -
  3690         -      if( pArg ){
  3691         -        pArg->cMode = pArg->mode;
  3692         -        if( pArg->autoExplain
  3693         -         && sqlite3_column_count(pStmt)==8
  3694         -         && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
  3695         -        ){
  3696         -          pArg->cMode = MODE_Explain;
  3697         -        }
  3698         -
  3699         -        /* 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         -        }
  3704         -      }
  3705         -
  3706         -      exec_prepared_stmt(pArg, pStmt, xCallback);
  3707         -      explain_data_delete(pArg);
  3708         -
  3709         -      /* print usage stats if stats on */
  3710         -      if( pArg && pArg->statsOn ){
  3711         -        display_stats(db, pArg, 0);
  3712         -      }
  3713         -
  3714         -      /* print loop-counters if required */
  3715         -      if( pArg && pArg->scanstatsOn ){
  3716         -        display_scanstats(db, pArg);
  3717         -      }
  3718         -
  3719         -      /* Finalize the statement just executed. If this fails, save a
  3720         -      ** copy of the error message. Otherwise, set zSql to point to the
  3721         -      ** next statement to execute. */
  3722         -      rc2 = sqlite3_finalize(pStmt);
  3723         -      if( rc!=SQLITE_NOMEM ) rc = rc2;
  3724         -      if( rc==SQLITE_OK ){
  3725         -        zSql = zLeftover;
  3726         -        while( IsSpace(zSql[0]) ) zSql++;
  3727         -      }else if( pzErrMsg ){
  3728         -        *pzErrMsg = save_err_msg(db);
  3729         -      }
  3730         -
  3731         -      /* clear saved stmt handle */
  3732         -      if( pArg ){
  3733         -        pArg->pStmt = NULL;
  3734         -      }
  3735         -    }
  3736         -  } /* end while */
  3737         -
  3738         -  return rc;
  3739         -}
  3740         -
  3741         -/*
  3742         -** Release memory previously allocated by tableColumnList().
  3743         -*/
  3744         -static 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         -*/
  3766         -static 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 */
  3774         -  int preserveRowid = ShellHasFlag(p, SHFLG_PreserveRowid);
  3775         -  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),
  3795         -                          "INTEGER")==0
  3796         -      ){
  3797         -        isIPK = 1;
  3798         -      }else{
  3799         -        isIPK = 0;
  3800         -      }
  3801         -    }
  3802         -  }
  3803         -  sqlite3_finalize(pStmt);
  3804         -  if( azCol==0 ) return 0;
  3805         -  azCol[0] = 0;
  3806         -  azCol[nCol+1] = 0;
  3807         -
  3808         -  /* The decision of whether or not a rowid really needs to be preserved
  3809         -  ** is tricky.  We never need to preserve a rowid for a WITHOUT ROWID table
  3810         -  ** or a table with an INTEGER PRIMARY KEY.  We are unable to preserve
  3811         -  ** rowids on tables where the rowid is inaccessible because there are other
  3812         -  ** columns in the table named "rowid", "_rowid_", and "oid".
  3813         -  */
  3814         -  if( preserveRowid && isIPK ){
  3815         -    /* If a single PRIMARY KEY column with type INTEGER was seen, then it
  3816         -    ** might be an alise for the ROWID.  But it might also be a WITHOUT ROWID
  3817         -    ** table or a INTEGER PRIMARY KEY DESC column, neither of which are
  3818         -    ** ROWID aliases.  To distinguish these cases, check to see if
  3819         -    ** there is a "pk" entry in "PRAGMA index_list".  There will be
  3820         -    ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID.
  3821         -    */
  3822         -    zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)"
  3823         -                           " WHERE origin='pk'", zTab);
  3824         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3825         -    sqlite3_free(zSql);
  3826         -    if( rc ){
  3827         -      freeColumnList(azCol);
  3828         -      return 0;
  3829         -    }
  3830         -    rc = sqlite3_step(pStmt);
  3831         -    sqlite3_finalize(pStmt);
  3832         -    preserveRowid = rc==SQLITE_ROW;
  3833         -  }
  3834         -  if( preserveRowid ){
  3835         -    /* Only preserve the rowid if we can find a name to use for the
  3836         -    ** rowid */
  3837         -    static char *azRowid[] = { "rowid", "_rowid_", "oid" };
  3838         -    int i, j;
  3839         -    for(j=0; j<3; j++){
  3840         -      for(i=1; i<=nCol; i++){
  3841         -        if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break;
  3842         -      }
  3843         -      if( i>nCol ){
  3844         -        /* At this point, we know that azRowid[j] is not the name of any
  3845         -        ** ordinary column in the table.  Verify that azRowid[j] is a valid
  3846         -        ** name for the rowid before adding it to azCol[0].  WITHOUT ROWID
  3847         -        ** tables will fail this last check */
  3848         -        rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0);
  3849         -        if( rc==SQLITE_OK ) azCol[0] = azRowid[j];
  3850         -        break;
  3851         -      }
  3852         -    }
  3853         -  }
  3854         -  return azCol;
  3855         -}
  3856         -
  3857         -/*
  3858         -** Toggle the reverse_unordered_selects setting.
  3859         -*/
  3860         -static void toggleSelectOrder(sqlite3 *db){
  3861         -  sqlite3_stmt *pStmt = 0;
  3862         -  int iSetting = 0;
  3863         -  char zStmt[100];
  3864         -  sqlite3_prepare_v2(db, "PRAGMA reverse_unordered_selects", -1, &pStmt, 0);
  3865         -  if( sqlite3_step(pStmt)==SQLITE_ROW ){
  3866         -    iSetting = sqlite3_column_int(pStmt, 0);
  3867         -  }
  3868         -  sqlite3_finalize(pStmt);
  3869         -  sqlite3_snprintf(sizeof(zStmt), zStmt,
  3870         -       "PRAGMA reverse_unordered_selects(%d)", !iSetting);
  3871         -  sqlite3_exec(db, zStmt, 0, 0, 0);
  3872         -}
  3873         -
  3874         -/*
  3875         -** This is a different callback routine used for dumping the database.
  3876         -** Each row received by this callback consists of a table name,
  3877         -** the table type ("index" or "table") and SQL to create the table.
  3878         -** This routine should print text sufficient to recreate the table.
  3879         -*/
  3880         -static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
  3881         -  int rc;
  3882         -  const char *zTable;
  3883         -  const char *zType;
  3884         -  const char *zSql;
  3885         -  ShellState *p = (ShellState *)pArg;
  3886         -
  3887         -  UNUSED_PARAMETER(azNotUsed);
  3888         -  if( nArg!=3 || azArg==0 ) return 0;
  3889         -  zTable = azArg[0];
  3890         -  zType = azArg[1];
  3891         -  zSql = azArg[2];
  3892         -
  3893         -  if( strcmp(zTable, "sqlite_sequence")==0 ){
  3894         -    raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
  3895         -  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  3896         -    raw_printf(p->out, "ANALYZE sqlite_master;\n");
  3897         -  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  3898         -    return 0;
  3899         -  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  3900         -    char *zIns;
  3901         -    if( !p->writableSchema ){
  3902         -      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  3903         -      p->writableSchema = 1;
  3904         -    }
  3905         -    zIns = sqlite3_mprintf(
  3906         -       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  3907         -       "VALUES('table','%q','%q',0,'%q');",
  3908         -       zTable, zTable, zSql);
  3909         -    utf8_printf(p->out, "%s\n", zIns);
  3910         -    sqlite3_free(zIns);
  3911         -    return 0;
  3912         -  }else{
  3913         -    printSchemaLine(p->out, zSql, ";\n");
  3914         -  }
  3915         -
  3916         -  if( strcmp(zType, "table")==0 ){
  3917         -    ShellText sSelect;
  3918         -    ShellText sTable;
  3919         -    char **azCol;
  3920         -    int i;
  3921         -    char *savedDestTable;
  3922         -    int savedMode;
  3923         -
  3924         -    azCol = tableColumnList(p, zTable);
  3925         -    if( azCol==0 ){
  3926         -      p->nErr++;
  3927         -      return 0;
  3928         -    }
  3929         -
  3930         -    /* Always quote the table name, even if it appears to be pure ascii,
  3931         -    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
  3932         -    initText(&sTable);
  3933         -    appendText(&sTable, zTable, quoteChar(zTable));
  3934         -    /* If preserving the rowid, add a column list after the table name.
  3935         -    ** In other words:  "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)"
  3936         -    ** instead of the usual "INSERT INTO tab VALUES(...)".
  3937         -    */
  3938         -    if( azCol[0] ){
  3939         -      appendText(&sTable, "(", 0);
  3940         -      appendText(&sTable, azCol[0], 0);
  3941         -      for(i=1; azCol[i]; i++){
  3942         -        appendText(&sTable, ",", 0);
  3943         -        appendText(&sTable, azCol[i], quoteChar(azCol[i]));
  3944         -      }
  3945         -      appendText(&sTable, ")", 0);
  3946         -    }
  3947         -
  3948         -    /* Build an appropriate SELECT statement */
  3949         -    initText(&sSelect);
  3950         -    appendText(&sSelect, "SELECT ", 0);
  3951         -    if( azCol[0] ){
  3952         -      appendText(&sSelect, azCol[0], 0);
  3953         -      appendText(&sSelect, ",", 0);
  3954         -    }
  3955         -    for(i=1; azCol[i]; i++){
  3956         -      appendText(&sSelect, azCol[i], quoteChar(azCol[i]));
  3957         -      if( azCol[i+1] ){
  3958         -        appendText(&sSelect, ",", 0);
  3959         -      }
  3960         -    }
  3961         -    freeColumnList(azCol);
  3962         -    appendText(&sSelect, " FROM ", 0);
  3963         -    appendText(&sSelect, zTable, quoteChar(zTable));
  3964         -
  3965         -    savedDestTable = p->zDestTable;
  3966         -    savedMode = p->mode;
  3967         -    p->zDestTable = sTable.z;
  3968         -    p->mode = p->cMode = MODE_Insert;
  3969         -    rc = shell_exec(p->db, sSelect.z, shell_callback, p, 0);
  3970         -    if( (rc&0xff)==SQLITE_CORRUPT ){
  3971         -      raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  3972         -      toggleSelectOrder(p->db);
  3973         -      shell_exec(p->db, sSelect.z, shell_callback, p, 0);
  3974         -      toggleSelectOrder(p->db);
  3975         -    }
  3976         -    p->zDestTable = savedDestTable;
  3977         -    p->mode = savedMode;
  3978         -    freeText(&sTable);
  3979         -    freeText(&sSelect);
  3980         -    if( rc ) p->nErr++;
  3981         -  }
  3982         -  return 0;
  3983         -}
  3984         -
  3985         -/*
  3986         -** Run zQuery.  Use dump_callback() as the callback routine so that
  3987         -** the contents of the query are output as SQL statements.
  3988         -**
  3989         -** If we get a SQLITE_CORRUPT error, rerun the query after appending
  3990         -** "ORDER BY rowid DESC" to the end.
  3991         -*/
  3992         -static int run_schema_dump_query(
  3993         -  ShellState *p,
  3994         -  const char *zQuery
  3995         -){
  3996         -  int rc;
  3997         -  char *zErr = 0;
  3998         -  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  3999         -  if( rc==SQLITE_CORRUPT ){
  4000         -    char *zQ2;
  4001         -    int len = strlen30(zQuery);
  4002         -    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  4003         -    if( zErr ){
  4004         -      utf8_printf(p->out, "/****** %s ******/\n", zErr);
  4005         -      sqlite3_free(zErr);
  4006         -      zErr = 0;
  4007         -    }
  4008         -    zQ2 = malloc( len+100 );
  4009         -    if( zQ2==0 ) return rc;
  4010         -    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  4011         -    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  4012         -    if( rc ){
  4013         -      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  4014         -    }else{
  4015         -      rc = SQLITE_CORRUPT;
  4016         -    }
  4017         -    sqlite3_free(zErr);
  4018         -    free(zQ2);
  4019         -  }
  4020         -  return rc;
  4021         -}
  4022         -
  4023         -/*
  4024         -** Text of a help message
  4025         -*/
  4026         -static char zHelp[] =
  4027         -#ifndef SQLITE_OMIT_AUTHORIZATION
  4028         -  ".auth ON|OFF           Show authorizer callbacks\n"
  4029         -#endif
  4030         -  ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
  4031         -  ".bail on|off           Stop after hitting an error.  Default OFF\n"
  4032         -  ".binary on|off         Turn binary output on or off.  Default OFF\n"
  4033         -  ".cd DIRECTORY          Change the working directory to DIRECTORY\n"
  4034         -  ".changes on|off        Show number of rows changed by SQL\n"
  4035         -  ".check GLOB            Fail if output since .testcase does not match\n"
  4036         -  ".clone NEWDB           Clone data into NEWDB from the existing database\n"
  4037         -  ".databases             List names and files of attached databases\n"
  4038         -  ".dbinfo ?DB?           Show status information about the database\n"
  4039         -  ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
  4040         -  "                         If TABLE specified, only dump tables matching\n"
  4041         -  "                         LIKE pattern TABLE.\n"
  4042         -  ".echo on|off           Turn command echo on or off\n"
  4043         -  ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
  4044         -  ".exit                  Exit this program\n"
  4045         -/* Because explain mode comes on automatically now, the ".explain" mode
  4046         -** is removed from the help screen.  It is still supported for legacy, however */
  4047         -/*".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"*/
  4048         -  ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
  4049         -  ".headers on|off        Turn display of headers on or off\n"
  4050         -  ".help                  Show this message\n"
  4051         -  ".import FILE TABLE     Import data from FILE into TABLE\n"
  4052         -#ifndef SQLITE_OMIT_TEST_CONTROL
  4053         -  ".imposter INDEX TABLE  Create imposter table TABLE on index INDEX\n"
  4054         -#endif
  4055         -  ".indexes ?TABLE?       Show names of all indexes\n"
  4056         -  "                         If TABLE specified, only show indexes for tables\n"
  4057         -  "                         matching LIKE pattern TABLE.\n"
  4058         -#ifdef SQLITE_ENABLE_IOTRACE
  4059         -  ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
  4060         -#endif
  4061         -  ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
  4062         -  ".lint OPTIONS          Report potential schema issues. Options:\n"
  4063         -  "                         fkey-indexes     Find missing foreign key indexes\n"
  4064         -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  4065         -  ".load FILE ?ENTRY?     Load an extension library\n"
  4066         -#endif
  4067         -  ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
  4068         -  ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
  4069         -  "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
  4070         -  "                         csv      Comma-separated values\n"
  4071         -  "                         column   Left-aligned columns.  (See .width)\n"
  4072         -  "                         html     HTML <table> code\n"
  4073         -  "                         insert   SQL insert statements for TABLE\n"
  4074         -  "                         line     One value per line\n"
  4075         -  "                         list     Values delimited by \"|\"\n"
  4076         -  "                         quote    Escape answers as for SQL\n"
  4077         -  "                         tabs     Tab-separated values\n"
  4078         -  "                         tcl      TCL list elements\n"
  4079         -  ".nullvalue STRING      Use STRING in place of NULL values\n"
  4080         -  ".once FILENAME         Output for the next SQL command only to FILENAME\n"
  4081         -  ".open ?OPTIONS? ?FILE? Close existing database and reopen FILE\n"
  4082         -  "                         The --new option starts with an empty file\n"
  4083         -  ".output ?FILENAME?     Send output to FILENAME or stdout\n"
  4084         -  ".print STRING...       Print literal STRING\n"
  4085         -  ".prompt MAIN CONTINUE  Replace the standard prompts\n"
  4086         -  ".quit                  Exit this program\n"
  4087         -  ".read FILENAME         Execute SQL in FILENAME\n"
  4088         -  ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
  4089         -  ".save FILE             Write in-memory database into FILE\n"
  4090         -  ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
  4091         -  ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
  4092         -  "                          Add --indent for pretty-printing\n"
  4093         -  ".selftest ?--init?     Run tests defined in the SELFTEST table\n"
  4094         -  ".separator COL ?ROW?   Change the column separator and optionally the row\n"
  4095         -  "                         separator for both the output mode and .import\n"
  4096         -#if defined(SQLITE_ENABLE_SESSION)
  4097         -  ".session CMD ...       Create or control sessions\n"
  4098         -#endif
  4099         -  ".sha3sum ?OPTIONS...?  Compute a SHA3 hash of database content\n"
  4100         -  ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
  4101         -  ".show                  Show the current values for various settings\n"
  4102         -  ".stats ?on|off?        Show stats or turn stats on or off\n"
  4103         -  ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
  4104         -  ".tables ?TABLE?        List names of tables\n"
  4105         -  "                         If TABLE specified, only list tables matching\n"
  4106         -  "                         LIKE pattern TABLE.\n"
  4107         -  ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
  4108         -  ".timeout MS            Try opening locked tables for MS milliseconds\n"
  4109         -  ".timer on|off          Turn SQL timer on or off\n"
  4110         -  ".trace FILE|off        Output each SQL statement as it is run\n"
  4111         -  ".vfsinfo ?AUX?         Information about the top-level VFS\n"
  4112         -  ".vfslist               List all available VFSes\n"
  4113         -  ".vfsname ?AUX?         Print the name of the VFS stack\n"
  4114         -  ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
  4115         -  "                         Negative values right-justify\n"
  4116         -;
  4117         -
  4118         -#if defined(SQLITE_ENABLE_SESSION)
  4119         -/*
  4120         -** Print help information for the ".sessions" command
  4121         -*/
  4122         -void session_help(ShellState *p){
  4123         -  raw_printf(p->out,
  4124         -    ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
  4125         -    "If ?NAME? is omitted, the first defined session is used.\n"
  4126         -    "Subcommands:\n"
  4127         -    "   attach TABLE             Attach TABLE\n"
  4128         -    "   changeset FILE           Write a changeset into FILE\n"
  4129         -    "   close                    Close one session\n"
  4130         -    "   enable ?BOOLEAN?         Set or query the enable bit\n"
  4131         -    "   filter GLOB...           Reject tables matching GLOBs\n"
  4132         -    "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
  4133         -    "   isempty                  Query whether the session is empty\n"
  4134         -    "   list                     List currently open session names\n"
  4135         -    "   open DB NAME             Open a new session on DB\n"
  4136         -    "   patchset FILE            Write a patchset into FILE\n"
  4137         -  );
  4138         -}
  4139         -#endif
  4140         -
  4141         -
  4142         -/* Forward reference */
  4143         -static int process_input(ShellState *p, FILE *in);
  4144         -
  4145         -/*
  4146         -** Read the content of file zName into memory obtained from sqlite3_malloc64()
  4147         -** and return a pointer to the buffer. The caller is responsible for freeing
  4148         -** the memory.
  4149         -**
  4150         -** If parameter pnByte is not NULL, (*pnByte) is set to the number of bytes
  4151         -** read.
  4152         -**
  4153         -** For convenience, a nul-terminator byte is always appended to the data read
  4154         -** from the file before the buffer is returned. This byte is not included in
  4155         -** the final value of (*pnByte), if applicable.
  4156         -**
  4157         -** NULL is returned if any error is encountered. The final value of *pnByte
  4158         -** is undefined in this case.
  4159         -*/
  4160         -static char *readFile(const char *zName, int *pnByte){
  4161         -  FILE *in = fopen(zName, "rb");
  4162         -  long nIn;
  4163         -  size_t nRead;
  4164         -  char *pBuf;
  4165         -  if( in==0 ) return 0;
  4166         -  fseek(in, 0, SEEK_END);
  4167         -  nIn = ftell(in);
  4168         -  rewind(in);
  4169         -  pBuf = sqlite3_malloc64( nIn+1 );
  4170         -  if( pBuf==0 ) return 0;
  4171         -  nRead = fread(pBuf, nIn, 1, in);
  4172         -  fclose(in);
  4173         -  if( nRead!=1 ){
  4174         -    sqlite3_free(pBuf);
  4175         -    return 0;
  4176         -  }
  4177         -  pBuf[nIn] = 0;
  4178         -  if( pnByte ) *pnByte = nIn;
  4179         -  return pBuf;
  4180         -}
  4181         -
  4182         -#if defined(SQLITE_ENABLE_SESSION)
  4183         -/*
  4184         -** Close a single OpenSession object and release all of its associated
  4185         -** resources.
  4186         -*/
  4187         -static void session_close(OpenSession *pSession){
  4188         -  int i;
  4189         -  sqlite3session_delete(pSession->p);
  4190         -  sqlite3_free(pSession->zName);
  4191         -  for(i=0; i<pSession->nFilter; i++){
  4192         -    sqlite3_free(pSession->azFilter[i]);
  4193         -  }
  4194         -  sqlite3_free(pSession->azFilter);
  4195         -  memset(pSession, 0, sizeof(OpenSession));
  4196         -}
  4197         -#endif
  4198         -
  4199         -/*
  4200         -** Close all OpenSession objects and release all associated resources.
  4201         -*/
  4202         -#if defined(SQLITE_ENABLE_SESSION)
  4203         -static void session_close_all(ShellState *p){
  4204         -  int i;
  4205         -  for(i=0; i<p->nSession; i++){
  4206         -    session_close(&p->aSession[i]);
  4207         -  }
  4208         -  p->nSession = 0;
  4209         -}
  4210         -#else
  4211         -# define session_close_all(X)
  4212         -#endif
  4213         -
  4214         -/*
  4215         -** Implementation of the xFilter function for an open session.  Omit
  4216         -** any tables named by ".session filter" but let all other table through.
  4217         -*/
  4218         -#if defined(SQLITE_ENABLE_SESSION)
  4219         -static int session_filter(void *pCtx, const char *zTab){
  4220         -  OpenSession *pSession = (OpenSession*)pCtx;
  4221         -  int i;
  4222         -  for(i=0; i<pSession->nFilter; i++){
  4223         -    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  4224         -  }
  4225         -  return 1;
  4226         -}
  4227         -#endif
  4228         -
  4229         -/*
  4230         -** Make sure the database is open.  If it is not, then open it.  If
  4231         -** the database fails to open, print an error message and exit.
  4232         -*/
  4233         -static void open_db(ShellState *p, int keepAlive){
  4234         -  if( p->db==0 ){
  4235         -    sqlite3_initialize();
  4236         -    sqlite3_open(p->zDbFilename, &p->db);
  4237         -    globalDb = p->db;
  4238         -    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  4239         -      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  4240         -          p->zDbFilename, sqlite3_errmsg(p->db));
  4241         -      if( keepAlive ) return;
  4242         -      exit(1);
  4243         -    }
  4244         -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  4245         -    sqlite3_enable_load_extension(p->db, 1);
  4246         -#endif
  4247         -    sqlite3_fileio_init(p->db, 0, 0);
  4248         -    sqlite3_shathree_init(p->db, 0, 0);
  4249         -    sqlite3_completion_init(p->db, 0, 0);
  4250         -    sqlite3_create_function(p->db, "shell_add_schema", 2, SQLITE_UTF8, 0,
  4251         -                            shellAddSchemaName, 0, 0);
  4252         -  }
  4253         -}
  4254         -
  4255         -#if HAVE_READLINE || HAVE_EDITLINE
  4256         -/*
  4257         -** Readline completion callbacks
  4258         -*/
  4259         -static char *readline_completion_generator(const char *text, int state){
  4260         -  static sqlite3_stmt *pStmt = 0;
  4261         -  char *zRet;
  4262         -  if( state==0 ){
  4263         -    char *zSql;
  4264         -    sqlite3_finalize(pStmt);
  4265         -    zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  4266         -                           "  FROM completion(%Q) ORDER BY 1", text);
  4267         -    sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  4268         -    sqlite3_free(zSql);
  4269         -  }
  4270         -  if( sqlite3_step(pStmt)==SQLITE_ROW ){
  4271         -    zRet = strdup((const char*)sqlite3_column_text(pStmt, 0));
  4272         -  }else{
  4273         -    sqlite3_finalize(pStmt);
  4274         -    pStmt = 0;
  4275         -    zRet = 0;
  4276         -  }
  4277         -  return zRet;
  4278         -}
  4279         -static char **readline_completion(const char *zText, int iStart, int iEnd){
  4280         -  rl_attempted_completion_over = 1;
  4281         -  return rl_completion_matches(zText, readline_completion_generator);
  4282         -}
  4283         -
  4284         -#elif HAVE_LINENOISE
  4285         -/*
  4286         -** Linenoise completion callback
  4287         -*/
  4288         -static void linenoise_completion(const char *zLine, linenoiseCompletions *lc){
  4289         -  int nLine = (int)strlen(zLine);
  4290         -  int i, iStart;
  4291         -  sqlite3_stmt *pStmt = 0;
  4292         -  char *zSql;
  4293         -  char zBuf[1000];
  4294         -
  4295         -  if( nLine>sizeof(zBuf)-30 ) return;
  4296         -  if( zLine[0]=='.' ) return;
  4297         -  for(i=nLine-1; i>=0 && (isalnum(zLine[i]) || zLine[i]=='_'); i--){}
  4298         -  if( i==nLine-1 ) return;
  4299         -  iStart = i+1;
  4300         -  memcpy(zBuf, zLine, iStart);
  4301         -  zSql = sqlite3_mprintf("SELECT DISTINCT candidate COLLATE nocase"
  4302         -                         "  FROM completion(%Q,%Q) ORDER BY 1",
  4303         -                         &zLine[iStart], zLine);
  4304         -  sqlite3_prepare_v2(globalDb, zSql, -1, &pStmt, 0);
  4305         -  sqlite3_free(zSql);
  4306         -  sqlite3_exec(globalDb, "PRAGMA page_count", 0, 0, 0); /* Load the schema */
  4307         -  while( sqlite3_step(pStmt)==SQLITE_ROW ){
  4308         -    const char *zCompletion = (const char*)sqlite3_column_text(pStmt, 0);
  4309         -    int nCompletion = sqlite3_column_bytes(pStmt, 0);
  4310         -    if( iStart+nCompletion < sizeof(zBuf)-1 ){
  4311         -      memcpy(zBuf+iStart, zCompletion, nCompletion+1);
  4312         -      linenoiseAddCompletion(lc, zBuf);
  4313         -    }
  4314         -  }
  4315         -  sqlite3_finalize(pStmt);
  4316         -}
  4317         -#endif
  4318         -
  4319         -/*
  4320         -** Do C-language style dequoting.
  4321         -**
  4322         -**    \a    -> alarm
  4323         -**    \b    -> backspace
  4324         -**    \t    -> tab
  4325         -**    \n    -> newline
  4326         -**    \v    -> vertical tab
  4327         -**    \f    -> form feed
  4328         -**    \r    -> carriage return
  4329         -**    \s    -> space
  4330         -**    \"    -> "
  4331         -**    \'    -> '
  4332         -**    \\    -> backslash
  4333         -**    \NNN  -> ascii character NNN in octal
  4334         -*/
  4335         -static void resolve_backslashes(char *z){
  4336         -  int i, j;
  4337         -  char c;
  4338         -  while( *z && *z!='\\' ) z++;
  4339         -  for(i=j=0; (c = z[i])!=0; i++, j++){
  4340         -    if( c=='\\' && z[i+1]!=0 ){
  4341         -      c = z[++i];
  4342         -      if( c=='a' ){
  4343         -        c = '\a';
  4344         -      }else if( c=='b' ){
  4345         -        c = '\b';
  4346         -      }else if( c=='t' ){
  4347         -        c = '\t';
  4348         -      }else if( c=='n' ){
  4349         -        c = '\n';
  4350         -      }else if( c=='v' ){
  4351         -        c = '\v';
  4352         -      }else if( c=='f' ){
  4353         -        c = '\f';
  4354         -      }else if( c=='r' ){
  4355         -        c = '\r';
  4356         -      }else if( c=='"' ){
  4357         -        c = '"';
  4358         -      }else if( c=='\'' ){
  4359         -        c = '\'';
  4360         -      }else if( c=='\\' ){
  4361         -        c = '\\';
  4362         -      }else if( c>='0' && c<='7' ){
  4363         -        c -= '0';
  4364         -        if( z[i+1]>='0' && z[i+1]<='7' ){
  4365         -          i++;
  4366         -          c = (c<<3) + z[i] - '0';
  4367         -          if( z[i+1]>='0' && z[i+1]<='7' ){
  4368         -            i++;
  4369         -            c = (c<<3) + z[i] - '0';
  4370         -          }
  4371         -        }
  4372         -      }
  4373         -    }
  4374         -    z[j] = c;
  4375         -  }
  4376         -  if( j<i ) z[j] = 0;
  4377         -}
  4378         -
  4379         -/*
  4380         -** Return the value of a hexadecimal digit.  Return -1 if the input
  4381         -** is not a hex digit.
  4382         -*/
  4383         -static int hexDigitValue(char c){
  4384         -  if( c>='0' && c<='9' ) return c - '0';
  4385         -  if( c>='a' && c<='f' ) return c - 'a' + 10;
  4386         -  if( c>='A' && c<='F' ) return c - 'A' + 10;
  4387         -  return -1;
  4388         -}
  4389         -
  4390         -/*
  4391         -** Interpret zArg as an integer value, possibly with suffixes.
  4392         -*/
  4393         -static sqlite3_int64 integerValue(const char *zArg){
  4394         -  sqlite3_int64 v = 0;
  4395         -  static const struct { char *zSuffix; int iMult; } aMult[] = {
  4396         -    { "KiB", 1024 },
  4397         -    { "MiB", 1024*1024 },
  4398         -    { "GiB", 1024*1024*1024 },
  4399         -    { "KB",  1000 },
  4400         -    { "MB",  1000000 },
  4401         -    { "GB",  1000000000 },
  4402         -    { "K",   1000 },
  4403         -    { "M",   1000000 },
  4404         -    { "G",   1000000000 },
  4405         -  };
  4406         -  int i;
  4407         -  int isNeg = 0;
  4408         -  if( zArg[0]=='-' ){
  4409         -    isNeg = 1;
  4410         -    zArg++;
  4411         -  }else if( zArg[0]=='+' ){
  4412         -    zArg++;
  4413         -  }
  4414         -  if( zArg[0]=='0' && zArg[1]=='x' ){
  4415         -    int x;
  4416         -    zArg += 2;
  4417         -    while( (x = hexDigitValue(zArg[0]))>=0 ){
  4418         -      v = (v<<4) + x;
  4419         -      zArg++;
  4420         -    }
  4421         -  }else{
  4422         -    while( IsDigit(zArg[0]) ){
  4423         -      v = v*10 + zArg[0] - '0';
  4424         -      zArg++;
  4425         -    }
  4426         -  }
  4427         -  for(i=0; i<ArraySize(aMult); i++){
  4428         -    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  4429         -      v *= aMult[i].iMult;
  4430         -      break;
  4431         -    }
  4432         -  }
  4433         -  return isNeg? -v : v;
  4434         -}
  4435         -
  4436         -/*
  4437         -** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
  4438         -** for TRUE and FALSE.  Return the integer value if appropriate.
  4439         -*/
  4440         -static int booleanValue(const char *zArg){
  4441         -  int i;
  4442         -  if( zArg[0]=='0' && zArg[1]=='x' ){
  4443         -    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  4444         -  }else{
  4445         -    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  4446         -  }
  4447         -  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  4448         -  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  4449         -    return 1;
  4450         -  }
  4451         -  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  4452         -    return 0;
  4453         -  }
  4454         -  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  4455         -          zArg);
  4456         -  return 0;
  4457         -}
  4458         -
  4459         -/*
  4460         -** Set or clear a shell flag according to a boolean value.
  4461         -*/
  4462         -static void setOrClearFlag(ShellState *p, unsigned mFlag, const char *zArg){
  4463         -  if( booleanValue(zArg) ){
  4464         -    ShellSetFlag(p, mFlag);
  4465         -  }else{
  4466         -    ShellClearFlag(p, mFlag);
  4467         -  }
  4468         -}
  4469         -
  4470         -/*
  4471         -** Close an output file, assuming it is not stderr or stdout
  4472         -*/
  4473         -static void output_file_close(FILE *f){
  4474         -  if( f && f!=stdout && f!=stderr ) fclose(f);
  4475         -}
  4476         -
  4477         -/*
  4478         -** Try to open an output file.   The names "stdout" and "stderr" are
  4479         -** recognized and do the right thing.  NULL is returned if the output
  4480         -** filename is "off".
  4481         -*/
  4482         -static FILE *output_file_open(const char *zFile){
  4483         -  FILE *f;
  4484         -  if( strcmp(zFile,"stdout")==0 ){
  4485         -    f = stdout;
  4486         -  }else if( strcmp(zFile, "stderr")==0 ){
  4487         -    f = stderr;
  4488         -  }else if( strcmp(zFile, "off")==0 ){
  4489         -    f = 0;
  4490         -  }else{
  4491         -    f = fopen(zFile, "wb");
  4492         -    if( f==0 ){
  4493         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  4494         -    }
  4495         -  }
  4496         -  return f;
  4497         -}
  4498         -
  4499         -#if !defined(SQLITE_UNTESTABLE)
  4500         -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  4501         -/*
  4502         -** A routine for handling output from sqlite3_trace().
  4503         -*/
  4504         -static int sql_trace_callback(
  4505         -  unsigned mType,
  4506         -  void *pArg,
  4507         -  void *pP,
  4508         -  void *pX
  4509         -){
  4510         -  FILE *f = (FILE*)pArg;
  4511         -  UNUSED_PARAMETER(mType);
  4512         -  UNUSED_PARAMETER(pP);
  4513         -  if( f ){
  4514         -    const char *z = (const char*)pX;
  4515         -    int i = (int)strlen(z);
  4516         -    while( i>0 && z[i-1]==';' ){ i--; }
  4517         -    utf8_printf(f, "%.*s;\n", i, z);
  4518         -  }
  4519         -  return 0;
  4520         -}
  4521         -#endif
  4522         -#endif
  4523         -
  4524         -/*
  4525         -** A no-op routine that runs with the ".breakpoint" doc-command.  This is
  4526         -** a useful spot to set a debugger breakpoint.
  4527         -*/
  4528         -static void test_breakpoint(void){
  4529         -  static int nCall = 0;
  4530         -  nCall++;
  4531         -}
  4532         -
  4533         -/*
  4534         -** An object used to read a CSV and other files for import.
  4535         -*/
  4536         -typedef struct ImportCtx ImportCtx;
  4537         -struct ImportCtx {
  4538         -  const char *zFile;  /* Name of the input file */
  4539         -  FILE *in;           /* Read the CSV text from this input stream */
  4540         -  char *z;            /* Accumulated text for a field */
  4541         -  int n;              /* Number of bytes in z */
  4542         -  int nAlloc;         /* Space allocated for z[] */
  4543         -  int nLine;          /* Current line number */
  4544         -  int bNotFirst;      /* True if one or more bytes already read */
  4545         -  int cTerm;          /* Character that terminated the most recent field */
  4546         -  int cColSep;        /* The column separator character.  (Usually ",") */
  4547         -  int cRowSep;        /* The row separator character.  (Usually "\n") */
  4548         -};
  4549         -
  4550         -/* Append a single byte to z[] */
  4551         -static void import_append_char(ImportCtx *p, int c){
  4552         -  if( p->n+1>=p->nAlloc ){
  4553         -    p->nAlloc += p->nAlloc + 100;
  4554         -    p->z = sqlite3_realloc64(p->z, p->nAlloc);
  4555         -    if( p->z==0 ){
  4556         -      raw_printf(stderr, "out of memory\n");
  4557         -      exit(1);
  4558         -    }
  4559         -  }
  4560         -  p->z[p->n++] = (char)c;
  4561         -}
  4562         -
  4563         -/* Read a single field of CSV text.  Compatible with rfc4180 and extended
  4564         -** with the option of having a separator other than ",".
  4565         -**
  4566         -**   +  Input comes from p->in.
  4567         -**   +  Store results in p->z of length p->n.  Space to hold p->z comes
  4568         -**      from sqlite3_malloc64().
  4569         -**   +  Use p->cSep as the column separator.  The default is ",".
  4570         -**   +  Use p->rSep as the row separator.  The default is "\n".
  4571         -**   +  Keep track of the line number in p->nLine.
  4572         -**   +  Store the character that terminates the field in p->cTerm.  Store
  4573         -**      EOF on end-of-file.
  4574         -**   +  Report syntax errors on stderr
  4575         -*/
  4576         -static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  4577         -  int c;
  4578         -  int cSep = p->cColSep;
  4579         -  int rSep = p->cRowSep;
  4580         -  p->n = 0;
  4581         -  c = fgetc(p->in);
  4582         -  if( c==EOF || seenInterrupt ){
  4583         -    p->cTerm = EOF;
  4584         -    return 0;
  4585         -  }
  4586         -  if( c=='"' ){
  4587         -    int pc, ppc;
  4588         -    int startLine = p->nLine;
  4589         -    int cQuote = c;
  4590         -    pc = ppc = 0;
  4591         -    while( 1 ){
  4592         -      c = fgetc(p->in);
  4593         -      if( c==rSep ) p->nLine++;
  4594         -      if( c==cQuote ){
  4595         -        if( pc==cQuote ){
  4596         -          pc = 0;
  4597         -          continue;
  4598         -        }
  4599         -      }
  4600         -      if( (c==cSep && pc==cQuote)
  4601         -       || (c==rSep && pc==cQuote)
  4602         -       || (c==rSep && pc=='\r' && ppc==cQuote)
  4603         -       || (c==EOF && pc==cQuote)
  4604         -      ){
  4605         -        do{ p->n--; }while( p->z[p->n]!=cQuote );
  4606         -        p->cTerm = c;
  4607         -        break;
  4608         -      }
  4609         -      if( pc==cQuote && c!='\r' ){
  4610         -        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  4611         -                p->zFile, p->nLine, cQuote);
  4612         -      }
  4613         -      if( c==EOF ){
  4614         -        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  4615         -                p->zFile, startLine, cQuote);
  4616         -        p->cTerm = c;
  4617         -        break;
  4618         -      }
  4619         -      import_append_char(p, c);
  4620         -      ppc = pc;
  4621         -      pc = c;
  4622         -    }
  4623         -  }else{
  4624         -    /* If this is the first field being parsed and it begins with the
  4625         -    ** UTF-8 BOM  (0xEF BB BF) then skip the BOM */
  4626         -    if( (c&0xff)==0xef && p->bNotFirst==0 ){
  4627         -      import_append_char(p, c);
  4628         -      c = fgetc(p->in);
  4629         -      if( (c&0xff)==0xbb ){
  4630         -        import_append_char(p, c);
  4631         -        c = fgetc(p->in);
  4632         -        if( (c&0xff)==0xbf ){
  4633         -          p->bNotFirst = 1;
  4634         -          p->n = 0;
  4635         -          return csv_read_one_field(p);
  4636         -        }
  4637         -      }
  4638         -    }
  4639         -    while( c!=EOF && c!=cSep && c!=rSep ){
  4640         -      import_append_char(p, c);
  4641         -      c = fgetc(p->in);
  4642         -    }
  4643         -    if( c==rSep ){
  4644         -      p->nLine++;
  4645         -      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  4646         -    }
  4647         -    p->cTerm = c;
  4648         -  }
  4649         -  if( p->z ) p->z[p->n] = 0;
  4650         -  p->bNotFirst = 1;
  4651         -  return p->z;
  4652         -}
  4653         -
  4654         -/* Read a single field of ASCII delimited text.
  4655         -**
  4656         -**   +  Input comes from p->in.
  4657         -**   +  Store results in p->z of length p->n.  Space to hold p->z comes
  4658         -**      from sqlite3_malloc64().
  4659         -**   +  Use p->cSep as the column separator.  The default is "\x1F".
  4660         -**   +  Use p->rSep as the row separator.  The default is "\x1E".
  4661         -**   +  Keep track of the row number in p->nLine.
  4662         -**   +  Store the character that terminates the field in p->cTerm.  Store
  4663         -**      EOF on end-of-file.
  4664         -**   +  Report syntax errors on stderr
  4665         -*/
  4666         -static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  4667         -  int c;
  4668         -  int cSep = p->cColSep;
  4669         -  int rSep = p->cRowSep;
  4670         -  p->n = 0;
  4671         -  c = fgetc(p->in);
  4672         -  if( c==EOF || seenInterrupt ){
  4673         -    p->cTerm = EOF;
  4674         -    return 0;
  4675         -  }
  4676         -  while( c!=EOF && c!=cSep && c!=rSep ){
  4677         -    import_append_char(p, c);
  4678         -    c = fgetc(p->in);
  4679         -  }
  4680         -  if( c==rSep ){
  4681         -    p->nLine++;
  4682         -  }
  4683         -  p->cTerm = c;
  4684         -  if( p->z ) p->z[p->n] = 0;
  4685         -  return p->z;
  4686         -}
  4687         -
  4688         -/*
  4689         -** Try to transfer data for table zTable.  If an error is seen while
  4690         -** moving forward, try to go backwards.  The backwards movement won't
  4691         -** work for WITHOUT ROWID tables.
  4692         -*/
  4693         -static void tryToCloneData(
  4694         -  ShellState *p,
  4695         -  sqlite3 *newDb,
  4696         -  const char *zTable
  4697         -){
  4698         -  sqlite3_stmt *pQuery = 0;
  4699         -  sqlite3_stmt *pInsert = 0;
  4700         -  char *zQuery = 0;
  4701         -  char *zInsert = 0;
  4702         -  int rc;
  4703         -  int i, j, n;
  4704         -  int nTable = (int)strlen(zTable);
  4705         -  int k = 0;
  4706         -  int cnt = 0;
  4707         -  const int spinRate = 10000;
  4708         -
  4709         -  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  4710         -  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4711         -  if( rc ){
  4712         -    utf8_printf(stderr, "Error %d: %s on [%s]\n",
  4713         -            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  4714         -            zQuery);
  4715         -    goto end_data_xfer;
  4716         -  }
  4717         -  n = sqlite3_column_count(pQuery);
  4718         -  zInsert = sqlite3_malloc64(200 + nTable + n*3);
  4719         -  if( zInsert==0 ){
  4720         -    raw_printf(stderr, "out of memory\n");
  4721         -    goto end_data_xfer;
  4722         -  }
  4723         -  sqlite3_snprintf(200+nTable,zInsert,
  4724         -                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  4725         -  i = (int)strlen(zInsert);
  4726         -  for(j=1; j<n; j++){
  4727         -    memcpy(zInsert+i, ",?", 2);
  4728         -    i += 2;
  4729         -  }
  4730         -  memcpy(zInsert+i, ");", 3);
  4731         -  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  4732         -  if( rc ){
  4733         -    utf8_printf(stderr, "Error %d: %s on [%s]\n",
  4734         -            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  4735         -            zQuery);
  4736         -    goto end_data_xfer;
  4737         -  }
  4738         -  for(k=0; k<2; k++){
  4739         -    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  4740         -      for(i=0; i<n; i++){
  4741         -        switch( sqlite3_column_type(pQuery, i) ){
  4742         -          case SQLITE_NULL: {
  4743         -            sqlite3_bind_null(pInsert, i+1);
  4744         -            break;
  4745         -          }
  4746         -          case SQLITE_INTEGER: {
  4747         -            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  4748         -            break;
  4749         -          }
  4750         -          case SQLITE_FLOAT: {
  4751         -            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  4752         -            break;
  4753         -          }
  4754         -          case SQLITE_TEXT: {
  4755         -            sqlite3_bind_text(pInsert, i+1,
  4756         -                             (const char*)sqlite3_column_text(pQuery,i),
  4757         -                             -1, SQLITE_STATIC);
  4758         -            break;
  4759         -          }
  4760         -          case SQLITE_BLOB: {
  4761         -            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  4762         -                                            sqlite3_column_bytes(pQuery,i),
  4763         -                                            SQLITE_STATIC);
  4764         -            break;
  4765         -          }
  4766         -        }
  4767         -      } /* End for */
  4768         -      rc = sqlite3_step(pInsert);
  4769         -      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  4770         -        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  4771         -                        sqlite3_errmsg(newDb));
  4772         -      }
  4773         -      sqlite3_reset(pInsert);
  4774         -      cnt++;
  4775         -      if( (cnt%spinRate)==0 ){
  4776         -        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  4777         -        fflush(stdout);
  4778         -      }
  4779         -    } /* End while */
  4780         -    if( rc==SQLITE_DONE ) break;
  4781         -    sqlite3_finalize(pQuery);
  4782         -    sqlite3_free(zQuery);
  4783         -    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  4784         -                             zTable);
  4785         -    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4786         -    if( rc ){
  4787         -      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  4788         -      break;
  4789         -    }
  4790         -  } /* End for(k=0...) */
  4791         -
  4792         -end_data_xfer:
  4793         -  sqlite3_finalize(pQuery);
  4794         -  sqlite3_finalize(pInsert);
  4795         -  sqlite3_free(zQuery);
  4796         -  sqlite3_free(zInsert);
  4797         -}
  4798         -
  4799         -
  4800         -/*
  4801         -** Try to transfer all rows of the schema that match zWhere.  For
  4802         -** each row, invoke xForEach() on the object defined by that row.
  4803         -** If an error is encountered while moving forward through the
  4804         -** sqlite_master table, try again moving backwards.
  4805         -*/
  4806         -static void tryToCloneSchema(
  4807         -  ShellState *p,
  4808         -  sqlite3 *newDb,
  4809         -  const char *zWhere,
  4810         -  void (*xForEach)(ShellState*,sqlite3*,const char*)
  4811         -){
  4812         -  sqlite3_stmt *pQuery = 0;
  4813         -  char *zQuery = 0;
  4814         -  int rc;
  4815         -  const unsigned char *zName;
  4816         -  const unsigned char *zSql;
  4817         -  char *zErrMsg = 0;
  4818         -
  4819         -  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  4820         -                           " WHERE %s", zWhere);
  4821         -  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4822         -  if( rc ){
  4823         -    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  4824         -                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  4825         -                    zQuery);
  4826         -    goto end_schema_xfer;
  4827         -  }
  4828         -  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  4829         -    zName = sqlite3_column_text(pQuery, 0);
  4830         -    zSql = sqlite3_column_text(pQuery, 1);
  4831         -    printf("%s... ", zName); fflush(stdout);
  4832         -    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  4833         -    if( zErrMsg ){
  4834         -      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  4835         -      sqlite3_free(zErrMsg);
  4836         -      zErrMsg = 0;
  4837         -    }
  4838         -    if( xForEach ){
  4839         -      xForEach(p, newDb, (const char*)zName);
  4840         -    }
  4841         -    printf("done\n");
  4842         -  }
  4843         -  if( rc!=SQLITE_DONE ){
  4844         -    sqlite3_finalize(pQuery);
  4845         -    sqlite3_free(zQuery);
  4846         -    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  4847         -                             " WHERE %s ORDER BY rowid DESC", zWhere);
  4848         -    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  4849         -    if( rc ){
  4850         -      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  4851         -                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  4852         -                      zQuery);
  4853         -      goto end_schema_xfer;
  4854         -    }
  4855         -    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  4856         -      zName = sqlite3_column_text(pQuery, 0);
  4857         -      zSql = sqlite3_column_text(pQuery, 1);
  4858         -      printf("%s... ", zName); fflush(stdout);
  4859         -      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  4860         -      if( zErrMsg ){
  4861         -        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  4862         -        sqlite3_free(zErrMsg);
  4863         -        zErrMsg = 0;
  4864         -      }
  4865         -      if( xForEach ){
  4866         -        xForEach(p, newDb, (const char*)zName);
  4867         -      }
  4868         -      printf("done\n");
  4869         -    }
  4870         -  }
  4871         -end_schema_xfer:
  4872         -  sqlite3_finalize(pQuery);
  4873         -  sqlite3_free(zQuery);
  4874         -}
  4875         -
  4876         -/*
  4877         -** Open a new database file named "zNewDb".  Try to recover as much information
  4878         -** as possible out of the main database (which might be corrupt) and write it
  4879         -** into zNewDb.
  4880         -*/
  4881         -static void tryToClone(ShellState *p, const char *zNewDb){
  4882         -  int rc;
  4883         -  sqlite3 *newDb = 0;
  4884         -  if( access(zNewDb,0)==0 ){
  4885         -    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  4886         -    return;
  4887         -  }
  4888         -  rc = sqlite3_open(zNewDb, &newDb);
  4889         -  if( rc ){
  4890         -    utf8_printf(stderr, "Cannot create output database: %s\n",
  4891         -            sqlite3_errmsg(newDb));
  4892         -  }else{
  4893         -    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  4894         -    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  4895         -    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  4896         -    tryToCloneSchema(p, newDb, "type!='table'", 0);
  4897         -    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  4898         -    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  4899         -  }
  4900         -  sqlite3_close(newDb);
  4901         -}
  4902         -
  4903         -/*
  4904         -** Change the output file back to stdout
  4905         -*/
  4906         -static void output_reset(ShellState *p){
  4907         -  if( p->outfile[0]=='|' ){
  4908         -#ifndef SQLITE_OMIT_POPEN
  4909         -    pclose(p->out);
  4910         -#endif
  4911         -  }else{
  4912         -    output_file_close(p->out);
  4913         -  }
  4914         -  p->outfile[0] = 0;
  4915         -  p->out = stdout;
  4916         -}
  4917         -
  4918         -/*
  4919         -** Run an SQL command and return the single integer result.
  4920         -*/
  4921         -static int db_int(ShellState *p, const char *zSql){
  4922         -  sqlite3_stmt *pStmt;
  4923         -  int res = 0;
  4924         -  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  4925         -  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  4926         -    res = sqlite3_column_int(pStmt,0);
  4927         -  }
  4928         -  sqlite3_finalize(pStmt);
  4929         -  return res;
  4930         -}
  4931         -
  4932         -/*
  4933         -** Convert a 2-byte or 4-byte big-endian integer into a native integer
  4934         -*/
  4935         -static unsigned int get2byteInt(unsigned char *a){
  4936         -  return (a[0]<<8) + a[1];
  4937         -}
  4938         -static unsigned int get4byteInt(unsigned char *a){
  4939         -  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  4940         -}
  4941         -
  4942         -/*
  4943         -** Implementation of the ".info" command.
  4944         -**
  4945         -** Return 1 on error, 2 to exit, and 0 otherwise.
  4946         -*/
  4947         -static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  4948         -  static const struct { const char *zName; int ofst; } aField[] = {
  4949         -     { "file change counter:",  24  },
  4950         -     { "database page count:",  28  },
  4951         -     { "freelist page count:",  36  },
  4952         -     { "schema cookie:",        40  },
  4953         -     { "schema format:",        44  },
  4954         -     { "default cache size:",   48  },
  4955         -     { "autovacuum top root:",  52  },
  4956         -     { "incremental vacuum:",   64  },
  4957         -     { "text encoding:",        56  },
  4958         -     { "user version:",         60  },
  4959         -     { "application id:",       68  },
  4960         -     { "software version:",     96  },
  4961         -  };
  4962         -  static const struct { const char *zName; const char *zSql; } aQuery[] = {
  4963         -     { "number of tables:",
  4964         -       "SELECT count(*) FROM %s WHERE type='table'" },
  4965         -     { "number of indexes:",
  4966         -       "SELECT count(*) FROM %s WHERE type='index'" },
  4967         -     { "number of triggers:",
  4968         -       "SELECT count(*) FROM %s WHERE type='trigger'" },
  4969         -     { "number of views:",
  4970         -       "SELECT count(*) FROM %s WHERE type='view'" },
  4971         -     { "schema size:",
  4972         -       "SELECT total(length(sql)) FROM %s" },
  4973         -  };
  4974         -  sqlite3_file *pFile = 0;
  4975         -  int i;
  4976         -  char *zSchemaTab;
  4977         -  char *zDb = nArg>=2 ? azArg[1] : "main";
  4978         -  unsigned char aHdr[100];
  4979         -  open_db(p, 0);
  4980         -  if( p->db==0 ) return 1;
  4981         -  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
  4982         -  if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
  4983         -    return 1;
  4984         -  }
  4985         -  i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
  4986         -  if( i!=SQLITE_OK ){
  4987         -    raw_printf(stderr, "unable to read database header\n");
  4988         -    return 1;
  4989         -  }
  4990         -  i = get2byteInt(aHdr+16);
  4991         -  if( i==1 ) i = 65536;
  4992         -  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  4993         -  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  4994         -  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  4995         -  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  4996         -  for(i=0; i<ArraySize(aField); i++){
  4997         -    int ofst = aField[i].ofst;
  4998         -    unsigned int val = get4byteInt(aHdr + ofst);
  4999         -    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  5000         -    switch( ofst ){
  5001         -      case 56: {
  5002         -        if( val==1 ) raw_printf(p->out, " (utf8)");
  5003         -        if( val==2 ) raw_printf(p->out, " (utf16le)");
  5004         -        if( val==3 ) raw_printf(p->out, " (utf16be)");
  5005         -      }
  5006         -    }
  5007         -    raw_printf(p->out, "\n");
  5008         -  }
  5009         -  if( zDb==0 ){
  5010         -    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  5011         -  }else if( strcmp(zDb,"temp")==0 ){
  5012         -    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  5013         -  }else{
  5014         -    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  5015         -  }
  5016         -  for(i=0; i<ArraySize(aQuery); i++){
  5017         -    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  5018         -    int val = db_int(p, zSql);
  5019         -    sqlite3_free(zSql);
  5020         -    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  5021         -  }
  5022         -  sqlite3_free(zSchemaTab);
  5023         -  return 0;
  5024         -}
  5025         -
  5026         -/*
  5027         -** Print the current sqlite3_errmsg() value to stderr and return 1.
  5028         -*/
  5029         -static int shellDatabaseError(sqlite3 *db){
  5030         -  const char *zErr = sqlite3_errmsg(db);
  5031         -  utf8_printf(stderr, "Error: %s\n", zErr);
  5032         -  return 1;
  5033         -}
  5034         -
  5035         -/*
  5036         -** Print an out-of-memory message to stderr and return 1.
  5037         -*/
  5038         -static int shellNomemError(void){
  5039         -  raw_printf(stderr, "Error: out of memory\n");
  5040         -  return 1;
  5041         -}
  5042         -
  5043         -/*
  5044         -** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
  5045         -** if they match and FALSE (0) if they do not match.
  5046         -**
  5047         -** Globbing rules:
  5048         -**
  5049         -**      '*'       Matches any sequence of zero or more characters.
  5050         -**
  5051         -**      '?'       Matches exactly one character.
  5052         -**
  5053         -**     [...]      Matches one character from the enclosed list of
  5054         -**                characters.
  5055         -**
  5056         -**     [^...]     Matches one character not in the enclosed list.
  5057         -**
  5058         -**      '#'       Matches any sequence of one or more digits with an
  5059         -**                optional + or - sign in front
  5060         -**
  5061         -**      ' '       Any span of whitespace matches any other span of
  5062         -**                whitespace.
  5063         -**
  5064         -** Extra whitespace at the end of z[] is ignored.
  5065         -*/
  5066         -static int testcase_glob(const char *zGlob, const char *z){
  5067         -  int c, c2;
  5068         -  int invert;
  5069         -  int seen;
  5070         -
  5071         -  while( (c = (*(zGlob++)))!=0 ){
  5072         -    if( IsSpace(c) ){
  5073         -      if( !IsSpace(*z) ) return 0;
  5074         -      while( IsSpace(*zGlob) ) zGlob++;
  5075         -      while( IsSpace(*z) ) z++;
  5076         -    }else if( c=='*' ){
  5077         -      while( (c=(*(zGlob++))) == '*' || c=='?' ){
  5078         -        if( c=='?' && (*(z++))==0 ) return 0;
  5079         -      }
  5080         -      if( c==0 ){
  5081         -        return 1;
  5082         -      }else if( c=='[' ){
  5083         -        while( *z && testcase_glob(zGlob-1,z)==0 ){
  5084         -          z++;
  5085         -        }
  5086         -        return (*z)!=0;
  5087         -      }
  5088         -      while( (c2 = (*(z++)))!=0 ){
  5089         -        while( c2!=c ){
  5090         -          c2 = *(z++);
  5091         -          if( c2==0 ) return 0;
  5092         -        }
  5093         -        if( testcase_glob(zGlob,z) ) return 1;
  5094         -      }
  5095         -      return 0;
  5096         -    }else if( c=='?' ){
  5097         -      if( (*(z++))==0 ) return 0;
  5098         -    }else if( c=='[' ){
  5099         -      int prior_c = 0;
  5100         -      seen = 0;
  5101         -      invert = 0;
  5102         -      c = *(z++);
  5103         -      if( c==0 ) return 0;
  5104         -      c2 = *(zGlob++);
  5105         -      if( c2=='^' ){
  5106         -        invert = 1;
  5107         -        c2 = *(zGlob++);
  5108         -      }
  5109         -      if( c2==']' ){
  5110         -        if( c==']' ) seen = 1;
  5111         -        c2 = *(zGlob++);
  5112         -      }
  5113         -      while( c2 && c2!=']' ){
  5114         -        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  5115         -          c2 = *(zGlob++);
  5116         -          if( c>=prior_c && c<=c2 ) seen = 1;
  5117         -          prior_c = 0;
  5118         -        }else{
  5119         -          if( c==c2 ){
  5120         -            seen = 1;
  5121         -          }
  5122         -          prior_c = c2;
  5123         -        }
  5124         -        c2 = *(zGlob++);
  5125         -      }
  5126         -      if( c2==0 || (seen ^ invert)==0 ) return 0;
  5127         -    }else if( c=='#' ){
  5128         -      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  5129         -      if( !IsDigit(z[0]) ) return 0;
  5130         -      z++;
  5131         -      while( IsDigit(z[0]) ){ z++; }
  5132         -    }else{
  5133         -      if( c!=(*(z++)) ) return 0;
  5134         -    }
  5135         -  }
  5136         -  while( IsSpace(*z) ){ z++; }
  5137         -  return *z==0;
  5138         -}
  5139         -
  5140         -
  5141         -/*
  5142         -** Compare the string as a command-line option with either one or two
  5143         -** initial "-" characters.
  5144         -*/
  5145         -static int optionMatch(const char *zStr, const char *zOpt){
  5146         -  if( zStr[0]!='-' ) return 0;
  5147         -  zStr++;
  5148         -  if( zStr[0]=='-' ) zStr++;
  5149         -  return strcmp(zStr, zOpt)==0;
  5150         -}
  5151         -
  5152         -/*
  5153         -** Delete a file.
  5154         -*/
  5155         -int shellDeleteFile(const char *zFilename){
  5156         -  int rc;
  5157         -#ifdef _WIN32
  5158         -  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  5159         -  rc = _wunlink(z);
  5160         -  sqlite3_free(z);
  5161         -#else
  5162         -  rc = unlink(zFilename);
  5163         -#endif
  5164         -  return rc;
  5165         -}
  5166         -
  5167         -
  5168         -/*
  5169         -** The implementation of SQL scalar function fkey_collate_clause(), used
  5170         -** by the ".lint fkey-indexes" command. This scalar function is always
  5171         -** called with four arguments - the parent table name, the parent column name,
  5172         -** the child table name and the child column name.
  5173         -**
  5174         -**   fkey_collate_clause('parent-tab', 'parent-col', 'child-tab', 'child-col')
  5175         -**
  5176         -** If either of the named tables or columns do not exist, this function
  5177         -** returns an empty string. An empty string is also returned if both tables
  5178         -** and columns exist but have the same default collation sequence. Or,
  5179         -** if both exist but the default collation sequences are different, this
  5180         -** function returns the string " COLLATE <parent-collation>", where
  5181         -** <parent-collation> is the default collation sequence of the parent column.
  5182         -*/
  5183         -static void shellFkeyCollateClause(
  5184         -  sqlite3_context *pCtx,
  5185         -  int nVal,
  5186         -  sqlite3_value **apVal
  5187         -){
  5188         -  sqlite3 *db = sqlite3_context_db_handle(pCtx);
  5189         -  const char *zParent;
  5190         -  const char *zParentCol;
  5191         -  const char *zParentSeq;
  5192         -  const char *zChild;
  5193         -  const char *zChildCol;
  5194         -  const char *zChildSeq = 0;  /* Initialize to avoid false-positive warning */
  5195         -  int rc;
  5196         -
  5197         -  assert( nVal==4 );
  5198         -  zParent = (const char*)sqlite3_value_text(apVal[0]);
  5199         -  zParentCol = (const char*)sqlite3_value_text(apVal[1]);
  5200         -  zChild = (const char*)sqlite3_value_text(apVal[2]);
  5201         -  zChildCol = (const char*)sqlite3_value_text(apVal[3]);
  5202         -
  5203         -  sqlite3_result_text(pCtx, "", -1, SQLITE_STATIC);
  5204         -  rc = sqlite3_table_column_metadata(
  5205         -      db, "main", zParent, zParentCol, 0, &zParentSeq, 0, 0, 0
  5206         -  );
  5207         -  if( rc==SQLITE_OK ){
  5208         -    rc = sqlite3_table_column_metadata(
  5209         -        db, "main", zChild, zChildCol, 0, &zChildSeq, 0, 0, 0
  5210         -    );
  5211         -  }
  5212         -
  5213         -  if( rc==SQLITE_OK && sqlite3_stricmp(zParentSeq, zChildSeq) ){
  5214         -    char *z = sqlite3_mprintf(" COLLATE %s", zParentSeq);
  5215         -    sqlite3_result_text(pCtx, z, -1, SQLITE_TRANSIENT);
  5216         -    sqlite3_free(z);
  5217         -  }
  5218         -}
  5219         -
  5220         -
  5221         -/*
  5222         -** The implementation of dot-command ".lint fkey-indexes".
  5223         -*/
  5224         -static int lintFkeyIndexes(
  5225         -  ShellState *pState,             /* Current shell tool state */
  5226         -  char **azArg,                   /* Array of arguments passed to dot command */
  5227         -  int nArg                        /* Number of entries in azArg[] */
  5228         -){
  5229         -  sqlite3 *db = pState->db;       /* Database handle to query "main" db of */
  5230         -  FILE *out = pState->out;        /* Stream to write non-error output to */
  5231         -  int bVerbose = 0;               /* If -verbose is present */
  5232         -  int bGroupByParent = 0;         /* If -groupbyparent is present */
  5233         -  int i;                          /* To iterate through azArg[] */
  5234         -  const char *zIndent = "";       /* How much to indent CREATE INDEX by */
  5235         -  int rc;                         /* Return code */
  5236         -  sqlite3_stmt *pSql = 0;         /* Compiled version of SQL statement below */
  5237         -
  5238         -  /*
  5239         -  ** This SELECT statement returns one row for each foreign key constraint
  5240         -  ** in the schema of the main database. The column values are:
  5241         -  **
  5242         -  ** 0. The text of an SQL statement similar to:
  5243         -  **
  5244         -  **      "EXPLAIN QUERY PLAN SELECT rowid FROM child_table WHERE child_key=?"
  5245         -  **
  5246         -  **    This is the same SELECT that the foreign keys implementation needs
  5247         -  **    to run internally on child tables. If there is an index that can
  5248         -  **    be used to optimize this query, then it can also be used by the FK
  5249         -  **    implementation to optimize DELETE or UPDATE statements on the parent
  5250         -  **    table.
  5251         -  **
  5252         -  ** 1. A GLOB pattern suitable for sqlite3_strglob(). If the plan output by
  5253         -  **    the EXPLAIN QUERY PLAN command matches this pattern, then the schema
  5254         -  **    contains an index that can be used to optimize the query.
  5255         -  **
  5256         -  ** 2. Human readable text that describes the child table and columns. e.g.
  5257         -  **
  5258         -  **       "child_table(child_key1, child_key2)"
  5259         -  **
  5260         -  ** 3. Human readable text that describes the parent table and columns. e.g.
  5261         -  **
  5262         -  **       "parent_table(parent_key1, parent_key2)"
  5263         -  **
  5264         -  ** 4. A full CREATE INDEX statement for an index that could be used to
  5265         -  **    optimize DELETE or UPDATE statements on the parent table. e.g.
  5266         -  **
  5267         -  **       "CREATE INDEX child_table_child_key ON child_table(child_key)"
  5268         -  **
  5269         -  ** 5. The name of the parent table.
  5270         -  **
  5271         -  ** These six values are used by the C logic below to generate the report.
  5272         -  */
  5273         -  const char *zSql =
  5274         -  "SELECT "
  5275         -    "     'EXPLAIN QUERY PLAN SELECT rowid FROM ' || quote(s.name) || ' WHERE '"
  5276         -    "  || group_concat(quote(s.name) || '.' || quote(f.[from]) || '=?' "
  5277         -    "  || fkey_collate_clause("
  5278         -    "       f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]),' AND ')"
  5279         -    ", "
  5280         -    "     'SEARCH TABLE ' || s.name || ' USING COVERING INDEX*('"
  5281         -    "  || group_concat('*=?', ' AND ') || ')'"
  5282         -    ", "
  5283         -    "     s.name  || '(' || group_concat(f.[from],  ', ') || ')'"
  5284         -    ", "
  5285         -    "     f.[table] || '(' || group_concat(COALESCE(f.[to], p.[name])) || ')'"
  5286         -    ", "
  5287         -    "     'CREATE INDEX ' || quote(s.name ||'_'|| group_concat(f.[from], '_'))"
  5288         -    "  || ' ON ' || quote(s.name) || '('"
  5289         -    "  || group_concat(quote(f.[from]) ||"
  5290         -    "        fkey_collate_clause("
  5291         -    "          f.[table], COALESCE(f.[to], p.[name]), s.name, f.[from]), ', ')"
  5292         -    "  || ');'"
  5293         -    ", "
  5294         -    "     f.[table] "
  5295         -    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
  5296         -    "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
  5297         -    "GROUP BY s.name, f.id "
  5298         -    "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
  5299         -  ;
  5300         -  const char *zGlobIPK = "SEARCH TABLE * USING INTEGER PRIMARY KEY (rowid=?)";
  5301         -
  5302         -  for(i=2; i<nArg; i++){
  5303         -    int n = (int)strlen(azArg[i]);
  5304         -    if( n>1 && sqlite3_strnicmp("-verbose", azArg[i], n)==0 ){
  5305         -      bVerbose = 1;
  5306         -    }
  5307         -    else if( n>1 && sqlite3_strnicmp("-groupbyparent", azArg[i], n)==0 ){
  5308         -      bGroupByParent = 1;
  5309         -      zIndent = "    ";
  5310         -    }
  5311         -    else{
  5312         -      raw_printf(stderr, "Usage: %s %s ?-verbose? ?-groupbyparent?\n",
  5313         -          azArg[0], azArg[1]
  5314         -      );
  5315         -      return SQLITE_ERROR;
  5316         -    }
  5317         -  }
  5318         -
  5319         -  /* Register the fkey_collate_clause() SQL function */
  5320         -  rc = sqlite3_create_function(db, "fkey_collate_clause", 4, SQLITE_UTF8,
  5321         -      0, shellFkeyCollateClause, 0, 0
  5322         -  );
  5323         -
  5324         -
  5325         -  if( rc==SQLITE_OK ){
  5326         -    rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
  5327         -  }
  5328         -  if( rc==SQLITE_OK ){
  5329         -    sqlite3_bind_int(pSql, 1, bGroupByParent);
  5330         -  }
  5331         -
  5332         -  if( rc==SQLITE_OK ){
  5333         -    int rc2;
  5334         -    char *zPrev = 0;
  5335         -    while( SQLITE_ROW==sqlite3_step(pSql) ){
  5336         -      int res = -1;
  5337         -      sqlite3_stmt *pExplain = 0;
  5338         -      const char *zEQP = (const char*)sqlite3_column_text(pSql, 0);
  5339         -      const char *zGlob = (const char*)sqlite3_column_text(pSql, 1);
  5340         -      const char *zFrom = (const char*)sqlite3_column_text(pSql, 2);
  5341         -      const char *zTarget = (const char*)sqlite3_column_text(pSql, 3);
  5342         -      const char *zCI = (const char*)sqlite3_column_text(pSql, 4);
  5343         -      const char *zParent = (const char*)sqlite3_column_text(pSql, 5);
  5344         -
  5345         -      rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  5346         -      if( rc!=SQLITE_OK ) break;
  5347         -      if( SQLITE_ROW==sqlite3_step(pExplain) ){
  5348         -        const char *zPlan = (const char*)sqlite3_column_text(pExplain, 3);
  5349         -        res = (
  5350         -              0==sqlite3_strglob(zGlob, zPlan)
  5351         -           || 0==sqlite3_strglob(zGlobIPK, zPlan)
  5352         -        );
  5353         -      }
  5354         -      rc = sqlite3_finalize(pExplain);
  5355         -      if( rc!=SQLITE_OK ) break;
  5356         -
  5357         -      if( res<0 ){
  5358         -        raw_printf(stderr, "Error: internal error");
  5359         -        break;
  5360         -      }else{
  5361         -        if( bGroupByParent
  5362         -        && (bVerbose || res==0)
  5363         -        && (zPrev==0 || sqlite3_stricmp(zParent, zPrev))
  5364         -        ){
  5365         -          raw_printf(out, "-- Parent table %s\n", zParent);
  5366         -          sqlite3_free(zPrev);
  5367         -          zPrev = sqlite3_mprintf("%s", zParent);
  5368         -        }
  5369         -
  5370         -        if( res==0 ){
  5371         -          raw_printf(out, "%s%s --> %s\n", zIndent, zCI, zTarget);
  5372         -        }else if( bVerbose ){
  5373         -          raw_printf(out, "%s/* no extra indexes required for %s -> %s */\n",
  5374         -              zIndent, zFrom, zTarget
  5375         -          );
  5376         -        }
  5377         -      }
  5378         -    }
  5379         -    sqlite3_free(zPrev);
  5380         -
  5381         -    if( rc!=SQLITE_OK ){
  5382         -      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  5383         -    }
  5384         -
  5385         -    rc2 = sqlite3_finalize(pSql);
  5386         -    if( rc==SQLITE_OK && rc2!=SQLITE_OK ){
  5387         -      rc = rc2;
  5388         -      raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  5389         -    }
  5390         -  }else{
  5391         -    raw_printf(stderr, "%s\n", sqlite3_errmsg(db));
  5392         -  }
  5393         -
  5394         -  return rc;
  5395         -}
  5396         -
  5397         -/*
  5398         -** Implementation of ".lint" dot command.
  5399         -*/
  5400         -static int lintDotCommand(
  5401         -  ShellState *pState,             /* Current shell tool state */
  5402         -  char **azArg,                   /* Array of arguments passed to dot command */
  5403         -  int nArg                        /* Number of entries in azArg[] */
  5404         -){
  5405         -  int n;
  5406         -  n = (nArg>=2 ? (int)strlen(azArg[1]) : 0);
  5407         -  if( n<1 || sqlite3_strnicmp(azArg[1], "fkey-indexes", n) ) goto usage;
  5408         -  return lintFkeyIndexes(pState, azArg, nArg);
  5409         -
  5410         - usage:
  5411         -  raw_printf(stderr, "Usage %s sub-command ?switches...?\n", azArg[0]);
  5412         -  raw_printf(stderr, "Where sub-commands are:\n");
  5413         -  raw_printf(stderr, "    fkey-indexes\n");
  5414         -  return SQLITE_ERROR;
  5415         -}
  5416         -
  5417         -
  5418         -/*
  5419         -** If an input line begins with "." then invoke this routine to
  5420         -** process that line.
  5421         -**
  5422         -** Return 1 on error, 2 to exit, and 0 otherwise.
  5423         -*/
  5424         -static int do_meta_command(char *zLine, ShellState *p){
  5425         -  int h = 1;
  5426         -  int nArg = 0;
  5427         -  int n, c;
  5428         -  int rc = 0;
  5429         -  char *azArg[50];
  5430         -
  5431         -  /* Parse the input line into tokens.
  5432         -  */
  5433         -  while( zLine[h] && nArg<ArraySize(azArg) ){
  5434         -    while( IsSpace(zLine[h]) ){ h++; }
  5435         -    if( zLine[h]==0 ) break;
  5436         -    if( zLine[h]=='\'' || zLine[h]=='"' ){
  5437         -      int delim = zLine[h++];
  5438         -      azArg[nArg++] = &zLine[h];
  5439         -      while( zLine[h] && zLine[h]!=delim ){
  5440         -        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  5441         -        h++;
  5442         -      }
  5443         -      if( zLine[h]==delim ){
  5444         -        zLine[h++] = 0;
  5445         -      }
  5446         -      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  5447         -    }else{
  5448         -      azArg[nArg++] = &zLine[h];
  5449         -      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  5450         -      if( zLine[h] ) zLine[h++] = 0;
  5451         -      resolve_backslashes(azArg[nArg-1]);
  5452         -    }
  5453         -  }
  5454         -
  5455         -  /* Process the input line.
  5456         -  */
  5457         -  if( nArg==0 ) return 0; /* no tokens, no error */
  5458         -  n = strlen30(azArg[0]);
  5459         -  c = azArg[0][0];
  5460         -
  5461         -#ifndef SQLITE_OMIT_AUTHORIZATION
  5462         -  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  5463         -    if( nArg!=2 ){
  5464         -      raw_printf(stderr, "Usage: .auth ON|OFF\n");
  5465         -      rc = 1;
  5466         -      goto meta_command_exit;
  5467         -    }
  5468         -    open_db(p, 0);
  5469         -    if( booleanValue(azArg[1]) ){
  5470         -      sqlite3_set_authorizer(p->db, shellAuth, p);
  5471         -    }else{
  5472         -      sqlite3_set_authorizer(p->db, 0, 0);
  5473         -    }
  5474         -  }else
  5475         -#endif
  5476         -
  5477         -  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  5478         -   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  5479         -  ){
  5480         -    const char *zDestFile = 0;
  5481         -    const char *zDb = 0;
  5482         -    sqlite3 *pDest;
  5483         -    sqlite3_backup *pBackup;
  5484         -    int j;
  5485         -    for(j=1; j<nArg; j++){
  5486         -      const char *z = azArg[j];
  5487         -      if( z[0]=='-' ){
  5488         -        while( z[0]=='-' ) z++;
  5489         -        /* No options to process at this time */
  5490         -        {
  5491         -          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  5492         -          return 1;
  5493         -        }
  5494         -      }else if( zDestFile==0 ){
  5495         -        zDestFile = azArg[j];
  5496         -      }else if( zDb==0 ){
  5497         -        zDb = zDestFile;
  5498         -        zDestFile = azArg[j];
  5499         -      }else{
  5500         -        raw_printf(stderr, "too many arguments to .backup\n");
  5501         -        return 1;
  5502         -      }
  5503         -    }
  5504         -    if( zDestFile==0 ){
  5505         -      raw_printf(stderr, "missing FILENAME argument on .backup\n");
  5506         -      return 1;
  5507         -    }
  5508         -    if( zDb==0 ) zDb = "main";
  5509         -    rc = sqlite3_open(zDestFile, &pDest);
  5510         -    if( rc!=SQLITE_OK ){
  5511         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  5512         -      sqlite3_close(pDest);
  5513         -      return 1;
  5514         -    }
  5515         -    open_db(p, 0);
  5516         -    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  5517         -    if( pBackup==0 ){
  5518         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  5519         -      sqlite3_close(pDest);
  5520         -      return 1;
  5521         -    }
  5522         -    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  5523         -    sqlite3_backup_finish(pBackup);
  5524         -    if( rc==SQLITE_DONE ){
  5525         -      rc = 0;
  5526         -    }else{
  5527         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  5528         -      rc = 1;
  5529         -    }
  5530         -    sqlite3_close(pDest);
  5531         -  }else
  5532         -
  5533         -  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  5534         -    if( nArg==2 ){
  5535         -      bail_on_error = booleanValue(azArg[1]);
  5536         -    }else{
  5537         -      raw_printf(stderr, "Usage: .bail on|off\n");
  5538         -      rc = 1;
  5539         -    }
  5540         -  }else
  5541         -
  5542         -  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  5543         -    if( nArg==2 ){
  5544         -      if( booleanValue(azArg[1]) ){
  5545         -        setBinaryMode(p->out, 1);
  5546         -      }else{
  5547         -        setTextMode(p->out, 1);
  5548         -      }
  5549         -    }else{
  5550         -      raw_printf(stderr, "Usage: .binary on|off\n");
  5551         -      rc = 1;
  5552         -    }
  5553         -  }else
  5554         -
  5555         -  if( c=='c' && strcmp(azArg[0],"cd")==0 ){
  5556         -    if( nArg==2 ){
  5557         -#if defined(_WIN32) || defined(WIN32)
  5558         -      wchar_t *z = sqlite3_win32_utf8_to_unicode(azArg[1]);
  5559         -      rc = !SetCurrentDirectoryW(z);
  5560         -      sqlite3_free(z);
  5561         -#else
  5562         -      rc = chdir(azArg[1]);
  5563         -#endif
  5564         -      if( rc ){
  5565         -        utf8_printf(stderr, "Cannot change to directory \"%s\"\n", azArg[1]);
  5566         -        rc = 1;
  5567         -      }
  5568         -    }else{
  5569         -      raw_printf(stderr, "Usage: .cd DIRECTORY\n");
  5570         -      rc = 1;
  5571         -    }
  5572         -  }else
  5573         -
  5574         -  /* The undocumented ".breakpoint" command causes a call to the no-op
  5575         -  ** routine named test_breakpoint().
  5576         -  */
  5577         -  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  5578         -    test_breakpoint();
  5579         -  }else
  5580         -
  5581         -  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  5582         -    if( nArg==2 ){
  5583         -      setOrClearFlag(p, SHFLG_CountChanges, azArg[1]);
  5584         -    }else{
  5585         -      raw_printf(stderr, "Usage: .changes on|off\n");
  5586         -      rc = 1;
  5587         -    }
  5588         -  }else
  5589         -
  5590         -  /* Cancel output redirection, if it is currently set (by .testcase)
  5591         -  ** Then read the content of the testcase-out.txt file and compare against
  5592         -  ** azArg[1].  If there are differences, report an error and exit.
  5593         -  */
  5594         -  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  5595         -    char *zRes = 0;
  5596         -    output_reset(p);
  5597         -    if( nArg!=2 ){
  5598         -      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  5599         -      rc = 2;
  5600         -    }else if( (zRes = readFile("testcase-out.txt", 0))==0 ){
  5601         -      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  5602         -      rc = 2;
  5603         -    }else if( testcase_glob(azArg[1],zRes)==0 ){
  5604         -      utf8_printf(stderr,
  5605         -                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
  5606         -                 p->zTestcase, azArg[1], zRes);
  5607         -      rc = 2;
  5608         -    }else{
  5609         -      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  5610         -      p->nCheck++;
  5611         -    }
  5612         -    sqlite3_free(zRes);
  5613         -  }else
  5614         -
  5615         -  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  5616         -    if( nArg==2 ){
  5617         -      tryToClone(p, azArg[1]);
  5618         -    }else{
  5619         -      raw_printf(stderr, "Usage: .clone FILENAME\n");
  5620         -      rc = 1;
  5621         -    }
  5622         -  }else
  5623         -
  5624         -  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  5625         -    ShellState data;
  5626         -    char *zErrMsg = 0;
  5627         -    open_db(p, 0);
  5628         -    memcpy(&data, p, sizeof(data));
  5629         -    data.showHeader = 0;
  5630         -    data.cMode = data.mode = MODE_List;
  5631         -    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
  5632         -    data.cnt = 0;
  5633         -    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
  5634         -                 callback, &data, &zErrMsg);
  5635         -    if( zErrMsg ){
  5636         -      utf8_printf(stderr,"Error: %s\n", zErrMsg);
  5637         -      sqlite3_free(zErrMsg);
  5638         -      rc = 1;
  5639         -    }
  5640         -  }else
  5641         -
  5642         -  if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
  5643         -    rc = shell_dbinfo_command(p, nArg, azArg);
  5644         -  }else
  5645         -
  5646         -  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  5647         -    const char *zLike = 0;
  5648         -    int i;
  5649         -    int savedShowHeader = p->showHeader;
  5650         -    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines);
  5651         -    for(i=1; i<nArg; i++){
  5652         -      if( azArg[i][0]=='-' ){
  5653         -        const char *z = azArg[i]+1;
  5654         -        if( z[0]=='-' ) z++;
  5655         -        if( strcmp(z,"preserve-rowids")==0 ){
  5656         -#ifdef SQLITE_OMIT_VIRTUALTABLE
  5657         -          raw_printf(stderr, "The --preserve-rowids option is not compatible"
  5658         -                             " with SQLITE_OMIT_VIRTUALTABLE\n");
  5659         -          rc = 1;
  5660         -          goto meta_command_exit;
  5661         -#else
  5662         -          ShellSetFlag(p, SHFLG_PreserveRowid);
  5663         -#endif
  5664         -        }else
  5665         -        if( strcmp(z,"newlines")==0 ){
  5666         -          ShellSetFlag(p, SHFLG_Newlines);
  5667         -        }else
  5668         -        {
  5669         -          raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
  5670         -          rc = 1;
  5671         -          goto meta_command_exit;
  5672         -        }
  5673         -      }else if( zLike ){
  5674         -        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
  5675         -                           "?--newlines? ?LIKE-PATTERN?\n");
  5676         -        rc = 1;
  5677         -        goto meta_command_exit;
  5678         -      }else{
  5679         -        zLike = azArg[i];
  5680         -      }
  5681         -    }
  5682         -    open_db(p, 0);
  5683         -    /* When playing back a "dump", the content might appear in an order
  5684         -    ** which causes immediate foreign key constraints to be violated.
  5685         -    ** So disable foreign-key constraint enforcement to prevent problems. */
  5686         -    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  5687         -    raw_printf(p->out, "BEGIN TRANSACTION;\n");
  5688         -    p->writableSchema = 0;
  5689         -    p->showHeader = 0;
  5690         -    /* Set writable_schema=ON since doing so forces SQLite to initialize
  5691         -    ** as much of the schema as it can even if the sqlite_master table is
  5692         -    ** corrupt. */
  5693         -    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  5694         -    p->nErr = 0;
  5695         -    if( zLike==0 ){
  5696         -      run_schema_dump_query(p,
  5697         -        "SELECT name, type, sql FROM sqlite_master "
  5698         -        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  5699         -      );
  5700         -      run_schema_dump_query(p,
  5701         -        "SELECT name, type, sql FROM sqlite_master "
  5702         -        "WHERE name=='sqlite_sequence'"
  5703         -      );
  5704         -      run_table_dump_query(p,
  5705         -        "SELECT sql FROM sqlite_master "
  5706         -        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  5707         -      );
  5708         -    }else{
  5709         -      char *zSql;
  5710         -      zSql = sqlite3_mprintf(
  5711         -        "SELECT name, type, sql FROM sqlite_master "
  5712         -        "WHERE tbl_name LIKE %Q AND type=='table'"
  5713         -        "  AND sql NOT NULL", zLike);
  5714         -      run_schema_dump_query(p,zSql);
  5715         -      sqlite3_free(zSql);
  5716         -      zSql = sqlite3_mprintf(
  5717         -        "SELECT sql FROM sqlite_master "
  5718         -        "WHERE sql NOT NULL"
  5719         -        "  AND type IN ('index','trigger','view')"
  5720         -        "  AND tbl_name LIKE %Q", zLike);
  5721         -      run_table_dump_query(p, zSql, 0);
  5722         -      sqlite3_free(zSql);
  5723         -    }
  5724         -    if( p->writableSchema ){
  5725         -      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  5726         -      p->writableSchema = 0;
  5727         -    }
  5728         -    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  5729         -    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  5730         -    raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  5731         -    p->showHeader = savedShowHeader;
  5732         -  }else
  5733         -
  5734         -  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  5735         -    if( nArg==2 ){
  5736         -      setOrClearFlag(p, SHFLG_Echo, azArg[1]);
  5737         -    }else{
  5738         -      raw_printf(stderr, "Usage: .echo on|off\n");
  5739         -      rc = 1;
  5740         -    }
  5741         -  }else
  5742         -
  5743         -  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  5744         -    if( nArg==2 ){
  5745         -      if( strcmp(azArg[1],"full")==0 ){
  5746         -        p->autoEQP = 2;
  5747         -      }else{
  5748         -        p->autoEQP = booleanValue(azArg[1]);
  5749         -      }
  5750         -    }else{
  5751         -      raw_printf(stderr, "Usage: .eqp on|off|full\n");
  5752         -      rc = 1;
  5753         -    }
  5754         -  }else
  5755         -
  5756         -  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  5757         -    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  5758         -    rc = 2;
  5759         -  }else
  5760         -
  5761         -  /* The ".explain" command is automatic now.  It is largely pointless.  It
  5762         -  ** retained purely for backwards compatibility */
  5763         -  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  5764         -    int val = 1;
  5765         -    if( nArg>=2 ){
  5766         -      if( strcmp(azArg[1],"auto")==0 ){
  5767         -        val = 99;
  5768         -      }else{
  5769         -        val =  booleanValue(azArg[1]);
  5770         -      }
  5771         -    }
  5772         -    if( val==1 && p->mode!=MODE_Explain ){
  5773         -      p->normalMode = p->mode;
  5774         -      p->mode = MODE_Explain;
  5775         -      p->autoExplain = 0;
  5776         -    }else if( val==0 ){
  5777         -      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  5778         -      p->autoExplain = 0;
  5779         -    }else if( val==99 ){
  5780         -      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  5781         -      p->autoExplain = 1;
  5782         -    }
  5783         -  }else
  5784         -
  5785         -  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  5786         -    ShellState data;
  5787         -    char *zErrMsg = 0;
  5788         -    int doStats = 0;
  5789         -    memcpy(&data, p, sizeof(data));
  5790         -    data.showHeader = 0;
  5791         -    data.cMode = data.mode = MODE_Semi;
  5792         -    if( nArg==2 && optionMatch(azArg[1], "indent") ){
  5793         -      data.cMode = data.mode = MODE_Pretty;
  5794         -      nArg = 1;
  5795         -    }
  5796         -    if( nArg!=1 ){
  5797         -      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  5798         -      rc = 1;
  5799         -      goto meta_command_exit;
  5800         -    }
  5801         -    open_db(p, 0);
  5802         -    rc = sqlite3_exec(p->db,
  5803         -       "SELECT sql FROM"
  5804         -       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  5805         -       "     FROM sqlite_master UNION ALL"
  5806         -       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  5807         -       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  5808         -       "ORDER BY rowid",
  5809         -       callback, &data, &zErrMsg
  5810         -    );
  5811         -    if( rc==SQLITE_OK ){
  5812         -      sqlite3_stmt *pStmt;
  5813         -      rc = sqlite3_prepare_v2(p->db,
  5814         -               "SELECT rowid FROM sqlite_master"
  5815         -               " WHERE name GLOB 'sqlite_stat[134]'",
  5816         -               -1, &pStmt, 0);
  5817         -      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  5818         -      sqlite3_finalize(pStmt);
  5819         -    }
  5820         -    if( doStats==0 ){
  5821         -      raw_printf(p->out, "/* No STAT tables available */\n");
  5822         -    }else{
  5823         -      raw_printf(p->out, "ANALYZE sqlite_master;\n");
  5824         -      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  5825         -                   callback, &data, &zErrMsg);
  5826         -      data.cMode = data.mode = MODE_Insert;
  5827         -      data.zDestTable = "sqlite_stat1";
  5828         -      shell_exec(p->db, "SELECT * FROM sqlite_stat1",
  5829         -                 shell_callback, &data,&zErrMsg);
  5830         -      data.zDestTable = "sqlite_stat3";
  5831         -      shell_exec(p->db, "SELECT * FROM sqlite_stat3",
  5832         -                 shell_callback, &data,&zErrMsg);
  5833         -      data.zDestTable = "sqlite_stat4";
  5834         -      shell_exec(p->db, "SELECT * FROM sqlite_stat4",
  5835         -                 shell_callback, &data, &zErrMsg);
  5836         -      raw_printf(p->out, "ANALYZE sqlite_master;\n");
  5837         -    }
  5838         -  }else
  5839         -
  5840         -  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  5841         -    if( nArg==2 ){
  5842         -      p->showHeader = booleanValue(azArg[1]);
  5843         -    }else{
  5844         -      raw_printf(stderr, "Usage: .headers on|off\n");
  5845         -      rc = 1;
  5846         -    }
  5847         -  }else
  5848         -
  5849         -  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  5850         -    utf8_printf(p->out, "%s", zHelp);
  5851         -  }else
  5852         -
  5853         -  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  5854         -    char *zTable;               /* Insert data into this table */
  5855         -    char *zFile;                /* Name of file to extra content from */
  5856         -    sqlite3_stmt *pStmt = NULL; /* A statement */
  5857         -    int nCol;                   /* Number of columns in the table */
  5858         -    int nByte;                  /* Number of bytes in an SQL string */
  5859         -    int i, j;                   /* Loop counters */
  5860         -    int needCommit;             /* True to COMMIT or ROLLBACK at end */
  5861         -    int nSep;                   /* Number of bytes in p->colSeparator[] */
  5862         -    char *zSql;                 /* An SQL statement */
  5863         -    ImportCtx sCtx;             /* Reader context */
  5864         -    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  5865         -    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
  5866         -
  5867         -    if( nArg!=3 ){
  5868         -      raw_printf(stderr, "Usage: .import FILE TABLE\n");
  5869         -      goto meta_command_exit;
  5870         -    }
  5871         -    zFile = azArg[1];
  5872         -    zTable = azArg[2];
  5873         -    seenInterrupt = 0;
  5874         -    memset(&sCtx, 0, sizeof(sCtx));
  5875         -    open_db(p, 0);
  5876         -    nSep = strlen30(p->colSeparator);
  5877         -    if( nSep==0 ){
  5878         -      raw_printf(stderr,
  5879         -                 "Error: non-null column separator required for import\n");
  5880         -      return 1;
  5881         -    }
  5882         -    if( nSep>1 ){
  5883         -      raw_printf(stderr, "Error: multi-character column separators not allowed"
  5884         -                      " for import\n");
  5885         -      return 1;
  5886         -    }
  5887         -    nSep = strlen30(p->rowSeparator);
  5888         -    if( nSep==0 ){
  5889         -      raw_printf(stderr, "Error: non-null row separator required for import\n");
  5890         -      return 1;
  5891         -    }
  5892         -    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  5893         -      /* When importing CSV (only), if the row separator is set to the
  5894         -      ** default output row separator, change it to the default input
  5895         -      ** row separator.  This avoids having to maintain different input
  5896         -      ** and output row separators. */
  5897         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  5898         -      nSep = strlen30(p->rowSeparator);
  5899         -    }
  5900         -    if( nSep>1 ){
  5901         -      raw_printf(stderr, "Error: multi-character row separators not allowed"
  5902         -                      " for import\n");
  5903         -      return 1;
  5904         -    }
  5905         -    sCtx.zFile = zFile;
  5906         -    sCtx.nLine = 1;
  5907         -    if( sCtx.zFile[0]=='|' ){
  5908         -#ifdef SQLITE_OMIT_POPEN
  5909         -      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  5910         -      return 1;
  5911         -#else
  5912         -      sCtx.in = popen(sCtx.zFile+1, "r");
  5913         -      sCtx.zFile = "<pipe>";
  5914         -      xCloser = pclose;
  5915         -#endif
  5916         -    }else{
  5917         -      sCtx.in = fopen(sCtx.zFile, "rb");
  5918         -      xCloser = fclose;
  5919         -    }
  5920         -    if( p->mode==MODE_Ascii ){
  5921         -      xRead = ascii_read_one_field;
  5922         -    }else{
  5923         -      xRead = csv_read_one_field;
  5924         -    }
  5925         -    if( sCtx.in==0 ){
  5926         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  5927         -      return 1;
  5928         -    }
  5929         -    sCtx.cColSep = p->colSeparator[0];
  5930         -    sCtx.cRowSep = p->rowSeparator[0];
  5931         -    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  5932         -    if( zSql==0 ){
  5933         -      raw_printf(stderr, "Error: out of memory\n");
  5934         -      xCloser(sCtx.in);
  5935         -      return 1;
  5936         -    }
  5937         -    nByte = strlen30(zSql);
  5938         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5939         -    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
  5940         -    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  5941         -      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  5942         -      char cSep = '(';
  5943         -      while( xRead(&sCtx) ){
  5944         -        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
  5945         -        cSep = ',';
  5946         -        if( sCtx.cTerm!=sCtx.cColSep ) break;
  5947         -      }
  5948         -      if( cSep=='(' ){
  5949         -        sqlite3_free(zCreate);
  5950         -        sqlite3_free(sCtx.z);
  5951         -        xCloser(sCtx.in);
  5952         -        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  5953         -        return 1;
  5954         -      }
  5955         -      zCreate = sqlite3_mprintf("%z\n)", zCreate);
  5956         -      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  5957         -      sqlite3_free(zCreate);
  5958         -      if( rc ){
  5959         -        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  5960         -                sqlite3_errmsg(p->db));
  5961         -        sqlite3_free(sCtx.z);
  5962         -        xCloser(sCtx.in);
  5963         -        return 1;
  5964         -      }
  5965         -      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5966         -    }
  5967         -    sqlite3_free(zSql);
  5968         -    if( rc ){
  5969         -      if (pStmt) sqlite3_finalize(pStmt);
  5970         -      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  5971         -      xCloser(sCtx.in);
  5972         -      return 1;
  5973         -    }
  5974         -    nCol = sqlite3_column_count(pStmt);
  5975         -    sqlite3_finalize(pStmt);
  5976         -    pStmt = 0;
  5977         -    if( nCol==0 ) return 0; /* no columns, no error */
  5978         -    zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 );
  5979         -    if( zSql==0 ){
  5980         -      raw_printf(stderr, "Error: out of memory\n");
  5981         -      xCloser(sCtx.in);
  5982         -      return 1;
  5983         -    }
  5984         -    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  5985         -    j = strlen30(zSql);
  5986         -    for(i=1; i<nCol; i++){
  5987         -      zSql[j++] = ',';
  5988         -      zSql[j++] = '?';
  5989         -    }
  5990         -    zSql[j++] = ')';
  5991         -    zSql[j] = 0;
  5992         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  5993         -    sqlite3_free(zSql);
  5994         -    if( rc ){
  5995         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  5996         -      if (pStmt) sqlite3_finalize(pStmt);
  5997         -      xCloser(sCtx.in);
  5998         -      return 1;
  5999         -    }
  6000         -    needCommit = sqlite3_get_autocommit(p->db);
  6001         -    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  6002         -    do{
  6003         -      int startLine = sCtx.nLine;
  6004         -      for(i=0; i<nCol; i++){
  6005         -        char *z = xRead(&sCtx);
  6006         -        /*
  6007         -        ** Did we reach end-of-file before finding any columns?
  6008         -        ** If so, stop instead of NULL filling the remaining columns.
  6009         -        */
  6010         -        if( z==0 && i==0 ) break;
  6011         -        /*
  6012         -        ** Did we reach end-of-file OR end-of-line before finding any
  6013         -        ** columns in ASCII mode?  If so, stop instead of NULL filling
  6014         -        ** the remaining columns.
  6015         -        */
  6016         -        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  6017         -        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  6018         -        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  6019         -          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  6020         -                          "filling the rest with NULL\n",
  6021         -                          sCtx.zFile, startLine, nCol, i+1);
  6022         -          i += 2;
  6023         -          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  6024         -        }
  6025         -      }
  6026         -      if( sCtx.cTerm==sCtx.cColSep ){
  6027         -        do{
  6028         -          xRead(&sCtx);
  6029         -          i++;
  6030         -        }while( sCtx.cTerm==sCtx.cColSep );
  6031         -        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  6032         -                        "extras ignored\n",
  6033         -                        sCtx.zFile, startLine, nCol, i);
  6034         -      }
  6035         -      if( i>=nCol ){
  6036         -        sqlite3_step(pStmt);
  6037         -        rc = sqlite3_reset(pStmt);
  6038         -        if( rc!=SQLITE_OK ){
  6039         -          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  6040         -                      startLine, sqlite3_errmsg(p->db));
  6041         -        }
  6042         -      }
  6043         -    }while( sCtx.cTerm!=EOF );
  6044         -
  6045         -    xCloser(sCtx.in);
  6046         -    sqlite3_free(sCtx.z);
  6047         -    sqlite3_finalize(pStmt);
  6048         -    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  6049         -  }else
  6050         -
  6051         -#ifndef SQLITE_UNTESTABLE
  6052         -  if( c=='i' && strncmp(azArg[0], "imposter", n)==0 ){
  6053         -    char *zSql;
  6054         -    char *zCollist = 0;
  6055         -    sqlite3_stmt *pStmt;
  6056         -    int tnum = 0;
  6057         -    int i;
  6058         -    if( nArg!=3 ){
  6059         -      utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n");
  6060         -      rc = 1;
  6061         -      goto meta_command_exit;
  6062         -    }
  6063         -    open_db(p, 0);
  6064         -    zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
  6065         -                           " WHERE name='%q' AND type='index'", azArg[1]);
  6066         -    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  6067         -    sqlite3_free(zSql);
  6068         -    if( sqlite3_step(pStmt)==SQLITE_ROW ){
  6069         -      tnum = sqlite3_column_int(pStmt, 0);
  6070         -    }
  6071         -    sqlite3_finalize(pStmt);
  6072         -    if( tnum==0 ){
  6073         -      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
  6074         -      rc = 1;
  6075         -      goto meta_command_exit;
  6076         -    }
  6077         -    zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
  6078         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  6079         -    sqlite3_free(zSql);
  6080         -    i = 0;
  6081         -    while( sqlite3_step(pStmt)==SQLITE_ROW ){
  6082         -      char zLabel[20];
  6083         -      const char *zCol = (const char*)sqlite3_column_text(pStmt,2);
  6084         -      i++;
  6085         -      if( zCol==0 ){
  6086         -        if( sqlite3_column_int(pStmt,1)==-1 ){
  6087         -          zCol = "_ROWID_";
  6088         -        }else{
  6089         -          sqlite3_snprintf(sizeof(zLabel),zLabel,"expr%d",i);
  6090         -          zCol = zLabel;
  6091         -        }
  6092         -      }
  6093         -      if( zCollist==0 ){
  6094         -        zCollist = sqlite3_mprintf("\"%w\"", zCol);
  6095         -      }else{
  6096         -        zCollist = sqlite3_mprintf("%z,\"%w\"", zCollist, zCol);
  6097         -      }
  6098         -    }
  6099         -    sqlite3_finalize(pStmt);
  6100         -    zSql = sqlite3_mprintf(
  6101         -          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
  6102         -          azArg[2], zCollist, zCollist);
  6103         -    sqlite3_free(zCollist);
  6104         -    rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
  6105         -    if( rc==SQLITE_OK ){
  6106         -      rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
  6107         -      sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 0);
  6108         -      if( rc ){
  6109         -        utf8_printf(stderr, "Error in [%s]: %s\n", zSql, sqlite3_errmsg(p->db));
  6110         -      }else{
  6111         -        utf8_printf(stdout, "%s;\n", zSql);
  6112         -        raw_printf(stdout,
  6113         -           "WARNING: writing to an imposter table will corrupt the index!\n"
  6114         -        );
  6115         -      }
  6116         -    }else{
  6117         -      raw_printf(stderr, "SQLITE_TESTCTRL_IMPOSTER returns %d\n", rc);
  6118         -      rc = 1;
  6119         -    }
  6120         -    sqlite3_free(zSql);
  6121         -  }else
  6122         -#endif /* !defined(SQLITE_OMIT_TEST_CONTROL) */
  6123         -
  6124         -#ifdef SQLITE_ENABLE_IOTRACE
  6125         -  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  6126         -    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  6127         -    if( iotrace && iotrace!=stdout ) fclose(iotrace);
  6128         -    iotrace = 0;
  6129         -    if( nArg<2 ){
  6130         -      sqlite3IoTrace = 0;
  6131         -    }else if( strcmp(azArg[1], "-")==0 ){
  6132         -      sqlite3IoTrace = iotracePrintf;
  6133         -      iotrace = stdout;
  6134         -    }else{
  6135         -      iotrace = fopen(azArg[1], "w");
  6136         -      if( iotrace==0 ){
  6137         -        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  6138         -        sqlite3IoTrace = 0;
  6139         -        rc = 1;
  6140         -      }else{
  6141         -        sqlite3IoTrace = iotracePrintf;
  6142         -      }
  6143         -    }
  6144         -  }else
  6145         -#endif
  6146         -
  6147         -  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  6148         -    static const struct {
  6149         -       const char *zLimitName;   /* Name of a limit */
  6150         -       int limitCode;            /* Integer code for that limit */
  6151         -    } aLimit[] = {
  6152         -      { "length",                SQLITE_LIMIT_LENGTH                    },
  6153         -      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
  6154         -      { "column",                SQLITE_LIMIT_COLUMN                    },
  6155         -      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
  6156         -      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
  6157         -      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
  6158         -      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
  6159         -      { "attached",              SQLITE_LIMIT_ATTACHED                  },
  6160         -      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
  6161         -      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
  6162         -      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
  6163         -      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
  6164         -    };
  6165         -    int i, n2;
  6166         -    open_db(p, 0);
  6167         -    if( nArg==1 ){
  6168         -      for(i=0; i<ArraySize(aLimit); i++){
  6169         -        printf("%20s %d\n", aLimit[i].zLimitName,
  6170         -               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  6171         -      }
  6172         -    }else if( nArg>3 ){
  6173         -      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  6174         -      rc = 1;
  6175         -      goto meta_command_exit;
  6176         -    }else{
  6177         -      int iLimit = -1;
  6178         -      n2 = strlen30(azArg[1]);
  6179         -      for(i=0; i<ArraySize(aLimit); i++){
  6180         -        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  6181         -          if( iLimit<0 ){
  6182         -            iLimit = i;
  6183         -          }else{
  6184         -            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  6185         -            rc = 1;
  6186         -            goto meta_command_exit;
  6187         -          }
  6188         -        }
  6189         -      }
  6190         -      if( iLimit<0 ){
  6191         -        utf8_printf(stderr, "unknown limit: \"%s\"\n"
  6192         -                        "enter \".limits\" with no arguments for a list.\n",
  6193         -                         azArg[1]);
  6194         -        rc = 1;
  6195         -        goto meta_command_exit;
  6196         -      }
  6197         -      if( nArg==3 ){
  6198         -        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  6199         -                      (int)integerValue(azArg[2]));
  6200         -      }
  6201         -      printf("%20s %d\n", aLimit[iLimit].zLimitName,
  6202         -             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  6203         -    }
  6204         -  }else
  6205         -
  6206         -  if( c=='l' && n>2 && strncmp(azArg[0], "lint", n)==0 ){
  6207         -    open_db(p, 0);
  6208         -    lintDotCommand(p, azArg, nArg);
  6209         -  }else
  6210         -
  6211         -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  6212         -  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  6213         -    const char *zFile, *zProc;
  6214         -    char *zErrMsg = 0;
  6215         -    if( nArg<2 ){
  6216         -      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  6217         -      rc = 1;
  6218         -      goto meta_command_exit;
  6219         -    }
  6220         -    zFile = azArg[1];
  6221         -    zProc = nArg>=3 ? azArg[2] : 0;
  6222         -    open_db(p, 0);
  6223         -    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  6224         -    if( rc!=SQLITE_OK ){
  6225         -      utf8_printf(stderr, "Error: %s\n", zErrMsg);
  6226         -      sqlite3_free(zErrMsg);
  6227         -      rc = 1;
  6228         -    }
  6229         -  }else
  6230         -#endif
  6231         -
  6232         -  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  6233         -    if( nArg!=2 ){
  6234         -      raw_printf(stderr, "Usage: .log FILENAME\n");
  6235         -      rc = 1;
  6236         -    }else{
  6237         -      const char *zFile = azArg[1];
  6238         -      output_file_close(p->pLog);
  6239         -      p->pLog = output_file_open(zFile);
  6240         -    }
  6241         -  }else
  6242         -
  6243         -  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  6244         -    const char *zMode = nArg>=2 ? azArg[1] : "";
  6245         -    int n2 = (int)strlen(zMode);
  6246         -    int c2 = zMode[0];
  6247         -    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  6248         -      p->mode = MODE_Line;
  6249         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  6250         -    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  6251         -      p->mode = MODE_Column;
  6252         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  6253         -    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  6254         -      p->mode = MODE_List;
  6255         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Column);
  6256         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  6257         -    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  6258         -      p->mode = MODE_Html;
  6259         -    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  6260         -      p->mode = MODE_Tcl;
  6261         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  6262         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  6263         -    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  6264         -      p->mode = MODE_Csv;
  6265         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  6266         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  6267         -    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  6268         -      p->mode = MODE_List;
  6269         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  6270         -    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  6271         -      p->mode = MODE_Insert;
  6272         -      set_table_name(p, nArg>=3 ? azArg[2] : "table");
  6273         -    }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
  6274         -      p->mode = MODE_Quote;
  6275         -    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  6276         -      p->mode = MODE_Ascii;
  6277         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  6278         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  6279         -    }else if( nArg==1 ){
  6280         -      raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
  6281         -    }else{
  6282         -      raw_printf(stderr, "Error: mode should be one of: "
  6283         -         "ascii column csv html insert line list quote tabs tcl\n");
  6284         -      rc = 1;
  6285         -    }
  6286         -    p->cMode = p->mode;
  6287         -  }else
  6288         -
  6289         -  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  6290         -    if( nArg==2 ){
  6291         -      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  6292         -                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  6293         -    }else{
  6294         -      raw_printf(stderr, "Usage: .nullvalue STRING\n");
  6295         -      rc = 1;
  6296         -    }
  6297         -  }else
  6298         -
  6299         -  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  6300         -    char *zNewFilename;  /* Name of the database file to open */
  6301         -    int iName = 1;       /* Index in azArg[] of the filename */
  6302         -    int newFlag = 0;     /* True to delete file before opening */
  6303         -    /* Close the existing database */
  6304         -    session_close_all(p);
  6305         -    sqlite3_close(p->db);
  6306         -    p->db = 0;
  6307         -    p->zDbFilename = 0;
  6308         -    sqlite3_free(p->zFreeOnClose);
  6309         -    p->zFreeOnClose = 0;
  6310         -    /* Check for command-line arguments */
  6311         -    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  6312         -      const char *z = azArg[iName];
  6313         -      if( optionMatch(z,"new") ){
  6314         -        newFlag = 1;
  6315         -      }else if( z[0]=='-' ){
  6316         -        utf8_printf(stderr, "unknown option: %s\n", z);
  6317         -        rc = 1;
  6318         -        goto meta_command_exit;
  6319         -      }
  6320         -    }
  6321         -    /* If a filename is specified, try to open it first */
  6322         -    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  6323         -    if( zNewFilename ){
  6324         -      if( newFlag ) shellDeleteFile(zNewFilename);
  6325         -      p->zDbFilename = zNewFilename;
  6326         -      open_db(p, 1);
  6327         -      if( p->db==0 ){
  6328         -        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  6329         -        sqlite3_free(zNewFilename);
  6330         -      }else{
  6331         -        p->zFreeOnClose = zNewFilename;
  6332         -      }
  6333         -    }
  6334         -    if( p->db==0 ){
  6335         -      /* As a fall-back open a TEMP database */
  6336         -      p->zDbFilename = 0;
  6337         -      open_db(p, 0);
  6338         -    }
  6339         -  }else
  6340         -
  6341         -  if( c=='o'
  6342         -   && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
  6343         -  ){
  6344         -    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  6345         -    if( nArg>2 ){
  6346         -      utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
  6347         -      rc = 1;
  6348         -      goto meta_command_exit;
  6349         -    }
  6350         -    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  6351         -      if( nArg<2 ){
  6352         -        raw_printf(stderr, "Usage: .once FILE\n");
  6353         -        rc = 1;
  6354         -        goto meta_command_exit;
  6355         -      }
  6356         -      p->outCount = 2;
  6357         -    }else{
  6358         -      p->outCount = 0;
  6359         -    }
  6360         -    output_reset(p);
  6361         -    if( zFile[0]=='|' ){
  6362         -#ifdef SQLITE_OMIT_POPEN
  6363         -      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  6364         -      rc = 1;
  6365         -      p->out = stdout;
  6366         -#else
  6367         -      p->out = popen(zFile + 1, "w");
  6368         -      if( p->out==0 ){
  6369         -        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  6370         -        p->out = stdout;
  6371         -        rc = 1;
  6372         -      }else{
  6373         -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  6374         -      }
  6375         -#endif
  6376         -    }else{
  6377         -      p->out = output_file_open(zFile);
  6378         -      if( p->out==0 ){
  6379         -        if( strcmp(zFile,"off")!=0 ){
  6380         -          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  6381         -        }
  6382         -        p->out = stdout;
  6383         -        rc = 1;
  6384         -      } else {
  6385         -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  6386         -      }
  6387         -    }
  6388         -  }else
  6389         -
  6390         -  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  6391         -    int i;
  6392         -    for(i=1; i<nArg; i++){
  6393         -      if( i>1 ) raw_printf(p->out, " ");
  6394         -      utf8_printf(p->out, "%s", azArg[i]);
  6395         -    }
  6396         -    raw_printf(p->out, "\n");
  6397         -  }else
  6398         -
  6399         -  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  6400         -    if( nArg >= 2) {
  6401         -      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  6402         -    }
  6403         -    if( nArg >= 3) {
  6404         -      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  6405         -    }
  6406         -  }else
  6407         -
  6408         -  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  6409         -    rc = 2;
  6410         -  }else
  6411         -
  6412         -  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  6413         -    FILE *alt;
  6414         -    if( nArg!=2 ){
  6415         -      raw_printf(stderr, "Usage: .read FILE\n");
  6416         -      rc = 1;
  6417         -      goto meta_command_exit;
  6418         -    }
  6419         -    alt = fopen(azArg[1], "rb");
  6420         -    if( alt==0 ){
  6421         -      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  6422         -      rc = 1;
  6423         -    }else{
  6424         -      rc = process_input(p, alt);
  6425         -      fclose(alt);
  6426         -    }
  6427         -  }else
  6428         -
  6429         -  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  6430         -    const char *zSrcFile;
  6431         -    const char *zDb;
  6432         -    sqlite3 *pSrc;
  6433         -    sqlite3_backup *pBackup;
  6434         -    int nTimeout = 0;
  6435         -
  6436         -    if( nArg==2 ){
  6437         -      zSrcFile = azArg[1];
  6438         -      zDb = "main";
  6439         -    }else if( nArg==3 ){
  6440         -      zSrcFile = azArg[2];
  6441         -      zDb = azArg[1];
  6442         -    }else{
  6443         -      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  6444         -      rc = 1;
  6445         -      goto meta_command_exit;
  6446         -    }
  6447         -    rc = sqlite3_open(zSrcFile, &pSrc);
  6448         -    if( rc!=SQLITE_OK ){
  6449         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  6450         -      sqlite3_close(pSrc);
  6451         -      return 1;
  6452         -    }
  6453         -    open_db(p, 0);
  6454         -    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  6455         -    if( pBackup==0 ){
  6456         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  6457         -      sqlite3_close(pSrc);
  6458         -      return 1;
  6459         -    }
  6460         -    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  6461         -          || rc==SQLITE_BUSY  ){
  6462         -      if( rc==SQLITE_BUSY ){
  6463         -        if( nTimeout++ >= 3 ) break;
  6464         -        sqlite3_sleep(100);
  6465         -      }
  6466         -    }
  6467         -    sqlite3_backup_finish(pBackup);
  6468         -    if( rc==SQLITE_DONE ){
  6469         -      rc = 0;
  6470         -    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  6471         -      raw_printf(stderr, "Error: source database is busy\n");
  6472         -      rc = 1;
  6473         -    }else{
  6474         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  6475         -      rc = 1;
  6476         -    }
  6477         -    sqlite3_close(pSrc);
  6478         -  }else
  6479         -
  6480         -
  6481         -  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  6482         -    if( nArg==2 ){
  6483         -      p->scanstatsOn = booleanValue(azArg[1]);
  6484         -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  6485         -      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  6486         -#endif
  6487         -    }else{
  6488         -      raw_printf(stderr, "Usage: .scanstats on|off\n");
  6489         -      rc = 1;
  6490         -    }
  6491         -  }else
  6492         -
  6493         -  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  6494         -    ShellText sSelect;
  6495         -    ShellState data;
  6496         -    char *zErrMsg = 0;
  6497         -    const char *zDiv = 0;
  6498         -    int iSchema = 0;
  6499         -
  6500         -    open_db(p, 0);
  6501         -    memcpy(&data, p, sizeof(data));
  6502         -    data.showHeader = 0;
  6503         -    data.cMode = data.mode = MODE_Semi;
  6504         -    initText(&sSelect);
  6505         -    if( nArg>=2 && optionMatch(azArg[1], "indent") ){
  6506         -      data.cMode = data.mode = MODE_Pretty;
  6507         -      nArg--;
  6508         -      if( nArg==2 ) azArg[1] = azArg[2];
  6509         -    }
  6510         -    if( nArg==2 && azArg[1][0]!='-' ){
  6511         -      int i;
  6512         -      for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  6513         -      if( strcmp(azArg[1],"sqlite_master")==0 ){
  6514         -        char *new_argv[2], *new_colv[2];
  6515         -        new_argv[0] = "CREATE TABLE sqlite_master (\n"
  6516         -                      "  type text,\n"
  6517         -                      "  name text,\n"
  6518         -                      "  tbl_name text,\n"
  6519         -                      "  rootpage integer,\n"
  6520         -                      "  sql text\n"
  6521         -                      ")";
  6522         -        new_argv[1] = 0;
  6523         -        new_colv[0] = "sql";
  6524         -        new_colv[1] = 0;
  6525         -        callback(&data, 1, new_argv, new_colv);
  6526         -        rc = SQLITE_OK;
  6527         -      }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  6528         -        char *new_argv[2], *new_colv[2];
  6529         -        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  6530         -                      "  type text,\n"
  6531         -                      "  name text,\n"
  6532         -                      "  tbl_name text,\n"
  6533         -                      "  rootpage integer,\n"
  6534         -                      "  sql text\n"
  6535         -                      ")";
  6536         -        new_argv[1] = 0;
  6537         -        new_colv[0] = "sql";
  6538         -        new_colv[1] = 0;
  6539         -        callback(&data, 1, new_argv, new_colv);
  6540         -        rc = SQLITE_OK;
  6541         -      }else{
  6542         -        zDiv = "(";
  6543         -      }
  6544         -    }else if( nArg==1 ){
  6545         -      zDiv = "(";
  6546         -    }else{
  6547         -      raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  6548         -      rc = 1;
  6549         -      goto meta_command_exit;
  6550         -    }
  6551         -    if( zDiv ){
  6552         -      sqlite3_stmt *pStmt = 0;
  6553         -      rc = sqlite3_prepare_v2(p->db, "SELECT name FROM pragma_database_list",
  6554         -                              -1, &pStmt, 0);
  6555         -      if( rc ){
  6556         -        utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  6557         -        sqlite3_finalize(pStmt);
  6558         -        rc = 1;
  6559         -        goto meta_command_exit;
  6560         -      }
  6561         -      appendText(&sSelect, "SELECT sql FROM", 0);
  6562         -      iSchema = 0;
  6563         -      while( sqlite3_step(pStmt)==SQLITE_ROW ){
  6564         -        const char *zDb = (const char*)sqlite3_column_text(pStmt, 0);
  6565         -        char zScNum[30];
  6566         -        sqlite3_snprintf(sizeof(zScNum), zScNum, "%d", ++iSchema);
  6567         -        appendText(&sSelect, zDiv, 0);
  6568         -        zDiv = " UNION ALL ";
  6569         -        if( strcmp(zDb, "main")!=0 ){
  6570         -          appendText(&sSelect, "SELECT shell_add_schema(sql,", 0);
  6571         -          appendText(&sSelect, zDb, '"');
  6572         -          appendText(&sSelect, ") AS sql, type, tbl_name, name, rowid,", 0);
  6573         -          appendText(&sSelect, zScNum, 0);
  6574         -          appendText(&sSelect, " AS snum, ", 0);
  6575         -          appendText(&sSelect, zDb, '\'');
  6576         -          appendText(&sSelect, " AS sname FROM ", 0);
  6577         -          appendText(&sSelect, zDb, '"');
  6578         -          appendText(&sSelect, ".sqlite_master", 0);
  6579         -        }else{
  6580         -          appendText(&sSelect, "SELECT sql, type, tbl_name, name, rowid, ", 0);
  6581         -          appendText(&sSelect, zScNum, 0);
  6582         -          appendText(&sSelect, " AS snum, 'main' AS sname FROM sqlite_master",0);
  6583         -        }
  6584         -      }
  6585         -      sqlite3_finalize(pStmt);
  6586         -      appendText(&sSelect, ") WHERE ", 0);
  6587         -      if( nArg>1 ){
  6588         -        char *zQarg = sqlite3_mprintf("%Q", azArg[1]);
  6589         -        if( strchr(azArg[1], '.') ){
  6590         -          appendText(&sSelect, "lower(printf('%s.%s',sname,tbl_name))", 0);
  6591         -        }else{
  6592         -          appendText(&sSelect, "lower(tbl_name)", 0);
  6593         -        }
  6594         -        appendText(&sSelect, strchr(azArg[1], '*') ? " GLOB " : " LIKE ", 0);
  6595         -        appendText(&sSelect, zQarg, 0);
  6596         -        appendText(&sSelect, " AND ", 0);
  6597         -        sqlite3_free(zQarg);
  6598         -      }
  6599         -      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
  6600         -                           " ORDER BY snum, rowid", 0);
  6601         -      rc = sqlite3_exec(p->db, sSelect.z, callback, &data, &zErrMsg);
  6602         -      freeText(&sSelect);
  6603         -    }
  6604         -    if( zErrMsg ){
  6605         -      utf8_printf(stderr,"Error: %s\n", zErrMsg);
  6606         -      sqlite3_free(zErrMsg);
  6607         -      rc = 1;
  6608         -    }else if( rc != SQLITE_OK ){
  6609         -      raw_printf(stderr,"Error: querying schema information\n");
  6610         -      rc = 1;
  6611         -    }else{
  6612         -      rc = 0;
  6613         -    }
  6614         -  }else
  6615         -
  6616         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  6617         -  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  6618         -    sqlite3SelectTrace = (int)integerValue(azArg[1]);
  6619         -  }else
  6620         -#endif
  6621         -
  6622         -#if defined(SQLITE_ENABLE_SESSION)
  6623         -  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  6624         -    OpenSession *pSession = &p->aSession[0];
  6625         -    char **azCmd = &azArg[1];
  6626         -    int iSes = 0;
  6627         -    int nCmd = nArg - 1;
  6628         -    int i;
  6629         -    if( nArg<=1 ) goto session_syntax_error;
  6630         -    open_db(p, 0);
  6631         -    if( nArg>=3 ){
  6632         -      for(iSes=0; iSes<p->nSession; iSes++){
  6633         -        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  6634         -      }
  6635         -      if( iSes<p->nSession ){
  6636         -        pSession = &p->aSession[iSes];
  6637         -        azCmd++;
  6638         -        nCmd--;
  6639         -      }else{
  6640         -        pSession = &p->aSession[0];
  6641         -        iSes = 0;
  6642         -      }
  6643         -    }
  6644         -
  6645         -    /* .session attach TABLE
  6646         -    ** Invoke the sqlite3session_attach() interface to attach a particular
  6647         -    ** table so that it is never filtered.
  6648         -    */
  6649         -    if( strcmp(azCmd[0],"attach")==0 ){
  6650         -      if( nCmd!=2 ) goto session_syntax_error;
  6651         -      if( pSession->p==0 ){
  6652         -        session_not_open:
  6653         -        raw_printf(stderr, "ERROR: No sessions are open\n");
  6654         -      }else{
  6655         -        rc = sqlite3session_attach(pSession->p, azCmd[1]);
  6656         -        if( rc ){
  6657         -          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  6658         -          rc = 0;
  6659         -        }
  6660         -      }
  6661         -    }else
  6662         -
  6663         -    /* .session changeset FILE
  6664         -    ** .session patchset FILE
  6665         -    ** Write a changeset or patchset into a file.  The file is overwritten.
  6666         -    */
  6667         -    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  6668         -      FILE *out = 0;
  6669         -      if( nCmd!=2 ) goto session_syntax_error;
  6670         -      if( pSession->p==0 ) goto session_not_open;
  6671         -      out = fopen(azCmd[1], "wb");
  6672         -      if( out==0 ){
  6673         -        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
  6674         -      }else{
  6675         -        int szChng;
  6676         -        void *pChng;
  6677         -        if( azCmd[0][0]=='c' ){
  6678         -          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  6679         -        }else{
  6680         -          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  6681         -        }
  6682         -        if( rc ){
  6683         -          printf("Error: error code %d\n", rc);
  6684         -          rc = 0;
  6685         -        }
  6686         -        if( pChng
  6687         -          && fwrite(pChng, szChng, 1, out)!=1 ){
  6688         -          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  6689         -                  szChng);
  6690         -        }
  6691         -        sqlite3_free(pChng);
  6692         -        fclose(out);
  6693         -      }
  6694         -    }else
  6695         -
  6696         -    /* .session close
  6697         -    ** Close the identified session
  6698         -    */
  6699         -    if( strcmp(azCmd[0], "close")==0 ){
  6700         -      if( nCmd!=1 ) goto session_syntax_error;
  6701         -      if( p->nSession ){
  6702         -        session_close(pSession);
  6703         -        p->aSession[iSes] = p->aSession[--p->nSession];
  6704         -      }
  6705         -    }else
  6706         -
  6707         -    /* .session enable ?BOOLEAN?
  6708         -    ** Query or set the enable flag
  6709         -    */
  6710         -    if( strcmp(azCmd[0], "enable")==0 ){
  6711         -      int ii;
  6712         -      if( nCmd>2 ) goto session_syntax_error;
  6713         -      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  6714         -      if( p->nSession ){
  6715         -        ii = sqlite3session_enable(pSession->p, ii);
  6716         -        utf8_printf(p->out, "session %s enable flag = %d\n",
  6717         -                    pSession->zName, ii);
  6718         -      }
  6719         -    }else
  6720         -
  6721         -    /* .session filter GLOB ....
  6722         -    ** Set a list of GLOB patterns of table names to be excluded.
  6723         -    */
  6724         -    if( strcmp(azCmd[0], "filter")==0 ){
  6725         -      int ii, nByte;
  6726         -      if( nCmd<2 ) goto session_syntax_error;
  6727         -      if( p->nSession ){
  6728         -        for(ii=0; ii<pSession->nFilter; ii++){
  6729         -          sqlite3_free(pSession->azFilter[ii]);
  6730         -        }
  6731         -        sqlite3_free(pSession->azFilter);
  6732         -        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  6733         -        pSession->azFilter = sqlite3_malloc( nByte );
  6734         -        if( pSession->azFilter==0 ){
  6735         -          raw_printf(stderr, "Error: out or memory\n");
  6736         -          exit(1);
  6737         -        }
  6738         -        for(ii=1; ii<nCmd; ii++){
  6739         -          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  6740         -        }
  6741         -        pSession->nFilter = ii-1;
  6742         -      }
  6743         -    }else
  6744         -
  6745         -    /* .session indirect ?BOOLEAN?
  6746         -    ** Query or set the indirect flag
  6747         -    */
  6748         -    if( strcmp(azCmd[0], "indirect")==0 ){
  6749         -      int ii;
  6750         -      if( nCmd>2 ) goto session_syntax_error;
  6751         -      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  6752         -      if( p->nSession ){
  6753         -        ii = sqlite3session_indirect(pSession->p, ii);
  6754         -        utf8_printf(p->out, "session %s indirect flag = %d\n",
  6755         -                    pSession->zName, ii);
  6756         -      }
  6757         -    }else
  6758         -
  6759         -    /* .session isempty
  6760         -    ** Determine if the session is empty
  6761         -    */
  6762         -    if( strcmp(azCmd[0], "isempty")==0 ){
  6763         -      int ii;
  6764         -      if( nCmd!=1 ) goto session_syntax_error;
  6765         -      if( p->nSession ){
  6766         -        ii = sqlite3session_isempty(pSession->p);
  6767         -        utf8_printf(p->out, "session %s isempty flag = %d\n",
  6768         -                    pSession->zName, ii);
  6769         -      }
  6770         -    }else
  6771         -
  6772         -    /* .session list
  6773         -    ** List all currently open sessions
  6774         -    */
  6775         -    if( strcmp(azCmd[0],"list")==0 ){
  6776         -      for(i=0; i<p->nSession; i++){
  6777         -        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  6778         -      }
  6779         -    }else
  6780         -
  6781         -    /* .session open DB NAME
  6782         -    ** Open a new session called NAME on the attached database DB.
  6783         -    ** DB is normally "main".
  6784         -    */
  6785         -    if( strcmp(azCmd[0],"open")==0 ){
  6786         -      char *zName;
  6787         -      if( nCmd!=3 ) goto session_syntax_error;
  6788         -      zName = azCmd[2];
  6789         -      if( zName[0]==0 ) goto session_syntax_error;
  6790         -      for(i=0; i<p->nSession; i++){
  6791         -        if( strcmp(p->aSession[i].zName,zName)==0 ){
  6792         -          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  6793         -          goto meta_command_exit;
  6794         -        }
  6795         -      }
  6796         -      if( p->nSession>=ArraySize(p->aSession) ){
  6797         -        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  6798         -        goto meta_command_exit;
  6799         -      }
  6800         -      pSession = &p->aSession[p->nSession];
  6801         -      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  6802         -      if( rc ){
  6803         -        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  6804         -        rc = 0;
  6805         -        goto meta_command_exit;
  6806         -      }
  6807         -      pSession->nFilter = 0;
  6808         -      sqlite3session_table_filter(pSession->p, session_filter, pSession);
  6809         -      p->nSession++;
  6810         -      pSession->zName = sqlite3_mprintf("%s", zName);
  6811         -    }else
  6812         -    /* If no command name matches, show a syntax error */
  6813         -    session_syntax_error:
  6814         -    session_help(p);
  6815         -  }else
  6816         -#endif
  6817         -
  6818         -#ifdef SQLITE_DEBUG
  6819         -  /* Undocumented commands for internal testing.  Subject to change
  6820         -  ** without notice. */
  6821         -  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  6822         -    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  6823         -      int i, v;
  6824         -      for(i=1; i<nArg; i++){
  6825         -        v = booleanValue(azArg[i]);
  6826         -        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  6827         -      }
  6828         -    }
  6829         -    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  6830         -      int i; sqlite3_int64 v;
  6831         -      for(i=1; i<nArg; i++){
  6832         -        char zBuf[200];
  6833         -        v = integerValue(azArg[i]);
  6834         -        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  6835         -        utf8_printf(p->out, "%s", zBuf);
  6836         -      }
  6837         -    }
  6838         -  }else
  6839         -#endif
  6840         -
  6841         -  if( c=='s' && n>=4 && strncmp(azArg[0],"selftest",n)==0 ){
  6842         -    int bIsInit = 0;         /* True to initialize the SELFTEST table */
  6843         -    int bVerbose = 0;        /* Verbose output */
  6844         -    int bSelftestExists;     /* True if SELFTEST already exists */
  6845         -    int i, k;                /* Loop counters */
  6846         -    int nTest = 0;           /* Number of tests runs */
  6847         -    int nErr = 0;            /* Number of errors seen */
  6848         -    ShellText str;           /* Answer for a query */
  6849         -    sqlite3_stmt *pStmt = 0; /* Query against the SELFTEST table */
  6850         -
  6851         -    open_db(p,0);
  6852         -    for(i=1; i<nArg; i++){
  6853         -      const char *z = azArg[i];
  6854         -      if( z[0]=='-' && z[1]=='-' ) z++;
  6855         -      if( strcmp(z,"-init")==0 ){
  6856         -        bIsInit = 1;
  6857         -      }else
  6858         -      if( strcmp(z,"-v")==0 ){
  6859         -        bVerbose++;
  6860         -      }else
  6861         -      {
  6862         -        utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  6863         -                    azArg[i], azArg[0]);
  6864         -        raw_printf(stderr, "Should be one of: --init -v\n");
  6865         -        rc = 1;
  6866         -        goto meta_command_exit;
  6867         -      }
  6868         -    }
  6869         -    if( sqlite3_table_column_metadata(p->db,"main","selftest",0,0,0,0,0,0)
  6870         -           != SQLITE_OK ){
  6871         -      bSelftestExists = 0;
  6872         -    }else{
  6873         -      bSelftestExists = 1;
  6874         -    }
  6875         -    if( bIsInit ){
  6876         -      createSelftestTable(p);
  6877         -      bSelftestExists = 1;
  6878         -    }
  6879         -    initText(&str);
  6880         -    appendText(&str, "x", 0);
  6881         -    for(k=bSelftestExists; k>=0; k--){
  6882         -      if( k==1 ){
  6883         -        rc = sqlite3_prepare_v2(p->db,
  6884         -            "SELECT tno,op,cmd,ans FROM selftest ORDER BY tno",
  6885         -            -1, &pStmt, 0);
  6886         -      }else{
  6887         -        rc = sqlite3_prepare_v2(p->db,
  6888         -          "VALUES(0,'memo','Missing SELFTEST table - default checks only',''),"
  6889         -          "      (1,'run','PRAGMA integrity_check','ok')",
  6890         -          -1, &pStmt, 0);
  6891         -      }
  6892         -      if( rc ){
  6893         -        raw_printf(stderr, "Error querying the selftest table\n");
  6894         -        rc = 1;
  6895         -        sqlite3_finalize(pStmt);
  6896         -        goto meta_command_exit;
  6897         -      }
  6898         -      for(i=1; sqlite3_step(pStmt)==SQLITE_ROW; i++){
  6899         -        int tno = sqlite3_column_int(pStmt, 0);
  6900         -        const char *zOp = (const char*)sqlite3_column_text(pStmt, 1);
  6901         -        const char *zSql = (const char*)sqlite3_column_text(pStmt, 2);
  6902         -        const char *zAns = (const char*)sqlite3_column_text(pStmt, 3);
  6903         -
  6904         -        k = 0;
  6905         -        if( bVerbose>0 ){
  6906         -          char *zQuote = sqlite3_mprintf("%q", zSql);
  6907         -          printf("%d: %s %s\n", tno, zOp, zSql);
  6908         -          sqlite3_free(zQuote);
  6909         -        }
  6910         -        if( strcmp(zOp,"memo")==0 ){
  6911         -          utf8_printf(p->out, "%s\n", zSql);
  6912         -        }else
  6913         -        if( strcmp(zOp,"run")==0 ){
  6914         -          char *zErrMsg = 0;
  6915         -          str.n = 0;
  6916         -          str.z[0] = 0;
  6917         -          rc = sqlite3_exec(p->db, zSql, captureOutputCallback, &str, &zErrMsg);
  6918         -          nTest++;
  6919         -          if( bVerbose ){
  6920         -            utf8_printf(p->out, "Result: %s\n", str.z);
  6921         -          }
  6922         -          if( rc || zErrMsg ){
  6923         -            nErr++;
  6924         -            rc = 1;
  6925         -            utf8_printf(p->out, "%d: error-code-%d: %s\n", tno, rc, zErrMsg);
  6926         -            sqlite3_free(zErrMsg);
  6927         -          }else if( strcmp(zAns,str.z)!=0 ){
  6928         -            nErr++;
  6929         -            rc = 1;
  6930         -            utf8_printf(p->out, "%d: Expected: [%s]\n", tno, zAns);
  6931         -            utf8_printf(p->out, "%d:      Got: [%s]\n", tno, str.z);
  6932         -          }
  6933         -        }else
  6934         -        {
  6935         -          utf8_printf(stderr,
  6936         -            "Unknown operation \"%s\" on selftest line %d\n", zOp, tno);
  6937         -          rc = 1;
  6938         -          break;
  6939         -        }
  6940         -      } /* End loop over rows of content from SELFTEST */
  6941         -      sqlite3_finalize(pStmt);
  6942         -    } /* End loop over k */
  6943         -    freeText(&str);
  6944         -    utf8_printf(p->out, "%d errors out of %d tests\n", nErr, nTest);
  6945         -  }else
  6946         -
  6947         -  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  6948         -    if( nArg<2 || nArg>3 ){
  6949         -      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  6950         -      rc = 1;
  6951         -    }
  6952         -    if( nArg>=2 ){
  6953         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  6954         -                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  6955         -    }
  6956         -    if( nArg>=3 ){
  6957         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  6958         -                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  6959         -    }
  6960         -  }else
  6961         -
  6962         -  if( c=='s' && n>=4 && strncmp(azArg[0],"sha3sum",n)==0 ){
  6963         -    const char *zLike = 0;   /* Which table to checksum. 0 means everything */
  6964         -    int i;                   /* Loop counter */
  6965         -    int bSchema = 0;         /* Also hash the schema */
  6966         -    int bSeparate = 0;       /* Hash each table separately */
  6967         -    int iSize = 224;         /* Hash algorithm to use */
  6968         -    int bDebug = 0;          /* Only show the query that would have run */
  6969         -    sqlite3_stmt *pStmt;     /* For querying tables names */
  6970         -    char *zSql;              /* SQL to be run */
  6971         -    char *zSep;              /* Separator */
  6972         -    ShellText sSql;          /* Complete SQL for the query to run the hash */
  6973         -    ShellText sQuery;        /* Set of queries used to read all content */
  6974         -    open_db(p, 0);
  6975         -    for(i=1; i<nArg; i++){
  6976         -      const char *z = azArg[i];
  6977         -      if( z[0]=='-' ){
  6978         -        z++;
  6979         -        if( z[0]=='-' ) z++;
  6980         -        if( strcmp(z,"schema")==0 ){
  6981         -          bSchema = 1;
  6982         -        }else
  6983         -        if( strcmp(z,"sha3-224")==0 || strcmp(z,"sha3-256")==0
  6984         -         || strcmp(z,"sha3-384")==0 || strcmp(z,"sha3-512")==0
  6985         -        ){
  6986         -          iSize = atoi(&z[5]);
  6987         -        }else
  6988         -        if( strcmp(z,"debug")==0 ){
  6989         -          bDebug = 1;
  6990         -        }else
  6991         -        {
  6992         -          utf8_printf(stderr, "Unknown option \"%s\" on \"%s\"\n",
  6993         -                      azArg[i], azArg[0]);
  6994         -          raw_printf(stderr, "Should be one of: --schema"
  6995         -                             " --sha3-224 --sha3-255 --sha3-384 --sha3-512\n");
  6996         -          rc = 1;
  6997         -          goto meta_command_exit;
  6998         -        }
  6999         -      }else if( zLike ){
  7000         -        raw_printf(stderr, "Usage: .sha3sum ?OPTIONS? ?LIKE-PATTERN?\n");
  7001         -        rc = 1;
  7002         -        goto meta_command_exit;
  7003         -      }else{
  7004         -        zLike = z;
  7005         -        bSeparate = 1;
  7006         -        if( sqlite3_strlike("sqlite_%", zLike, 0)==0 ) bSchema = 1;
  7007         -      }
  7008         -    }
  7009         -    if( bSchema ){
  7010         -      zSql = "SELECT lower(name) FROM sqlite_master"
  7011         -             " WHERE type='table' AND coalesce(rootpage,0)>1"
  7012         -             " UNION ALL SELECT 'sqlite_master'"
  7013         -             " ORDER BY 1 collate nocase";
  7014         -    }else{
  7015         -      zSql = "SELECT lower(name) FROM sqlite_master"
  7016         -             " WHERE type='table' AND coalesce(rootpage,0)>1"
  7017         -             " AND name NOT LIKE 'sqlite_%'"
  7018         -             " ORDER BY 1 collate nocase";
  7019         -    }
  7020         -    sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  7021         -    initText(&sQuery);
  7022         -    initText(&sSql);
  7023         -    appendText(&sSql, "WITH [sha3sum$query](a,b) AS(",0);
  7024         -    zSep = "VALUES(";
  7025         -    while( SQLITE_ROW==sqlite3_step(pStmt) ){
  7026         -      const char *zTab = (const char*)sqlite3_column_text(pStmt,0);
  7027         -      if( zLike && sqlite3_strlike(zLike, zTab, 0)!=0 ) continue;
  7028         -      if( strncmp(zTab, "sqlite_",7)!=0 ){
  7029         -        appendText(&sQuery,"SELECT * FROM ", 0);
  7030         -        appendText(&sQuery,zTab,'"');
  7031         -        appendText(&sQuery," NOT INDEXED;", 0);
  7032         -      }else if( strcmp(zTab, "sqlite_master")==0 ){
  7033         -        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
  7034         -                           " ORDER BY name;", 0);
  7035         -      }else if( strcmp(zTab, "sqlite_sequence")==0 ){
  7036         -        appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
  7037         -                           " ORDER BY name;", 0);
  7038         -      }else if( strcmp(zTab, "sqlite_stat1")==0 ){
  7039         -        appendText(&sQuery,"SELECT tbl,idx,stat FROM sqlite_stat1"
  7040         -                           " ORDER BY tbl,idx;", 0);
  7041         -      }else if( strcmp(zTab, "sqlite_stat3")==0
  7042         -             || strcmp(zTab, "sqlite_stat4")==0 ){
  7043         -        appendText(&sQuery, "SELECT * FROM ", 0);
  7044         -        appendText(&sQuery, zTab, 0);
  7045         -        appendText(&sQuery, " ORDER BY tbl, idx, rowid;\n", 0);
  7046         -      }
  7047         -      appendText(&sSql, zSep, 0);
  7048         -      appendText(&sSql, sQuery.z, '\'');
  7049         -      sQuery.n = 0;
  7050         -      appendText(&sSql, ",", 0);
  7051         -      appendText(&sSql, zTab, '\'');
  7052         -      zSep = "),(";
  7053         -    }
  7054         -    sqlite3_finalize(pStmt);
  7055         -    if( bSeparate ){
  7056         -      zSql = sqlite3_mprintf(
  7057         -          "%s))"
  7058         -          " SELECT lower(hex(sha3_query(a,%d))) AS hash, b AS label"
  7059         -          "   FROM [sha3sum$query]",
  7060         -          sSql.z, iSize);
  7061         -    }else{
  7062         -      zSql = sqlite3_mprintf(
  7063         -          "%s))"
  7064         -          " SELECT lower(hex(sha3_query(group_concat(a,''),%d))) AS hash"
  7065         -          "   FROM [sha3sum$query]",
  7066         -          sSql.z, iSize);
  7067         -    }
  7068         -    freeText(&sQuery);
  7069         -    freeText(&sSql);
  7070         -    if( bDebug ){
  7071         -      utf8_printf(p->out, "%s\n", zSql);
  7072         -    }else{
  7073         -      shell_exec(p->db, zSql, shell_callback, p, 0);
  7074         -    }
  7075         -    sqlite3_free(zSql);
  7076         -  }else
  7077         -
  7078         -  if( c=='s'
  7079         -   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  7080         -  ){
  7081         -    char *zCmd;
  7082         -    int i, x;
  7083         -    if( nArg<2 ){
  7084         -      raw_printf(stderr, "Usage: .system COMMAND\n");
  7085         -      rc = 1;
  7086         -      goto meta_command_exit;
  7087         -    }
  7088         -    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  7089         -    for(i=2; i<nArg; i++){
  7090         -      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  7091         -                             zCmd, azArg[i]);
  7092         -    }
  7093         -    x = system(zCmd);
  7094         -    sqlite3_free(zCmd);
  7095         -    if( x ) raw_printf(stderr, "System command returns %d\n", x);
  7096         -  }else
  7097         -
  7098         -  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  7099         -    static const char *azBool[] = { "off", "on", "full", "unk" };
  7100         -    int i;
  7101         -    if( nArg!=1 ){
  7102         -      raw_printf(stderr, "Usage: .show\n");
  7103         -      rc = 1;
  7104         -      goto meta_command_exit;
  7105         -    }
  7106         -    utf8_printf(p->out, "%12.12s: %s\n","echo",
  7107         -                                  azBool[ShellHasFlag(p, SHFLG_Echo)]);
  7108         -    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  7109         -    utf8_printf(p->out, "%12.12s: %s\n","explain",
  7110         -         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  7111         -    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  7112         -    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  7113         -    utf8_printf(p->out, "%12.12s: ", "nullvalue");
  7114         -      output_c_string(p->out, p->nullValue);
  7115         -      raw_printf(p->out, "\n");
  7116         -    utf8_printf(p->out,"%12.12s: %s\n","output",
  7117         -            strlen30(p->outfile) ? p->outfile : "stdout");
  7118         -    utf8_printf(p->out,"%12.12s: ", "colseparator");
  7119         -      output_c_string(p->out, p->colSeparator);
  7120         -      raw_printf(p->out, "\n");
  7121         -    utf8_printf(p->out,"%12.12s: ", "rowseparator");
  7122         -      output_c_string(p->out, p->rowSeparator);
  7123         -      raw_printf(p->out, "\n");
  7124         -    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  7125         -    utf8_printf(p->out, "%12.12s: ", "width");
  7126         -    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  7127         -      raw_printf(p->out, "%d ", p->colWidth[i]);
  7128         -    }
  7129         -    raw_printf(p->out, "\n");
  7130         -    utf8_printf(p->out, "%12.12s: %s\n", "filename",
  7131         -                p->zDbFilename ? p->zDbFilename : "");
  7132         -  }else
  7133         -
  7134         -  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  7135         -    if( nArg==2 ){
  7136         -      p->statsOn = booleanValue(azArg[1]);
  7137         -    }else if( nArg==1 ){
  7138         -      display_stats(p->db, p, 0);
  7139         -    }else{
  7140         -      raw_printf(stderr, "Usage: .stats ?on|off?\n");
  7141         -      rc = 1;
  7142         -    }
  7143         -  }else
  7144         -
  7145         -  if( (c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0)
  7146         -   || (c=='i' && (strncmp(azArg[0], "indices", n)==0
  7147         -                 || strncmp(azArg[0], "indexes", n)==0) )
  7148         -  ){
  7149         -    sqlite3_stmt *pStmt;
  7150         -    char **azResult;
  7151         -    int nRow, nAlloc;
  7152         -    int ii;
  7153         -    ShellText s;
  7154         -    initText(&s);
  7155         -    open_db(p, 0);
  7156         -    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  7157         -    if( rc ) return shellDatabaseError(p->db);
  7158         -
  7159         -    if( nArg>2 && c=='i' ){
  7160         -      /* It is an historical accident that the .indexes command shows an error
  7161         -      ** when called with the wrong number of arguments whereas the .tables
  7162         -      ** command does not. */
  7163         -      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  7164         -      rc = 1;
  7165         -      goto meta_command_exit;
  7166         -    }
  7167         -    for(ii=0; sqlite3_step(pStmt)==SQLITE_ROW; ii++){
  7168         -      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  7169         -      if( zDbName==0 ) continue;
  7170         -      if( s.z && s.z[0] ) appendText(&s, " UNION ALL ", 0);
  7171         -      if( sqlite3_stricmp(zDbName, "main")==0 ){
  7172         -        appendText(&s, "SELECT name FROM ", 0);
  7173         -      }else{
  7174         -        appendText(&s, "SELECT ", 0);
  7175         -        appendText(&s, zDbName, '\'');
  7176         -        appendText(&s, "||'.'||name FROM ", 0);
  7177         -      }
  7178         -      appendText(&s, zDbName, '"');
  7179         -      appendText(&s, ".sqlite_master ", 0);
  7180         -      if( c=='t' ){
  7181         -        appendText(&s," WHERE type IN ('table','view')"
  7182         -                      "   AND name NOT LIKE 'sqlite_%'"
  7183         -                      "   AND name LIKE ?1", 0);
  7184         -      }else{
  7185         -        appendText(&s," WHERE type='index'"
  7186         -                      "   AND tbl_name LIKE ?1", 0);
  7187         -      }
  7188         -    }
  7189         -    rc = sqlite3_finalize(pStmt);
  7190         -    appendText(&s, " ORDER BY 1", 0);
  7191         -    rc = sqlite3_prepare_v2(p->db, s.z, -1, &pStmt, 0);
  7192         -    freeText(&s);
  7193         -    if( rc ) return shellDatabaseError(p->db);
  7194         -
  7195         -    /* Run the SQL statement prepared by the above block. Store the results
  7196         -    ** as an array of nul-terminated strings in azResult[].  */
  7197         -    nRow = nAlloc = 0;
  7198         -    azResult = 0;
  7199         -    if( nArg>1 ){
  7200         -      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  7201         -    }else{
  7202         -      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  7203         -    }
  7204         -    while( sqlite3_step(pStmt)==SQLITE_ROW ){
  7205         -      if( nRow>=nAlloc ){
  7206         -        char **azNew;
  7207         -        int n2 = nAlloc*2 + 10;
  7208         -        azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2);
  7209         -        if( azNew==0 ){
  7210         -          rc = shellNomemError();
  7211         -          break;
  7212         -        }
  7213         -        nAlloc = n2;
  7214         -        azResult = azNew;
  7215         -      }
  7216         -      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  7217         -      if( 0==azResult[nRow] ){
  7218         -        rc = shellNomemError();
  7219         -        break;
  7220         -      }
  7221         -      nRow++;
  7222         -    }
  7223         -    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  7224         -      rc = shellDatabaseError(p->db);
  7225         -    }
  7226         -
  7227         -    /* Pretty-print the contents of array azResult[] to the output */
  7228         -    if( rc==0 && nRow>0 ){
  7229         -      int len, maxlen = 0;
  7230         -      int i, j;
  7231         -      int nPrintCol, nPrintRow;
  7232         -      for(i=0; i<nRow; i++){
  7233         -        len = strlen30(azResult[i]);
  7234         -        if( len>maxlen ) maxlen = len;
  7235         -      }
  7236         -      nPrintCol = 80/(maxlen+2);
  7237         -      if( nPrintCol<1 ) nPrintCol = 1;
  7238         -      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  7239         -      for(i=0; i<nPrintRow; i++){
  7240         -        for(j=i; j<nRow; j+=nPrintRow){
  7241         -          char *zSp = j<nPrintRow ? "" : "  ";
  7242         -          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  7243         -                      azResult[j] ? azResult[j]:"");
  7244         -        }
  7245         -        raw_printf(p->out, "\n");
  7246         -      }
  7247         -    }
  7248         -
  7249         -    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  7250         -    sqlite3_free(azResult);
  7251         -  }else
  7252         -
  7253         -  /* Begin redirecting output to the file "testcase-out.txt" */
  7254         -  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  7255         -    output_reset(p);
  7256         -    p->out = output_file_open("testcase-out.txt");
  7257         -    if( p->out==0 ){
  7258         -      raw_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  7259         -    }
  7260         -    if( nArg>=2 ){
  7261         -      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  7262         -    }else{
  7263         -      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  7264         -    }
  7265         -  }else
  7266         -
  7267         -#ifndef SQLITE_UNTESTABLE
  7268         -  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  7269         -    static const struct {
  7270         -       const char *zCtrlName;   /* Name of a test-control option */
  7271         -       int ctrlCode;            /* Integer code for that option */
  7272         -    } aCtrl[] = {
  7273         -      { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
  7274         -      { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
  7275         -      { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
  7276         -      { "bitvec_test",           SQLITE_TESTCTRL_BITVEC_TEST            },
  7277         -      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
  7278         -      { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
  7279         -      { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
  7280         -      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
  7281         -      { "always",                SQLITE_TESTCTRL_ALWAYS                 },
  7282         -      { "reserve",               SQLITE_TESTCTRL_RESERVE                },
  7283         -      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
  7284         -      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
  7285         -      { "byteorder",             SQLITE_TESTCTRL_BYTEORDER              },
  7286         -      { "never_corrupt",         SQLITE_TESTCTRL_NEVER_CORRUPT          },
  7287         -      { "imposter",              SQLITE_TESTCTRL_IMPOSTER               },
  7288         -    };
  7289         -    int testctrl = -1;
  7290         -    int rc2 = 0;
  7291         -    int i, n2;
  7292         -    open_db(p, 0);
  7293         -
  7294         -    /* convert testctrl text option to value. allow any unique prefix
  7295         -    ** of the option name, or a numerical value. */
  7296         -    n2 = strlen30(azArg[1]);
  7297         -    for(i=0; i<ArraySize(aCtrl); i++){
  7298         -      if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
  7299         -        if( testctrl<0 ){
  7300         -          testctrl = aCtrl[i].ctrlCode;
  7301         -        }else{
  7302         -          utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  7303         -          testctrl = -1;
  7304         -          break;
  7305         -        }
  7306         -      }
  7307         -    }
  7308         -    if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
  7309         -    if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  7310         -      utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  7311         -    }else{
  7312         -      switch(testctrl){
  7313         -
  7314         -        /* sqlite3_test_control(int, db, int) */
  7315         -        case SQLITE_TESTCTRL_OPTIMIZATIONS:
  7316         -        case SQLITE_TESTCTRL_RESERVE:
  7317         -          if( nArg==3 ){
  7318         -            int opt = (int)strtol(azArg[2], 0, 0);
  7319         -            rc2 = sqlite3_test_control(testctrl, p->db, opt);
  7320         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7321         -          } else {
  7322         -            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  7323         -                    azArg[1]);
  7324         -          }
  7325         -          break;
  7326         -
  7327         -        /* sqlite3_test_control(int) */
  7328         -        case SQLITE_TESTCTRL_PRNG_SAVE:
  7329         -        case SQLITE_TESTCTRL_PRNG_RESTORE:
  7330         -        case SQLITE_TESTCTRL_PRNG_RESET:
  7331         -        case SQLITE_TESTCTRL_BYTEORDER:
  7332         -          if( nArg==2 ){
  7333         -            rc2 = sqlite3_test_control(testctrl);
  7334         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7335         -          } else {
  7336         -            utf8_printf(stderr,"Error: testctrl %s takes no options\n",
  7337         -                        azArg[1]);
  7338         -          }
  7339         -          break;
  7340         -
  7341         -        /* sqlite3_test_control(int, uint) */
  7342         -        case SQLITE_TESTCTRL_PENDING_BYTE:
  7343         -          if( nArg==3 ){
  7344         -            unsigned int opt = (unsigned int)integerValue(azArg[2]);
  7345         -            rc2 = sqlite3_test_control(testctrl, opt);
  7346         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7347         -          } else {
  7348         -            utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
  7349         -                           " int option\n", azArg[1]);
  7350         -          }
  7351         -          break;
  7352         -
  7353         -        /* sqlite3_test_control(int, int) */
  7354         -        case SQLITE_TESTCTRL_ASSERT:
  7355         -        case SQLITE_TESTCTRL_ALWAYS:
  7356         -        case SQLITE_TESTCTRL_NEVER_CORRUPT:
  7357         -          if( nArg==3 ){
  7358         -            int opt = booleanValue(azArg[2]);
  7359         -            rc2 = sqlite3_test_control(testctrl, opt);
  7360         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7361         -          } else {
  7362         -            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  7363         -                            azArg[1]);
  7364         -          }
  7365         -          break;
  7366         -
  7367         -        /* sqlite3_test_control(int, char *) */
  7368         -#ifdef SQLITE_N_KEYWORD
  7369         -        case SQLITE_TESTCTRL_ISKEYWORD:
  7370         -          if( nArg==3 ){
  7371         -            const char *opt = azArg[2];
  7372         -            rc2 = sqlite3_test_control(testctrl, opt);
  7373         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7374         -          } else {
  7375         -            utf8_printf(stderr,
  7376         -                        "Error: testctrl %s takes a single char * option\n",
  7377         -                        azArg[1]);
  7378         -          }
  7379         -          break;
  7380         -#endif
  7381         -
  7382         -        case SQLITE_TESTCTRL_IMPOSTER:
  7383         -          if( nArg==5 ){
  7384         -            rc2 = sqlite3_test_control(testctrl, p->db,
  7385         -                          azArg[2],
  7386         -                          integerValue(azArg[3]),
  7387         -                          integerValue(azArg[4]));
  7388         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  7389         -          }else{
  7390         -            raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
  7391         -          }
  7392         -          break;
  7393         -
  7394         -        case SQLITE_TESTCTRL_BITVEC_TEST:
  7395         -        case SQLITE_TESTCTRL_FAULT_INSTALL:
  7396         -        case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  7397         -        default:
  7398         -          utf8_printf(stderr,
  7399         -                      "Error: CLI support for testctrl %s not implemented\n",
  7400         -                      azArg[1]);
  7401         -          break;
  7402         -      }
  7403         -    }
  7404         -  }else
  7405         -#endif /* !defined(SQLITE_UNTESTABLE) */
  7406         -
  7407         -  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  7408         -    open_db(p, 0);
  7409         -    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  7410         -  }else
  7411         -
  7412         -  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  7413         -    if( nArg==2 ){
  7414         -      enableTimer = booleanValue(azArg[1]);
  7415         -      if( enableTimer && !HAS_TIMER ){
  7416         -        raw_printf(stderr, "Error: timer not available on this system.\n");
  7417         -        enableTimer = 0;
  7418         -      }
  7419         -    }else{
  7420         -      raw_printf(stderr, "Usage: .timer on|off\n");
  7421         -      rc = 1;
  7422         -    }
  7423         -  }else
  7424         -
  7425         -  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  7426         -    open_db(p, 0);
  7427         -    if( nArg!=2 ){
  7428         -      raw_printf(stderr, "Usage: .trace FILE|off\n");
  7429         -      rc = 1;
  7430         -      goto meta_command_exit;
  7431         -    }
  7432         -    output_file_close(p->traceOut);
  7433         -    p->traceOut = output_file_open(azArg[1]);
  7434         -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  7435         -    if( p->traceOut==0 ){
  7436         -      sqlite3_trace_v2(p->db, 0, 0, 0);
  7437         -    }else{
  7438         -      sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
  7439         -    }
  7440         -#endif
  7441         -  }else
  7442         -
  7443         -#if SQLITE_USER_AUTHENTICATION
  7444         -  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  7445         -    if( nArg<2 ){
  7446         -      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  7447         -      rc = 1;
  7448         -      goto meta_command_exit;
  7449         -    }
  7450         -    open_db(p, 0);
  7451         -    if( strcmp(azArg[1],"login")==0 ){
  7452         -      if( nArg!=4 ){
  7453         -        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  7454         -        rc = 1;
  7455         -        goto meta_command_exit;
  7456         -      }
  7457         -      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  7458         -                                    (int)strlen(azArg[3]));
  7459         -      if( rc ){
  7460         -        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  7461         -        rc = 1;
  7462         -      }
  7463         -    }else if( strcmp(azArg[1],"add")==0 ){
  7464         -      if( nArg!=5 ){
  7465         -        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  7466         -        rc = 1;
  7467         -        goto meta_command_exit;
  7468         -      }
  7469         -      rc = sqlite3_user_add(p->db, azArg[2],
  7470         -                            azArg[3], (int)strlen(azArg[3]),
  7471         -                            booleanValue(azArg[4]));
  7472         -      if( rc ){
  7473         -        raw_printf(stderr, "User-Add failed: %d\n", rc);
  7474         -        rc = 1;
  7475         -      }
  7476         -    }else if( strcmp(azArg[1],"edit")==0 ){
  7477         -      if( nArg!=5 ){
  7478         -        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  7479         -        rc = 1;
  7480         -        goto meta_command_exit;
  7481         -      }
  7482         -      rc = sqlite3_user_change(p->db, azArg[2],
  7483         -                              azArg[3], (int)strlen(azArg[3]),
  7484         -                              booleanValue(azArg[4]));
  7485         -      if( rc ){
  7486         -        raw_printf(stderr, "User-Edit failed: %d\n", rc);
  7487         -        rc = 1;
  7488         -      }
  7489         -    }else if( strcmp(azArg[1],"delete")==0 ){
  7490         -      if( nArg!=3 ){
  7491         -        raw_printf(stderr, "Usage: .user delete USER\n");
  7492         -        rc = 1;
  7493         -        goto meta_command_exit;
  7494         -      }
  7495         -      rc = sqlite3_user_delete(p->db, azArg[2]);
  7496         -      if( rc ){
  7497         -        raw_printf(stderr, "User-Delete failed: %d\n", rc);
  7498         -        rc = 1;
  7499         -      }
  7500         -    }else{
  7501         -      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  7502         -      rc = 1;
  7503         -      goto meta_command_exit;
  7504         -    }
  7505         -  }else
  7506         -#endif /* SQLITE_USER_AUTHENTICATION */
  7507         -
  7508         -  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  7509         -    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  7510         -        sqlite3_libversion(), sqlite3_sourceid());
  7511         -  }else
  7512         -
  7513         -  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  7514         -    const char *zDbName = nArg==2 ? azArg[1] : "main";
  7515         -    sqlite3_vfs *pVfs = 0;
  7516         -    if( p->db ){
  7517         -      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  7518         -      if( pVfs ){
  7519         -        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
  7520         -        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
  7521         -        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
  7522         -        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  7523         -      }
  7524         -    }
  7525         -  }else
  7526         -
  7527         -  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  7528         -    sqlite3_vfs *pVfs;
  7529         -    sqlite3_vfs *pCurrent = 0;
  7530         -    if( p->db ){
  7531         -      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  7532         -    }
  7533         -    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  7534         -      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
  7535         -           pVfs==pCurrent ? "  <--- CURRENT" : "");
  7536         -      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
  7537         -      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
  7538         -      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  7539         -      if( pVfs->pNext ){
  7540         -        raw_printf(p->out, "-----------------------------------\n");
  7541         -      }
  7542         -    }
  7543         -  }else
  7544         -
  7545         -  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  7546         -    const char *zDbName = nArg==2 ? azArg[1] : "main";
  7547         -    char *zVfsName = 0;
  7548         -    if( p->db ){
  7549         -      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  7550         -      if( zVfsName ){
  7551         -        utf8_printf(p->out, "%s\n", zVfsName);
  7552         -        sqlite3_free(zVfsName);
  7553         -      }
  7554         -    }
  7555         -  }else
  7556         -
  7557         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  7558         -  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  7559         -    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  7560         -  }else
  7561         -#endif
  7562         -
  7563         -  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  7564         -    int j;
  7565         -    assert( nArg<=ArraySize(azArg) );
  7566         -    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  7567         -      p->colWidth[j-1] = (int)integerValue(azArg[j]);
  7568         -    }
  7569         -  }else
  7570         -
  7571         -  {
  7572         -    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  7573         -      " \"%s\". Enter \".help\" for help\n", azArg[0]);
  7574         -    rc = 1;
  7575         -  }
  7576         -
  7577         -meta_command_exit:
  7578         -  if( p->outCount ){
  7579         -    p->outCount--;
  7580         -    if( p->outCount==0 ) output_reset(p);
  7581         -  }
  7582         -  return rc;
  7583         -}
  7584         -
  7585         -/*
  7586         -** Return TRUE if a semicolon occurs anywhere in the first N characters
  7587         -** of string z[].
  7588         -*/
  7589         -static int line_contains_semicolon(const char *z, int N){
  7590         -  int i;
  7591         -  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
  7592         -  return 0;
  7593         -}
  7594         -
  7595         -/*
  7596         -** Test to see if a line consists entirely of whitespace.
  7597         -*/
  7598         -static int _all_whitespace(const char *z){
  7599         -  for(; *z; z++){
  7600         -    if( IsSpace(z[0]) ) continue;
  7601         -    if( *z=='/' && z[1]=='*' ){
  7602         -      z += 2;
  7603         -      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  7604         -      if( *z==0 ) return 0;
  7605         -      z++;
  7606         -      continue;
  7607         -    }
  7608         -    if( *z=='-' && z[1]=='-' ){
  7609         -      z += 2;
  7610         -      while( *z && *z!='\n' ){ z++; }
  7611         -      if( *z==0 ) return 1;
  7612         -      continue;
  7613         -    }
  7614         -    return 0;
  7615         -  }
  7616         -  return 1;
  7617         -}
  7618         -
  7619         -/*
  7620         -** Return TRUE if the line typed in is an SQL command terminator other
  7621         -** than a semi-colon.  The SQL Server style "go" command is understood
  7622         -** as is the Oracle "/".
  7623         -*/
  7624         -static int line_is_command_terminator(const char *zLine){
  7625         -  while( IsSpace(zLine[0]) ){ zLine++; };
  7626         -  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  7627         -    return 1;  /* Oracle */
  7628         -  }
  7629         -  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  7630         -         && _all_whitespace(&zLine[2]) ){
  7631         -    return 1;  /* SQL Server */
  7632         -  }
  7633         -  return 0;
  7634         -}
  7635         -
  7636         -/*
  7637         -** Return true if zSql is a complete SQL statement.  Return false if it
  7638         -** ends in the middle of a string literal or C-style comment.
  7639         -*/
  7640         -static int line_is_complete(char *zSql, int nSql){
  7641         -  int rc;
  7642         -  if( zSql==0 ) return 1;
  7643         -  zSql[nSql] = ';';
  7644         -  zSql[nSql+1] = 0;
  7645         -  rc = sqlite3_complete(zSql);
  7646         -  zSql[nSql] = 0;
  7647         -  return rc;
  7648         -}
  7649         -
  7650         -/*
  7651         -** Run a single line of SQL
  7652         -*/
  7653         -static int runOneSqlLine(ShellState *p, char *zSql, FILE *in, int startline){
  7654         -  int rc;
  7655         -  char *zErrMsg = 0;
  7656         -
  7657         -  open_db(p, 0);
  7658         -  if( ShellHasFlag(p,SHFLG_Backslash) ) resolve_backslashes(zSql);
  7659         -  BEGIN_TIMER;
  7660         -  rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  7661         -  END_TIMER;
  7662         -  if( rc || zErrMsg ){
  7663         -    char zPrefix[100];
  7664         -    if( in!=0 || !stdin_is_interactive ){
  7665         -      sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  7666         -                       "Error: near line %d:", startline);
  7667         -    }else{
  7668         -      sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  7669         -    }
  7670         -    if( zErrMsg!=0 ){
  7671         -      utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  7672         -      sqlite3_free(zErrMsg);
  7673         -      zErrMsg = 0;
  7674         -    }else{
  7675         -      utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  7676         -    }
  7677         -    return 1;
  7678         -  }else if( ShellHasFlag(p, SHFLG_CountChanges) ){
  7679         -    raw_printf(p->out, "changes: %3d   total_changes: %d\n",
  7680         -            sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  7681         -  }
  7682         -  return 0;
  7683         -}
  7684         -
  7685         -
  7686         -/*
  7687         -** Read input from *in and process it.  If *in==0 then input
  7688         -** is interactive - the user is typing it it.  Otherwise, input
  7689         -** is coming from a file or device.  A prompt is issued and history
  7690         -** is saved only if input is interactive.  An interrupt signal will
  7691         -** cause this routine to exit immediately, unless input is interactive.
  7692         -**
  7693         -** Return the number of errors.
  7694         -*/
  7695         -static int process_input(ShellState *p, FILE *in){
  7696         -  char *zLine = 0;          /* A single input line */
  7697         -  char *zSql = 0;           /* Accumulated SQL text */
  7698         -  int nLine;                /* Length of current line */
  7699         -  int nSql = 0;             /* Bytes of zSql[] used */
  7700         -  int nAlloc = 0;           /* Allocated zSql[] space */
  7701         -  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
  7702         -  int rc;                   /* Error code */
  7703         -  int errCnt = 0;           /* Number of errors seen */
  7704         -  int lineno = 0;           /* Current line number */
  7705         -  int startline = 0;        /* Line number for start of current input */
  7706         -
  7707         -  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  7708         -    fflush(p->out);
  7709         -    zLine = one_input_line(in, zLine, nSql>0);
  7710         -    if( zLine==0 ){
  7711         -      /* End of input */
  7712         -      if( in==0 && stdin_is_interactive ) printf("\n");
  7713         -      break;
  7714         -    }
  7715         -    if( seenInterrupt ){
  7716         -      if( in!=0 ) break;
  7717         -      seenInterrupt = 0;
  7718         -    }
  7719         -    lineno++;
  7720         -    if( nSql==0 && _all_whitespace(zLine) ){
  7721         -      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  7722         -      continue;
  7723         -    }
  7724         -    if( zLine && zLine[0]=='.' && nSql==0 ){
  7725         -      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zLine);
  7726         -      rc = do_meta_command(zLine, p);
  7727         -      if( rc==2 ){ /* exit requested */
  7728         -        break;
  7729         -      }else if( rc ){
  7730         -        errCnt++;
  7731         -      }
  7732         -      continue;
  7733         -    }
  7734         -    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  7735         -      memcpy(zLine,";",2);
  7736         -    }
  7737         -    nLine = strlen30(zLine);
  7738         -    if( nSql+nLine+2>=nAlloc ){
  7739         -      nAlloc = nSql+nLine+100;
  7740         -      zSql = realloc(zSql, nAlloc);
  7741         -      if( zSql==0 ){
  7742         -        raw_printf(stderr, "Error: out of memory\n");
  7743         -        exit(1);
  7744         -      }
  7745         -    }
  7746         -    nSqlPrior = nSql;
  7747         -    if( nSql==0 ){
  7748         -      int i;
  7749         -      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  7750         -      assert( nAlloc>0 && zSql!=0 );
  7751         -      memcpy(zSql, zLine+i, nLine+1-i);
  7752         -      startline = lineno;
  7753         -      nSql = nLine-i;
  7754         -    }else{
  7755         -      zSql[nSql++] = '\n';
  7756         -      memcpy(zSql+nSql, zLine, nLine+1);
  7757         -      nSql += nLine;
  7758         -    }
  7759         -    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  7760         -                && sqlite3_complete(zSql) ){
  7761         -      errCnt += runOneSqlLine(p, zSql, in, startline);
  7762         -      nSql = 0;
  7763         -      if( p->outCount ){
  7764         -        output_reset(p);
  7765         -        p->outCount = 0;
  7766         -      }
  7767         -    }else if( nSql && _all_whitespace(zSql) ){
  7768         -      if( ShellHasFlag(p, SHFLG_Echo) ) printf("%s\n", zSql);
  7769         -      nSql = 0;
  7770         -    }
  7771         -  }
  7772         -  if( nSql && !_all_whitespace(zSql) ){
  7773         -    runOneSqlLine(p, zSql, in, startline);
  7774         -  }
  7775         -  free(zSql);
  7776         -  free(zLine);
  7777         -  return errCnt>0;
  7778         -}
  7779         -
  7780         -/*
  7781         -** Return a pathname which is the user's home directory.  A
  7782         -** 0 return indicates an error of some kind.
  7783         -*/
  7784         -static char *find_home_dir(int clearFlag){
  7785         -  static char *home_dir = NULL;
  7786         -  if( clearFlag ){
  7787         -    free(home_dir);
  7788         -    home_dir = 0;
  7789         -    return 0;
  7790         -  }
  7791         -  if( home_dir ) return home_dir;
  7792         -
  7793         -#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  7794         -     && !defined(__RTP__) && !defined(_WRS_KERNEL)
  7795         -  {
  7796         -    struct passwd *pwent;
  7797         -    uid_t uid = getuid();
  7798         -    if( (pwent=getpwuid(uid)) != NULL) {
  7799         -      home_dir = pwent->pw_dir;
  7800         -    }
  7801         -  }
  7802         -#endif
  7803         -
  7804         -#if defined(_WIN32_WCE)
  7805         -  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  7806         -   */
  7807         -  home_dir = "/";
  7808         -#else
  7809         -
  7810         -#if defined(_WIN32) || defined(WIN32)
  7811         -  if (!home_dir) {
  7812         -    home_dir = getenv("USERPROFILE");
  7813         -  }
  7814         -#endif
  7815         -
  7816         -  if (!home_dir) {
  7817         -    home_dir = getenv("HOME");
  7818         -  }
  7819         -
  7820         -#if defined(_WIN32) || defined(WIN32)
  7821         -  if (!home_dir) {
  7822         -    char *zDrive, *zPath;
  7823         -    int n;
  7824         -    zDrive = getenv("HOMEDRIVE");
  7825         -    zPath = getenv("HOMEPATH");
  7826         -    if( zDrive && zPath ){
  7827         -      n = strlen30(zDrive) + strlen30(zPath) + 1;
  7828         -      home_dir = malloc( n );
  7829         -      if( home_dir==0 ) return 0;
  7830         -      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  7831         -      return home_dir;
  7832         -    }
  7833         -    home_dir = "c:\\";
  7834         -  }
  7835         -#endif
  7836         -
  7837         -#endif /* !_WIN32_WCE */
  7838         -
  7839         -  if( home_dir ){
  7840         -    int n = strlen30(home_dir) + 1;
  7841         -    char *z = malloc( n );
  7842         -    if( z ) memcpy(z, home_dir, n);
  7843         -    home_dir = z;
  7844         -  }
  7845         -
  7846         -  return home_dir;
  7847         -}
  7848         -
  7849         -/*
  7850         -** Read input from the file given by sqliterc_override.  Or if that
  7851         -** parameter is NULL, take input from ~/.sqliterc
  7852         -**
  7853         -** Returns the number of errors.
  7854         -*/
  7855         -static void process_sqliterc(
  7856         -  ShellState *p,                  /* Configuration data */
  7857         -  const char *sqliterc_override   /* Name of config file. NULL to use default */
  7858         -){
  7859         -  char *home_dir = NULL;
  7860         -  const char *sqliterc = sqliterc_override;
  7861         -  char *zBuf = 0;
  7862         -  FILE *in = NULL;
  7863         -
  7864         -  if (sqliterc == NULL) {
  7865         -    home_dir = find_home_dir(0);
  7866         -    if( home_dir==0 ){
  7867         -      raw_printf(stderr, "-- warning: cannot find home directory;"
  7868         -                      " cannot read ~/.sqliterc\n");
  7869         -      return;
  7870         -    }
  7871         -    sqlite3_initialize();
  7872         -    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  7873         -    sqliterc = zBuf;
  7874         -  }
  7875         -  in = fopen(sqliterc,"rb");
  7876         -  if( in ){
  7877         -    if( stdin_is_interactive ){
  7878         -      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  7879         -    }
  7880         -    process_input(p,in);
  7881         -    fclose(in);
  7882         -  }
  7883         -  sqlite3_free(zBuf);
  7884         -}
  7885         -
  7886         -/*
  7887         -** Show available command line options
  7888         -*/
  7889         -static const char zOptions[] =
  7890         -  "   -ascii               set output mode to 'ascii'\n"
  7891         -  "   -bail                stop after hitting an error\n"
  7892         -  "   -batch               force batch I/O\n"
  7893         -  "   -column              set output mode to 'column'\n"
  7894         -  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
  7895         -  "   -csv                 set output mode to 'csv'\n"
  7896         -  "   -echo                print commands before execution\n"
  7897         -  "   -init FILENAME       read/process named file\n"
  7898         -  "   -[no]header          turn headers on or off\n"
  7899         -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  7900         -  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
  7901         -#endif
  7902         -  "   -help                show this message\n"
  7903         -  "   -html                set output mode to HTML\n"
  7904         -  "   -interactive         force interactive I/O\n"
  7905         -  "   -line                set output mode to 'line'\n"
  7906         -  "   -list                set output mode to 'list'\n"
  7907         -  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
  7908         -  "   -mmap N              default mmap size set to N\n"
  7909         -#ifdef SQLITE_ENABLE_MULTIPLEX
  7910         -  "   -multiplex           enable the multiplexor VFS\n"
  7911         -#endif
  7912         -  "   -newline SEP         set output row separator. Default: '\\n'\n"
  7913         -  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
  7914         -  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
  7915         -  "   -quote               set output mode to 'quote'\n"
  7916         -  "   -separator SEP       set output column separator. Default: '|'\n"
  7917         -  "   -stats               print memory stats before each finalize\n"
  7918         -  "   -version             show SQLite version\n"
  7919         -  "   -vfs NAME            use NAME as the default VFS\n"
  7920         -#ifdef SQLITE_ENABLE_VFSTRACE
  7921         -  "   -vfstrace            enable tracing of all VFS calls\n"
  7922         -#endif
  7923         -;
  7924         -static void usage(int showDetail){
  7925         -  utf8_printf(stderr,
  7926         -      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  7927         -      "FILENAME is the name of an SQLite database. A new database is created\n"
  7928         -      "if the file does not previously exist.\n", Argv0);
  7929         -  if( showDetail ){
  7930         -    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  7931         -  }else{
  7932         -    raw_printf(stderr, "Use the -help option for additional information\n");
  7933         -  }
  7934         -  exit(1);
  7935         -}
  7936         -
  7937         -/*
  7938         -** Initialize the state information in data
  7939         -*/
  7940         -static void main_init(ShellState *data) {
  7941         -  memset(data, 0, sizeof(*data));
  7942         -  data->normalMode = data->cMode = data->mode = MODE_List;
  7943         -  data->autoExplain = 1;
  7944         -  memcpy(data->colSeparator,SEP_Column, 2);
  7945         -  memcpy(data->rowSeparator,SEP_Row, 2);
  7946         -  data->showHeader = 0;
  7947         -  data->shellFlgs = SHFLG_Lookaside;
  7948         -  sqlite3_config(SQLITE_CONFIG_URI, 1);
  7949         -  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  7950         -  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  7951         -  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  7952         -  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
  7953         -}
  7954         -
  7955         -/*
  7956         -** Output text to the console in a font that attracts extra attention.
  7957         -*/
  7958         -#ifdef _WIN32
  7959         -static void printBold(const char *zText){
  7960         -  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  7961         -  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  7962         -  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  7963         -  SetConsoleTextAttribute(out,
  7964         -         FOREGROUND_RED|FOREGROUND_INTENSITY
  7965         -  );
  7966         -  printf("%s", zText);
  7967         -  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  7968         -}
  7969         -#else
  7970         -static void printBold(const char *zText){
  7971         -  printf("\033[1m%s\033[0m", zText);
  7972         -}
  7973         -#endif
  7974         -
  7975         -/*
  7976         -** Get the argument to an --option.  Throw an error and die if no argument
  7977         -** is available.
  7978         -*/
  7979         -static char *cmdline_option_value(int argc, char **argv, int i){
  7980         -  if( i==argc ){
  7981         -    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  7982         -            argv[0], argv[argc-1]);
  7983         -    exit(1);
  7984         -  }
  7985         -  return argv[i];
  7986         -}
  7987         -
  7988         -#ifndef SQLITE_SHELL_IS_UTF8
  7989         -#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  7990         -#    define SQLITE_SHELL_IS_UTF8          (0)
  7991         -#  else
  7992         -#    define SQLITE_SHELL_IS_UTF8          (1)
  7993         -#  endif
  7994         -#endif
  7995         -
  7996         -#if SQLITE_SHELL_IS_UTF8
  7997         -int SQLITE_CDECL main(int argc, char **argv){
  7998         -#else
  7999         -int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  8000         -  char **argv;
  8001         -#endif
  8002         -  char *zErrMsg = 0;
  8003         -  ShellState data;
  8004         -  const char *zInitFile = 0;
  8005         -  int i;
  8006         -  int rc = 0;
  8007         -  int warnInmemoryDb = 0;
  8008         -  int readStdin = 1;
  8009         -  int nCmd = 0;
  8010         -  char **azCmd = 0;
  8011         -
  8012         -  setBinaryMode(stdin, 0);
  8013         -  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  8014         -  stdin_is_interactive = isatty(0);
  8015         -  stdout_is_console = isatty(1);
  8016         -
  8017         -#if USE_SYSTEM_SQLITE+0!=1
  8018         -  if( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,60)!=0 ){
  8019         -    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  8020         -            sqlite3_sourceid(), SQLITE_SOURCE_ID);
  8021         -    exit(1);
  8022         -  }
  8023         -#endif
  8024         -  main_init(&data);
  8025         -#if !SQLITE_SHELL_IS_UTF8
  8026         -  sqlite3_initialize();
  8027         -  argv = sqlite3_malloc64(sizeof(argv[0])*argc);
  8028         -  if( argv==0 ){
  8029         -    raw_printf(stderr, "out of memory\n");
  8030         -    exit(1);
  8031         -  }
  8032         -  for(i=0; i<argc; i++){
  8033         -    argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
  8034         -    if( argv[i]==0 ){
  8035         -      raw_printf(stderr, "out of memory\n");
  8036         -      exit(1);
  8037         -    }
  8038         -  }
  8039         -#endif
  8040         -  assert( argc>=1 && argv && argv[0] );
  8041         -  Argv0 = argv[0];
  8042         -
  8043         -  /* Make sure we have a valid signal handler early, before anything
  8044         -  ** else is done.
  8045         -  */
  8046         -#ifdef SIGINT
  8047         -  signal(SIGINT, interrupt_handler);
  8048         -#endif
  8049         -
  8050         -#ifdef SQLITE_SHELL_DBNAME_PROC
  8051         -  {
  8052         -    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  8053         -    ** of a C-function that will provide the name of the database file.  Use
  8054         -    ** this compile-time option to embed this shell program in larger
  8055         -    ** applications. */
  8056         -    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  8057         -    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  8058         -    warnInmemoryDb = 0;
  8059         -  }
  8060         -#endif
  8061         -
  8062         -  /* Do an initial pass through the command-line argument to locate
  8063         -  ** the name of the database file, the name of the initialization file,
  8064         -  ** the size of the alternative malloc heap,
  8065         -  ** and the first command to execute.
  8066         -  */
  8067         -  for(i=1; i<argc; i++){
  8068         -    char *z;
  8069         -    z = argv[i];
  8070         -    if( z[0]!='-' ){
  8071         -      if( data.zDbFilename==0 ){
  8072         -        data.zDbFilename = z;
  8073         -      }else{
  8074         -        /* Excesss arguments are interpreted as SQL (or dot-commands) and
  8075         -        ** mean that nothing is read from stdin */
  8076         -        readStdin = 0;
  8077         -        nCmd++;
  8078         -        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  8079         -        if( azCmd==0 ){
  8080         -          raw_printf(stderr, "out of memory\n");
  8081         -          exit(1);
  8082         -        }
  8083         -        azCmd[nCmd-1] = z;
  8084         -      }
  8085         -    }
  8086         -    if( z[1]=='-' ) z++;
  8087         -    if( strcmp(z,"-separator")==0
  8088         -     || strcmp(z,"-nullvalue")==0
  8089         -     || strcmp(z,"-newline")==0
  8090         -     || strcmp(z,"-cmd")==0
  8091         -    ){
  8092         -      (void)cmdline_option_value(argc, argv, ++i);
  8093         -    }else if( strcmp(z,"-init")==0 ){
  8094         -      zInitFile = cmdline_option_value(argc, argv, ++i);
  8095         -    }else if( strcmp(z,"-batch")==0 ){
  8096         -      /* Need to check for batch mode here to so we can avoid printing
  8097         -      ** informational messages (like from process_sqliterc) before
  8098         -      ** we do the actual processing of arguments later in a second pass.
  8099         -      */
  8100         -      stdin_is_interactive = 0;
  8101         -    }else if( strcmp(z,"-heap")==0 ){
  8102         -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  8103         -      const char *zSize;
  8104         -      sqlite3_int64 szHeap;
  8105         -
  8106         -      zSize = cmdline_option_value(argc, argv, ++i);
  8107         -      szHeap = integerValue(zSize);
  8108         -      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  8109         -      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  8110         -#else
  8111         -      (void)cmdline_option_value(argc, argv, ++i);
  8112         -#endif
  8113         -    }else if( strcmp(z,"-pagecache")==0 ){
  8114         -      int n, sz;
  8115         -      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  8116         -      if( sz>70000 ) sz = 70000;
  8117         -      if( sz<0 ) sz = 0;
  8118         -      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  8119         -      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  8120         -                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  8121         -      data.shellFlgs |= SHFLG_Pagecache;
  8122         -    }else if( strcmp(z,"-lookaside")==0 ){
  8123         -      int n, sz;
  8124         -      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  8125         -      if( sz<0 ) sz = 0;
  8126         -      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  8127         -      if( n<0 ) n = 0;
  8128         -      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  8129         -      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  8130         -#ifdef SQLITE_ENABLE_VFSTRACE
  8131         -    }else if( strcmp(z,"-vfstrace")==0 ){
  8132         -      extern int vfstrace_register(
  8133         -         const char *zTraceName,
  8134         -         const char *zOldVfsName,
  8135         -         int (*xOut)(const char*,void*),
  8136         -         void *pOutArg,
  8137         -         int makeDefault
  8138         -      );
  8139         -      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  8140         -#endif
  8141         -#ifdef SQLITE_ENABLE_MULTIPLEX
  8142         -    }else if( strcmp(z,"-multiplex")==0 ){
  8143         -      extern int sqlite3_multiple_initialize(const char*,int);
  8144         -      sqlite3_multiplex_initialize(0, 1);
  8145         -#endif
  8146         -    }else if( strcmp(z,"-mmap")==0 ){
  8147         -      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  8148         -      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  8149         -    }else if( strcmp(z,"-vfs")==0 ){
  8150         -      sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
  8151         -      if( pVfs ){
  8152         -        sqlite3_vfs_register(pVfs, 1);
  8153         -      }else{
  8154         -        utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  8155         -        exit(1);
  8156         -      }
  8157         -    }
  8158         -  }
  8159         -  if( data.zDbFilename==0 ){
  8160         -#ifndef SQLITE_OMIT_MEMORYDB
  8161         -    data.zDbFilename = ":memory:";
  8162         -    warnInmemoryDb = argc==1;
  8163         -#else
  8164         -    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  8165         -    return 1;
  8166         -#endif
  8167         -  }
  8168         -  data.out = stdout;
  8169         -
  8170         -  /* Go ahead and open the database file if it already exists.  If the
  8171         -  ** file does not exist, delay opening it.  This prevents empty database
  8172         -  ** files from being created if a user mistypes the database name argument
  8173         -  ** to the sqlite command-line tool.
  8174         -  */
  8175         -  if( access(data.zDbFilename, 0)==0 ){
  8176         -    open_db(&data, 0);
  8177         -  }
  8178         -
  8179         -  /* Process the initialization file if there is one.  If no -init option
  8180         -  ** is given on the command line, look for a file named ~/.sqliterc and
  8181         -  ** try to process it.
  8182         -  */
  8183         -  process_sqliterc(&data,zInitFile);
  8184         -
  8185         -  /* Make a second pass through the command-line argument and set
  8186         -  ** options.  This second pass is delayed until after the initialization
  8187         -  ** file is processed so that the command-line arguments will override
  8188         -  ** settings in the initialization file.
  8189         -  */
  8190         -  for(i=1; i<argc; i++){
  8191         -    char *z = argv[i];
  8192         -    if( z[0]!='-' ) continue;
  8193         -    if( z[1]=='-' ){ z++; }
  8194         -    if( strcmp(z,"-init")==0 ){
  8195         -      i++;
  8196         -    }else if( strcmp(z,"-html")==0 ){
  8197         -      data.mode = MODE_Html;
  8198         -    }else if( strcmp(z,"-list")==0 ){
  8199         -      data.mode = MODE_List;
  8200         -    }else if( strcmp(z,"-quote")==0 ){
  8201         -      data.mode = MODE_Quote;
  8202         -    }else if( strcmp(z,"-line")==0 ){
  8203         -      data.mode = MODE_Line;
  8204         -    }else if( strcmp(z,"-column")==0 ){
  8205         -      data.mode = MODE_Column;
  8206         -    }else if( strcmp(z,"-csv")==0 ){
  8207         -      data.mode = MODE_Csv;
  8208         -      memcpy(data.colSeparator,",",2);
  8209         -    }else if( strcmp(z,"-ascii")==0 ){
  8210         -      data.mode = MODE_Ascii;
  8211         -      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  8212         -                       SEP_Unit);
  8213         -      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  8214         -                       SEP_Record);
  8215         -    }else if( strcmp(z,"-separator")==0 ){
  8216         -      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  8217         -                       "%s",cmdline_option_value(argc,argv,++i));
  8218         -    }else if( strcmp(z,"-newline")==0 ){
  8219         -      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  8220         -                       "%s",cmdline_option_value(argc,argv,++i));
  8221         -    }else if( strcmp(z,"-nullvalue")==0 ){
  8222         -      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  8223         -                       "%s",cmdline_option_value(argc,argv,++i));
  8224         -    }else if( strcmp(z,"-header")==0 ){
  8225         -      data.showHeader = 1;
  8226         -    }else if( strcmp(z,"-noheader")==0 ){
  8227         -      data.showHeader = 0;
  8228         -    }else if( strcmp(z,"-echo")==0 ){
  8229         -      ShellSetFlag(&data, SHFLG_Echo);
  8230         -    }else if( strcmp(z,"-eqp")==0 ){
  8231         -      data.autoEQP = 1;
  8232         -    }else if( strcmp(z,"-eqpfull")==0 ){
  8233         -      data.autoEQP = 2;
  8234         -    }else if( strcmp(z,"-stats")==0 ){
  8235         -      data.statsOn = 1;
  8236         -    }else if( strcmp(z,"-scanstats")==0 ){
  8237         -      data.scanstatsOn = 1;
  8238         -    }else if( strcmp(z,"-backslash")==0 ){
  8239         -      /* Undocumented command-line option: -backslash
  8240         -      ** Causes C-style backslash escapes to be evaluated in SQL statements
  8241         -      ** prior to sending the SQL into SQLite.  Useful for injecting
  8242         -      ** crazy bytes in the middle of SQL statements for testing and debugging.
  8243         -      */
  8244         -      ShellSetFlag(&data, SHFLG_Backslash);
  8245         -    }else if( strcmp(z,"-bail")==0 ){
  8246         -      bail_on_error = 1;
  8247         -    }else if( strcmp(z,"-version")==0 ){
  8248         -      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  8249         -      return 0;
  8250         -    }else if( strcmp(z,"-interactive")==0 ){
  8251         -      stdin_is_interactive = 1;
  8252         -    }else if( strcmp(z,"-batch")==0 ){
  8253         -      stdin_is_interactive = 0;
  8254         -    }else if( strcmp(z,"-heap")==0 ){
  8255         -      i++;
  8256         -    }else if( strcmp(z,"-pagecache")==0 ){
  8257         -      i+=2;
  8258         -    }else if( strcmp(z,"-lookaside")==0 ){
  8259         -      i+=2;
  8260         -    }else if( strcmp(z,"-mmap")==0 ){
  8261         -      i++;
  8262         -    }else if( strcmp(z,"-vfs")==0 ){
  8263         -      i++;
  8264         -#ifdef SQLITE_ENABLE_VFSTRACE
  8265         -    }else if( strcmp(z,"-vfstrace")==0 ){
  8266         -      i++;
  8267         -#endif
  8268         -#ifdef SQLITE_ENABLE_MULTIPLEX
  8269         -    }else if( strcmp(z,"-multiplex")==0 ){
  8270         -      i++;
  8271         -#endif
  8272         -    }else if( strcmp(z,"-help")==0 ){
  8273         -      usage(1);
  8274         -    }else if( strcmp(z,"-cmd")==0 ){
  8275         -      /* Run commands that follow -cmd first and separately from commands
  8276         -      ** that simply appear on the command-line.  This seems goofy.  It would
  8277         -      ** be better if all commands ran in the order that they appear.  But
  8278         -      ** we retain the goofy behavior for historical compatibility. */
  8279         -      if( i==argc-1 ) break;
  8280         -      z = cmdline_option_value(argc,argv,++i);
  8281         -      if( z[0]=='.' ){
  8282         -        rc = do_meta_command(z, &data);
  8283         -        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  8284         -      }else{
  8285         -        open_db(&data, 0);
  8286         -        rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  8287         -        if( zErrMsg!=0 ){
  8288         -          utf8_printf(stderr,"Error: %s\n", zErrMsg);
  8289         -          if( bail_on_error ) return rc!=0 ? rc : 1;
  8290         -        }else if( rc!=0 ){
  8291         -          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  8292         -          if( bail_on_error ) return rc;
  8293         -        }
  8294         -      }
  8295         -    }else{
  8296         -      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  8297         -      raw_printf(stderr,"Use -help for a list of options.\n");
  8298         -      return 1;
  8299         -    }
  8300         -    data.cMode = data.mode;
  8301         -  }
  8302         -
  8303         -  if( !readStdin ){
  8304         -    /* Run all arguments that do not begin with '-' as if they were separate
  8305         -    ** command-line inputs, except for the argToSkip argument which contains
  8306         -    ** the database filename.
  8307         -    */
  8308         -    for(i=0; i<nCmd; i++){
  8309         -      if( azCmd[i][0]=='.' ){
  8310         -        rc = do_meta_command(azCmd[i], &data);
  8311         -        if( rc ) return rc==2 ? 0 : rc;
  8312         -      }else{
  8313         -        open_db(&data, 0);
  8314         -        rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
  8315         -        if( zErrMsg!=0 ){
  8316         -          utf8_printf(stderr,"Error: %s\n", zErrMsg);
  8317         -          return rc!=0 ? rc : 1;
  8318         -        }else if( rc!=0 ){
  8319         -          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  8320         -          return rc;
  8321         -        }
  8322         -      }
  8323         -    }
  8324         -    free(azCmd);
  8325         -  }else{
  8326         -    /* Run commands received from standard input
  8327         -    */
  8328         -    if( stdin_is_interactive ){
  8329         -      char *zHome;
  8330         -      char *zHistory = 0;
  8331         -      int nHistory;
  8332         -      printf(
  8333         -        "SQLite version %s %.19s\n" /*extra-version-info*/
  8334         -        "Enter \".help\" for usage hints.\n",
  8335         -        sqlite3_libversion(), sqlite3_sourceid()
  8336         -      );
  8337         -      if( warnInmemoryDb ){
  8338         -        printf("Connected to a ");
  8339         -        printBold("transient in-memory database");
  8340         -        printf(".\nUse \".open FILENAME\" to reopen on a "
  8341         -               "persistent database.\n");
  8342         -      }
  8343         -      zHome = find_home_dir(0);
  8344         -      if( zHome ){
  8345         -        nHistory = strlen30(zHome) + 20;
  8346         -        if( (zHistory = malloc(nHistory))!=0 ){
  8347         -          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  8348         -        }
  8349         -      }
  8350         -      if( zHistory ){ shell_read_history(zHistory); }
  8351         -#if HAVE_READLINE || HAVE_EDITLINE
  8352         -      rl_attempted_completion_function = readline_completion;
  8353         -#elif HAVE_LINENOISE
  8354         -      linenoiseSetCompletionCallback(linenoise_completion);
  8355         -#endif
  8356         -      rc = process_input(&data, 0);
  8357         -      if( zHistory ){
  8358         -        shell_stifle_history(2000);
  8359         -        shell_write_history(zHistory);
  8360         -        free(zHistory);
  8361         -      }
  8362         -    }else{
  8363         -      rc = process_input(&data, stdin);
  8364         -    }
  8365         -  }
  8366         -  set_table_name(&data, 0);
  8367         -  if( data.db ){
  8368         -    session_close_all(&data);
  8369         -    sqlite3_close(data.db);
  8370         -  }
  8371         -  sqlite3_free(data.zFreeOnClose);
  8372         -  find_home_dir(1);
  8373         -#if !SQLITE_SHELL_IS_UTF8
  8374         -  for(i=0; i<argc; i++) sqlite3_free(argv[i]);
  8375         -  sqlite3_free(argv);
  8376         -#endif
  8377         -  return rc;
  8378         -}

Changes to tool/mkshellc.tcl.

     1      1   #!/usr/bin/tclsh
     2      2   #
     3         -# Run this script to generate the "src/shell.c" source file from 
            3  +# Run this script to generate the "shell.c" source file from 
     4      4   # constituent parts.
            5  +#
            6  +# No arguments are required.  This script determines the location
            7  +# of its input files relative to the location of the script itself.
            8  +# This script should be tool/mkshellc.tcl.  If the directory holding
            9  +# the script is $DIR, then the component parts are located in $DIR/../src
           10  +# and $DIR/../ext/misc.
     5     11   #
     6     12   set topdir [file dir [file dir [file normal $argv0]]]
     7         -puts "Overwriting $topdir/src/shell.c with new shell source code..."
     8         -set out [open $topdir/src/shell.c wb]
           13  +set out stdout
     9     14   puts $out {/* DO NOT EDIT!
    10     15   ** This file is automatically generated by the script in the canonical
    11     16   ** SQLite source tree at tool/mkshellc.tcl.  That script combines source
    12     17   ** code from various constituent source files of SQLite into this single
    13     18   ** "shell.c" file used to implement the SQLite command-line shell.
    14     19   **
    15     20   ** Most of the code found below comes from the "src/shell.c.in" file in