Check-in [826bd13545]
Not logged in

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

Overview
Comment:update SQLite to version 3.15.2
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 826bd135452bee7c5b31533490e2f7615839e886
User & Date: chw 2016-11-30 06:03:13
Context
2016-12-02
08:57
add tcl upstream changes check-in: b0c1c5f75f user: chw tags: trunk
2016-11-30
06:03
update SQLite to version 3.15.2 check-in: 826bd13545 user: chw tags: trunk
05:51
elimate compiler warnings in sdl2tk check-in: 5d19f522b0 user: chw tags: trunk
Changes

Changes to assets/sqlite3/pkgIndex.tcl.

     1      1   #
     2      2   # Tcl package index file
     3      3   #
     4      4   # Note sqlite*3* init specifically
     5      5   #
     6         -package ifneeded sqlite3 3.15.1 \
            6  +package ifneeded sqlite3 3.15.2 \
     7      7       [list load libtclsqlite3[info sharedlibextension] Sqlite3]

Deleted jni/tcl/pkgs/sqlite3.15.1/Android.mk.

     1         -LOCAL_PATH := $(call my-dir)
     2         -
     3         -###########################
     4         -#
     5         -# tclsqlite3 shared library
     6         -#
     7         -###########################
     8         -
     9         -include $(CLEAR_VARS)
    10         -
    11         -tcl_path := $(LOCAL_PATH)/../../tcl
    12         -
    13         -include $(tcl_path)/tcl-config.mk
    14         -
    15         -LOCAL_ADDITIONAL_DEPENDENCIES += $(tcl_path)/tcl-config.mk
    16         -
    17         -LOCAL_MODULE := tclsqlite3
    18         -
    19         -LOCAL_ARM_MODE := arm
    20         -
    21         -LOCAL_C_INCLUDES := $(tcl_includes) \
    22         -	$(LOCAL_PATH)/icu4c \
    23         -	$(LOCAL_PATH)/compat/sqlite3
    24         -
    25         -LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES)
    26         -
    27         -LOCAL_SRC_FILES := \
    28         -	generic/tclsqlite3.c \
    29         -	compat/sqlite3/shell.c \
    30         -	icu4c/dl_icu.c
    31         -
    32         -LOCAL_CFLAGS := $(tcl_cflags) \
    33         -	-DSQLITE_3_SUFFIX_ONLY=1 \
    34         -	-DSQLITE_LIKE_DOESNT_MATCH_BLOBS=1 \
    35         -	-DSQLITE_OMIT_BUILTIN_TEST=1 \
    36         -	-DSQLITE_OMIT_LOOKASIDE=1 \
    37         -	-DSQLITE_SECURE_DELETE=1 \
    38         -	-DSQLITE_SOUNDEX=1 \
    39         -	-DSQLITE_THREADSAFE=1 \
    40         -	-DSQLITE_USE_ALLOCA=1 \
    41         -	-DSQLITE_ENABLE_COLUMN_METADATA=1 \
    42         -	-DSQLITE_ENABLE_UPDATE_DELETE_LIMIT=1 \
    43         -	-DSQLITE_ENABLE_DBSTAT_VTAB=1 \
    44         -	-DSQLITE_ENABLE_FTS3_PARENTHESIS=1 \
    45         -	-DSQLITE_ENABLE_FTS3=1 \
    46         -	-DSQLITE_ENABLE_FTS4=1 \
    47         -	-DSQLITE_ENABLE_FTS5=1 \
    48         -	-DSQLITE_ENABLE_RTREE=1 \
    49         -	-DSQLITE_ENABLE_RBU=1 \
    50         -	-DSQLITE_ENABLE_ICU=1 \
    51         -	-DSQLITE_ENABLE_LOAD_EXTENSION=1 \
    52         -	-DSQLITE_ENABLE_JSON1=1 \
    53         -	-DSQLITE_ENABLE_UNLOCK_NOTIFY=1 \
    54         -	-DHAVE_USLEEP=1 \
    55         -	-DHAVE_MREMAP=1 \
    56         -	-DHAVE_ISNAN=1 \
    57         -	-DU_LIB_SUFFIX_C_NAME=_sqlite3 \
    58         -	-DPACKAGE_NAME="\"sqlite\"" \
    59         -	-DPACKAGE_VERSION="\"3.15.1\"" \
    60         -	-DBUILD_sqlite=1 \
    61         -	-Dmain=sqlite3_shell \
    62         -	-O2
    63         -
    64         -LOCAL_SHARED_LIBRARIES := libtcl
    65         -
    66         -LOCAL_LDLIBS :=	-llog
    67         -
    68         -include $(BUILD_SHARED_LIBRARY)

Deleted jni/tcl/pkgs/sqlite3.15.1/Makefile.in.

     1         -# Makefile.in --
     2         -#
     3         -#	This file is a Makefile for Sample TEA Extension.  If it has the name
     4         -#	"Makefile.in" then it is a template for a Makefile;  to generate the
     5         -#	actual Makefile, run "./configure", which is a configuration script
     6         -#	generated by the "autoconf" program (constructs like "@foo@" will get
     7         -#	replaced in the actual Makefile.
     8         -#
     9         -# Copyright (c) 1999 Scriptics Corporation.
    10         -# Copyright (c) 2002-2005 ActiveState Corporation.
    11         -#
    12         -# See the file "license.terms" for information on usage and redistribution
    13         -# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
    14         -#
    15         -# RCS: @(#) $Id: Makefile.in,v 1.59 2005/07/26 19:17:02 mdejong Exp $
    16         -
    17         -#========================================================================
    18         -# Add additional lines to handle any additional AC_SUBST cases that
    19         -# have been added in a customized configure script.
    20         -#========================================================================
    21         -
    22         -#SAMPLE_NEW_VAR	= @SAMPLE_NEW_VAR@
    23         -
    24         -#========================================================================
    25         -# Nothing of the variables below this line should need to be changed.
    26         -# Please check the TARGETS section below to make sure the make targets
    27         -# are correct.
    28         -#========================================================================
    29         -
    30         -#========================================================================
    31         -# The names of the source files is defined in the configure script.
    32         -# The object files are used for linking into the final library.
    33         -# This will be used when a dist target is added to the Makefile.
    34         -# It is not important to specify the directory, as long as it is the
    35         -# $(srcdir) or in the generic, win or unix subdirectory.
    36         -#========================================================================
    37         -
    38         -PKG_SOURCES	= @PKG_SOURCES@
    39         -PKG_OBJECTS	= @PKG_OBJECTS@
    40         -
    41         -PKG_STUB_SOURCES = @PKG_STUB_SOURCES@
    42         -PKG_STUB_OBJECTS = @PKG_STUB_OBJECTS@
    43         -
    44         -#========================================================================
    45         -# PKG_TCL_SOURCES identifies Tcl runtime files that are associated with
    46         -# this package that need to be installed, if any.
    47         -#========================================================================
    48         -
    49         -PKG_TCL_SOURCES = @PKG_TCL_SOURCES@
    50         -
    51         -#========================================================================
    52         -# This is a list of public header files to be installed, if any.
    53         -#========================================================================
    54         -
    55         -PKG_HEADERS	= @PKG_HEADERS@
    56         -
    57         -#========================================================================
    58         -# "PKG_LIB_FILE" refers to the library (dynamic or static as per
    59         -# configuration options) composed of the named objects.
    60         -#========================================================================
    61         -
    62         -PKG_LIB_FILE	= @PKG_LIB_FILE@
    63         -PKG_STUB_LIB_FILE = @PKG_STUB_LIB_FILE@
    64         -
    65         -lib_BINARIES	= $(PKG_LIB_FILE)
    66         -BINARIES	= $(lib_BINARIES)
    67         -
    68         -SHELL		= @SHELL@
    69         -
    70         -srcdir		= @srcdir@
    71         -prefix		= @prefix@
    72         -exec_prefix	= @exec_prefix@
    73         -
    74         -bindir		= @bindir@
    75         -libdir		= @libdir@
    76         -datarootdir	= @datarootdir@
    77         -datadir		= @datadir@
    78         -mandir		= @mandir@
    79         -includedir	= @includedir@
    80         -
    81         -DESTDIR		=
    82         -
    83         -PKG_DIR		= $(PACKAGE_NAME)$(PACKAGE_VERSION)
    84         -pkgdatadir	= $(datadir)/$(PKG_DIR)
    85         -pkglibdir	= $(libdir)/$(PKG_DIR)
    86         -pkgincludedir	= $(includedir)/$(PKG_DIR)
    87         -
    88         -top_builddir	= .
    89         -
    90         -INSTALL		= @INSTALL@
    91         -INSTALL_PROGRAM	= @INSTALL_PROGRAM@
    92         -INSTALL_DATA	= @INSTALL_DATA@
    93         -INSTALL_SCRIPT	= @INSTALL_SCRIPT@
    94         -
    95         -PACKAGE_NAME	= @PACKAGE_NAME@
    96         -PACKAGE_VERSION	= @PACKAGE_VERSION@
    97         -CC		= @CC@
    98         -CFLAGS_DEFAULT	= @CFLAGS_DEFAULT@
    99         -CFLAGS_WARNING	= @CFLAGS_WARNING@
   100         -CLEANFILES	= @CLEANFILES@
   101         -EXEEXT		= @EXEEXT@
   102         -LDFLAGS_DEFAULT	= @LDFLAGS_DEFAULT@
   103         -MAKE_LIB	= @MAKE_LIB@
   104         -MAKE_SHARED_LIB	= @MAKE_SHARED_LIB@
   105         -MAKE_STATIC_LIB	= @MAKE_STATIC_LIB@
   106         -MAKE_STUB_LIB	= @MAKE_STUB_LIB@
   107         -OBJEXT		= @OBJEXT@
   108         -RANLIB		= @RANLIB@
   109         -RANLIB_STUB	= @RANLIB_STUB@
   110         -SHLIB_CFLAGS	= @SHLIB_CFLAGS@
   111         -SHLIB_LD	= @SHLIB_LD@
   112         -SHLIB_LD_LIBS	= @SHLIB_LD_LIBS@
   113         -STLIB_LD	= @STLIB_LD@
   114         -#TCL_DEFS	= @TCL_DEFS@
   115         -TCL_BIN_DIR	= @TCL_BIN_DIR@
   116         -TCL_SRC_DIR	= @TCL_SRC_DIR@
   117         -#TK_BIN_DIR	= @TK_BIN_DIR@
   118         -#TK_SRC_DIR	= @TK_SRC_DIR@
   119         -
   120         -# This is no longer necessary even for packages that use private Tcl headers
   121         -#TCL_TOP_DIR_NATIVE	= @TCL_TOP_DIR_NATIVE@
   122         -# Not used, but retained for reference of what libs Tcl required
   123         -#TCL_LIBS	= @TCL_LIBS@
   124         -
   125         -#========================================================================
   126         -# TCLLIBPATH seeds the auto_path in Tcl's init.tcl so we can test our
   127         -# package without installing.  The other environment variables allow us
   128         -# to test against an uninstalled Tcl.  Add special env vars that you
   129         -# require for testing here (like TCLX_LIBRARY).
   130         -#========================================================================
   131         -
   132         -EXTRA_PATH	= $(top_builddir):$(TCL_BIN_DIR)
   133         -#EXTRA_PATH	= $(top_builddir):$(TCL_BIN_DIR):$(TK_BIN_DIR)
   134         -TCLLIBPATH	= $(top_builddir)
   135         -TCLSH_ENV	= TCL_LIBRARY=`@CYGPATH@ $(TCL_SRC_DIR)/library` \
   136         -		  @LD_LIBRARY_PATH_VAR@="$(EXTRA_PATH):$(@LD_LIBRARY_PATH_VAR@)" \
   137         -		  PATH="$(EXTRA_PATH):$(PATH)" \
   138         -		  TCLLIBPATH="$(TCLLIBPATH)"
   139         -#		  TK_LIBRARY=`@CYGPATH@ $(TK_SRC_DIR)/library`
   140         -
   141         -TCLSH_PROG	= @TCLSH_PROG@
   142         -TCLSH	= $(TCLSH_ENV) $(TCLSH_PROG)
   143         -
   144         -#WISH_PROG	= @WISH_PROG@
   145         -#WISH	= $(TCLSH_ENV) $(WISH_PROG)
   146         -
   147         -
   148         -SHARED_BUILD	= @SHARED_BUILD@
   149         -
   150         -INCLUDES	= @PKG_INCLUDES@ @TCL_INCLUDES@ -I$(srcdir)/..
   151         -#INCLUDES	= @PKG_INCLUDES@ @TCL_INCLUDES@ @TK_INCLUDES@ @TK_XINCLUDES@
   152         -
   153         -PKG_CFLAGS	= @PKG_CFLAGS@ -DSQLITE_API=MODULE_SCOPE -DSQLITE_EXTERN=
   154         -
   155         -# TCL_DEFS is not strictly need here, but if you remove it, then you
   156         -# must make sure that configure.in checks for the necessary components
   157         -# that your library may use.  TCL_DEFS can actually be a problem if
   158         -# you do not compile with a similar machine setup as the Tcl core was
   159         -# compiled with.
   160         -#DEFS		= $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS)
   161         -DEFS		= @DEFS@ $(PKG_CFLAGS)
   162         -
   163         -CONFIG_CLEAN_FILES = Makefile pkgIndex.tcl
   164         -
   165         -CPPFLAGS	= @CPPFLAGS@
   166         -LIBS		= @PKG_LIBS@ @LIBS@
   167         -AR		= @AR@
   168         -CFLAGS		= @CFLAGS@
   169         -COMPILE		= $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
   170         -
   171         -#========================================================================
   172         -# Start of user-definable TARGETS section
   173         -#========================================================================
   174         -
   175         -#========================================================================
   176         -# TEA TARGETS.  Please note that the "libraries:" target refers to platform
   177         -# independent files, and the "binaries:" target inclues executable programs and
   178         -# platform-dependent libraries.  Modify these targets so that they install
   179         -# the various pieces of your package.  The make and install rules
   180         -# for the BINARIES that you specified above have already been done.
   181         -#========================================================================
   182         -
   183         -all: binaries libraries doc
   184         -
   185         -#========================================================================
   186         -# The binaries target builds executable programs, Windows .dll's, unix
   187         -# shared/static libraries, and any other platform-dependent files.
   188         -# The list of targets to build for "binaries:" is specified at the top
   189         -# of the Makefile, in the "BINARIES" variable.
   190         -#========================================================================
   191         -
   192         -binaries: $(BINARIES)
   193         -
   194         -libraries:
   195         -
   196         -
   197         -#========================================================================
   198         -# Your doc target should differentiate from doc builds (by the developer)
   199         -# and doc installs (see install-doc), which just install the docs on the
   200         -# end user machine when building from source.
   201         -#========================================================================
   202         -
   203         -doc:
   204         -	@echo "If you have documentation to create, place the commands to"
   205         -	@echo "build the docs in the 'doc:' target.  For example:"
   206         -	@echo "        xml2nroff sample.xml > sample.n"
   207         -	@echo "        xml2html sample.xml > sample.html"
   208         -
   209         -install: all install-binaries install-libraries install-doc
   210         -
   211         -install-binaries: binaries install-lib-binaries install-bin-binaries
   212         -
   213         -#========================================================================
   214         -# This rule installs platform-independent files, such as header files.
   215         -# The list=...; for p in $$list handles the empty list case x-platform.
   216         -#========================================================================
   217         -
   218         -install-libraries: libraries
   219         -	@mkdir -p $(DESTDIR)$(includedir)
   220         -	@echo "Installing header files in $(DESTDIR)$(includedir)"
   221         -	@list='$(PKG_HEADERS)'; for i in $$list; do \
   222         -	    echo "Installing $(srcdir)/$$i" ; \
   223         -	    $(INSTALL_DATA) $(srcdir)/$$i $(DESTDIR)$(includedir) ; \
   224         -	done;
   225         -
   226         -#========================================================================
   227         -# Install documentation.  Unix manpages should go in the $(mandir)
   228         -# directory.
   229         -#========================================================================
   230         -
   231         -install-doc: doc
   232         -	@mkdir -p $(DESTDIR)$(mandir)/mann
   233         -	@echo "Installing documentation in $(DESTDIR)$(mandir)"
   234         -	@list='$(srcdir)/doc/*.n'; for i in $$list; do \
   235         -	    echo "Installing $$i"; \
   236         -	    rm -f $(DESTDIR)$(mandir)/mann/`basename $$i`; \
   237         -	    $(INSTALL_DATA) $$i $(DESTDIR)$(mandir)/mann ; \
   238         -	done
   239         -
   240         -test: binaries libraries
   241         -	$(TCLSH) `@CYGPATH@ $(srcdir)/tests/all.tcl` $(TESTFLAGS) \
   242         -		-load "package ifneeded ${PACKAGE_NAME}3 ${PACKAGE_VERSION} \
   243         -			[list load `@CYGPATH@ $(PKG_LIB_FILE)` $(PACKAGE_NAME)3]"
   244         -
   245         -shell: binaries libraries
   246         -	@$(TCLSH) $(SCRIPT)
   247         -
   248         -gdb:
   249         -	$(TCLSH_ENV) gdb $(TCLSH_PROG) $(SCRIPT)
   250         -
   251         -depend:
   252         -
   253         -#========================================================================
   254         -# $(PKG_LIB_FILE) should be listed as part of the BINARIES variable
   255         -# mentioned above.  That will ensure that this target is built when you
   256         -# run "make binaries".
   257         -#
   258         -# The $(PKG_OBJECTS) objects are created and linked into the final
   259         -# library.  In most cases these object files will correspond to the
   260         -# source files above.
   261         -#========================================================================
   262         -
   263         -$(PKG_LIB_FILE): $(PKG_OBJECTS)
   264         -	-rm -f $(PKG_LIB_FILE)
   265         -	${MAKE_LIB}
   266         -	$(RANLIB) $(PKG_LIB_FILE)
   267         -
   268         -$(PKG_STUB_LIB_FILE): $(PKG_STUB_OBJECTS)
   269         -	-rm -f $(PKG_STUB_LIB_FILE)
   270         -	${MAKE_STUB_LIB}
   271         -	$(RANLIB_STUB) $(PKG_STUB_LIB_FILE)
   272         -
   273         -#========================================================================
   274         -# We need to enumerate the list of .c to .o lines here.
   275         -#
   276         -# In the following lines, $(srcdir) refers to the toplevel directory
   277         -# containing your extension.  If your sources are in a subdirectory,
   278         -# you will have to modify the paths to reflect this:
   279         -#
   280         -# sample.$(OBJEXT): $(srcdir)/generic/sample.c
   281         -# 	$(COMPILE) -c `@CYGPATH@ $(srcdir)/generic/sample.c` -o $@
   282         -#
   283         -# Setting the VPATH variable to a list of paths will cause the makefile
   284         -# to look into these paths when resolving .c to .obj dependencies.
   285         -# As necessary, add $(srcdir):$(srcdir)/compat:....
   286         -#========================================================================
   287         -
   288         -VPATH = $(srcdir):$(srcdir)/generic:$(srcdir)/unix:$(srcdir)/win
   289         -
   290         -.c.@OBJEXT@:
   291         -	$(COMPILE) -c `@CYGPATH@ $<` -o $@
   292         -
   293         -#========================================================================
   294         -# Distribution creation
   295         -# You may need to tweak this target to make it work correctly.
   296         -#========================================================================
   297         -
   298         -#COMPRESS	= tar cvf $(PKG_DIR).tar $(PKG_DIR); compress $(PKG_DIR).tar
   299         -COMPRESS	= gtar zcvf $(PKG_DIR).tar.gz $(PKG_DIR)
   300         -DIST_ROOT	= /tmp/dist
   301         -DIST_DIR	= $(DIST_ROOT)/$(PKG_DIR)
   302         -
   303         -dist-clean:
   304         -	rm -rf $(DIST_DIR) $(DIST_ROOT)/$(PKG_DIR).tar.*
   305         -
   306         -dist: dist-clean
   307         -	mkdir -p $(DIST_DIR)/compat/sqlite3
   308         -	cp -p $(srcdir)/README* $(srcdir)/license* \
   309         -		$(srcdir)/aclocal.m4 $(srcdir)/configure $(srcdir)/*.in \
   310         -		$(srcdir)/configure.ac $(DIST_DIR)/
   311         -	chmod 664 $(DIST_DIR)/Makefile.in $(DIST_DIR)/aclocal.m4
   312         -	chmod 775 $(DIST_DIR)/configure $(DIST_DIR)/configure.ac
   313         -
   314         -	for i in $(srcdir)/*.[ch]; do \
   315         -	    if [ -f $$i ]; then \
   316         -		cp -p $$i $(DIST_DIR)/ ; \
   317         -	    fi; \
   318         -	done;
   319         -
   320         -	mkdir -p $(DIST_DIR)/tclconfig
   321         -	cp $(srcdir)/tclconfig/install-sh $(srcdir)/tclconfig/tcl.m4 \
   322         -		$(DIST_DIR)/tclconfig/
   323         -	chmod 664 $(DIST_DIR)/tclconfig/tcl.m4
   324         -	chmod +x $(DIST_DIR)/tclconfig/install-sh
   325         -
   326         -	list='demos doc generic library mac tests unix win compat/sqlite3'; \
   327         -	for p in $$list; do \
   328         -	    if test -d $(srcdir)/$$p ; then \
   329         -		mkdir -p $(DIST_DIR)/$$p; \
   330         -		cp -p $(srcdir)/$$p/*.* $(DIST_DIR)/$$p/; \
   331         -	    fi; \
   332         -	done
   333         -
   334         -	(cd $(DIST_ROOT); $(COMPRESS);)
   335         -
   336         -#========================================================================
   337         -# End of user-definable section
   338         -#========================================================================
   339         -
   340         -#========================================================================
   341         -# Don't modify the file to clean here.  Instead, set the "CLEANFILES"
   342         -# variable in configure.in
   343         -#========================================================================
   344         -
   345         -clean:  
   346         -	-test -z "$(BINARIES)" || rm -f $(BINARIES)
   347         -	-rm -f *.$(OBJEXT) core *.core
   348         -	-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
   349         -
   350         -distclean: clean
   351         -	-rm -f *.tab.c
   352         -	-rm -f $(CONFIG_CLEAN_FILES)
   353         -	-rm -f config.h config.cache config.log config.status
   354         -
   355         -#========================================================================
   356         -# Install binary object libraries.  On Windows this includes both .dll and
   357         -# .lib files.  Because the .lib files are not explicitly listed anywhere,
   358         -# we need to deduce their existence from the .dll file of the same name.
   359         -# Library files go into the lib directory.
   360         -# In addition, this will generate the pkgIndex.tcl
   361         -# file in the install location (assuming it can find a usable tclsh shell)
   362         -#
   363         -# You should not have to modify this target.
   364         -#========================================================================
   365         -
   366         -install-lib-binaries: binaries
   367         -	@mkdir -p $(DESTDIR)$(pkglibdir)
   368         -	@list='$(lib_BINARIES)'; for p in $$list; do \
   369         -	  if test -f $$p; then \
   370         -	    echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
   371         -	    $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p; \
   372         -	    stub=`echo $$p|sed -e "s/.*\(stub\).*/\1/"`; \
   373         -	    if test "x$$stub" = "xstub"; then \
   374         -		echo " $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p"; \
   375         -		$(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p; \
   376         -	    else \
   377         -		echo " $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p"; \
   378         -		$(RANLIB) $(DESTDIR)$(pkglibdir)/$$p; \
   379         -	    fi; \
   380         -	    ext=`echo $$p|sed -e "s/.*\.//"`; \
   381         -	    if test "x$$ext" = "xdll"; then \
   382         -		lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \
   383         -		if test -f $$lib; then \
   384         -		    echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \
   385         -	            $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \
   386         -		fi; \
   387         -	    fi; \
   388         -	  fi; \
   389         -	done
   390         -	@list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
   391         -	  if test -f $(srcdir)/$$p; then \
   392         -	    destp=`basename $$p`; \
   393         -	    echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
   394         -	    $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
   395         -	  fi; \
   396         -	done
   397         -	@if test "x$(SHARED_BUILD)" = "x1"; then \
   398         -	    echo " Install pkgIndex.tcl $(DESTDIR)$(pkglibdir)"; \
   399         -	    $(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir); \
   400         -	fi
   401         -
   402         -#========================================================================
   403         -# Install binary executables (e.g. .exe files and dependent .dll files)
   404         -# This is for files that must go in the bin directory (located next to
   405         -# wish and tclsh), like dependent .dll files on Windows.
   406         -#
   407         -# You should not have to modify this target, except to define bin_BINARIES
   408         -# above if necessary.
   409         -#========================================================================
   410         -
   411         -install-bin-binaries: binaries
   412         -	@mkdir -p $(DESTDIR)$(bindir)
   413         -	@list='$(bin_BINARIES)'; for p in $$list; do \
   414         -	  if test -f $$p; then \
   415         -	    echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \
   416         -	    $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \
   417         -	  fi; \
   418         -	done
   419         -	$(INSTALL_PROGRAM) $(srcdir)/compat/sqlite3/spaceanal.tcl $(DESTDIR)$(bindir)/sqlite3_analyzer
   420         -
   421         -.SUFFIXES: .c .$(OBJEXT)
   422         -
   423         -Makefile: $(srcdir)/Makefile.in  $(top_builddir)/config.status
   424         -	cd $(top_builddir) \
   425         -	  && CONFIG_FILES=$@ CONFIG_HEADERS= $(SHELL) ./config.status
   426         -
   427         -uninstall-binaries:
   428         -	list='$(lib_BINARIES)'; for p in $$list; do \
   429         -	  rm -f $(DESTDIR)$(pkglibdir)/$$p; \
   430         -	done
   431         -	list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
   432         -	  p=`basename $$p`; \
   433         -	  rm -f $(DESTDIR)$(pkglibdir)/$$p; \
   434         -	done
   435         -	list='$(bin_BINARIES)'; for p in $$list; do \
   436         -	  rm -f $(DESTDIR)$(bindir)/$$p; \
   437         -	done
   438         -
   439         -.PHONY: all binaries clean depend distclean doc install libraries test
   440         -
   441         -# Tell versions [3.59,3.63) of GNU make to not export all variables.
   442         -# Otherwise a system limit (for SysV at least) may be exceeded.
   443         -.NOEXPORT:

Deleted jni/tcl/pkgs/sqlite3.15.1/README.

     1         -This is the SQLite extension for Tcl using the Tcl Extension
     2         -Architecture (TEA).  For additional information on SQLite see
     3         -
     4         -        http://www.sqlite.org/
     5         -
     6         -
     7         -UNIX BUILD
     8         -==========
     9         -
    10         -Building under most UNIX systems is easy, just run the configure script
    11         -and then run make. For more information about the build process, see
    12         -the tcl/unix/README file in the Tcl src dist. The following minimal
    13         -example will install the extension in the /opt/tcl directory.
    14         -
    15         -	$ cd sqlite-*-tea
    16         -	$ ./configure --prefix=/opt/tcl
    17         -	$ make
    18         -	$ make install
    19         -
    20         -WINDOWS BUILD
    21         -=============
    22         -
    23         -The recommended method to build extensions under windows is to use the
    24         -Msys + Mingw build process. This provides a Unix-style build while
    25         -generating native Windows binaries. Using the Msys + Mingw build tools
    26         -means that you can use the same configure script as per the Unix build
    27         -to create a Makefile. See the tcl/win/README file for the URL of
    28         -the Msys + Mingw download.
    29         -
    30         -If you have VC++ then you may wish to use the files in the win
    31         -subdirectory and build the extension using just VC++. These files have
    32         -been designed to be as generic as possible but will require some
    33         -additional maintenance by the project developer to synchronise with
    34         -the TEA configure.in and Makefile.in files. Instructions for using the
    35         -VC++ makefile are written in the first part of the Makefile.vc
    36         -file.

Deleted jni/tcl/pkgs/sqlite3.15.1/aclocal.m4.

     1         -#
     2         -# Include the TEA standard macro set
     3         -#
     4         -
     5         -builtin(include,tclconfig/tcl.m4)
     6         -
     7         -#
     8         -# Add here whatever m4 macros you want to define for your package
     9         -#

Deleted jni/tcl/pkgs/sqlite3.15.1/compat/sqlite3/shell.c.

     1         -/*
     2         -** 2001 September 15
     3         -**
     4         -** The author disclaims copyright to this source code.  In place of
     5         -** a legal notice, here is a blessing:
     6         -**
     7         -**    May you do good and not evil.
     8         -**    May you find forgiveness for yourself and forgive others.
     9         -**    May you share freely, never taking more than you give.
    10         -**
    11         -*************************************************************************
    12         -** This file contains code to implement the "sqlite" command line
    13         -** utility for accessing SQLite databases.
    14         -*/
    15         -#if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS)
    16         -/* This needs to come before any includes for MSVC compiler */
    17         -#define _CRT_SECURE_NO_WARNINGS
    18         -#endif
    19         -
    20         -/*
    21         -** If requested, include the SQLite compiler options file for MSVC.
    22         -*/
    23         -#if defined(INCLUDE_MSVC_H)
    24         -#include "msvc.h"
    25         -#endif
    26         -
    27         -/*
    28         -** No support for loadable extensions in VxWorks.
    29         -*/
    30         -#if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION
    31         -# define SQLITE_OMIT_LOAD_EXTENSION 1
    32         -#endif
    33         -
    34         -/*
    35         -** Enable large-file support for fopen() and friends on unix.
    36         -*/
    37         -#ifndef SQLITE_DISABLE_LFS
    38         -# define _LARGE_FILE       1
    39         -# ifndef _FILE_OFFSET_BITS
    40         -#   define _FILE_OFFSET_BITS 64
    41         -# endif
    42         -# define _LARGEFILE_SOURCE 1
    43         -#endif
    44         -
    45         -#include <stdlib.h>
    46         -#include <string.h>
    47         -#include <stdio.h>
    48         -#include <assert.h>
    49         -#include "sqlite3.h"
    50         -#if SQLITE_USER_AUTHENTICATION
    51         -# include "sqlite3userauth.h"
    52         -#endif
    53         -#include <ctype.h>
    54         -#include <stdarg.h>
    55         -
    56         -#if !defined(_WIN32) && !defined(WIN32)
    57         -# include <signal.h>
    58         -# if !defined(__RTP__) && !defined(_WRS_KERNEL)
    59         -#  include <pwd.h>
    60         -# endif
    61         -# include <unistd.h>
    62         -# include <sys/types.h>
    63         -#endif
    64         -
    65         -#if HAVE_READLINE
    66         -# include <readline/readline.h>
    67         -# include <readline/history.h>
    68         -#endif
    69         -
    70         -#if HAVE_EDITLINE
    71         -# include <editline/readline.h>
    72         -#endif
    73         -
    74         -#if HAVE_EDITLINE || HAVE_READLINE
    75         -
    76         -# define shell_add_history(X) add_history(X)
    77         -# define shell_read_history(X) read_history(X)
    78         -# define shell_write_history(X) write_history(X)
    79         -# define shell_stifle_history(X) stifle_history(X)
    80         -# define shell_readline(X) readline(X)
    81         -
    82         -#elif HAVE_LINENOISE
    83         -
    84         -# include "linenoise.h"
    85         -# define shell_add_history(X) linenoiseHistoryAdd(X)
    86         -# define shell_read_history(X) linenoiseHistoryLoad(X)
    87         -# define shell_write_history(X) linenoiseHistorySave(X)
    88         -# define shell_stifle_history(X) linenoiseHistorySetMaxLen(X)
    89         -# define shell_readline(X) linenoise(X)
    90         -
    91         -#else
    92         -
    93         -# define shell_read_history(X)
    94         -# define shell_write_history(X)
    95         -# define shell_stifle_history(X)
    96         -
    97         -# define SHELL_USE_LOCAL_GETLINE 1
    98         -#endif
    99         -
   100         -
   101         -#if defined(_WIN32) || defined(WIN32)
   102         -# include <io.h>
   103         -# include <fcntl.h>
   104         -# define isatty(h) _isatty(h)
   105         -# ifndef access
   106         -#  define access(f,m) _access((f),(m))
   107         -# endif
   108         -# undef popen
   109         -# define popen _popen
   110         -# undef pclose
   111         -# define pclose _pclose
   112         -#else
   113         - /* Make sure isatty() has a prototype. */
   114         - extern int isatty(int);
   115         -
   116         -# if !defined(__RTP__) && !defined(_WRS_KERNEL)
   117         -  /* popen and pclose are not C89 functions and so are
   118         -  ** sometimes omitted from the <stdio.h> header */
   119         -   extern FILE *popen(const char*,const char*);
   120         -   extern int pclose(FILE*);
   121         -# else
   122         -#  define SQLITE_OMIT_POPEN 1
   123         -# endif
   124         -#endif
   125         -
   126         -#if defined(_WIN32_WCE)
   127         -/* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
   128         - * thus we always assume that we have a console. That can be
   129         - * overridden with the -batch command line option.
   130         - */
   131         -#define isatty(x) 1
   132         -#endif
   133         -
   134         -/* ctype macros that work with signed characters */
   135         -#define IsSpace(X)  isspace((unsigned char)X)
   136         -#define IsDigit(X)  isdigit((unsigned char)X)
   137         -#define ToLower(X)  (char)tolower((unsigned char)X)
   138         -
   139         -#if defined(_WIN32) || defined(WIN32)
   140         -#include <windows.h>
   141         -
   142         -/* string conversion routines only needed on Win32 */
   143         -extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR);
   144         -extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int);
   145         -extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int);
   146         -extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
   147         -#endif
   148         -
   149         -/* On Windows, we normally run with output mode of TEXT so that \n characters
   150         -** are automatically translated into \r\n.  However, this behavior needs
   151         -** to be disabled in some cases (ex: when generating CSV output and when
   152         -** rendering quoted strings that contain \n characters).  The following
   153         -** routines take care of that.
   154         -*/
   155         -#if defined(_WIN32) || defined(WIN32)
   156         -static void setBinaryMode(FILE *file, int isOutput){
   157         -  if( isOutput ) fflush(file);
   158         -  _setmode(_fileno(file), _O_BINARY);
   159         -}
   160         -static void setTextMode(FILE *file, int isOutput){
   161         -  if( isOutput ) fflush(file);
   162         -  _setmode(_fileno(file), _O_TEXT);
   163         -}
   164         -#else
   165         -# define setBinaryMode(X,Y)
   166         -# define setTextMode(X,Y)
   167         -#endif
   168         -
   169         -
   170         -/* True if the timer is enabled */
   171         -static int enableTimer = 0;
   172         -
   173         -/* Return the current wall-clock time */
   174         -static sqlite3_int64 timeOfDay(void){
   175         -  static sqlite3_vfs *clockVfs = 0;
   176         -  sqlite3_int64 t;
   177         -  if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
   178         -  if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){
   179         -    clockVfs->xCurrentTimeInt64(clockVfs, &t);
   180         -  }else{
   181         -    double r;
   182         -    clockVfs->xCurrentTime(clockVfs, &r);
   183         -    t = (sqlite3_int64)(r*86400000.0);
   184         -  }
   185         -  return t;
   186         -}
   187         -
   188         -#if !defined(_WIN32) && !defined(WIN32) && !defined(__minux)
   189         -#include <sys/time.h>
   190         -#include <sys/resource.h>
   191         -
   192         -/* VxWorks does not support getrusage() as far as we can determine */
   193         -#if defined(_WRS_KERNEL) || defined(__RTP__)
   194         -struct rusage {
   195         -  struct timeval ru_utime; /* user CPU time used */
   196         -  struct timeval ru_stime; /* system CPU time used */
   197         -};
   198         -#define getrusage(A,B) memset(B,0,sizeof(*B))
   199         -#endif
   200         -
   201         -/* Saved resource information for the beginning of an operation */
   202         -static struct rusage sBegin;  /* CPU time at start */
   203         -static sqlite3_int64 iBegin;  /* Wall-clock time at start */
   204         -
   205         -/*
   206         -** Begin timing an operation
   207         -*/
   208         -static void beginTimer(void){
   209         -  if( enableTimer ){
   210         -    getrusage(RUSAGE_SELF, &sBegin);
   211         -    iBegin = timeOfDay();
   212         -  }
   213         -}
   214         -
   215         -/* Return the difference of two time_structs in seconds */
   216         -static double timeDiff(struct timeval *pStart, struct timeval *pEnd){
   217         -  return (pEnd->tv_usec - pStart->tv_usec)*0.000001 +
   218         -         (double)(pEnd->tv_sec - pStart->tv_sec);
   219         -}
   220         -
   221         -/*
   222         -** Print the timing results.
   223         -*/
   224         -static void endTimer(void){
   225         -  if( enableTimer ){
   226         -    sqlite3_int64 iEnd = timeOfDay();
   227         -    struct rusage sEnd;
   228         -    getrusage(RUSAGE_SELF, &sEnd);
   229         -    printf("Run Time: real %.3f user %f sys %f\n",
   230         -       (iEnd - iBegin)*0.001,
   231         -       timeDiff(&sBegin.ru_utime, &sEnd.ru_utime),
   232         -       timeDiff(&sBegin.ru_stime, &sEnd.ru_stime));
   233         -  }
   234         -}
   235         -
   236         -#define BEGIN_TIMER beginTimer()
   237         -#define END_TIMER endTimer()
   238         -#define HAS_TIMER 1
   239         -
   240         -#elif (defined(_WIN32) || defined(WIN32))
   241         -
   242         -/* Saved resource information for the beginning of an operation */
   243         -static HANDLE hProcess;
   244         -static FILETIME ftKernelBegin;
   245         -static FILETIME ftUserBegin;
   246         -static sqlite3_int64 ftWallBegin;
   247         -
   248         -/*
   249         -** Begin timing an operation
   250         -*/
   251         -static void beginTimer(void){
   252         -  if( enableTimer ){
   253         -    FILETIME ftCreation, ftExit;
   254         -    GetProcessTimes(hProcess,&ftCreation,&ftExit,
   255         -                        &ftKernelBegin,&ftUserBegin);
   256         -    ftWallBegin = timeOfDay();
   257         -  }
   258         -}
   259         -
   260         -/* Return the difference of two FILETIME structs in seconds */
   261         -static double timeDiff(FILETIME *pStart, FILETIME *pEnd){
   262         -  sqlite_int64 i64Start = *((sqlite_int64 *) pStart);
   263         -  sqlite_int64 i64End = *((sqlite_int64 *) pEnd);
   264         -  return (double) ((i64End - i64Start) / 10000000.0);
   265         -}
   266         -
   267         -/*
   268         -** Print the timing results.
   269         -*/
   270         -static void endTimer(void){
   271         -  if( enableTimer){
   272         -    FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd;
   273         -    sqlite3_int64 ftWallEnd = timeOfDay();
   274         -    GetProcessTimes(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd);
   275         -    printf("Run Time: real %.3f user %f sys %f\n",
   276         -       (ftWallEnd - ftWallBegin)*0.001,
   277         -       timeDiff(&ftUserBegin, &ftUserEnd),
   278         -       timeDiff(&ftKernelBegin, &ftKernelEnd));
   279         -  }
   280         -}
   281         -
   282         -#define BEGIN_TIMER beginTimer()
   283         -#define END_TIMER endTimer()
   284         -#define HAS_TIMER 1
   285         -
   286         -#else
   287         -#define BEGIN_TIMER
   288         -#define END_TIMER
   289         -#define HAS_TIMER 0
   290         -#endif
   291         -
   292         -/*
   293         -** Used to prevent warnings about unused parameters
   294         -*/
   295         -#define UNUSED_PARAMETER(x) (void)(x)
   296         -
   297         -/*
   298         -** If the following flag is set, then command execution stops
   299         -** at an error if we are not interactive.
   300         -*/
   301         -static int bail_on_error = 0;
   302         -
   303         -/*
   304         -** Threat stdin as an interactive input if the following variable
   305         -** is true.  Otherwise, assume stdin is connected to a file or pipe.
   306         -*/
   307         -static int stdin_is_interactive = 1;
   308         -
   309         -/*
   310         -** On Windows systems we have to know if standard output is a console
   311         -** in order to translate UTF-8 into MBCS.  The following variable is
   312         -** true if translation is required.
   313         -*/
   314         -static int stdout_is_console = 1;
   315         -
   316         -/*
   317         -** The following is the open SQLite database.  We make a pointer
   318         -** to this database a static variable so that it can be accessed
   319         -** by the SIGINT handler to interrupt database processing.
   320         -*/
   321         -static sqlite3 *globalDb = 0;
   322         -
   323         -/*
   324         -** True if an interrupt (Control-C) has been received.
   325         -*/
   326         -static volatile int seenInterrupt = 0;
   327         -
   328         -/*
   329         -** This is the name of our program. It is set in main(), used
   330         -** in a number of other places, mostly for error messages.
   331         -*/
   332         -static char *Argv0;
   333         -
   334         -/*
   335         -** Prompt strings. Initialized in main. Settable with
   336         -**   .prompt main continue
   337         -*/
   338         -static char mainPrompt[20];     /* First line prompt. default: "sqlite> "*/
   339         -static char continuePrompt[20]; /* Continuation prompt. default: "   ...> " */
   340         -
   341         -/*
   342         -** Render output like fprintf().  Except, if the output is going to the
   343         -** console and if this is running on a Windows machine, translate the
   344         -** output from UTF-8 into MBCS.
   345         -*/
   346         -#if defined(_WIN32) || defined(WIN32)
   347         -void utf8_printf(FILE *out, const char *zFormat, ...){
   348         -  va_list ap;
   349         -  va_start(ap, zFormat);
   350         -  if( stdout_is_console && (out==stdout || out==stderr) ){
   351         -    char *z1 = sqlite3_vmprintf(zFormat, ap);
   352         -    char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0);
   353         -    sqlite3_free(z1);
   354         -    fputs(z2, out);
   355         -    sqlite3_free(z2);
   356         -  }else{
   357         -    vfprintf(out, zFormat, ap);
   358         -  }
   359         -  va_end(ap);
   360         -}
   361         -#elif !defined(utf8_printf)
   362         -# define utf8_printf fprintf
   363         -#endif
   364         -
   365         -/*
   366         -** Render output like fprintf().  This should not be used on anything that
   367         -** includes string formatting (e.g. "%s").
   368         -*/
   369         -#if !defined(raw_printf)
   370         -# define raw_printf fprintf
   371         -#endif
   372         -
   373         -/*
   374         -** Write I/O traces to the following stream.
   375         -*/
   376         -#ifdef SQLITE_ENABLE_IOTRACE
   377         -static FILE *iotrace = 0;
   378         -#endif
   379         -
   380         -/*
   381         -** This routine works like printf in that its first argument is a
   382         -** format string and subsequent arguments are values to be substituted
   383         -** in place of % fields.  The result of formatting this string
   384         -** is written to iotrace.
   385         -*/
   386         -#ifdef SQLITE_ENABLE_IOTRACE
   387         -static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){
   388         -  va_list ap;
   389         -  char *z;
   390         -  if( iotrace==0 ) return;
   391         -  va_start(ap, zFormat);
   392         -  z = sqlite3_vmprintf(zFormat, ap);
   393         -  va_end(ap);
   394         -  utf8_printf(iotrace, "%s", z);
   395         -  sqlite3_free(z);
   396         -}
   397         -#endif
   398         -
   399         -
   400         -/*
   401         -** Determines if a string is a number of not.
   402         -*/
   403         -static int isNumber(const char *z, int *realnum){
   404         -  if( *z=='-' || *z=='+' ) z++;
   405         -  if( !IsDigit(*z) ){
   406         -    return 0;
   407         -  }
   408         -  z++;
   409         -  if( realnum ) *realnum = 0;
   410         -  while( IsDigit(*z) ){ z++; }
   411         -  if( *z=='.' ){
   412         -    z++;
   413         -    if( !IsDigit(*z) ) return 0;
   414         -    while( IsDigit(*z) ){ z++; }
   415         -    if( realnum ) *realnum = 1;
   416         -  }
   417         -  if( *z=='e' || *z=='E' ){
   418         -    z++;
   419         -    if( *z=='+' || *z=='-' ) z++;
   420         -    if( !IsDigit(*z) ) return 0;
   421         -    while( IsDigit(*z) ){ z++; }
   422         -    if( realnum ) *realnum = 1;
   423         -  }
   424         -  return *z==0;
   425         -}
   426         -
   427         -/*
   428         -** A global char* and an SQL function to access its current value
   429         -** from within an SQL statement. This program used to use the
   430         -** sqlite_exec_printf() API to substitue a string into an SQL statement.
   431         -** The correct way to do this with sqlite3 is to use the bind API, but
   432         -** since the shell is built around the callback paradigm it would be a lot
   433         -** of work. Instead just use this hack, which is quite harmless.
   434         -*/
   435         -static const char *zShellStatic = 0;
   436         -static void shellstaticFunc(
   437         -  sqlite3_context *context,
   438         -  int argc,
   439         -  sqlite3_value **argv
   440         -){
   441         -  assert( 0==argc );
   442         -  assert( zShellStatic );
   443         -  UNUSED_PARAMETER(argc);
   444         -  UNUSED_PARAMETER(argv);
   445         -  sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC);
   446         -}
   447         -
   448         -
   449         -/*
   450         -** Compute a string length that is limited to what can be stored in
   451         -** lower 30 bits of a 32-bit signed integer.
   452         -*/
   453         -static int strlen30(const char *z){
   454         -  const char *z2 = z;
   455         -  while( *z2 ){ z2++; }
   456         -  return 0x3fffffff & (int)(z2 - z);
   457         -}
   458         -
   459         -/*
   460         -** This routine reads a line of text from FILE in, stores
   461         -** the text in memory obtained from malloc() and returns a pointer
   462         -** to the text.  NULL is returned at end of file, or if malloc()
   463         -** fails.
   464         -**
   465         -** If zLine is not NULL then it is a malloced buffer returned from
   466         -** a previous call to this routine that may be reused.
   467         -*/
   468         -static char *local_getline(char *zLine, FILE *in){
   469         -  int nLine = zLine==0 ? 0 : 100;
   470         -  int n = 0;
   471         -
   472         -  while( 1 ){
   473         -    if( n+100>nLine ){
   474         -      nLine = nLine*2 + 100;
   475         -      zLine = realloc(zLine, nLine);
   476         -      if( zLine==0 ) return 0;
   477         -    }
   478         -    if( fgets(&zLine[n], nLine - n, in)==0 ){
   479         -      if( n==0 ){
   480         -        free(zLine);
   481         -        return 0;
   482         -      }
   483         -      zLine[n] = 0;
   484         -      break;
   485         -    }
   486         -    while( zLine[n] ) n++;
   487         -    if( n>0 && zLine[n-1]=='\n' ){
   488         -      n--;
   489         -      if( n>0 && zLine[n-1]=='\r' ) n--;
   490         -      zLine[n] = 0;
   491         -      break;
   492         -    }
   493         -  }
   494         -#if defined(_WIN32) || defined(WIN32)
   495         -  /* For interactive input on Windows systems, translate the
   496         -  ** multi-byte characterset characters into UTF-8. */
   497         -  if( stdin_is_interactive && in==stdin ){
   498         -    char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0);
   499         -    if( zTrans ){
   500         -      int nTrans = strlen30(zTrans)+1;
   501         -      if( nTrans>nLine ){
   502         -        zLine = realloc(zLine, nTrans);
   503         -        if( zLine==0 ){
   504         -          sqlite3_free(zTrans);
   505         -          return 0;
   506         -        }
   507         -      }
   508         -      memcpy(zLine, zTrans, nTrans);
   509         -      sqlite3_free(zTrans);
   510         -    }
   511         -  }
   512         -#endif /* defined(_WIN32) || defined(WIN32) */
   513         -  return zLine;
   514         -}
   515         -
   516         -/*
   517         -** Retrieve a single line of input text.
   518         -**
   519         -** If in==0 then read from standard input and prompt before each line.
   520         -** If isContinuation is true, then a continuation prompt is appropriate.
   521         -** If isContinuation is zero, then the main prompt should be used.
   522         -**
   523         -** If zPrior is not NULL then it is a buffer from a prior call to this
   524         -** routine that can be reused.
   525         -**
   526         -** The result is stored in space obtained from malloc() and must either
   527         -** be freed by the caller or else passed back into this routine via the
   528         -** zPrior argument for reuse.
   529         -*/
   530         -static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
   531         -  char *zPrompt;
   532         -  char *zResult;
   533         -  if( in!=0 ){
   534         -    zResult = local_getline(zPrior, in);
   535         -  }else{
   536         -    zPrompt = isContinuation ? continuePrompt : mainPrompt;
   537         -#if SHELL_USE_LOCAL_GETLINE
   538         -    printf("%s", zPrompt);
   539         -    fflush(stdout);
   540         -    zResult = local_getline(zPrior, stdin);
   541         -#else
   542         -    free(zPrior);
   543         -    zResult = shell_readline(zPrompt);
   544         -    if( zResult && *zResult ) shell_add_history(zResult);
   545         -#endif
   546         -  }
   547         -  return zResult;
   548         -}
   549         -
   550         -#if defined(SQLITE_ENABLE_SESSION)
   551         -/*
   552         -** State information for a single open session
   553         -*/
   554         -typedef struct OpenSession OpenSession;
   555         -struct OpenSession {
   556         -  char *zName;             /* Symbolic name for this session */
   557         -  int nFilter;             /* Number of xFilter rejection GLOB patterns */
   558         -  char **azFilter;         /* Array of xFilter rejection GLOB patterns */
   559         -  sqlite3_session *p;      /* The open session */
   560         -};
   561         -#endif
   562         -
   563         -/*
   564         -** Shell output mode information from before ".explain on",
   565         -** saved so that it can be restored by ".explain off"
   566         -*/
   567         -typedef struct SavedModeInfo SavedModeInfo;
   568         -struct SavedModeInfo {
   569         -  int valid;          /* Is there legit data in here? */
   570         -  int mode;           /* Mode prior to ".explain on" */
   571         -  int showHeader;     /* The ".header" setting prior to ".explain on" */
   572         -  int colWidth[100];  /* Column widths prior to ".explain on" */
   573         -};
   574         -
   575         -/*
   576         -** State information about the database connection is contained in an
   577         -** instance of the following structure.
   578         -*/
   579         -typedef struct ShellState ShellState;
   580         -struct ShellState {
   581         -  sqlite3 *db;           /* The database */
   582         -  int echoOn;            /* True to echo input commands */
   583         -  int autoExplain;       /* Automatically turn on .explain mode */
   584         -  int autoEQP;           /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */
   585         -  int statsOn;           /* True to display memory stats before each finalize */
   586         -  int scanstatsOn;       /* True to display scan stats before each finalize */
   587         -  int countChanges;      /* True to display change counts */
   588         -  int backslashOn;       /* Resolve C-style \x escapes in SQL input text */
   589         -  int outCount;          /* Revert to stdout when reaching zero */
   590         -  int cnt;               /* Number of records displayed so far */
   591         -  FILE *out;             /* Write results here */
   592         -  FILE *traceOut;        /* Output for sqlite3_trace() */
   593         -  int nErr;              /* Number of errors seen */
   594         -  int mode;              /* An output mode setting */
   595         -  int cMode;             /* temporary output mode for the current query */
   596         -  int normalMode;        /* Output mode before ".explain on" */
   597         -  int writableSchema;    /* True if PRAGMA writable_schema=ON */
   598         -  int showHeader;        /* True to show column names in List or Column mode */
   599         -  int nCheck;            /* Number of ".check" commands run */
   600         -  unsigned shellFlgs;    /* Various flags */
   601         -  char *zDestTable;      /* Name of destination table when MODE_Insert */
   602         -  char zTestcase[30];    /* Name of current test case */
   603         -  char colSeparator[20]; /* Column separator character for several modes */
   604         -  char rowSeparator[20]; /* Row separator character for MODE_Ascii */
   605         -  int colWidth[100];     /* Requested width of each column when in column mode*/
   606         -  int actualWidth[100];  /* Actual width of each column */
   607         -  char nullValue[20];    /* The text to print when a NULL comes back from
   608         -                         ** the database */
   609         -  char outfile[FILENAME_MAX]; /* Filename for *out */
   610         -  const char *zDbFilename;    /* name of the database file */
   611         -  char *zFreeOnClose;         /* Filename to free when closing */
   612         -  const char *zVfs;           /* Name of VFS to use */
   613         -  sqlite3_stmt *pStmt;   /* Current statement if any. */
   614         -  FILE *pLog;            /* Write log output here */
   615         -  int *aiIndent;         /* Array of indents used in MODE_Explain */
   616         -  int nIndent;           /* Size of array aiIndent[] */
   617         -  int iIndent;           /* Index of current op in aiIndent[] */
   618         -#if defined(SQLITE_ENABLE_SESSION)
   619         -  int nSession;             /* Number of active sessions */
   620         -  OpenSession aSession[4];  /* Array of sessions.  [0] is in focus. */
   621         -#endif
   622         -};
   623         -
   624         -/*
   625         -** These are the allowed shellFlgs values
   626         -*/
   627         -#define SHFLG_Scratch     0x00001     /* The --scratch option is used */
   628         -#define SHFLG_Pagecache   0x00002     /* The --pagecache option is used */
   629         -#define SHFLG_Lookaside   0x00004     /* Lookaside memory is used */
   630         -
   631         -/*
   632         -** These are the allowed modes.
   633         -*/
   634         -#define MODE_Line     0  /* One column per line.  Blank line between records */
   635         -#define MODE_Column   1  /* One record per line in neat columns */
   636         -#define MODE_List     2  /* One record per line with a separator */
   637         -#define MODE_Semi     3  /* Same as MODE_List but append ";" to each line */
   638         -#define MODE_Html     4  /* Generate an XHTML table */
   639         -#define MODE_Insert   5  /* Generate SQL "insert" statements */
   640         -#define MODE_Tcl      6  /* Generate ANSI-C or TCL quoted elements */
   641         -#define MODE_Csv      7  /* Quote strings, numbers are plain */
   642         -#define MODE_Explain  8  /* Like MODE_Column, but do not truncate data */
   643         -#define MODE_Ascii    9  /* Use ASCII unit and record separators (0x1F/0x1E) */
   644         -#define MODE_Pretty  10  /* Pretty-print schemas */
   645         -
   646         -static const char *const modeDescr[] = {
   647         -  "line",
   648         -  "column",
   649         -  "list",
   650         -  "semi",
   651         -  "html",
   652         -  "insert",
   653         -  "tcl",
   654         -  "csv",
   655         -  "explain",
   656         -  "ascii",
   657         -  "prettyprint",
   658         -};
   659         -
   660         -/*
   661         -** These are the column/row/line separators used by the various
   662         -** import/export modes.
   663         -*/
   664         -#define SEP_Column    "|"
   665         -#define SEP_Row       "\n"
   666         -#define SEP_Tab       "\t"
   667         -#define SEP_Space     " "
   668         -#define SEP_Comma     ","
   669         -#define SEP_CrLf      "\r\n"
   670         -#define SEP_Unit      "\x1F"
   671         -#define SEP_Record    "\x1E"
   672         -
   673         -/*
   674         -** Number of elements in an array
   675         -*/
   676         -#define ArraySize(X)  (int)(sizeof(X)/sizeof(X[0]))
   677         -
   678         -/*
   679         -** A callback for the sqlite3_log() interface.
   680         -*/
   681         -static void shellLog(void *pArg, int iErrCode, const char *zMsg){
   682         -  ShellState *p = (ShellState*)pArg;
   683         -  if( p->pLog==0 ) return;
   684         -  utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg);
   685         -  fflush(p->pLog);
   686         -}
   687         -
   688         -/*
   689         -** Output the given string as a hex-encoded blob (eg. X'1234' )
   690         -*/
   691         -static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
   692         -  int i;
   693         -  char *zBlob = (char *)pBlob;
   694         -  raw_printf(out,"X'");
   695         -  for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); }
   696         -  raw_printf(out,"'");
   697         -}
   698         -
   699         -/*
   700         -** Output the given string as a quoted string using SQL quoting conventions.
   701         -*/
   702         -static void output_quoted_string(FILE *out, const char *z){
   703         -  int i;
   704         -  int nSingle = 0;
   705         -  setBinaryMode(out, 1);
   706         -  for(i=0; z[i]; i++){
   707         -    if( z[i]=='\'' ) nSingle++;
   708         -  }
   709         -  if( nSingle==0 ){
   710         -    utf8_printf(out,"'%s'",z);
   711         -  }else{
   712         -    raw_printf(out,"'");
   713         -    while( *z ){
   714         -      for(i=0; z[i] && z[i]!='\''; i++){}
   715         -      if( i==0 ){
   716         -        raw_printf(out,"''");
   717         -        z++;
   718         -      }else if( z[i]=='\'' ){
   719         -        utf8_printf(out,"%.*s''",i,z);
   720         -        z += i+1;
   721         -      }else{
   722         -        utf8_printf(out,"%s",z);
   723         -        break;
   724         -      }
   725         -    }
   726         -    raw_printf(out,"'");
   727         -  }
   728         -  setTextMode(out, 1);
   729         -}
   730         -
   731         -/*
   732         -** Output the given string as a quoted according to C or TCL quoting rules.
   733         -*/
   734         -static void output_c_string(FILE *out, const char *z){
   735         -  unsigned int c;
   736         -  fputc('"', out);
   737         -  while( (c = *(z++))!=0 ){
   738         -    if( c=='\\' ){
   739         -      fputc(c, out);
   740         -      fputc(c, out);
   741         -    }else if( c=='"' ){
   742         -      fputc('\\', out);
   743         -      fputc('"', out);
   744         -    }else if( c=='\t' ){
   745         -      fputc('\\', out);
   746         -      fputc('t', out);
   747         -    }else if( c=='\n' ){
   748         -      fputc('\\', out);
   749         -      fputc('n', out);
   750         -    }else if( c=='\r' ){
   751         -      fputc('\\', out);
   752         -      fputc('r', out);
   753         -    }else if( !isprint(c&0xff) ){
   754         -      raw_printf(out, "\\%03o", c&0xff);
   755         -    }else{
   756         -      fputc(c, out);
   757         -    }
   758         -  }
   759         -  fputc('"', out);
   760         -}
   761         -
   762         -/*
   763         -** Output the given string with characters that are special to
   764         -** HTML escaped.
   765         -*/
   766         -static void output_html_string(FILE *out, const char *z){
   767         -  int i;
   768         -  if( z==0 ) z = "";
   769         -  while( *z ){
   770         -    for(i=0;   z[i]
   771         -            && z[i]!='<'
   772         -            && z[i]!='&'
   773         -            && z[i]!='>'
   774         -            && z[i]!='\"'
   775         -            && z[i]!='\'';
   776         -        i++){}
   777         -    if( i>0 ){
   778         -      utf8_printf(out,"%.*s",i,z);
   779         -    }
   780         -    if( z[i]=='<' ){
   781         -      raw_printf(out,"&lt;");
   782         -    }else if( z[i]=='&' ){
   783         -      raw_printf(out,"&amp;");
   784         -    }else if( z[i]=='>' ){
   785         -      raw_printf(out,"&gt;");
   786         -    }else if( z[i]=='\"' ){
   787         -      raw_printf(out,"&quot;");
   788         -    }else if( z[i]=='\'' ){
   789         -      raw_printf(out,"&#39;");
   790         -    }else{
   791         -      break;
   792         -    }
   793         -    z += i + 1;
   794         -  }
   795         -}
   796         -
   797         -/*
   798         -** If a field contains any character identified by a 1 in the following
   799         -** array, then the string must be quoted for CSV.
   800         -*/
   801         -static const char needCsvQuote[] = {
   802         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   803         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   804         -  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0,
   805         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   806         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   807         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   808         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,
   809         -  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1,
   810         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   811         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   812         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   813         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   814         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   815         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   816         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   817         -  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,
   818         -};
   819         -
   820         -/*
   821         -** Output a single term of CSV.  Actually, p->colSeparator is used for
   822         -** the separator, which may or may not be a comma.  p->nullValue is
   823         -** the null value.  Strings are quoted if necessary.  The separator
   824         -** is only issued if bSep is true.
   825         -*/
   826         -static void output_csv(ShellState *p, const char *z, int bSep){
   827         -  FILE *out = p->out;
   828         -  if( z==0 ){
   829         -    utf8_printf(out,"%s",p->nullValue);
   830         -  }else{
   831         -    int i;
   832         -    int nSep = strlen30(p->colSeparator);
   833         -    for(i=0; z[i]; i++){
   834         -      if( needCsvQuote[((unsigned char*)z)[i]]
   835         -         || (z[i]==p->colSeparator[0] &&
   836         -             (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){
   837         -        i = 0;
   838         -        break;
   839         -      }
   840         -    }
   841         -    if( i==0 ){
   842         -      putc('"', out);
   843         -      for(i=0; z[i]; i++){
   844         -        if( z[i]=='"' ) putc('"', out);
   845         -        putc(z[i], out);
   846         -      }
   847         -      putc('"', out);
   848         -    }else{
   849         -      utf8_printf(out, "%s", z);
   850         -    }
   851         -  }
   852         -  if( bSep ){
   853         -    utf8_printf(p->out, "%s", p->colSeparator);
   854         -  }
   855         -}
   856         -
   857         -#if defined(SIGINT) || defined(_WIN32) || defined(WIN32)
   858         -/*
   859         -** This routine runs when the user presses Ctrl-C
   860         -*/
   861         -static void interrupt_handler(int NotUsed){
   862         -  UNUSED_PARAMETER(NotUsed);
   863         -  seenInterrupt++;
   864         -  if( seenInterrupt>2 ) exit(1);
   865         -  if( globalDb ) sqlite3_interrupt(globalDb);
   866         -}
   867         -
   868         -#if defined(_WIN32) || defined(WIN32)
   869         -/*
   870         -** Windows event handler
   871         -*/
   872         -BOOL WINAPI CtrlHandler(DWORD dwType){
   873         -  switch( dwType ){
   874         -    case CTRL_C_EVENT:
   875         -      interrupt_handler(0);
   876         -      return TRUE;
   877         -
   878         -    default:
   879         -      return FALSE;
   880         -  }
   881         -}
   882         -#endif
   883         -#endif
   884         -
   885         -#ifndef SQLITE_OMIT_AUTHORIZATION
   886         -/*
   887         -** When the ".auth ON" is set, the following authorizer callback is
   888         -** invoked.  It always returns SQLITE_OK.
   889         -*/
   890         -static int shellAuth(
   891         -  void *pClientData,
   892         -  int op,
   893         -  const char *zA1,
   894         -  const char *zA2,
   895         -  const char *zA3,
   896         -  const char *zA4
   897         -){
   898         -  ShellState *p = (ShellState*)pClientData;
   899         -  static const char *const azAction[] = { 0,
   900         -     "CREATE_INDEX",         "CREATE_TABLE",         "CREATE_TEMP_INDEX",
   901         -     "CREATE_TEMP_TABLE",    "CREATE_TEMP_TRIGGER",  "CREATE_TEMP_VIEW",
   902         -     "CREATE_TRIGGER",       "CREATE_VIEW",          "DELETE",
   903         -     "DROP_INDEX",           "DROP_TABLE",           "DROP_TEMP_INDEX",
   904         -     "DROP_TEMP_TABLE",      "DROP_TEMP_TRIGGER",    "DROP_TEMP_VIEW",
   905         -     "DROP_TRIGGER",         "DROP_VIEW",            "INSERT",
   906         -     "PRAGMA",               "READ",                 "SELECT",
   907         -     "TRANSACTION",          "UPDATE",               "ATTACH",
   908         -     "DETACH",               "ALTER_TABLE",          "REINDEX",
   909         -     "ANALYZE",              "CREATE_VTABLE",        "DROP_VTABLE",
   910         -     "FUNCTION",             "SAVEPOINT",            "RECURSIVE"
   911         -  };
   912         -  int i;
   913         -  const char *az[4];
   914         -  az[0] = zA1;
   915         -  az[1] = zA2;
   916         -  az[2] = zA3;
   917         -  az[3] = zA4;
   918         -  utf8_printf(p->out, "authorizer: %s", azAction[op]);
   919         -  for(i=0; i<4; i++){
   920         -    raw_printf(p->out, " ");
   921         -    if( az[i] ){
   922         -      output_c_string(p->out, az[i]);
   923         -    }else{
   924         -      raw_printf(p->out, "NULL");
   925         -    }
   926         -  }
   927         -  raw_printf(p->out, "\n");
   928         -  return SQLITE_OK;
   929         -}
   930         -#endif
   931         -
   932         -
   933         -/*
   934         -** This is the callback routine that the shell
   935         -** invokes for each row of a query result.
   936         -*/
   937         -static int shell_callback(
   938         -  void *pArg,
   939         -  int nArg,        /* Number of result columns */
   940         -  char **azArg,    /* Text of each result column */
   941         -  char **azCol,    /* Column names */
   942         -  int *aiType      /* Column types */
   943         -){
   944         -  int i;
   945         -  ShellState *p = (ShellState*)pArg;
   946         -
   947         -  switch( p->cMode ){
   948         -    case MODE_Line: {
   949         -      int w = 5;
   950         -      if( azArg==0 ) break;
   951         -      for(i=0; i<nArg; i++){
   952         -        int len = strlen30(azCol[i] ? azCol[i] : "");
   953         -        if( len>w ) w = len;
   954         -      }
   955         -      if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator);
   956         -      for(i=0; i<nArg; i++){
   957         -        utf8_printf(p->out,"%*s = %s%s", w, azCol[i],
   958         -                azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator);
   959         -      }
   960         -      break;
   961         -    }
   962         -    case MODE_Explain:
   963         -    case MODE_Column: {
   964         -      static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
   965         -      const int *colWidth;
   966         -      int showHdr;
   967         -      char *rowSep;
   968         -      if( p->cMode==MODE_Column ){
   969         -        colWidth = p->colWidth;
   970         -        showHdr = p->showHeader;
   971         -        rowSep = p->rowSeparator;
   972         -      }else{
   973         -        colWidth = aExplainWidths;
   974         -        showHdr = 1;
   975         -        rowSep = SEP_Row;
   976         -      }
   977         -      if( p->cnt++==0 ){
   978         -        for(i=0; i<nArg; i++){
   979         -          int w, n;
   980         -          if( i<ArraySize(p->colWidth) ){
   981         -            w = colWidth[i];
   982         -          }else{
   983         -            w = 0;
   984         -          }
   985         -          if( w==0 ){
   986         -            w = strlen30(azCol[i] ? azCol[i] : "");
   987         -            if( w<10 ) w = 10;
   988         -            n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue);
   989         -            if( w<n ) w = n;
   990         -          }
   991         -          if( i<ArraySize(p->actualWidth) ){
   992         -            p->actualWidth[i] = w;
   993         -          }
   994         -          if( showHdr ){
   995         -            if( w<0 ){
   996         -              utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i],
   997         -                      i==nArg-1 ? rowSep : "  ");
   998         -            }else{
   999         -              utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i],
  1000         -                      i==nArg-1 ? rowSep : "  ");
  1001         -            }
  1002         -          }
  1003         -        }
  1004         -        if( showHdr ){
  1005         -          for(i=0; i<nArg; i++){
  1006         -            int w;
  1007         -            if( i<ArraySize(p->actualWidth) ){
  1008         -               w = p->actualWidth[i];
  1009         -               if( w<0 ) w = -w;
  1010         -            }else{
  1011         -               w = 10;
  1012         -            }
  1013         -            utf8_printf(p->out,"%-*.*s%s",w,w,
  1014         -                   "----------------------------------------------------------"
  1015         -                   "----------------------------------------------------------",
  1016         -                    i==nArg-1 ? rowSep : "  ");
  1017         -          }
  1018         -        }
  1019         -      }
  1020         -      if( azArg==0 ) break;
  1021         -      for(i=0; i<nArg; i++){
  1022         -        int w;
  1023         -        if( i<ArraySize(p->actualWidth) ){
  1024         -           w = p->actualWidth[i];
  1025         -        }else{
  1026         -           w = 10;
  1027         -        }
  1028         -        if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){
  1029         -          w = strlen30(azArg[i]);
  1030         -        }
  1031         -        if( i==1 && p->aiIndent && p->pStmt ){
  1032         -          if( p->iIndent<p->nIndent ){
  1033         -            utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], "");
  1034         -          }
  1035         -          p->iIndent++;
  1036         -        }
  1037         -        if( w<0 ){
  1038         -          utf8_printf(p->out,"%*.*s%s",-w,-w,
  1039         -              azArg[i] ? azArg[i] : p->nullValue,
  1040         -              i==nArg-1 ? rowSep : "  ");
  1041         -        }else{
  1042         -          utf8_printf(p->out,"%-*.*s%s",w,w,
  1043         -              azArg[i] ? azArg[i] : p->nullValue,
  1044         -              i==nArg-1 ? rowSep : "  ");
  1045         -        }
  1046         -      }
  1047         -      break;
  1048         -    }
  1049         -    case MODE_Semi: {   /* .schema and .fullschema output */
  1050         -      utf8_printf(p->out, "%s;\n", azArg[0]);
  1051         -      break;
  1052         -    }
  1053         -    case MODE_Pretty: {  /* .schema and .fullschema with --indent */
  1054         -      char *z;
  1055         -      int j;
  1056         -      int nParen = 0;
  1057         -      char cEnd = 0;
  1058         -      char c;
  1059         -      int nLine = 0;
  1060         -      assert( nArg==1 );
  1061         -      if( azArg[0]==0 ) break;
  1062         -      if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0
  1063         -       || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0
  1064         -      ){
  1065         -        utf8_printf(p->out, "%s;\n", azArg[0]);
  1066         -        break;
  1067         -      }
  1068         -      z = sqlite3_mprintf("%s", azArg[0]);
  1069         -      j = 0;
  1070         -      for(i=0; IsSpace(z[i]); i++){}
  1071         -      for(; (c = z[i])!=0; i++){
  1072         -        if( IsSpace(c) ){
  1073         -          if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue;
  1074         -        }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){
  1075         -          j--;
  1076         -        }
  1077         -        z[j++] = c;
  1078         -      }
  1079         -      while( j>0 && IsSpace(z[j-1]) ){ j--; }
  1080         -      z[j] = 0;
  1081         -      if( strlen30(z)>=79 ){
  1082         -        for(i=j=0; (c = z[i])!=0; i++){
  1083         -          if( c==cEnd ){
  1084         -            cEnd = 0;
  1085         -          }else if( c=='"' || c=='\'' || c=='`' ){
  1086         -            cEnd = c;
  1087         -          }else if( c=='[' ){
  1088         -            cEnd = ']';
  1089         -          }else if( c=='(' ){
  1090         -            nParen++;
  1091         -          }else if( c==')' ){
  1092         -            nParen--;
  1093         -            if( nLine>0 && nParen==0 && j>0 ){
  1094         -              utf8_printf(p->out, "%.*s\n", j, z);
  1095         -              j = 0;
  1096         -            }
  1097         -          }
  1098         -          z[j++] = c;
  1099         -          if( nParen==1 && (c=='(' || c==',' || c=='\n') ){
  1100         -            if( c=='\n' ) j--;
  1101         -            utf8_printf(p->out, "%.*s\n  ", j, z);
  1102         -            j = 0;
  1103         -            nLine++;
  1104         -            while( IsSpace(z[i+1]) ){ i++; }
  1105         -          }
  1106         -        }
  1107         -        z[j] = 0;
  1108         -      }
  1109         -      utf8_printf(p->out, "%s;\n", z);
  1110         -      sqlite3_free(z);
  1111         -      break;
  1112         -    }
  1113         -    case MODE_List: {
  1114         -      if( p->cnt++==0 && p->showHeader ){
  1115         -        for(i=0; i<nArg; i++){
  1116         -          utf8_printf(p->out,"%s%s",azCol[i],
  1117         -                  i==nArg-1 ? p->rowSeparator : p->colSeparator);
  1118         -        }
  1119         -      }
  1120         -      if( azArg==0 ) break;
  1121         -      for(i=0; i<nArg; i++){
  1122         -        char *z = azArg[i];
  1123         -        if( z==0 ) z = p->nullValue;
  1124         -        utf8_printf(p->out, "%s", z);
  1125         -        if( i<nArg-1 ){
  1126         -          utf8_printf(p->out, "%s", p->colSeparator);
  1127         -        }else{
  1128         -          utf8_printf(p->out, "%s", p->rowSeparator);
  1129         -        }
  1130         -      }
  1131         -      break;
  1132         -    }
  1133         -    case MODE_Html: {
  1134         -      if( p->cnt++==0 && p->showHeader ){
  1135         -        raw_printf(p->out,"<TR>");
  1136         -        for(i=0; i<nArg; i++){
  1137         -          raw_printf(p->out,"<TH>");
  1138         -          output_html_string(p->out, azCol[i]);
  1139         -          raw_printf(p->out,"</TH>\n");
  1140         -        }
  1141         -        raw_printf(p->out,"</TR>\n");
  1142         -      }
  1143         -      if( azArg==0 ) break;
  1144         -      raw_printf(p->out,"<TR>");
  1145         -      for(i=0; i<nArg; i++){
  1146         -        raw_printf(p->out,"<TD>");
  1147         -        output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  1148         -        raw_printf(p->out,"</TD>\n");
  1149         -      }
  1150         -      raw_printf(p->out,"</TR>\n");
  1151         -      break;
  1152         -    }
  1153         -    case MODE_Tcl: {
  1154         -      if( p->cnt++==0 && p->showHeader ){
  1155         -        for(i=0; i<nArg; i++){
  1156         -          output_c_string(p->out,azCol[i] ? azCol[i] : "");
  1157         -          if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  1158         -        }
  1159         -        utf8_printf(p->out, "%s", p->rowSeparator);
  1160         -      }
  1161         -      if( azArg==0 ) break;
  1162         -      for(i=0; i<nArg; i++){
  1163         -        output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue);
  1164         -        if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator);
  1165         -      }
  1166         -      utf8_printf(p->out, "%s", p->rowSeparator);
  1167         -      break;
  1168         -    }
  1169         -    case MODE_Csv: {
  1170         -      setBinaryMode(p->out, 1);
  1171         -      if( p->cnt++==0 && p->showHeader ){
  1172         -        for(i=0; i<nArg; i++){
  1173         -          output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1);
  1174         -        }
  1175         -        utf8_printf(p->out, "%s", p->rowSeparator);
  1176         -      }
  1177         -      if( nArg>0 ){
  1178         -        for(i=0; i<nArg; i++){
  1179         -          output_csv(p, azArg[i], i<nArg-1);
  1180         -        }
  1181         -        utf8_printf(p->out, "%s", p->rowSeparator);
  1182         -      }
  1183         -      setTextMode(p->out, 1);
  1184         -      break;
  1185         -    }
  1186         -    case MODE_Insert: {
  1187         -      p->cnt++;
  1188         -      if( azArg==0 ) break;
  1189         -      utf8_printf(p->out,"INSERT INTO %s",p->zDestTable);
  1190         -      if( p->showHeader ){
  1191         -        raw_printf(p->out,"(");
  1192         -        for(i=0; i<nArg; i++){
  1193         -          char *zSep = i>0 ? ",": "";
  1194         -          utf8_printf(p->out, "%s%s", zSep, azCol[i]);
  1195         -        }
  1196         -        raw_printf(p->out,")");
  1197         -      }
  1198         -      raw_printf(p->out," VALUES(");
  1199         -      for(i=0; i<nArg; i++){
  1200         -        char *zSep = i>0 ? ",": "";
  1201         -        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
  1202         -          utf8_printf(p->out,"%sNULL",zSep);
  1203         -        }else if( aiType && aiType[i]==SQLITE_TEXT ){
  1204         -          if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1205         -          output_quoted_string(p->out, azArg[i]);
  1206         -        }else if( aiType && (aiType[i]==SQLITE_INTEGER
  1207         -                             || aiType[i]==SQLITE_FLOAT) ){
  1208         -          utf8_printf(p->out,"%s%s",zSep, azArg[i]);
  1209         -        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
  1210         -          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
  1211         -          int nBlob = sqlite3_column_bytes(p->pStmt, i);
  1212         -          if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1213         -          output_hex_blob(p->out, pBlob, nBlob);
  1214         -        }else if( isNumber(azArg[i], 0) ){
  1215         -          utf8_printf(p->out,"%s%s",zSep, azArg[i]);
  1216         -        }else{
  1217         -          if( zSep[0] ) utf8_printf(p->out,"%s",zSep);
  1218         -          output_quoted_string(p->out, azArg[i]);
  1219         -        }
  1220         -      }
  1221         -      raw_printf(p->out,");\n");
  1222         -      break;
  1223         -    }
  1224         -    case MODE_Ascii: {
  1225         -      if( p->cnt++==0 && p->showHeader ){
  1226         -        for(i=0; i<nArg; i++){
  1227         -          if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  1228         -          utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : "");
  1229         -        }
  1230         -        utf8_printf(p->out, "%s", p->rowSeparator);
  1231         -      }
  1232         -      if( azArg==0 ) break;
  1233         -      for(i=0; i<nArg; i++){
  1234         -        if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator);
  1235         -        utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue);
  1236         -      }
  1237         -      utf8_printf(p->out, "%s", p->rowSeparator);
  1238         -      break;
  1239         -    }
  1240         -  }
  1241         -  return 0;
  1242         -}
  1243         -
  1244         -/*
  1245         -** This is the callback routine that the SQLite library
  1246         -** invokes for each row of a query result.
  1247         -*/
  1248         -static int callback(void *pArg, int nArg, char **azArg, char **azCol){
  1249         -  /* since we don't have type info, call the shell_callback with a NULL value */
  1250         -  return shell_callback(pArg, nArg, azArg, azCol, NULL);
  1251         -}
  1252         -
  1253         -/*
  1254         -** Set the destination table field of the ShellState structure to
  1255         -** the name of the table given.  Escape any quote characters in the
  1256         -** table name.
  1257         -*/
  1258         -static void set_table_name(ShellState *p, const char *zName){
  1259         -  int i, n;
  1260         -  int needQuote;
  1261         -  char *z;
  1262         -
  1263         -  if( p->zDestTable ){
  1264         -    free(p->zDestTable);
  1265         -    p->zDestTable = 0;
  1266         -  }
  1267         -  if( zName==0 ) return;
  1268         -  needQuote = !isalpha((unsigned char)*zName) && *zName!='_';
  1269         -  for(i=n=0; zName[i]; i++, n++){
  1270         -    if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){
  1271         -      needQuote = 1;
  1272         -      if( zName[i]=='\'' ) n++;
  1273         -    }
  1274         -  }
  1275         -  if( needQuote ) n += 2;
  1276         -  z = p->zDestTable = malloc( n+1 );
  1277         -  if( z==0 ){
  1278         -    raw_printf(stderr,"Error: out of memory\n");
  1279         -    exit(1);
  1280         -  }
  1281         -  n = 0;
  1282         -  if( needQuote ) z[n++] = '\'';
  1283         -  for(i=0; zName[i]; i++){
  1284         -    z[n++] = zName[i];
  1285         -    if( zName[i]=='\'' ) z[n++] = '\'';
  1286         -  }
  1287         -  if( needQuote ) z[n++] = '\'';
  1288         -  z[n] = 0;
  1289         -}
  1290         -
  1291         -/* zIn is either a pointer to a NULL-terminated string in memory obtained
  1292         -** from malloc(), or a NULL pointer. The string pointed to by zAppend is
  1293         -** added to zIn, and the result returned in memory obtained from malloc().
  1294         -** zIn, if it was not NULL, is freed.
  1295         -**
  1296         -** If the third argument, quote, is not '\0', then it is used as a
  1297         -** quote character for zAppend.
  1298         -*/
  1299         -static char *appendText(char *zIn, char const *zAppend, char quote){
  1300         -  int len;
  1301         -  int i;
  1302         -  int nAppend = strlen30(zAppend);
  1303         -  int nIn = (zIn?strlen30(zIn):0);
  1304         -
  1305         -  len = nAppend+nIn+1;
  1306         -  if( quote ){
  1307         -    len += 2;
  1308         -    for(i=0; i<nAppend; i++){
  1309         -      if( zAppend[i]==quote ) len++;
  1310         -    }
  1311         -  }
  1312         -
  1313         -  zIn = (char *)realloc(zIn, len);
  1314         -  if( !zIn ){
  1315         -    return 0;
  1316         -  }
  1317         -
  1318         -  if( quote ){
  1319         -    char *zCsr = &zIn[nIn];
  1320         -    *zCsr++ = quote;
  1321         -    for(i=0; i<nAppend; i++){
  1322         -      *zCsr++ = zAppend[i];
  1323         -      if( zAppend[i]==quote ) *zCsr++ = quote;
  1324         -    }
  1325         -    *zCsr++ = quote;
  1326         -    *zCsr++ = '\0';
  1327         -    assert( (zCsr-zIn)==len );
  1328         -  }else{
  1329         -    memcpy(&zIn[nIn], zAppend, nAppend);
  1330         -    zIn[len-1] = '\0';
  1331         -  }
  1332         -
  1333         -  return zIn;
  1334         -}
  1335         -
  1336         -
  1337         -/*
  1338         -** Execute a query statement that will generate SQL output.  Print
  1339         -** the result columns, comma-separated, on a line and then add a
  1340         -** semicolon terminator to the end of that line.
  1341         -**
  1342         -** If the number of columns is 1 and that column contains text "--"
  1343         -** then write the semicolon on a separate line.  That way, if a
  1344         -** "--" comment occurs at the end of the statement, the comment
  1345         -** won't consume the semicolon terminator.
  1346         -*/
  1347         -static int run_table_dump_query(
  1348         -  ShellState *p,           /* Query context */
  1349         -  const char *zSelect,     /* SELECT statement to extract content */
  1350         -  const char *zFirstRow    /* Print before first row, if not NULL */
  1351         -){
  1352         -  sqlite3_stmt *pSelect;
  1353         -  int rc;
  1354         -  int nResult;
  1355         -  int i;
  1356         -  const char *z;
  1357         -  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  1358         -  if( rc!=SQLITE_OK || !pSelect ){
  1359         -    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  1360         -                sqlite3_errmsg(p->db));
  1361         -    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1362         -    return rc;
  1363         -  }
  1364         -  rc = sqlite3_step(pSelect);
  1365         -  nResult = sqlite3_column_count(pSelect);
  1366         -  while( rc==SQLITE_ROW ){
  1367         -    if( zFirstRow ){
  1368         -      utf8_printf(p->out, "%s", zFirstRow);
  1369         -      zFirstRow = 0;
  1370         -    }
  1371         -    z = (const char*)sqlite3_column_text(pSelect, 0);
  1372         -    utf8_printf(p->out, "%s", z);
  1373         -    for(i=1; i<nResult; i++){
  1374         -      utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i));
  1375         -    }
  1376         -    if( z==0 ) z = "";
  1377         -    while( z[0] && (z[0]!='-' || z[1]!='-') ) z++;
  1378         -    if( z[0] ){
  1379         -      raw_printf(p->out, "\n;\n");
  1380         -    }else{
  1381         -      raw_printf(p->out, ";\n");
  1382         -    }
  1383         -    rc = sqlite3_step(pSelect);
  1384         -  }
  1385         -  rc = sqlite3_finalize(pSelect);
  1386         -  if( rc!=SQLITE_OK ){
  1387         -    utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc,
  1388         -                sqlite3_errmsg(p->db));
  1389         -    if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1390         -  }
  1391         -  return rc;
  1392         -}
  1393         -
  1394         -/*
  1395         -** Allocate space and save off current error string.
  1396         -*/
  1397         -static char *save_err_msg(
  1398         -  sqlite3 *db            /* Database to query */
  1399         -){
  1400         -  int nErrMsg = 1+strlen30(sqlite3_errmsg(db));
  1401         -  char *zErrMsg = sqlite3_malloc(nErrMsg);
  1402         -  if( zErrMsg ){
  1403         -    memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg);
  1404         -  }
  1405         -  return zErrMsg;
  1406         -}
  1407         -
  1408         -#ifdef __linux__
  1409         -/*
  1410         -** Attempt to display I/O stats on Linux using /proc/PID/io
  1411         -*/
  1412         -static void displayLinuxIoStats(FILE *out){
  1413         -  FILE *in;
  1414         -  char z[200];
  1415         -  sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid());
  1416         -  in = fopen(z, "rb");
  1417         -  if( in==0 ) return;
  1418         -  while( fgets(z, sizeof(z), in)!=0 ){
  1419         -    static const struct {
  1420         -      const char *zPattern;
  1421         -      const char *zDesc;
  1422         -    } aTrans[] = {
  1423         -      { "rchar: ",                  "Bytes received by read():" },
  1424         -      { "wchar: ",                  "Bytes sent to write():"    },
  1425         -      { "syscr: ",                  "Read() system calls:"      },
  1426         -      { "syscw: ",                  "Write() system calls:"     },
  1427         -      { "read_bytes: ",             "Bytes read from storage:"  },
  1428         -      { "write_bytes: ",            "Bytes written to storage:" },
  1429         -      { "cancelled_write_bytes: ",  "Cancelled write bytes:"    },
  1430         -    };
  1431         -    int i;
  1432         -    for(i=0; i<ArraySize(aTrans); i++){
  1433         -      int n = (int)strlen(aTrans[i].zPattern);
  1434         -      if( strncmp(aTrans[i].zPattern, z, n)==0 ){
  1435         -        utf8_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]);
  1436         -        break;
  1437         -      }
  1438         -    }
  1439         -  }
  1440         -  fclose(in);
  1441         -}
  1442         -#endif
  1443         -
  1444         -
  1445         -/*
  1446         -** Display memory stats.
  1447         -*/
  1448         -static int display_stats(
  1449         -  sqlite3 *db,                /* Database to query */
  1450         -  ShellState *pArg,           /* Pointer to ShellState */
  1451         -  int bReset                  /* True to reset the stats */
  1452         -){
  1453         -  int iCur;
  1454         -  int iHiwtr;
  1455         -
  1456         -  if( pArg && pArg->out ){
  1457         -
  1458         -    iHiwtr = iCur = -1;
  1459         -    sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset);
  1460         -    raw_printf(pArg->out,
  1461         -            "Memory Used:                         %d (max %d) bytes\n",
  1462         -            iCur, iHiwtr);
  1463         -    iHiwtr = iCur = -1;
  1464         -    sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset);
  1465         -    raw_printf(pArg->out, "Number of Outstanding Allocations:   %d (max %d)\n",
  1466         -            iCur, iHiwtr);
  1467         -    if( pArg->shellFlgs & SHFLG_Pagecache ){
  1468         -      iHiwtr = iCur = -1;
  1469         -      sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset);
  1470         -      raw_printf(pArg->out,
  1471         -              "Number of Pcache Pages Used:         %d (max %d) pages\n",
  1472         -              iCur, iHiwtr);
  1473         -    }
  1474         -    iHiwtr = iCur = -1;
  1475         -    sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset);
  1476         -    raw_printf(pArg->out,
  1477         -            "Number of Pcache Overflow Bytes:     %d (max %d) bytes\n",
  1478         -            iCur, iHiwtr);
  1479         -    if( pArg->shellFlgs & SHFLG_Scratch ){
  1480         -      iHiwtr = iCur = -1;
  1481         -      sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset);
  1482         -      raw_printf(pArg->out,
  1483         -              "Number of Scratch Allocations Used:  %d (max %d)\n",
  1484         -              iCur, iHiwtr);
  1485         -    }
  1486         -    iHiwtr = iCur = -1;
  1487         -    sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset);
  1488         -    raw_printf(pArg->out,
  1489         -            "Number of Scratch Overflow Bytes:    %d (max %d) bytes\n",
  1490         -            iCur, iHiwtr);
  1491         -    iHiwtr = iCur = -1;
  1492         -    sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset);
  1493         -    raw_printf(pArg->out, "Largest Allocation:                  %d bytes\n",
  1494         -            iHiwtr);
  1495         -    iHiwtr = iCur = -1;
  1496         -    sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset);
  1497         -    raw_printf(pArg->out, "Largest Pcache Allocation:           %d bytes\n",
  1498         -            iHiwtr);
  1499         -    iHiwtr = iCur = -1;
  1500         -    sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset);
  1501         -    raw_printf(pArg->out, "Largest Scratch Allocation:          %d bytes\n",
  1502         -            iHiwtr);
  1503         -#ifdef YYTRACKMAXSTACKDEPTH
  1504         -    iHiwtr = iCur = -1;
  1505         -    sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset);
  1506         -    raw_printf(pArg->out, "Deepest Parser Stack:                %d (max %d)\n",
  1507         -            iCur, iHiwtr);
  1508         -#endif
  1509         -  }
  1510         -
  1511         -  if( pArg && pArg->out && db ){
  1512         -    if( pArg->shellFlgs & SHFLG_Lookaside ){
  1513         -      iHiwtr = iCur = -1;
  1514         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED,
  1515         -                        &iCur, &iHiwtr, bReset);
  1516         -      raw_printf(pArg->out,
  1517         -              "Lookaside Slots Used:                %d (max %d)\n",
  1518         -              iCur, iHiwtr);
  1519         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT,
  1520         -                        &iCur, &iHiwtr, bReset);
  1521         -      raw_printf(pArg->out, "Successful lookaside attempts:       %d\n",
  1522         -              iHiwtr);
  1523         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE,
  1524         -                        &iCur, &iHiwtr, bReset);
  1525         -      raw_printf(pArg->out, "Lookaside failures due to size:      %d\n",
  1526         -              iHiwtr);
  1527         -      sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL,
  1528         -                        &iCur, &iHiwtr, bReset);
  1529         -      raw_printf(pArg->out, "Lookaside failures due to OOM:       %d\n",
  1530         -              iHiwtr);
  1531         -    }
  1532         -    iHiwtr = iCur = -1;
  1533         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset);
  1534         -    raw_printf(pArg->out, "Pager Heap Usage:                    %d bytes\n",
  1535         -            iCur);
  1536         -    iHiwtr = iCur = -1;
  1537         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1);
  1538         -    raw_printf(pArg->out, "Page cache hits:                     %d\n", iCur);
  1539         -    iHiwtr = iCur = -1;
  1540         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1);
  1541         -    raw_printf(pArg->out, "Page cache misses:                   %d\n", iCur);
  1542         -    iHiwtr = iCur = -1;
  1543         -    sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1);
  1544         -    raw_printf(pArg->out, "Page cache writes:                   %d\n", iCur);
  1545         -    iHiwtr = iCur = -1;
  1546         -    sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset);
  1547         -    raw_printf(pArg->out, "Schema Heap Usage:                   %d bytes\n",
  1548         -            iCur);
  1549         -    iHiwtr = iCur = -1;
  1550         -    sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset);
  1551         -    raw_printf(pArg->out, "Statement Heap/Lookaside Usage:      %d bytes\n",
  1552         -            iCur);
  1553         -  }
  1554         -
  1555         -  if( pArg && pArg->out && db && pArg->pStmt ){
  1556         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP,
  1557         -                               bReset);
  1558         -    raw_printf(pArg->out, "Fullscan Steps:                      %d\n", iCur);
  1559         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset);
  1560         -    raw_printf(pArg->out, "Sort Operations:                     %d\n", iCur);
  1561         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset);
  1562         -    raw_printf(pArg->out, "Autoindex Inserts:                   %d\n", iCur);
  1563         -    iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset);
  1564         -    raw_printf(pArg->out, "Virtual Machine Steps:               %d\n", iCur);
  1565         -  }
  1566         -
  1567         -#ifdef __linux__
  1568         -  displayLinuxIoStats(pArg->out);
  1569         -#endif
  1570         -
  1571         -  /* Do not remove this machine readable comment: extra-stats-output-here */
  1572         -
  1573         -  return 0;
  1574         -}
  1575         -
  1576         -/*
  1577         -** Display scan stats.
  1578         -*/
  1579         -static void display_scanstats(
  1580         -  sqlite3 *db,                    /* Database to query */
  1581         -  ShellState *pArg                /* Pointer to ShellState */
  1582         -){
  1583         -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  1584         -  UNUSED_PARAMETER(db);
  1585         -  UNUSED_PARAMETER(pArg);
  1586         -#else
  1587         -  int i, k, n, mx;
  1588         -  raw_printf(pArg->out, "-------- scanstats --------\n");
  1589         -  mx = 0;
  1590         -  for(k=0; k<=mx; k++){
  1591         -    double rEstLoop = 1.0;
  1592         -    for(i=n=0; 1; i++){
  1593         -      sqlite3_stmt *p = pArg->pStmt;
  1594         -      sqlite3_int64 nLoop, nVisit;
  1595         -      double rEst;
  1596         -      int iSid;
  1597         -      const char *zExplain;
  1598         -      if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){
  1599         -        break;
  1600         -      }
  1601         -      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid);
  1602         -      if( iSid>mx ) mx = iSid;
  1603         -      if( iSid!=k ) continue;
  1604         -      if( n==0 ){
  1605         -        rEstLoop = (double)nLoop;
  1606         -        if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k);
  1607         -      }
  1608         -      n++;
  1609         -      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit);
  1610         -      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst);
  1611         -      sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain);
  1612         -      utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain);
  1613         -      rEstLoop *= rEst;
  1614         -      raw_printf(pArg->out,
  1615         -          "         nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n",
  1616         -          nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst
  1617         -      );
  1618         -    }
  1619         -  }
  1620         -  raw_printf(pArg->out, "---------------------------\n");
  1621         -#endif
  1622         -}
  1623         -
  1624         -/*
  1625         -** Parameter azArray points to a zero-terminated array of strings. zStr
  1626         -** points to a single nul-terminated string. Return non-zero if zStr
  1627         -** is equal, according to strcmp(), to any of the strings in the array.
  1628         -** Otherwise, return zero.
  1629         -*/
  1630         -static int str_in_array(const char *zStr, const char *const *azArray){
  1631         -  int i;
  1632         -  for(i=0; azArray[i]; i++){
  1633         -    if( 0==strcmp(zStr, azArray[i]) ) return 1;
  1634         -  }
  1635         -  return 0;
  1636         -}
  1637         -
  1638         -/*
  1639         -** If compiled statement pSql appears to be an EXPLAIN statement, allocate
  1640         -** and populate the ShellState.aiIndent[] array with the number of
  1641         -** spaces each opcode should be indented before it is output.
  1642         -**
  1643         -** The indenting rules are:
  1644         -**
  1645         -**     * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent
  1646         -**       all opcodes that occur between the p2 jump destination and the opcode
  1647         -**       itself by 2 spaces.
  1648         -**
  1649         -**     * For each "Goto", if the jump destination is earlier in the program
  1650         -**       and ends on one of:
  1651         -**          Yield  SeekGt  SeekLt  RowSetRead  Rewind
  1652         -**       or if the P1 parameter is one instead of zero,
  1653         -**       then indent all opcodes between the earlier instruction
  1654         -**       and "Goto" by 2 spaces.
  1655         -*/
  1656         -static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){
  1657         -  const char *zSql;               /* The text of the SQL statement */
  1658         -  const char *z;                  /* Used to check if this is an EXPLAIN */
  1659         -  int *abYield = 0;               /* True if op is an OP_Yield */
  1660         -  int nAlloc = 0;                 /* Allocated size of p->aiIndent[], abYield */
  1661         -  int iOp;                        /* Index of operation in p->aiIndent[] */
  1662         -
  1663         -  const char *const azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext",
  1664         -                           "NextIfOpen", "PrevIfOpen", 0 };
  1665         -  const char *const azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead",
  1666         -                            "Rewind", 0 };
  1667         -  const char *const azGoto[] = { "Goto", 0 };
  1668         -
  1669         -  /* Try to figure out if this is really an EXPLAIN statement. If this
  1670         -  ** cannot be verified, return early.  */
  1671         -  if( sqlite3_column_count(pSql)!=8 ){
  1672         -    p->cMode = p->mode;
  1673         -    return;
  1674         -  }
  1675         -  zSql = sqlite3_sql(pSql);
  1676         -  if( zSql==0 ) return;
  1677         -  for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++);
  1678         -  if( sqlite3_strnicmp(z, "explain", 7) ){
  1679         -    p->cMode = p->mode;
  1680         -    return;
  1681         -  }
  1682         -
  1683         -  for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){
  1684         -    int i;
  1685         -    int iAddr = sqlite3_column_int(pSql, 0);
  1686         -    const char *zOp = (const char*)sqlite3_column_text(pSql, 1);
  1687         -
  1688         -    /* Set p2 to the P2 field of the current opcode. Then, assuming that
  1689         -    ** p2 is an instruction address, set variable p2op to the index of that
  1690         -    ** instruction in the aiIndent[] array. p2 and p2op may be different if
  1691         -    ** the current instruction is part of a sub-program generated by an
  1692         -    ** SQL trigger or foreign key.  */
  1693         -    int p2 = sqlite3_column_int(pSql, 3);
  1694         -    int p2op = (p2 + (iOp-iAddr));
  1695         -
  1696         -    /* Grow the p->aiIndent array as required */
  1697         -    if( iOp>=nAlloc ){
  1698         -      if( iOp==0 ){
  1699         -        /* Do further verfication that this is explain output.  Abort if
  1700         -        ** it is not */
  1701         -        static const char *const explainCols[] = {
  1702         -           "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" };
  1703         -        int jj;
  1704         -        for(jj=0; jj<ArraySize(explainCols); jj++){
  1705         -          if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){
  1706         -            p->cMode = p->mode;
  1707         -            sqlite3_reset(pSql);
  1708         -            return;
  1709         -          }
  1710         -        }
  1711         -      }
  1712         -      nAlloc += 100;
  1713         -      p->aiIndent = (int*)sqlite3_realloc(p->aiIndent, nAlloc*sizeof(int));
  1714         -      abYield = (int*)sqlite3_realloc(abYield, nAlloc*sizeof(int));
  1715         -    }
  1716         -    abYield[iOp] = str_in_array(zOp, azYield);
  1717         -    p->aiIndent[iOp] = 0;
  1718         -    p->nIndent = iOp+1;
  1719         -
  1720         -    if( str_in_array(zOp, azNext) ){
  1721         -      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  1722         -    }
  1723         -    if( str_in_array(zOp, azGoto) && p2op<p->nIndent
  1724         -     && (abYield[p2op] || sqlite3_column_int(pSql, 2))
  1725         -    ){
  1726         -      for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2;
  1727         -    }
  1728         -  }
  1729         -
  1730         -  p->iIndent = 0;
  1731         -  sqlite3_free(abYield);
  1732         -  sqlite3_reset(pSql);
  1733         -}
  1734         -
  1735         -/*
  1736         -** Free the array allocated by explain_data_prepare().
  1737         -*/
  1738         -static void explain_data_delete(ShellState *p){
  1739         -  sqlite3_free(p->aiIndent);
  1740         -  p->aiIndent = 0;
  1741         -  p->nIndent = 0;
  1742         -  p->iIndent = 0;
  1743         -}
  1744         -
  1745         -/*
  1746         -** Disable and restore .wheretrace and .selecttrace settings.
  1747         -*/
  1748         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  1749         -extern int sqlite3SelectTrace;
  1750         -static int savedSelectTrace;
  1751         -#endif
  1752         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  1753         -extern int sqlite3WhereTrace;
  1754         -static int savedWhereTrace;
  1755         -#endif
  1756         -static void disable_debug_trace_modes(void){
  1757         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  1758         -  savedSelectTrace = sqlite3SelectTrace;
  1759         -  sqlite3SelectTrace = 0;
  1760         -#endif
  1761         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  1762         -  savedWhereTrace = sqlite3WhereTrace;
  1763         -  sqlite3WhereTrace = 0;
  1764         -#endif
  1765         -}
  1766         -static void restore_debug_trace_modes(void){
  1767         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  1768         -  sqlite3SelectTrace = savedSelectTrace;
  1769         -#endif
  1770         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  1771         -  sqlite3WhereTrace = savedWhereTrace;
  1772         -#endif
  1773         -}
  1774         -
  1775         -/*
  1776         -** Run a prepared statement
  1777         -*/
  1778         -static void exec_prepared_stmt(
  1779         -  ShellState *pArg,                                /* Pointer to ShellState */
  1780         -  sqlite3_stmt *pStmt,                             /* Statment to run */
  1781         -  int (*xCallback)(void*,int,char**,char**,int*)   /* Callback function */
  1782         -){
  1783         -  int rc;
  1784         -
  1785         -  /* perform the first step.  this will tell us if we
  1786         -  ** have a result set or not and how wide it is.
  1787         -  */
  1788         -  rc = sqlite3_step(pStmt);
  1789         -  /* if we have a result set... */
  1790         -  if( SQLITE_ROW == rc ){
  1791         -    /* if we have a callback... */
  1792         -    if( xCallback ){
  1793         -      /* allocate space for col name ptr, value ptr, and type */
  1794         -      int nCol = sqlite3_column_count(pStmt);
  1795         -      void *pData = sqlite3_malloc(3*nCol*sizeof(const char*) + 1);
  1796         -      if( !pData ){
  1797         -        rc = SQLITE_NOMEM;
  1798         -      }else{
  1799         -        char **azCols = (char **)pData;      /* Names of result columns */
  1800         -        char **azVals = &azCols[nCol];       /* Results */
  1801         -        int *aiTypes = (int *)&azVals[nCol]; /* Result types */
  1802         -        int i, x;
  1803         -        assert(sizeof(int) <= sizeof(char *));
  1804         -        /* save off ptrs to column names */
  1805         -        for(i=0; i<nCol; i++){
  1806         -          azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  1807         -        }
  1808         -        do{
  1809         -          /* extract the data and data types */
  1810         -          for(i=0; i<nCol; i++){
  1811         -            aiTypes[i] = x = sqlite3_column_type(pStmt, i);
  1812         -            if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){
  1813         -              azVals[i] = "";
  1814         -            }else{
  1815         -              azVals[i] = (char*)sqlite3_column_text(pStmt, i);
  1816         -            }
  1817         -            if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){
  1818         -              rc = SQLITE_NOMEM;
  1819         -              break; /* from for */
  1820         -            }
  1821         -          } /* end for */
  1822         -
  1823         -          /* if data and types extracted successfully... */
  1824         -          if( SQLITE_ROW == rc ){
  1825         -            /* call the supplied callback with the result row data */
  1826         -            if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){
  1827         -              rc = SQLITE_ABORT;
  1828         -            }else{
  1829         -              rc = sqlite3_step(pStmt);
  1830         -            }
  1831         -          }
  1832         -        } while( SQLITE_ROW == rc );
  1833         -        sqlite3_free(pData);
  1834         -      }
  1835         -    }else{
  1836         -      do{
  1837         -        rc = sqlite3_step(pStmt);
  1838         -      } while( rc == SQLITE_ROW );
  1839         -    }
  1840         -  }
  1841         -}
  1842         -
  1843         -/*
  1844         -** Execute a statement or set of statements.  Print
  1845         -** any result rows/columns depending on the current mode
  1846         -** set via the supplied callback.
  1847         -**
  1848         -** This is very similar to SQLite's built-in sqlite3_exec()
  1849         -** function except it takes a slightly different callback
  1850         -** and callback data argument.
  1851         -*/
  1852         -static int shell_exec(
  1853         -  sqlite3 *db,                              /* An open database */
  1854         -  const char *zSql,                         /* SQL to be evaluated */
  1855         -  int (*xCallback)(void*,int,char**,char**,int*),   /* Callback function */
  1856         -                                            /* (not the same as sqlite3_exec) */
  1857         -  ShellState *pArg,                         /* Pointer to ShellState */
  1858         -  char **pzErrMsg                           /* Error msg written here */
  1859         -){
  1860         -  sqlite3_stmt *pStmt = NULL;     /* Statement to execute. */
  1861         -  int rc = SQLITE_OK;             /* Return Code */
  1862         -  int rc2;
  1863         -  const char *zLeftover;          /* Tail of unprocessed SQL */
  1864         -
  1865         -  if( pzErrMsg ){
  1866         -    *pzErrMsg = NULL;
  1867         -  }
  1868         -
  1869         -  while( zSql[0] && (SQLITE_OK == rc) ){
  1870         -    static const char *zStmtSql;
  1871         -    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  1872         -    if( SQLITE_OK != rc ){
  1873         -      if( pzErrMsg ){
  1874         -        *pzErrMsg = save_err_msg(db);
  1875         -      }
  1876         -    }else{
  1877         -      if( !pStmt ){
  1878         -        /* this happens for a comment or white-space */
  1879         -        zSql = zLeftover;
  1880         -        while( IsSpace(zSql[0]) ) zSql++;
  1881         -        continue;
  1882         -      }
  1883         -      zStmtSql = sqlite3_sql(pStmt);
  1884         -      while( IsSpace(zStmtSql[0]) ) zStmtSql++;
  1885         -
  1886         -      /* save off the prepared statment handle and reset row count */
  1887         -      if( pArg ){
  1888         -        pArg->pStmt = pStmt;
  1889         -        pArg->cnt = 0;
  1890         -      }
  1891         -
  1892         -      /* echo the sql statement if echo on */
  1893         -      if( pArg && pArg->echoOn ){
  1894         -        utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1895         -      }
  1896         -
  1897         -      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
  1898         -      if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){
  1899         -        sqlite3_stmt *pExplain;
  1900         -        char *zEQP;
  1901         -        disable_debug_trace_modes();
  1902         -        zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql);
  1903         -        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  1904         -        if( rc==SQLITE_OK ){
  1905         -          while( sqlite3_step(pExplain)==SQLITE_ROW ){
  1906         -            raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0));
  1907         -            raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
  1908         -            raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
  1909         -            utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
  1910         -          }
  1911         -        }
  1912         -        sqlite3_finalize(pExplain);
  1913         -        sqlite3_free(zEQP);
  1914         -        if( pArg->autoEQP>=2 ){
  1915         -          /* Also do an EXPLAIN for ".eqp full" mode */
  1916         -          zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql);
  1917         -          rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
  1918         -          if( rc==SQLITE_OK ){
  1919         -            pArg->cMode = MODE_Explain;
  1920         -            explain_data_prepare(pArg, pExplain);
  1921         -            exec_prepared_stmt(pArg, pExplain, xCallback);
  1922         -            explain_data_delete(pArg);
  1923         -          }
  1924         -          sqlite3_finalize(pExplain);
  1925         -          sqlite3_free(zEQP);
  1926         -        }
  1927         -        restore_debug_trace_modes();
  1928         -      }
  1929         -
  1930         -      if( pArg ){
  1931         -        pArg->cMode = pArg->mode;
  1932         -        if( pArg->autoExplain
  1933         -         && sqlite3_column_count(pStmt)==8
  1934         -         && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0
  1935         -        ){
  1936         -          pArg->cMode = MODE_Explain;
  1937         -        }
  1938         -
  1939         -        /* If the shell is currently in ".explain" mode, gather the extra
  1940         -        ** data required to add indents to the output.*/
  1941         -        if( pArg->cMode==MODE_Explain ){
  1942         -          explain_data_prepare(pArg, pStmt);
  1943         -        }
  1944         -      }
  1945         -
  1946         -      exec_prepared_stmt(pArg, pStmt, xCallback);
  1947         -      explain_data_delete(pArg);
  1948         -
  1949         -      /* print usage stats if stats on */
  1950         -      if( pArg && pArg->statsOn ){
  1951         -        display_stats(db, pArg, 0);
  1952         -      }
  1953         -
  1954         -      /* print loop-counters if required */
  1955         -      if( pArg && pArg->scanstatsOn ){
  1956         -        display_scanstats(db, pArg);
  1957         -      }
  1958         -
  1959         -      /* Finalize the statement just executed. If this fails, save a
  1960         -      ** copy of the error message. Otherwise, set zSql to point to the
  1961         -      ** next statement to execute. */
  1962         -      rc2 = sqlite3_finalize(pStmt);
  1963         -      if( rc!=SQLITE_NOMEM ) rc = rc2;
  1964         -      if( rc==SQLITE_OK ){
  1965         -        zSql = zLeftover;
  1966         -        while( IsSpace(zSql[0]) ) zSql++;
  1967         -      }else if( pzErrMsg ){
  1968         -        *pzErrMsg = save_err_msg(db);
  1969         -      }
  1970         -
  1971         -      /* clear saved stmt handle */
  1972         -      if( pArg ){
  1973         -        pArg->pStmt = NULL;
  1974         -      }
  1975         -    }
  1976         -  } /* end while */
  1977         -
  1978         -  return rc;
  1979         -}
  1980         -
  1981         -
  1982         -/*
  1983         -** This is a different callback routine used for dumping the database.
  1984         -** Each row received by this callback consists of a table name,
  1985         -** the table type ("index" or "table") and SQL to create the table.
  1986         -** This routine should print text sufficient to recreate the table.
  1987         -*/
  1988         -static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
  1989         -  int rc;
  1990         -  const char *zTable;
  1991         -  const char *zType;
  1992         -  const char *zSql;
  1993         -  const char *zPrepStmt = 0;
  1994         -  ShellState *p = (ShellState *)pArg;
  1995         -
  1996         -  UNUSED_PARAMETER(azCol);
  1997         -  if( nArg!=3 ) return 1;
  1998         -  zTable = azArg[0];
  1999         -  zType = azArg[1];
  2000         -  zSql = azArg[2];
  2001         -
  2002         -  if( strcmp(zTable, "sqlite_sequence")==0 ){
  2003         -    zPrepStmt = "DELETE FROM sqlite_sequence;\n";
  2004         -  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
  2005         -    raw_printf(p->out, "ANALYZE sqlite_master;\n");
  2006         -  }else if( strncmp(zTable, "sqlite_", 7)==0 ){
  2007         -    return 0;
  2008         -  }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
  2009         -    char *zIns;
  2010         -    if( !p->writableSchema ){
  2011         -      raw_printf(p->out, "PRAGMA writable_schema=ON;\n");
  2012         -      p->writableSchema = 1;
  2013         -    }
  2014         -    zIns = sqlite3_mprintf(
  2015         -       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
  2016         -       "VALUES('table','%q','%q',0,'%q');",
  2017         -       zTable, zTable, zSql);
  2018         -    utf8_printf(p->out, "%s\n", zIns);
  2019         -    sqlite3_free(zIns);
  2020         -    return 0;
  2021         -  }else{
  2022         -    utf8_printf(p->out, "%s;\n", zSql);
  2023         -  }
  2024         -
  2025         -  if( strcmp(zType, "table")==0 ){
  2026         -    sqlite3_stmt *pTableInfo = 0;
  2027         -    char *zSelect = 0;
  2028         -    char *zTableInfo = 0;
  2029         -    char *zTmp = 0;
  2030         -    int nRow = 0;
  2031         -
  2032         -    zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  2033         -    zTableInfo = appendText(zTableInfo, zTable, '"');
  2034         -    zTableInfo = appendText(zTableInfo, ");", 0);
  2035         -
  2036         -    rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
  2037         -    free(zTableInfo);
  2038         -    if( rc!=SQLITE_OK || !pTableInfo ){
  2039         -      return 1;
  2040         -    }
  2041         -
  2042         -    zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  2043         -    /* Always quote the table name, even if it appears to be pure ascii,
  2044         -    ** in case it is a keyword. Ex:  INSERT INTO "table" ... */
  2045         -    zTmp = appendText(zTmp, zTable, '"');
  2046         -    if( zTmp ){
  2047         -      zSelect = appendText(zSelect, zTmp, '\'');
  2048         -      free(zTmp);
  2049         -    }
  2050         -    zSelect = appendText(zSelect, " || ' VALUES(' || ", 0);
  2051         -    rc = sqlite3_step(pTableInfo);
  2052         -    while( rc==SQLITE_ROW ){
  2053         -      const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1);
  2054         -      zSelect = appendText(zSelect, "quote(", 0);
  2055         -      zSelect = appendText(zSelect, zText, '"');
  2056         -      rc = sqlite3_step(pTableInfo);
  2057         -      if( rc==SQLITE_ROW ){
  2058         -        zSelect = appendText(zSelect, "), ", 0);
  2059         -      }else{
  2060         -        zSelect = appendText(zSelect, ") ", 0);
  2061         -      }
  2062         -      nRow++;
  2063         -    }
  2064         -    rc = sqlite3_finalize(pTableInfo);
  2065         -    if( rc!=SQLITE_OK || nRow==0 ){
  2066         -      free(zSelect);
  2067         -      return 1;
  2068         -    }
  2069         -    zSelect = appendText(zSelect, "|| ')' FROM  ", 0);
  2070         -    zSelect = appendText(zSelect, zTable, '"');
  2071         -
  2072         -    rc = run_table_dump_query(p, zSelect, zPrepStmt);
  2073         -    if( rc==SQLITE_CORRUPT ){
  2074         -      zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0);
  2075         -      run_table_dump_query(p, zSelect, 0);
  2076         -    }
  2077         -    free(zSelect);
  2078         -  }
  2079         -  return 0;
  2080         -}
  2081         -
  2082         -/*
  2083         -** Run zQuery.  Use dump_callback() as the callback routine so that
  2084         -** the contents of the query are output as SQL statements.
  2085         -**
  2086         -** If we get a SQLITE_CORRUPT error, rerun the query after appending
  2087         -** "ORDER BY rowid DESC" to the end.
  2088         -*/
  2089         -static int run_schema_dump_query(
  2090         -  ShellState *p,
  2091         -  const char *zQuery
  2092         -){
  2093         -  int rc;
  2094         -  char *zErr = 0;
  2095         -  rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr);
  2096         -  if( rc==SQLITE_CORRUPT ){
  2097         -    char *zQ2;
  2098         -    int len = strlen30(zQuery);
  2099         -    raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n");
  2100         -    if( zErr ){
  2101         -      utf8_printf(p->out, "/****** %s ******/\n", zErr);
  2102         -      sqlite3_free(zErr);
  2103         -      zErr = 0;
  2104         -    }
  2105         -    zQ2 = malloc( len+100 );
  2106         -    if( zQ2==0 ) return rc;
  2107         -    sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery);
  2108         -    rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr);
  2109         -    if( rc ){
  2110         -      utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr);
  2111         -    }else{
  2112         -      rc = SQLITE_CORRUPT;
  2113         -    }
  2114         -    sqlite3_free(zErr);
  2115         -    free(zQ2);
  2116         -  }
  2117         -  return rc;
  2118         -}
  2119         -
  2120         -/*
  2121         -** Text of a help message
  2122         -*/
  2123         -static char zHelp[] =
  2124         -#ifndef SQLITE_OMIT_AUTHORIZATION
  2125         -  ".auth ON|OFF           Show authorizer callbacks\n"
  2126         -#endif
  2127         -  ".backup ?DB? FILE      Backup DB (default \"main\") to FILE\n"
  2128         -  ".bail on|off           Stop after hitting an error.  Default OFF\n"
  2129         -  ".binary on|off         Turn binary output on or off.  Default OFF\n"
  2130         -  ".changes on|off        Show number of rows changed by SQL\n"
  2131         -  ".check GLOB            Fail if output since .testcase does not match\n"
  2132         -  ".clone NEWDB           Clone data into NEWDB from the existing database\n"
  2133         -  ".databases             List names and files of attached databases\n"
  2134         -  ".dbinfo ?DB?           Show status information about the database\n"
  2135         -  ".dump ?TABLE? ...      Dump the database in an SQL text format\n"
  2136         -  "                         If TABLE specified, only dump tables matching\n"
  2137         -  "                         LIKE pattern TABLE.\n"
  2138         -  ".echo on|off           Turn command echo on or off\n"
  2139         -  ".eqp on|off|full       Enable or disable automatic EXPLAIN QUERY PLAN\n"
  2140         -  ".exit                  Exit this program\n"
  2141         -  ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n"
  2142         -  ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n"
  2143         -  ".headers on|off        Turn display of headers on or off\n"
  2144         -  ".help                  Show this message\n"
  2145         -  ".import FILE TABLE     Import data from FILE into TABLE\n"
  2146         -  ".indexes ?TABLE?       Show names of all indexes\n"
  2147         -  "                         If TABLE specified, only show indexes for tables\n"
  2148         -  "                         matching LIKE pattern TABLE.\n"
  2149         -#ifdef SQLITE_ENABLE_IOTRACE
  2150         -  ".iotrace FILE          Enable I/O diagnostic logging to FILE\n"
  2151         -#endif
  2152         -  ".limit ?LIMIT? ?VAL?   Display or change the value of an SQLITE_LIMIT\n"
  2153         -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  2154         -  ".load FILE ?ENTRY?     Load an extension library\n"
  2155         -#endif
  2156         -  ".log FILE|off          Turn logging on or off.  FILE can be stderr/stdout\n"
  2157         -  ".mode MODE ?TABLE?     Set output mode where MODE is one of:\n"
  2158         -  "                         ascii    Columns/rows delimited by 0x1F and 0x1E\n"
  2159         -  "                         csv      Comma-separated values\n"
  2160         -  "                         column   Left-aligned columns.  (See .width)\n"
  2161         -  "                         html     HTML <table> code\n"
  2162         -  "                         insert   SQL insert statements for TABLE\n"
  2163         -  "                         line     One value per line\n"
  2164         -  "                         list     Values delimited by .separator strings\n"
  2165         -  "                         tabs     Tab-separated values\n"
  2166         -  "                         tcl      TCL list elements\n"
  2167         -  ".nullvalue STRING      Use STRING in place of NULL values\n"
  2168         -  ".once FILENAME         Output for the next SQL command only to FILENAME\n"
  2169         -  ".open ?--new? ?FILE?   Close existing database and reopen FILE\n"
  2170         -  "                         The --new starts with an empty file\n"
  2171         -  ".output ?FILENAME?     Send output to FILENAME or stdout\n"
  2172         -  ".print STRING...       Print literal STRING\n"
  2173         -  ".prompt MAIN CONTINUE  Replace the standard prompts\n"
  2174         -  ".quit                  Exit this program\n"
  2175         -  ".read FILENAME         Execute SQL in FILENAME\n"
  2176         -  ".restore ?DB? FILE     Restore content of DB (default \"main\") from FILE\n"
  2177         -  ".save FILE             Write in-memory database into FILE\n"
  2178         -  ".scanstats on|off      Turn sqlite3_stmt_scanstatus() metrics on or off\n"
  2179         -  ".schema ?PATTERN?      Show the CREATE statements matching PATTERN\n"
  2180         -  "                          Add --indent for pretty-printing\n"
  2181         -  ".separator COL ?ROW?   Change the column separator and optionally the row\n"
  2182         -  "                         separator for both the output mode and .import\n"
  2183         -#if defined(SQLITE_ENABLE_SESSION)
  2184         -  ".session CMD ...       Create or control sessions\n"
  2185         -#endif
  2186         -  ".shell CMD ARGS...     Run CMD ARGS... in a system shell\n"
  2187         -  ".show                  Show the current values for various settings\n"
  2188         -  ".stats ?on|off?        Show stats or turn stats on or off\n"
  2189         -  ".system CMD ARGS...    Run CMD ARGS... in a system shell\n"
  2190         -  ".tables ?TABLE?        List names of tables\n"
  2191         -  "                         If TABLE specified, only list tables matching\n"
  2192         -  "                         LIKE pattern TABLE.\n"
  2193         -  ".testcase NAME         Begin redirecting output to 'testcase-out.txt'\n"
  2194         -  ".timeout MS            Try opening locked tables for MS milliseconds\n"
  2195         -  ".timer on|off          Turn SQL timer on or off\n"
  2196         -  ".trace FILE|off        Output each SQL statement as it is run\n"
  2197         -  ".vfsinfo ?AUX?         Information about the top-level VFS\n"
  2198         -  ".vfslist               List all available VFSes\n"
  2199         -  ".vfsname ?AUX?         Print the name of the VFS stack\n"
  2200         -  ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
  2201         -  "                         Negative values right-justify\n"
  2202         -;
  2203         -
  2204         -#if defined(SQLITE_ENABLE_SESSION)
  2205         -/*
  2206         -** Print help information for the ".sessions" command
  2207         -*/
  2208         -void session_help(ShellState *p){
  2209         -  raw_printf(p->out,
  2210         -    ".session ?NAME? SUBCOMMAND ?ARGS...?\n"
  2211         -    "If ?NAME? is omitted, the first defined session is used.\n"
  2212         -    "Subcommands:\n"
  2213         -    "   attach TABLE             Attach TABLE\n"
  2214         -    "   changeset FILE           Write a changeset into FILE\n"
  2215         -    "   close                    Close one session\n"
  2216         -    "   enable ?BOOLEAN?         Set or query the enable bit\n"
  2217         -    "   filter GLOB...           Reject tables matching GLOBs\n"
  2218         -    "   indirect ?BOOLEAN?       Mark or query the indirect status\n"
  2219         -    "   isempty                  Query whether the session is empty\n"
  2220         -    "   list                     List currently open session names\n"
  2221         -    "   open DB NAME             Open a new session on DB\n"
  2222         -    "   patchset FILE            Write a patchset into FILE\n"
  2223         -  );
  2224         -}
  2225         -#endif
  2226         -
  2227         -
  2228         -/* Forward reference */
  2229         -static int process_input(ShellState *p, FILE *in);
  2230         -
  2231         -
  2232         -/*
  2233         -** Read the content of a file into memory obtained from sqlite3_malloc64().
  2234         -** The caller is responsible for freeing the memory.
  2235         -**
  2236         -** NULL is returned if any error is encountered.
  2237         -*/
  2238         -static char *readFile(const char *zName){
  2239         -  FILE *in = fopen(zName, "rb");
  2240         -  size_t nIn;
  2241         -  size_t nRead;
  2242         -  char *pBuf;
  2243         -  if( in==0 ) return 0;
  2244         -  fseek(in, 0, SEEK_END);
  2245         -  nIn = ftell(in);
  2246         -  rewind(in);
  2247         -  pBuf = sqlite3_malloc( nIn+1 );
  2248         -  if( pBuf==0 ) return 0;
  2249         -  nRead = fread(pBuf, nIn, 1, in);
  2250         -  fclose(in);
  2251         -  if( nRead!=1 ){
  2252         -    sqlite3_free(pBuf);
  2253         -    return 0;
  2254         -  }
  2255         -  pBuf[nIn] = 0;
  2256         -  return pBuf;
  2257         -}
  2258         -
  2259         -/*
  2260         -** Implementation of the "readfile(X)" SQL function.  The entire content
  2261         -** of the file named X is read and returned as a BLOB.  NULL is returned
  2262         -** if the file does not exist or is unreadable.
  2263         -*/
  2264         -static void readfileFunc(
  2265         -  sqlite3_context *context,
  2266         -  int argc,
  2267         -  sqlite3_value **argv
  2268         -){
  2269         -  const char *zName;
  2270         -  void *pBuf;
  2271         -
  2272         -  UNUSED_PARAMETER(argc);
  2273         -  zName = (const char*)sqlite3_value_text(argv[0]);
  2274         -  if( zName==0 ) return;
  2275         -  pBuf = readFile(zName);
  2276         -  if( pBuf ) sqlite3_result_blob(context, pBuf, -1, sqlite3_free);
  2277         -}
  2278         -
  2279         -/*
  2280         -** Implementation of the "writefile(X,Y)" SQL function.  The argument Y
  2281         -** is written into file X.  The number of bytes written is returned.  Or
  2282         -** NULL is returned if something goes wrong, such as being unable to open
  2283         -** file X for writing.
  2284         -*/
  2285         -static void writefileFunc(
  2286         -  sqlite3_context *context,
  2287         -  int argc,
  2288         -  sqlite3_value **argv
  2289         -){
  2290         -  FILE *out;
  2291         -  const char *z;
  2292         -  sqlite3_int64 rc;
  2293         -  const char *zFile;
  2294         -
  2295         -  UNUSED_PARAMETER(argc);
  2296         -  zFile = (const char*)sqlite3_value_text(argv[0]);
  2297         -  if( zFile==0 ) return;
  2298         -  out = fopen(zFile, "wb");
  2299         -  if( out==0 ) return;
  2300         -  z = (const char*)sqlite3_value_blob(argv[1]);
  2301         -  if( z==0 ){
  2302         -    rc = 0;
  2303         -  }else{
  2304         -    rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out);
  2305         -  }
  2306         -  fclose(out);
  2307         -  sqlite3_result_int64(context, rc);
  2308         -}
  2309         -
  2310         -#if defined(SQLITE_ENABLE_SESSION)
  2311         -/*
  2312         -** Close a single OpenSession object and release all of its associated
  2313         -** resources.
  2314         -*/
  2315         -static void session_close(OpenSession *pSession){
  2316         -  int i;
  2317         -  sqlite3session_delete(pSession->p);
  2318         -  sqlite3_free(pSession->zName);
  2319         -  for(i=0; i<pSession->nFilter; i++){
  2320         -    sqlite3_free(pSession->azFilter[i]);
  2321         -  }
  2322         -  sqlite3_free(pSession->azFilter);
  2323         -  memset(pSession, 0, sizeof(OpenSession));
  2324         -}
  2325         -#endif
  2326         -
  2327         -/*
  2328         -** Close all OpenSession objects and release all associated resources.
  2329         -*/
  2330         -#if defined(SQLITE_ENABLE_SESSION)
  2331         -static void session_close_all(ShellState *p){
  2332         -  int i;
  2333         -  for(i=0; i<p->nSession; i++){
  2334         -    session_close(&p->aSession[i]);
  2335         -  }
  2336         -  p->nSession = 0;
  2337         -}
  2338         -#else
  2339         -# define session_close_all(X)
  2340         -#endif
  2341         -
  2342         -/*
  2343         -** Implementation of the xFilter function for an open session.  Omit
  2344         -** any tables named by ".session filter" but let all other table through.
  2345         -*/
  2346         -#if defined(SQLITE_ENABLE_SESSION)
  2347         -static int session_filter(void *pCtx, const char *zTab){
  2348         -  OpenSession *pSession = (OpenSession*)pCtx;
  2349         -  int i;
  2350         -  for(i=0; i<pSession->nFilter; i++){
  2351         -    if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0;
  2352         -  }
  2353         -  return 1;
  2354         -}
  2355         -#endif
  2356         -
  2357         -/*
  2358         -** Make sure the database is open.  If it is not, then open it.  If
  2359         -** the database fails to open, print an error message and exit.
  2360         -*/
  2361         -static void open_db(ShellState *p, int keepAlive){
  2362         -  if( p->db==0 ){
  2363         -    sqlite3_initialize();
  2364         -    sqlite3_open(p->zDbFilename, &p->db);
  2365         -    globalDb = p->db;
  2366         -    if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){
  2367         -      sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0,
  2368         -          shellstaticFunc, 0, 0);
  2369         -    }
  2370         -    if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){
  2371         -      utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n",
  2372         -          p->zDbFilename, sqlite3_errmsg(p->db));
  2373         -      if( keepAlive ) return;
  2374         -      exit(1);
  2375         -    }
  2376         -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  2377         -    sqlite3_enable_load_extension(p->db, 1);
  2378         -#endif
  2379         -    sqlite3_db_config(p->db, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, (char *)0);
  2380         -    sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0,
  2381         -                            readfileFunc, 0, 0);
  2382         -    sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0,
  2383         -                            writefileFunc, 0, 0);
  2384         -  }
  2385         -}
  2386         -
  2387         -/*
  2388         -** Do C-language style dequoting.
  2389         -**
  2390         -**    \a    -> alarm
  2391         -**    \b    -> backspace
  2392         -**    \t    -> tab
  2393         -**    \n    -> newline
  2394         -**    \v    -> vertical tab
  2395         -**    \f    -> form feed
  2396         -**    \r    -> carriage return
  2397         -**    \s    -> space
  2398         -**    \"    -> "
  2399         -**    \'    -> '
  2400         -**    \\    -> backslash
  2401         -**    \NNN  -> ascii character NNN in octal
  2402         -*/
  2403         -static void resolve_backslashes(char *z){
  2404         -  int i, j;
  2405         -  char c;
  2406         -  while( *z && *z!='\\' ) z++;
  2407         -  for(i=j=0; (c = z[i])!=0; i++, j++){
  2408         -    if( c=='\\' && z[i+1]!=0 ){
  2409         -      c = z[++i];
  2410         -      if( c=='a' ){
  2411         -        c = '\a';
  2412         -      }else if( c=='b' ){
  2413         -        c = '\b';
  2414         -      }else if( c=='t' ){
  2415         -        c = '\t';
  2416         -      }else if( c=='n' ){
  2417         -        c = '\n';
  2418         -      }else if( c=='v' ){
  2419         -        c = '\v';
  2420         -      }else if( c=='f' ){
  2421         -        c = '\f';
  2422         -      }else if( c=='r' ){
  2423         -        c = '\r';
  2424         -      }else if( c=='"' ){
  2425         -        c = '"';
  2426         -      }else if( c=='\'' ){
  2427         -        c = '\'';
  2428         -      }else if( c=='\\' ){
  2429         -        c = '\\';
  2430         -      }else if( c>='0' && c<='7' ){
  2431         -        c -= '0';
  2432         -        if( z[i+1]>='0' && z[i+1]<='7' ){
  2433         -          i++;
  2434         -          c = (c<<3) + z[i] - '0';
  2435         -          if( z[i+1]>='0' && z[i+1]<='7' ){
  2436         -            i++;
  2437         -            c = (c<<3) + z[i] - '0';
  2438         -          }
  2439         -        }
  2440         -      }
  2441         -    }
  2442         -    z[j] = c;
  2443         -  }
  2444         -  if( j<i ) z[j] = 0;
  2445         -}
  2446         -
  2447         -/*
  2448         -** Return the value of a hexadecimal digit.  Return -1 if the input
  2449         -** is not a hex digit.
  2450         -*/
  2451         -static int hexDigitValue(char c){
  2452         -  if( c>='0' && c<='9' ) return c - '0';
  2453         -  if( c>='a' && c<='f' ) return c - 'a' + 10;
  2454         -  if( c>='A' && c<='F' ) return c - 'A' + 10;
  2455         -  return -1;
  2456         -}
  2457         -
  2458         -/*
  2459         -** Interpret zArg as an integer value, possibly with suffixes.
  2460         -*/
  2461         -static sqlite3_int64 integerValue(const char *zArg){
  2462         -  sqlite3_int64 v = 0;
  2463         -  static const struct { char zSuffix[4]; int iMult; } aMult[] = {
  2464         -    { "KiB", 1024 },
  2465         -    { "MiB", 1024*1024 },
  2466         -    { "GiB", 1024*1024*1024 },
  2467         -    { "KB",  1000 },
  2468         -    { "MB",  1000000 },
  2469         -    { "GB",  1000000000 },
  2470         -    { "K",   1000 },
  2471         -    { "M",   1000000 },
  2472         -    { "G",   1000000000 },
  2473         -  };
  2474         -  int i;
  2475         -  int isNeg = 0;
  2476         -  if( zArg[0]=='-' ){
  2477         -    isNeg = 1;
  2478         -    zArg++;
  2479         -  }else if( zArg[0]=='+' ){
  2480         -    zArg++;
  2481         -  }
  2482         -  if( zArg[0]=='0' && zArg[1]=='x' ){
  2483         -    int x;
  2484         -    zArg += 2;
  2485         -    while( (x = hexDigitValue(zArg[0]))>=0 ){
  2486         -      v = (v<<4) + x;
  2487         -      zArg++;
  2488         -    }
  2489         -  }else{
  2490         -    while( IsDigit(zArg[0]) ){
  2491         -      v = v*10 + zArg[0] - '0';
  2492         -      zArg++;
  2493         -    }
  2494         -  }
  2495         -  for(i=0; i<ArraySize(aMult); i++){
  2496         -    if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
  2497         -      v *= aMult[i].iMult;
  2498         -      break;
  2499         -    }
  2500         -  }
  2501         -  return isNeg? -v : v;
  2502         -}
  2503         -
  2504         -/*
  2505         -** Interpret zArg as either an integer or a boolean value.  Return 1 or 0
  2506         -** for TRUE and FALSE.  Return the integer value if appropriate.
  2507         -*/
  2508         -static int booleanValue(const char *zArg){
  2509         -  int i;
  2510         -  if( zArg[0]=='0' && zArg[1]=='x' ){
  2511         -    for(i=2; hexDigitValue(zArg[i])>=0; i++){}
  2512         -  }else{
  2513         -    for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){}
  2514         -  }
  2515         -  if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff);
  2516         -  if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){
  2517         -    return 1;
  2518         -  }
  2519         -  if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){
  2520         -    return 0;
  2521         -  }
  2522         -  utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n",
  2523         -          zArg);
  2524         -  return 0;
  2525         -}
  2526         -
  2527         -/*
  2528         -** Close an output file, assuming it is not stderr or stdout
  2529         -*/
  2530         -static void output_file_close(FILE *f){
  2531         -  if( f && f!=stdout && f!=stderr ) fclose(f);
  2532         -}
  2533         -
  2534         -/*
  2535         -** Try to open an output file.   The names "stdout" and "stderr" are
  2536         -** recognized and do the right thing.  NULL is returned if the output
  2537         -** filename is "off".
  2538         -*/
  2539         -static FILE *output_file_open(const char *zFile){
  2540         -  FILE *f;
  2541         -  if( strcmp(zFile,"stdout")==0 ){
  2542         -    f = stdout;
  2543         -  }else if( strcmp(zFile, "stderr")==0 ){
  2544         -    f = stderr;
  2545         -  }else if( strcmp(zFile, "off")==0 ){
  2546         -    f = 0;
  2547         -  }else{
  2548         -    f = fopen(zFile, "wb");
  2549         -    if( f==0 ){
  2550         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  2551         -    }
  2552         -  }
  2553         -  return f;
  2554         -}
  2555         -
  2556         -/*
  2557         -** A routine for handling output from sqlite3_trace().
  2558         -*/
  2559         -static int sql_trace_callback(
  2560         -  unsigned mType,
  2561         -  void *pArg,
  2562         -  void *pP,
  2563         -  void *pX
  2564         -){
  2565         -  FILE *f = (FILE*)pArg;
  2566         -  UNUSED_PARAMETER(mType);
  2567         -  UNUSED_PARAMETER(pP);
  2568         -  if( f ){
  2569         -    const char *z = (const char*)pX;
  2570         -    int i = (int)strlen(z);
  2571         -    while( i>0 && z[i-1]==';' ){ i--; }
  2572         -    utf8_printf(f, "%.*s;\n", i, z);
  2573         -  }
  2574         -  return 0;
  2575         -}
  2576         -
  2577         -/*
  2578         -** A no-op routine that runs with the ".breakpoint" doc-command.  This is
  2579         -** a useful spot to set a debugger breakpoint.
  2580         -*/
  2581         -static void test_breakpoint(void){
  2582         -  static int nCall = 0;
  2583         -  nCall++;
  2584         -}
  2585         -
  2586         -/*
  2587         -** An object used to read a CSV and other files for import.
  2588         -*/
  2589         -typedef struct ImportCtx ImportCtx;
  2590         -struct ImportCtx {
  2591         -  const char *zFile;  /* Name of the input file */
  2592         -  FILE *in;           /* Read the CSV text from this input stream */
  2593         -  char *z;            /* Accumulated text for a field */
  2594         -  int n;              /* Number of bytes in z */
  2595         -  int nAlloc;         /* Space allocated for z[] */
  2596         -  int nLine;          /* Current line number */
  2597         -  int cTerm;          /* Character that terminated the most recent field */
  2598         -  int cColSep;        /* The column separator character.  (Usually ",") */
  2599         -  int cRowSep;        /* The row separator character.  (Usually "\n") */
  2600         -};
  2601         -
  2602         -/* Append a single byte to z[] */
  2603         -static void import_append_char(ImportCtx *p, int c){
  2604         -  if( p->n+1>=p->nAlloc ){
  2605         -    p->nAlloc += p->nAlloc + 100;
  2606         -    p->z = sqlite3_realloc(p->z, p->nAlloc);
  2607         -    if( p->z==0 ){
  2608         -      raw_printf(stderr, "out of memory\n");
  2609         -      exit(1);
  2610         -    }
  2611         -  }
  2612         -  p->z[p->n++] = (char)c;
  2613         -}
  2614         -
  2615         -/* Read a single field of CSV text.  Compatible with rfc4180 and extended
  2616         -** with the option of having a separator other than ",".
  2617         -**
  2618         -**   +  Input comes from p->in.
  2619         -**   +  Store results in p->z of length p->n.  Space to hold p->z comes
  2620         -**      from sqlite3_malloc64().
  2621         -**   +  Use p->cSep as the column separator.  The default is ",".
  2622         -**   +  Use p->rSep as the row separator.  The default is "\n".
  2623         -**   +  Keep track of the line number in p->nLine.
  2624         -**   +  Store the character that terminates the field in p->cTerm.  Store
  2625         -**      EOF on end-of-file.
  2626         -**   +  Report syntax errors on stderr
  2627         -*/
  2628         -static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){
  2629         -  int c;
  2630         -  int cSep = p->cColSep;
  2631         -  int rSep = p->cRowSep;
  2632         -  p->n = 0;
  2633         -  c = fgetc(p->in);
  2634         -  if( c==EOF || seenInterrupt ){
  2635         -    p->cTerm = EOF;
  2636         -    return 0;
  2637         -  }
  2638         -  if( c=='"' ){
  2639         -    int pc, ppc;
  2640         -    int startLine = p->nLine;
  2641         -    int cQuote = c;
  2642         -    pc = ppc = 0;
  2643         -    while( 1 ){
  2644         -      c = fgetc(p->in);
  2645         -      if( c==rSep ) p->nLine++;
  2646         -      if( c==cQuote ){
  2647         -        if( pc==cQuote ){
  2648         -          pc = 0;
  2649         -          continue;
  2650         -        }
  2651         -      }
  2652         -      if( (c==cSep && pc==cQuote)
  2653         -       || (c==rSep && pc==cQuote)
  2654         -       || (c==rSep && pc=='\r' && ppc==cQuote)
  2655         -       || (c==EOF && pc==cQuote)
  2656         -      ){
  2657         -        do{ p->n--; }while( p->z[p->n]!=cQuote );
  2658         -        p->cTerm = c;
  2659         -        break;
  2660         -      }
  2661         -      if( pc==cQuote && c!='\r' ){
  2662         -        utf8_printf(stderr, "%s:%d: unescaped %c character\n",
  2663         -                p->zFile, p->nLine, cQuote);
  2664         -      }
  2665         -      if( c==EOF ){
  2666         -        utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n",
  2667         -                p->zFile, startLine, cQuote);
  2668         -        p->cTerm = c;
  2669         -        break;
  2670         -      }
  2671         -      import_append_char(p, c);
  2672         -      ppc = pc;
  2673         -      pc = c;
  2674         -    }
  2675         -  }else{
  2676         -    while( c!=EOF && c!=cSep && c!=rSep ){
  2677         -      import_append_char(p, c);
  2678         -      c = fgetc(p->in);
  2679         -    }
  2680         -    if( c==rSep ){
  2681         -      p->nLine++;
  2682         -      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  2683         -    }
  2684         -    p->cTerm = c;
  2685         -  }
  2686         -  if( p->z ) p->z[p->n] = 0;
  2687         -  return p->z;
  2688         -}
  2689         -
  2690         -/* Read a single field of ASCII delimited text.
  2691         -**
  2692         -**   +  Input comes from p->in.
  2693         -**   +  Store results in p->z of length p->n.  Space to hold p->z comes
  2694         -**      from sqlite3_malloc64().
  2695         -**   +  Use p->cSep as the column separator.  The default is "\x1F".
  2696         -**   +  Use p->rSep as the row separator.  The default is "\x1E".
  2697         -**   +  Keep track of the row number in p->nLine.
  2698         -**   +  Store the character that terminates the field in p->cTerm.  Store
  2699         -**      EOF on end-of-file.
  2700         -**   +  Report syntax errors on stderr
  2701         -*/
  2702         -static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){
  2703         -  int c;
  2704         -  int cSep = p->cColSep;
  2705         -  int rSep = p->cRowSep;
  2706         -  p->n = 0;
  2707         -  c = fgetc(p->in);
  2708         -  if( c==EOF || seenInterrupt ){
  2709         -    p->cTerm = EOF;
  2710         -    return 0;
  2711         -  }
  2712         -  while( c!=EOF && c!=cSep && c!=rSep ){
  2713         -    import_append_char(p, c);
  2714         -    c = fgetc(p->in);
  2715         -  }
  2716         -  if( c==rSep ){
  2717         -    p->nLine++;
  2718         -  }
  2719         -  p->cTerm = c;
  2720         -  if( p->z ) p->z[p->n] = 0;
  2721         -  return p->z;
  2722         -}
  2723         -
  2724         -/*
  2725         -** Try to transfer data for table zTable.  If an error is seen while
  2726         -** moving forward, try to go backwards.  The backwards movement won't
  2727         -** work for WITHOUT ROWID tables.
  2728         -*/
  2729         -static void tryToCloneData(
  2730         -  ShellState *p,
  2731         -  sqlite3 *newDb,
  2732         -  const char *zTable
  2733         -){
  2734         -  sqlite3_stmt *pQuery = 0;
  2735         -  sqlite3_stmt *pInsert = 0;
  2736         -  char *zQuery = 0;
  2737         -  char *zInsert = 0;
  2738         -  int rc;
  2739         -  int i, j, n;
  2740         -  int nTable = (int)strlen(zTable);
  2741         -  int k = 0;
  2742         -  int cnt = 0;
  2743         -  const int spinRate = 10000;
  2744         -
  2745         -  zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
  2746         -  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2747         -  if( rc ){
  2748         -    utf8_printf(stderr, "Error %d: %s on [%s]\n",
  2749         -            sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2750         -            zQuery);
  2751         -    goto end_data_xfer;
  2752         -  }
  2753         -  n = sqlite3_column_count(pQuery);
  2754         -  zInsert = sqlite3_malloc(200 + nTable + n*3);
  2755         -  if( zInsert==0 ){
  2756         -    raw_printf(stderr, "out of memory\n");
  2757         -    goto end_data_xfer;
  2758         -  }
  2759         -  sqlite3_snprintf(200+nTable,zInsert,
  2760         -                   "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable);
  2761         -  i = (int)strlen(zInsert);
  2762         -  for(j=1; j<n; j++){
  2763         -    memcpy(zInsert+i, ",?", 2);
  2764         -    i += 2;
  2765         -  }
  2766         -  memcpy(zInsert+i, ");", 3);
  2767         -  rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0);
  2768         -  if( rc ){
  2769         -    utf8_printf(stderr, "Error %d: %s on [%s]\n",
  2770         -            sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb),
  2771         -            zQuery);
  2772         -    goto end_data_xfer;
  2773         -  }
  2774         -  for(k=0; k<2; k++){
  2775         -    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2776         -      for(i=0; i<n; i++){
  2777         -        switch( sqlite3_column_type(pQuery, i) ){
  2778         -          case SQLITE_NULL: {
  2779         -            sqlite3_bind_null(pInsert, i+1);
  2780         -            break;
  2781         -          }
  2782         -          case SQLITE_INTEGER: {
  2783         -            sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i));
  2784         -            break;
  2785         -          }
  2786         -          case SQLITE_FLOAT: {
  2787         -            sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i));
  2788         -            break;
  2789         -          }
  2790         -          case SQLITE_TEXT: {
  2791         -            sqlite3_bind_text(pInsert, i+1,
  2792         -                             (const char*)sqlite3_column_text(pQuery,i),
  2793         -                             -1, SQLITE_STATIC);
  2794         -            break;
  2795         -          }
  2796         -          case SQLITE_BLOB: {
  2797         -            sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i),
  2798         -                                            sqlite3_column_bytes(pQuery,i),
  2799         -                                            SQLITE_STATIC);
  2800         -            break;
  2801         -          }
  2802         -        }
  2803         -      } /* End for */
  2804         -      rc = sqlite3_step(pInsert);
  2805         -      if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  2806         -        utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb),
  2807         -                        sqlite3_errmsg(newDb));
  2808         -      }
  2809         -      sqlite3_reset(pInsert);
  2810         -      cnt++;
  2811         -      if( (cnt%spinRate)==0 ){
  2812         -        printf("%c\b", "|/-\\"[(cnt/spinRate)%4]);
  2813         -        fflush(stdout);
  2814         -      }
  2815         -    } /* End while */
  2816         -    if( rc==SQLITE_DONE ) break;
  2817         -    sqlite3_finalize(pQuery);
  2818         -    sqlite3_free(zQuery);
  2819         -    zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;",
  2820         -                             zTable);
  2821         -    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2822         -    if( rc ){
  2823         -      utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable);
  2824         -      break;
  2825         -    }
  2826         -  } /* End for(k=0...) */
  2827         -
  2828         -end_data_xfer:
  2829         -  sqlite3_finalize(pQuery);
  2830         -  sqlite3_finalize(pInsert);
  2831         -  sqlite3_free(zQuery);
  2832         -  sqlite3_free(zInsert);
  2833         -}
  2834         -
  2835         -
  2836         -/*
  2837         -** Try to transfer all rows of the schema that match zWhere.  For
  2838         -** each row, invoke xForEach() on the object defined by that row.
  2839         -** If an error is encountered while moving forward through the
  2840         -** sqlite_master table, try again moving backwards.
  2841         -*/
  2842         -static void tryToCloneSchema(
  2843         -  ShellState *p,
  2844         -  sqlite3 *newDb,
  2845         -  const char *zWhere,
  2846         -  void (*xForEach)(ShellState*,sqlite3*,const char*)
  2847         -){
  2848         -  sqlite3_stmt *pQuery = 0;
  2849         -  char *zQuery = 0;
  2850         -  int rc;
  2851         -  const unsigned char *zName;
  2852         -  const unsigned char *zSql;
  2853         -  char *zErrMsg = 0;
  2854         -
  2855         -  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2856         -                           " WHERE %s", zWhere);
  2857         -  rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2858         -  if( rc ){
  2859         -    utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  2860         -                    sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2861         -                    zQuery);
  2862         -    goto end_schema_xfer;
  2863         -  }
  2864         -  while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2865         -    zName = sqlite3_column_text(pQuery, 0);
  2866         -    zSql = sqlite3_column_text(pQuery, 1);
  2867         -    printf("%s... ", zName); fflush(stdout);
  2868         -    sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2869         -    if( zErrMsg ){
  2870         -      utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2871         -      sqlite3_free(zErrMsg);
  2872         -      zErrMsg = 0;
  2873         -    }
  2874         -    if( xForEach ){
  2875         -      xForEach(p, newDb, (const char*)zName);
  2876         -    }
  2877         -    printf("done\n");
  2878         -  }
  2879         -  if( rc!=SQLITE_DONE ){
  2880         -    sqlite3_finalize(pQuery);
  2881         -    sqlite3_free(zQuery);
  2882         -    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
  2883         -                             " WHERE %s ORDER BY rowid DESC", zWhere);
  2884         -    rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
  2885         -    if( rc ){
  2886         -      utf8_printf(stderr, "Error: (%d) %s on [%s]\n",
  2887         -                      sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db),
  2888         -                      zQuery);
  2889         -      goto end_schema_xfer;
  2890         -    }
  2891         -    while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){
  2892         -      zName = sqlite3_column_text(pQuery, 0);
  2893         -      zSql = sqlite3_column_text(pQuery, 1);
  2894         -      printf("%s... ", zName); fflush(stdout);
  2895         -      sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg);
  2896         -      if( zErrMsg ){
  2897         -        utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql);
  2898         -        sqlite3_free(zErrMsg);
  2899         -        zErrMsg = 0;
  2900         -      }
  2901         -      if( xForEach ){
  2902         -        xForEach(p, newDb, (const char*)zName);
  2903         -      }
  2904         -      printf("done\n");
  2905         -    }
  2906         -  }
  2907         -end_schema_xfer:
  2908         -  sqlite3_finalize(pQuery);
  2909         -  sqlite3_free(zQuery);
  2910         -}
  2911         -
  2912         -/*
  2913         -** Open a new database file named "zNewDb".  Try to recover as much information
  2914         -** as possible out of the main database (which might be corrupt) and write it
  2915         -** into zNewDb.
  2916         -*/
  2917         -static void tryToClone(ShellState *p, const char *zNewDb){
  2918         -  int rc;
  2919         -  sqlite3 *newDb = 0;
  2920         -  if( access(zNewDb,0)==0 ){
  2921         -    utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb);
  2922         -    return;
  2923         -  }
  2924         -  rc = sqlite3_open(zNewDb, &newDb);
  2925         -  if( rc ){
  2926         -    utf8_printf(stderr, "Cannot create output database: %s\n",
  2927         -            sqlite3_errmsg(newDb));
  2928         -  }else{
  2929         -    sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0);
  2930         -    sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0);
  2931         -    tryToCloneSchema(p, newDb, "type='table'", tryToCloneData);
  2932         -    tryToCloneSchema(p, newDb, "type!='table'", 0);
  2933         -    sqlite3_exec(newDb, "COMMIT;", 0, 0, 0);
  2934         -    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  2935         -  }
  2936         -  sqlite3_close(newDb);
  2937         -}
  2938         -
  2939         -/*
  2940         -** Change the output file back to stdout
  2941         -*/
  2942         -static void output_reset(ShellState *p){
  2943         -  if( p->outfile[0]=='|' ){
  2944         -#ifndef SQLITE_OMIT_POPEN
  2945         -    pclose(p->out);
  2946         -#endif
  2947         -  }else{
  2948         -    output_file_close(p->out);
  2949         -  }
  2950         -  p->outfile[0] = 0;
  2951         -  p->out = stdout;
  2952         -}
  2953         -
  2954         -/*
  2955         -** Run an SQL command and return the single integer result.
  2956         -*/
  2957         -static int db_int(ShellState *p, const char *zSql){
  2958         -  sqlite3_stmt *pStmt;
  2959         -  int res = 0;
  2960         -  sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2961         -  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  2962         -    res = sqlite3_column_int(pStmt,0);
  2963         -  }
  2964         -  sqlite3_finalize(pStmt);
  2965         -  return res;
  2966         -}
  2967         -
  2968         -/*
  2969         -** Convert a 2-byte or 4-byte big-endian integer into a native integer
  2970         -*/
  2971         -static unsigned int get2byteInt(unsigned char *a){
  2972         -  return (a[0]<<8) + a[1];
  2973         -}
  2974         -static unsigned int get4byteInt(unsigned char *a){
  2975         -  return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
  2976         -}
  2977         -
  2978         -/*
  2979         -** Implementation of the ".info" command.
  2980         -**
  2981         -** Return 1 on error, 2 to exit, and 0 otherwise.
  2982         -*/
  2983         -static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
  2984         -  static const struct { const char *zName; int ofst; } aField[] = {
  2985         -     { "file change counter:",  24  },
  2986         -     { "database page count:",  28  },
  2987         -     { "freelist page count:",  36  },
  2988         -     { "schema cookie:",        40  },
  2989         -     { "schema format:",        44  },
  2990         -     { "default cache size:",   48  },
  2991         -     { "autovacuum top root:",  52  },
  2992         -     { "incremental vacuum:",   64  },
  2993         -     { "text encoding:",        56  },
  2994         -     { "user version:",         60  },
  2995         -     { "application id:",       68  },
  2996         -     { "software version:",     96  },
  2997         -  };
  2998         -  static const struct { const char *zName; const char *zSql; } aQuery[] = {
  2999         -     { "number of tables:",
  3000         -       "SELECT count(*) FROM %s WHERE type='table'" },
  3001         -     { "number of indexes:",
  3002         -       "SELECT count(*) FROM %s WHERE type='index'" },
  3003         -     { "number of triggers:",
  3004         -       "SELECT count(*) FROM %s WHERE type='trigger'" },
  3005         -     { "number of views:",
  3006         -       "SELECT count(*) FROM %s WHERE type='view'" },
  3007         -     { "schema size:",
  3008         -       "SELECT total(length(sql)) FROM %s" },
  3009         -  };
  3010         -  sqlite3_file *pFile = 0;
  3011         -  int i;
  3012         -  char *zSchemaTab;
  3013         -  char *zDb = nArg>=2 ? azArg[1] : "main";
  3014         -  unsigned char aHdr[100];
  3015         -  open_db(p, 0);
  3016         -  if( p->db==0 ) return 1;
  3017         -  sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile);
  3018         -  if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){
  3019         -    return 1;
  3020         -  }
  3021         -  i = pFile->pMethods->xRead(pFile, aHdr, 100, 0);
  3022         -  if( i!=SQLITE_OK ){
  3023         -    raw_printf(stderr, "unable to read database header\n");
  3024         -    return 1;
  3025         -  }
  3026         -  i = get2byteInt(aHdr+16);
  3027         -  if( i==1 ) i = 65536;
  3028         -  utf8_printf(p->out, "%-20s %d\n", "database page size:", i);
  3029         -  utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]);
  3030         -  utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]);
  3031         -  utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]);
  3032         -  for(i=0; i<ArraySize(aField); i++){
  3033         -    int ofst = aField[i].ofst;
  3034         -    unsigned int val = get4byteInt(aHdr + ofst);
  3035         -    utf8_printf(p->out, "%-20s %u", aField[i].zName, val);
  3036         -    switch( ofst ){
  3037         -      case 56: {
  3038         -        if( val==1 ) raw_printf(p->out, " (utf8)");
  3039         -        if( val==2 ) raw_printf(p->out, " (utf16le)");
  3040         -        if( val==3 ) raw_printf(p->out, " (utf16be)");
  3041         -      }
  3042         -    }
  3043         -    raw_printf(p->out, "\n");
  3044         -  }
  3045         -  if( zDb==0 ){
  3046         -    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
  3047         -  }else if( strcmp(zDb,"temp")==0 ){
  3048         -    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
  3049         -  }else{
  3050         -    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
  3051         -  }
  3052         -  for(i=0; i<ArraySize(aQuery); i++){
  3053         -    char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
  3054         -    int val = db_int(p, zSql);
  3055         -    sqlite3_free(zSql);
  3056         -    utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val);
  3057         -  }
  3058         -  sqlite3_free(zSchemaTab);
  3059         -  return 0;
  3060         -}
  3061         -
  3062         -/*
  3063         -** Print the current sqlite3_errmsg() value to stderr and return 1.
  3064         -*/
  3065         -static int shellDatabaseError(sqlite3 *db){
  3066         -  const char *zErr = sqlite3_errmsg(db);
  3067         -  utf8_printf(stderr, "Error: %s\n", zErr);
  3068         -  return 1;
  3069         -}
  3070         -
  3071         -/*
  3072         -** Print an out-of-memory message to stderr and return 1.
  3073         -*/
  3074         -static int shellNomemError(void){
  3075         -  raw_printf(stderr, "Error: out of memory\n");
  3076         -  return 1;
  3077         -}
  3078         -
  3079         -/*
  3080         -** Compare the pattern in zGlob[] against the text in z[].  Return TRUE
  3081         -** if they match and FALSE (0) if they do not match.
  3082         -**
  3083         -** Globbing rules:
  3084         -**
  3085         -**      '*'       Matches any sequence of zero or more characters.
  3086         -**
  3087         -**      '?'       Matches exactly one character.
  3088         -**
  3089         -**     [...]      Matches one character from the enclosed list of
  3090         -**                characters.
  3091         -**
  3092         -**     [^...]     Matches one character not in the enclosed list.
  3093         -**
  3094         -**      '#'       Matches any sequence of one or more digits with an
  3095         -**                optional + or - sign in front
  3096         -**
  3097         -**      ' '       Any span of whitespace matches any other span of
  3098         -**                whitespace.
  3099         -**
  3100         -** Extra whitespace at the end of z[] is ignored.
  3101         -*/
  3102         -static int testcase_glob(const char *zGlob, const char *z){
  3103         -  int c, c2;
  3104         -  int invert;
  3105         -  int seen;
  3106         -
  3107         -  while( (c = (*(zGlob++)))!=0 ){
  3108         -    if( IsSpace(c) ){
  3109         -      if( !IsSpace(*z) ) return 0;
  3110         -      while( IsSpace(*zGlob) ) zGlob++;
  3111         -      while( IsSpace(*z) ) z++;
  3112         -    }else if( c=='*' ){
  3113         -      while( (c=(*(zGlob++))) == '*' || c=='?' ){
  3114         -        if( c=='?' && (*(z++))==0 ) return 0;
  3115         -      }
  3116         -      if( c==0 ){
  3117         -        return 1;
  3118         -      }else if( c=='[' ){
  3119         -        while( *z && testcase_glob(zGlob-1,z)==0 ){
  3120         -          z++;
  3121         -        }
  3122         -        return (*z)!=0;
  3123         -      }
  3124         -      while( (c2 = (*(z++)))!=0 ){
  3125         -        while( c2!=c ){
  3126         -          c2 = *(z++);
  3127         -          if( c2==0 ) return 0;
  3128         -        }
  3129         -        if( testcase_glob(zGlob,z) ) return 1;
  3130         -      }
  3131         -      return 0;
  3132         -    }else if( c=='?' ){
  3133         -      if( (*(z++))==0 ) return 0;
  3134         -    }else if( c=='[' ){
  3135         -      int prior_c = 0;
  3136         -      seen = 0;
  3137         -      invert = 0;
  3138         -      c = *(z++);
  3139         -      if( c==0 ) return 0;
  3140         -      c2 = *(zGlob++);
  3141         -      if( c2=='^' ){
  3142         -        invert = 1;
  3143         -        c2 = *(zGlob++);
  3144         -      }
  3145         -      if( c2==']' ){
  3146         -        if( c==']' ) seen = 1;
  3147         -        c2 = *(zGlob++);
  3148         -      }
  3149         -      while( c2 && c2!=']' ){
  3150         -        if( c2=='-' && zGlob[0]!=']' && zGlob[0]!=0 && prior_c>0 ){
  3151         -          c2 = *(zGlob++);
  3152         -          if( c>=prior_c && c<=c2 ) seen = 1;
  3153         -          prior_c = 0;
  3154         -        }else{
  3155         -          if( c==c2 ){
  3156         -            seen = 1;
  3157         -          }
  3158         -          prior_c = c2;
  3159         -        }
  3160         -        c2 = *(zGlob++);
  3161         -      }
  3162         -      if( c2==0 || (seen ^ invert)==0 ) return 0;
  3163         -    }else if( c=='#' ){
  3164         -      if( (z[0]=='-' || z[0]=='+') && IsDigit(z[1]) ) z++;
  3165         -      if( !IsDigit(z[0]) ) return 0;
  3166         -      z++;
  3167         -      while( IsDigit(z[0]) ){ z++; }
  3168         -    }else{
  3169         -      if( c!=(*(z++)) ) return 0;
  3170         -    }
  3171         -  }
  3172         -  while( IsSpace(*z) ){ z++; }
  3173         -  return *z==0;
  3174         -}
  3175         -
  3176         -
  3177         -/*
  3178         -** Compare the string as a command-line option with either one or two
  3179         -** initial "-" characters.
  3180         -*/
  3181         -static int optionMatch(const char *zStr, const char *zOpt){
  3182         -  if( zStr[0]!='-' ) return 0;
  3183         -  zStr++;
  3184         -  if( zStr[0]=='-' ) zStr++;
  3185         -  return strcmp(zStr, zOpt)==0;
  3186         -}
  3187         -
  3188         -/*
  3189         -** Delete a file.
  3190         -*/
  3191         -int shellDeleteFile(const char *zFilename){
  3192         -  int rc;
  3193         -#ifdef _WIN32
  3194         -  wchar_t *z = sqlite3_win32_utf8_to_unicode(zFilename);
  3195         -  rc = _wunlink(z);
  3196         -  sqlite3_free(z);
  3197         -#else
  3198         -  rc = unlink(zFilename);
  3199         -#endif
  3200         -  return rc;
  3201         -}
  3202         -
  3203         -/*
  3204         -** If an input line begins with "." then invoke this routine to
  3205         -** process that line.
  3206         -**
  3207         -** Return 1 on error, 2 to exit, and 0 otherwise.
  3208         -*/
  3209         -static int do_meta_command(char *zLine, ShellState *p){
  3210         -  int h = 1;
  3211         -  int nArg = 0;
  3212         -  int n, c;
  3213         -  int rc = 0;
  3214         -  char *azArg[50];
  3215         -
  3216         -  /* Parse the input line into tokens.
  3217         -  */
  3218         -  while( zLine[h] && nArg<ArraySize(azArg) ){
  3219         -    while( IsSpace(zLine[h]) ){ h++; }
  3220         -    if( zLine[h]==0 ) break;
  3221         -    if( zLine[h]=='\'' || zLine[h]=='"' ){
  3222         -      int delim = zLine[h++];
  3223         -      azArg[nArg++] = &zLine[h];
  3224         -      while( zLine[h] && zLine[h]!=delim ){
  3225         -        if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++;
  3226         -        h++;
  3227         -      }
  3228         -      if( zLine[h]==delim ){
  3229         -        zLine[h++] = 0;
  3230         -      }
  3231         -      if( delim=='"' ) resolve_backslashes(azArg[nArg-1]);
  3232         -    }else{
  3233         -      azArg[nArg++] = &zLine[h];
  3234         -      while( zLine[h] && !IsSpace(zLine[h]) ){ h++; }
  3235         -      if( zLine[h] ) zLine[h++] = 0;
  3236         -      resolve_backslashes(azArg[nArg-1]);
  3237         -    }
  3238         -  }
  3239         -
  3240         -  /* Process the input line.
  3241         -  */
  3242         -  if( nArg==0 ) return 0; /* no tokens, no error */
  3243         -  n = strlen30(azArg[0]);
  3244         -  c = azArg[0][0];
  3245         -
  3246         -#ifndef SQLITE_OMIT_AUTHORIZATION
  3247         -  if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){
  3248         -    if( nArg!=2 ){
  3249         -      raw_printf(stderr, "Usage: .auth ON|OFF\n");
  3250         -      rc = 1;
  3251         -      goto meta_command_exit;
  3252         -    }
  3253         -    open_db(p, 0);
  3254         -    if( booleanValue(azArg[1]) ){
  3255         -      sqlite3_set_authorizer(p->db, shellAuth, p);
  3256         -    }else{
  3257         -      sqlite3_set_authorizer(p->db, 0, 0);
  3258         -    }
  3259         -  }else
  3260         -#endif
  3261         -
  3262         -  if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0)
  3263         -   || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0)
  3264         -  ){
  3265         -    const char *zDestFile = 0;
  3266         -    const char *zDb = 0;
  3267         -    sqlite3 *pDest;
  3268         -    sqlite3_backup *pBackup;
  3269         -    int j;
  3270         -    for(j=1; j<nArg; j++){
  3271         -      const char *z = azArg[j];
  3272         -      if( z[0]=='-' ){
  3273         -        while( z[0]=='-' ) z++;
  3274         -        /* No options to process at this time */
  3275         -        {
  3276         -          utf8_printf(stderr, "unknown option: %s\n", azArg[j]);
  3277         -          return 1;
  3278         -        }
  3279         -      }else if( zDestFile==0 ){
  3280         -        zDestFile = azArg[j];
  3281         -      }else if( zDb==0 ){
  3282         -        zDb = zDestFile;
  3283         -        zDestFile = azArg[j];
  3284         -      }else{
  3285         -        raw_printf(stderr, "too many arguments to .backup\n");
  3286         -        return 1;
  3287         -      }
  3288         -    }
  3289         -    if( zDestFile==0 ){
  3290         -      raw_printf(stderr, "missing FILENAME argument on .backup\n");
  3291         -      return 1;
  3292         -    }
  3293         -    if( zDb==0 ) zDb = "main";
  3294         -    rc = sqlite3_open(zDestFile, &pDest);
  3295         -    if( rc!=SQLITE_OK ){
  3296         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile);
  3297         -      sqlite3_close(pDest);
  3298         -      return 1;
  3299         -    }
  3300         -    open_db(p, 0);
  3301         -    pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb);
  3302         -    if( pBackup==0 ){
  3303         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  3304         -      sqlite3_close(pDest);
  3305         -      return 1;
  3306         -    }
  3307         -    while(  (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){}
  3308         -    sqlite3_backup_finish(pBackup);
  3309         -    if( rc==SQLITE_DONE ){
  3310         -      rc = 0;
  3311         -    }else{
  3312         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest));
  3313         -      rc = 1;
  3314         -    }
  3315         -    sqlite3_close(pDest);
  3316         -  }else
  3317         -
  3318         -  if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){
  3319         -    if( nArg==2 ){
  3320         -      bail_on_error = booleanValue(azArg[1]);
  3321         -    }else{
  3322         -      raw_printf(stderr, "Usage: .bail on|off\n");
  3323         -      rc = 1;
  3324         -    }
  3325         -  }else
  3326         -
  3327         -  if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){
  3328         -    if( nArg==2 ){
  3329         -      if( booleanValue(azArg[1]) ){
  3330         -        setBinaryMode(p->out, 1);
  3331         -      }else{
  3332         -        setTextMode(p->out, 1);
  3333         -      }
  3334         -    }else{
  3335         -      raw_printf(stderr, "Usage: .binary on|off\n");
  3336         -      rc = 1;
  3337         -    }
  3338         -  }else
  3339         -
  3340         -  /* The undocumented ".breakpoint" command causes a call to the no-op
  3341         -  ** routine named test_breakpoint().
  3342         -  */
  3343         -  if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){
  3344         -    test_breakpoint();
  3345         -  }else
  3346         -
  3347         -  if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){
  3348         -    if( nArg==2 ){
  3349         -      p->countChanges = booleanValue(azArg[1]);
  3350         -    }else{
  3351         -      raw_printf(stderr, "Usage: .changes on|off\n");
  3352         -      rc = 1;
  3353         -    }
  3354         -  }else
  3355         -
  3356         -  /* Cancel output redirection, if it is currently set (by .testcase)
  3357         -  ** Then read the content of the testcase-out.txt file and compare against
  3358         -  ** azArg[1].  If there are differences, report an error and exit.
  3359         -  */
  3360         -  if( c=='c' && n>=3 && strncmp(azArg[0], "check", n)==0 ){
  3361         -    char *zRes = 0;
  3362         -    output_reset(p);
  3363         -    if( nArg!=2 ){
  3364         -      raw_printf(stderr, "Usage: .check GLOB-PATTERN\n");
  3365         -      rc = 2;
  3366         -    }else if( (zRes = readFile("testcase-out.txt"))==0 ){
  3367         -      raw_printf(stderr, "Error: cannot read 'testcase-out.txt'\n");
  3368         -      rc = 2;
  3369         -    }else if( testcase_glob(azArg[1],zRes)==0 ){
  3370         -      utf8_printf(stderr,
  3371         -                 "testcase-%s FAILED\n Expected: [%s]\n      Got: [%s]\n",
  3372         -                 p->zTestcase, azArg[1], zRes);
  3373         -      rc = 2;
  3374         -    }else{
  3375         -      utf8_printf(stdout, "testcase-%s ok\n", p->zTestcase);
  3376         -      p->nCheck++;
  3377         -    }
  3378         -    sqlite3_free(zRes);
  3379         -  }else
  3380         -
  3381         -  if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){
  3382         -    if( nArg==2 ){
  3383         -      tryToClone(p, azArg[1]);
  3384         -    }else{
  3385         -      raw_printf(stderr, "Usage: .clone FILENAME\n");
  3386         -      rc = 1;
  3387         -    }
  3388         -  }else
  3389         -
  3390         -  if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
  3391         -    ShellState data;
  3392         -    char *zErrMsg = 0;
  3393         -    open_db(p, 0);
  3394         -    memcpy(&data, p, sizeof(data));
  3395         -    data.showHeader = 1;
  3396         -    data.cMode = data.mode = MODE_Column;
  3397         -    data.colWidth[0] = 3;
  3398         -    data.colWidth[1] = 15;
  3399         -    data.colWidth[2] = 58;
  3400         -    data.cnt = 0;
  3401         -    sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg);
  3402         -    if( zErrMsg ){
  3403         -      utf8_printf(stderr,"Error: %s\n", zErrMsg);
  3404         -      sqlite3_free(zErrMsg);
  3405         -      rc = 1;
  3406         -    }
  3407         -  }else
  3408         -
  3409         -  if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){
  3410         -    rc = shell_dbinfo_command(p, nArg, azArg);
  3411         -  }else
  3412         -
  3413         -  if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
  3414         -    open_db(p, 0);
  3415         -    /* When playing back a "dump", the content might appear in an order
  3416         -    ** which causes immediate foreign key constraints to be violated.
  3417         -    ** So disable foreign-key constraint enforcement to prevent problems. */
  3418         -    if( nArg!=1 && nArg!=2 ){
  3419         -      raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n");
  3420         -      rc = 1;
  3421         -      goto meta_command_exit;
  3422         -    }
  3423         -    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
  3424         -    raw_printf(p->out, "BEGIN TRANSACTION;\n");
  3425         -    p->writableSchema = 0;
  3426         -    sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
  3427         -    p->nErr = 0;
  3428         -    if( nArg==1 ){
  3429         -      run_schema_dump_query(p,
  3430         -        "SELECT name, type, sql FROM sqlite_master "
  3431         -        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
  3432         -      );
  3433         -      run_schema_dump_query(p,
  3434         -        "SELECT name, type, sql FROM sqlite_master "
  3435         -        "WHERE name=='sqlite_sequence'"
  3436         -      );
  3437         -      run_table_dump_query(p,
  3438         -        "SELECT sql FROM sqlite_master "
  3439         -        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
  3440         -      );
  3441         -    }else{
  3442         -      int i;
  3443         -      for(i=1; i<nArg; i++){
  3444         -        zShellStatic = azArg[i];
  3445         -        run_schema_dump_query(p,
  3446         -          "SELECT name, type, sql FROM sqlite_master "
  3447         -          "WHERE tbl_name LIKE shellstatic() AND type=='table'"
  3448         -          "  AND sql NOT NULL");
  3449         -        run_table_dump_query(p,
  3450         -          "SELECT sql FROM sqlite_master "
  3451         -          "WHERE sql NOT NULL"
  3452         -          "  AND type IN ('index','trigger','view')"
  3453         -          "  AND tbl_name LIKE shellstatic()", 0
  3454         -        );
  3455         -        zShellStatic = 0;
  3456         -      }
  3457         -    }
  3458         -    if( p->writableSchema ){
  3459         -      raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
  3460         -      p->writableSchema = 0;
  3461         -    }
  3462         -    sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
  3463         -    sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  3464         -    raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  3465         -  }else
  3466         -
  3467         -  if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){
  3468         -    if( nArg==2 ){
  3469         -      p->echoOn = booleanValue(azArg[1]);
  3470         -    }else{
  3471         -      raw_printf(stderr, "Usage: .echo on|off\n");
  3472         -      rc = 1;
  3473         -    }
  3474         -  }else
  3475         -
  3476         -  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){
  3477         -    if( nArg==2 ){
  3478         -      if( strcmp(azArg[1],"full")==0 ){
  3479         -        p->autoEQP = 2;
  3480         -      }else{
  3481         -        p->autoEQP = booleanValue(azArg[1]);
  3482         -      }
  3483         -    }else{
  3484         -      raw_printf(stderr, "Usage: .eqp on|off|full\n");
  3485         -      rc = 1;
  3486         -    }
  3487         -  }else
  3488         -
  3489         -  if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  3490         -    if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  3491         -    rc = 2;
  3492         -  }else
  3493         -
  3494         -  if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
  3495         -    int val = 1;
  3496         -    if( nArg>=2 ){
  3497         -      if( strcmp(azArg[1],"auto")==0 ){
  3498         -        val = 99;
  3499         -      }else{
  3500         -        val =  booleanValue(azArg[1]);
  3501         -      }
  3502         -    }
  3503         -    if( val==1 && p->mode!=MODE_Explain ){
  3504         -      p->normalMode = p->mode;
  3505         -      p->mode = MODE_Explain;
  3506         -      p->autoExplain = 0;
  3507         -    }else if( val==0 ){
  3508         -      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  3509         -      p->autoExplain = 0;
  3510         -    }else if( val==99 ){
  3511         -      if( p->mode==MODE_Explain ) p->mode = p->normalMode;
  3512         -      p->autoExplain = 1;
  3513         -    }
  3514         -  }else
  3515         -
  3516         -  if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){
  3517         -    ShellState data;
  3518         -    char *zErrMsg = 0;
  3519         -    int doStats = 0;
  3520         -    memcpy(&data, p, sizeof(data));
  3521         -    data.showHeader = 0;
  3522         -    data.cMode = data.mode = MODE_Semi;
  3523         -    if( nArg==2 && optionMatch(azArg[1], "indent") ){
  3524         -      data.cMode = data.mode = MODE_Pretty;
  3525         -      nArg = 1;
  3526         -    }
  3527         -    if( nArg!=1 ){
  3528         -      raw_printf(stderr, "Usage: .fullschema ?--indent?\n");
  3529         -      rc = 1;
  3530         -      goto meta_command_exit;
  3531         -    }
  3532         -    open_db(p, 0);
  3533         -    rc = sqlite3_exec(p->db,
  3534         -       "SELECT sql FROM"
  3535         -       "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  3536         -       "     FROM sqlite_master UNION ALL"
  3537         -       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  3538         -       "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  3539         -       "ORDER BY rowid",
  3540         -       callback, &data, &zErrMsg
  3541         -    );
  3542         -    if( rc==SQLITE_OK ){
  3543         -      sqlite3_stmt *pStmt;
  3544         -      rc = sqlite3_prepare_v2(p->db,
  3545         -               "SELECT rowid FROM sqlite_master"
  3546         -               " WHERE name GLOB 'sqlite_stat[134]'",
  3547         -               -1, &pStmt, 0);
  3548         -      doStats = sqlite3_step(pStmt)==SQLITE_ROW;
  3549         -      sqlite3_finalize(pStmt);
  3550         -    }
  3551         -    if( doStats==0 ){
  3552         -      raw_printf(p->out, "/* No STAT tables available */\n");
  3553         -    }else{
  3554         -      raw_printf(p->out, "ANALYZE sqlite_master;\n");
  3555         -      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
  3556         -                   callback, &data, &zErrMsg);
  3557         -      data.cMode = data.mode = MODE_Insert;
  3558         -      data.zDestTable = "sqlite_stat1";
  3559         -      shell_exec(p->db, "SELECT * FROM sqlite_stat1",
  3560         -                 shell_callback, &data,&zErrMsg);
  3561         -      data.zDestTable = "sqlite_stat3";
  3562         -      shell_exec(p->db, "SELECT * FROM sqlite_stat3",
  3563         -                 shell_callback, &data,&zErrMsg);
  3564         -      data.zDestTable = "sqlite_stat4";
  3565         -      shell_exec(p->db, "SELECT * FROM sqlite_stat4",
  3566         -                 shell_callback, &data, &zErrMsg);
  3567         -      raw_printf(p->out, "ANALYZE sqlite_master;\n");
  3568         -    }
  3569         -  }else
  3570         -
  3571         -  if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
  3572         -    if( nArg==2 ){
  3573         -      p->showHeader = booleanValue(azArg[1]);
  3574         -    }else{
  3575         -      raw_printf(stderr, "Usage: .headers on|off\n");
  3576         -      rc = 1;
  3577         -    }
  3578         -  }else
  3579         -
  3580         -  if( c=='h' && strncmp(azArg[0], "help", n)==0 ){
  3581         -    utf8_printf(p->out, "%s", zHelp);
  3582         -  }else
  3583         -
  3584         -  if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
  3585         -    char *zTable;               /* Insert data into this table */
  3586         -    char *zFile;                /* Name of file to extra content from */
  3587         -    sqlite3_stmt *pStmt = NULL; /* A statement */
  3588         -    int nCol;                   /* Number of columns in the table */
  3589         -    int nByte;                  /* Number of bytes in an SQL string */
  3590         -    int i, j;                   /* Loop counters */
  3591         -    int needCommit;             /* True to COMMIT or ROLLBACK at end */
  3592         -    int nSep;                   /* Number of bytes in p->colSeparator[] */
  3593         -    char *zSql;                 /* An SQL statement */
  3594         -    ImportCtx sCtx;             /* Reader context */
  3595         -    char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
  3596         -    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
  3597         -
  3598         -    if( nArg!=3 ){
  3599         -      raw_printf(stderr, "Usage: .import FILE TABLE\n");
  3600         -      goto meta_command_exit;
  3601         -    }
  3602         -    zFile = azArg[1];
  3603         -    zTable = azArg[2];
  3604         -    seenInterrupt = 0;
  3605         -    memset(&sCtx, 0, sizeof(sCtx));
  3606         -    open_db(p, 0);
  3607         -    nSep = strlen30(p->colSeparator);
  3608         -    if( nSep==0 ){
  3609         -      raw_printf(stderr,
  3610         -                 "Error: non-null column separator required for import\n");
  3611         -      return 1;
  3612         -    }
  3613         -    if( nSep>1 ){
  3614         -      raw_printf(stderr, "Error: multi-character column separators not allowed"
  3615         -                      " for import\n");
  3616         -      return 1;
  3617         -    }
  3618         -    nSep = strlen30(p->rowSeparator);
  3619         -    if( nSep==0 ){
  3620         -      raw_printf(stderr, "Error: non-null row separator required for import\n");
  3621         -      return 1;
  3622         -    }
  3623         -    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
  3624         -      /* When importing CSV (only), if the row separator is set to the
  3625         -      ** default output row separator, change it to the default input
  3626         -      ** row separator.  This avoids having to maintain different input
  3627         -      ** and output row separators. */
  3628         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
  3629         -      nSep = strlen30(p->rowSeparator);
  3630         -    }
  3631         -    if( nSep>1 ){
  3632         -      raw_printf(stderr, "Error: multi-character row separators not allowed"
  3633         -                      " for import\n");
  3634         -      return 1;
  3635         -    }
  3636         -    sCtx.zFile = zFile;
  3637         -    sCtx.nLine = 1;
  3638         -    if( sCtx.zFile[0]=='|' ){
  3639         -#ifdef SQLITE_OMIT_POPEN
  3640         -      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  3641         -      return 1;
  3642         -#else
  3643         -      sCtx.in = popen(sCtx.zFile+1, "r");
  3644         -      sCtx.zFile = "<pipe>";
  3645         -      xCloser = pclose;
  3646         -#endif
  3647         -    }else{
  3648         -      sCtx.in = fopen(sCtx.zFile, "rb");
  3649         -      xCloser = fclose;
  3650         -    }
  3651         -    if( p->mode==MODE_Ascii ){
  3652         -      xRead = ascii_read_one_field;
  3653         -    }else{
  3654         -      xRead = csv_read_one_field;
  3655         -    }
  3656         -    if( sCtx.in==0 ){
  3657         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
  3658         -      return 1;
  3659         -    }
  3660         -    sCtx.cColSep = p->colSeparator[0];
  3661         -    sCtx.cRowSep = p->rowSeparator[0];
  3662         -    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  3663         -    if( zSql==0 ){
  3664         -      raw_printf(stderr, "Error: out of memory\n");
  3665         -      xCloser(sCtx.in);
  3666         -      return 1;
  3667         -    }
  3668         -    nByte = strlen30(zSql);
  3669         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3670         -    import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
  3671         -    if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
  3672         -      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  3673         -      char cSep = '(';
  3674         -      while( xRead(&sCtx) ){
  3675         -        zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
  3676         -        cSep = ',';
  3677         -        if( sCtx.cTerm!=sCtx.cColSep ) break;
  3678         -      }
  3679         -      if( cSep=='(' ){
  3680         -        sqlite3_free(zCreate);
  3681         -        sqlite3_free(sCtx.z);
  3682         -        xCloser(sCtx.in);
  3683         -        utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
  3684         -        return 1;
  3685         -      }
  3686         -      zCreate = sqlite3_mprintf("%z\n)", zCreate);
  3687         -      rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
  3688         -      sqlite3_free(zCreate);
  3689         -      if( rc ){
  3690         -        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  3691         -                sqlite3_errmsg(p->db));
  3692         -        sqlite3_free(sCtx.z);
  3693         -        xCloser(sCtx.in);
  3694         -        return 1;
  3695         -      }
  3696         -      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3697         -    }
  3698         -    sqlite3_free(zSql);
  3699         -    if( rc ){
  3700         -      if (pStmt) sqlite3_finalize(pStmt);
  3701         -      utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
  3702         -      xCloser(sCtx.in);
  3703         -      return 1;
  3704         -    }
  3705         -    nCol = sqlite3_column_count(pStmt);
  3706         -    sqlite3_finalize(pStmt);
  3707         -    pStmt = 0;
  3708         -    if( nCol==0 ) return 0; /* no columns, no error */
  3709         -    zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 );
  3710         -    if( zSql==0 ){
  3711         -      raw_printf(stderr, "Error: out of memory\n");
  3712         -      xCloser(sCtx.in);
  3713         -      return 1;
  3714         -    }
  3715         -    sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
  3716         -    j = strlen30(zSql);
  3717         -    for(i=1; i<nCol; i++){
  3718         -      zSql[j++] = ',';
  3719         -      zSql[j++] = '?';
  3720         -    }
  3721         -    zSql[j++] = ')';
  3722         -    zSql[j] = 0;
  3723         -    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  3724         -    sqlite3_free(zSql);
  3725         -    if( rc ){
  3726         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  3727         -      if (pStmt) sqlite3_finalize(pStmt);
  3728         -      xCloser(sCtx.in);
  3729         -      return 1;
  3730         -    }
  3731         -    needCommit = sqlite3_get_autocommit(p->db);
  3732         -    if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
  3733         -    do{
  3734         -      int startLine = sCtx.nLine;
  3735         -      for(i=0; i<nCol; i++){
  3736         -        char *z = xRead(&sCtx);
  3737         -        /*
  3738         -        ** Did we reach end-of-file before finding any columns?
  3739         -        ** If so, stop instead of NULL filling the remaining columns.
  3740         -        */
  3741         -        if( z==0 && i==0 ) break;
  3742         -        /*
  3743         -        ** Did we reach end-of-file OR end-of-line before finding any
  3744         -        ** columns in ASCII mode?  If so, stop instead of NULL filling
  3745         -        ** the remaining columns.
  3746         -        */
  3747         -        if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break;
  3748         -        sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  3749         -        if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){
  3750         -          utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  3751         -                          "filling the rest with NULL\n",
  3752         -                          sCtx.zFile, startLine, nCol, i+1);
  3753         -          i += 2;
  3754         -          while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; }
  3755         -        }
  3756         -      }
  3757         -      if( sCtx.cTerm==sCtx.cColSep ){
  3758         -        do{
  3759         -          xRead(&sCtx);
  3760         -          i++;
  3761         -        }while( sCtx.cTerm==sCtx.cColSep );
  3762         -        utf8_printf(stderr, "%s:%d: expected %d columns but found %d - "
  3763         -                        "extras ignored\n",
  3764         -                        sCtx.zFile, startLine, nCol, i);
  3765         -      }
  3766         -      if( i>=nCol ){
  3767         -        sqlite3_step(pStmt);
  3768         -        rc = sqlite3_reset(pStmt);
  3769         -        if( rc!=SQLITE_OK ){
  3770         -          utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
  3771         -                      startLine, sqlite3_errmsg(p->db));
  3772         -        }
  3773         -      }
  3774         -    }while( sCtx.cTerm!=EOF );
  3775         -
  3776         -    xCloser(sCtx.in);
  3777         -    sqlite3_free(sCtx.z);
  3778         -    sqlite3_finalize(pStmt);
  3779         -    if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
  3780         -  }else
  3781         -
  3782         -  if( c=='i' && (strncmp(azArg[0], "indices", n)==0
  3783         -                 || strncmp(azArg[0], "indexes", n)==0) ){
  3784         -    ShellState data;
  3785         -    char *zErrMsg = 0;
  3786         -    open_db(p, 0);
  3787         -    memcpy(&data, p, sizeof(data));
  3788         -    data.showHeader = 0;
  3789         -    data.cMode = data.mode = MODE_List;
  3790         -    if( nArg==1 ){
  3791         -      rc = sqlite3_exec(p->db,
  3792         -        "SELECT name FROM sqlite_master "
  3793         -        "WHERE type='index' AND name NOT LIKE 'sqlite_%' "
  3794         -        "UNION ALL "
  3795         -        "SELECT name FROM sqlite_temp_master "
  3796         -        "WHERE type='index' "
  3797         -        "ORDER BY 1",
  3798         -        callback, &data, &zErrMsg
  3799         -      );
  3800         -    }else if( nArg==2 ){
  3801         -      zShellStatic = azArg[1];
  3802         -      rc = sqlite3_exec(p->db,
  3803         -        "SELECT name FROM sqlite_master "
  3804         -        "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3805         -        "UNION ALL "
  3806         -        "SELECT name FROM sqlite_temp_master "
  3807         -        "WHERE type='index' AND tbl_name LIKE shellstatic() "
  3808         -        "ORDER BY 1",
  3809         -        callback, &data, &zErrMsg
  3810         -      );
  3811         -      zShellStatic = 0;
  3812         -    }else{
  3813         -      raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n");
  3814         -      rc = 1;
  3815         -      goto meta_command_exit;
  3816         -    }
  3817         -    if( zErrMsg ){
  3818         -      utf8_printf(stderr,"Error: %s\n", zErrMsg);
  3819         -      sqlite3_free(zErrMsg);
  3820         -      rc = 1;
  3821         -    }else if( rc != SQLITE_OK ){
  3822         -      raw_printf(stderr,
  3823         -                 "Error: querying sqlite_master and sqlite_temp_master\n");
  3824         -      rc = 1;
  3825         -    }
  3826         -  }else
  3827         -
  3828         -#ifdef SQLITE_ENABLE_IOTRACE
  3829         -  if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){
  3830         -    SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...);
  3831         -    if( iotrace && iotrace!=stdout ) fclose(iotrace);
  3832         -    iotrace = 0;
  3833         -    if( nArg<2 ){
  3834         -      sqlite3IoTrace = 0;
  3835         -    }else if( strcmp(azArg[1], "-")==0 ){
  3836         -      sqlite3IoTrace = iotracePrintf;
  3837         -      iotrace = stdout;
  3838         -    }else{
  3839         -      iotrace = fopen(azArg[1], "w");
  3840         -      if( iotrace==0 ){
  3841         -        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
  3842         -        sqlite3IoTrace = 0;
  3843         -        rc = 1;
  3844         -      }else{
  3845         -        sqlite3IoTrace = iotracePrintf;
  3846         -      }
  3847         -    }
  3848         -  }else
  3849         -#endif
  3850         -  if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){
  3851         -    static const struct {
  3852         -       const char *zLimitName;   /* Name of a limit */
  3853         -       int limitCode;            /* Integer code for that limit */
  3854         -    } aLimit[] = {
  3855         -      { "length",                SQLITE_LIMIT_LENGTH                    },
  3856         -      { "sql_length",            SQLITE_LIMIT_SQL_LENGTH                },
  3857         -      { "column",                SQLITE_LIMIT_COLUMN                    },
  3858         -      { "expr_depth",            SQLITE_LIMIT_EXPR_DEPTH                },
  3859         -      { "compound_select",       SQLITE_LIMIT_COMPOUND_SELECT           },
  3860         -      { "vdbe_op",               SQLITE_LIMIT_VDBE_OP                   },
  3861         -      { "function_arg",          SQLITE_LIMIT_FUNCTION_ARG              },
  3862         -      { "attached",              SQLITE_LIMIT_ATTACHED                  },
  3863         -      { "like_pattern_length",   SQLITE_LIMIT_LIKE_PATTERN_LENGTH       },
  3864         -      { "variable_number",       SQLITE_LIMIT_VARIABLE_NUMBER           },
  3865         -      { "trigger_depth",         SQLITE_LIMIT_TRIGGER_DEPTH             },
  3866         -      { "worker_threads",        SQLITE_LIMIT_WORKER_THREADS            },
  3867         -    };
  3868         -    int i, n2;
  3869         -    open_db(p, 0);
  3870         -    if( nArg==1 ){
  3871         -      for(i=0; i<ArraySize(aLimit); i++){
  3872         -        printf("%20s %d\n", aLimit[i].zLimitName,
  3873         -               sqlite3_limit(p->db, aLimit[i].limitCode, -1));
  3874         -      }
  3875         -    }else if( nArg>3 ){
  3876         -      raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n");
  3877         -      rc = 1;
  3878         -      goto meta_command_exit;
  3879         -    }else{
  3880         -      int iLimit = -1;
  3881         -      n2 = strlen30(azArg[1]);
  3882         -      for(i=0; i<ArraySize(aLimit); i++){
  3883         -        if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){
  3884         -          if( iLimit<0 ){
  3885         -            iLimit = i;
  3886         -          }else{
  3887         -            utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]);
  3888         -            rc = 1;
  3889         -            goto meta_command_exit;
  3890         -          }
  3891         -        }
  3892         -      }
  3893         -      if( iLimit<0 ){
  3894         -        utf8_printf(stderr, "unknown limit: \"%s\"\n"
  3895         -                        "enter \".limits\" with no arguments for a list.\n",
  3896         -                         azArg[1]);
  3897         -        rc = 1;
  3898         -        goto meta_command_exit;
  3899         -      }
  3900         -      if( nArg==3 ){
  3901         -        sqlite3_limit(p->db, aLimit[iLimit].limitCode,
  3902         -                      (int)integerValue(azArg[2]));
  3903         -      }
  3904         -      printf("%20s %d\n", aLimit[iLimit].zLimitName,
  3905         -             sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1));
  3906         -    }
  3907         -  }else
  3908         -
  3909         -#ifndef SQLITE_OMIT_LOAD_EXTENSION
  3910         -  if( c=='l' && strncmp(azArg[0], "load", n)==0 ){
  3911         -    const char *zFile, *zProc;
  3912         -    char *zErrMsg = 0;
  3913         -    if( nArg<2 ){
  3914         -      raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n");
  3915         -      rc = 1;
  3916         -      goto meta_command_exit;
  3917         -    }
  3918         -    zFile = azArg[1];
  3919         -    zProc = nArg>=3 ? azArg[2] : 0;
  3920         -    open_db(p, 0);
  3921         -    rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg);
  3922         -    if( rc!=SQLITE_OK ){
  3923         -      utf8_printf(stderr, "Error: %s\n", zErrMsg);
  3924         -      sqlite3_free(zErrMsg);
  3925         -      rc = 1;
  3926         -    }
  3927         -  }else
  3928         -#endif
  3929         -
  3930         -  if( c=='l' && strncmp(azArg[0], "log", n)==0 ){
  3931         -    if( nArg!=2 ){
  3932         -      raw_printf(stderr, "Usage: .log FILENAME\n");
  3933         -      rc = 1;
  3934         -    }else{
  3935         -      const char *zFile = azArg[1];
  3936         -      output_file_close(p->pLog);
  3937         -      p->pLog = output_file_open(zFile);
  3938         -    }
  3939         -  }else
  3940         -
  3941         -  if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){
  3942         -    const char *zMode = nArg>=2 ? azArg[1] : "";
  3943         -    int n2 = (int)strlen(zMode);
  3944         -    int c2 = zMode[0];
  3945         -    if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){
  3946         -      p->mode = MODE_Line;
  3947         -    }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
  3948         -      p->mode = MODE_Column;
  3949         -    }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
  3950         -      p->mode = MODE_List;
  3951         -    }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){
  3952         -      p->mode = MODE_Html;
  3953         -    }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){
  3954         -      p->mode = MODE_Tcl;
  3955         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space);
  3956         -    }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){
  3957         -      p->mode = MODE_Csv;
  3958         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
  3959         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
  3960         -    }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){
  3961         -      p->mode = MODE_List;
  3962         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab);
  3963         -    }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){
  3964         -      p->mode = MODE_Insert;
  3965         -      set_table_name(p, nArg>=3 ? azArg[2] : "table");
  3966         -    }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
  3967         -      p->mode = MODE_Ascii;
  3968         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
  3969         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
  3970         -    }else {
  3971         -      raw_printf(stderr, "Error: mode should be one of: "
  3972         -         "ascii column csv html insert line list tabs tcl\n");
  3973         -      rc = 1;
  3974         -    }
  3975         -    p->cMode = p->mode;
  3976         -  }else
  3977         -
  3978         -  if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){
  3979         -    if( nArg==2 ){
  3980         -      sqlite3_snprintf(sizeof(p->nullValue), p->nullValue,
  3981         -                       "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]);
  3982         -    }else{
  3983         -      raw_printf(stderr, "Usage: .nullvalue STRING\n");
  3984         -      rc = 1;
  3985         -    }
  3986         -  }else
  3987         -
  3988         -  if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
  3989         -    char *zNewFilename;  /* Name of the database file to open */
  3990         -    int iName = 1;       /* Index in azArg[] of the filename */
  3991         -    int newFlag = 0;     /* True to delete file before opening */
  3992         -    /* Close the existing database */
  3993         -    session_close_all(p);
  3994         -    sqlite3_close(p->db);
  3995         -    p->db = 0;
  3996         -    sqlite3_free(p->zFreeOnClose);
  3997         -    p->zFreeOnClose = 0;
  3998         -    /* Check for command-line arguments */
  3999         -    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
  4000         -      const char *z = azArg[iName];
  4001         -      if( optionMatch(z,"new") ){
  4002         -        newFlag = 1;
  4003         -      }else if( z[0]=='-' ){
  4004         -        utf8_printf(stderr, "unknown option: %s\n", z);
  4005         -        rc = 1;
  4006         -        goto meta_command_exit;
  4007         -      }
  4008         -    }
  4009         -    /* If a filename is specified, try to open it first */
  4010         -    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
  4011         -    if( zNewFilename ){
  4012         -      if( newFlag ) shellDeleteFile(zNewFilename);
  4013         -      p->zDbFilename = zNewFilename;
  4014         -      open_db(p, 1);
  4015         -      if( p->db==0 ){
  4016         -        utf8_printf(stderr, "Error: cannot open '%s'\n", zNewFilename);
  4017         -        sqlite3_free(zNewFilename);
  4018         -      }else{
  4019         -        p->zFreeOnClose = zNewFilename;
  4020         -      }
  4021         -    }
  4022         -    if( p->db==0 ){
  4023         -      /* As a fall-back open a TEMP database */
  4024         -      p->zDbFilename = 0;
  4025         -      open_db(p, 0);
  4026         -    }
  4027         -  }else
  4028         -
  4029         -  if( c=='o'
  4030         -   && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0)
  4031         -  ){
  4032         -    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
  4033         -    if( nArg>2 ){
  4034         -      utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]);
  4035         -      rc = 1;
  4036         -      goto meta_command_exit;
  4037         -    }
  4038         -    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
  4039         -      if( nArg<2 ){
  4040         -        raw_printf(stderr, "Usage: .once FILE\n");
  4041         -        rc = 1;
  4042         -        goto meta_command_exit;
  4043         -      }
  4044         -      p->outCount = 2;
  4045         -    }else{
  4046         -      p->outCount = 0;
  4047         -    }
  4048         -    output_reset(p);
  4049         -    if( zFile[0]=='|' ){
  4050         -#ifdef SQLITE_OMIT_POPEN
  4051         -      raw_printf(stderr, "Error: pipes are not supported in this OS\n");
  4052         -      rc = 1;
  4053         -      p->out = stdout;
  4054         -#else
  4055         -      p->out = popen(zFile + 1, "w");
  4056         -      if( p->out==0 ){
  4057         -        utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1);
  4058         -        p->out = stdout;
  4059         -        rc = 1;
  4060         -      }else{
  4061         -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  4062         -      }
  4063         -#endif
  4064         -    }else{
  4065         -      p->out = output_file_open(zFile);
  4066         -      if( p->out==0 ){
  4067         -        if( strcmp(zFile,"off")!=0 ){
  4068         -          utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile);
  4069         -        }
  4070         -        p->out = stdout;
  4071         -        rc = 1;
  4072         -      } else {
  4073         -        sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
  4074         -      }
  4075         -    }
  4076         -  }else
  4077         -
  4078         -  if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){
  4079         -    int i;
  4080         -    for(i=1; i<nArg; i++){
  4081         -      if( i>1 ) raw_printf(p->out, " ");
  4082         -      utf8_printf(p->out, "%s", azArg[i]);
  4083         -    }
  4084         -    raw_printf(p->out, "\n");
  4085         -  }else
  4086         -
  4087         -  if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){
  4088         -    if( nArg >= 2) {
  4089         -      strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1);
  4090         -    }
  4091         -    if( nArg >= 3) {
  4092         -      strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1);
  4093         -    }
  4094         -  }else
  4095         -
  4096         -  if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){
  4097         -    rc = 2;
  4098         -  }else
  4099         -
  4100         -  if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){
  4101         -    FILE *alt;
  4102         -    if( nArg!=2 ){
  4103         -      raw_printf(stderr, "Usage: .read FILE\n");
  4104         -      rc = 1;
  4105         -      goto meta_command_exit;
  4106         -    }
  4107         -    alt = fopen(azArg[1], "rb");
  4108         -    if( alt==0 ){
  4109         -      utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
  4110         -      rc = 1;
  4111         -    }else{
  4112         -      rc = process_input(p, alt);
  4113         -      fclose(alt);
  4114         -    }
  4115         -  }else
  4116         -
  4117         -  if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){
  4118         -    const char *zSrcFile;
  4119         -    const char *zDb;
  4120         -    sqlite3 *pSrc;
  4121         -    sqlite3_backup *pBackup;
  4122         -    int nTimeout = 0;
  4123         -
  4124         -    if( nArg==2 ){
  4125         -      zSrcFile = azArg[1];
  4126         -      zDb = "main";
  4127         -    }else if( nArg==3 ){
  4128         -      zSrcFile = azArg[2];
  4129         -      zDb = azArg[1];
  4130         -    }else{
  4131         -      raw_printf(stderr, "Usage: .restore ?DB? FILE\n");
  4132         -      rc = 1;
  4133         -      goto meta_command_exit;
  4134         -    }
  4135         -    rc = sqlite3_open(zSrcFile, &pSrc);
  4136         -    if( rc!=SQLITE_OK ){
  4137         -      utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile);
  4138         -      sqlite3_close(pSrc);
  4139         -      return 1;
  4140         -    }
  4141         -    open_db(p, 0);
  4142         -    pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main");
  4143         -    if( pBackup==0 ){
  4144         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  4145         -      sqlite3_close(pSrc);
  4146         -      return 1;
  4147         -    }
  4148         -    while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK
  4149         -          || rc==SQLITE_BUSY  ){
  4150         -      if( rc==SQLITE_BUSY ){
  4151         -        if( nTimeout++ >= 3 ) break;
  4152         -        sqlite3_sleep(100);
  4153         -      }
  4154         -    }
  4155         -    sqlite3_backup_finish(pBackup);
  4156         -    if( rc==SQLITE_DONE ){
  4157         -      rc = 0;
  4158         -    }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  4159         -      raw_printf(stderr, "Error: source database is busy\n");
  4160         -      rc = 1;
  4161         -    }else{
  4162         -      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
  4163         -      rc = 1;
  4164         -    }
  4165         -    sqlite3_close(pSrc);
  4166         -  }else
  4167         -
  4168         -
  4169         -  if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){
  4170         -    if( nArg==2 ){
  4171         -      p->scanstatsOn = booleanValue(azArg[1]);
  4172         -#ifndef SQLITE_ENABLE_STMT_SCANSTATUS
  4173         -      raw_printf(stderr, "Warning: .scanstats not available in this build.\n");
  4174         -#endif
  4175         -    }else{
  4176         -      raw_printf(stderr, "Usage: .scanstats on|off\n");
  4177         -      rc = 1;
  4178         -    }
  4179         -  }else
  4180         -
  4181         -  if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
  4182         -    ShellState data;
  4183         -    char *zErrMsg = 0;
  4184         -    open_db(p, 0);
  4185         -    memcpy(&data, p, sizeof(data));
  4186         -    data.showHeader = 0;
  4187         -    data.cMode = data.mode = MODE_Semi;
  4188         -    if( nArg>=2 && optionMatch(azArg[1], "indent") ){
  4189         -      data.cMode = data.mode = MODE_Pretty;
  4190         -      nArg--;
  4191         -      if( nArg==2 ) azArg[1] = azArg[2];
  4192         -    }
  4193         -    if( nArg==2 && azArg[1][0]!='-' ){
  4194         -      int i;
  4195         -      for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]);
  4196         -      if( strcmp(azArg[1],"sqlite_master")==0 ){
  4197         -        char *new_argv[2], *new_colv[2];
  4198         -        new_argv[0] = "CREATE TABLE sqlite_master (\n"
  4199         -                      "  type text,\n"
  4200         -                      "  name text,\n"
  4201         -                      "  tbl_name text,\n"
  4202         -                      "  rootpage integer,\n"
  4203         -                      "  sql text\n"
  4204         -                      ")";
  4205         -        new_argv[1] = 0;
  4206         -        new_colv[0] = "sql";
  4207         -        new_colv[1] = 0;
  4208         -        callback(&data, 1, new_argv, new_colv);
  4209         -        rc = SQLITE_OK;
  4210         -      }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){
  4211         -        char *new_argv[2], *new_colv[2];
  4212         -        new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n"
  4213         -                      "  type text,\n"
  4214         -                      "  name text,\n"
  4215         -                      "  tbl_name text,\n"
  4216         -                      "  rootpage integer,\n"
  4217         -                      "  sql text\n"
  4218         -                      ")";
  4219         -        new_argv[1] = 0;
  4220         -        new_colv[0] = "sql";
  4221         -        new_colv[1] = 0;
  4222         -        callback(&data, 1, new_argv, new_colv);
  4223         -        rc = SQLITE_OK;
  4224         -      }else{
  4225         -        zShellStatic = azArg[1];
  4226         -        rc = sqlite3_exec(p->db,
  4227         -          "SELECT sql FROM "
  4228         -          "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  4229         -          "     FROM sqlite_master UNION ALL"
  4230         -          "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  4231         -          "WHERE lower(tbl_name) LIKE shellstatic()"
  4232         -          "  AND type!='meta' AND sql NOTNULL "
  4233         -          "ORDER BY rowid",
  4234         -          callback, &data, &zErrMsg);
  4235         -        zShellStatic = 0;
  4236         -      }
  4237         -    }else if( nArg==1 ){
  4238         -      rc = sqlite3_exec(p->db,
  4239         -         "SELECT sql FROM "
  4240         -         "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
  4241         -         "     FROM sqlite_master UNION ALL"
  4242         -         "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
  4243         -         "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
  4244         -         "ORDER BY rowid",
  4245         -         callback, &data, &zErrMsg
  4246         -      );
  4247         -    }else{
  4248         -      raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
  4249         -      rc = 1;
  4250         -      goto meta_command_exit;
  4251         -    }
  4252         -    if( zErrMsg ){
  4253         -      utf8_printf(stderr,"Error: %s\n", zErrMsg);
  4254         -      sqlite3_free(zErrMsg);
  4255         -      rc = 1;
  4256         -    }else if( rc != SQLITE_OK ){
  4257         -      raw_printf(stderr,"Error: querying schema information\n");
  4258         -      rc = 1;
  4259         -    }else{
  4260         -      rc = 0;
  4261         -    }
  4262         -  }else
  4263         -
  4264         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
  4265         -  if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
  4266         -    sqlite3SelectTrace = integerValue(azArg[1]);
  4267         -  }else
  4268         -#endif
  4269         -
  4270         -#if defined(SQLITE_ENABLE_SESSION)
  4271         -  if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
  4272         -    OpenSession *pSession = &p->aSession[0];
  4273         -    char **azCmd = &azArg[1];
  4274         -    int iSes = 0;
  4275         -    int nCmd = nArg - 1;
  4276         -    int i;
  4277         -    if( nArg<=1 ) goto session_syntax_error;
  4278         -    open_db(p, 0);
  4279         -    if( nArg>=3 ){
  4280         -      for(iSes=0; iSes<p->nSession; iSes++){
  4281         -        if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break;
  4282         -      }
  4283         -      if( iSes<p->nSession ){
  4284         -        pSession = &p->aSession[iSes];
  4285         -        azCmd++;
  4286         -        nCmd--;
  4287         -      }else{
  4288         -        pSession = &p->aSession[0];
  4289         -        iSes = 0;
  4290         -      }
  4291         -    }
  4292         -
  4293         -    /* .session attach TABLE
  4294         -    ** Invoke the sqlite3session_attach() interface to attach a particular
  4295         -    ** table so that it is never filtered.
  4296         -    */
  4297         -    if( strcmp(azCmd[0],"attach")==0 ){
  4298         -      if( nCmd!=2 ) goto session_syntax_error;
  4299         -      if( pSession->p==0 ){
  4300         -        session_not_open:
  4301         -        raw_printf(stderr, "ERROR: No sessions are open\n");
  4302         -      }else{
  4303         -        rc = sqlite3session_attach(pSession->p, azCmd[1]);
  4304         -        if( rc ){
  4305         -          raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc);
  4306         -          rc = 0;
  4307         -        }
  4308         -      }
  4309         -    }else
  4310         -
  4311         -    /* .session changeset FILE
  4312         -    ** .session patchset FILE
  4313         -    ** Write a changeset or patchset into a file.  The file is overwritten.
  4314         -    */
  4315         -    if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){
  4316         -      FILE *out = 0;
  4317         -      if( nCmd!=2 ) goto session_syntax_error;
  4318         -      if( pSession->p==0 ) goto session_not_open;
  4319         -      out = fopen(azCmd[1], "wb");
  4320         -      if( out==0 ){
  4321         -        utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]);
  4322         -      }else{
  4323         -        int szChng;
  4324         -        void *pChng;
  4325         -        if( azCmd[0][0]=='c' ){
  4326         -          rc = sqlite3session_changeset(pSession->p, &szChng, &pChng);
  4327         -        }else{
  4328         -          rc = sqlite3session_patchset(pSession->p, &szChng, &pChng);
  4329         -        }
  4330         -        if( rc ){
  4331         -          printf("Error: error code %d\n", rc);
  4332         -          rc = 0;
  4333         -        }
  4334         -        if( pChng
  4335         -          && fwrite(pChng, szChng, 1, out)!=1 ){
  4336         -          raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n",
  4337         -                  szChng);
  4338         -        }
  4339         -        sqlite3_free(pChng);
  4340         -        fclose(out);
  4341         -      }
  4342         -    }else
  4343         -
  4344         -    /* .session close
  4345         -    ** Close the identified session
  4346         -    */
  4347         -    if( strcmp(azCmd[0], "close")==0 ){
  4348         -      if( nCmd!=1 ) goto session_syntax_error;
  4349         -      if( p->nSession ){
  4350         -        session_close(pSession);
  4351         -        p->aSession[iSes] = p->aSession[--p->nSession];
  4352         -      }
  4353         -    }else
  4354         -
  4355         -    /* .session enable ?BOOLEAN?
  4356         -    ** Query or set the enable flag
  4357         -    */
  4358         -    if( strcmp(azCmd[0], "enable")==0 ){
  4359         -      int ii;
  4360         -      if( nCmd>2 ) goto session_syntax_error;
  4361         -      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  4362         -      if( p->nSession ){
  4363         -        ii = sqlite3session_enable(pSession->p, ii);
  4364         -        utf8_printf(p->out, "session %s enable flag = %d\n",
  4365         -                    pSession->zName, ii);
  4366         -      }
  4367         -    }else
  4368         -
  4369         -    /* .session filter GLOB ....
  4370         -    ** Set a list of GLOB patterns of table names to be excluded.
  4371         -    */
  4372         -    if( strcmp(azCmd[0], "filter")==0 ){
  4373         -      int ii, nByte;
  4374         -      if( nCmd<2 ) goto session_syntax_error;
  4375         -      if( p->nSession ){
  4376         -        for(ii=0; ii<pSession->nFilter; ii++){
  4377         -          sqlite3_free(pSession->azFilter[ii]);
  4378         -        }
  4379         -        sqlite3_free(pSession->azFilter);
  4380         -        nByte = sizeof(pSession->azFilter[0])*(nCmd-1);
  4381         -        pSession->azFilter = sqlite3_malloc( nByte );
  4382         -        if( pSession->azFilter==0 ){
  4383         -          raw_printf(stderr, "Error: out or memory\n");
  4384         -          exit(1);
  4385         -        }
  4386         -        for(ii=1; ii<nCmd; ii++){
  4387         -          pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]);
  4388         -        }
  4389         -        pSession->nFilter = ii-1;
  4390         -      }
  4391         -    }else
  4392         -
  4393         -    /* .session indirect ?BOOLEAN?
  4394         -    ** Query or set the indirect flag
  4395         -    */
  4396         -    if( strcmp(azCmd[0], "indirect")==0 ){
  4397         -      int ii;
  4398         -      if( nCmd>2 ) goto session_syntax_error;
  4399         -      ii = nCmd==1 ? -1 : booleanValue(azCmd[1]);
  4400         -      if( p->nSession ){
  4401         -        ii = sqlite3session_indirect(pSession->p, ii);
  4402         -        utf8_printf(p->out, "session %s indirect flag = %d\n",
  4403         -                    pSession->zName, ii);
  4404         -      }
  4405         -    }else
  4406         -
  4407         -    /* .session isempty
  4408         -    ** Determine if the session is empty
  4409         -    */
  4410         -    if( strcmp(azCmd[0], "isempty")==0 ){
  4411         -      int ii;
  4412         -      if( nCmd!=1 ) goto session_syntax_error;
  4413         -      if( p->nSession ){
  4414         -        ii = sqlite3session_isempty(pSession->p);
  4415         -        utf8_printf(p->out, "session %s isempty flag = %d\n",
  4416         -                    pSession->zName, ii);
  4417         -      }
  4418         -    }else
  4419         -
  4420         -    /* .session list
  4421         -    ** List all currently open sessions
  4422         -    */
  4423         -    if( strcmp(azCmd[0],"list")==0 ){
  4424         -      for(i=0; i<p->nSession; i++){
  4425         -        utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName);
  4426         -      }
  4427         -    }else
  4428         -
  4429         -    /* .session open DB NAME
  4430         -    ** Open a new session called NAME on the attached database DB.
  4431         -    ** DB is normally "main".
  4432         -    */
  4433         -    if( strcmp(azCmd[0],"open")==0 ){
  4434         -      char *zName;
  4435         -      if( nCmd!=3 ) goto session_syntax_error;
  4436         -      zName = azCmd[2];
  4437         -      if( zName[0]==0 ) goto session_syntax_error;
  4438         -      for(i=0; i<p->nSession; i++){
  4439         -        if( strcmp(p->aSession[i].zName,zName)==0 ){
  4440         -          utf8_printf(stderr, "Session \"%s\" already exists\n", zName);
  4441         -          goto meta_command_exit;
  4442         -        }
  4443         -      }
  4444         -      if( p->nSession>=ArraySize(p->aSession) ){
  4445         -        raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession));
  4446         -        goto meta_command_exit;
  4447         -      }
  4448         -      pSession = &p->aSession[p->nSession];
  4449         -      rc = sqlite3session_create(p->db, azCmd[1], &pSession->p);
  4450         -      if( rc ){
  4451         -        raw_printf(stderr, "Cannot open session: error code=%d\n", rc);
  4452         -        rc = 0;
  4453         -        goto meta_command_exit;
  4454         -      }
  4455         -      pSession->nFilter = 0;
  4456         -      sqlite3session_table_filter(pSession->p, session_filter, pSession);
  4457         -      p->nSession++;
  4458         -      pSession->zName = sqlite3_mprintf("%s", zName);
  4459         -    }else
  4460         -    /* If no command name matches, show a syntax error */
  4461         -    session_syntax_error:
  4462         -    session_help(p);
  4463         -  }else
  4464         -#endif
  4465         -
  4466         -#ifdef SQLITE_DEBUG
  4467         -  /* Undocumented commands for internal testing.  Subject to change
  4468         -  ** without notice. */
  4469         -  if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){
  4470         -    if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){
  4471         -      int i, v;
  4472         -      for(i=1; i<nArg; i++){
  4473         -        v = booleanValue(azArg[i]);
  4474         -        utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v);
  4475         -      }
  4476         -    }
  4477         -    if( strncmp(azArg[0]+9, "integer", n-9)==0 ){
  4478         -      int i; sqlite3_int64 v;
  4479         -      for(i=1; i<nArg; i++){
  4480         -        char zBuf[200];
  4481         -        v = integerValue(azArg[i]);
  4482         -        sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v);
  4483         -        utf8_printf(p->out, "%s", zBuf);
  4484         -      }
  4485         -    }
  4486         -  }else
  4487         -#endif
  4488         -
  4489         -  if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){
  4490         -    if( nArg<2 || nArg>3 ){
  4491         -      raw_printf(stderr, "Usage: .separator COL ?ROW?\n");
  4492         -      rc = 1;
  4493         -    }
  4494         -    if( nArg>=2 ){
  4495         -      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator,
  4496         -                       "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]);
  4497         -    }
  4498         -    if( nArg>=3 ){
  4499         -      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator,
  4500         -                       "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]);
  4501         -    }
  4502         -  }else
  4503         -
  4504         -  if( c=='s'
  4505         -   && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0)
  4506         -  ){
  4507         -    char *zCmd;
  4508         -    int i, x;
  4509         -    if( nArg<2 ){
  4510         -      raw_printf(stderr, "Usage: .system COMMAND\n");
  4511         -      rc = 1;
  4512         -      goto meta_command_exit;
  4513         -    }
  4514         -    zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]);
  4515         -    for(i=2; i<nArg; i++){
  4516         -      zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"",
  4517         -                             zCmd, azArg[i]);
  4518         -    }
  4519         -    x = system(zCmd);
  4520         -    sqlite3_free(zCmd);
  4521         -    if( x ) raw_printf(stderr, "System command returns %d\n", x);
  4522         -  }else
  4523         -
  4524         -  if( c=='s' && strncmp(azArg[0], "show", n)==0 ){
  4525         -    static const char *const azBool[] = { "off", "on", "full", "unk" };
  4526         -    int i;
  4527         -    if( nArg!=1 ){
  4528         -      raw_printf(stderr, "Usage: .show\n");
  4529         -      rc = 1;
  4530         -      goto meta_command_exit;
  4531         -    }
  4532         -    utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[p->echoOn!=0]);
  4533         -    utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]);
  4534         -    utf8_printf(p->out, "%12.12s: %s\n","explain",
  4535         -         p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off");
  4536         -    utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]);
  4537         -    utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]);
  4538         -    utf8_printf(p->out, "%12.12s: ", "nullvalue");
  4539         -      output_c_string(p->out, p->nullValue);
  4540         -      raw_printf(p->out, "\n");
  4541         -    utf8_printf(p->out,"%12.12s: %s\n","output",
  4542         -            strlen30(p->outfile) ? p->outfile : "stdout");
  4543         -    utf8_printf(p->out,"%12.12s: ", "colseparator");
  4544         -      output_c_string(p->out, p->colSeparator);
  4545         -      raw_printf(p->out, "\n");
  4546         -    utf8_printf(p->out,"%12.12s: ", "rowseparator");
  4547         -      output_c_string(p->out, p->rowSeparator);
  4548         -      raw_printf(p->out, "\n");
  4549         -    utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
  4550         -    utf8_printf(p->out, "%12.12s: ", "width");
  4551         -    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
  4552         -      raw_printf(p->out, "%d ", p->colWidth[i]);
  4553         -    }
  4554         -    raw_printf(p->out, "\n");
  4555         -    utf8_printf(p->out, "%12.12s: %s\n", "filename",
  4556         -                p->zDbFilename ? p->zDbFilename : "");
  4557         -  }else
  4558         -
  4559         -  if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){
  4560         -    if( nArg==2 ){
  4561         -      p->statsOn = booleanValue(azArg[1]);
  4562         -    }else if( nArg==1 ){
  4563         -      display_stats(p->db, p, 0);
  4564         -    }else{
  4565         -      raw_printf(stderr, "Usage: .stats ?on|off?\n");
  4566         -      rc = 1;
  4567         -    }
  4568         -  }else
  4569         -
  4570         -  if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){
  4571         -    sqlite3_stmt *pStmt;
  4572         -    char **azResult;
  4573         -    int nRow, nAlloc;
  4574         -    char *zSql = 0;
  4575         -    int ii;
  4576         -    open_db(p, 0);
  4577         -    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
  4578         -    if( rc ) return shellDatabaseError(p->db);
  4579         -
  4580         -    /* Create an SQL statement to query for the list of tables in the
  4581         -    ** main and all attached databases where the table name matches the
  4582         -    ** LIKE pattern bound to variable "?1". */
  4583         -    zSql = sqlite3_mprintf(
  4584         -        "SELECT name FROM sqlite_master"
  4585         -        " WHERE type IN ('table','view')"
  4586         -        "   AND name NOT LIKE 'sqlite_%%'"
  4587         -        "   AND name LIKE ?1");
  4588         -    while( zSql && sqlite3_step(pStmt)==SQLITE_ROW ){
  4589         -      const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1);
  4590         -      if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue;
  4591         -      if( strcmp(zDbName,"temp")==0 ){
  4592         -        zSql = sqlite3_mprintf(
  4593         -                 "%z UNION ALL "
  4594         -                 "SELECT 'temp.' || name FROM sqlite_temp_master"
  4595         -                 " WHERE type IN ('table','view')"
  4596         -                 "   AND name NOT LIKE 'sqlite_%%'"
  4597         -                 "   AND name LIKE ?1", zSql);
  4598         -      }else{
  4599         -        zSql = sqlite3_mprintf(
  4600         -                 "%z UNION ALL "
  4601         -                 "SELECT '%q.' || name FROM \"%w\".sqlite_master"
  4602         -                 " WHERE type IN ('table','view')"
  4603         -                 "   AND name NOT LIKE 'sqlite_%%'"
  4604         -                 "   AND name LIKE ?1", zSql, zDbName, zDbName);
  4605         -      }
  4606         -    }
  4607         -    rc = sqlite3_finalize(pStmt);
  4608         -    if( zSql && rc==SQLITE_OK ){
  4609         -      zSql = sqlite3_mprintf("%z ORDER BY 1", zSql);
  4610         -      if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  4611         -    }
  4612         -    sqlite3_free(zSql);
  4613         -    if( !zSql ) return shellNomemError();
  4614         -    if( rc ) return shellDatabaseError(p->db);
  4615         -
  4616         -    /* Run the SQL statement prepared by the above block. Store the results
  4617         -    ** as an array of nul-terminated strings in azResult[].  */
  4618         -    nRow = nAlloc = 0;
  4619         -    azResult = 0;
  4620         -    if( nArg>1 ){
  4621         -      sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT);
  4622         -    }else{
  4623         -      sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC);
  4624         -    }
  4625         -    while( sqlite3_step(pStmt)==SQLITE_ROW ){
  4626         -      if( nRow>=nAlloc ){
  4627         -        char **azNew;
  4628         -        int n2 = nAlloc*2 + 10;
  4629         -        azNew = sqlite3_realloc(azResult, sizeof(azResult[0])*n2);
  4630         -        if( azNew==0 ){
  4631         -          rc = shellNomemError();
  4632         -          break;
  4633         -        }
  4634         -        nAlloc = n2;
  4635         -        azResult = azNew;
  4636         -      }
  4637         -      azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
  4638         -      if( 0==azResult[nRow] ){
  4639         -        rc = shellNomemError();
  4640         -        break;
  4641         -      }
  4642         -      nRow++;
  4643         -    }
  4644         -    if( sqlite3_finalize(pStmt)!=SQLITE_OK ){
  4645         -      rc = shellDatabaseError(p->db);
  4646         -    }
  4647         -
  4648         -    /* Pretty-print the contents of array azResult[] to the output */
  4649         -    if( rc==0 && nRow>0 ){
  4650         -      int len, maxlen = 0;
  4651         -      int i, j;
  4652         -      int nPrintCol, nPrintRow;
  4653         -      for(i=0; i<nRow; i++){
  4654         -        len = strlen30(azResult[i]);
  4655         -        if( len>maxlen ) maxlen = len;
  4656         -      }
  4657         -      nPrintCol = 80/(maxlen+2);
  4658         -      if( nPrintCol<1 ) nPrintCol = 1;
  4659         -      nPrintRow = (nRow + nPrintCol - 1)/nPrintCol;
  4660         -      for(i=0; i<nPrintRow; i++){
  4661         -        for(j=i; j<nRow; j+=nPrintRow){
  4662         -          char *zSp = j<nPrintRow ? "" : "  ";
  4663         -          utf8_printf(p->out, "%s%-*s", zSp, maxlen,
  4664         -                      azResult[j] ? azResult[j]:"");
  4665         -        }
  4666         -        raw_printf(p->out, "\n");
  4667         -      }
  4668         -    }
  4669         -
  4670         -    for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]);
  4671         -    sqlite3_free(azResult);
  4672         -  }else
  4673         -
  4674         -  /* Begin redirecting output to the file "testcase-out.txt" */
  4675         -  if( c=='t' && strcmp(azArg[0],"testcase")==0 ){
  4676         -    output_reset(p);
  4677         -    p->out = output_file_open("testcase-out.txt");
  4678         -    if( p->out==0 ){
  4679         -      utf8_printf(stderr, "Error: cannot open 'testcase-out.txt'\n");
  4680         -    }
  4681         -    if( nArg>=2 ){
  4682         -      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "%s", azArg[1]);
  4683         -    }else{
  4684         -      sqlite3_snprintf(sizeof(p->zTestcase), p->zTestcase, "?");
  4685         -    }
  4686         -  }else
  4687         -
  4688         -  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
  4689         -    static const struct {
  4690         -       const char *zCtrlName;   /* Name of a test-control option */
  4691         -       int ctrlCode;            /* Integer code for that option */
  4692         -    } aCtrl[] = {
  4693         -      { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
  4694         -      { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
  4695         -      { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
  4696         -      { "bitvec_test",           SQLITE_TESTCTRL_BITVEC_TEST            },
  4697         -      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
  4698         -      { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
  4699         -      { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
  4700         -      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
  4701         -      { "always",                SQLITE_TESTCTRL_ALWAYS                 },
  4702         -      { "reserve",               SQLITE_TESTCTRL_RESERVE                },
  4703         -      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
  4704         -      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
  4705         -      { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
  4706         -      { "byteorder",             SQLITE_TESTCTRL_BYTEORDER              },
  4707         -      { "never_corrupt",         SQLITE_TESTCTRL_NEVER_CORRUPT          },
  4708         -      { "imposter",              SQLITE_TESTCTRL_IMPOSTER               },
  4709         -    };
  4710         -    int testctrl = -1;
  4711         -    int rc2 = 0;
  4712         -    int i, n2;
  4713         -    open_db(p, 0);
  4714         -
  4715         -    /* convert testctrl text option to value. allow any unique prefix
  4716         -    ** of the option name, or a numerical value. */
  4717         -    n2 = strlen30(azArg[1]);
  4718         -    for(i=0; i<ArraySize(aCtrl); i++){
  4719         -      if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){
  4720         -        if( testctrl<0 ){
  4721         -          testctrl = aCtrl[i].ctrlCode;
  4722         -        }else{
  4723         -          utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]);
  4724         -          testctrl = -1;
  4725         -          break;
  4726         -        }
  4727         -      }
  4728         -    }
  4729         -    if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]);
  4730         -    if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){
  4731         -      utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]);
  4732         -    }else{
  4733         -      switch(testctrl){
  4734         -
  4735         -        /* sqlite3_test_control(int, db, int) */
  4736         -        case SQLITE_TESTCTRL_OPTIMIZATIONS:
  4737         -        case SQLITE_TESTCTRL_RESERVE:
  4738         -          if( nArg==3 ){
  4739         -            int opt = (int)strtol(azArg[2], 0, 0);
  4740         -            rc2 = sqlite3_test_control(testctrl, p->db, opt);
  4741         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4742         -          } else {
  4743         -            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  4744         -                    azArg[1]);
  4745         -          }
  4746         -          break;
  4747         -
  4748         -        /* sqlite3_test_control(int) */
  4749         -        case SQLITE_TESTCTRL_PRNG_SAVE:
  4750         -        case SQLITE_TESTCTRL_PRNG_RESTORE:
  4751         -        case SQLITE_TESTCTRL_PRNG_RESET:
  4752         -        case SQLITE_TESTCTRL_BYTEORDER:
  4753         -          if( nArg==2 ){
  4754         -            rc2 = sqlite3_test_control(testctrl);
  4755         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4756         -          } else {
  4757         -            utf8_printf(stderr,"Error: testctrl %s takes no options\n",
  4758         -                        azArg[1]);
  4759         -          }
  4760         -          break;
  4761         -
  4762         -        /* sqlite3_test_control(int, uint) */
  4763         -        case SQLITE_TESTCTRL_PENDING_BYTE:
  4764         -          if( nArg==3 ){
  4765         -            unsigned int opt = (unsigned int)integerValue(azArg[2]);
  4766         -            rc2 = sqlite3_test_control(testctrl, opt);
  4767         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4768         -          } else {
  4769         -            utf8_printf(stderr,"Error: testctrl %s takes a single unsigned"
  4770         -                           " int option\n", azArg[1]);
  4771         -          }
  4772         -          break;
  4773         -
  4774         -        /* sqlite3_test_control(int, int) */
  4775         -        case SQLITE_TESTCTRL_ASSERT:
  4776         -        case SQLITE_TESTCTRL_ALWAYS:
  4777         -        case SQLITE_TESTCTRL_NEVER_CORRUPT:
  4778         -          if( nArg==3 ){
  4779         -            int opt = booleanValue(azArg[2]);
  4780         -            rc2 = sqlite3_test_control(testctrl, opt);
  4781         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4782         -          } else {
  4783         -            utf8_printf(stderr,"Error: testctrl %s takes a single int option\n",
  4784         -                            azArg[1]);
  4785         -          }
  4786         -          break;
  4787         -
  4788         -        /* sqlite3_test_control(int, char *) */
  4789         -#ifdef SQLITE_N_KEYWORD
  4790         -        case SQLITE_TESTCTRL_ISKEYWORD:
  4791         -          if( nArg==3 ){
  4792         -            const char *opt = azArg[2];
  4793         -            rc2 = sqlite3_test_control(testctrl, opt);
  4794         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4795         -          } else {
  4796         -            utf8_printf(stderr,
  4797         -                        "Error: testctrl %s takes a single char * option\n",
  4798         -                        azArg[1]);
  4799         -          }
  4800         -          break;
  4801         -#endif
  4802         -
  4803         -        case SQLITE_TESTCTRL_IMPOSTER:
  4804         -          if( nArg==5 ){
  4805         -            rc2 = sqlite3_test_control(testctrl, p->db,
  4806         -                          azArg[2],
  4807         -                          integerValue(azArg[3]),
  4808         -                          integerValue(azArg[4]));
  4809         -            raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2);
  4810         -          }else{
  4811         -            raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n");
  4812         -          }
  4813         -          break;
  4814         -
  4815         -        case SQLITE_TESTCTRL_BITVEC_TEST:
  4816         -        case SQLITE_TESTCTRL_FAULT_INSTALL:
  4817         -        case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS:
  4818         -        case SQLITE_TESTCTRL_SCRATCHMALLOC:
  4819         -        default:
  4820         -          utf8_printf(stderr,
  4821         -                      "Error: CLI support for testctrl %s not implemented\n",
  4822         -                      azArg[1]);
  4823         -          break;
  4824         -      }
  4825         -    }
  4826         -  }else
  4827         -
  4828         -  if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){
  4829         -    open_db(p, 0);
  4830         -    sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0);
  4831         -  }else
  4832         -
  4833         -  if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){
  4834         -    if( nArg==2 ){
  4835         -      enableTimer = booleanValue(azArg[1]);
  4836         -      if( enableTimer && !HAS_TIMER ){
  4837         -        raw_printf(stderr, "Error: timer not available on this system.\n");
  4838         -        enableTimer = 0;
  4839         -      }
  4840         -    }else{
  4841         -      raw_printf(stderr, "Usage: .timer on|off\n");
  4842         -      rc = 1;
  4843         -    }
  4844         -  }else
  4845         -
  4846         -  if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){
  4847         -    open_db(p, 0);
  4848         -    if( nArg!=2 ){
  4849         -      raw_printf(stderr, "Usage: .trace FILE|off\n");
  4850         -      rc = 1;
  4851         -      goto meta_command_exit;
  4852         -    }
  4853         -    output_file_close(p->traceOut);
  4854         -    p->traceOut = output_file_open(azArg[1]);
  4855         -#if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT)
  4856         -    if( p->traceOut==0 ){
  4857         -      sqlite3_trace_v2(p->db, 0, 0, 0);
  4858         -    }else{
  4859         -      sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut);
  4860         -    }
  4861         -#endif
  4862         -  }else
  4863         -
  4864         -#if SQLITE_USER_AUTHENTICATION
  4865         -  if( c=='u' && strncmp(azArg[0], "user", n)==0 ){
  4866         -    if( nArg<2 ){
  4867         -      raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n");
  4868         -      rc = 1;
  4869         -      goto meta_command_exit;
  4870         -    }
  4871         -    open_db(p, 0);
  4872         -    if( strcmp(azArg[1],"login")==0 ){
  4873         -      if( nArg!=4 ){
  4874         -        raw_printf(stderr, "Usage: .user login USER PASSWORD\n");
  4875         -        rc = 1;
  4876         -        goto meta_command_exit;
  4877         -      }
  4878         -      rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3],
  4879         -                                    (int)strlen(azArg[3]));
  4880         -      if( rc ){
  4881         -        utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]);
  4882         -        rc = 1;
  4883         -      }
  4884         -    }else if( strcmp(azArg[1],"add")==0 ){
  4885         -      if( nArg!=5 ){
  4886         -        raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n");
  4887         -        rc = 1;
  4888         -        goto meta_command_exit;
  4889         -      }
  4890         -      rc = sqlite3_user_add(p->db, azArg[2],
  4891         -                            azArg[3], (int)strlen(azArg[3]),
  4892         -                            booleanValue(azArg[4]));
  4893         -      if( rc ){
  4894         -        raw_printf(stderr, "User-Add failed: %d\n", rc);
  4895         -        rc = 1;
  4896         -      }
  4897         -    }else if( strcmp(azArg[1],"edit")==0 ){
  4898         -      if( nArg!=5 ){
  4899         -        raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n");
  4900         -        rc = 1;
  4901         -        goto meta_command_exit;
  4902         -      }
  4903         -      rc = sqlite3_user_change(p->db, azArg[2],
  4904         -                              azArg[3], (int)strlen(azArg[3]),
  4905         -                              booleanValue(azArg[4]));
  4906         -      if( rc ){
  4907         -        raw_printf(stderr, "User-Edit failed: %d\n", rc);
  4908         -        rc = 1;
  4909         -      }
  4910         -    }else if( strcmp(azArg[1],"delete")==0 ){
  4911         -      if( nArg!=3 ){
  4912         -        raw_printf(stderr, "Usage: .user delete USER\n");
  4913         -        rc = 1;
  4914         -        goto meta_command_exit;
  4915         -      }
  4916         -      rc = sqlite3_user_delete(p->db, azArg[2]);
  4917         -      if( rc ){
  4918         -        raw_printf(stderr, "User-Delete failed: %d\n", rc);
  4919         -        rc = 1;
  4920         -      }
  4921         -    }else{
  4922         -      raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n");
  4923         -      rc = 1;
  4924         -      goto meta_command_exit;
  4925         -    }
  4926         -  }else
  4927         -#endif /* SQLITE_USER_AUTHENTICATION */
  4928         -
  4929         -  if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  4930         -    utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/,
  4931         -        sqlite3_libversion(), sqlite3_sourceid());
  4932         -  }else
  4933         -
  4934         -  if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){
  4935         -    const char *zDbName = nArg==2 ? azArg[1] : "main";
  4936         -    sqlite3_vfs *pVfs;
  4937         -    if( p->db ){
  4938         -      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs);
  4939         -      if( pVfs ){
  4940         -        utf8_printf(p->out, "vfs.zName      = \"%s\"\n", pVfs->zName);
  4941         -        raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
  4942         -        raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
  4943         -        raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  4944         -      }
  4945         -    }
  4946         -  }else
  4947         -
  4948         -  if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){
  4949         -    sqlite3_vfs *pVfs;
  4950         -    sqlite3_vfs *pCurrent = 0;
  4951         -    if( p->db ){
  4952         -      sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent);
  4953         -    }
  4954         -    for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){
  4955         -      utf8_printf(p->out, "vfs.zName      = \"%s\"%s\n", pVfs->zName,
  4956         -           pVfs==pCurrent ? "  <--- CURRENT" : "");
  4957         -      raw_printf(p->out, "vfs.iVersion   = %d\n", pVfs->iVersion);
  4958         -      raw_printf(p->out, "vfs.szOsFile   = %d\n", pVfs->szOsFile);
  4959         -      raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname);
  4960         -      if( pVfs->pNext ){
  4961         -        raw_printf(p->out, "-----------------------------------\n");
  4962         -      }
  4963         -    }
  4964         -  }else
  4965         -
  4966         -  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
  4967         -    const char *zDbName = nArg==2 ? azArg[1] : "main";
  4968         -    char *zVfsName = 0;
  4969         -    if( p->db ){
  4970         -      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
  4971         -      if( zVfsName ){
  4972         -        utf8_printf(p->out, "%s\n", zVfsName);
  4973         -        sqlite3_free(zVfsName);
  4974         -      }
  4975         -    }
  4976         -  }else
  4977         -
  4978         -#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
  4979         -  if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
  4980         -    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
  4981         -  }else
  4982         -#endif
  4983         -
  4984         -  if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
  4985         -    int j;
  4986         -    assert( nArg<=ArraySize(azArg) );
  4987         -    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  4988         -      p->colWidth[j-1] = (int)integerValue(azArg[j]);
  4989         -    }
  4990         -  }else
  4991         -
  4992         -  {
  4993         -    utf8_printf(stderr, "Error: unknown command or invalid arguments: "
  4994         -      " \"%s\". Enter \".help\" for help\n", azArg[0]);
  4995         -    rc = 1;
  4996         -  }
  4997         -
  4998         -meta_command_exit:
  4999         -  if( p->outCount ){
  5000         -    p->outCount--;
  5001         -    if( p->outCount==0 ) output_reset(p);
  5002         -  }
  5003         -  return rc;
  5004         -}
  5005         -
  5006         -/*
  5007         -** Return TRUE if a semicolon occurs anywhere in the first N characters
  5008         -** of string z[].
  5009         -*/
  5010         -static int line_contains_semicolon(const char *z, int N){
  5011         -  int i;
  5012         -  for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
  5013         -  return 0;
  5014         -}
  5015         -
  5016         -/*
  5017         -** Test to see if a line consists entirely of whitespace.
  5018         -*/
  5019         -static int _all_whitespace(const char *z){
  5020         -  for(; *z; z++){
  5021         -    if( IsSpace(z[0]) ) continue;
  5022         -    if( *z=='/' && z[1]=='*' ){
  5023         -      z += 2;
  5024         -      while( *z && (*z!='*' || z[1]!='/') ){ z++; }
  5025         -      if( *z==0 ) return 0;
  5026         -      z++;
  5027         -      continue;
  5028         -    }
  5029         -    if( *z=='-' && z[1]=='-' ){
  5030         -      z += 2;
  5031         -      while( *z && *z!='\n' ){ z++; }
  5032         -      if( *z==0 ) return 1;
  5033         -      continue;
  5034         -    }
  5035         -    return 0;
  5036         -  }
  5037         -  return 1;
  5038         -}
  5039         -
  5040         -/*
  5041         -** Return TRUE if the line typed in is an SQL command terminator other
  5042         -** than a semi-colon.  The SQL Server style "go" command is understood
  5043         -** as is the Oracle "/".
  5044         -*/
  5045         -static int line_is_command_terminator(const char *zLine){
  5046         -  while( IsSpace(zLine[0]) ){ zLine++; };
  5047         -  if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  5048         -    return 1;  /* Oracle */
  5049         -  }
  5050         -  if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  5051         -         && _all_whitespace(&zLine[2]) ){
  5052         -    return 1;  /* SQL Server */
  5053         -  }
  5054         -  return 0;
  5055         -}
  5056         -
  5057         -/*
  5058         -** Return true if zSql is a complete SQL statement.  Return false if it
  5059         -** ends in the middle of a string literal or C-style comment.
  5060         -*/
  5061         -static int line_is_complete(char *zSql, int nSql){
  5062         -  int rc;
  5063         -  if( zSql==0 ) return 1;
  5064         -  zSql[nSql] = ';';
  5065         -  zSql[nSql+1] = 0;
  5066         -  rc = sqlite3_complete(zSql);
  5067         -  zSql[nSql] = 0;
  5068         -  return rc;
  5069         -}
  5070         -
  5071         -/*
  5072         -** Read input from *in and process it.  If *in==0 then input
  5073         -** is interactive - the user is typing it it.  Otherwise, input
  5074         -** is coming from a file or device.  A prompt is issued and history
  5075         -** is saved only if input is interactive.  An interrupt signal will
  5076         -** cause this routine to exit immediately, unless input is interactive.
  5077         -**
  5078         -** Return the number of errors.
  5079         -*/
  5080         -static int process_input(ShellState *p, FILE *in){
  5081         -  char *zLine = 0;          /* A single input line */
  5082         -  char *zSql = 0;           /* Accumulated SQL text */
  5083         -  int nLine;                /* Length of current line */
  5084         -  int nSql = 0;             /* Bytes of zSql[] used */
  5085         -  int nAlloc = 0;           /* Allocated zSql[] space */
  5086         -  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
  5087         -  char *zErrMsg;            /* Error message returned */
  5088         -  int rc;                   /* Error code */
  5089         -  int errCnt = 0;           /* Number of errors seen */
  5090         -  int lineno = 0;           /* Current line number */
  5091         -  int startline = 0;        /* Line number for start of current input */
  5092         -
  5093         -  while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  5094         -    fflush(p->out);
  5095         -    zLine = one_input_line(in, zLine, nSql>0);
  5096         -    if( zLine==0 ){
  5097         -      /* End of input */
  5098         -      if( in==0 && stdin_is_interactive ) printf("\n");
  5099         -      break;
  5100         -    }
  5101         -    if( seenInterrupt ){
  5102         -      if( in!=0 ) break;
  5103         -      seenInterrupt = 0;
  5104         -    }
  5105         -    lineno++;
  5106         -    if( nSql==0 && _all_whitespace(zLine) ){
  5107         -      if( p->echoOn ) printf("%s\n", zLine);
  5108         -      continue;
  5109         -    }
  5110         -    if( zLine && zLine[0]=='.' && nSql==0 ){
  5111         -      if( p->echoOn ) printf("%s\n", zLine);
  5112         -      rc = do_meta_command(zLine, p);
  5113         -      if( rc==2 ){ /* exit requested */
  5114         -        break;
  5115         -      }else if( rc ){
  5116         -        errCnt++;
  5117         -      }
  5118         -      continue;
  5119         -    }
  5120         -    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  5121         -      memcpy(zLine,";",2);
  5122         -    }
  5123         -    nLine = strlen30(zLine);
  5124         -    if( nSql+nLine+2>=nAlloc ){
  5125         -      nAlloc = nSql+nLine+100;
  5126         -      zSql = realloc(zSql, nAlloc);
  5127         -      if( zSql==0 ){
  5128         -        raw_printf(stderr, "Error: out of memory\n");
  5129         -        exit(1);
  5130         -      }
  5131         -    }
  5132         -    nSqlPrior = nSql;
  5133         -    if( nSql==0 ){
  5134         -      int i;
  5135         -      for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  5136         -      assert( nAlloc>0 && zSql!=0 );
  5137         -      memcpy(zSql, zLine+i, nLine+1-i);
  5138         -      startline = lineno;
  5139         -      nSql = nLine-i;
  5140         -    }else{
  5141         -      zSql[nSql++] = '\n';
  5142         -      memcpy(zSql+nSql, zLine, nLine+1);
  5143         -      nSql += nLine;
  5144         -    }
  5145         -    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  5146         -                && sqlite3_complete(zSql) ){
  5147         -      p->cnt = 0;
  5148         -      open_db(p, 0);
  5149         -      if( p->backslashOn ) resolve_backslashes(zSql);
  5150         -      BEGIN_TIMER;
  5151         -      rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  5152         -      END_TIMER;
  5153         -      if( rc || zErrMsg ){
  5154         -        char zPrefix[100];
  5155         -        if( in!=0 || !stdin_is_interactive ){
  5156         -          sqlite3_snprintf(sizeof(zPrefix), zPrefix,
  5157         -                           "Error: near line %d:", startline);
  5158         -        }else{
  5159         -          sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:");
  5160         -        }
  5161         -        if( zErrMsg!=0 ){
  5162         -          utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg);
  5163         -          sqlite3_free(zErrMsg);
  5164         -          zErrMsg = 0;
  5165         -        }else{
  5166         -          utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  5167         -        }
  5168         -        errCnt++;
  5169         -      }else if( p->countChanges ){
  5170         -        raw_printf(p->out, "changes: %3d   total_changes: %d\n",
  5171         -                sqlite3_changes(p->db), sqlite3_total_changes(p->db));
  5172         -      }
  5173         -      nSql = 0;
  5174         -      if( p->outCount ){
  5175         -        output_reset(p);
  5176         -        p->outCount = 0;
  5177         -      }
  5178         -    }else if( nSql && _all_whitespace(zSql) ){
  5179         -      if( p->echoOn ) printf("%s\n", zSql);
  5180         -      nSql = 0;
  5181         -    }
  5182         -  }
  5183         -  if( nSql ){
  5184         -    if( !_all_whitespace(zSql) ){
  5185         -      utf8_printf(stderr, "Error: incomplete SQL: %s\n", zSql);
  5186         -      errCnt++;
  5187         -    }
  5188         -  }
  5189         -  free(zSql);
  5190         -  free(zLine);
  5191         -  return errCnt>0;
  5192         -}
  5193         -
  5194         -/*
  5195         -** Return a pathname which is the user's home directory.  A
  5196         -** 0 return indicates an error of some kind.
  5197         -*/
  5198         -static char *find_home_dir(int clearFlag){
  5199         -  static char *home_dir = NULL;
  5200         -  if( clearFlag ){
  5201         -    free(home_dir);
  5202         -    home_dir = 0;
  5203         -    return 0;
  5204         -  }
  5205         -  if( home_dir ) return home_dir;
  5206         -
  5207         -#if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \
  5208         -     && !defined(__RTP__) && !defined(_WRS_KERNEL)
  5209         -  {
  5210         -    struct passwd *pwent;
  5211         -    uid_t uid = getuid();
  5212         -    if( (pwent=getpwuid(uid)) != NULL) {
  5213         -      home_dir = pwent->pw_dir;
  5214         -    }
  5215         -  }
  5216         -#endif
  5217         -
  5218         -#if defined(_WIN32_WCE)
  5219         -  /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv()
  5220         -   */
  5221         -  home_dir = "/";
  5222         -#else
  5223         -
  5224         -#if defined(_WIN32) || defined(WIN32)
  5225         -  if (!home_dir) {
  5226         -    home_dir = getenv("USERPROFILE");
  5227         -  }
  5228         -#endif
  5229         -
  5230         -  if (!home_dir) {
  5231         -    home_dir = getenv("HOME");
  5232         -  }
  5233         -
  5234         -#if defined(_WIN32) || defined(WIN32)
  5235         -  if (!home_dir) {
  5236         -    char *zDrive, *zPath;
  5237         -    int n;
  5238         -    zDrive = getenv("HOMEDRIVE");
  5239         -    zPath = getenv("HOMEPATH");
  5240         -    if( zDrive && zPath ){
  5241         -      n = strlen30(zDrive) + strlen30(zPath) + 1;
  5242         -      home_dir = malloc( n );
  5243         -      if( home_dir==0 ) return 0;
  5244         -      sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath);
  5245         -      return home_dir;
  5246         -    }
  5247         -    home_dir = "c:\\";
  5248         -  }
  5249         -#endif
  5250         -
  5251         -#endif /* !_WIN32_WCE */
  5252         -
  5253         -  if( home_dir ){
  5254         -    int n = strlen30(home_dir) + 1;
  5255         -    char *z = malloc( n );
  5256         -    if( z ) memcpy(z, home_dir, n);
  5257         -    home_dir = z;
  5258         -  }
  5259         -
  5260         -  return home_dir;
  5261         -}
  5262         -
  5263         -/*
  5264         -** Read input from the file given by sqliterc_override.  Or if that
  5265         -** parameter is NULL, take input from ~/.sqliterc
  5266         -**
  5267         -** Returns the number of errors.
  5268         -*/
  5269         -static void process_sqliterc(
  5270         -  ShellState *p,                  /* Configuration data */
  5271         -  const char *sqliterc_override   /* Name of config file. NULL to use default */
  5272         -){
  5273         -  char *home_dir = NULL;
  5274         -  const char *sqliterc = sqliterc_override;
  5275         -  char *zBuf = 0;
  5276         -  FILE *in = NULL;
  5277         -
  5278         -  if (sqliterc == NULL) {
  5279         -    home_dir = find_home_dir(0);
  5280         -    if( home_dir==0 ){
  5281         -      raw_printf(stderr, "-- warning: cannot find home directory;"
  5282         -                      " cannot read ~/.sqliterc\n");
  5283         -      return;
  5284         -    }
  5285         -    sqlite3_initialize();
  5286         -    zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir);
  5287         -    sqliterc = zBuf;
  5288         -  }
  5289         -  in = fopen(sqliterc,"rb");
  5290         -  if( in ){
  5291         -    if( stdin_is_interactive ){
  5292         -      utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
  5293         -    }
  5294         -    process_input(p,in);
  5295         -    fclose(in);
  5296         -  }
  5297         -  sqlite3_free(zBuf);
  5298         -}
  5299         -
  5300         -/*
  5301         -** Show available command line options
  5302         -*/
  5303         -static const char zOptions[] =
  5304         -  "   -ascii               set output mode to 'ascii'\n"
  5305         -  "   -bail                stop after hitting an error\n"
  5306         -  "   -batch               force batch I/O\n"
  5307         -  "   -column              set output mode to 'column'\n"
  5308         -  "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
  5309         -  "   -csv                 set output mode to 'csv'\n"
  5310         -  "   -echo                print commands before execution\n"
  5311         -  "   -init FILENAME       read/process named file\n"
  5312         -  "   -[no]header          turn headers on or off\n"
  5313         -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  5314         -  "   -heap SIZE           Size of heap for memsys3 or memsys5\n"
  5315         -#endif
  5316         -  "   -help                show this message\n"
  5317         -  "   -html                set output mode to HTML\n"
  5318         -  "   -interactive         force interactive I/O\n"
  5319         -  "   -line                set output mode to 'line'\n"
  5320         -  "   -list                set output mode to 'list'\n"
  5321         -  "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
  5322         -  "   -mmap N              default mmap size set to N\n"
  5323         -#ifdef SQLITE_ENABLE_MULTIPLEX
  5324         -  "   -multiplex           enable the multiplexor VFS\n"
  5325         -#endif
  5326         -  "   -newline SEP         set output row separator. Default: '\\n'\n"
  5327         -  "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
  5328         -  "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
  5329         -  "   -scanstats           print scan stats before each finalize\n"
  5330         -  "   -scratch SIZE N      use N slots of SZ bytes each for scratch memory\n"
  5331         -  "   -separator SEP       set output column separator. Default: '|'\n"
  5332         -  "   -stats               print memory stats before each finalize\n"
  5333         -  "   -version             show SQLite version\n"
  5334         -  "   -vfs NAME            use NAME as the default VFS\n"
  5335         -#ifdef SQLITE_ENABLE_VFSTRACE
  5336         -  "   -vfstrace            enable tracing of all VFS calls\n"
  5337         -#endif
  5338         -;
  5339         -static void usage(int showDetail){
  5340         -  utf8_printf(stderr,
  5341         -      "Usage: %s [OPTIONS] FILENAME [SQL]\n"
  5342         -      "FILENAME is the name of an SQLite database. A new database is created\n"
  5343         -      "if the file does not previously exist.\n", Argv0);
  5344         -  if( showDetail ){
  5345         -    utf8_printf(stderr, "OPTIONS include:\n%s", zOptions);
  5346         -  }else{
  5347         -    raw_printf(stderr, "Use the -help option for additional information\n");
  5348         -  }
  5349         -  exit(1);
  5350         -}
  5351         -
  5352         -/*
  5353         -** Initialize the state information in data
  5354         -*/
  5355         -static void main_init(ShellState *data) {
  5356         -  memset(data, 0, sizeof(*data));
  5357         -  data->normalMode = data->cMode = data->mode = MODE_List;
  5358         -  data->autoExplain = 1;
  5359         -  memcpy(data->colSeparator,SEP_Column, 2);
  5360         -  memcpy(data->rowSeparator,SEP_Row, 2);
  5361         -  data->showHeader = 0;
  5362         -  data->shellFlgs = SHFLG_Lookaside;
  5363         -  sqlite3_config(SQLITE_CONFIG_URI, 1);
  5364         -  sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data);
  5365         -  sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  5366         -  sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> ");
  5367         -  sqlite3_snprintf(sizeof(continuePrompt), continuePrompt,"   ...> ");
  5368         -}
  5369         -
  5370         -/*
  5371         -** Output text to the console in a font that attracts extra attention.
  5372         -*/
  5373         -#ifdef _WIN32
  5374         -static void printBold(const char *zText){
  5375         -  HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
  5376         -  CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
  5377         -  GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
  5378         -  SetConsoleTextAttribute(out,
  5379         -         FOREGROUND_RED|FOREGROUND_INTENSITY
  5380         -  );
  5381         -  printf("%s", zText);
  5382         -  SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
  5383         -}
  5384         -#else
  5385         -static void printBold(const char *zText){
  5386         -  printf("\033[1m%s\033[0m", zText);
  5387         -}
  5388         -#endif
  5389         -
  5390         -/*
  5391         -** Get the argument to an --option.  Throw an error and die if no argument
  5392         -** is available.
  5393         -*/
  5394         -static char *cmdline_option_value(int argc, char **argv, int i){
  5395         -  if( i==argc ){
  5396         -    utf8_printf(stderr, "%s: Error: missing argument to %s\n",
  5397         -            argv[0], argv[argc-1]);
  5398         -    exit(1);
  5399         -  }
  5400         -  return argv[i];
  5401         -}
  5402         -
  5403         -#if defined(_WIN32) && defined(__MSVCRT__) && !defined(main)
  5404         -int _CRT_glob = 0x0001; /* See MinGW bug #2062 */
  5405         -#endif
  5406         -
  5407         -#ifndef SQLITE_SHELL_IS_UTF8
  5408         -#  if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
  5409         -#    define SQLITE_SHELL_IS_UTF8          (0)
  5410         -#  else
  5411         -#    define SQLITE_SHELL_IS_UTF8          (1)
  5412         -#  endif
  5413         -#endif
  5414         -
  5415         -#if SQLITE_SHELL_IS_UTF8
  5416         -int SQLITE_CDECL main(int argc, char **argv){
  5417         -#else
  5418         -int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
  5419         -  char **argv;
  5420         -#endif
  5421         -  char *zErrMsg = 0;
  5422         -  ShellState data;
  5423         -  const char *zInitFile = 0;
  5424         -  int i;
  5425         -  int rc = 0;
  5426         -  int warnInmemoryDb = 0;
  5427         -  int readStdin = 1;
  5428         -  int nCmd = 0;
  5429         -  char **azCmd = 0;
  5430         -
  5431         -  setBinaryMode(stdin, 0);
  5432         -  setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */
  5433         -  stdin_is_interactive = isatty(0);
  5434         -  stdout_is_console = isatty(1);
  5435         -
  5436         -#if USE_SYSTEM_SQLITE+0!=1
  5437         -  if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  5438         -    utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  5439         -            sqlite3_sourceid(), SQLITE_SOURCE_ID);
  5440         -    exit(1);
  5441         -  }
  5442         -#endif
  5443         -  main_init(&data);
  5444         -#if !SQLITE_SHELL_IS_UTF8
  5445         -  sqlite3_initialize();
  5446         -  argv = sqlite3_malloc(sizeof(argv[0])*argc);
  5447         -  if( argv==0 ){
  5448         -    raw_printf(stderr, "out of memory\n");
  5449         -    exit(1);
  5450         -  }
  5451         -  for(i=0; i<argc; i++){
  5452         -    argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]);
  5453         -    if( argv[i]==0 ){
  5454         -      raw_printf(stderr, "out of memory\n");
  5455         -      exit(1);
  5456         -    }
  5457         -  }
  5458         -#endif
  5459         -  assert( argc>=1 && argv && argv[0] );
  5460         -  Argv0 = argv[0];
  5461         -
  5462         -  /* Make sure we have a valid signal handler early, before anything
  5463         -  ** else is done.
  5464         -  */
  5465         -#ifdef SIGINT
  5466         -  signal(SIGINT, interrupt_handler);
  5467         -#elif defined(WIN32) || defined(_WIN32)
  5468         -  SetConsoleCtrlHandler(CtrlHandler, TRUE);
  5469         -#endif
  5470         -
  5471         -#ifdef SQLITE_SHELL_DBNAME_PROC
  5472         -  {
  5473         -    /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name
  5474         -    ** of a C-function that will provide the name of the database file.  Use
  5475         -    ** this compile-time option to embed this shell program in larger
  5476         -    ** applications. */
  5477         -    extern void SQLITE_SHELL_DBNAME_PROC(const char**);
  5478         -    SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
  5479         -    warnInmemoryDb = 0;
  5480         -  }
  5481         -#endif
  5482         -
  5483         -  /* Do an initial pass through the command-line argument to locate
  5484         -  ** the name of the database file, the name of the initialization file,
  5485         -  ** the size of the alternative malloc heap,
  5486         -  ** and the first command to execute.
  5487         -  */
  5488         -  for(i=1; i<argc; i++){
  5489         -    char *z;
  5490         -    z = argv[i];
  5491         -    if( z[0]!='-' ){
  5492         -      if( data.zDbFilename==0 ){
  5493         -        data.zDbFilename = z;
  5494         -      }else{
  5495         -        /* Excesss arguments are interpreted as SQL (or dot-commands) and
  5496         -        ** mean that nothing is read from stdin */
  5497         -        readStdin = 0;
  5498         -        nCmd++;
  5499         -        azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd);
  5500         -        if( azCmd==0 ){
  5501         -          raw_printf(stderr, "out of memory\n");
  5502         -          exit(1);
  5503         -        }
  5504         -        azCmd[nCmd-1] = z;
  5505         -      }
  5506         -    }
  5507         -    if( z[1]=='-' ) z++;
  5508         -    if( strcmp(z,"-separator")==0
  5509         -     || strcmp(z,"-nullvalue")==0
  5510         -     || strcmp(z,"-newline")==0
  5511         -     || strcmp(z,"-cmd")==0
  5512         -    ){
  5513         -      (void)cmdline_option_value(argc, argv, ++i);
  5514         -    }else if( strcmp(z,"-init")==0 ){
  5515         -      zInitFile = cmdline_option_value(argc, argv, ++i);
  5516         -    }else if( strcmp(z,"-batch")==0 ){
  5517         -      /* Need to check for batch mode here to so we can avoid printing
  5518         -      ** informational messages (like from process_sqliterc) before
  5519         -      ** we do the actual processing of arguments later in a second pass.
  5520         -      */
  5521         -      stdin_is_interactive = 0;
  5522         -    }else if( strcmp(z,"-heap")==0 ){
  5523         -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  5524         -      const char *zSize;
  5525         -      sqlite3_int64 szHeap;
  5526         -
  5527         -      zSize = cmdline_option_value(argc, argv, ++i);
  5528         -      szHeap = integerValue(zSize);
  5529         -      if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000;
  5530         -      sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64);
  5531         -#else
  5532         -      (void)cmdline_option_value(argc, argv, ++i);
  5533         -#endif
  5534         -    }else if( strcmp(z,"-scratch")==0 ){
  5535         -      int n, sz;
  5536         -      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5537         -      if( sz>400000 ) sz = 400000;
  5538         -      if( sz<2500 ) sz = 2500;
  5539         -      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5540         -      if( n>10 ) n = 10;
  5541         -      if( n<1 ) n = 1;
  5542         -      sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n);
  5543         -      data.shellFlgs |= SHFLG_Scratch;
  5544         -    }else if( strcmp(z,"-pagecache")==0 ){
  5545         -      int n, sz;
  5546         -      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5547         -      if( sz>70000 ) sz = 70000;
  5548         -      if( sz<0 ) sz = 0;
  5549         -      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5550         -      sqlite3_config(SQLITE_CONFIG_PAGECACHE,
  5551         -                    (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
  5552         -      data.shellFlgs |= SHFLG_Pagecache;
  5553         -    }else if( strcmp(z,"-lookaside")==0 ){
  5554         -      int n, sz;
  5555         -      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5556         -      if( sz<0 ) sz = 0;
  5557         -      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
  5558         -      if( n<0 ) n = 0;
  5559         -      sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n);
  5560         -      if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside;
  5561         -#ifdef SQLITE_ENABLE_VFSTRACE
  5562         -    }else if( strcmp(z,"-vfstrace")==0 ){
  5563         -      extern int vfstrace_register(
  5564         -         const char *zTraceName,
  5565         -         const char *zOldVfsName,
  5566         -         int (*xOut)(const char*,void*),
  5567         -         void *pOutArg,
  5568         -         int makeDefault
  5569         -      );
  5570         -      vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1);
  5571         -#endif
  5572         -#ifdef SQLITE_ENABLE_MULTIPLEX
  5573         -    }else if( strcmp(z,"-multiplex")==0 ){
  5574         -      extern int sqlite3_multiple_initialize(const char*,int);
  5575         -      sqlite3_multiplex_initialize(0, 1);
  5576         -#endif
  5577         -    }else if( strcmp(z,"-mmap")==0 ){
  5578         -      sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i));
  5579         -      sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz);
  5580         -    }else if( strcmp(z,"-vfs")==0 ){
  5581         -      sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i));
  5582         -      if( pVfs ){
  5583         -        sqlite3_vfs_register(pVfs, 1);
  5584         -      }else{
  5585         -        utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]);
  5586         -        exit(1);
  5587         -      }
  5588         -    }
  5589         -  }
  5590         -  if( data.zDbFilename==0 ){
  5591         -#ifndef SQLITE_OMIT_MEMORYDB
  5592         -    data.zDbFilename = ":memory:";
  5593         -    warnInmemoryDb = argc==1;
  5594         -#else
  5595         -    utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0);
  5596         -    return 1;
  5597         -#endif
  5598         -  }
  5599         -  data.out = stdout;
  5600         -
  5601         -  /* Go ahead and open the database file if it already exists.  If the
  5602         -  ** file does not exist, delay opening it.  This prevents empty database
  5603         -  ** files from being created if a user mistypes the database name argument
  5604         -  ** to the sqlite command-line tool.
  5605         -  */
  5606         -  if( access(data.zDbFilename, 0)==0 ){
  5607         -    open_db(&data, 0);
  5608         -  }
  5609         -
  5610         -  /* Process the initialization file if there is one.  If no -init option
  5611         -  ** is given on the command line, look for a file named ~/.sqliterc and
  5612         -  ** try to process it.
  5613         -  */
  5614         -  process_sqliterc(&data,zInitFile);
  5615         -
  5616         -  /* Make a second pass through the command-line argument and set
  5617         -  ** options.  This second pass is delayed until after the initialization
  5618         -  ** file is processed so that the command-line arguments will override
  5619         -  ** settings in the initialization file.
  5620         -  */
  5621         -  for(i=1; i<argc; i++){
  5622         -    char *z = argv[i];
  5623         -    if( z[0]!='-' ) continue;
  5624         -    if( z[1]=='-' ){ z++; }
  5625         -    if( strcmp(z,"-init")==0 ){
  5626         -      i++;
  5627         -    }else if( strcmp(z,"-html")==0 ){
  5628         -      data.mode = MODE_Html;
  5629         -    }else if( strcmp(z,"-list")==0 ){
  5630         -      data.mode = MODE_List;
  5631         -    }else if( strcmp(z,"-line")==0 ){
  5632         -      data.mode = MODE_Line;
  5633         -    }else if( strcmp(z,"-column")==0 ){
  5634         -      data.mode = MODE_Column;
  5635         -    }else if( strcmp(z,"-csv")==0 ){
  5636         -      data.mode = MODE_Csv;
  5637         -      memcpy(data.colSeparator,",",2);
  5638         -    }else if( strcmp(z,"-ascii")==0 ){
  5639         -      data.mode = MODE_Ascii;
  5640         -      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  5641         -                       SEP_Unit);
  5642         -      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  5643         -                       SEP_Record);
  5644         -    }else if( strcmp(z,"-separator")==0 ){
  5645         -      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
  5646         -                       "%s",cmdline_option_value(argc,argv,++i));
  5647         -    }else if( strcmp(z,"-newline")==0 ){
  5648         -      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
  5649         -                       "%s",cmdline_option_value(argc,argv,++i));
  5650         -    }else if( strcmp(z,"-nullvalue")==0 ){
  5651         -      sqlite3_snprintf(sizeof(data.nullValue), data.nullValue,
  5652         -                       "%s",cmdline_option_value(argc,argv,++i));
  5653         -    }else if( strcmp(z,"-header")==0 ){
  5654         -      data.showHeader = 1;
  5655         -    }else if( strcmp(z,"-noheader")==0 ){
  5656         -      data.showHeader = 0;
  5657         -    }else if( strcmp(z,"-echo")==0 ){
  5658         -      data.echoOn = 1;
  5659         -    }else if( strcmp(z,"-eqp")==0 ){
  5660         -      data.autoEQP = 1;
  5661         -    }else if( strcmp(z,"-eqpfull")==0 ){
  5662         -      data.autoEQP = 2;
  5663         -    }else if( strcmp(z,"-stats")==0 ){
  5664         -      data.statsOn = 1;
  5665         -    }else if( strcmp(z,"-scanstats")==0 ){
  5666         -      data.scanstatsOn = 1;
  5667         -    }else if( strcmp(z,"-backslash")==0 ){
  5668         -      /* Undocumented command-line option: -backslash
  5669         -      ** Causes C-style backslash escapes to be evaluated in SQL statements
  5670         -      ** prior to sending the SQL into SQLite.  Useful for injecting
  5671         -      ** crazy bytes in the middle of SQL statements for testing and debugging.
  5672         -      */
  5673         -      data.backslashOn = 1;
  5674         -    }else if( strcmp(z,"-bail")==0 ){
  5675         -      bail_on_error = 1;
  5676         -    }else if( strcmp(z,"-version")==0 ){
  5677         -      printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  5678         -      return 0;
  5679         -    }else if( strcmp(z,"-interactive")==0 ){
  5680         -      stdin_is_interactive = 1;
  5681         -    }else if( strcmp(z,"-batch")==0 ){
  5682         -      stdin_is_interactive = 0;
  5683         -    }else if( strcmp(z,"-heap")==0 ){
  5684         -      i++;
  5685         -    }else if( strcmp(z,"-scratch")==0 ){
  5686         -      i+=2;
  5687         -    }else if( strcmp(z,"-pagecache")==0 ){
  5688         -      i+=2;
  5689         -    }else if( strcmp(z,"-lookaside")==0 ){
  5690         -      i+=2;
  5691         -    }else if( strcmp(z,"-mmap")==0 ){
  5692         -      i++;
  5693         -    }else if( strcmp(z,"-vfs")==0 ){
  5694         -      i++;
  5695         -#ifdef SQLITE_ENABLE_VFSTRACE
  5696         -    }else if( strcmp(z,"-vfstrace")==0 ){
  5697         -      i++;
  5698         -#endif
  5699         -#ifdef SQLITE_ENABLE_MULTIPLEX
  5700         -    }else if( strcmp(z,"-multiplex")==0 ){
  5701         -      i++;
  5702         -#endif
  5703         -    }else if( strcmp(z,"-help")==0 ){
  5704         -      usage(1);
  5705         -    }else if( strcmp(z,"-cmd")==0 ){
  5706         -      /* Run commands that follow -cmd first and separately from commands
  5707         -      ** that simply appear on the command-line.  This seems goofy.  It would
  5708         -      ** be better if all commands ran in the order that they appear.  But
  5709         -      ** we retain the goofy behavior for historical compatibility. */
  5710         -      if( i==argc-1 ) break;
  5711         -      z = cmdline_option_value(argc,argv,++i);
  5712         -      if( z[0]=='.' ){
  5713         -        rc = do_meta_command(z, &data);
  5714         -        if( rc && bail_on_error ) return rc==2 ? 0 : rc;
  5715         -      }else{
  5716         -        open_db(&data, 0);
  5717         -        rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg);
  5718         -        if( zErrMsg!=0 ){
  5719         -          utf8_printf(stderr,"Error: %s\n", zErrMsg);
  5720         -          if( bail_on_error ) return rc!=0 ? rc : 1;
  5721         -        }else if( rc!=0 ){
  5722         -          utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z);
  5723         -          if( bail_on_error ) return rc;
  5724         -        }
  5725         -      }
  5726         -    }else{
  5727         -      utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z);
  5728         -      raw_printf(stderr,"Use -help for a list of options.\n");
  5729         -      return 1;
  5730         -    }
  5731         -    data.cMode = data.mode;
  5732         -  }
  5733         -
  5734         -  if( !readStdin ){
  5735         -    /* Run all arguments that do not begin with '-' as if they were separate
  5736         -    ** command-line inputs, except for the argToSkip argument which contains
  5737         -    ** the database filename.
  5738         -    */
  5739         -    for(i=0; i<nCmd; i++){
  5740         -      if( azCmd[i][0]=='.' ){
  5741         -        rc = do_meta_command(azCmd[i], &data);
  5742         -        if( rc ) return rc==2 ? 0 : rc;
  5743         -      }else{
  5744         -        open_db(&data, 0);
  5745         -        rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg);
  5746         -        if( zErrMsg!=0 ){
  5747         -          utf8_printf(stderr,"Error: %s\n", zErrMsg);
  5748         -          return rc!=0 ? rc : 1;
  5749         -        }else if( rc!=0 ){
  5750         -          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
  5751         -          return rc;
  5752         -        }
  5753         -      }
  5754         -    }
  5755         -    free(azCmd);
  5756         -  }else{
  5757         -    /* Run commands received from standard input
  5758         -    */
  5759         -    if( stdin_is_interactive ){
  5760         -      char *zHome;
  5761         -      char *zHistory = 0;
  5762         -      int nHistory;
  5763         -      printf(
  5764         -        "SQLite version %s %.19s\n" /*extra-version-info*/
  5765         -        "Enter \".help\" for usage hints.\n",
  5766         -        sqlite3_libversion(), sqlite3_sourceid()
  5767         -      );
  5768         -      if( warnInmemoryDb ){
  5769         -        printf("Connected to a ");
  5770         -        printBold("transient in-memory database");
  5771         -        printf(".\nUse \".open FILENAME\" to reopen on a "
  5772         -               "persistent database.\n");
  5773         -      }
  5774         -      zHome = find_home_dir(0);
  5775         -      if( zHome ){
  5776         -        nHistory = strlen30(zHome) + 20;
  5777         -        if( (zHistory = malloc(nHistory))!=0 ){
  5778         -          sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome);
  5779         -        }
  5780         -      }
  5781         -      if( zHistory ){ shell_read_history(zHistory); }
  5782         -      rc = process_input(&data, 0);
  5783         -      if( zHistory ){
  5784         -        shell_stifle_history(100);
  5785         -        shell_write_history(zHistory);
  5786         -        free(zHistory);
  5787         -      }
  5788         -    }else{
  5789         -      rc = process_input(&data, stdin);
  5790         -    }
  5791         -  }
  5792         -  set_table_name(&data, 0);
  5793         -  if( data.db ){
  5794         -    session_close_all(&data);
  5795         -    sqlite3_close(data.db);
  5796         -  }
  5797         -  sqlite3_free(data.zFreeOnClose);
  5798         -  find_home_dir(1);
  5799         -#if !SQLITE_SHELL_IS_UTF8
  5800         -  for(i=0; i<argc; i++) sqlite3_free(argv[i]);
  5801         -  sqlite3_free(argv);
  5802         -#endif
  5803         -  return rc;
  5804         -}

Deleted jni/tcl/pkgs/sqlite3.15.1/compat/sqlite3/spaceanal.tcl.

     1         -#! /bin/sh
     2         -# restart with tclsh \
     3         -exec tclsh "$0" ${1+"$@"}
     4         -package require sqlite3
     5         -
     6         -# Run this TCL script using "testfixture" in order get a report that shows
     7         -# how much disk space is used by a particular data to actually store data
     8         -# versus how much space is unused.
     9         -#
    10         -
    11         -if {[catch {
    12         -
    13         -# Argument $tname is the name of a table within the database opened by
    14         -# database handle [db]. Return true if it is a WITHOUT ROWID table, or
    15         -# false otherwise.
    16         -#
    17         -proc is_without_rowid {tname} {
    18         -  set t [string map {' ''} $tname]
    19         -  db eval "PRAGMA index_list = '$t'" o {
    20         -    if {$o(origin) == "pk"} {
    21         -      set n $o(name)
    22         -      if {0==[db one { SELECT count(*) FROM sqlite_master WHERE name=$n }]} {
    23         -        return 1
    24         -      }
    25         -    }
    26         -  }
    27         -  return 0
    28         -}
    29         -
    30         -# Read and run TCL commands from standard input.  Used to implement
    31         -# the --tclsh option.
    32         -#
    33         -proc tclsh {} {
    34         -  set line {}
    35         -  while {![eof stdin]} {
    36         -    if {$line!=""} {
    37         -      puts -nonewline "> "
    38         -    } else {
    39         -      puts -nonewline "% "
    40         -    }
    41         -    flush stdout
    42         -    append line [gets stdin]
    43         -    if {[info complete $line]} {
    44         -      if {[catch {uplevel #0 $line} result]} {
    45         -        puts stderr "Error: $result"
    46         -      } elseif {$result!=""} {
    47         -        puts $result
    48         -      }
    49         -      set line {}
    50         -    } else {
    51         -      append line \n
    52         -    }
    53         -  }
    54         -}
    55         -
    56         -
    57         -# Get the name of the database to analyze
    58         -#
    59         -proc usage {} {
    60         -  set argv0 [file rootname [file tail [info script]]]
    61         -  puts stderr "Usage: $argv0 ?--pageinfo? ?--stats? database-filename"
    62         -  puts stderr {
    63         -Analyze the SQLite3 database file specified by the "database-filename"
    64         -argument and output a report detailing size and storage efficiency
    65         -information for the database and its constituent tables and indexes.
    66         -
    67         -Options:
    68         -
    69         -   --pageinfo   Show how each page of the database-file is used
    70         -
    71         -   --stats      Output SQL text that creates a new database containing
    72         -                statistics about the database that was analyzed
    73         -
    74         -   --tclsh      Run the built-in TCL interpreter interactively (for debugging)
    75         -
    76         -   --version    Show the version number of SQLite
    77         -}
    78         -  exit 1
    79         -}
    80         -set file_to_analyze {}
    81         -set flags(-pageinfo) 0
    82         -set flags(-stats) 0
    83         -set flags(-debug) 0
    84         -append argv {}
    85         -foreach arg $argv {
    86         -  if {[regexp {^-+pageinfo$} $arg]} {
    87         -    set flags(-pageinfo) 1
    88         -  } elseif {[regexp {^-+stats$} $arg]} {
    89         -    set flags(-stats) 1
    90         -  } elseif {[regexp {^-+debug$} $arg]} {
    91         -    set flags(-debug) 1
    92         -  } elseif {[regexp {^-+tclsh$} $arg]} {
    93         -    tclsh
    94         -    exit 0
    95         -  } elseif {[regexp {^-+version$} $arg]} {
    96         -    sqlite3 mem :memory:
    97         -    puts [mem one {SELECT sqlite_version()||' '||sqlite_source_id()}]
    98         -    mem close
    99         -    exit 0
   100         -  } elseif {[regexp {^-} $arg]} {
   101         -    puts stderr "Unknown option: $arg"
   102         -    usage
   103         -  } elseif {$file_to_analyze!=""} {
   104         -    usage
   105         -  } else {
   106         -    set file_to_analyze $arg
   107         -  }
   108         -}
   109         -if {$file_to_analyze==""} usage
   110         -set root_filename $file_to_analyze
   111         -regexp {^file:(//)?([^?]*)} $file_to_analyze all x1 root_filename
   112         -if {![file exists $root_filename]} {
   113         -  puts stderr "No such file: $root_filename"
   114         -  exit 1
   115         -}
   116         -if {![file readable $root_filename]} {
   117         -  puts stderr "File is not readable: $root_filename"
   118         -  exit 1
   119         -}
   120         -set true_file_size [file size $root_filename]
   121         -if {$true_file_size<512} {
   122         -  puts stderr "Empty or malformed database: $root_filename"
   123         -  exit 1
   124         -}
   125         -
   126         -# Compute the total file size assuming test_multiplexor is being used.
   127         -# Assume that SQLITE_ENABLE_8_3_NAMES might be enabled
   128         -#
   129         -set extension [file extension $root_filename]
   130         -set pattern $root_filename
   131         -append pattern {[0-3][0-9][0-9]}
   132         -foreach f [glob -nocomplain $pattern] {
   133         -  incr true_file_size [file size $f]
   134         -  set extension {}
   135         -}
   136         -if {[string length $extension]>=2 && [string length $extension]<=4} {
   137         -  set pattern [file rootname $root_filename]
   138         -  append pattern {.[0-3][0-9][0-9]}
   139         -  foreach f [glob -nocomplain $pattern] {
   140         -    incr true_file_size [file size $f]
   141         -  }
   142         -}
   143         -
   144         -# Open the database
   145         -#
   146         -if {[catch {sqlite3 db $file_to_analyze -uri 1} msg]} {
   147         -  puts stderr "error trying to open $file_to_analyze: $msg"
   148         -  exit 1
   149         -}
   150         -if {$flags(-debug)} {
   151         -  proc dbtrace {txt} {puts $txt; flush stdout;}
   152         -  db trace ::dbtrace
   153         -}
   154         -
   155         -db eval {SELECT count(*) FROM sqlite_master}
   156         -set pageSize [expr {wide([db one {PRAGMA page_size}])}]
   157         -
   158         -if {$flags(-pageinfo)} {
   159         -  db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
   160         -  db eval {SELECT name, path, pageno FROM temp.stat ORDER BY pageno} {
   161         -    puts "$pageno $name $path"
   162         -  }
   163         -  exit 0
   164         -}
   165         -if {$flags(-stats)} {
   166         -  db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
   167         -  puts "BEGIN;"
   168         -  puts "CREATE TABLE stats("
   169         -  puts "  name       STRING,           /* Name of table or index */"
   170         -  puts "  path       INTEGER,          /* Path to page from root */"
   171         -  puts "  pageno     INTEGER,          /* Page number */"
   172         -  puts "  pagetype   STRING,           /* 'internal', 'leaf' or 'overflow' */"
   173         -  puts "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"
   174         -  puts "  payload    INTEGER,          /* Bytes of payload on this page */"
   175         -  puts "  unused     INTEGER,          /* Bytes of unused space on this page */"
   176         -  puts "  mx_payload INTEGER,          /* Largest payload size of all cells */"
   177         -  puts "  pgoffset   INTEGER,          /* Offset of page in file */"
   178         -  puts "  pgsize     INTEGER           /* Size of the page */"
   179         -  puts ");"
   180         -  db eval {SELECT quote(name) || ',' ||
   181         -                  quote(path) || ',' ||
   182         -                  quote(pageno) || ',' ||
   183         -                  quote(pagetype) || ',' ||
   184         -                  quote(ncell) || ',' ||
   185         -                  quote(payload) || ',' ||
   186         -                  quote(unused) || ',' ||
   187         -                  quote(mx_payload) || ',' ||
   188         -                  quote(pgoffset) || ',' ||
   189         -                  quote(pgsize) AS x FROM stat} {
   190         -    puts "INSERT INTO stats VALUES($x);"
   191         -  }
   192         -  puts "COMMIT;"
   193         -  exit 0
   194         -}
   195         -
   196         -
   197         -# In-memory database for collecting statistics. This script loops through
   198         -# the tables and indices in the database being analyzed, adding a row for each
   199         -# to an in-memory database (for which the schema is shown below). It then
   200         -# queries the in-memory db to produce the space-analysis report.
   201         -#
   202         -sqlite3 mem :memory:
   203         -if {$flags(-debug)} {
   204         -  proc dbtrace {txt} {puts $txt; flush stdout;}
   205         -  mem trace ::dbtrace
   206         -}
   207         -set tabledef {CREATE TABLE space_used(
   208         -   name clob,        -- Name of a table or index in the database file
   209         -   tblname clob,     -- Name of associated table
   210         -   is_index boolean, -- TRUE if it is an index, false for a table
   211         -   is_without_rowid boolean, -- TRUE if WITHOUT ROWID table  
   212         -   nentry int,       -- Number of entries in the BTree
   213         -   leaf_entries int, -- Number of leaf entries
   214         -   depth int,        -- Depth of the b-tree
   215         -   payload int,      -- Total amount of data stored in this table or index
   216         -   ovfl_payload int, -- Total amount of data stored on overflow pages
   217         -   ovfl_cnt int,     -- Number of entries that use overflow
   218         -   mx_payload int,   -- Maximum payload size
   219         -   int_pages int,    -- Number of interior pages used
   220         -   leaf_pages int,   -- Number of leaf pages used
   221         -   ovfl_pages int,   -- Number of overflow pages used
   222         -   int_unused int,   -- Number of unused bytes on interior pages
   223         -   leaf_unused int,  -- Number of unused bytes on primary pages
   224         -   ovfl_unused int,  -- Number of unused bytes on overflow pages
   225         -   gap_cnt int,      -- Number of gaps in the page layout
   226         -   compressed_size int  -- Total bytes stored on disk
   227         -);}
   228         -mem eval $tabledef
   229         -
   230         -# Create a temporary "dbstat" virtual table.
   231         -#
   232         -db eval {CREATE VIRTUAL TABLE temp.stat USING dbstat}
   233         -db eval {CREATE TEMP TABLE dbstat AS SELECT * FROM temp.stat
   234         -         ORDER BY name, path}
   235         -db eval {DROP TABLE temp.stat}
   236         -
   237         -set isCompressed 0
   238         -set compressOverhead 0
   239         -set depth 0
   240         -set sql { SELECT name, tbl_name FROM sqlite_master WHERE rootpage>0 }
   241         -foreach {name tblname} [concat sqlite_master sqlite_master [db eval $sql]] {
   242         -
   243         -  set is_index [expr {$name!=$tblname}]
   244         -  set is_without_rowid [is_without_rowid $name]
   245         -  db eval {
   246         -    SELECT 
   247         -      sum(ncell) AS nentry,
   248         -      sum((pagetype=='leaf')*ncell) AS leaf_entries,
   249         -      sum(payload) AS payload,
   250         -      sum((pagetype=='overflow') * payload) AS ovfl_payload,
   251         -      sum(path LIKE '%+000000') AS ovfl_cnt,
   252         -      max(mx_payload) AS mx_payload,
   253         -      sum(pagetype=='internal') AS int_pages,
   254         -      sum(pagetype=='leaf') AS leaf_pages,
   255         -      sum(pagetype=='overflow') AS ovfl_pages,
   256         -      sum((pagetype=='internal') * unused) AS int_unused,
   257         -      sum((pagetype=='leaf') * unused) AS leaf_unused,
   258         -      sum((pagetype=='overflow') * unused) AS ovfl_unused,
   259         -      sum(pgsize) AS compressed_size,
   260         -      max((length(CASE WHEN path LIKE '%+%' THEN '' ELSE path END)+3)/4)
   261         -        AS depth
   262         -    FROM temp.dbstat WHERE name = $name
   263         -  } break
   264         -
   265         -  set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
   266         -  set storage [expr {$total_pages*$pageSize}]
   267         -  if {!$isCompressed && $storage>$compressed_size} {
   268         -    set isCompressed 1
   269         -    set compressOverhead 14
   270         -  }
   271         -
   272         -  # Column 'gap_cnt' is set to the number of non-contiguous entries in the
   273         -  # list of pages visited if the b-tree structure is traversed in a top-down
   274         -  # fashion (each node visited before its child-tree is passed). Any overflow
   275         -  # chains present are traversed from start to finish before any child-tree
   276         -  # is.
   277         -  #
   278         -  set gap_cnt 0
   279         -  set prev 0
   280         -  db eval {
   281         -    SELECT pageno, pagetype FROM temp.dbstat
   282         -     WHERE name=$name
   283         -     ORDER BY pageno
   284         -  } {
   285         -    if {$prev>0 && $pagetype=="leaf" && $pageno!=$prev+1} {
   286         -      incr gap_cnt
   287         -    }
   288         -    set prev $pageno
   289         -  }
   290         -  mem eval {
   291         -    INSERT INTO space_used VALUES(
   292         -      $name,
   293         -      $tblname,
   294         -      $is_index,
   295         -      $is_without_rowid,
   296         -      $nentry,
   297         -      $leaf_entries,
   298         -      $depth,
   299         -      $payload,     
   300         -      $ovfl_payload,
   301         -      $ovfl_cnt,   
   302         -      $mx_payload,
   303         -      $int_pages,
   304         -      $leaf_pages,  
   305         -      $ovfl_pages, 
   306         -      $int_unused, 
   307         -      $leaf_unused,
   308         -      $ovfl_unused,
   309         -      $gap_cnt,
   310         -      $compressed_size
   311         -    );
   312         -  }
   313         -}
   314         -
   315         -proc integerify {real} {
   316         -  if {[string is double -strict $real]} {
   317         -    return [expr {wide($real)}]
   318         -  } else {
   319         -    return 0
   320         -  }
   321         -}
   322         -mem function int integerify
   323         -
   324         -# Quote a string for use in an SQL query. Examples:
   325         -#
   326         -# [quote {hello world}]   == {'hello world'}
   327         -# [quote {hello world's}] == {'hello world''s'}
   328         -#
   329         -proc quote {txt} {
   330         -  return [string map {' ''} $txt]
   331         -}
   332         -
   333         -# Output a title line
   334         -#
   335         -proc titleline {title} {
   336         -  if {$title==""} {
   337         -    puts [string repeat * 79]
   338         -  } else {
   339         -    set len [string length $title]
   340         -    set stars [string repeat * [expr 79-$len-5]]
   341         -    puts "*** $title $stars"
   342         -  }
   343         -}
   344         -
   345         -# Generate a single line of output in the statistics section of the
   346         -# report.
   347         -#
   348         -proc statline {title value {extra {}}} {
   349         -  set len [string length $title]
   350         -  set dots [string repeat . [expr 50-$len]]
   351         -  set len [string length $value]
   352         -  set sp2 [string range {          } $len end]
   353         -  if {$extra ne ""} {
   354         -    set extra " $extra"
   355         -  }
   356         -  puts "$title$dots $value$sp2$extra"
   357         -}
   358         -
   359         -# Generate a formatted percentage value for $num/$denom
   360         -#
   361         -proc percent {num denom {of {}}} {
   362         -  if {$denom==0.0} {return ""}
   363         -  set v [expr {$num*100.0/$denom}]
   364         -  set of {}
   365         -  if {$v==100.0 || $v<0.001 || ($v>1.0 && $v<99.0)} {
   366         -    return [format {%5.1f%% %s} $v $of]
   367         -  } elseif {$v<0.1 || $v>99.9} {
   368         -    return [format {%7.3f%% %s} $v $of]
   369         -  } else {
   370         -    return [format {%6.2f%% %s} $v $of]
   371         -  }
   372         -}
   373         -
   374         -proc divide {num denom} {
   375         -  if {$denom==0} {return 0.0}
   376         -  return [format %.2f [expr double($num)/double($denom)]]
   377         -}
   378         -
   379         -# Generate a subreport that covers some subset of the database.
   380         -# the $where clause determines which subset to analyze.
   381         -#
   382         -proc subreport {title where showFrag} {
   383         -  global pageSize file_pgcnt compressOverhead
   384         -
   385         -  # Query the in-memory database for the sum of various statistics 
   386         -  # for the subset of tables/indices identified by the WHERE clause in
   387         -  # $where. Note that even if the WHERE clause matches no rows, the
   388         -  # following query returns exactly one row (because it is an aggregate).
   389         -  #
   390         -  # The results of the query are stored directly by SQLite into local 
   391         -  # variables (i.e. $nentry, $payload etc.).
   392         -  #
   393         -  mem eval "
   394         -    SELECT
   395         -      int(sum(
   396         -        CASE WHEN (is_without_rowid OR is_index) THEN nentry 
   397         -             ELSE leaf_entries 
   398         -        END
   399         -      )) AS nentry,
   400         -      int(sum(payload)) AS payload,
   401         -      int(sum(ovfl_payload)) AS ovfl_payload,
   402         -      max(mx_payload) AS mx_payload,
   403         -      int(sum(ovfl_cnt)) as ovfl_cnt,
   404         -      int(sum(leaf_pages)) AS leaf_pages,
   405         -      int(sum(int_pages)) AS int_pages,
   406         -      int(sum(ovfl_pages)) AS ovfl_pages,
   407         -      int(sum(leaf_unused)) AS leaf_unused,
   408         -      int(sum(int_unused)) AS int_unused,
   409         -      int(sum(ovfl_unused)) AS ovfl_unused,
   410         -      int(sum(gap_cnt)) AS gap_cnt,
   411         -      int(sum(compressed_size)) AS compressed_size,
   412         -      int(max(depth)) AS depth,
   413         -      count(*) AS cnt
   414         -    FROM space_used WHERE $where" {} {}
   415         -
   416         -  # Output the sub-report title, nicely decorated with * characters.
   417         -  #
   418         -  puts ""
   419         -  titleline $title
   420         -  puts ""
   421         -
   422         -  # Calculate statistics and store the results in TCL variables, as follows:
   423         -  #
   424         -  # total_pages: Database pages consumed.
   425         -  # total_pages_percent: Pages consumed as a percentage of the file.
   426         -  # storage: Bytes consumed.
   427         -  # payload_percent: Payload bytes used as a percentage of $storage.
   428         -  # total_unused: Unused bytes on pages.
   429         -  # avg_payload: Average payload per btree entry.
   430         -  # avg_fanout: Average fanout for internal pages.
   431         -  # avg_unused: Average unused bytes per btree entry.
   432         -  # ovfl_cnt_percent: Percentage of btree entries that use overflow pages.
   433         -  #
   434         -  set total_pages [expr {$leaf_pages+$int_pages+$ovfl_pages}]
   435         -  set total_pages_percent [percent $total_pages $file_pgcnt]
   436         -  set storage [expr {$total_pages*$pageSize}]
   437         -  set payload_percent [percent $payload $storage {of storage consumed}]
   438         -  set total_unused [expr {$ovfl_unused+$int_unused+$leaf_unused}]
   439         -  set avg_payload [divide $payload $nentry]
   440         -  set avg_unused [divide $total_unused $nentry]
   441         -  if {$int_pages>0} {
   442         -    # TODO: Is this formula correct?
   443         -    set nTab [mem eval "
   444         -      SELECT count(*) FROM (
   445         -          SELECT DISTINCT tblname FROM space_used WHERE $where AND is_index=0
   446         -      )
   447         -    "]
   448         -    set avg_fanout [mem eval "
   449         -      SELECT (sum(leaf_pages+int_pages)-$nTab)/sum(int_pages) FROM space_used
   450         -          WHERE $where
   451         -    "]
   452         -    set avg_fanout [format %.2f $avg_fanout]
   453         -  }
   454         -  set ovfl_cnt_percent [percent $ovfl_cnt $nentry {of all entries}]
   455         -
   456         -  # Print out the sub-report statistics.
   457         -  #
   458         -  statline {Percentage of total database} $total_pages_percent
   459         -  statline {Number of entries} $nentry
   460         -  statline {Bytes of storage consumed} $storage
   461         -  if {$compressed_size!=$storage} {
   462         -    set compressed_size [expr {$compressed_size+$compressOverhead*$total_pages}]
   463         -    set pct [expr {$compressed_size*100.0/$storage}]
   464         -    set pct [format {%5.1f%%} $pct]
   465         -    statline {Bytes used after compression} $compressed_size $pct
   466         -  }
   467         -  statline {Bytes of payload} $payload $payload_percent
   468         -  if {$cnt==1} {statline {B-tree depth} $depth}
   469         -  statline {Average payload per entry} $avg_payload
   470         -  statline {Average unused bytes per entry} $avg_unused
   471         -  if {[info exists avg_fanout]} {
   472         -    statline {Average fanout} $avg_fanout
   473         -  }
   474         -  if {$showFrag && $total_pages>1} {
   475         -    set fragmentation [percent $gap_cnt [expr {$total_pages-1}]]
   476         -    statline {Non-sequential pages} $gap_cnt $fragmentation
   477         -  }
   478         -  statline {Maximum payload per entry} $mx_payload
   479         -  statline {Entries that use overflow} $ovfl_cnt $ovfl_cnt_percent
   480         -  if {$int_pages>0} {
   481         -    statline {Index pages used} $int_pages
   482         -  }
   483         -  statline {Primary pages used} $leaf_pages
   484         -  statline {Overflow pages used} $ovfl_pages
   485         -  statline {Total pages used} $total_pages
   486         -  if {$int_unused>0} {
   487         -    set int_unused_percent [
   488         -         percent $int_unused [expr {$int_pages*$pageSize}] {of index space}]
   489         -    statline "Unused bytes on index pages" $int_unused $int_unused_percent
   490         -  }
   491         -  statline "Unused bytes on primary pages" $leaf_unused [
   492         -     percent $leaf_unused [expr {$leaf_pages*$pageSize}] {of primary space}]
   493         -  statline "Unused bytes on overflow pages" $ovfl_unused [
   494         -     percent $ovfl_unused [expr {$ovfl_pages*$pageSize}] {of overflow space}]
   495         -  statline "Unused bytes on all pages" $total_unused [
   496         -               percent $total_unused $storage {of all space}]
   497         -  return 1
   498         -}
   499         -
   500         -# Calculate the overhead in pages caused by auto-vacuum. 
   501         -#
   502         -# This procedure calculates and returns the number of pages used by the 
   503         -# auto-vacuum 'pointer-map'. If the database does not support auto-vacuum,
   504         -# then 0 is returned. The two arguments are the size of the database file in
   505         -# pages and the page size used by the database (in bytes).
   506         -proc autovacuum_overhead {filePages pageSize} {
   507         -
   508         -  # Set $autovacuum to non-zero for databases that support auto-vacuum.
   509         -  set autovacuum [db one {PRAGMA auto_vacuum}]
   510         -
   511         -  # If the database is not an auto-vacuum database or the file consists
   512         -  # of one page only then there is no overhead for auto-vacuum. Return zero.
   513         -  if {0==$autovacuum || $filePages==1} {
   514         -    return 0
   515         -  }
   516         -
   517         -  # The number of entries on each pointer map page. The layout of the
   518         -  # database file is one pointer-map page, followed by $ptrsPerPage other
   519         -  # pages, followed by a pointer-map page etc. The first pointer-map page
   520         -  # is the second page of the file overall.
   521         -  set ptrsPerPage [expr double($pageSize/5)]
   522         -
   523         -  # Return the number of pointer map pages in the database.
   524         -  return [expr wide(ceil( ($filePages-1.0)/($ptrsPerPage+1.0) ))]
   525         -}
   526         -
   527         -
   528         -# Calculate the summary statistics for the database and store the results
   529         -# in TCL variables. They are output below. Variables are as follows:
   530         -#
   531         -# pageSize:      Size of each page in bytes.
   532         -# file_bytes:    File size in bytes.
   533         -# file_pgcnt:    Number of pages in the file.
   534         -# file_pgcnt2:   Number of pages in the file (calculated).
   535         -# av_pgcnt:      Pages consumed by the auto-vacuum pointer-map.
   536         -# av_percent:    Percentage of the file consumed by auto-vacuum pointer-map.
   537         -# inuse_pgcnt:   Data pages in the file.
   538         -# inuse_percent: Percentage of pages used to store data.
   539         -# free_pgcnt:    Free pages calculated as (<total pages> - <in-use pages>)
   540         -# free_pgcnt2:   Free pages in the file according to the file header.
   541         -# free_percent:  Percentage of file consumed by free pages (calculated).
   542         -# free_percent2: Percentage of file consumed by free pages (header).
   543         -# ntable:        Number of tables in the db.
   544         -# nindex:        Number of indices in the db.
   545         -# nautoindex:    Number of indices created automatically.
   546         -# nmanindex:     Number of indices created manually.
   547         -# user_payload:  Number of bytes of payload in table btrees 
   548         -#                (not including sqlite_master)
   549         -# user_percent:  $user_payload as a percentage of total file size.
   550         -
   551         -### The following, setting $file_bytes based on the actual size of the file
   552         -### on disk, causes this tool to choke on zipvfs databases. So set it based
   553         -### on the return of [PRAGMA page_count] instead.
   554         -if 0 {
   555         -  set file_bytes  [file size $file_to_analyze]
   556         -  set file_pgcnt  [expr {$file_bytes/$pageSize}]
   557         -}
   558         -set file_pgcnt  [db one {PRAGMA page_count}]
   559         -set file_bytes  [expr {$file_pgcnt * $pageSize}]
   560         -
   561         -set av_pgcnt    [autovacuum_overhead $file_pgcnt $pageSize]
   562         -set av_percent  [percent $av_pgcnt $file_pgcnt]
   563         -
   564         -set sql {SELECT sum(leaf_pages+int_pages+ovfl_pages) FROM space_used}
   565         -set inuse_pgcnt   [expr wide([mem eval $sql])]
   566         -set inuse_percent [percent $inuse_pgcnt $file_pgcnt]
   567         -
   568         -set free_pgcnt    [expr {$file_pgcnt-$inuse_pgcnt-$av_pgcnt}]
   569         -set free_percent  [percent $free_pgcnt $file_pgcnt]
   570         -set free_pgcnt2   [db one {PRAGMA freelist_count}]
   571         -set free_percent2 [percent $free_pgcnt2 $file_pgcnt]
   572         -
   573         -set file_pgcnt2 [expr {$inuse_pgcnt+$free_pgcnt2+$av_pgcnt}]
   574         -
   575         -set ntable [db eval {SELECT count(*)+1 FROM sqlite_master WHERE type='table'}]
   576         -set nindex [db eval {SELECT count(*) FROM sqlite_master WHERE type='index'}]
   577         -set sql {SELECT count(*) FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
   578         -set nautoindex [db eval $sql]
   579         -set nmanindex [expr {$nindex-$nautoindex}]
   580         -
   581         -# set total_payload [mem eval "SELECT sum(payload) FROM space_used"]
   582         -set user_payload [mem one {SELECT int(sum(payload)) FROM space_used
   583         -     WHERE NOT is_index AND name NOT LIKE 'sqlite_master'}]
   584         -set user_percent [percent $user_payload $file_bytes]
   585         -
   586         -# Output the summary statistics calculated above.
   587         -#
   588         -puts "/** Disk-Space Utilization Report For $root_filename"
   589         -puts ""
   590         -statline {Page size in bytes} $pageSize
   591         -statline {Pages in the whole file (measured)} $file_pgcnt
   592         -statline {Pages in the whole file (calculated)} $file_pgcnt2
   593         -statline {Pages that store data} $inuse_pgcnt $inuse_percent
   594         -statline {Pages on the freelist (per header)} $free_pgcnt2 $free_percent2
   595         -statline {Pages on the freelist (calculated)} $free_pgcnt $free_percent
   596         -statline {Pages of auto-vacuum overhead} $av_pgcnt $av_percent
   597         -statline {Number of tables in the database} $ntable
   598         -statline {Number of indices} $nindex
   599         -statline {Number of defined indices} $nmanindex
   600         -statline {Number of implied indices} $nautoindex
   601         -if {$isCompressed} {
   602         -  statline {Size of uncompressed content in bytes} $file_bytes
   603         -  set efficiency [percent $true_file_size $file_bytes]
   604         -  statline {Size of compressed file on disk} $true_file_size $efficiency
   605         -} else {
   606         -  statline {Size of the file in bytes} $file_bytes
   607         -}
   608         -statline {Bytes of user payload stored} $user_payload $user_percent
   609         -
   610         -# Output table rankings
   611         -#
   612         -puts ""
   613         -titleline "Page counts for all tables with their indices"
   614         -puts ""
   615         -mem eval {SELECT tblname, count(*) AS cnt, 
   616         -              int(sum(int_pages+leaf_pages+ovfl_pages)) AS size
   617         -          FROM space_used GROUP BY tblname ORDER BY size+0 DESC, tblname} {} {
   618         -  statline [string toupper $tblname] $size [percent $size $file_pgcnt]
   619         -}
   620         -puts ""
   621         -titleline "Page counts for all tables and indices separately"
   622         -puts ""
   623         -mem eval {
   624         -  SELECT
   625         -       upper(name) AS nm,
   626         -       int(int_pages+leaf_pages+ovfl_pages) AS size
   627         -    FROM space_used
   628         -   ORDER BY size+0 DESC, name} {} {
   629         -  statline $nm $size [percent $size $file_pgcnt]
   630         -}
   631         -if {$isCompressed} {
   632         -  puts ""
   633         -  titleline "Bytes of disk space used after compression"
   634         -  puts ""
   635         -  set csum 0
   636         -  mem eval {SELECT tblname,
   637         -                  int(sum(compressed_size)) +
   638         -                         $compressOverhead*sum(int_pages+leaf_pages+ovfl_pages)
   639         -                        AS csize
   640         -          FROM space_used GROUP BY tblname ORDER BY csize+0 DESC, tblname} {} {
   641         -    incr csum $csize
   642         -    statline [string toupper $tblname] $csize [percent $csize $true_file_size]
   643         -  }
   644         -  set overhead [expr {$true_file_size - $csum}]
   645         -  if {$overhead>0} {
   646         -    statline {Header and free space} $overhead [percent $overhead $true_file_size]
   647         -  }
   648         -}
   649         -
   650         -# Output subreports
   651         -#
   652         -if {$nindex>0} {
   653         -  subreport {All tables and indices} 1 0
   654         -}
   655         -subreport {All tables} {NOT is_index} 0
   656         -if {$nindex>0} {
   657         -  subreport {All indices} {is_index} 0
   658         -}
   659         -foreach tbl [mem eval {SELECT DISTINCT tblname name FROM space_used
   660         -                       ORDER BY name}] {
   661         -  set qn [quote $tbl]
   662         -  set name [string toupper $tbl]
   663         -  set n [mem eval {SELECT count(*) FROM space_used WHERE tblname=$tbl}]
   664         -  if {$n>1} {
   665         -    set idxlist [mem eval "SELECT name FROM space_used
   666         -                            WHERE tblname='$qn' AND is_index
   667         -                            ORDER BY 1"]
   668         -    subreport "Table $name and all its indices" "tblname='$qn'" 0
   669         -    subreport "Table $name w/o any indices" "name='$qn'" 1
   670         -    if {[llength $idxlist]>1} {
   671         -      subreport "Indices of table $name" "tblname='$qn' AND is_index" 0
   672         -    }
   673         -    foreach idx $idxlist {
   674         -      set qidx [quote $idx]
   675         -      subreport "Index [string toupper $idx] of table $name" "name='$qidx'" 1
   676         -    }
   677         -  } else {
   678         -    subreport "Table $name" "name='$qn'" 1
   679         -  }
   680         -}
   681         -
   682         -# Output instructions on what the numbers above mean.
   683         -#
   684         -puts ""
   685         -titleline Definitions
   686         -puts {
   687         -Page size in bytes
   688         -
   689         -    The number of bytes in a single page of the database file.  
   690         -    Usually 1024.
   691         -
   692         -Number of pages in the whole file
   693         -}
   694         -puts "    The number of $pageSize-byte pages that go into forming the complete
   695         -    database"
   696         -puts {
   697         -Pages that store data
   698         -
   699         -    The number of pages that store data, either as primary B*Tree pages or
   700         -    as overflow pages.  The number at the right is the data pages divided by
   701         -    the total number of pages in the file.
   702         -
   703         -Pages on the freelist
   704         -
   705         -    The number of pages that are not currently in use but are reserved for
   706         -    future use.  The percentage at the right is the number of freelist pages
   707         -    divided by the total number of pages in the file.
   708         -
   709         -Pages of auto-vacuum overhead
   710         -
   711         -    The number of pages that store data used by the database to facilitate
   712         -    auto-vacuum. This is zero for databases that do not support auto-vacuum.
   713         -
   714         -Number of tables in the database
   715         -
   716         -    The number of tables in the database, including the SQLITE_MASTER table
   717         -    used to store schema information.
   718         -
   719         -Number of indices
   720         -
   721         -    The total number of indices in the database.
   722         -
   723         -Number of defined indices
   724         -
   725         -    The number of indices created using an explicit CREATE INDEX statement.
   726         -
   727         -Number of implied indices
   728         -
   729         -    The number of indices used to implement PRIMARY KEY or UNIQUE constraints
   730         -    on tables.
   731         -
   732         -Size of the file in bytes
   733         -
   734         -    The total amount of disk space used by the entire database files.
   735         -
   736         -Bytes of user payload stored
   737         -
   738         -    The total number of bytes of user payload stored in the database. The
   739         -    schema information in the SQLITE_MASTER table is not counted when
   740         -    computing this number.  The percentage at the right shows the payload
   741         -    divided by the total file size.
   742         -
   743         -Percentage of total database
   744         -
   745         -    The amount of the complete database file that is devoted to storing
   746         -    information described by this category.
   747         -
   748         -Number of entries
   749         -
   750         -    The total number of B-Tree key/value pairs stored under this category.
   751         -
   752         -Bytes of storage consumed
   753         -
   754         -    The total amount of disk space required to store all B-Tree entries
   755         -    under this category.  The is the total number of pages used times
   756         -    the pages size.
   757         -
   758         -Bytes of payload
   759         -
   760         -    The amount of payload stored under this category.  Payload is the data
   761         -    part of table entries and the key part of index entries.  The percentage
   762         -    at the right is the bytes of payload divided by the bytes of storage 
   763         -    consumed.
   764         -
   765         -Average payload per entry
   766         -
   767         -    The average amount of payload on each entry.  This is just the bytes of
   768         -    payload divided by the number of entries.
   769         -
   770         -Average unused bytes per entry
   771         -
   772         -    The average amount of free space remaining on all pages under this
   773         -    category on a per-entry basis.  This is the number of unused bytes on
   774         -    all pages divided by the number of entries.
   775         -
   776         -Non-sequential pages
   777         -
   778         -    The number of pages in the table or index that are out of sequence.
   779         -    Many filesystems are optimized for sequential file access so a small
   780         -    number of non-sequential pages might result in faster queries,
   781         -    especially for larger database files that do not fit in the disk cache.
   782         -    Note that after running VACUUM, the root page of each table or index is
   783         -    at the beginning of the database file and all other pages are in a
   784         -    separate part of the database file, resulting in a single non-
   785         -    sequential page.
   786         -
   787         -Maximum payload per entry
   788         -
   789         -    The largest payload size of any entry.
   790         -
   791         -Entries that use overflow
   792         -
   793         -    The number of entries that user one or more overflow pages.
   794         -
   795         -Total pages used
   796         -
   797         -    This is the number of pages used to hold all information in the current
   798         -    category.  This is the sum of index, primary, and overflow pages.
   799         -
   800         -Index pages used
   801         -
   802         -    This is the number of pages in a table B-tree that hold only key (rowid)
   803         -    information and no data.
   804         -
   805         -Primary pages used
   806         -
   807         -    This is the number of B-tree pages that hold both key and data.
   808         -
   809         -Overflow pages used
   810         -
   811         -    The total number of overflow pages used for this category.
   812         -
   813         -Unused bytes on index pages
   814         -
   815         -    The total number of bytes of unused space on all index pages.  The
   816         -    percentage at the right is the number of unused bytes divided by the
   817         -    total number of bytes on index pages.
   818         -
   819         -Unused bytes on primary pages
   820         -
   821         -    The total number of bytes of unused space on all primary pages.  The
   822         -    percentage at the right is the number of unused bytes divided by the
   823         -    total number of bytes on primary pages.
   824         -
   825         -Unused bytes on overflow pages
   826         -
   827         -    The total number of bytes of unused space on all overflow pages.  The
   828         -    percentage at the right is the number of unused bytes divided by the
   829         -    total number of bytes on overflow pages.
   830         -
   831         -Unused bytes on all pages
   832         -
   833         -    The total number of bytes of unused space on all primary and overflow 
   834         -    pages.  The percentage at the right is the number of unused bytes 
   835         -    divided by the total number of bytes.
   836         -}
   837         -
   838         -# Output a dump of the in-memory database. This can be used for more
   839         -# complex offline analysis.
   840         -#
   841         -titleline {}
   842         -puts "The entire text of this report can be sourced into any SQL database"
   843         -puts "engine for further analysis.  All of the text above is an SQL comment."
   844         -puts "The data used to generate this report follows:"
   845         -puts "*/"
   846         -puts "BEGIN;"
   847         -puts $tabledef
   848         -unset -nocomplain x
   849         -mem eval {SELECT * FROM space_used} x {
   850         -  puts -nonewline "INSERT INTO space_used VALUES"
   851         -  set sep (
   852         -  foreach col $x(*) {
   853         -    set v $x($col)
   854         -    if {$v=="" || ![string is double $v]} {set v '[quote $v]'}
   855         -    puts -nonewline $sep$v
   856         -    set sep ,
   857         -  }
   858         -  puts ");"
   859         -}
   860         -puts "COMMIT;"
   861         -
   862         -} err]} {
   863         -  puts "ERROR: $err"
   864         -  puts $errorInfo
   865         -  exit 1
   866         -}

Deleted jni/tcl/pkgs/sqlite3.15.1/compat/sqlite3/sqlite3.c.

more than 10,000 changes

Deleted jni/tcl/pkgs/sqlite3.15.1/compat/sqlite3/sqlite3.h.

more than 10,000 changes

Deleted jni/tcl/pkgs/sqlite3.15.1/compat/sqlite3/sqlite3ext.h.

     1         -/*
     2         -** 2006 June 7
     3         -**
     4         -** The author disclaims copyright to this source code.  In place of
     5         -** a legal notice, here is a blessing:
     6         -**
     7         -**    May you do good and not evil.
     8         -**    May you find forgiveness for yourself and forgive others.
     9         -**    May you share freely, never taking more than you give.
    10         -**
    11         -*************************************************************************
    12         -** This header file defines the SQLite interface for use by
    13         -** shared libraries that want to be imported as extensions into
    14         -** an SQLite instance.  Shared libraries that intend to be loaded
    15         -** as extensions by SQLite should #include this file instead of 
    16         -** sqlite3.h.
    17         -*/
    18         -#ifndef SQLITE3EXT_H
    19         -#define SQLITE3EXT_H
    20         -#include "sqlite3.h"
    21         -
    22         -/*
    23         -** The following structure holds pointers to all of the SQLite API
    24         -** routines.
    25         -**
    26         -** WARNING:  In order to maintain backwards compatibility, add new
    27         -** interfaces to the end of this structure only.  If you insert new
    28         -** interfaces in the middle of this structure, then older different
    29         -** versions of SQLite will not be able to load each other's shared
    30         -** libraries!
    31         -*/
    32         -struct sqlite3_api_routines {
    33         -  void * (*aggregate_context)(sqlite3_context*,int nBytes);
    34         -  int  (*aggregate_count)(sqlite3_context*);
    35         -  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
    36         -  int  (*bind_double)(sqlite3_stmt*,int,double);
    37         -  int  (*bind_int)(sqlite3_stmt*,int,int);
    38         -  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
    39         -  int  (*bind_null)(sqlite3_stmt*,int);
    40         -  int  (*bind_parameter_count)(sqlite3_stmt*);
    41         -  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
    42         -  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
    43         -  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
    44         -  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
    45         -  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
    46         -  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
    47         -  int  (*busy_timeout)(sqlite3*,int ms);
    48         -  int  (*changes)(sqlite3*);
    49         -  int  (*close)(sqlite3*);
    50         -  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
    51         -                           int eTextRep,const char*));
    52         -  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
    53         -                             int eTextRep,const void*));
    54         -  const void * (*column_blob)(sqlite3_stmt*,int iCol);
    55         -  int  (*column_bytes)(sqlite3_stmt*,int iCol);
    56         -  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
    57         -  int  (*column_count)(sqlite3_stmt*pStmt);
    58         -  const char * (*column_database_name)(sqlite3_stmt*,int);
    59         -  const void * (*column_database_name16)(sqlite3_stmt*,int);
    60         -  const char * (*column_decltype)(sqlite3_stmt*,int i);
    61         -  const void * (*column_decltype16)(sqlite3_stmt*,int);
    62         -  double  (*column_double)(sqlite3_stmt*,int iCol);
    63         -  int  (*column_int)(sqlite3_stmt*,int iCol);
    64         -  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
    65         -  const char * (*column_name)(sqlite3_stmt*,int);
    66         -  const void * (*column_name16)(sqlite3_stmt*,int);
    67         -  const char * (*column_origin_name)(sqlite3_stmt*,int);
    68         -  const void * (*column_origin_name16)(sqlite3_stmt*,int);
    69         -  const char * (*column_table_name)(sqlite3_stmt*,int);
    70         -  const void * (*column_table_name16)(sqlite3_stmt*,int);
    71         -  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
    72         -  const void * (*column_text16)(sqlite3_stmt*,int iCol);
    73         -  int  (*column_type)(sqlite3_stmt*,int iCol);
    74         -  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
    75         -  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
    76         -  int  (*complete)(const char*sql);
    77         -  int  (*complete16)(const void*sql);
    78         -  int  (*create_collation)(sqlite3*,const char*,int,void*,
    79         -                           int(*)(void*,int,const void*,int,const void*));
    80         -  int  (*create_collation16)(sqlite3*,const void*,int,void*,
    81         -                             int(*)(void*,int,const void*,int,const void*));
    82         -  int  (*create_function)(sqlite3*,const char*,int,int,void*,
    83         -                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
    84         -                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
    85         -                          void (*xFinal)(sqlite3_context*));
    86         -  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
    87         -                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
    88         -                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
    89         -                            void (*xFinal)(sqlite3_context*));
    90         -  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
    91         -  int  (*data_count)(sqlite3_stmt*pStmt);
    92         -  sqlite3 * (*db_handle)(sqlite3_stmt*);
    93         -  int (*declare_vtab)(sqlite3*,const char*);
    94         -  int  (*enable_shared_cache)(int);
    95         -  int  (*errcode)(sqlite3*db);
    96         -  const char * (*errmsg)(sqlite3*);
    97         -  const void * (*errmsg16)(sqlite3*);
    98         -  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
    99         -  int  (*expired)(sqlite3_stmt*);
   100         -  int  (*finalize)(sqlite3_stmt*pStmt);
   101         -  void  (*free)(void*);
   102         -  void  (*free_table)(char**result);
   103         -  int  (*get_autocommit)(sqlite3*);
   104         -  void * (*get_auxdata)(sqlite3_context*,int);
   105         -  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
   106         -  int  (*global_recover)(void);
   107         -  void  (*interruptx)(sqlite3*);
   108         -  sqlite_int64  (*last_insert_rowid)(sqlite3*);
   109         -  const char * (*libversion)(void);
   110         -  int  (*libversion_number)(void);
   111         -  void *(*malloc)(int);
   112         -  char * (*mprintf)(const char*,...);
   113         -  int  (*open)(const char*,sqlite3**);
   114         -  int  (*open16)(const void*,sqlite3**);
   115         -  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   116         -  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   117         -  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
   118         -  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
   119         -  void *(*realloc)(void*,int);
   120         -  int  (*reset)(sqlite3_stmt*pStmt);
   121         -  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
   122         -  void  (*result_double)(sqlite3_context*,double);
   123         -  void  (*result_error)(sqlite3_context*,const char*,int);
   124         -  void  (*result_error16)(sqlite3_context*,const void*,int);
   125         -  void  (*result_int)(sqlite3_context*,int);
   126         -  void  (*result_int64)(sqlite3_context*,sqlite_int64);
   127         -  void  (*result_null)(sqlite3_context*);
   128         -  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
   129         -  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
   130         -  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
   131         -  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
   132         -  void  (*result_value)(sqlite3_context*,sqlite3_value*);
   133         -  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
   134         -  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
   135         -                         const char*,const char*),void*);
   136         -  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
   137         -  char * (*snprintf)(int,char*,const char*,...);
   138         -  int  (*step)(sqlite3_stmt*);
   139         -  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
   140         -                                char const**,char const**,int*,int*,int*);
   141         -  void  (*thread_cleanup)(void);
   142         -  int  (*total_changes)(sqlite3*);
   143         -  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
   144         -  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
   145         -  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
   146         -                                         sqlite_int64),void*);
   147         -  void * (*user_data)(sqlite3_context*);
   148         -  const void * (*value_blob)(sqlite3_value*);
   149         -  int  (*value_bytes)(sqlite3_value*);
   150         -  int  (*value_bytes16)(sqlite3_value*);
   151         -  double  (*value_double)(sqlite3_value*);
   152         -  int  (*value_int)(sqlite3_value*);
   153         -  sqlite_int64  (*value_int64)(sqlite3_value*);
   154         -  int  (*value_numeric_type)(sqlite3_value*);
   155         -  const unsigned char * (*value_text)(sqlite3_value*);
   156         -  const void * (*value_text16)(sqlite3_value*);
   157         -  const void * (*value_text16be)(sqlite3_value*);
   158         -  const void * (*value_text16le)(sqlite3_value*);
   159         -  int  (*value_type)(sqlite3_value*);
   160         -  char *(*vmprintf)(const char*,va_list);
   161         -  /* Added ??? */
   162         -  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
   163         -  /* Added by 3.3.13 */
   164         -  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
   165         -  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
   166         -  int (*clear_bindings)(sqlite3_stmt*);
   167         -  /* Added by 3.4.1 */
   168         -  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
   169         -                          void (*xDestroy)(void *));
   170         -  /* Added by 3.5.0 */
   171         -  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
   172         -  int (*blob_bytes)(sqlite3_blob*);
   173         -  int (*blob_close)(sqlite3_blob*);
   174         -  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
   175         -                   int,sqlite3_blob**);
   176         -  int (*blob_read)(sqlite3_blob*,void*,int,int);
   177         -  int (*blob_write)(sqlite3_blob*,const void*,int,int);
   178         -  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
   179         -                             int(*)(void*,int,const void*,int,const void*),
   180         -                             void(*)(void*));
   181         -  int (*file_control)(sqlite3*,const char*,int,void*);
   182         -  sqlite3_int64 (*memory_highwater)(int);
   183         -  sqlite3_int64 (*memory_used)(void);
   184         -  sqlite3_mutex *(*mutex_alloc)(int);
   185         -  void (*mutex_enter)(sqlite3_mutex*);
   186         -  void (*mutex_free)(sqlite3_mutex*);
   187         -  void (*mutex_leave)(sqlite3_mutex*);
   188         -  int (*mutex_try)(sqlite3_mutex*);
   189         -  int (*open_v2)(const char*,sqlite3**,int,const char*);
   190         -  int (*release_memory)(int);
   191         -  void (*result_error_nomem)(sqlite3_context*);
   192         -  void (*result_error_toobig)(sqlite3_context*);
   193         -  int (*sleep)(int);
   194         -  void (*soft_heap_limit)(int);
   195         -  sqlite3_vfs *(*vfs_find)(const char*);
   196         -  int (*vfs_register)(sqlite3_vfs*,int);
   197         -  int (*vfs_unregister)(sqlite3_vfs*);
   198         -  int (*xthreadsafe)(void);
   199         -  void (*result_zeroblob)(sqlite3_context*,int);
   200         -  void (*result_error_code)(sqlite3_context*,int);
   201         -  int (*test_control)(int, ...);
   202         -  void (*randomness)(int,void*);
   203         -  sqlite3 *(*context_db_handle)(sqlite3_context*);
   204         -  int (*extended_result_codes)(sqlite3*,int);
   205         -  int (*limit)(sqlite3*,int,int);
   206         -  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
   207         -  const char *(*sql)(sqlite3_stmt*);
   208         -  int (*status)(int,int*,int*,int);
   209         -  int (*backup_finish)(sqlite3_backup*);
   210         -  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
   211         -  int (*backup_pagecount)(sqlite3_backup*);
   212         -  int (*backup_remaining)(sqlite3_backup*);
   213         -  int (*backup_step)(sqlite3_backup*,int);
   214         -  const char *(*compileoption_get)(int);
   215         -  int (*compileoption_used)(const char*);
   216         -  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
   217         -                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   218         -                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   219         -                            void (*xFinal)(sqlite3_context*),
   220         -                            void(*xDestroy)(void*));
   221         -  int (*db_config)(sqlite3*,int,...);
   222         -  sqlite3_mutex *(*db_mutex)(sqlite3*);
   223         -  int (*db_status)(sqlite3*,int,int*,int*,int);
   224         -  int (*extended_errcode)(sqlite3*);
   225         -  void (*log)(int,const char*,...);
   226         -  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
   227         -  const char *(*sourceid)(void);
   228         -  int (*stmt_status)(sqlite3_stmt*,int,int);
   229         -  int (*strnicmp)(const char*,const char*,int);
   230         -  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
   231         -  int (*wal_autocheckpoint)(sqlite3*,int);
   232         -  int (*wal_checkpoint)(sqlite3*,const char*);
   233         -  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
   234         -  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
   235         -  int (*vtab_config)(sqlite3*,int op,...);
   236         -  int (*vtab_on_conflict)(sqlite3*);
   237         -  /* Version 3.7.16 and later */
   238         -  int (*close_v2)(sqlite3*);
   239         -  const char *(*db_filename)(sqlite3*,const char*);
   240         -  int (*db_readonly)(sqlite3*,const char*);
   241         -  int (*db_release_memory)(sqlite3*);
   242         -  const char *(*errstr)(int);
   243         -  int (*stmt_busy)(sqlite3_stmt*);
   244         -  int (*stmt_readonly)(sqlite3_stmt*);
   245         -  int (*stricmp)(const char*,const char*);
   246         -  int (*uri_boolean)(const char*,const char*,int);
   247         -  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
   248         -  const char *(*uri_parameter)(const char*,const char*);
   249         -  char *(*vsnprintf)(int,char*,const char*,va_list);
   250         -  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
   251         -  /* Version 3.8.7 and later */
   252         -  int (*auto_extension)(void(*)(void));
   253         -  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
   254         -                     void(*)(void*));
   255         -  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
   256         -                      void(*)(void*),unsigned char);
   257         -  int (*cancel_auto_extension)(void(*)(void));
   258         -  int (*load_extension)(sqlite3*,const char*,const char*,char**);
   259         -  void *(*malloc64)(sqlite3_uint64);
   260         -  sqlite3_uint64 (*msize)(void*);
   261         -  void *(*realloc64)(void*,sqlite3_uint64);
   262         -  void (*reset_auto_extension)(void);
   263         -  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
   264         -                        void(*)(void*));
   265         -  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
   266         -                         void(*)(void*), unsigned char);
   267         -  int (*strglob)(const char*,const char*);
   268         -  /* Version 3.8.11 and later */
   269         -  sqlite3_value *(*value_dup)(const sqlite3_value*);
   270         -  void (*value_free)(sqlite3_value*);
   271         -  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
   272         -  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
   273         -  /* Version 3.9.0 and later */
   274         -  unsigned int (*value_subtype)(sqlite3_value*);
   275         -  void (*result_subtype)(sqlite3_context*,unsigned int);
   276         -  /* Version 3.10.0 and later */
   277         -  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
   278         -  int (*strlike)(const char*,const char*,unsigned int);
   279         -  int (*db_cacheflush)(sqlite3*);
   280         -  /* Version 3.12.0 and later */
   281         -  int (*system_errno)(sqlite3*);
   282         -  /* Version 3.14.0 and later */
   283         -  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
   284         -  char *(*expanded_sql)(sqlite3_stmt*);
   285         -};
   286         -
   287         -/*
   288         -** This is the function signature used for all extension entry points.  It
   289         -** is also defined in the file "loadext.c".
   290         -*/
   291         -typedef int (*sqlite3_loadext_entry)(
   292         -  sqlite3 *db,                       /* Handle to the database. */
   293         -  char **pzErrMsg,                   /* Used to set error string on failure. */
   294         -  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
   295         -);
   296         -
   297         -/*
   298         -** The following macros redefine the API routines so that they are
   299         -** redirected through the global sqlite3_api structure.
   300         -**
   301         -** This header file is also used by the loadext.c source file
   302         -** (part of the main SQLite library - not an extension) so that
   303         -** it can get access to the sqlite3_api_routines structure
   304         -** definition.  But the main library does not want to redefine
   305         -** the API.  So the redefinition macros are only valid if the
   306         -** SQLITE_CORE macros is undefined.
   307         -*/
   308         -#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   309         -#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
   310         -#ifndef sqlite3_bind_blob
   311         -#define sqlite3_bind_blob              sqlite3_api->bind_blob
   312         -#endif
   313         -#define sqlite3_bind_double            sqlite3_api->bind_double
   314         -#define sqlite3_bind_int               sqlite3_api->bind_int
   315         -#define sqlite3_bind_int64             sqlite3_api->bind_int64
   316         -#define sqlite3_bind_null              sqlite3_api->bind_null
   317         -#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
   318         -#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
   319         -#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
   320         -#ifndef sqlite3_bind_text
   321         -#define sqlite3_bind_text              sqlite3_api->bind_text
   322         -#endif
   323         -#ifndef sqlite3_bind_text16
   324         -#define sqlite3_bind_text16            sqlite3_api->bind_text16
   325         -#endif
   326         -#define sqlite3_bind_value             sqlite3_api->bind_value
   327         -#define sqlite3_busy_handler           sqlite3_api->busy_handler
   328         -#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
   329         -#define sqlite3_changes                sqlite3_api->changes
   330         -#define sqlite3_close                  sqlite3_api->close
   331         -#define sqlite3_collation_needed       sqlite3_api->collation_needed
   332         -#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
   333         -#define sqlite3_column_blob            sqlite3_api->column_blob
   334         -#define sqlite3_column_bytes           sqlite3_api->column_bytes
   335         -#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
   336         -#define sqlite3_column_count           sqlite3_api->column_count
   337         -#define sqlite3_column_database_name   sqlite3_api->column_database_name
   338         -#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
   339         -#define sqlite3_column_decltype        sqlite3_api->column_decltype
   340         -#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
   341         -#define sqlite3_column_double          sqlite3_api->column_double
   342         -#define sqlite3_column_int             sqlite3_api->column_int
   343         -#define sqlite3_column_int64           sqlite3_api->column_int64
   344         -#define sqlite3_column_name            sqlite3_api->column_name
   345         -#define sqlite3_column_name16          sqlite3_api->column_name16
   346         -#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
   347         -#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
   348         -#define sqlite3_column_table_name      sqlite3_api->column_table_name
   349         -#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
   350         -#define sqlite3_column_text            sqlite3_api->column_text
   351         -#define sqlite3_column_text16          sqlite3_api->column_text16
   352         -#define sqlite3_column_type            sqlite3_api->column_type
   353         -#define sqlite3_column_value           sqlite3_api->column_value
   354         -#define sqlite3_commit_hook            sqlite3_api->commit_hook
   355         -#define sqlite3_complete               sqlite3_api->complete
   356         -#define sqlite3_complete16             sqlite3_api->complete16
   357         -#undef sqlite3_create_collation
   358         -#define sqlite3_create_collation(a,b,c,d,e) sqlite3_create_collation_v2(a,b,c,d,e,0)
   359         -#define sqlite3_create_collation16     sqlite3_api->create_collation16
   360         -#undef sqlite3_create_function
   361         -#define sqlite3_create_function(a,b,c,d,e,f,g,h) sqlite3_create_function_v2(a,b,c,d,e,f,g,h,0)
   362         -#define sqlite3_create_function16      sqlite3_api->create_function16
   363         -#undef sqlite3_create_module
   364         -#define sqlite3_create_module(a,b,c,d) sqlite3_create_module_v2(a,b,c,d,0)
   365         -#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
   366         -#define sqlite3_data_count             sqlite3_api->data_count
   367         -#define sqlite3_db_handle              sqlite3_api->db_handle
   368         -#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
   369         -#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
   370         -#define sqlite3_errcode                sqlite3_api->errcode
   371         -#define sqlite3_errmsg                 sqlite3_api->errmsg
   372         -#define sqlite3_errmsg16               sqlite3_api->errmsg16
   373         -#define sqlite3_exec                   sqlite3_api->exec
   374         -#define sqlite3_finalize               sqlite3_api->finalize
   375         -#define sqlite3_free                   sqlite3_api->free
   376         -#define sqlite3_free_table             sqlite3_api->free_table
   377         -#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
   378         -#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
   379         -#define sqlite3_get_table              sqlite3_api->get_table
   380         -#define sqlite3_interrupt              sqlite3_api->interruptx
   381         -#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
   382         -#define sqlite3_libversion             sqlite3_api->libversion
   383         -#define sqlite3_libversion_number      sqlite3_api->libversion_number
   384         -#ifndef sqlite3_malloc
   385         -#define sqlite3_malloc                 sqlite3_api->malloc
   386         -#endif
   387         -#define sqlite3_mprintf                sqlite3_api->mprintf
   388         -#define sqlite3_open                   sqlite3_api->open
   389         -#define sqlite3_open16                 sqlite3_api->open16
   390         -#define sqlite3_prepare                sqlite3_api->prepare
   391         -#define sqlite3_prepare16              sqlite3_api->prepare16
   392         -#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   393         -#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   394         -#define sqlite3_profile                sqlite3_api->profile
   395         -#define sqlite3_progress_handler       sqlite3_api->progress_handler
   396         -#ifndef sqlite3_realloc
   397         -#define sqlite3_realloc                sqlite3_api->realloc
   398         -#endif
   399         -#define sqlite3_reset                  sqlite3_api->reset
   400         -#define sqlite3_result_blob            sqlite3_api->result_blob
   401         -#define sqlite3_result_double          sqlite3_api->result_double
   402         -#define sqlite3_result_error           sqlite3_api->result_error
   403         -#define sqlite3_result_error16         sqlite3_api->result_error16
   404         -#define sqlite3_result_int             sqlite3_api->result_int
   405         -#define sqlite3_result_int64           sqlite3_api->result_int64
   406         -#define sqlite3_result_null            sqlite3_api->result_null
   407         -#ifndef sqlite3_result_text
   408         -#define sqlite3_result_text            sqlite3_api->result_text
   409         -#endif
   410         -#ifndef sqlite3_result_text16
   411         -#define sqlite3_result_text16          sqlite3_api->result_text16
   412         -#endif
   413         -#ifndef sqlite3_result_text16be
   414         -#define sqlite3_result_text16be        sqlite3_api->result_text16be
   415         -#endif
   416         -#ifndef sqlite3_result_text16le
   417         -#define sqlite3_result_text16le        sqlite3_api->result_text16le
   418         -#endif
   419         -#define sqlite3_result_value           sqlite3_api->result_value
   420         -#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
   421         -#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
   422         -#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
   423         -#define sqlite3_snprintf               sqlite3_api->snprintf
   424         -#define sqlite3_step                   sqlite3_api->step
   425         -#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
   426         -#define sqlite3_total_changes          sqlite3_api->total_changes
   427         -#define sqlite3_trace                  sqlite3_api->trace
   428         -#define sqlite3_update_hook            sqlite3_api->update_hook
   429         -#define sqlite3_user_data              sqlite3_api->user_data
   430         -#define sqlite3_value_blob             sqlite3_api->value_blob
   431         -#define sqlite3_value_bytes            sqlite3_api->value_bytes
   432         -#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
   433         -#define sqlite3_value_double           sqlite3_api->value_double
   434         -#define sqlite3_value_int              sqlite3_api->value_int
   435         -#define sqlite3_value_int64            sqlite3_api->value_int64
   436         -#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
   437         -#ifndef sqlite3_value_text
   438         -#define sqlite3_value_text             sqlite3_api->value_text
   439         -#endif
   440         -#ifndef sqlite3_value_text16
   441         -#define sqlite3_value_text16           sqlite3_api->value_text16
   442         -#endif
   443         -#ifndef sqlite3_value_text16be
   444         -#define sqlite3_value_text16be         sqlite3_api->value_text16be
   445         -#endif
   446         -#ifndef sqlite3_value_text16le
   447         -#define sqlite3_value_text16le         sqlite3_api->value_text16le
   448         -#endif
   449         -#define sqlite3_value_type             sqlite3_api->value_type
   450         -#define sqlite3_vmprintf               sqlite3_api->vmprintf
   451         -#define sqlite3_vsnprintf              sqlite3_api->vsnprintf
   452         -#define sqlite3_overload_function      sqlite3_api->overload_function
   453         -#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
   454         -#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
   455         -#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
   456         -#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
   457         -#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
   458         -#define sqlite3_blob_close             sqlite3_api->blob_close
   459         -#define sqlite3_blob_open              sqlite3_api->blob_open
   460         -#define sqlite3_blob_read              sqlite3_api->blob_read
   461         -#define sqlite3_blob_write             sqlite3_api->blob_write
   462         -#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
   463         -#define sqlite3_file_control           sqlite3_api->file_control
   464         -#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
   465         -#define sqlite3_memory_used            sqlite3_api->memory_used
   466         -#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
   467         -#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
   468         -#define sqlite3_mutex_free             sqlite3_api->mutex_free
   469         -#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
   470         -#define sqlite3_mutex_try              sqlite3_api->mutex_try
   471         -#define sqlite3_open_v2                sqlite3_api->open_v2
   472         -#define sqlite3_release_memory         sqlite3_api->release_memory
   473         -#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
   474         -#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
   475         -#define sqlite3_sleep                  sqlite3_api->sleep
   476         -#define sqlite3_vfs_find               sqlite3_api->vfs_find
   477         -#define sqlite3_vfs_register           sqlite3_api->vfs_register
   478         -#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
   479         -#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
   480         -#ifndef sqlite3_result_zeroblob
   481         -#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
   482         -#endif
   483         -#define sqlite3_result_error_code      sqlite3_api->result_error_code
   484         -#define sqlite3_test_control           sqlite3_api->test_control
   485         -#define sqlite3_randomness             sqlite3_api->randomness
   486         -#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
   487         -#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
   488         -#define sqlite3_limit                  sqlite3_api->limit
   489         -#define sqlite3_next_stmt              sqlite3_api->next_stmt
   490         -#define sqlite3_sql                    sqlite3_api->sql
   491         -#define sqlite3_status                 sqlite3_api->status
   492         -#define sqlite3_backup_finish          sqlite3_api->backup_finish
   493         -#define sqlite3_backup_init            sqlite3_api->backup_init
   494         -#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
   495         -#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
   496         -#define sqlite3_backup_step            sqlite3_api->backup_step
   497         -#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
   498         -#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
   499         -#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
   500         -#define sqlite3_db_config              sqlite3_api->db_config
   501         -#define sqlite3_db_mutex               sqlite3_api->db_mutex
   502         -#define sqlite3_db_status              sqlite3_api->db_status
   503         -#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
   504         -#define sqlite3_log                    sqlite3_api->log
   505         -#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
   506         -#define sqlite3_sourceid               sqlite3_api->sourceid
   507         -#define sqlite3_stmt_status            sqlite3_api->stmt_status
   508         -#define sqlite3_strnicmp               sqlite3_api->strnicmp
   509         -#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
   510         -#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
   511         -#undef sqlite3_wal_checkpoint
   512         -#define sqlite3_wal_checkpoint(a,b)    sqlite3_wal_checkpoint_v2(a,b,SQLITE_CHECKPOINT_PASSIVE,0,0)
   513         -#define sqlite3_wal_hook               sqlite3_api->wal_hook
   514         -#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
   515         -#define sqlite3_vtab_config            sqlite3_api->vtab_config
   516         -#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
   517         -/* Version 3.7.16 and later */
   518         -#define sqlite3_close_v2               sqlite3_api->close_v2
   519         -#define sqlite3_db_filename            sqlite3_api->db_filename
   520         -#define sqlite3_db_readonly            sqlite3_api->db_readonly
   521         -#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
   522         -#define sqlite3_errstr                 sqlite3_api->errstr
   523         -#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
   524         -#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
   525         -#define sqlite3_stricmp                sqlite3_api->stricmp
   526         -#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
   527         -#define sqlite3_uri_int64              sqlite3_api->uri_int64
   528         -#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
   529         -#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
   530         -#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
   531         -/* Version 3.8.7 and later */
   532         -#define sqlite3_auto_extension         sqlite3_api->auto_extension
   533         -#define sqlite3_bind_blob64            sqlite3_api->bind_blob64
   534         -#define sqlite3_bind_text64            sqlite3_api->bind_text64
   535         -#define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
   536         -#define sqlite3_load_extension         sqlite3_api->load_extension
   537         -#define sqlite3_malloc64               sqlite3_api->malloc64
   538         -#define sqlite3_msize                  sqlite3_api->msize
   539         -#define sqlite3_realloc64              sqlite3_api->realloc64
   540         -#define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
   541         -#define sqlite3_result_blob64          sqlite3_api->result_blob64
   542         -#define sqlite3_result_text64          sqlite3_api->result_text64
   543         -#define sqlite3_strglob                sqlite3_api->strglob
   544         -/* Version 3.8.11 and later */
   545         -#define sqlite3_value_dup              sqlite3_api->value_dup
   546         -#define sqlite3_value_free             sqlite3_api->value_free
   547         -#define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
   548         -#define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
   549         -/* Version 3.9.0 and later */
   550         -#define sqlite3_value_subtype          sqlite3_api->value_subtype
   551         -#define sqlite3_result_subtype         sqlite3_api->result_subtype
   552         -/* Version 3.10.0 and later */
   553         -#define sqlite3_status64               sqlite3_api->status64
   554         -#define sqlite3_strlike                sqlite3_api->strlike
   555         -#define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
   556         -/* Version 3.12.0 and later */
   557         -#define sqlite3_system_errno           sqlite3_api->system_errno
   558         -/* Version 3.14.0 and later */
   559         -#define sqlite3_trace_v2               sqlite3_api->trace_v2
   560         -#define sqlite3_expanded_sql           sqlite3_api->expanded_sql
   561         -#endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
   562         -
   563         -#if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
   564         -  /* This case when the file really is being compiled as a loadable 
   565         -  ** extension */
   566         -# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
   567         -# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
   568         -# define SQLITE_EXTENSION_INIT3     \
   569         -    extern const sqlite3_api_routines *sqlite3_api;
   570         -#else
   571         -  /* This case when the file is being statically linked into the 
   572         -  ** application */
   573         -# define SQLITE_EXTENSION_INIT1     /*no-op*/
   574         -# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
   575         -# define SQLITE_EXTENSION_INIT3     /*no-op*/
   576         -#endif
   577         -
   578         -#endif /* SQLITE3EXT_H */

Deleted jni/tcl/pkgs/sqlite3.15.1/configure.

more than 10,000 changes

Deleted jni/tcl/pkgs/sqlite3.15.1/configure.ac.

     1         -#!/bin/bash -norc
     2         -dnl	This file is an input file used by the GNU "autoconf" program to
     3         -dnl	generate the file "configure", which is run during Tcl installation
     4         -dnl	to configure the system for the local environment.
     5         -#
     6         -# RCS: @(#) $Id: configure.in,v 1.43 2005/07/26 19:17:05 mdejong Exp $
     7         -
     8         -#-----------------------------------------------------------------------
     9         -# Sample configure.ac for Tcl Extensions.  The only places you should
    10         -# need to modify this file are marked by the string __CHANGE__
    11         -#-----------------------------------------------------------------------
    12         -
    13         -#-----------------------------------------------------------------------
    14         -# __CHANGE__
    15         -# Set your package name and version numbers here.
    16         -#
    17         -# This initializes the environment with PACKAGE_NAME and PACKAGE_VERSION
    18         -# set as provided.  These will also be added as -D defs in your Makefile
    19         -# so you can encode the package version directly into the source files.
    20         -#-----------------------------------------------------------------------
    21         -
    22         -AC_INIT([sqlite], [3.15.1])
    23         -
    24         -#--------------------------------------------------------------------
    25         -# Call TEA_INIT as the first TEA_ macro to set up initial vars.
    26         -# This will define a ${TEA_PLATFORM} variable == "unix" or "windows"
    27         -# as well as PKG_LIB_FILE and PKG_STUB_LIB_FILE.
    28         -#--------------------------------------------------------------------
    29         -
    30         -TEA_INIT([3.10])
    31         -
    32         -AC_CONFIG_AUX_DIR(tclconfig)
    33         -
    34         -#--------------------------------------------------------------------
    35         -# Load the tclConfig.sh file
    36         -#--------------------------------------------------------------------
    37         -
    38         -TEA_PATH_TCLCONFIG
    39         -TEA_LOAD_TCLCONFIG
    40         -
    41         -#--------------------------------------------------------------------
    42         -# Load the tkConfig.sh file if necessary (Tk extension)
    43         -#--------------------------------------------------------------------
    44         -
    45         -#TEA_PATH_TKCONFIG
    46         -#TEA_LOAD_TKCONFIG
    47         -
    48         -#-----------------------------------------------------------------------
    49         -# Handle the --prefix=... option by defaulting to what Tcl gave.
    50         -# Must be called after TEA_LOAD_TCLCONFIG and before TEA_SETUP_COMPILER.
    51         -#-----------------------------------------------------------------------
    52         -
    53         -TEA_PREFIX
    54         -
    55         -#-----------------------------------------------------------------------
    56         -# Standard compiler checks.
    57         -# This sets up CC by using the CC env var, or looks for gcc otherwise.
    58         -# This also calls AC_PROG_CC, AC_PROG_INSTALL and a few others to create
    59         -# the basic setup necessary to compile executables.
    60         -#-----------------------------------------------------------------------
    61         -
    62         -TEA_SETUP_COMPILER
    63         -
    64         -#-----------------------------------------------------------------------
    65         -# __CHANGE__
    66         -# Specify the C source files to compile in TEA_ADD_SOURCES,
    67         -# public headers that need to be installed in TEA_ADD_HEADERS,
    68         -# stub library C source files to compile in TEA_ADD_STUB_SOURCES,
    69         -# and runtime Tcl library files in TEA_ADD_TCL_SOURCES.
    70         -# This defines PKG(_STUB)_SOURCES, PKG(_STUB)_OBJECTS, PKG_HEADERS
    71         -# and PKG_TCL_SOURCES.
    72         -#-----------------------------------------------------------------------
    73         -
    74         -TEA_ADD_SOURCES([tclsqlite3.c])
    75         -TEA_ADD_HEADERS([])
    76         -TEA_ADD_INCLUDES([-I\"`\${CYGPATH} \${srcdir}/generic`\"])
    77         -TEA_ADD_LIBS([])
    78         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_DBSTAT_VTAB=1])
    79         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS3_PARENTHESIS=1])
    80         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS4=1])
    81         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_FTS5=1])
    82         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_COLUMN_METADATA=1])
    83         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_JSON1=1])
    84         -TEA_ADD_CFLAGS([-DSQLITE_3_SUFFIX_ONLY=1])
    85         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_RTREE=1])
    86         -TEA_ADD_CFLAGS([-DSQLITE_ENABLE_UPDATE_DELETE_LIMIT=1])
    87         -TEA_ADD_CFLAGS([-DSQLITE_LIKE_DOESNT_MATCH_BLOBS=1])
    88         -TEA_ADD_CFLAGS([-DSQLITE_OMIT_BUILTIN_TEST=1])
    89         -TEA_ADD_CFLAGS([-DSQLITE_OMIT_DEPRECATED=1])
    90         -TEA_ADD_CFLAGS([-DSQLITE_OMIT_LOOKASIDE=1])
    91         -TEA_ADD_CFLAGS([-DSQLITE_SECURE_DELETE=1])
    92         -TEA_ADD_CFLAGS([-DSQLITE_SOUNDEX=1])
    93         -TEA_ADD_CFLAGS([-DSQLITE_USE_ALLOCA=1])
    94         -TEA_ADD_CFLAGS([-DSQLITE_WIN32_NO_ANSI=1])
    95         -TEA_ADD_CFLAGS([-DSQLITE_WIN32_GETVERSIONEX=0])
    96         -TEA_ADD_STUB_SOURCES([])
    97         -TEA_ADD_TCL_SOURCES([])
    98         -
    99         -#--------------------------------------------------------------------
   100         -# The --with-system-sqlite causes the TCL bindings to SQLite to use
   101         -# the system shared library for SQLite rather than statically linking
   102         -# against its own private copy.  This is dangerous and leads to
   103         -# undersirable dependences and is not recommended.
   104         -# Patchs from rmax.
   105         -#--------------------------------------------------------------------
   106         -AC_ARG_WITH([system-sqlite],
   107         - [AC_HELP_STRING([--with-system-sqlite],
   108         -   [use a system-supplied libsqlite3 instead of the bundled one])],
   109         - [], [with_system_sqlite=no])
   110         -if test x$with_system_sqlite != xno; then
   111         - AC_CHECK_HEADER([sqlite3.h],
   112         -   [AC_CHECK_LIB([sqlite3],[sqlite3_initialize],
   113         -     [AC_DEFINE(USE_SYSTEM_SQLITE)
   114         -      LIBS="$LIBS -lsqlite3"])])
   115         -fi
   116         -
   117         -#--------------------------------------------------------------------
   118         -# __CHANGE__
   119         -# Choose which headers you need.  Extension authors should try very
   120         -# hard to only rely on the Tcl public header files.  Internal headers
   121         -# contain private data structures and are subject to change without
   122         -# notice.
   123         -# This MUST be called after TEA_LOAD_TCLCONFIG / TEA_LOAD_TKCONFIG
   124         -#--------------------------------------------------------------------
   125         -
   126         -TEA_PUBLIC_TCL_HEADERS
   127         -#TEA_PRIVATE_TCL_HEADERS
   128         -
   129         -#TEA_PUBLIC_TK_HEADERS
   130         -#TEA_PRIVATE_TK_HEADERS
   131         -#TEA_PATH_X
   132         -
   133         -#--------------------------------------------------------------------
   134         -# Check whether --enable-threads or --disable-threads was given.
   135         -# This auto-enables if Tcl was compiled threaded.
   136         -#--------------------------------------------------------------------
   137         -
   138         -TEA_ENABLE_THREADS
   139         -if test "${TCL_THREADS}" = "1" ; then
   140         -    AC_DEFINE(SQLITE_THREADSAFE, 1, [Trigger sqlite threadsafe build])
   141         -    # Not automatically added by Tcl because its assumed Tcl links to them,
   142         -    # but it may not if it isn't really a threaded build.
   143         -    TEA_ADD_LIBS([$THREADS_LIBS])
   144         -else
   145         -    AC_DEFINE(SQLITE_THREADSAFE, 0, [Trigger sqlite non-threadsafe build])
   146         -fi
   147         -
   148         -#--------------------------------------------------------------------
   149         -# The statement below defines a collection of symbols related to
   150         -# building as a shared library instead of a static library.
   151         -#--------------------------------------------------------------------
   152         -
   153         -TEA_ENABLE_SHARED
   154         -
   155         -#--------------------------------------------------------------------
   156         -# This macro figures out what flags to use with the compiler/linker
   157         -# when building shared/static debug/optimized objects.  This information
   158         -# can be taken from the tclConfig.sh file, but this figures it all out.
   159         -#--------------------------------------------------------------------
   160         -
   161         -TEA_CONFIG_CFLAGS
   162         -
   163         -#--------------------------------------------------------------------
   164         -# Set the default compiler switches based on the --enable-symbols option.
   165         -#--------------------------------------------------------------------
   166         -
   167         -TEA_ENABLE_SYMBOLS
   168         -
   169         -#--------------------------------------------------------------------
   170         -# Everyone should be linking against the Tcl stub library.  If you
   171         -# can't for some reason, remove this definition.  If you aren't using
   172         -# stubs, you also need to modify the SHLIB_LD_LIBS setting below to
   173         -# link against the non-stubbed Tcl library.  Add Tk too if necessary.
   174         -#--------------------------------------------------------------------
   175         -
   176         -AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
   177         -#AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
   178         -
   179         -
   180         -#--------------------------------------------------------------------
   181         -# Redefine fdatasync as fsync on systems that lack fdatasync
   182         -#--------------------------------------------------------------------
   183         -#
   184         -#AC_CHECK_FUNC(fdatasync, , AC_DEFINE(fdatasync, fsync))
   185         -AC_CHECK_HEADERS([malloc.h])
   186         -# Check for library functions that SQLite can optionally use.
   187         -AC_CHECK_FUNCS([fdatasync usleep strchrnul localtime_r gmtime_r localtime_s malloc_usable_size utime flock readlink lstat pread pread64 pwrite pwrite64 rand_s])
   188         -
   189         -AC_FUNC_STRERROR_R
   190         -
   191         -
   192         -#--------------------------------------------------------------------
   193         -# This macro generates a line to use when building a library.  It
   194         -# depends on values set by the TEA_ENABLE_SHARED, TEA_ENABLE_SYMBOLS,
   195         -# and TEA_LOAD_TCLCONFIG macros above.
   196         -#--------------------------------------------------------------------
   197         -
   198         -TEA_MAKE_LIB
   199         -
   200         -#--------------------------------------------------------------------
   201         -# Determine the name of the tclsh and/or wish executables in the
   202         -# Tcl and Tk build directories or the location they were installed
   203         -# into. These paths are used to support running test cases only,
   204         -# the Makefile should not be making use of these paths to generate
   205         -# a pkgIndex.tcl file or anything else at extension build time.
   206         -#--------------------------------------------------------------------
   207         -
   208         -TEA_PROG_TCLSH
   209         -#TEA_PROG_WISH
   210         -
   211         -#--------------------------------------------------------------------
   212         -# Finally, substitute all of the various values into the Makefile.
   213         -# You may alternatively have a special pkgIndex.tcl.in or other files
   214         -# which require substituting th AC variables in.  Include these here.
   215         -#--------------------------------------------------------------------
   216         -
   217         -AC_OUTPUT([Makefile pkgIndex.tcl])

Deleted jni/tcl/pkgs/sqlite3.15.1/doc/sqlite3.n.

     1         -.TH sqlite3 n 4.1 "Tcl-Extensions"
     2         -.HS sqlite3 tcl
     3         -.BS
     4         -.SH NAME
     5         -sqlite3 \- an interface to the SQLite3 database engine
     6         -.SH SYNOPSIS
     7         -\fBsqlite3\fI command_name ?filename?\fR
     8         -.br
     9         -.SH DESCRIPTION
    10         -SQLite3 is a self-contains, zero-configuration, transactional SQL database
    11         -engine.  This extension provides an easy to use interface for accessing
    12         -SQLite database files from Tcl.
    13         -.PP
    14         -For full documentation see \fIhttp://www.sqlite.org/\fR and
    15         -in particular \fIhttp://www.sqlite.org/tclsqlite.html\fR.

Deleted jni/tcl/pkgs/sqlite3.15.1/generic/tclsqlite3.c.

     1         -#ifdef USE_SYSTEM_SQLITE
     2         -# include <sqlite3.h>
     3         -#else
     4         -#include "../compat/sqlite3/sqlite3.c"
     5         -#endif
     6         -/*
     7         -** 2001 September 15
     8         -**
     9         -** The author disclaims copyright to this source code.  In place of
    10         -** a legal notice, here is a blessing:
    11         -**
    12         -**    May you do good and not evil.
    13         -**    May you find forgiveness for yourself and forgive others.
    14         -**    May you share freely, never taking more than you give.
    15         -**
    16         -*************************************************************************
    17         -** A TCL Interface to SQLite.  Append this file to sqlite3.c and
    18         -** compile the whole thing to build a TCL-enabled version of SQLite.
    19         -**
    20         -** Compile-time options:
    21         -**
    22         -**  -DTCLSH=1             Add a "main()" routine that works as a tclsh.
    23         -**
    24         -**  -DSQLITE_TCLMD5       When used in conjuction with -DTCLSH=1, add
    25         -**                        four new commands to the TCL interpreter for
    26         -**                        generating MD5 checksums:  md5, md5file,
    27         -**                        md5-10x8, and md5file-10x8.
    28         -**
    29         -**  -DSQLITE_TEST         When used in conjuction with -DTCLSH=1, add
    30         -**                        hundreds of new commands used for testing
    31         -**                        SQLite.  This option implies -DSQLITE_TCLMD5.
    32         -*/
    33         -
    34         -/*
    35         -** If requested, include the SQLite compiler options file for MSVC.
    36         -*/
    37         -#if defined(INCLUDE_MSVC_H)
    38         -# include "msvc.h"
    39         -#endif
    40         -
    41         -#if defined(INCLUDE_SQLITE_TCL_H)
    42         -# include "sqlite_tcl.h"
    43         -#else
    44         -# include "tcl.h"
    45         -# ifndef SQLITE_TCLAPI
    46         -#  define SQLITE_TCLAPI
    47         -# endif
    48         -#endif
    49         -#include <errno.h>
    50         -
    51         -/*
    52         -** Some additional include files are needed if this file is not
    53         -** appended to the amalgamation.
    54         -*/
    55         -#ifndef SQLITE_AMALGAMATION
    56         -# include "sqlite3.h"
    57         -# include <stdlib.h>
    58         -# include <string.h>
    59         -# include <assert.h>
    60         -  typedef unsigned char u8;
    61         -#endif
    62         -#include <ctype.h>
    63         -
    64         -/* Used to get the current process ID */
    65         -#if !defined(_WIN32)
    66         -# include <unistd.h>
    67         -# define GETPID getpid
    68         -#elif !defined(_WIN32_WCE)
    69         -# ifndef SQLITE_AMALGAMATION
    70         -#  define WIN32_LEAN_AND_MEAN
    71         -#  include <windows.h>
    72         -# endif
    73         -# define GETPID (int)GetCurrentProcessId
    74         -#endif
    75         -
    76         -/*
    77         - * If we are not sure the platform is 32-bit, always use sqlite3_????64()
    78         - * in stead of sqlite3_????() for certain functions, in order to prevent overflow.
    79         - */
    80         -#if !defined(i386)     && !defined(__i386__)   && !defined(_M_IX86) && \
    81         -    !defined(_M_ARM)   && !defined(__arm__)    && !defined(__x86) && \
    82         -    (!defined(__SIZEOF_POINTER__) || (__SIZEOF_POINTER__ != 4))
    83         -# undef sqlite3_bind_text
    84         -# undef sqlite3_result_text
    85         -# define sqlite3_bind_text(pStmt, i, zData, nData, xDel) sqlite3_bind_text64(pStmt, i, zData, nData, xDel, SQLITE_UTF8)
    86         -# define sqlite3_result_text(pCtx, z, n, xDel) sqlite3_result_text64(pCtx, z, n, xDel, SQLITE_UTF8)
    87         -#endif
    88         -
    89         -#define NUM_PREPARED_STMTS 10
    90         -#define MAX_PREPARED_STMTS 100
    91         -
    92         -/* Forward declaration */
    93         -typedef struct SqliteDb SqliteDb;
    94         -
    95         -/*
    96         -** New SQL functions can be created as TCL scripts.  Each such function
    97         -** is described by an instance of the following structure.
    98         -*/
    99         -typedef struct SqlFunc SqlFunc;
   100         -struct SqlFunc {
   101         -  Tcl_Interp *interp;   /* The TCL interpret to execute the function */
   102         -  Tcl_Obj *pScript;     /* The Tcl_Obj representation of the script */
   103         -  SqliteDb *pDb;        /* Database connection that owns this function */
   104         -  int useEvalObjv;      /* True if it is safe to use Tcl_EvalObjv */
   105         -  char *zName;          /* Name of this function */
   106         -  SqlFunc *pNext;       /* Next function on the list of them all */
   107         -};
   108         -
   109         -/*
   110         -** New collation sequences function can be created as TCL scripts.  Each such
   111         -** function is described by an instance of the following structure.
   112         -*/
   113         -typedef struct SqlCollate SqlCollate;
   114         -struct SqlCollate {
   115         -  Tcl_Interp *interp;   /* The TCL interpret to execute the function */
   116         -  char *zScript;        /* The script to be run */
   117         -  SqlCollate *pNext;    /* Next function on the list of them all */
   118         -};
   119         -
   120         -/*
   121         -** Prepared statements are cached for faster execution.  Each prepared
   122         -** statement is described by an instance of the following structure.
   123         -*/
   124         -typedef struct SqlPreparedStmt SqlPreparedStmt;
   125         -struct SqlPreparedStmt {
   126         -  SqlPreparedStmt *pNext;  /* Next in linked list */
   127         -  SqlPreparedStmt *pPrev;  /* Previous on the list */
   128         -  sqlite3_stmt *pStmt;     /* The prepared statement */
   129         -  int nSql;                /* chars in zSql[] */
   130         -  const char *zSql;        /* Text of the SQL statement */
   131         -  int nParm;               /* Size of apParm array */
   132         -  Tcl_Obj **apParm;        /* Array of referenced object pointers */
   133         -};
   134         -
   135         -typedef struct IncrblobChannel IncrblobChannel;
   136         -
   137         -/*
   138         -** There is one instance of this structure for each SQLite database
   139         -** that has been opened by the SQLite TCL interface.
   140         -**
   141         -** If this module is built with SQLITE_TEST defined (to create the SQLite
   142         -** testfixture executable), then it may be configured to use either
   143         -** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements.
   144         -** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used.
   145         -*/
   146         -struct SqliteDb {
   147         -  sqlite3 *db;               /* The "real" database structure. MUST BE FIRST */
   148         -  Tcl_Interp *interp;        /* The interpreter used for this database */
   149         -  char *zBusy;               /* The busy callback routine */
   150         -  char *zCommit;             /* The commit hook callback routine */
   151         -  char *zTrace;              /* The trace callback routine */
   152         -  char *zTraceV2;            /* The trace_v2 callback routine */
   153         -  char *zProfile;            /* The profile callback routine */
   154         -  char *zProgress;           /* The progress callback routine */
   155         -  char *zAuth;               /* The authorization callback routine */
   156         -  int disableAuth;           /* Disable the authorizer if it exists */
   157         -  char *zNull;               /* Text to substitute for an SQL NULL value */
   158         -  SqlFunc *pFunc;            /* List of SQL functions */
   159         -  Tcl_Obj *pUpdateHook;      /* Update hook script (if any) */
   160         -  Tcl_Obj *pPreUpdateHook;   /* Pre-update hook script (if any) */
   161         -  Tcl_Obj *pRollbackHook;    /* Rollback hook script (if any) */
   162         -  Tcl_Obj *pWalHook;         /* WAL hook script (if any) */
   163         -  Tcl_Obj *pUnlockNotify;    /* Unlock notify script (if any) */
   164         -  SqlCollate *pCollate;      /* List of SQL collation functions */
   165         -  int rc;                    /* Return code of most recent sqlite3_exec() */
   166         -  Tcl_Obj *pCollateNeeded;   /* Collation needed script */
   167         -  SqlPreparedStmt *stmtList; /* List of prepared statements*/
   168         -  SqlPreparedStmt *stmtLast; /* Last statement in the list */
   169         -  int maxStmt;               /* The next maximum number of stmtList */
   170         -  int nStmt;                 /* Number of statements in stmtList */
   171         -  IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */
   172         -  int nStep, nSort, nIndex;  /* Statistics for most recent operation */
   173         -  int nTransaction;          /* Number of nested [transaction] methods */
   174         -  int openFlags;             /* Flags used to open.  (SQLITE_OPEN_URI) */
   175         -#ifdef SQLITE_TEST
   176         -  int bLegacyPrepare;        /* True to use sqlite3_prepare() */
   177         -#endif
   178         -};
   179         -
   180         -struct IncrblobChannel {
   181         -  sqlite3_blob *pBlob;      /* sqlite3 blob handle */
   182         -  SqliteDb *pDb;            /* Associated database connection */
   183         -  int iSeek;                /* Current seek offset */
   184         -  Tcl_Channel channel;      /* Channel identifier */
   185         -  IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
   186         -  IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
   187         -};
   188         -
   189         -/*
   190         -** Compute a string length that is limited to what can be stored in
   191         -** lower 30 bits of a 32-bit signed integer.
   192         -*/
   193         -static int strlen30(const char *z){
   194         -  const char *z2 = z;
   195         -  while( *z2 ){ z2++; }
   196         -  return 0x3fffffff & (int)(z2 - z);
   197         -}
   198         -
   199         -#ifdef USE_TCL_STUBS
   200         -# define tclStubsPtr staticTclStubsPtr
   201         -static const TclStubs *tclStubsPtr = 0;
   202         -#endif
   203         -
   204         -#ifndef SQLITE_OMIT_INCRBLOB
   205         -/*
   206         -** Close all incrblob channels opened using database connection pDb.
   207         -** This is called when shutting down the database connection.
   208         -*/
   209         -static void closeIncrblobChannels(SqliteDb *pDb){
   210         -  IncrblobChannel *p;
   211         -  IncrblobChannel *pNext;
   212         -
   213         -  for(p=pDb->pIncrblob; p; p=pNext){
   214         -    pNext = p->pNext;
   215         -
   216         -    /* Note: Calling unregister here call Tcl_Close on the incrblob channel,
   217         -    ** which deletes the IncrblobChannel structure at *p. So do not
   218         -    ** call Tcl_Free() here.
   219         -    */
   220         -    Tcl_UnregisterChannel(pDb->interp, p->channel);
   221         -  }
   222         -}
   223         -
   224         -/*
   225         -** Close an incremental blob channel.
   226         -*/
   227         -static int SQLITE_TCLAPI incrblobClose(
   228         -  ClientData instanceData,
   229         -  Tcl_Interp *interp
   230         -){
   231         -  IncrblobChannel *p = (IncrblobChannel *)instanceData;
   232         -  int rc = sqlite3_blob_close(p->pBlob);
   233         -  sqlite3 *db = p->pDb->db;
   234         -
   235         -  /* Remove the channel from the SqliteDb.pIncrblob list. */
   236         -  if( p->pNext ){
   237         -    p->pNext->pPrev = p->pPrev;
   238         -  }
   239         -  if( p->pPrev ){
   240         -    p->pPrev->pNext = p->pNext;
   241         -  }
   242         -  if( p->pDb->pIncrblob==p ){
   243         -    p->pDb->pIncrblob = p->pNext;
   244         -  }
   245         -
   246         -  /* Free the IncrblobChannel structure */
   247         -  Tcl_Free((char *)p);
   248         -
   249         -  if( rc!=SQLITE_OK ){
   250         -    Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
   251         -    return TCL_ERROR;
   252         -  }
   253         -  return TCL_OK;
   254         -}
   255         -
   256         -/*
   257         -** Read data from an incremental blob channel.
   258         -*/
   259         -static int SQLITE_TCLAPI incrblobInput(
   260         -  ClientData instanceData,
   261         -  char *buf,
   262         -  int bufSize,
   263         -  int *errorCodePtr
   264         -){
   265         -  IncrblobChannel *p = (IncrblobChannel *)instanceData;
   266         -  int nRead = bufSize;         /* Number of bytes to read */
   267         -  int nBlob;                   /* Total size of the blob */
   268         -  int rc;                      /* sqlite error code */
   269         -
   270         -  nBlob = sqlite3_blob_bytes(p->pBlob);
   271         -  if( (p->iSeek+nRead)>nBlob ){
   272         -    nRead = nBlob-p->iSeek;
   273         -  }
   274         -  if( nRead<=0 ){
   275         -    return 0;
   276         -  }
   277         -
   278         -  rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek);
   279         -  if( rc!=SQLITE_OK ){
   280         -    *errorCodePtr = rc;
   281         -    return -1;
   282         -  }
   283         -
   284         -  p->iSeek += nRead;
   285         -  return nRead;
   286         -}
   287         -
   288         -/*
   289         -** Write data to an incremental blob channel.
   290         -*/
   291         -static int SQLITE_TCLAPI incrblobOutput(
   292         -  ClientData instanceData,
   293         -  const char *buf,
   294         -  int toWrite,
   295         -  int *errorCodePtr
   296         -){
   297         -  IncrblobChannel *p = (IncrblobChannel *)instanceData;
   298         -  int nWrite = toWrite;        /* Number of bytes to write */
   299         -  int nBlob;                   /* Total size of the blob */
   300         -  int rc;                      /* sqlite error code */
   301         -
   302         -  nBlob = sqlite3_blob_bytes(p->pBlob);
   303         -  if( (p->iSeek+nWrite)>nBlob ){
   304         -    *errorCodePtr = EINVAL;
   305         -    return -1;
   306         -  }
   307         -  if( nWrite<=0 ){
   308         -    return 0;
   309         -  }
   310         -
   311         -  rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek);
   312         -  if( rc!=SQLITE_OK ){
   313         -    *errorCodePtr = EIO;
   314         -    return -1;
   315         -  }
   316         -
   317         -  p->iSeek += nWrite;
   318         -  return nWrite;
   319         -}
   320         -
   321         -/*
   322         -** Seek an incremental blob channel.
   323         -*/
   324         -static int SQLITE_TCLAPI incrblobSeek(
   325         -  ClientData instanceData,
   326         -  long offset,
   327         -  int seekMode,
   328         -  int *errorCodePtr
   329         -){
   330         -  IncrblobChannel *p = (IncrblobChannel *)instanceData;
   331         -
   332         -  switch( seekMode ){
   333         -    case SEEK_SET:
   334         -      p->iSeek = offset;
   335         -      break;
   336         -    case SEEK_CUR:
   337         -      p->iSeek += offset;
   338         -      break;
   339         -    case SEEK_END:
   340         -      p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
   341         -      break;
   342         -
   343         -    default: assert(!"Bad seekMode");
   344         -  }
   345         -
   346         -  return p->iSeek;
   347         -}
   348         -
   349         -
   350         -static void SQLITE_TCLAPI incrblobWatch(
   351         -  ClientData instanceData,
   352         -  int mode
   353         -){
   354         -  /* NO-OP */
   355         -}
   356         -static int SQLITE_TCLAPI incrblobHandle(
   357         -  ClientData instanceData,
   358         -  int dir,
   359         -  ClientData *hPtr
   360         -){
   361         -  return TCL_ERROR;
   362         -}
   363         -
   364         -static Tcl_ChannelType IncrblobChannelType = {
   365         -  "incrblob",                        /* typeName                             */
   366         -  TCL_CHANNEL_VERSION_2,             /* version                              */
   367         -  incrblobClose,                     /* closeProc                            */
   368         -  incrblobInput,                     /* inputProc                            */
   369         -  incrblobOutput,                    /* outputProc                           */
   370         -  incrblobSeek,                      /* seekProc                             */
   371         -  0,                                 /* setOptionProc                        */
   372         -  0,                                 /* getOptionProc                        */
   373         -  incrblobWatch,                     /* watchProc (this is a no-op)          */
   374         -  incrblobHandle,                    /* getHandleProc (always returns error) */
   375         -  0,                                 /* close2Proc                           */
   376         -  0,                                 /* blockModeProc                        */
   377         -  0,                                 /* flushProc                            */
   378         -  0,                                 /* handlerProc                          */
   379         -  0,                                 /* wideSeekProc                         */
   380         -};
   381         -
   382         -/*
   383         -** Create a new incrblob channel.
   384         -*/
   385         -static int createIncrblobChannel(
   386         -  Tcl_Interp *interp,
   387         -  SqliteDb *pDb,
   388         -  const char *zDb,
   389         -  const char *zTable,
   390         -  const char *zColumn,
   391         -  sqlite_int64 iRow,
   392         -  int isReadonly
   393         -){
   394         -  IncrblobChannel *p;
   395         -  sqlite3 *db = pDb->db;
   396         -  sqlite3_blob *pBlob;
   397         -  int rc;
   398         -  int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE);
   399         -
   400         -  /* This variable is used to name the channels: "incrblob_[incr count]" */
   401         -  static int count = 0;
   402         -  char zChannel[64];
   403         -
   404         -  rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob);
   405         -  if( rc!=SQLITE_OK ){
   406         -    Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE);
   407         -    return TCL_ERROR;
   408         -  }
   409         -
   410         -  p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel));
   411         -  p->iSeek = 0;
   412         -  p->pBlob = pBlob;
   413         -
   414         -  sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count);
   415         -  p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags);
   416         -  Tcl_RegisterChannel(interp, p->channel);
   417         -
   418         -  /* Link the new channel into the SqliteDb.pIncrblob list. */
   419         -  p->pNext = pDb->pIncrblob;
   420         -  p->pPrev = 0;
   421         -  if( p->pNext ){
   422         -    p->pNext->pPrev = p;
   423         -  }
   424         -  pDb->pIncrblob = p;
   425         -  p->pDb = pDb;
   426         -
   427         -  Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE);
   428         -  return TCL_OK;
   429         -}
   430         -#else  /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */
   431         -  #define closeIncrblobChannels(pDb)
   432         -#endif
   433         -
   434         -/*
   435         -** Look at the script prefix in pCmd.  We will be executing this script
   436         -** after first appending one or more arguments.  This routine analyzes
   437         -** the script to see if it is safe to use Tcl_EvalObjv() on the script
   438         -** rather than the more general Tcl_EvalEx().  Tcl_EvalObjv() is much
   439         -** faster.
   440         -**
   441         -** Scripts that are safe to use with Tcl_EvalObjv() consists of a
   442         -** command name followed by zero or more arguments with no [...] or $
   443         -** or {...} or ; to be seen anywhere.  Most callback scripts consist
   444         -** of just a single procedure name and they meet this requirement.
   445         -*/
   446         -static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
   447         -  /* We could try to do something with Tcl_Parse().  But we will instead
   448         -  ** just do a search for forbidden characters.  If any of the forbidden
   449         -  ** characters appear in pCmd, we will report the string as unsafe.
   450         -  */
   451         -  const char *z;
   452         -  int n;
   453         -  z = Tcl_GetStringFromObj(pCmd, &n);
   454         -  while( n-- > 0 ){
   455         -    int c = *(z++);
   456         -    if( c=='$' || c=='[' || c==';' ) return 0;
   457         -  }
   458         -  return 1;
   459         -}
   460         -
   461         -/*
   462         -** Find an SqlFunc structure with the given name.  Or create a new
   463         -** one if an existing one cannot be found.  Return a pointer to the
   464         -** structure.
   465         -*/
   466         -static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){
   467         -  SqlFunc *p, *pNew;
   468         -  int nName = strlen30(zName);
   469         -  pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + nName + 1 );
   470         -  pNew->zName = (char*)&pNew[1];
   471         -  memcpy(pNew->zName, zName, nName+1);
   472         -  for(p=pDb->pFunc; p; p=p->pNext){
   473         -    if( sqlite3_stricmp(p->zName, pNew->zName)==0 ){
   474         -      Tcl_Free((char*)pNew);
   475         -      return p;
   476         -    }
   477         -  }
   478         -  pNew->interp = pDb->interp;
   479         -  pNew->pDb = pDb;
   480         -  pNew->pScript = 0;
   481         -  pNew->pNext = pDb->pFunc;
   482         -  pDb->pFunc = pNew;
   483         -  return pNew;
   484         -}
   485         -
   486         -/*
   487         -** Free a single SqlPreparedStmt object.
   488         -*/
   489         -static void dbFreeStmt(SqlPreparedStmt *pStmt){
   490         -#ifdef SQLITE_TEST
   491         -  if( sqlite3_sql(pStmt->pStmt)==0 ){
   492         -    Tcl_Free((char *)pStmt->zSql);
   493         -  }
   494         -#endif
   495         -  sqlite3_finalize(pStmt->pStmt);
   496         -  Tcl_Free((char *)pStmt);
   497         -}
   498         -
   499         -/*
   500         -** Finalize and free a list of prepared statements
   501         -*/
   502         -static void flushStmtCache(SqliteDb *pDb){
   503         -  SqlPreparedStmt *pPreStmt;
   504         -  SqlPreparedStmt *pNext;
   505         -
   506         -  for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){
   507         -    pNext = pPreStmt->pNext;
   508         -    dbFreeStmt(pPreStmt);
   509         -  }
   510         -  pDb->nStmt = 0;
   511         -  pDb->stmtLast = 0;
   512         -  pDb->stmtList = 0;
   513         -}
   514         -
   515         -/*
   516         -** TCL calls this procedure when an sqlite3 database command is
   517         -** deleted.
   518         -*/
   519         -static void SQLITE_TCLAPI DbDeleteCmd(void *db){
   520         -  SqliteDb *pDb = (SqliteDb*)db;
   521         -  flushStmtCache(pDb);
   522         -  closeIncrblobChannels(pDb);
   523         -  sqlite3_close(pDb->db);
   524         -  while( pDb->pFunc ){
   525         -    SqlFunc *pFunc = pDb->pFunc;
   526         -    pDb->pFunc = pFunc->pNext;
   527         -    assert( pFunc->pDb==pDb );
   528         -    Tcl_DecrRefCount(pFunc->pScript);
   529         -    Tcl_Free((char*)pFunc);
   530         -  }
   531         -  while( pDb->pCollate ){
   532         -    SqlCollate *pCollate = pDb->pCollate;
   533         -    pDb->pCollate = pCollate->pNext;
   534         -    Tcl_Free((char*)pCollate);
   535         -  }
   536         -  if( pDb->zBusy ){
   537         -    Tcl_Free(pDb->zBusy);
   538         -  }
   539         -  if( pDb->zTrace ){
   540         -    Tcl_Free(pDb->zTrace);
   541         -  }
   542         -  if( pDb->zTraceV2 ){
   543         -    Tcl_Free(pDb->zTraceV2);
   544         -  }
   545         -  if( pDb->zProfile ){
   546         -    Tcl_Free(pDb->zProfile);
   547         -  }
   548         -  if( pDb->zAuth ){
   549         -    Tcl_Free(pDb->zAuth);
   550         -  }
   551         -  if( pDb->zNull ){
   552         -    Tcl_Free(pDb->zNull);
   553         -  }
   554         -  if( pDb->pUpdateHook ){
   555         -    Tcl_DecrRefCount(pDb->pUpdateHook);
   556         -  }
   557         -  if( pDb->pPreUpdateHook ){
   558         -    Tcl_DecrRefCount(pDb->pPreUpdateHook);
   559         -  }
   560         -  if( pDb->pRollbackHook ){
   561         -    Tcl_DecrRefCount(pDb->pRollbackHook);
   562         -  }
   563         -  if( pDb->pWalHook ){
   564         -    Tcl_DecrRefCount(pDb->pWalHook);
   565         -  }
   566         -  if( pDb->pCollateNeeded ){
   567         -    Tcl_DecrRefCount(pDb->pCollateNeeded);
   568         -  }
   569         -  Tcl_Free((char*)pDb);
   570         -}
   571         -
   572         -/*
   573         -** This routine is called when a database file is locked while trying
   574         -** to execute SQL.
   575         -*/
   576         -static int DbBusyHandler(void *cd, int nTries){
   577         -  SqliteDb *pDb = (SqliteDb*)cd;
   578         -  int rc;
   579         -  char zVal[32];
   580         -  Tcl_DString dstring;
   581         -
   582         -  sqlite3_snprintf(sizeof(zVal), zVal, " %d", nTries);
   583         -  Tcl_DStringInit(&dstring);
   584         -  Tcl_DStringAppend(&dstring, pDb->zBusy, -1);
   585         -  Tcl_DStringAppend(&dstring, zVal, -1);
   586         -  rc = Tcl_EvalEx(pDb->interp, Tcl_DStringValue(&dstring),
   587         -      Tcl_DStringLength(&dstring), TCL_EVAL_GLOBAL);
   588         -  Tcl_DStringFree(&dstring);
   589         -  if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
   590         -    return 0;
   591         -  }
   592         -  return 1;
   593         -}
   594         -
   595         -#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   596         -/*
   597         -** This routine is invoked as the 'progress callback' for the database.
   598         -*/
   599         -static int DbProgressHandler(void *cd){
   600         -  SqliteDb *pDb = (SqliteDb*)cd;
   601         -  int rc;
   602         -
   603         -  assert( pDb->zProgress );
   604         -  rc = Tcl_EvalEx(pDb->interp, pDb->zProgress, -1, 0);
   605         -  if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
   606         -    return 1;
   607         -  }
   608         -  return 0;
   609         -}
   610         -#endif
   611         -
   612         -#ifndef SQLITE_OMIT_TRACE
   613         -/*
   614         -** This routine is called by the SQLite trace handler whenever a new
   615         -** block of SQL is executed.  The TCL script in pDb->zTrace is executed.
   616         -*/
   617         -static int DbTraceHandler(
   618         -  unsigned type, /* One of the SQLITE_TRACE_* event types. */
   619         -  void *cd,      /* The original context data pointer. */
   620         -  void *pd,      /* Primary event data, depends on event type. */
   621         -  void *xd       /* Extra event data, depends on event type. */
   622         -){
   623         -  SqliteDb *pDb = (SqliteDb*)cd;
   624         -  Tcl_DString str;
   625         -
   626         -  Tcl_DStringInit(&str);
   627         -  Tcl_DStringAppend(&str, pDb->zTrace, -1);
   628         -  Tcl_DStringAppendElement(&str, (char *)xd);
   629         -  Tcl_EvalEx(pDb->interp, Tcl_DStringValue(&str), -1, 0);
   630         -  Tcl_DStringFree(&str);
   631         -  Tcl_ResetResult(pDb->interp);
   632         -  return TCL_OK;
   633         -}
   634         -#endif
   635         -
   636         -#ifndef SQLITE_OMIT_TRACE
   637         -/*
   638         -** This routine is called by the SQLite trace_v2 handler whenever a new
   639         -** supported event is generated.  Unsupported event types are ignored.
   640         -** The TCL script in pDb->zTraceV2 is executed, with the arguments for
   641         -** the event appended to it (as list elements).
   642         -*/
   643         -static int DbTraceV2Handler(
   644         -  unsigned type, /* One of the SQLITE_TRACE_* event types. */
   645         -  void *cd,      /* The original context data pointer. */
   646         -  void *pd,      /* Primary event data, depends on event type. */
   647         -  void *xd       /* Extra event data, depends on event type. */
   648         -){
   649         -  SqliteDb *pDb = (SqliteDb*)cd;
   650         -  Tcl_Obj *pCmd;
   651         -
   652         -  switch( type ){
   653         -    case SQLITE_TRACE_STMT: {
   654         -      sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
   655         -      char *zSql = (char *)xd;
   656         -
   657         -      pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
   658         -      Tcl_IncrRefCount(pCmd);
   659         -      Tcl_ListObjAppendElement(pDb->interp, pCmd,
   660         -                               Tcl_NewWideIntObj((Tcl_WideInt)(size_t)pStmt));
   661         -      Tcl_ListObjAppendElement(pDb->interp, pCmd,
   662         -                               Tcl_NewStringObj(zSql, -1));
   663         -      Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
   664         -      Tcl_DecrRefCount(pCmd);
   665         -      Tcl_ResetResult(pDb->interp);
   666         -      break;
   667         -    }
   668         -    case SQLITE_TRACE_PROFILE: {
   669         -      sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
   670         -      size_t ns = (size_t)xd;
   671         -
   672         -      pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
   673         -      Tcl_IncrRefCount(pCmd);
   674         -      Tcl_ListObjAppendElement(pDb->interp, pCmd,
   675         -                               Tcl_NewWideIntObj((Tcl_WideInt)(size_t)pStmt));
   676         -      Tcl_ListObjAppendElement(pDb->interp, pCmd,
   677         -                               Tcl_NewWideIntObj((Tcl_WideInt)ns));
   678         -      Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
   679         -      Tcl_DecrRefCount(pCmd);
   680         -      Tcl_ResetResult(pDb->interp);
   681         -      break;
   682         -    }
   683         -    case SQLITE_TRACE_ROW: {
   684         -      sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
   685         -
   686         -      pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
   687         -      Tcl_IncrRefCount(pCmd);
   688         -      Tcl_ListObjAppendElement(pDb->interp, pCmd,
   689         -                               Tcl_NewWideIntObj((Tcl_WideInt)(size_t)pStmt));
   690         -      Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
   691         -      Tcl_DecrRefCount(pCmd);
   692         -      Tcl_ResetResult(pDb->interp);
   693         -      break;
   694         -    }
   695         -    case SQLITE_TRACE_CLOSE: {
   696         -      sqlite3 *db = (sqlite3 *)pd;
   697         -
   698         -      pCmd = Tcl_NewStringObj(pDb->zTraceV2, -1);
   699         -      Tcl_IncrRefCount(pCmd);
   700         -      Tcl_ListObjAppendElement(pDb->interp, pCmd,
   701         -                               Tcl_NewWideIntObj((Tcl_WideInt)(size_t)db));
   702         -      Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
   703         -      Tcl_DecrRefCount(pCmd);
   704         -      Tcl_ResetResult(pDb->interp);
   705         -      break;
   706         -    }
   707         -  }
   708         -  return SQLITE_OK;
   709         -}
   710         -#endif
   711         -
   712         -#ifndef SQLITE_OMIT_TRACE
   713         -/*
   714         -** This routine is called by the SQLite profile handler after a statement
   715         -** SQL has executed.  The TCL script in pDb->zProfile is evaluated.
   716         -*/
   717         -static int DbProfileHandler(
   718         -  unsigned type, /* One of the SQLITE_TRACE_* event types. */
   719         -  void *cd,      /* The original context data pointer. */
   720         -  void *pd,      /* Primary event data, depends on event type. */
   721         -  void *xd       /* Extra event data, depends on event type. */
   722         -){
   723         -  SqliteDb *pDb = (SqliteDb*)cd;
   724         -  Tcl_DString str;
   725         -  char zTm[100];
   726         -  sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;  
   727         -
   728         -  sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", (Tcl_WideInt)(size_t)xd);
   729         -  Tcl_DStringInit(&str);
   730         -  Tcl_DStringAppend(&str, pDb->zProfile, -1);
   731         -  Tcl_DStringAppendElement(&str, sqlite3_sql(pStmt));
   732         -  Tcl_DStringAppendElement(&str, zTm);
   733         -  Tcl_EvalEx(pDb->interp, Tcl_DStringValue(&str), -1, 0);
   734         -  Tcl_DStringFree(&str);
   735         -  Tcl_ResetResult(pDb->interp);
   736         -  return SQLITE_OK;
   737         -}
   738         -#endif
   739         -
   740         -/*
   741         -** This routine is called when a transaction is committed.  The
   742         -** TCL script in pDb->zCommit is executed.  If it returns non-zero or
   743         -** if it throws an exception, the transaction is rolled back instead
   744         -** of being committed.
   745         -*/
   746         -static int DbCommitHandler(void *cd){
   747         -  SqliteDb *pDb = (SqliteDb*)cd;
   748         -  int rc;
   749         -
   750         -  rc = Tcl_EvalEx(pDb->interp, pDb->zCommit, -1, 0);
   751         -  if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){
   752         -    return 1;
   753         -  }
   754         -  return 0;
   755         -}
   756         -
   757         -static void DbRollbackHandler(void *clientData){
   758         -  SqliteDb *pDb = (SqliteDb*)clientData;
   759         -  assert(pDb->pRollbackHook);
   760         -  if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){
   761         -    Tcl_BackgroundError(pDb->interp);
   762         -  }
   763         -}
   764         -
   765         -/*
   766         -** This procedure handles wal_hook callbacks.
   767         -*/
   768         -static int DbWalHandler(
   769         -  void *clientData,
   770         -  sqlite3 *db,
   771         -  const char *zDb,
   772         -  int nEntry
   773         -){
   774         -  int ret = SQLITE_OK;
   775         -  Tcl_Obj *p;
   776         -  SqliteDb *pDb = (SqliteDb*)clientData;
   777         -  Tcl_Interp *interp = pDb->interp;
   778         -  assert(pDb->pWalHook);
   779         -
   780         -  assert( db==pDb->db );
   781         -  p = Tcl_DuplicateObj(pDb->pWalHook);
   782         -  Tcl_IncrRefCount(p);
   783         -  Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1));
   784         -  Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry));
   785         -  if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0)
   786         -   || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret)
   787         -  ){
   788         -    Tcl_BackgroundError(interp);
   789         -  }
   790         -  Tcl_DecrRefCount(p);
   791         -
   792         -  return ret;
   793         -}
   794         -
   795         -#if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY)
   796         -static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){
   797         -  char zBuf[64];
   798         -  sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", iArg);
   799         -  Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY);
   800         -  sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", nArg);
   801         -  Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY);
   802         -}
   803         -#else
   804         -# define setTestUnlockNotifyVars(x,y,z)
   805         -#endif
   806         -
   807         -#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
   808         -static void DbUnlockNotify(void **apArg, int nArg){
   809         -  int i;
   810         -  for(i=0; i<nArg; i++){
   811         -    const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT);
   812         -    SqliteDb *pDb = (SqliteDb *)apArg[i];
   813         -    setTestUnlockNotifyVars(pDb->interp, i, nArg);
   814         -    assert( pDb->pUnlockNotify);
   815         -    Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags);
   816         -    Tcl_DecrRefCount(pDb->pUnlockNotify);
   817         -    pDb->pUnlockNotify = 0;
   818         -  }
   819         -}
   820         -#endif
   821         -
   822         -#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   823         -/*
   824         -** Pre-update hook callback.
   825         -*/
   826         -static void DbPreUpdateHandler(
   827         -  void *p,
   828         -  sqlite3 *db,
   829         -  int op,
   830         -  const char *zDb,
   831         -  const char *zTbl,
   832         -  sqlite_int64 iKey1,
   833         -  sqlite_int64 iKey2
   834         -){
   835         -  SqliteDb *pDb = (SqliteDb *)p;
   836         -  Tcl_Obj *pCmd;
   837         -  static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
   838         -
   839         -  assert( (SQLITE_DELETE-1)/9 == 0 );
   840         -  assert( (SQLITE_INSERT-1)/9 == 1 );
   841         -  assert( (SQLITE_UPDATE-1)/9 == 2 );
   842         -  assert( pDb->pPreUpdateHook );
   843         -  assert( db==pDb->db );
   844         -  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
   845         -
   846         -  pCmd = Tcl_DuplicateObj(pDb->pPreUpdateHook);
   847         -  Tcl_IncrRefCount(pCmd);
   848         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
   849         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
   850         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
   851         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey1));
   852         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(iKey2));
   853         -  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
   854         -  Tcl_DecrRefCount(pCmd);
   855         -}
   856         -#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
   857         -
   858         -static void DbUpdateHandler(
   859         -  void *p,
   860         -  int op,
   861         -  const char *zDb,
   862         -  const char *zTbl,
   863         -  sqlite_int64 rowid
   864         -){
   865         -  SqliteDb *pDb = (SqliteDb *)p;
   866         -  Tcl_Obj *pCmd;
   867         -  static const char *azStr[] = {"DELETE", "INSERT", "UPDATE"};
   868         -
   869         -  assert( (SQLITE_DELETE-1)/9 == 0 );
   870         -  assert( (SQLITE_INSERT-1)/9 == 1 );
   871         -  assert( (SQLITE_UPDATE-1)/9 == 2 );
   872         -
   873         -  assert( pDb->pUpdateHook );
   874         -  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
   875         -
   876         -  pCmd = Tcl_DuplicateObj(pDb->pUpdateHook);
   877         -  Tcl_IncrRefCount(pCmd);
   878         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(azStr[(op-1)/9], -1));
   879         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1));
   880         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1));
   881         -  Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid));
   882         -  Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT);
   883         -  Tcl_DecrRefCount(pCmd);
   884         -}
   885         -
   886         -static void tclCollateNeeded(
   887         -  void *pCtx,
   888         -  sqlite3 *db,
   889         -  int enc,
   890         -  const char *zName
   891         -){
   892         -  SqliteDb *pDb = (SqliteDb *)pCtx;
   893         -  Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
   894         -  Tcl_IncrRefCount(pScript);
   895         -  Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
   896         -  Tcl_EvalObjEx(pDb->interp, pScript, 0);
   897         -  Tcl_DecrRefCount(pScript);
   898         -}
   899         -
   900         -/*
   901         -** This routine is called to evaluate an SQL collation function implemented
   902         -** using TCL script.
   903         -*/
   904         -static int tclSqlCollate(
   905         -  void *pCtx,
   906         -  int nA,
   907         -  const void *zA,
   908         -  int nB,
   909         -  const void *zB
   910         -){
   911         -  SqlCollate *p = (SqlCollate *)pCtx;
   912         -  Tcl_Obj *pCmd;
   913         -
   914         -  pCmd = Tcl_NewStringObj(p->zScript, -1);
   915         -  Tcl_IncrRefCount(pCmd);
   916         -  Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA));
   917         -  Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB));
   918         -  Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
   919         -  Tcl_DecrRefCount(pCmd);
   920         -  return (atoi(Tcl_GetStringResult(p->interp)));
   921         -}
   922         -
   923         -/*
   924         -** This routine is called to evaluate an SQL function implemented
   925         -** using TCL script.
   926         -*/
   927         -static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
   928         -  SqlFunc *p = sqlite3_user_data(context);
   929         -  Tcl_Obj *pCmd;
   930         -  int i;
   931         -  int rc;
   932         -
   933         -  if( argc==0 ){
   934         -    /* If there are no arguments to the function, call Tcl_EvalObjEx on the
   935         -    ** script object directly.  This allows the TCL compiler to generate
   936         -    ** bytecode for the command on the first invocation and thus make
   937         -    ** subsequent invocations much faster. */
   938         -    pCmd = p->pScript;
   939         -    Tcl_IncrRefCount(pCmd);
   940         -    rc = Tcl_EvalObjEx(p->interp, pCmd, 0);
   941         -    Tcl_DecrRefCount(pCmd);
   942         -  }else{
   943         -    /* If there are arguments to the function, make a shallow copy of the
   944         -    ** script object, lappend the arguments, then evaluate the copy.
   945         -    **
   946         -    ** By "shallow" copy, we mean only the outer list Tcl_Obj is duplicated.
   947         -    ** The new Tcl_Obj contains pointers to the original list elements.
   948         -    ** That way, when Tcl_EvalObjv() is run and shimmers the first element
   949         -    ** of the list to tclCmdNameType, that alternate representation will
   950         -    ** be preserved and reused on the next invocation.
   951         -    */
   952         -    Tcl_Obj **aArg;
   953         -    int nArg;
   954         -    if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){
   955         -      sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
   956         -      return;
   957         -    }
   958         -    pCmd = Tcl_NewListObj(nArg, aArg);
   959         -    Tcl_IncrRefCount(pCmd);
   960         -    for(i=0; i<argc; i++){
   961         -      sqlite3_value *pIn = argv[i];
   962         -      Tcl_Obj *pVal;
   963         -
   964         -      /* Set pVal to contain the i'th column of this row. */
   965         -      switch( sqlite3_value_type(pIn) ){
   966         -        case SQLITE_BLOB: {
   967         -          int bytes = sqlite3_value_bytes(pIn);
   968         -          pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes);
   969         -          break;
   970         -        }
   971         -        case SQLITE_INTEGER: {
   972         -          sqlite_int64 v = sqlite3_value_int64(pIn);
   973         -          if( v>=-2147483647 && v<=2147483647 ){
   974         -            pVal = Tcl_NewIntObj((int)v);
   975         -          }else{
   976         -            pVal = Tcl_NewWideIntObj(v);
   977         -          }
   978         -          break;
   979         -        }
   980         -        case SQLITE_FLOAT: {
   981         -          double r = sqlite3_value_double(pIn);
   982         -          pVal = Tcl_NewDoubleObj(r);
   983         -          break;
   984         -        }
   985         -        case SQLITE_NULL: {
   986         -          pVal = Tcl_NewStringObj(p->pDb->zNull, -1);
   987         -          break;
   988         -        }
   989         -        default: {
   990         -          int bytes = sqlite3_value_bytes(pIn);
   991         -          pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes);
   992         -          break;
   993         -        }
   994         -      }
   995         -      rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal);
   996         -      if( rc ){
   997         -        Tcl_DecrRefCount(pCmd);
   998         -        sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
   999         -        return;
  1000         -      }
  1001         -    }
  1002         -    if( !p->useEvalObjv ){
  1003         -      /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd
  1004         -      ** is a list without a string representation.  To prevent this from
  1005         -      ** happening, make sure pCmd has a valid string representation */
  1006         -      Tcl_GetString(pCmd);
  1007         -    }
  1008         -    rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT);
  1009         -    Tcl_DecrRefCount(pCmd);
  1010         -  }
  1011         -
  1012         -  if( rc && rc!=TCL_RETURN ){
  1013         -    sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1);
  1014         -  }else{
  1015         -    Tcl_Obj *pVar = Tcl_GetObjResult(p->interp);
  1016         -    int n;
  1017         -    u8 *data;
  1018         -    const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
  1019         -    char c = zType[0];
  1020         -    if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
  1021         -      /* Only return a BLOB type if the Tcl variable is a bytearray and
  1022         -      ** has no string representation. */
  1023         -      data = Tcl_GetByteArrayFromObj(pVar, &n);
  1024         -      sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT);
  1025         -    }else if( c=='b' && strcmp(zType,"boolean")==0 ){
  1026         -      Tcl_GetIntFromObj(0, pVar, &n);
  1027         -      sqlite3_result_int(context, n);
  1028         -    }else if( c=='d' && strcmp(zType,"double")==0 ){
  1029         -      double r;
  1030         -      Tcl_GetDoubleFromObj(0, pVar, &r);
  1031         -      sqlite3_result_double(context, r);
  1032         -    }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
  1033         -          (c=='i' && strcmp(zType,"int")==0) ){
  1034         -      Tcl_WideInt v;
  1035         -      Tcl_GetWideIntFromObj(0, pVar, &v);
  1036         -      sqlite3_result_int64(context, v);
  1037         -    }else{
  1038         -      data = (unsigned char *)Tcl_GetString(pVar);
  1039         -      sqlite3_result_text(context, (char *)data, pVar->length, SQLITE_TRANSIENT);
  1040         -    }
  1041         -  }
  1042         -}
  1043         -
  1044         -#ifndef SQLITE_OMIT_AUTHORIZATION
  1045         -/*
  1046         -** This is the authentication function.  It appends the authentication
  1047         -** type code and the two arguments to zCmd[] then invokes the result
  1048         -** on the interpreter.  The reply is examined to determine if the
  1049         -** authentication fails or succeeds.
  1050         -*/
  1051         -static int auth_callback(
  1052         -  void *pArg,
  1053         -  int code,
  1054         -  const char *zArg1,
  1055         -  const char *zArg2,
  1056         -  const char *zArg3,
  1057         -  const char *zArg4
  1058         -#ifdef SQLITE_USER_AUTHENTICATION
  1059         -  ,const char *zArg5
  1060         -#endif
  1061         -){
  1062         -  const char *zCode;
  1063         -  Tcl_DString str;
  1064         -  int rc;
  1065         -  const char *zReply;
  1066         -  SqliteDb *pDb = (SqliteDb*)pArg;
  1067         -  if( pDb->disableAuth ) return SQLITE_OK;
  1068         -
  1069         -  switch( code ){
  1070         -    case SQLITE_COPY              : zCode="SQLITE_COPY"; break;
  1071         -    case SQLITE_CREATE_INDEX      : zCode="SQLITE_CREATE_INDEX"; break;
  1072         -    case SQLITE_CREATE_TABLE      : zCode="SQLITE_CREATE_TABLE"; break;
  1073         -    case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break;
  1074         -    case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break;
  1075         -    case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break;
  1076         -    case SQLITE_CREATE_TEMP_VIEW  : zCode="SQLITE_CREATE_TEMP_VIEW"; break;
  1077         -    case SQLITE_CREATE_TRIGGER    : zCode="SQLITE_CREATE_TRIGGER"; break;
  1078         -    case SQLITE_CREATE_VIEW       : zCode="SQLITE_CREATE_VIEW"; break;
  1079         -    case SQLITE_DELETE            : zCode="SQLITE_DELETE"; break;
  1080         -    case SQLITE_DROP_INDEX        : zCode="SQLITE_DROP_INDEX"; break;
  1081         -    case SQLITE_DROP_TABLE        : zCode="SQLITE_DROP_TABLE"; break;
  1082         -    case SQLITE_DROP_TEMP_INDEX   : zCode="SQLITE_DROP_TEMP_INDEX"; break;
  1083         -    case SQLITE_DROP_TEMP_TABLE   : zCode="SQLITE_DROP_TEMP_TABLE"; break;
  1084         -    case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break;
  1085         -    case SQLITE_DROP_TEMP_VIEW    : zCode="SQLITE_DROP_TEMP_VIEW"; break;
  1086         -    case SQLITE_DROP_TRIGGER      : zCode="SQLITE_DROP_TRIGGER"; break;
  1087         -    case SQLITE_DROP_VIEW         : zCode="SQLITE_DROP_VIEW"; break;
  1088         -    case SQLITE_INSERT            : zCode="SQLITE_INSERT"; break;
  1089         -    case SQLITE_PRAGMA            : zCode="SQLITE_PRAGMA"; break;
  1090         -    case SQLITE_READ              : zCode="SQLITE_READ"; break;
  1091         -    case SQLITE_SELECT            : zCode="SQLITE_SELECT"; break;
  1092         -    case SQLITE_TRANSACTION       : zCode="SQLITE_TRANSACTION"; break;
  1093         -    case SQLITE_UPDATE            : zCode="SQLITE_UPDATE"; break;
  1094         -    case SQLITE_ATTACH            : zCode="SQLITE_ATTACH"; break;
  1095         -    case SQLITE_DETACH            : zCode="SQLITE_DETACH"; break;
  1096         -    case SQLITE_ALTER_TABLE       : zCode="SQLITE_ALTER_TABLE"; break;
  1097         -    case SQLITE_REINDEX           : zCode="SQLITE_REINDEX"; break;
  1098         -    case SQLITE_ANALYZE           : zCode="SQLITE_ANALYZE"; break;
  1099         -    case SQLITE_CREATE_VTABLE     : zCode="SQLITE_CREATE_VTABLE"; break;
  1100         -    case SQLITE_DROP_VTABLE       : zCode="SQLITE_DROP_VTABLE"; break;
  1101         -    case SQLITE_FUNCTION          : zCode="SQLITE_FUNCTION"; break;
  1102         -    case SQLITE_SAVEPOINT         : zCode="SQLITE_SAVEPOINT"; break;
  1103         -    case SQLITE_RECURSIVE         : zCode="SQLITE_RECURSIVE"; break;
  1104         -    default                       : zCode="????"; break;
  1105         -  }
  1106         -  Tcl_DStringInit(&str);
  1107         -  Tcl_DStringAppend(&str, pDb->zAuth, -1);
  1108         -  Tcl_DStringAppendElement(&str, zCode);
  1109         -  Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : "");
  1110         -  Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : "");
  1111         -  Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : "");
  1112         -  Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : "");
  1113         -#ifdef SQLITE_USER_AUTHENTICATION
  1114         -  Tcl_DStringAppendElement(&str, zArg5 ? zArg5 : "");
  1115         -#endif
  1116         -  rc = Tcl_EvalEx(pDb->interp, Tcl_DStringValue(&str), -1, TCL_EVAL_GLOBAL);
  1117         -  Tcl_DStringFree(&str);
  1118         -  zReply = rc==TCL_OK ? Tcl_GetStringResult(pDb->interp) : "SQLITE_DENY";
  1119         -  if( strcmp(zReply,"SQLITE_OK")==0 ){
  1120         -    rc = SQLITE_OK;
  1121         -  }else if( strcmp(zReply,"SQLITE_DENY")==0 ){
  1122         -    rc = SQLITE_DENY;
  1123         -  }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){
  1124         -    rc = SQLITE_IGNORE;
  1125         -  }else{
  1126         -    rc = 999;
  1127         -  }
  1128         -  return rc;
  1129         -}
  1130         -#endif /* SQLITE_OMIT_AUTHORIZATION */
  1131         -
  1132         -#if 0
  1133         -/*
  1134         -** This routine reads a line of text from FILE in, stores
  1135         -** the text in memory obtained from malloc() and returns a pointer
  1136         -** to the text.  NULL is returned at end of file, or if malloc()
  1137         -** fails.
  1138         -**
  1139         -** The interface is like "readline" but no command-line editing
  1140         -** is done.
  1141         -**
  1142         -** copied from shell.c from '.import' command
  1143         -*/
  1144         -static char *local_getline(char *zPrompt, FILE *in){
  1145         -  char *zLine;
  1146         -  int nLine;
  1147         -  int n;
  1148         -
  1149         -  nLine = 100;
  1150         -  zLine = malloc( nLine );
  1151         -  if( zLine==0 ) return 0;
  1152         -  n = 0;
  1153         -  while( 1 ){
  1154         -    if( n+100>nLine ){
  1155         -      nLine = nLine*2 + 100;
  1156         -      zLine = realloc(zLine, nLine);
  1157         -      if( zLine==0 ) return 0;
  1158         -    }
  1159         -    if( fgets(&zLine[n], nLine - n, in)==0 ){
  1160         -      if( n==0 ){
  1161         -        free(zLine);
  1162         -        return 0;
  1163         -      }
  1164         -      zLine[n] = 0;
  1165         -      break;
  1166         -    }
  1167         -    while( zLine[n] ){ n++; }
  1168         -    if( n>0 && zLine[n-1]=='\n' ){
  1169         -      n--;
  1170         -      zLine[n] = 0;
  1171         -      break;
  1172         -    }
  1173         -  }
  1174         -  zLine = realloc( zLine, n+1 );
  1175         -  return zLine;
  1176         -}
  1177         -#endif
  1178         -
  1179         -
  1180         -/*
  1181         -** This function is part of the implementation of the command:
  1182         -**
  1183         -**   $db transaction [-deferred|-immediate|-exclusive] SCRIPT
  1184         -**
  1185         -** It is invoked after evaluating the script SCRIPT to commit or rollback
  1186         -** the transaction or savepoint opened by the [transaction] command.
  1187         -*/
  1188         -static int SQLITE_TCLAPI DbTransPostCmd(
  1189         -  ClientData data[],                   /* data[0] is the Sqlite3Db* for $db */
  1190         -  Tcl_Interp *interp,                  /* Tcl interpreter */
  1191         -  int result                           /* Result of evaluating SCRIPT */
  1192         -){
  1193         -  static const char *const azEnd[] = {
  1194         -    "RELEASE _tcl_transaction",        /* rc==TCL_ERROR, nTransaction!=0 */
  1195         -    "COMMIT",                          /* rc!=TCL_ERROR, nTransaction==0 */
  1196         -    "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction",
  1197         -    "ROLLBACK"                         /* rc==TCL_ERROR, nTransaction==0 */
  1198         -  };
  1199         -  SqliteDb *pDb = (SqliteDb*)data[0];
  1200         -  int rc = result;
  1201         -  const char *zEnd;
  1202         -
  1203         -  pDb->nTransaction--;
  1204         -  zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)];
  1205         -
  1206         -  pDb->disableAuth++;
  1207         -  if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){
  1208         -      /* This is a tricky scenario to handle. The most likely cause of an
  1209         -      ** error is that the exec() above was an attempt to commit the
  1210         -      ** top-level transaction that returned SQLITE_BUSY. Or, less likely,
  1211         -      ** that an IO-error has occurred. In either case, throw a Tcl exception
  1212         -      ** and try to rollback the transaction.
  1213         -      **
  1214         -      ** But it could also be that the user executed one or more BEGIN,
  1215         -      ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing
  1216         -      ** this method's logic. Not clear how this would be best handled.
  1217         -      */
  1218         -    if( rc!=TCL_ERROR ){
  1219         -      Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), (char*)0);
  1220         -      rc = TCL_ERROR;
  1221         -    }
  1222         -    sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0);
  1223         -  }
  1224         -  pDb->disableAuth--;
  1225         -
  1226         -  return rc;
  1227         -}
  1228         -
  1229         -/*
  1230         -** Unless SQLITE_TEST is defined, this function is a simple wrapper around
  1231         -** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either
  1232         -** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending
  1233         -** on whether or not the [db_use_legacy_prepare] command has been used to
  1234         -** configure the connection.
  1235         -*/
  1236         -static int dbPrepare(
  1237         -  SqliteDb *pDb,                  /* Database object */
  1238         -  const char *zSql,               /* SQL to compile */
  1239         -  sqlite3_stmt **ppStmt,          /* OUT: Prepared statement */
  1240         -  const char **pzOut              /* OUT: Pointer to next SQL statement */
  1241         -){
  1242         -#ifdef SQLITE_TEST
  1243         -  if( pDb->bLegacyPrepare ){
  1244         -    return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut);
  1245         -  }
  1246         -#endif
  1247         -  return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut);
  1248         -}
  1249         -
  1250         -/*
  1251         -** Search the cache for a prepared-statement object that implements the
  1252         -** first SQL statement in the buffer pointed to by parameter zIn. If
  1253         -** no such prepared-statement can be found, allocate and prepare a new
  1254         -** one. In either case, bind the current values of the relevant Tcl
  1255         -** variables to any $var, :var or @var variables in the statement. Before
  1256         -** returning, set *ppPreStmt to point to the prepared-statement object.
  1257         -**
  1258         -** Output parameter *pzOut is set to point to the next SQL statement in
  1259         -** buffer zIn, or to the '\0' byte at the end of zIn if there is no
  1260         -** next statement.
  1261         -**
  1262         -** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned
  1263         -** and an error message loaded into interpreter pDb->interp.
  1264         -*/
  1265         -static int dbPrepareAndBind(
  1266         -  SqliteDb *pDb,                  /* Database object */
  1267         -  char const *zIn,                /* SQL to compile */
  1268         -  char const **pzOut,             /* OUT: Pointer to next SQL statement */
  1269         -  SqlPreparedStmt **ppPreStmt     /* OUT: Object used to cache statement */
  1270         -){
  1271         -  const char *zSql = zIn;         /* Pointer to first SQL statement in zIn */
  1272         -  sqlite3_stmt *pStmt = 0;        /* Prepared statement object */
  1273         -  SqlPreparedStmt *pPreStmt;      /* Pointer to cached statement */
  1274         -  int nSql;                       /* Length of zSql in bytes */
  1275         -  int nVar = 0;                   /* Number of variables in statement */
  1276         -  int iParm = 0;                  /* Next free entry in apParm */
  1277         -  char c;
  1278         -  int i;
  1279         -  Tcl_Interp *interp = pDb->interp;
  1280         -
  1281         -  *ppPreStmt = 0;
  1282         -
  1283         -  /* Trim spaces from the start of zSql and calculate the remaining length. */
  1284         -  while( (c = zSql[0])==' ' || c=='\t' || c=='\r' || c=='\n' ){ zSql++; }
  1285         -  nSql = strlen30(zSql);
  1286         -
  1287         -  for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){
  1288         -    int n = pPreStmt->nSql;
  1289         -    if( nSql>=n
  1290         -        && memcmp(pPreStmt->zSql, zSql, n)==0
  1291         -        && (zSql[n]==0 || zSql[n-1]==';')
  1292         -    ){
  1293         -      pStmt = pPreStmt->pStmt;
  1294         -      *pzOut = &zSql[pPreStmt->nSql];
  1295         -
  1296         -      /* When a prepared statement is found, unlink it from the
  1297         -      ** cache list.  It will later be added back to the beginning
  1298         -      ** of the cache list in order to implement LRU replacement.
  1299         -      */
  1300         -      if( pPreStmt->pPrev ){
  1301         -        pPreStmt->pPrev->pNext = pPreStmt->pNext;
  1302         -      }else{
  1303         -        pDb->stmtList = pPreStmt->pNext;
  1304         -      }
  1305         -      if( pPreStmt->pNext ){
  1306         -        pPreStmt->pNext->pPrev = pPreStmt->pPrev;
  1307         -      }else{
  1308         -        pDb->stmtLast = pPreStmt->pPrev;
  1309         -      }
  1310         -      pDb->nStmt--;
  1311         -      nVar = sqlite3_bind_parameter_count(pStmt);
  1312         -      break;
  1313         -    }
  1314         -  }
  1315         -
  1316         -  /* If no prepared statement was found. Compile the SQL text. Also allocate
  1317         -  ** a new SqlPreparedStmt structure.  */
  1318         -  if( pPreStmt==0 ){
  1319         -    int nByte;
  1320         -
  1321         -    if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){
  1322         -      Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
  1323         -      return TCL_ERROR;
  1324         -    }
  1325         -    if( pStmt==0 ){
  1326         -      if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){
  1327         -        /* A compile-time error in the statement. */
  1328         -        Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3_errmsg(pDb->db), -1));
  1329         -        return TCL_ERROR;
  1330         -      }else{
  1331         -        /* The statement was a no-op.  Continue to the next statement
  1332         -        ** in the SQL string.
  1333         -        */
  1334         -        return TCL_OK;
  1335         -      }
  1336         -    }
  1337         -
  1338         -    assert( pPreStmt==0 );
  1339         -    nVar = sqlite3_bind_parameter_count(pStmt);
  1340         -    nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *);
  1341         -    pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte);
  1342         -    memset(pPreStmt, 0, nByte);
  1343         -
  1344         -    pPreStmt->pStmt = pStmt;
  1345         -    pPreStmt->nSql = (int)(*pzOut - zSql);
  1346         -    pPreStmt->zSql = sqlite3_sql(pStmt);
  1347         -    pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1];
  1348         -#ifdef SQLITE_TEST
  1349         -    if( pPreStmt->zSql==0 ){
  1350         -      char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1);
  1351         -      memcpy(zCopy, zSql, pPreStmt->nSql);
  1352         -      zCopy[pPreStmt->nSql] = '\0';
  1353         -      pPreStmt->zSql = zCopy;
  1354         -    }
  1355         -#endif
  1356         -  }
  1357         -  assert( pPreStmt );
  1358         -  assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql );
  1359         -  assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) );
  1360         -
  1361         -  /* Bind values to parameters that begin with $ or : */
  1362         -  for(i=1; i<=nVar; i++){
  1363         -    const char *zVar = sqlite3_bind_parameter_name(pStmt, i);
  1364         -    if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){
  1365         -      Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0);
  1366         -      if( pVar ){
  1367         -        int n;
  1368         -        u8 *data;
  1369         -        const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
  1370         -        c = zType[0];
  1371         -        if( zVar[0]=='@' ||
  1372         -           (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
  1373         -          /* Load a BLOB type if the Tcl variable is a bytearray and
  1374         -          ** it has no string representation or the host
  1375         -          ** parameter name begins with "@". */
  1376         -          data = Tcl_GetByteArrayFromObj(pVar, &n);
  1377         -          sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC);
  1378         -          Tcl_IncrRefCount(pVar);
  1379         -          pPreStmt->apParm[iParm++] = pVar;
  1380         -        }else if( c=='b' && strcmp(zType,"boolean")==0 ){
  1381         -          Tcl_GetIntFromObj(interp, pVar, &n);
  1382         -          sqlite3_bind_int(pStmt, i, n);
  1383         -        }else if( c=='d' && strcmp(zType,"double")==0 ){
  1384         -          double r;
  1385         -          Tcl_GetDoubleFromObj(interp, pVar, &r);
  1386         -          sqlite3_bind_double(pStmt, i, r);
  1387         -        }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
  1388         -              (c=='i' && strcmp(zType,"int")==0) ){
  1389         -          Tcl_WideInt v;
  1390         -          Tcl_GetWideIntFromObj(interp, pVar, &v);
  1391         -          sqlite3_bind_int64(pStmt, i, v);
  1392         -        }else{
  1393         -          data = (unsigned char *)Tcl_GetString(pVar);
  1394         -          sqlite3_bind_text(pStmt, i, (char *)data, pVar->length, SQLITE_STATIC);
  1395         -          Tcl_IncrRefCount(pVar);
  1396         -          pPreStmt->apParm[iParm++] = pVar;
  1397         -        }
  1398         -      }else{
  1399         -        sqlite3_bind_null(pStmt, i);
  1400         -      }
  1401         -    }
  1402         -  }
  1403         -  pPreStmt->nParm = iParm;
  1404         -  *ppPreStmt = pPreStmt;
  1405         -
  1406         -  return TCL_OK;
  1407         -}
  1408         -
  1409         -/*
  1410         -** Release a statement reference obtained by calling dbPrepareAndBind().
  1411         -** There should be exactly one call to this function for each call to
  1412         -** dbPrepareAndBind().
  1413         -**
  1414         -** If the discard parameter is non-zero, then the statement is deleted
  1415         -** immediately. Otherwise it is added to the LRU list and may be returned
  1416         -** by a subsequent call to dbPrepareAndBind().
  1417         -*/
  1418         -static void dbReleaseStmt(
  1419         -  SqliteDb *pDb,                  /* Database handle */
  1420         -  SqlPreparedStmt *pPreStmt,      /* Prepared statement handle to release */
  1421         -  int discard                     /* True to delete (not cache) the pPreStmt */
  1422         -){
  1423         -  int i;
  1424         -
  1425         -  /* Free the bound string and blob parameters */
  1426         -  for(i=0; i<pPreStmt->nParm; i++){
  1427         -    Tcl_DecrRefCount(pPreStmt->apParm[i]);
  1428         -  }
  1429         -  pPreStmt->nParm = 0;
  1430         -
  1431         -  if( pDb->maxStmt<=0 || discard ){
  1432         -    /* If the cache is turned off, deallocated the statement */
  1433         -    dbFreeStmt(pPreStmt);
  1434         -  }else{
  1435         -    /* Add the prepared statement to the beginning of the cache list. */
  1436         -    pPreStmt->pNext = pDb->stmtList;
  1437         -    pPreStmt->pPrev = 0;
  1438         -    if( pDb->stmtList ){
  1439         -     pDb->stmtList->pPrev = pPreStmt;
  1440         -    }
  1441         -    pDb->stmtList = pPreStmt;
  1442         -    if( pDb->stmtLast==0 ){
  1443         -      assert( pDb->nStmt==0 );
  1444         -      pDb->stmtLast = pPreStmt;
  1445         -    }else{
  1446         -      assert( pDb->nStmt>0 );
  1447         -    }
  1448         -    pDb->nStmt++;
  1449         -
  1450         -    /* If we have too many statement in cache, remove the surplus from
  1451         -    ** the end of the cache list.  */
  1452         -    while( pDb->nStmt>pDb->maxStmt ){
  1453         -      SqlPreparedStmt *pLast = pDb->stmtLast;
  1454         -      pDb->stmtLast = pLast->pPrev;
  1455         -      pDb->stmtLast->pNext = 0;
  1456         -      pDb->nStmt--;
  1457         -      dbFreeStmt(pLast);
  1458         -    }
  1459         -  }
  1460         -}
  1461         -
  1462         -/*
  1463         -** Structure used with dbEvalXXX() functions:
  1464         -**
  1465         -**   dbEvalInit()
  1466         -**   dbEvalStep()
  1467         -**   dbEvalFinalize()
  1468         -**   dbEvalRowInfo()
  1469         -**   dbEvalColumnValue()
  1470         -*/
  1471         -typedef struct DbEvalContext DbEvalContext;
  1472         -struct DbEvalContext {
  1473         -  SqliteDb *pDb;                  /* Database handle */
  1474         -  Tcl_Obj *pSql;                  /* Object holding string zSql */
  1475         -  const char *zSql;               /* Remaining SQL to execute */
  1476         -  SqlPreparedStmt *pPreStmt;      /* Current statement */
  1477         -  int nCol;                       /* Number of columns returned by pStmt */
  1478         -  Tcl_Obj *pArray;                /* Name of array variable */
  1479         -  Tcl_Obj **apColName;            /* Array of column names */
  1480         -};
  1481         -
  1482         -/*
  1483         -** Release any cache of column names currently held as part of
  1484         -** the DbEvalContext structure passed as the first argument.
  1485         -*/
  1486         -static void dbReleaseColumnNames(DbEvalContext *p){
  1487         -  if( p->apColName ){
  1488         -    int i;
  1489         -    for(i=0; i<p->nCol; i++){
  1490         -      Tcl_DecrRefCount(p->apColName[i]);
  1491         -    }
  1492         -    Tcl_Free((char *)p->apColName);
  1493         -    p->apColName = 0;
  1494         -  }
  1495         -  p->nCol = 0;
  1496         -}
  1497         -
  1498         -/*
  1499         -** Initialize a DbEvalContext structure.
  1500         -**
  1501         -** If pArray is not NULL, then it contains the name of a Tcl array
  1502         -** variable. The "*" member of this array is set to a list containing
  1503         -** the names of the columns returned by the statement as part of each
  1504         -** call to dbEvalStep(), in order from left to right. e.g. if the names
  1505         -** of the returned columns are a, b and c, it does the equivalent of the
  1506         -** tcl command:
  1507         -**
  1508         -**     set ${pArray}(*) {a b c}
  1509         -*/
  1510         -static void dbEvalInit(
  1511         -  DbEvalContext *p,               /* Pointer to structure to initialize */
  1512         -  SqliteDb *pDb,                  /* Database handle */
  1513         -  Tcl_Obj *pSql,                  /* Object containing SQL script */
  1514         -  Tcl_Obj *pArray                 /* Name of Tcl array to set (*) element of */
  1515         -){
  1516         -  memset(p, 0, sizeof(DbEvalContext));
  1517         -  p->pDb = pDb;
  1518         -  p->zSql = Tcl_GetString(pSql);
  1519         -  p->pSql = pSql;
  1520         -  Tcl_IncrRefCount(pSql);
  1521         -  if( pArray ){
  1522         -    p->pArray = pArray;
  1523         -    Tcl_IncrRefCount(pArray);
  1524         -  }
  1525         -}
  1526         -
  1527         -/*
  1528         -** Obtain information about the row that the DbEvalContext passed as the
  1529         -** first argument currently points to.
  1530         -*/
  1531         -static void dbEvalRowInfo(
  1532         -  DbEvalContext *p,               /* Evaluation context */
  1533         -  int *pnCol,                     /* OUT: Number of column names */
  1534         -  Tcl_Obj ***papColName           /* OUT: Array of column names */
  1535         -){
  1536         -  /* Compute column names */
  1537         -  if( 0==p->apColName ){
  1538         -    sqlite3_stmt *pStmt = p->pPreStmt->pStmt;
  1539         -    int i;                        /* Iterator variable */
  1540         -    int nCol;                     /* Number of columns returned by pStmt */
  1541         -    Tcl_Obj **apColName = 0;      /* Array of column names */
  1542         -
  1543         -    p->nCol = nCol = sqlite3_column_count(pStmt);
  1544         -    if( nCol>0 && (papColName || p->pArray) ){
  1545         -      apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol );
  1546         -      for(i=0; i<nCol; i++){
  1547         -        apColName[i] = Tcl_NewStringObj(sqlite3_column_name(pStmt,i), -1);
  1548         -        Tcl_IncrRefCount(apColName[i]);
  1549         -      }
  1550         -      p->apColName = apColName;
  1551         -    }
  1552         -
  1553         -    /* If results are being stored in an array variable, then create
  1554         -    ** the array(*) entry for that array
  1555         -    */
  1556         -    if( p->pArray ){
  1557         -      Tcl_Interp *interp = p->pDb->interp;
  1558         -      Tcl_Obj *pColList = Tcl_NewObj();
  1559         -      Tcl_Obj *pStar = Tcl_NewStringObj("*", -1);
  1560         -
  1561         -      for(i=0; i<nCol; i++){
  1562         -        Tcl_ListObjAppendElement(interp, pColList, apColName[i]);
  1563         -      }
  1564         -      Tcl_IncrRefCount(pStar);
  1565         -      Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0);
  1566         -      Tcl_DecrRefCount(pStar);
  1567         -    }
  1568         -  }
  1569         -
  1570         -  if( papColName ){
  1571         -    *papColName = p->apColName;
  1572         -  }
  1573         -  if( pnCol ){
  1574         -    *pnCol = p->nCol;
  1575         -  }
  1576         -}
  1577         -
  1578         -/*
  1579         -** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is
  1580         -** returned, then an error message is stored in the interpreter before
  1581         -** returning.
  1582         -**
  1583         -** A return value of TCL_OK means there is a row of data available. The
  1584         -** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This
  1585         -** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK
  1586         -** is returned, then the SQL script has finished executing and there are
  1587         -** no further rows available. This is similar to SQLITE_DONE.
  1588         -*/
  1589         -static int dbEvalStep(DbEvalContext *p){
  1590         -  const char *zPrevSql = 0;       /* Previous value of p->zSql */
  1591         -
  1592         -  while( p->zSql[0] || p->pPreStmt ){
  1593         -    int rc;
  1594         -    if( p->pPreStmt==0 ){
  1595         -      zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql);
  1596         -      rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt);
  1597         -      if( rc!=TCL_OK ) return rc;
  1598         -    }else{
  1599         -      int rcs;
  1600         -      Sq